List of usage examples for org.bouncycastle.asn1.x509 Extension authorityKeyIdentifier
ASN1ObjectIdentifier authorityKeyIdentifier
To view the source code for org.bouncycastle.asn1.x509 Extension authorityKeyIdentifier.
Click Source Link
From source file:org.conscrypt.java.security.cert.CertificateFactoryTest.java
License:Apache License
@SuppressWarnings("deprecation") private static KeyHolder generateCertificate(boolean isCa, KeyHolder issuer) throws Exception { Date startDate = new Date(); GregorianCalendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("UTC")); cal.set(2100, 0, 1, 0, 0, 0); // Jan 1, 2100 UTC Date expiryDate = cal.getTime(); KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); KeyPair keyPair = kpg.generateKeyPair(); BigInteger serial;/*from w w w. ja v a 2 s .co m*/ X500Principal issuerPrincipal; X500Principal subjectPrincipal; PrivateKey caKey; if (issuer != null) { serial = issuer.certificate.getSerialNumber().add(BigInteger.ONE); subjectPrincipal = new X500Principal("CN=Test Certificate Serial #" + serial.toString()); issuerPrincipal = issuer.certificate.getSubjectX500Principal(); caKey = issuer.privateKey; } else { serial = BigInteger.ONE; subjectPrincipal = new X500Principal("CN=Test CA, O=Tests, C=US"); issuerPrincipal = subjectPrincipal; caKey = keyPair.getPrivate(); } BasicConstraints basicConstraints; if (isCa) { basicConstraints = new BasicConstraints(10 - serial.intValue()); } else { basicConstraints = new BasicConstraints(false); } X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); PublicKey pubKey = keyPair.getPublic(); certGen.setSerialNumber(serial); certGen.setIssuerDN(issuerPrincipal); certGen.setNotBefore(startDate); certGen.setNotAfter(expiryDate); certGen.setSubjectDN(subjectPrincipal); certGen.setPublicKey(pubKey); certGen.setSignatureAlgorithm("SHA1withRSA"); if (issuer != null) { certGen.addExtension(Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(issuer.certificate)); } else { certGen.addExtension(Extension.authorityKeyIdentifier, false, new AuthorityKeyIdentifier(generatePublicKeyDigest(pubKey))); } certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(generatePublicKeyDigest(pubKey))); certGen.addExtension(Extension.basicConstraints, true, basicConstraints); X509Certificate cert = certGen.generate(caKey); KeyHolder holder = new KeyHolder(); holder.certificate = cert; holder.privateKey = keyPair.getPrivate(); return holder; }
From source file:org.demoiselle.signer.core.extension.BasicCertificate.java
License:Open Source License
/** * *//w w w. jav a2 s .c o m * @return the authority key identifier of a certificate * */ public String getAuthorityKeyIdentifier() { // TODO - Precisa validar este metodo com a RFC try { DLSequence sequence = (DLSequence) getExtensionValue(Extension.authorityKeyIdentifier.getId()); if (sequence == null || sequence.size() == 0) { return null; } DERTaggedObject taggedObject = (DERTaggedObject) sequence.getObjectAt(0); DEROctetString oct = (DEROctetString) taggedObject.getObject(); return toString(oct.getOctets()); } catch (Exception error) { logger.info(error.getMessage()); return null; } }
From source file:org.eclipse.milo.opcua.stack.core.util.SelfSignedCertificateGenerator.java
License:Open Source License
protected void addAuthorityKeyIdentifier(X509v3CertificateBuilder certificateBuilder, KeyPair keyPair) throws CertIOException, NoSuchAlgorithmException { certificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic())); }
From source file:org.ejbca.core.ejb.authentication.web.WebAuthenticationProviderSessionBeanTest.java
License:Open Source License
private static X509Certificate generateUnbornCert(String dn, String policyId, PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, IllegalStateException, NoSuchProviderException, OperatorCreationException, CertificateException, IOException { int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign; // Create self signed certificate Date firstDate = new Date(); // Set starting date to tomorrow firstDate.setTime(firstDate.getTime() + (24 * 3600 * 1000)); Date lastDate = new Date(); // Set Expiry in two days lastDate.setTime(lastDate.getTime() + ((2 * 24 * 60 * 60 * 1000))); // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be // a CVC public key that is passed as parameter PublicKey publicKey = null;/*from w ww. j a va 2 s. co m*/ if (pubKey instanceof RSAPublicKey) { RSAPublicKey rsapk = (RSAPublicKey) pubKey; RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent()); try { publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec); } catch (InvalidKeySpecException e) { publicKey = pubKey; } } else if (pubKey instanceof ECPublicKey) { ECPublicKey ecpk = (ECPublicKey) pubKey; try { ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA" publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec); } catch (InvalidKeySpecException e) { publicKey = pubKey; } catch (NullPointerException e) { publicKey = pubKey; } } else { publicKey = pubKey; } // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this // bean is created. byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(new Date().getTime()); random.nextBytes(serno); final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo( (ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded())); X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(CertTools.stringToBcX500Name(dn), new java.math.BigInteger(serno).abs(), firstDate, lastDate, CertTools.stringToBcX500Name(dn), pkinfo); // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certbuilder.addExtension(Extension.basicConstraints, true, bc); // Put critical KeyUsage in CA-certificates if (isCA) { X509KeyUsage ku = new X509KeyUsage(keyusage); certbuilder.addExtension(Extension.keyUsage, true, ku); } // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox. try { if (isCA) { ASN1InputStream spkiAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())); ASN1InputStream apkiAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())); try { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) spkiAsn1InputStream.readObject()); X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils(); SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) apkiAsn1InputStream.readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski); certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki); } finally { spkiAsn1InputStream.close(); apkiAsn1InputStream.close(); } } } catch (IOException e) { // do nothing } // CertificatePolicies extension if supplied policy ID, always non-critical if (policyId != null) { PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId)); DERSequence seq = new DERSequence(pi); certbuilder.addExtension(Extension.certificatePolicies, false, seq); } final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA") .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(privKey), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded()); return selfcert; }
From source file:org.elasticsearch.xpack.core.ssl.CertGenUtils.java
License:Open Source License
/** * Generates a signed certificate/*w w w. j a v a 2 s . co m*/ * * @param principal the principal of the certificate; commonly referred to as the * distinguished name (DN) * @param subjectAltNames the subject alternative names that should be added to the * certificate as an X509v3 extension. May be {@code null} * @param keyPair the key pair that will be associated with the certificate * @param caCert the CA certificate. If {@code null}, this results in a self signed * certificate * @param caPrivKey the CA private key. If {@code null}, this results in a self signed * certificate * @param isCa whether or not the generated certificate is a CA * @param days no of days certificate will be valid from now * @param signatureAlgorithm algorithm used for signing certificate. If {@code null} or * empty, then use default algorithm {@link CertGenUtils#getDefaultSignatureAlgorithm(PrivateKey)} * @return a signed {@link X509Certificate} */ private static X509Certificate generateSignedCertificate(X500Principal principal, GeneralNames subjectAltNames, KeyPair keyPair, X509Certificate caCert, PrivateKey caPrivKey, boolean isCa, int days, String signatureAlgorithm) throws NoSuchAlgorithmException, CertificateException, CertIOException, OperatorCreationException { Objects.requireNonNull(keyPair, "Key-Pair must not be null"); final DateTime notBefore = new DateTime(DateTimeZone.UTC); if (days < 1) { throw new IllegalArgumentException("the certificate must be valid for at least one day"); } final DateTime notAfter = notBefore.plusDays(days); final BigInteger serial = CertGenUtils.getSerial(); JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); X500Name subject = X500Name.getInstance(principal.getEncoded()); final X500Name issuer; final AuthorityKeyIdentifier authorityKeyIdentifier; if (caCert != null) { if (caCert.getBasicConstraints() < 0) { throw new IllegalArgumentException("ca certificate is not a CA!"); } issuer = X500Name.getInstance(caCert.getIssuerX500Principal().getEncoded()); authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()); } else { issuer = subject; authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(keyPair.getPublic()); } JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, new Time(notBefore.toDate(), Locale.ROOT), new Time(notAfter.toDate(), Locale.ROOT), subject, keyPair.getPublic()); builder.addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(keyPair.getPublic())); builder.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier); if (subjectAltNames != null) { builder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); } builder.addExtension(Extension.basicConstraints, isCa, new BasicConstraints(isCa)); PrivateKey signingKey = caPrivKey != null ? caPrivKey : keyPair.getPrivate(); ContentSigner signer = new JcaContentSignerBuilder( (Strings.isNullOrEmpty(signatureAlgorithm)) ? getDefaultSignatureAlgorithm(signingKey) : signatureAlgorithm).setProvider(CertGenUtils.BC_PROV).build(signingKey); X509CertificateHolder certificateHolder = builder.build(signer); return new JcaX509CertificateConverter().getCertificate(certificateHolder); }
From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java
License:Open Source License
/** * revoke one enrollment of user/*from ww w . ja va 2s. com*/ * * @param revoker admin user who has revoker attribute configured in CA-server * @param enrollment the user enrollment to be revoked * @param reason revoke reason, see RFC 5280 * @throws RevocationException * @throws InvalidArgumentException */ public void revoke(User revoker, Enrollment enrollment, String reason) throws RevocationException, InvalidArgumentException { if (enrollment == null) { throw new InvalidArgumentException("revokee enrollment is not set"); } if (revoker == null) { throw new InvalidArgumentException("revoker is not set"); } logger.debug(format("revoke revoker: %s, reason: %s, url: %s", revoker.getName(), reason, url)); try { setUpSSL(); // get cert from to-be-revoked enrollment BufferedInputStream pem = new BufferedInputStream( new ByteArrayInputStream(enrollment.getCert().getBytes())); CertificateFactory certFactory = CertificateFactory .getInstance(Config.getConfig().getCertificateFormat()); X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(pem); // get its serial number String serial = DatatypeConverter.printHexBinary(certificate.getSerialNumber().toByteArray()); // get its aki // 2.5.29.35 : AuthorityKeyIdentifier byte[] extensionValue = certificate.getExtensionValue(Extension.authorityKeyIdentifier.getId()); ASN1OctetString akiOc = ASN1OctetString.getInstance(extensionValue); String aki = DatatypeConverter .printHexBinary(AuthorityKeyIdentifier.getInstance(akiOc.getOctets()).getKeyIdentifier()); // build request body RevocationRequest req = new RevocationRequest(name, null, serial, aki, reason); String body = req.toJson(); String authHdr = getHTTPAuthCertificate(revoker.getEnrollment(), body); // send revoke request httpPost(url + HFCA_REVOKE, body, authHdr); logger.debug("revoke done"); } catch (CertificateException e) { logger.error("Cannot validate certificate. Error is: " + e.getMessage()); throw new RevocationException("Error while revoking cert. " + e.getMessage(), e); } catch (Exception e) { logger.error(e.getMessage(), e); throw new RevocationException("Error while revoking the user. " + e.getMessage(), e); } }
From source file:org.hyperledger.fabric_ca.sdkintegration.HFCAClientIT.java
License:Apache License
@Test public void testCertificateRevoke() throws Exception { SampleUser user = getTestUser(TEST_USER1_ORG); if (!user.isRegistered()) { RegistrationRequest rr = new RegistrationRequest(user.getName(), TEST_USER1_AFFILIATION); String password = "testUserRevoke"; rr.setSecret(password);/*ww w.j a va2s .c om*/ rr.addAttribute(new Attribute("user.role", "department lead")); rr.addAttribute(new Attribute(HFCAClient.HFCA_ATTRIBUTE_HFREVOKER, "true")); user.setEnrollmentSecret(client.register(rr, admin)); // Admin can register other users. if (!user.getEnrollmentSecret().equals(password)) { fail("Secret returned from RegistrationRequest not match : " + user.getEnrollmentSecret()); } } if (!user.isEnrolled()) { EnrollmentRequest req = new EnrollmentRequest(DEFAULT_PROFILE_NAME, "label 2", null); req.addHost("example3.ibm.com"); user.setEnrollment(client.enroll(user.getName(), user.getEnrollmentSecret(), req)); } // verify String cert = user.getEnrollment().getCert(); BufferedInputStream pem = new BufferedInputStream(new ByteArrayInputStream(cert.getBytes())); CertificateFactory certFactory = CertificateFactory.getInstance(Config.getConfig().getCertificateFormat()); X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(pem); // get its serial number String serial = DatatypeConverter.printHexBinary(certificate.getSerialNumber().toByteArray()); // get its aki // 2.5.29.35 : AuthorityKeyIdentifier byte[] extensionValue = certificate.getExtensionValue(Extension.authorityKeyIdentifier.getId()); ASN1OctetString akiOc = ASN1OctetString.getInstance(extensionValue); String aki = DatatypeConverter .printHexBinary(AuthorityKeyIdentifier.getInstance(akiOc.getOctets()).getKeyIdentifier()); int startedWithRevokes = -1; if (!testConfig.isRunningAgainstFabric10()) { Thread.sleep(1000); //prevent clock skewing. make sure we request started with revokes. startedWithRevokes = getRevokes(null).length; //one more after we do this revoke. Thread.sleep(1000); //prevent clock skewing. make sure we request started with revokes. } // revoke all enrollment of this user client.revoke(admin, serial, aki, "revoke certificate"); if (!testConfig.isRunningAgainstFabric10()) { final int newRevokes = getRevokes(null).length; assertEquals(format("Expected one more revocation %d, but got %d", startedWithRevokes + 1, newRevokes), startedWithRevokes + 1, newRevokes); } }
From source file:org.hyperledger.fabric_ca.sdkintegration.HFCAClientIT.java
License:Apache License
@Test public void testGetCertificates() throws Exception { if (testConfig.isRunningAgainstFabric10()) { return;/*from w ww. jav a 2 s. co m*/ } HFCACertificateRequest certReq = client.newHFCACertificateRequest(); SampleUser admin2 = sampleStore.getMember("admin2", "org2.department1"); RegistrationRequest rr = new RegistrationRequest(admin2.getName(), "org2.department1"); String password = "password"; rr.setSecret(password); rr.addAttribute(new Attribute("hf.Registrar.Roles", "client,peer,user")); client.register(rr, admin); admin2.setEnrollment(client.enroll(admin2.getName(), password)); rr = new RegistrationRequest("testUser", "org2.department1"); rr.setSecret(password); client.register(rr, admin); Enrollment enroll = client.enroll("testUser", password); // Get all certificates that 'admin2' is allowed to see because no attributes are set // in the certificate request. This returns 2 certificates, one certificate for the caller // itself 'admin2' and the other certificate for 'testuser2'. These are the only two users // that fall under the caller's affiliation of 'org2.department1'. HFCACertificateResponse resp = client.getHFCACertificates(admin2, certReq); assertEquals(2, resp.getCerts().size()); assertTrue(resultContains(resp.getCerts(), new String[] { "admin", "testUser" })); // Get certificate for a specific enrollment id certReq.setEnrollmentID("admin2"); resp = client.getHFCACertificates(admin, certReq); assertEquals(1, resp.getCerts().size()); assertTrue(resultContains(resp.getCerts(), new String[] { "admin" })); // Get certificate for a specific serial number certReq = client.newHFCACertificateRequest(); X509Certificate cert = getCert(enroll.getCert().getBytes()); String serial = cert.getSerialNumber().toString(16); certReq.setSerial(serial); resp = client.getHFCACertificates(admin, certReq); assertEquals(1, resp.getCerts().size()); assertTrue(resultContains(resp.getCerts(), new String[] { "testUser" })); // Get certificate for a specific AKI certReq = client.newHFCACertificateRequest(); String oid = Extension.authorityKeyIdentifier.getId(); byte[] extensionValue = cert.getExtensionValue(oid); ASN1OctetString aki0c = ASN1OctetString.getInstance(extensionValue); AuthorityKeyIdentifier aki = AuthorityKeyIdentifier.getInstance(aki0c.getOctets()); String aki2 = DatatypeConverter.printHexBinary(aki.getKeyIdentifier()); certReq.setAki(aki2); resp = client.getHFCACertificates(admin2, certReq); assertEquals(2, resp.getCerts().size()); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // Get certificates that expired before a specific date // In this case, using a really old date should return 0 certificates certReq = client.newHFCACertificateRequest(); certReq.setExpiredEnd(formatter.parse("2014-30-31")); resp = client.getHFCACertificates(admin, certReq); assertEquals(0, resp.getCerts().size()); // Get certificates that expired before a specific date // In this case, using a date far into the future should return all certificates certReq = client.newHFCACertificateRequest(); Calendar cal = Calendar.getInstance(); Date date = new Date(); cal.setTime(date); cal.add(Calendar.YEAR, 20); date = cal.getTime(); certReq.setExpiredEnd(date); resp = client.getHFCACertificates(admin2, certReq); assertEquals(2, resp.getCerts().size()); assertTrue(resultContains(resp.getCerts(), new String[] { "admin2", "testUser" })); // Get certificates that expired after specific date // In this case, using a really old date should return all certificates that the caller is // allowed to see because they all have a future expiration date certReq = client.newHFCACertificateRequest(); certReq.setExpiredStart(formatter.parse("2014-03-31")); resp = client.getHFCACertificates(admin2, certReq); assertEquals(2, resp.getCerts().size()); // Get certificates that expired after specified date // In this case, using a date far into the future should return zero certificates certReq = client.newHFCACertificateRequest(); certReq.setExpiredStart(date); resp = client.getHFCACertificates(admin, certReq); assertEquals(0, resp.getCerts().size()); client.revoke(admin, "testUser", "baduser"); // Get certificates that were revoked after specific date certReq = client.newHFCACertificateRequest(); certReq.setRevokedStart(formatter.parse("2014-03-31")); resp = client.getHFCACertificates(admin2, certReq); assertEquals(1, resp.getCerts().size()); certReq = client.newHFCACertificateRequest(); certReq.setRevokedEnd(formatter.parse("2014-03-31")); resp = client.getHFCACertificates(admin2, certReq); assertEquals(0, resp.getCerts().size()); certReq = client.newHFCACertificateRequest(); certReq.setRevoked(false); resp = client.getHFCACertificates(admin2, certReq); assertEquals(1, resp.getCerts().size()); assertTrue(resultContains(resp.getCerts(), new String[] { "admin2" })); assertFalse(resultContains(resp.getCerts(), new String[] { "testUser" })); certReq = client.newHFCACertificateRequest(); certReq.setRevoked(true); resp = client.getHFCACertificates(admin2, certReq); assertTrue(resultContains(resp.getCerts(), new String[] { "admin2", "testUser" })); assertEquals(2, resp.getCerts().size()); certReq = client.newHFCACertificateRequest(); certReq.setExpired(false); resp = client.getHFCACertificates(admin2, certReq); assertEquals(2, resp.getCerts().size()); }
From source file:org.keycloak.common.util.CertificateUtils.java
License:Apache License
/** * Generates version 3 {@link java.security.cert.X509Certificate}. * * @param keyPair the key pair/*from w w w . ja v a 2s. co m*/ * @param caPrivateKey the CA private key * @param caCert the CA certificate * @param subject the subject name * * @return the x509 certificate * * @throws Exception the exception */ public static X509Certificate generateV3Certificate(KeyPair keyPair, PrivateKey caPrivateKey, X509Certificate caCert, String subject) throws Exception { try { X500Name subjectDN = new X500Name("CN=" + subject); // Serial Number SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); BigInteger serialNumber = BigInteger.valueOf(Math.abs(random.nextInt())); // Validity Date notBefore = new Date(System.currentTimeMillis()); Date notAfter = new Date(System.currentTimeMillis() + (((1000L * 60 * 60 * 24 * 30)) * 12) * 3); // SubjectPublicKeyInfo SubjectPublicKeyInfo subjPubKeyInfo = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(keyPair.getPublic().getEncoded())); X509v3CertificateBuilder certGen = new X509v3CertificateBuilder( new X500Name(caCert.getSubjectDN().getName()), serialNumber, notBefore, notAfter, subjectDN, subjPubKeyInfo); DigestCalculator digCalc = new BcDigestCalculatorProvider() .get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1)); X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc); // Subject Key Identifier certGen.addExtension(Extension.subjectKeyIdentifier, false, x509ExtensionUtils.createSubjectKeyIdentifier(subjPubKeyInfo)); // Authority Key Identifier certGen.addExtension(Extension.authorityKeyIdentifier, false, x509ExtensionUtils.createAuthorityKeyIdentifier(subjPubKeyInfo)); // Key Usage certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); // Extended Key Usage KeyPurposeId[] EKU = new KeyPurposeId[2]; EKU[0] = KeyPurposeId.id_kp_emailProtection; EKU[1] = KeyPurposeId.id_kp_serverAuth; certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(EKU)); // Basic Constraints certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(0)); // Content Signer ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC") .build(caPrivateKey); // Certificate return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen)); } catch (Exception e) { throw new RuntimeException("Error creating X509v3Certificate.", e); } }
From source file:org.kontalk.certgen.X509Bridge.java
License:Open Source License
/** * Creates a self-signed certificate from a public and private key. The * (critical) key-usage extension is set up with: digital signature, * non-repudiation, key-encipherment, key-agreement and certificate-signing. * The (non-critical) Netscape extension is set up with: SSL client and * S/MIME. A URI subjectAltName may also be set up. * * @param pubKey//from w w w.j ava2 s . c o m * public key * @param privKey * private key * @param subject * subject (and issuer) DN for this certificate, RFC 2253 format * preferred. * @param startDate * date from which the certificate will be valid * (defaults to current date and time if null) * @param endDate * date until which the certificate will be valid * (defaults to start date and time if null) * @param subjectAltName * URI to be placed in subjectAltName * @return self-signed certificate */ private static X509Certificate createCertificate(PublicKey pubKey, PrivateKey privKey, X500Name subject, Date startDate, Date endDate, String subjectAltName, byte[] publicKeyData) throws InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException, CertificateException, NoSuchProviderException, IOException, OperatorCreationException { /* * Sets the signature algorithm. */ BcContentSignerBuilder signerBuilder; String pubKeyAlgorithm = pubKey.getAlgorithm(); if (pubKeyAlgorithm.equals("DSA")) { AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithDSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); signerBuilder = new BcDSAContentSignerBuilder(sigAlgId, digAlgId); } else if (pubKeyAlgorithm.equals("RSA")) { AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder() .find("SHA1WithRSAEncryption"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId); } /* else if (pubKeyAlgorithm.equals("ECDSA")) { // TODO is this even legal? certGenerator.setSignatureAlgorithm("SHA1WithECDSA"); } */ else { throw new RuntimeException("Algorithm not recognised: " + pubKeyAlgorithm); } AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(privKey.getEncoded()); ContentSigner signer = signerBuilder.build(keyp); /* * Sets up the validity dates. */ if (startDate == null) { startDate = new Date(System.currentTimeMillis()); } if (endDate == null) { endDate = startDate; } X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( /* * Sets up the subject distinguished name. * Since it's a self-signed certificate, issuer and subject are the * same. */ subject, /* * The serial-number of this certificate is 1. It makes sense * because it's self-signed. */ BigInteger.ONE, startDate, endDate, subject, /* * Sets the public-key to embed in this certificate. */ SubjectPublicKeyInfo.getInstance(new ASN1InputStream(pubKey.getEncoded()).readObject())); /* * Adds the Basic Constraint (CA: true) extension. */ certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); /* * Adds the Key Usage extension. */ certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.nonRepudiation | KeyUsage.keyEncipherment | KeyUsage.keyAgreement | KeyUsage.keyCertSign)); /* * Adds the Netscape certificate type extension. */ certBuilder.addExtension(MiscObjectIdentifiers.netscapeCertType, false, new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.smime)); JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); /* * Adds the subject key identifier extension. */ SubjectKeyIdentifier subjectKeyIdentifier = extUtils.createSubjectKeyIdentifier(pubKey); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, subjectKeyIdentifier); /* * Adds the authority key identifier extension. */ AuthorityKeyIdentifier authorityKeyIdentifier = extUtils.createAuthorityKeyIdentifier(pubKey); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, authorityKeyIdentifier); /* * Adds the subject alternative-name extension. */ if (subjectAltName != null) { GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.otherName, subjectAltName)); certBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames); } /* * Adds the PGP public key block extension. */ SubjectPGPPublicKeyInfo publicKeyExtension = new SubjectPGPPublicKeyInfo(publicKeyData); certBuilder.addExtension(SubjectPGPPublicKeyInfo.OID, false, publicKeyExtension); /* * Creates and sign this certificate with the private key * corresponding to the public key of the certificate * (hence the name "self-signed certificate"). */ X509CertificateHolder holder = certBuilder.build(signer); /* * Checks that this certificate has indeed been correctly signed. */ X509Certificate cert = new JcaX509CertificateConverter().getCertificate(holder); cert.verify(pubKey); return cert; }