List of usage examples for org.bouncycastle.asn1.x500 X500Name getEncoded
public byte[] getEncoded() throws IOException
From source file:co.runrightfast.core.security.auth.x500.DistinguishedNameTest.java
License:Apache License
@Test public void test_toX500Name() throws IOException { final DistinguishedName dn = DistinguishedName.builder().commonName("Alfio Zappala").country("US") .domain("www.runrightfast.co").localityName("Rochester").organizationName("RunRightFast.co") .organizationalUnitName("Executive").stateOrProvinceName("NY").streetAddress("123 Main St.") .userid("0123456789").build(); log.info(String.format("dn =\n%s", dn)); final X500Principal principal = dn.toX500Principal(); log.info(String.format("principle name =\n%s", principal.getName())); final X500Principal principal2 = new X500Principal(principal.getEncoded()); log.info(String.format("principle2 name =\n%s", principal2.getName())); log.info(String.format("principle2 name RFC2253 =\n%s", principal2.getName(X500Principal.RFC2253))); assertThat(Arrays.areEqual(principal.getEncoded(), principal2.getEncoded()), is(true)); assertThat(principal, is(principal2)); final X500Name name1 = DistinguishedName.toX500Name(principal); final X500Name name2 = DistinguishedName.toX500Name(principal2); log.info(String.format("name1 : %s", name1)); log.info(String.format("name2 : %s", name2)); assertThat(Arrays.areEqual(name1.getEncoded(), name1.getEncoded()), is(true)); }
From source file:net.sf.keystore_explorer.crypto.x509.X500NameUtils.java
License:Open Source License
/** * Convert an X.500 Name to an X.500 Principal. * * @param name//from w w w . j av a 2s.c o m * X.500 Name * @return X.500 Principal * @throws IOException if an encoding error occurs (incorrect form for DN) */ public static X500Principal x500NameToX500Principal(X500Name name) throws IOException { return new X500Principal(name.getEncoded()); }
From source file:org.bitrepository.protocol.security.CertificateID.java
License:Open Source License
public CertificateID(X500Name issuer, BigInteger serialNumber) { try {// w w w .java 2s . com this.issuer = new X500Principal(issuer.getEncoded()); } catch (IOException e) { throw new RuntimeException("Failed to create X500Principal from X500Name", e); } this.serial = serialNumber; }
From source file:org.cesecore.keybind.InternalKeyBindingMgmtTest.java
License:Open Source License
@Test public void workflowIssueCertFromCsrUpdateAndRenew() throws Exception { final String TEST_METHOD_NAME = Thread.currentThread().getStackTrace()[1].getMethodName(); final String KEY_BINDING_NAME = TEST_METHOD_NAME; final String KEY_PAIR_ALIAS = TEST_METHOD_NAME; final String endEntityId = TESTCLASSNAME + "_" + TEST_METHOD_NAME; // Clean up old key binding removeInternalKeyBindingByName(alwaysAllowToken, TEST_METHOD_NAME); int internalKeyBindingId = 0; String certFpToDelete = null; try {/*from ww w .j a v a 2 s .co m*/ // First create a new CryptoToken cryptoTokenManagementSession.createKeyPair(alwaysAllowToken, cryptoTokenId, KEY_PAIR_ALIAS, "RSA2048"); // Create a new InternalKeyBinding with a implementation specific property and bind it to the previously generated key final Map<String, Serializable> dataMap = new LinkedHashMap<String, Serializable>(); dataMap.put(PROPERTY_ALIAS, Boolean.FALSE); internalKeyBindingId = internalKeyBindingMgmtSession.createInternalKeyBinding(alwaysAllowToken, KEYBINDING_TYPE_ALIAS, KEY_BINDING_NAME, InternalKeyBindingStatus.ACTIVE, null, cryptoTokenId, KEY_PAIR_ALIAS, AlgorithmConstants.SIGALG_SHA1_WITH_RSA, dataMap, null); // Add a user to EJBCA for the renewal later on final EndEntityInformation endEntityInformation = new EndEntityInformation(endEntityId, "CN=" + TESTCLASSNAME + "_" + TEST_METHOD_NAME, x509ca.getCAId(), null, null, EndEntityTypes.ENDUSER.toEndEntityType(), 1, CertificateProfileConstants.CERTPROFILE_FIXED_OCSPSIGNER, EndEntityConstants.TOKEN_USERGEN, 0, null); endEntityInformation.setPassword("foo123"); // Request a CSR for the key pair // First make a couple of requests with different DN to see that that part works final X500Name x500name = CertTools.stringToBcX500Name("CN=name,O=org,C=SE", false); final byte[] csr = internalKeyBindingMgmtSession.generateCsrForNextKey(alwaysAllowToken, internalKeyBindingId, x500name.getEncoded()); final JcaPKCS10CertificationRequest jcareq = new JcaPKCS10CertificationRequest(csr); assertEquals("Wrong order of DN, should be X500 with C first", "C=SE,O=org,CN=name", jcareq.getSubject().toString()); final X500Name x500name2 = CertTools.stringToBcX500Name("CN=name,O=org,C=SE", true); final byte[] csr2 = internalKeyBindingMgmtSession.generateCsrForNextKey(alwaysAllowToken, internalKeyBindingId, x500name2.getEncoded()); final JcaPKCS10CertificationRequest jcareq2 = new JcaPKCS10CertificationRequest(csr2); assertEquals("Wrong order of DN, should be LDAP with CN first", "CN=name,O=org,C=SE", jcareq2.getSubject().toString()); // Now make the request that we will actually use final byte[] csr3 = internalKeyBindingMgmtSession.generateCsrForNextKey(alwaysAllowToken, internalKeyBindingId, null); final RequestMessage req = new PKCS10RequestMessage(csr3); assertEquals("CN=" + KEY_BINDING_NAME, req.getRequestDN()); X509Certificate keyBindingCertificate = (X509Certificate) (((X509ResponseMessage) certificateCreateSession .createCertificate(alwaysAllowToken, endEntityInformation, req, X509ResponseMessage.class, signSession.fetchCertGenParams())).getCertificate()); certFpToDelete = CertTools.getFingerprintAsString(keyBindingCertificate); // Ask the key binding to search the database for a new certificate matching its public key final String boundCertificateFingerprint = internalKeyBindingMgmtSession .updateCertificateForInternalKeyBinding(alwaysAllowToken, internalKeyBindingId); // Verify that it was the right certificate it found assertEquals("Wrong certificate was found for InternalKeyBinding", CertTools.getFingerprintAsString(keyBindingCertificate), boundCertificateFingerprint); // ...so now we have a mapping between a certificate in the database and a key pair in a CryptoToken // Since we no have a certificate issued by an internal CA, we should be able to renew it final String renewedCertificateFingerprint = internalKeyBindingMgmtSession .renewInternallyIssuedCertificate(alwaysAllowToken, internalKeyBindingId, endEntityInformation); assertNotNull("Renewal returned null which is an undefined state.", renewedCertificateFingerprint); assertFalse("After certificate renewal the same certificate was returned", boundCertificateFingerprint.equals(renewedCertificateFingerprint)); final String actualCertificateFingerprint = internalKeyBindingMgmtSession .getInternalKeyBindingInfo(alwaysAllowToken, internalKeyBindingId).getCertificateId(); assertFalse("After certificate renewal the same certificate still in use.", boundCertificateFingerprint.equals(actualCertificateFingerprint)); // Check DN in generated CSR when we have a bound certificate, should be the DN of the old certificate final byte[] csr4 = internalKeyBindingMgmtSession.generateCsrForNextKey(alwaysAllowToken, internalKeyBindingId, null); final JcaPKCS10CertificationRequest jcareq4 = new JcaPKCS10CertificationRequest(csr4); assertEquals("Wrong DN, should be from the bound certificate", "CN=" + TESTCLASSNAME + "_" + TEST_METHOD_NAME, jcareq4.getSubject().toString()); } finally { internalKeyBindingMgmtSession.deleteInternalKeyBinding(alwaysAllowToken, internalKeyBindingId); internalCertStoreSession.removeCertificate(certFpToDelete); } }
From source file:org.ejbca.core.protocol.cmp.CmpRaThrowAwayTest.java
License:Open Source License
@Test public void testLegacyEncodedRequestOverride() throws Exception { reconfigureCA(false, false, false);/*from w w w . j a v a 2 s. co m*/ // Setup "Allow subject DN override" and "Allow certificate serial number override" in used cert profile reconfigureCertificateProfile(true, true); final String issuerDn = CertTools.getSubjectDN(getTestCACert(TESTCA_NAME)); final X500Name issuerX500Name = new X500Name(issuerDn); final org.bouncycastle.asn1.crmf.CertTemplateBuilder certTemplate = new org.bouncycastle.asn1.crmf.CertTemplateBuilder(); certTemplate.setIssuer(issuerX500Name); final KeyPair keyPair = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA); final String serialNumber = "88883311121333FF33012345"; final byte[] transactionId = new byte[16]; final byte[] senderNonce = new byte[16]; final Random random = new Random(); random.nextBytes(transactionId); random.nextBytes(senderNonce); final String subjectDn = "C=SE,O=PrimeKey,OU=Labs,CN=Sec_" + serialNumber; final X500Name subjectX500Name = CertTools.stringToBcX500Name(subjectDn, new TeletexNamingStyle(), false); certTemplate.setSubject(subjectX500Name); final byte[] bytes = keyPair.getPublic().getEncoded(); final ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); final org.bouncycastle.asn1.ASN1InputStream asn1InputStream = new org.bouncycastle.asn1.ASN1InputStream( bIn); final org.bouncycastle.asn1.x509.SubjectPublicKeyInfo keyInfo = new org.bouncycastle.asn1.x509.SubjectPublicKeyInfo( (org.bouncycastle.asn1.ASN1Sequence) asn1InputStream.readObject()); asn1InputStream.close(); certTemplate.setPublicKey(keyInfo); // Request a custom certificate serial number certTemplate.setSerialNumber(new ASN1Integer(new BigInteger(serialNumber, 16))); final org.bouncycastle.asn1.crmf.ProofOfPossession myProofOfPossession = new org.bouncycastle.asn1.crmf.ProofOfPossession(); final CertRequest certRequest = new CertRequest(4, certTemplate.build(), null); final AttributeTypeAndValue[] avs = { new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken, new DERUTF8String(PBE_SECRET)) }; final CertReqMsg certReqMsg = new CertReqMsg(certRequest, myProofOfPossession, avs); final CertReqMessages certReqMessages = new CertReqMessages(certReqMsg); PKIHeaderBuilder pkiHeader = new PKIHeaderBuilder(2, new GeneralName(subjectX500Name), new GeneralName(new X500Name(issuerDn))); pkiHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); pkiHeader.setSenderNonce(new DEROctetString(senderNonce)); pkiHeader.setTransactionID(new DEROctetString(transactionId)); pkiHeader.setProtectionAlg(null); final DEROctetString senderKID = null; pkiHeader.setSenderKID(senderKID); final PKIBody pkiBody = new PKIBody(0, certReqMessages); final PKIMessage pkiMessage = new PKIMessage(pkiHeader.build(), pkiBody); final PKIMessage req = protectPKIMessage(pkiMessage, false, PBE_SECRET, "unusedKeyId", 567); assertNotNull("Request was not created properly.", req); final CertReqMessages initializationRequest = (CertReqMessages) req.getBody().getContent(); final int requestId = initializationRequest.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue() .intValue(); final byte[] reqBytes = req.getEncoded(); final byte[] cmpResponse = sendCmpHttp(reqBytes, 200, configAlias); final X509Certificate cert = checkCmpCertRepMessage(subjectX500Name, this.caCertificate, cmpResponse, requestId); LOG.debug("Request:\n" + new String(CertTools.getPEMFromCertificateRequest(certRequest.getEncoded()))); LOG.debug("Result:\n" + new String( CertTools.getPemFromCertificateChain(new ArrayList<Certificate>(Arrays.asList(cert))))); final byte[] requestSubjectyX500Principal = cert.getSubjectX500Principal().getEncoded(); final byte[] responeSubjectyX500Principal = subjectX500Name.getEncoded(); assertTrue("Requested X500Name was not returned the same way as requested.", Arrays.equals(requestSubjectyX500Principal, responeSubjectyX500Principal)); // We cannot assume that the unique serial number index is enabled, and hence we cant be sure that our serial number override was allowed, but at least we can print it LOG.info("Requested serial number: " + serialNumber); LOG.info("Response serial number: " + CertTools.getSerialNumberAsString(cert)); }
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
License:Open Source License
/** * Normally not overrided. Could be overrided if DN in cert is changed from request by a {@link org.ejbca.core.protocol.ExtendedUserDataHandler}. * // w w w . ja v a 2 s . c o m * @param expected * @param actual * @throws IOException * @throws ArrayComparisonFailure */ @SuppressWarnings("static-method") protected void checkDN(X500Name expected, X500Name actual) throws ArrayComparisonFailure, IOException { assertArrayEquals("Was '" + actual + "' expected '" + expected + "'.", expected.getEncoded(), actual.getEncoded()); }
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
License:Open Source License
protected static void checkCmpPKIErrorMessage(byte[] retMsg, String sender, X500Name recipient, int errorCode, String errorMsg) throws IOException { //// ww w . j a va 2s . c o m // Parse response message // PKIMessage respObject = null; ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(retMsg)); try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respObject); PKIHeader header = respObject.getHeader(); assertEquals(header.getSender().getTagNo(), 4); { final X500Name name = X500Name.getInstance(header.getSender().getName()); assertEquals(name.toString(), sender); } { final X500Name name = X500Name.getInstance(header.getRecipient().getName()); assertArrayEquals(name.getEncoded(), recipient.getEncoded()); } PKIBody body = respObject.getBody(); int tag = body.getType(); assertEquals(tag, 23); ErrorMsgContent n = (ErrorMsgContent) body.getContent(); assertNotNull(n); PKIStatusInfo info = n.getPKIStatusInfo(); assertNotNull(info); BigInteger i = info.getStatus(); assertEquals(i.intValue(), 2); DERBitString b = info.getFailInfo(); assertEquals("Return wrong error code.", errorCode, b.intValue()); if (errorMsg != null) { PKIFreeText freeText = info.getStatusString(); DERUTF8String utf = freeText.getStringAt(0); assertEquals(errorMsg, utf.getString()); } }
From source file:org.ejbca.core.protocol.cmp.CrmfKeyUpdateTest.java
License:Open Source License
private static X509Certificate checkKurCertRepMessage(X500Name eeDN, Certificate issuerCert, byte[] retMsg, int requestId) throws Exception { ///* w w w .j a v a 2 s . c o m*/ // Parse response message // PKIMessage respObject = null; ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(retMsg)); try { respObject = PKIMessage.getInstance(asn1InputStream.readObject()); } finally { asn1InputStream.close(); } assertNotNull(respObject); // Verify body type PKIBody body = respObject.getBody(); int tag = body.getType(); assertEquals(8, tag); // Verify the response CertRepMessage c = (CertRepMessage) body.getContent(); assertNotNull(c); CertResponse resp = c.getResponse()[0]; assertNotNull(resp); assertEquals(resp.getCertReqId().getValue().intValue(), requestId); // Verify response status PKIStatusInfo info = resp.getStatus(); assertNotNull(info); assertEquals(0, info.getStatus().intValue()); // Verify response certificate CertifiedKeyPair kp = resp.getCertifiedKeyPair(); assertNotNull(kp); CertOrEncCert cc = kp.getCertOrEncCert(); assertNotNull(cc); final CMPCertificate cmpcert = cc.getCertificate(); assertNotNull(cmpcert); X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(cmpcert.getEncoded()); final X500Name name = new X500Name(CertTools.getSubjectDN(cert)); assertArrayEquals(eeDN.getEncoded(), name.getEncoded()); assertEquals(CertTools.stringToBCDNString(CertTools.getIssuerDN(cert)), CertTools.getSubjectDN(issuerCert)); // Verify the issuer of cert CMPCertificate respCmpCaCert = c.getCaPubs()[0]; final X509Certificate respCaCert = (X509Certificate) CertTools .getCertfromByteArray(respCmpCaCert.getEncoded()); assertEquals(CertTools.getFingerprintAsString(issuerCert), CertTools.getFingerprintAsString(respCaCert)); Collection<Certificate> cacerts = new ArrayList<Certificate>(); cacerts.add(issuerCert); assertTrue(CertTools.verify(cert, cacerts)); cacerts = new ArrayList<Certificate>(); cacerts.add(respCaCert); assertTrue(CertTools.verify(cert, cacerts)); return cert; }
From source file:org.ejbca.ui.cli.keybind.InternalKeyBindingGenerateCsrCommand.java
License:Open Source License
@Override public CommandResult executeCommand(Integer internalKeyBindingId, ParameterContainer parameters) throws AuthorizationDeniedException, IOException, InvalidKeyException, CryptoTokenOfflineException, InvalidAlgorithmParameterException { final InternalKeyBindingMgmtSessionRemote internalKeyBindingMgmtSession = EjbRemoteHelper.INSTANCE .getRemoteSession(InternalKeyBindingMgmtSessionRemote.class); final boolean switchGenKeyPair = parameters.containsKey(GENKEYPAIR_KEY); final String csrSubjectDN = parameters.get(SUBJECTDN_KEY); // If contains key we want to boolean to be false, because LDAP DN order is "true" final boolean x500dnorder = !parameters.containsKey(SUBJECTDN_ORDER_KEY); final X500Name x500Name; if (csrSubjectDN != null) { x500Name = CertTools.stringToBcX500Name(csrSubjectDN, x500dnorder); getLogger().info(/*ww w . j a v a2 s.co m*/ "Using subject DN from argument '" + x500Name.toString() + "', with order " + x500dnorder); } else { if (parameters.containsKey(SUBJECTDN_ORDER_KEY)) { getLogger().warn(SUBJECTDN_ORDER_KEY + " is defined, but " + SUBJECTDN_KEY + " is not."); } getLogger().info("Using default subject DN, from existing mapped certificate if it is present"); x500Name = null; } String nextKeyAlias; if (switchGenKeyPair) { nextKeyAlias = internalKeyBindingMgmtSession.generateNextKeyPair(getAdmin(), internalKeyBindingId); getLogger().info("A new key pair has been generated with alias " + nextKeyAlias); } else { final InternalKeyBinding internalKeyBinding = internalKeyBindingMgmtSession .getInternalKeyBindingInfo(getAdmin(), internalKeyBindingId); nextKeyAlias = internalKeyBinding.getNextKeyPairAlias(); if (nextKeyAlias == null) { nextKeyAlias = internalKeyBinding.getKeyPairAlias(); } getLogger().info("Next key pair alias is " + nextKeyAlias); } final byte[] certificateRequestBytes = internalKeyBindingMgmtSession.generateCsrForNextKey(getAdmin(), internalKeyBindingId, x500Name != null ? x500Name.getEncoded() : null); if (certificateRequestBytes == null) { getLogger().error("Unable to generate CSR for " + nextKeyAlias); return CommandResult.FUNCTIONAL_FAILURE; } else { final byte[] pemEncodedPublicKey = CertTools.getPEMFromCertificateRequest(certificateRequestBytes); final OutputStream fos = new FileOutputStream(parameters.get(CSR_FILE_KEY)); fos.write(pemEncodedPublicKey); fos.close(); getLogger().info("Stored PEM encoded PKCS#10 request for \"" + parameters.get(KEYBINDING_NAME_KEY) + "\" as " + parameters.get(CSR_FILE_KEY)); return CommandResult.SUCCESS; } }
From source file:org.globus.gsi.bc.X500NameHelper.java
License:Apache License
/** * Gets the last name component from the {@link X500Name X500Name} name. * * @return the last name component. Null if there is none. * @throws IOException /*from ww w.j a v a 2 s . c o m*/ */ public static ASN1Set getLastNameEntry(X500Name name) throws IOException { ASN1Sequence seq = (ASN1Sequence) ASN1Sequence.fromByteArray(name.getEncoded()); int size = seq.size(); return (size > 0) ? (ASN1Set) seq.getObjectAt(size - 1) : null; }