org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils Java Examples
The following examples show how to use
org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FluentKeySigner.java From brooklyn-server with Apache License 2.0 | 6 votes |
@SuppressWarnings("deprecation") public X509Certificate newCertificateFor(X500Principal subject, PublicKey keyToCertify) { try { X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); v3CertGen.setSerialNumber( serialNumber != null ? serialNumber : // must be positive BigInteger.valueOf(srand.nextLong()).abs().add(BigInteger.ONE)); v3CertGen.setIssuerDN(issuerPrincipal); v3CertGen.setNotBefore(validityStartDate); v3CertGen.setNotAfter(validityEndDate); v3CertGen.setSignatureAlgorithm(signatureAlgorithm); v3CertGen.setSubjectDN(subject); v3CertGen.setPublicKey(keyToCertify); JcaX509ExtensionUtils jcaX509ExtensionUtils = new JcaX509ExtensionUtils(); v3CertGen.addExtension(X509Extension.subjectKeyIdentifier, false, jcaX509ExtensionUtils.createSubjectKeyIdentifier(keyToCertify)); if (numAllowedIntermediateCAs != null) { // This certificate is for a CA that can issue certificates. // See https://unitstep.net/blog/2009/03/16/using-the-basic-constraints-extension-in-x509-v3-certificates-for-intermediate-cas/ v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(numAllowedIntermediateCAs)); } if (authorityKeyIdentifier!=null) v3CertGen.addExtension(X509Extension.authorityKeyIdentifier, false, authorityKeyIdentifier); X509Certificate pkCertificate = v3CertGen.generate(issuerKey.getPrivate(), "BC"); return pkCertificate; } catch (Exception e) { throw Exceptions.propagate(e); } }
Example #2
Source File: DSSASN1Utils.java From dss with GNU Lesser General Public License v2.1 | 6 votes |
/** * This method returns SKI bytes from certificate. * * @param certificateToken * {@code CertificateToken} * @param computeIfMissing * if the extension is missing and computeIfMissing = true, it will compute the SKI value from the Public * Key * @return ski bytes from the given certificate */ public static byte[] getSki(final CertificateToken certificateToken, boolean computeIfMissing) { try { byte[] extensionValue = certificateToken.getCertificate().getExtensionValue(Extension.subjectKeyIdentifier.getId()); if (Utils.isArrayNotEmpty(extensionValue)) { ASN1Primitive extension = JcaX509ExtensionUtils.parseExtensionValue(extensionValue); SubjectKeyIdentifier skiBC = SubjectKeyIdentifier.getInstance(extension); return skiBC.getKeyIdentifier(); } else if (computeIfMissing) { // If extension not present, we compute it from the certificate public key return computeSkiFromCert(certificateToken); } return null; } catch (IOException e) { throw new DSSException(e); } }
Example #3
Source File: BurpCertificate.java From SAMLRaider with MIT License | 6 votes |
public String getSubjectKeyIdentifier() { // https://stackoverflow.com/questions/6523081/why-doesnt-my-key-identifier-match byte[] e = certificate.getExtensionValue(Extension.subjectKeyIdentifier.getId()); if (e == null) { return ""; } ASN1Primitive ap; byte[] k = {}; try { ap = JcaX509ExtensionUtils.parseExtensionValue(e); k = ASN1OctetString.getInstance(ap.getEncoded()).getOctets(); } catch (IOException e1) { e1.printStackTrace(); } return CertificateHelper.addHexColons(CertificateHelper.byteArrayToHex(k)); }
Example #4
Source File: BurpCertificate.java From SAMLRaider with MIT License | 6 votes |
public String getAuthorityKeyIdentifier() { byte[] e = certificate.getExtensionValue(Extension.authorityKeyIdentifier.getId()); if (e == null) { return ""; } ASN1Primitive ap; byte[] k = {}; try { ap = JcaX509ExtensionUtils.parseExtensionValue(e); k = ASN1Sequence.getInstance(ap.getEncoded()).getEncoded(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // Very ugly hack to extract the SHA1 Hash (59 Hex Chars) from the // Extension :( return CertificateHelper.addHexColons(CertificateHelper.byteArrayToHex(k)).substring(12, k.length * 3 - 1); }
Example #5
Source File: X509Util.java From logback-gelf with GNU Lesser General Public License v2.1 | 6 votes |
private X509Certificate build() throws NoSuchAlgorithmException, CertIOException, OperatorCreationException, CertificateException { final X500Principal issuer = new X500Principal("CN=MyCA"); final BigInteger sn = new BigInteger(64, new SecureRandom()); final Date from = Date.valueOf(LocalDate.now()); final Date to = Date.valueOf(LocalDate.now().plusYears(1)); final X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(issuer, sn, from, to, issuer, keyPair.getPublic()); final JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); v3CertGen.addExtension(Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(keyPair.getPublic())); v3CertGen.addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(keyPair.getPublic())); v3CertGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(0)); v3CertGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); final ContentSigner signer = new JcaContentSignerBuilder(SIG_ALGORITHM) .build(keyPair.getPrivate()); return new JcaX509CertificateConverter() .setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(v3CertGen.build(signer)); }
Example #6
Source File: BasicCertificate.java From signer with GNU Lesser General Public License v3.0 | 6 votes |
/** * Returns the AuthorityInfoAccess extension value on list format.<br> * Otherwise, returns <b>list empty</b>.<br> * @return List Authority info access list */ public List<String> getAuthorityInfoAccess() { List<String> address = new ArrayList<String>(); try { byte[] authorityInfoAccess = certificate.getExtensionValue(Extension.authorityInfoAccess.getId()); if (authorityInfoAccess != null && authorityInfoAccess.length > 0) { AuthorityInformationAccess infoAccess = AuthorityInformationAccess.getInstance( JcaX509ExtensionUtils.parseExtensionValue(authorityInfoAccess)); for (AccessDescription desc : infoAccess.getAccessDescriptions()) if (desc.getAccessLocation().getTagNo() == GeneralName.uniformResourceIdentifier) address.add(((DERIA5String) desc.getAccessLocation().getName()).getString()); } return address; } catch (Exception error) { logger.info(error.getMessage()); return address; } }
Example #7
Source File: SM2PfxMaker.java From gmhelper with Apache License 2.0 | 5 votes |
/** * @param privKey 用户私钥 * @param pubKey 用户公钥 * @param cert X509证书 * @param passwd 口令 * @return * @throws NoSuchAlgorithmException * @throws IOException * @throws PKCSException */ public PKCS12PfxPdu makePfx(PrivateKey privKey, PublicKey pubKey, X509Certificate cert, String passwd) throws NoSuchAlgorithmException, IOException, PKCSException { JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); PKCS12SafeBagBuilder eeCertBagBuilder = new JcaPKCS12SafeBagBuilder(cert); eeCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("User Key")); eeCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, extUtils.createSubjectKeyIdentifier(pubKey)); char[] passwdChars = passwd.toCharArray(); PKCS12SafeBagBuilder keyBagBuilder = new JcaPKCS12SafeBagBuilder(privKey, new BcPKCS12PBEOutputEncryptorBuilder( PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC, new CBCBlockCipher(new DESedeEngine())).build(passwdChars)); keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("User Key")); keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, extUtils.createSubjectKeyIdentifier(pubKey)); PKCS12PfxPduBuilder pfxPduBuilder = new PKCS12PfxPduBuilder(); PKCS12SafeBag[] certs = new PKCS12SafeBag[1]; certs[0] = eeCertBagBuilder.build(); pfxPduBuilder.addEncryptedData(new BcPKCS12PBEOutputEncryptorBuilder( PKCSObjectIdentifiers.pbeWithSHAAnd40BitRC2_CBC, new CBCBlockCipher(new RC2Engine())).build(passwdChars), certs); pfxPduBuilder.addData(keyBagBuilder.build()); return pfxPduBuilder.build(new BcPKCS12MacCalculatorBuilder(), passwdChars); }
Example #8
Source File: CertificateUtils.java From nifi with Apache License 2.0 | 5 votes |
/** * Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority. * * @param keyPair the {@link KeyPair} to generate the {@link X509Certificate} for * @param dn the distinguished name to user for the {@link X509Certificate} * @param signingAlgorithm the signing algorithm to use for the {@link X509Certificate} * @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid * @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority * @throws CertificateException if there is an generating the new certificate */ public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn, String signingAlgorithm, int certificateDurationDays) throws CertificateException { try { ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); Date startDate = new Date(); Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays)); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( reverseX500Name(new X500Name(dn)), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo); // Set certificate extensions // (1) digitalSignature extension certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign | KeyUsage.keyCertSign)); certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true)); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic())); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic())); // (2) extendedKeyUsage extension certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth})); // Sign the certificate X509CertificateHolder certificateHolder = certBuilder.build(sigGen); return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder); } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) { throw new CertificateException(e); } }
Example #9
Source File: DSSASN1Utils.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
/** * This method returns authority key identifier as binaries from the certificate * extension (SHA-1 of the public key of the issuer certificate). * * @param certificateToken * the {@code CertificateToken} * @return authority key identifier bytes from the given certificate (can be * null if the certificate is self signed) */ public static byte[] getAuthorityKeyIdentifier(CertificateToken certificateToken) { byte[] extensionValue = certificateToken.getCertificate().getExtensionValue(Extension.authorityKeyIdentifier.getId()); if (Utils.isArrayNotEmpty(extensionValue)) { try { ASN1Primitive extension = JcaX509ExtensionUtils.parseExtensionValue(extensionValue); AuthorityKeyIdentifier aki = AuthorityKeyIdentifier.getInstance(extension); return aki.getKeyIdentifier(); } catch (IOException e) { throw new DSSException("Unable to parse the authorityKeyIdentifier extension", e); } } return null; }
Example #10
Source File: CertificateUtils.java From nifi with Apache License 2.0 | 5 votes |
/** * Generates an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair} * * @param dn the distinguished name to use * @param publicKey the public key to issue the certificate to * @param extensions extensions extracted from the CSR * @param issuer the issuer's certificate * @param issuerKeyPair the issuer's keypair * @param signingAlgorithm the signing algorithm to use * @param days the number of days it should be valid for * @return an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair} * @throws CertificateException if there is an error issuing the certificate */ public static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, Extensions extensions, X509Certificate issuer, KeyPair issuerKeyPair, String signingAlgorithm, int days) throws CertificateException { try { ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerKeyPair.getPrivate()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); Date startDate = new Date(); Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(days)); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( reverseX500Name(new X500Name(issuer.getSubjectX500Principal().getName())), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey)); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(issuerKeyPair.getPublic())); // Set certificate extensions // (1) digitalSignature extension certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation)); certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false)); // (2) extendedKeyUsage extension certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth})); // (3) subjectAlternativeName if (extensions != null && extensions.getExtension(Extension.subjectAlternativeName) != null) { certBuilder.addExtension(Extension.subjectAlternativeName, false, extensions.getExtensionParsedValue(Extension.subjectAlternativeName)); } X509CertificateHolder certificateHolder = certBuilder.build(sigGen); return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder); } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) { throw new CertificateException(e); } }
Example #11
Source File: SignedCertificateGenerator.java From credhub with Apache License 2.0 | 5 votes |
@Autowired SignedCertificateGenerator( final CurrentTimeProvider timeProvider, final RandomSerialNumberGenerator serialNumberGenerator, final JcaContentSignerBuilder jcaContentSignerBuilder, final JcaX509CertificateConverter jcaX509CertificateConverter ) throws Exception { super(); this.timeProvider = timeProvider; this.serialNumberGenerator = serialNumberGenerator; this.jcaX509ExtensionUtils = new JcaX509ExtensionUtils(); this.jcaContentSignerBuilder = jcaContentSignerBuilder; this.jcaX509CertificateConverter = jcaX509CertificateConverter; }
Example #12
Source File: SparkTrustManager.java From Spark with Apache License 2.0 | 5 votes |
public Collection<X509CRL> loadCRL(X509Certificate[] chain) throws IOException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, CertStoreException, CRLException, CertificateException { // for each certificate in chain for (X509Certificate cert : chain) { if (cert.getExtensionValue(Extension.cRLDistributionPoints.getId()) != null) { ASN1Primitive primitive = JcaX509ExtensionUtils .parseExtensionValue(cert.getExtensionValue(Extension.cRLDistributionPoints.getId())); // extract distribution point extension CRLDistPoint distPoint = CRLDistPoint.getInstance(primitive); DistributionPoint[] dp = distPoint.getDistributionPoints(); // each distribution point extension can hold number of distribution points for (DistributionPoint d : dp) { DistributionPointName dpName = d.getDistributionPoint(); // Look for URIs in fullName if (dpName != null && dpName.getType() == DistributionPointName.FULL_NAME) { GeneralName[] genNames = GeneralNames.getInstance(dpName.getName()).getNames(); // Look for an URI for (GeneralName genName : genNames) { // extract url URL url = new URL(genName.getName().toString()); try { // download from Internet to the collection crlCollection.add(downloadCRL(url)); } catch (CertificateException | CRLException e) { throw new CRLException("Couldn't download CRL"); } } } } } else { Log.warning("Certificate " + cert.getSubjectX500Principal().getName().toString() + " have no CRLs"); } // parameters for cert store is collection type, using collection with crl create parameters CollectionCertStoreParameters params = new CollectionCertStoreParameters(crlCollection); // this parameters are next used for creation of certificate store with crls crlStore = CertStore.getInstance("Collection", params); } return crlCollection; }
Example #13
Source File: KeyStoreGenerator.java From cute-proxy with BSD 2-Clause "Simplified" License | 5 votes |
public KeyStoreGenerator(Path rootKeyStorePath, char[] rootKeyStorePassword) throws Exception { logger.debug("Loading CA certificate/private key from file {}", rootKeyStorePath); KeyStore rootKeyStore = KeyStore.getInstance("PKCS12"); try (InputStream input = Files.newInputStream(rootKeyStorePath)) { rootKeyStore.load(input, rootKeyStorePassword); } var aliases = rootKeyStore.aliases(); String alias = aliases.nextElement(); logger.debug("Loading CA certificate/private by alias {}", alias); Key key = rootKeyStore.getKey(alias, rootKeyStorePassword); requireNonNull(key, "Specified key of the KeyStore not found!"); RSAPrivateCrtKey privateCrtKey = (RSAPrivateCrtKey) key; privateKeyParameters = getPrivateKeyParameters(privateCrtKey); // and get the certificate rootCert = (X509Certificate) rootKeyStore.getCertificate(alias); requireNonNull(rootCert, "Specified certificate of the KeyStore not found!"); logger.debug("Successfully loaded CA key and certificate. CA DN is {}", rootCert.getSubjectDN().getName()); rootCert.verify(rootCert.getPublicKey()); logger.debug("Successfully verified CA certificate with its own public key."); secureRandom = new SecureRandom(); random = new Random(); jcaX509ExtensionUtils = new JcaX509ExtensionUtils(); }
Example #14
Source File: TlsResourceBuilder.java From qpid-broker-j with Apache License 2.0 | 5 votes |
private static Extension createSubjectKeyExtension(final PublicKey publicKey) throws CertificateException { try { return new Extension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey).getEncoded()); } catch (IOException | NoSuchAlgorithmException e) { throw new CertificateException(e); } }
Example #15
Source File: TlsResourceBuilder.java From qpid-broker-j with Apache License 2.0 | 5 votes |
private static Extension createAuthorityKeyExtension(final PublicKey publicKey) throws CertificateException { try { return new Extension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(publicKey).getEncoded()); } catch (IOException | NoSuchAlgorithmException e) { throw new CertificateException(e); } }
Example #16
Source File: CertificateUtils.java From nifi-registry with Apache License 2.0 | 5 votes |
/** * Generates an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair} * * @param dn the distinguished name to use * @param publicKey the public key to issue the certificate to * @param extensions extensions extracted from the CSR * @param issuer the issuer's certificate * @param issuerKeyPair the issuer's keypair * @param signingAlgorithm the signing algorithm to use * @param days the number of days it should be valid for * @return an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair} * @throws CertificateException if there is an error issuing the certificate */ public static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, Extensions extensions, X509Certificate issuer, KeyPair issuerKeyPair, String signingAlgorithm, int days) throws CertificateException { try { ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerKeyPair.getPrivate()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); Date startDate = new Date(); Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(days)); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( reverseX500Name(new X500Name(issuer.getSubjectX500Principal().getName())), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey)); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(issuerKeyPair.getPublic())); // Set certificate extensions // (1) digitalSignature extension certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation)); certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false)); // (2) extendedKeyUsage extension certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth})); // (3) subjectAlternativeName if(extensions != null && extensions.getExtension(Extension.subjectAlternativeName) != null) { certBuilder.addExtension(Extension.subjectAlternativeName, false, extensions.getExtensionParsedValue(Extension.subjectAlternativeName)); } X509CertificateHolder certificateHolder = certBuilder.build(sigGen); return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder); } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) { throw new CertificateException(e); } }
Example #17
Source File: CertificateUtils.java From nifi-registry with Apache License 2.0 | 5 votes |
/** * Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority. * * @param keyPair the {@link KeyPair} to generate the {@link X509Certificate} for * @param dn the distinguished name to user for the {@link X509Certificate} * @param signingAlgorithm the signing algorithm to use for the {@link X509Certificate} * @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid * @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority * @throws CertificateException if there is an generating the new certificate */ public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn, String signingAlgorithm, int certificateDurationDays) throws CertificateException { try { ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); Date startDate = new Date(); Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays)); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( reverseX500Name(new X500Name(dn)), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo); // Set certificate extensions // (1) digitalSignature extension certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign | KeyUsage.keyCertSign)); certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true)); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic())); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic())); // (2) extendedKeyUsage extension certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth})); // Sign the certificate X509CertificateHolder certificateHolder = certBuilder.build(sigGen); return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder); } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) { throw new CertificateException(e); } }
Example #18
Source File: HttpBaseTest.java From calcite-avatica with Apache License 2.0 | 5 votes |
private X509Certificate generateCert(String keyName, KeyPair kp, boolean isCertAuthority, PublicKey signerPublicKey, PrivateKey signerPrivateKey) throws IOException, OperatorCreationException, CertificateException, NoSuchAlgorithmException { Calendar startDate = DateTimeUtils.calendar(); Calendar endDate = DateTimeUtils.calendar(); endDate.add(Calendar.YEAR, 100); BigInteger serialNumber = BigInteger.valueOf(startDate.getTimeInMillis()); X500Name issuer = new X500Name( IETFUtils.rDNsFromString("cn=localhost", RFC4519Style.INSTANCE)); JcaX509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(issuer, serialNumber, startDate.getTime(), endDate.getTime(), issuer, kp.getPublic()); JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils(); certGen.addExtension(Extension.subjectKeyIdentifier, false, extensionUtils.createSubjectKeyIdentifier(kp.getPublic())); certGen.addExtension(Extension.basicConstraints, false, new BasicConstraints(isCertAuthority)); certGen.addExtension(Extension.authorityKeyIdentifier, false, extensionUtils.createAuthorityKeyIdentifier(signerPublicKey)); if (isCertAuthority) { certGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign)); } X509CertificateHolder certificateHolder = certGen.build( new JcaContentSignerBuilder(SIGNING_ALGORITHM).build(signerPrivateKey)); return new JcaX509CertificateConverter().getCertificate(certificateHolder); }
Example #19
Source File: CertificateUtils.java From localization_nifi with Apache License 2.0 | 5 votes |
/** * Generates an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair} * * @param dn the distinguished name to use * @param publicKey the public key to issue the certificate to * @param extensions extensions extracted from the CSR * @param issuer the issuer's certificate * @param issuerKeyPair the issuer's keypair * @param signingAlgorithm the signing algorithm to use * @param days the number of days it should be valid for * @return an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair} * @throws CertificateException if there is an error issuing the certificate */ public static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, Extensions extensions, X509Certificate issuer, KeyPair issuerKeyPair, String signingAlgorithm, int days) throws CertificateException { try { ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerKeyPair.getPrivate()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()); Date startDate = new Date(); Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(days)); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( reverseX500Name(new X500Name(issuer.getSubjectX500Principal().getName())), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey)); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(issuerKeyPair.getPublic())); // Set certificate extensions // (1) digitalSignature extension certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation)); certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false)); // (2) extendedKeyUsage extension certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth})); // (3) subjectAlternativeName if(extensions != null && extensions.getExtension(Extension.subjectAlternativeName) != null) { certBuilder.addExtension(Extension.subjectAlternativeName, false, extensions.getExtensionParsedValue(Extension.subjectAlternativeName)); } X509CertificateHolder certificateHolder = certBuilder.build(sigGen); return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder); } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) { throw new CertificateException(e); } }
Example #20
Source File: CertificateUtils.java From localization_nifi with Apache License 2.0 | 5 votes |
/** * Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority. * * @param keyPair the {@link KeyPair} to generate the {@link X509Certificate} for * @param dn the distinguished name to user for the {@link X509Certificate} * @param signingAlgorithm the signing algorithm to use for the {@link X509Certificate} * @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid * @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority * @throws CertificateException if there is an generating the new certificate */ public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn, String signingAlgorithm, int certificateDurationDays) throws CertificateException { try { ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate()); SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); Date startDate = new Date(); Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays)); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( reverseX500Name(new X500Name(dn)), getUniqueSerialNumber(), startDate, endDate, reverseX500Name(new X500Name(dn)), subPubKeyInfo); // Set certificate extensions // (1) digitalSignature extension certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign | KeyUsage.keyCertSign)); certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true)); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic())); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic())); // (2) extendedKeyUsage extension certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth})); // Sign the certificate X509CertificateHolder certificateHolder = certBuilder.build(sigGen); return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder); } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) { throw new CertificateException(e); } }
Example #21
Source File: X509CertExtensions.java From littleca with Apache License 2.0 | 5 votes |
public static void buildAllExtensions(X509v3CertificateBuilder certBuilder, PublicKey userPublicKey, PublicKey caPublicKey) throws Exception { JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils(); // 添加CRL分布点 /// certBuilder.addExtension(Extension.cRLDistributionPoints, true, // X509CertExtensions.buildCRLDIstPoint()); // 添加证书策略 // certBuilder.addExtension(Extension.certificatePolicies, true, // X509CertExtensions.buildPolicyInfo()); // 颁发者密钥标识 certBuilder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(caPublicKey)); // 使用者密钥标识 certBuilder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(userPublicKey)); // 密钥用法 certBuilder.addExtension(Extension.keyUsage, true, X509CertExtensions.builldKeyUsage()); // 增强密钥用法 certBuilder.addExtension(Extension.extendedKeyUsage, true, X509CertExtensions.builldExtendKeyUsage()); // 主题备用名称扩展 /*certBuilder.addExtension(Extension.issuerAlternativeName, true, X509CertExtensions .buildSubjectAlternativeName(new GeneralName(GeneralName.rfc822Name, "[email protected]")));*/ // 基本约束 if (userPublicKey == caPublicKey) { certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(3)); } else { certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(0)); } }
Example #22
Source File: SM2PfxMaker.java From gmhelper with Apache License 2.0 | 4 votes |
/** * @param privKey 用户私钥 * @param pubKey 用户公钥 * @param chain X509证书数组,切记这里固定了必须是3个元素的数组,且第一个必须是叶子证书、第二个为中级CA证书、第三个为根CA证书 * @param passwd 口令 * @return * @throws NoSuchAlgorithmException * @throws IOException * @throws PKCSException */ public PKCS12PfxPdu makePfx(PrivateKey privKey, PublicKey pubKey, X509Certificate[] chain, String passwd) throws NoSuchAlgorithmException, IOException, PKCSException { JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); PKCS12SafeBagBuilder taCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[2]); taCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Primary Certificate")); PKCS12SafeBagBuilder caCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[1]); caCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Intermediate Certificate")); PKCS12SafeBagBuilder eeCertBagBuilder = new JcaPKCS12SafeBagBuilder(chain[0]); eeCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("User Key")); eeCertBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, extUtils.createSubjectKeyIdentifier(pubKey)); char[] passwdChars = passwd.toCharArray(); PKCS12SafeBagBuilder keyBagBuilder = new JcaPKCS12SafeBagBuilder(privKey, new BcPKCS12PBEOutputEncryptorBuilder( PKCSObjectIdentifiers.pbeWithSHAAnd3_KeyTripleDES_CBC, new CBCBlockCipher(new DESedeEngine())).build(passwdChars)); keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("User Key")); keyBagBuilder.addBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, extUtils.createSubjectKeyIdentifier(pubKey)); PKCS12PfxPduBuilder pfxPduBuilder = new PKCS12PfxPduBuilder(); PKCS12SafeBag[] certs = new PKCS12SafeBag[3]; certs[0] = eeCertBagBuilder.build(); certs[1] = caCertBagBuilder.build(); certs[2] = taCertBagBuilder.build(); pfxPduBuilder.addEncryptedData(new BcPKCS12PBEOutputEncryptorBuilder( PKCSObjectIdentifiers.pbeWithSHAAnd40BitRC2_CBC, new CBCBlockCipher(new RC2Engine())).build(passwdChars), certs); pfxPduBuilder.addData(keyBagBuilder.build()); return pfxPduBuilder.build(new BcPKCS12MacCalculatorBuilder(), passwdChars); }
Example #23
Source File: CertificateModel.java From Spark with Apache License 2.0 | 4 votes |
/** * Get values of the extension and format them into readable Strings. * * @param cert * @param oid */ private void extensionExtractHandler(X509Certificate cert, String oid, boolean critical) { try { ASN1Primitive primitive = JcaX509ExtensionUtils.parseExtensionValue(cert.getExtensionValue(oid)); String value = Res.getString("cert.is.critical") + critical + "\n"; boolean isSupported = true; if (oid.equals(Extension.subjectDirectoryAttributes.toString())) { value += subjectDirectoryAttributesExtractor(primitive); } else if (oid.equals(Extension.subjectKeyIdentifier.toString())) { value += subjectKeyIdentifierExtractor(primitive); } else if (oid.equals(Extension.keyUsage.toString())) { value += keyUsageExtractor(cert); } else if (oid.equals(Extension.subjectAlternativeName.toString())) { value += alternativeNameExtractor(cert.getSubjectAlternativeNames()); } else if (oid.equals(Extension.issuerAlternativeName.toString())) { value += alternativeNameExtractor(cert.getIssuerAlternativeNames()); } else if (oid.equals(Extension.basicConstraints.toString())) { value += basicConstraintsExtractor(primitive); } else if (oid.equals(Extension.nameConstraints.toString())) { value += NameConstraintsExtractor(primitive); } else if (oid.equals(Extension.cRLDistributionPoints.toString())) { value += CRLPointsExtractor(primitive); } else if (oid.equals(Extension.policyMappings.toString())) { value += policyMappingsExtractor(cert); } else if (oid.equals(Extension.authorityKeyIdentifier.toString())) { value += authorityKeyIdentifierExtractor(primitive); } else if (oid.equals(Extension.policyConstraints.toString())) { value += policyConstraintsExtractor(primitive); } else if (oid.equals(Extension.extendedKeyUsage.toString())) { value += extendedKeyUsageExtractor(cert); } else { addToUnsupported(critical, oid); isSupported = false; } if (isSupported) { extensions.put(oid, value); } } catch (NullPointerException | IOException | CertificateParsingException e) { Log.error("Couldn't extract " + oid + ": " + OIDTranslator.getDescription(oid) + "extension.", e); addToUnsupported(critical, oid); } }
Example #24
Source File: TlsHelper.java From nifi with Apache License 2.0 | 4 votes |
public static byte[] getKeyIdentifier(PublicKey publicKey) throws NoSuchAlgorithmException { return new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey).getKeyIdentifier(); }
Example #25
Source File: TlsTestCase.java From wildfly-core with GNU Lesser General Public License v2.1 | 4 votes |
private static X509CRLHolder createCRL() throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); SelfSignedX509CertificateAndSigningKey muneraSelfSignedX509CertificateAndSigningKey = SelfSignedX509CertificateAndSigningKey.builder() .setDn(MUNERASOFT_DN) .setKeyAlgorithmName("RSA") .setSignatureAlgorithmName("SHA256withRSA") .addExtension(false, "BasicConstraints", "CA:true,pathlen:2147483647") .build(); X509Certificate muneraCertificate = muneraSelfSignedX509CertificateAndSigningKey.getSelfSignedCertificate(); Calendar calendar = Calendar.getInstance(); Date currentDate = calendar.getTime(); calendar.add(Calendar.YEAR, 1); Date nextYear = calendar.getTime(); calendar.add(Calendar.YEAR, -1); calendar.add(Calendar.SECOND, -30); Date revokeDate = calendar.getTime(); X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder( new X500Name(MUNERASOFT_DN.getName()), currentDate ); crlBuilder.addExtension( Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(muneraCertificate.getPublicKey()) ); crlBuilder.addExtension( Extension.cRLNumber, false, new CRLNumber(BigInteger.valueOf(4110)) ); crlBuilder.addCRLEntry( new BigInteger("1005"), revokeDate, CRLReason.unspecified ); crlBuilder.addCRLEntry( new BigInteger("1006"), revokeDate, CRLReason.unspecified ); return crlBuilder.setNextUpdate(nextYear).build( new JcaContentSignerBuilder("SHA256withRSA") .setProvider("BC") .build(muneraSelfSignedX509CertificateAndSigningKey.getSigningKey()) ); }
Example #26
Source File: CertificateManager.java From Openfire with Apache License 2.0 | 4 votes |
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, X500NameBuilder issuerBuilder, X500NameBuilder subjectBuilder, String domain, String signAlgoritm, Set<String> sanDnsNames ) throws GeneralSecurityException, IOException { PublicKey pubKey = kp.getPublic(); PrivateKey privKey = kp.getPrivate(); byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed((new Date().getTime())); random.nextBytes(serno); BigInteger serial = (new java.math.BigInteger(serno)).abs(); X500Name issuerDN = issuerBuilder.build(); X500Name subjectDN = subjectBuilder.build(); // builder JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( // issuerDN, // serial, // new Date(), // new Date(System.currentTimeMillis() + days * (1000L * 60 * 60 * 24)), // subjectDN, // pubKey // ); // add subjectAlternativeName extension that includes all relevant names. final GeneralNames subjectAlternativeNames = getSubjectAlternativeNames( sanDnsNames ); final boolean critical = subjectDN.getRDNs().length == 0; certBuilder.addExtension(Extension.subjectAlternativeName, critical, subjectAlternativeNames); // add keyIdentifiers extensions JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils(); certBuilder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(pubKey)); certBuilder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(pubKey)); try { // build the certificate ContentSigner signer = new JcaContentSignerBuilder(signAlgoritm).build(privKey); X509CertificateHolder cert = certBuilder.build(signer); // verify the validity if (!cert.isValidOn(new Date())) { throw new GeneralSecurityException("Certificate validity not valid"); } // verify the signature (self-signed) ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().build(pubKey); if (!cert.isSignatureValid(verifierProvider)) { throw new GeneralSecurityException("Certificate signature not valid"); } return new JcaX509CertificateConverter().getCertificate(cert); } catch (OperatorCreationException | CertException e) { throw new GeneralSecurityException(e); } }
Example #27
Source File: SignedCertificateGeneratorTest.java From credhub with Apache License 2.0 | 4 votes |
@Before public void beforeEach() throws Exception { timeProvider = mock(CurrentTimeProvider.class); now = Instant.ofEpochMilli(1493066824); later = now.plus(Duration.ofDays(expectedDurationInDays)); when(timeProvider.getInstant()).thenReturn(now); serialNumberGenerator = mock(RandomSerialNumberGenerator.class); when(serialNumberGenerator.generate()).thenReturn(BigInteger.valueOf(1337)); jcaX509ExtensionUtils = new JcaX509ExtensionUtils(); generator = KeyPairGenerator .getInstance("RSA", BouncyCastleFipsProvider.PROVIDER_NAME); generator.initialize(1024); // doesn't matter for testing issuerKey = generator.generateKeyPair(); issuerDn = new X500Principal(caName); generatedCertificateKeyPair = generator.generateKeyPair(); certificateGenerationParameters = defaultCertificateParameters(); subject = new SignedCertificateGenerator(timeProvider, serialNumberGenerator, jcaContentSignerBuilder, jcaX509CertificateConverter ); caSubjectKeyIdentifier = jcaX509ExtensionUtils.createSubjectKeyIdentifier(issuerKey.getPublic()); caSerialNumber = BigInteger.valueOf(42L); final JcaX509v3CertificateBuilder x509v3CertificateBuilder = new JcaX509v3CertificateBuilder( issuerDn, caSerialNumber, Date.from(now), Date.from(later), issuerDn, issuerKey.getPublic() ); certificateAuthority = createCertificateAuthority(x509v3CertificateBuilder); x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, caSubjectKeyIdentifier); certificateAuthorityWithSubjectKeyId = createCertificateAuthority(x509v3CertificateBuilder); expectedSubjectKeyIdentifier = certificateAuthorityWithSubjectKeyId.getExtensionValue(Extension.subjectKeyIdentifier.getId()); }
Example #28
Source File: X509Util.java From logback-gelf with GNU Lesser General Public License v2.1 | 4 votes |
X509Certificate build(final String commonName, final String... subjectAltName) throws IOException, OperatorCreationException, CertificateException, NoSuchAlgorithmException { final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(SIG_ALGORITHM); final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); final AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded()); final SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); final ContentSigner sigGen; final X500Name issuer = new X500Name(CA_NAME); final X500NameBuilder x500NameBuilder = new X500NameBuilder(); if (commonName != null) { x500NameBuilder.addRDN(BCStyle.CN, commonName); } x500NameBuilder.addRDN(BCStyle.O, "snakeoil"); final X500Name name = x500NameBuilder.build(); final Date from = Date.valueOf(validFrom); final Date to = Date.valueOf(validTo); final BigInteger sn = new BigInteger(64, new SecureRandom()); final X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(issuer, sn, from, to, name, subPubKeyInfo); if (caCertificate != null) { sigGen = new JcaContentSignerBuilder(SIG_ALGORITHM).build(caPrivateKey); final JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils(); v3CertGen.addExtension(Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCertificate)); } else { sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId) .build(privateKeyAsymKeyParam); } if (subjectAltName != null) { final GeneralName[] generalNames = Arrays.stream(subjectAltName) .map(s -> new GeneralName(GeneralName.dNSName, s)) .toArray(GeneralName[]::new); v3CertGen.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(generalNames).getEncoded()); } final X509CertificateHolder certificateHolder = v3CertGen.build(sigGen); return new JcaX509CertificateConverter() .setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(certificateHolder); }
Example #29
Source File: TlsHelper.java From localization_nifi with Apache License 2.0 | 4 votes |
public static byte[] getKeyIdentifier(PublicKey publicKey) throws NoSuchAlgorithmException { return new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey).getKeyIdentifier(); }