org.bouncycastle.cert.CertIOException Java Examples
The following examples show how to use
org.bouncycastle.cert.CertIOException.
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: IdentityController.java From Spark with Apache License 2.0 | 6 votes |
public X509Certificate createSelfSignedCertificate(KeyPair keyPair) throws NoSuchAlgorithmException, NoSuchProviderException, CertIOException, OperatorCreationException, CertificateException { long serial = System.currentTimeMillis(); SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); X500Name name = new X500Name(createX500NameString()); X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(name, BigInteger.valueOf(serial), new Date(System.currentTimeMillis() - 1000000000), new Date(System.currentTimeMillis() + 1000000000), name, keyInfo ); certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certBuilder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth)); JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA"); ContentSigner signer = csBuilder.build(keyPair.getPrivate()); X509CertificateHolder certHolder = certBuilder.build(signer); X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certHolder); return cert; }
Example #2
Source File: KeyGenerator.java From chvote-1-0 with GNU Affero General Public License v3.0 | 6 votes |
private X509v3CertificateBuilder createCertificateBuilder(KeyPair keyPair) throws PropertyConfigurationException, CertIOException { X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); nameBuilder.addRDN(BCStyle.CN, propertyConfigurationService.getConfigValue(CERT_COMMON_NAME_PROPERTY)); nameBuilder.addRDN(BCStyle.O, propertyConfigurationService.getConfigValue(CERT_ORGANISATION_PROPERTY)); nameBuilder.addRDN(BCStyle.OU, propertyConfigurationService.getConfigValue(CERT_ORGANISATIONAL_UNIT_PROPERTY)); nameBuilder.addRDN(BCStyle.C, propertyConfigurationService.getConfigValue(CERT_COUNTRY_PROPERTY)); X500Name x500Name = nameBuilder.build(); BigInteger serial = new BigInteger(CERT_SERIAL_NUMBER_BIT_SIZE, SecureRandomFactory.createPRNG()); SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); Date startDate = new Date(); Date endDate = Date.from(startDate.toInstant().plus(propertyConfigurationService.getConfigValueAsInt(CERT_VALIDITY_DAYS_PROPERTY), ChronoUnit.DAYS)); X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(x500Name, serial, startDate, endDate, x500Name, publicKeyInfo); String certFriendlyName = propertyConfigurationService.getConfigValue(CERT_PRIVATE_FRIENDLY_NAME_PROPERTY); certificateBuilder.addExtension(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, false, new DERBMPString(certFriendlyName)); return certificateBuilder; }
Example #3
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 #4
Source File: Certificate.java From bouncr with Eclipse Public License 1.0 | 6 votes |
public static X500PrivateCredential generateServerCertificate(KeyPair caKeyPair) throws NoSuchAlgorithmException, CertificateException, OperatorCreationException, CertIOException { X500Name issuerName = new X500Name("CN=bouncrca"); X500Name subjectName = new X500Name("CN=bouncr"); BigInteger serial = BigInteger.valueOf(2); long t1 = System.currentTimeMillis(); KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA"); rsa.initialize(2048, SecureRandom.getInstance("NativePRNGNonBlocking")); KeyPair kp = rsa.generateKeyPair(); System.out.println(System.currentTimeMillis() - t1); X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, NOT_BEFORE, NOT_AFTER, subjectName, kp.getPublic()); DERSequence subjectAlternativeNames = new DERSequence(new ASN1Encodable[] { new GeneralName(GeneralName.dNSName, "localhost"), new GeneralName(GeneralName.dNSName, "127.0.0.1") }); builder.addExtension(Extension.subjectAlternativeName, false, subjectAlternativeNames); X509Certificate cert = signCertificate(builder, caKeyPair.getPrivate()); return new X500PrivateCredential(cert, kp.getPrivate()); }
Example #5
Source File: SubjectAlternativeNameHolder.java From PowerTunnel with MIT License | 5 votes |
public void fillInto(X509v3CertificateBuilder certGen) throws CertIOException { if (!sans.isEmpty()) { ASN1Encodable[] encodables = sans.toArray(new ASN1Encodable[sans .size()]); certGen.addExtension(Extension.subjectAlternativeName, false, new DERSequence(encodables)); } }
Example #6
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 #7
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 #8
Source File: MyUtil.java From xipki with Apache License 2.0 | 5 votes |
public static X509Cert issueSubCaCert(PrivateKey rcaKey, X500Name issuer, SubjectPublicKeyInfo pubKeyInfo, X500Name subject, BigInteger serialNumber, Date startTime) throws CertIOException, OperatorCreationException { Date notAfter = new Date(startTime.getTime() + CaEmulator.DAY_IN_MS * 3650); X509v3CertificateBuilder certGenerator = new X509v3CertificateBuilder(issuer, serialNumber, startTime, notAfter, subject, pubKeyInfo); X509KeyUsage ku = new X509KeyUsage(X509KeyUsage.keyCertSign | X509KeyUsage.cRLSign); certGenerator.addExtension(Extension.keyUsage, true, ku); BasicConstraints bc = new BasicConstraints(0); certGenerator.addExtension(Extension.basicConstraints, true, bc); String signatureAlgorithm = ScepUtil.getSignatureAlgorithm(rcaKey, HashAlgo.SHA256); ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(rcaKey); return new X509Cert(certGenerator.build(contentSigner)); }
Example #9
Source File: OxAuthCryptoProvider.java From oxAuth with MIT License | 5 votes |
public X509Certificate generateV3Certificate(KeyPair keyPair, String issuer, String signatureAlgorithm, Long expirationTime) throws CertIOException, OperatorCreationException, CertificateException { PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); // Signers name X500Name issuerName = new X500Name(issuer); // Subjects name - the same as we are self signed. X500Name subjectName = new X500Name(issuer); // Serial BigInteger serial = new BigInteger(256, new SecureRandom()); // Not before Date notBefore = new Date(System.currentTimeMillis() - 10000); Date notAfter = new Date(expirationTime); // Create the certificate - version 3 JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, notBefore, notAfter, subjectName, publicKey); ASN1EncodableVector purposes = new ASN1EncodableVector(); purposes.add(KeyPurposeId.id_kp_serverAuth); purposes.add(KeyPurposeId.id_kp_clientAuth); purposes.add(KeyPurposeId.anyExtendedKeyUsage); ASN1ObjectIdentifier extendedKeyUsage = new ASN1ObjectIdentifier("2.5.29.37").intern(); builder.addExtension(extendedKeyUsage, false, new DERSequence(purposes)); ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).setProvider("BC").build(privateKey); X509CertificateHolder holder = builder.build(signer); X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(holder); return cert; }
Example #10
Source File: SubjectAlternativeNameHolder.java From LittleProxy-mitm with Apache License 2.0 | 5 votes |
public void fillInto(X509v3CertificateBuilder certGen) throws CertIOException { if (!sans.isEmpty()) { ASN1Encodable[] encodables = sans.toArray(new ASN1Encodable[sans .size()]); certGen.addExtension(Extension.subjectAlternativeName, false, new DERSequence(encodables)); } }
Example #11
Source File: CertificateGeneratorTest.java From credhub with Apache License 2.0 | 5 votes |
private X509CertificateHolder makeCert(final KeyPair certKeyPair, final PrivateKey caPrivateKey, final X500Name caDn, final X500Name subjectDn, final boolean isCa) throws OperatorCreationException, NoSuchAlgorithmException, CertIOException { final SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(certKeyPair.getPublic() .getEncoded()); final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA") .setProvider(BouncyCastleFipsProvider.PROVIDER_NAME) .build(caPrivateKey); final CurrentTimeProvider currentTimeProvider = new CurrentTimeProvider(); final Instant now = Instant.from(currentTimeProvider.getInstant()); final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder( caDn, BigInteger.TEN, Date.from(now), Date.from(now.plus(Duration.ofDays(365))), subjectDn, publicKeyInfo ); x509v3CertificateBuilder .addExtension(Extension.basicConstraints, true, new BasicConstraints(isCa)); return x509v3CertificateBuilder.build(contentSigner); }
Example #12
Source File: SubjectAlternativeNameHolder.java From AndroidHttpCapture with MIT License | 5 votes |
public void fillInto(X509v3CertificateBuilder certGen) throws CertIOException { if (!sans.isEmpty()) { ASN1Encodable[] encodables = sans.toArray(new ASN1Encodable[sans .size()]); certGen.addExtension(Extension.subjectAlternativeName, false, new DERSequence(encodables)); } }
Example #13
Source File: IdentityCertificateService.java From flashback with BSD 2-Clause "Simplified" License | 5 votes |
/** * Fill subject alternate names in to signedCertificatebuilder to build new certificate * @param sans a list of subject alternate name. * * */ private void fillSans(List<ASN1Encodable> sans, X509v3CertificateBuilder x509v3CertificateBuilder) throws CertIOException { if (!sans.isEmpty()) { ASN1Encodable[] encodables = sans.toArray(new ASN1Encodable[sans.size()]); x509v3CertificateBuilder.addExtension(Extension.subjectAlternativeName, false, new DERSequence(encodables)); } }
Example #14
Source File: CertificateHelper.java From signer with GNU Lesser General Public License v3.0 | 5 votes |
public static KeyStore createRootCertificate(Authority authority, String keyStoreType) throws NoSuchAlgorithmException, NoSuchProviderException, CertIOException, IOException, OperatorCreationException, CertificateException, KeyStoreException { KeyPair keyPair = generateKeyPair(ROOT_KEYSIZE); X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); nameBuilder.addRDN(BCStyle.CN, authority.commonName()); nameBuilder.addRDN(BCStyle.O, authority.organization()); nameBuilder.addRDN(BCStyle.OU, authority.organizationalUnitName()); X500Name issuer = nameBuilder.build(); BigInteger serial = BigInteger.valueOf(initRandomSerial()); X500Name subject = issuer; PublicKey pubKey = keyPair.getPublic(); X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE, NOT_AFTER, subject, pubKey); generator.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(pubKey)); generator.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign); generator.addExtension(Extension.keyUsage, false, usage); ASN1EncodableVector purposes = new ASN1EncodableVector(); purposes.add(KeyPurposeId.id_kp_serverAuth); purposes.add(KeyPurposeId.id_kp_clientAuth); purposes.add(KeyPurposeId.anyExtendedKeyUsage); generator.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes)); X509Certificate cert = signCertificate(generator, keyPair.getPrivate()); KeyStore result = KeyStore.getInstance(keyStoreType/* , PROVIDER_NAME */); result.load(null, null); result.setKeyEntry(authority.alias(), keyPair.getPrivate(), authority.password(), new Certificate[] { cert }); return result; }
Example #15
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 #16
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 #17
Source File: AttestationCertificateBuilder.java From webauthn4j with Apache License 2.0 | 5 votes |
public void addBasicConstraintsExtension() { try { certificateBuilder.addExtension( Extension.basicConstraints, false, new BasicConstraints(true) ); } catch (CertIOException e) { throw new UncheckedIOException(e); } }
Example #18
Source File: SelfSignedCertificate.java From hadoop-ozone with Apache License 2.0 | 5 votes |
public X509CertificateHolder build() throws SCMSecurityException, IOException { Preconditions.checkNotNull(key, "Key cannot be null"); Preconditions.checkArgument(Strings.isNotBlank(subject), "Subject " + "cannot be blank"); Preconditions.checkArgument(Strings.isNotBlank(clusterID), "Cluster ID " + "cannot be blank"); Preconditions.checkArgument(Strings.isNotBlank(scmID), "SCM ID cannot " + "be blank"); Preconditions.checkArgument(beginDate.isBefore(endDate), "Certificate " + "begin date should be before end date"); // We just read the beginDate and EndDate as Start of the Day and // confirm that we do not violate the maxDuration Config. Duration certDuration = Duration.between(beginDate.atStartOfDay(), endDate.atStartOfDay()); Duration maxDuration = config.getMaxCertificateDuration(); if (certDuration.compareTo(maxDuration) > 0) { throw new SCMSecurityException("The cert duration violates the " + "maximum configured value. Please check the hdds.x509.max" + ".duration config key. Current Value: " + certDuration + " config: " + maxDuration); } SelfSignedCertificate rootCertificate = new SelfSignedCertificate(this.subject, this.scmID, this.clusterID, this.beginDate, this.endDate, this.config, key); try { return rootCertificate.generateCertificate(isCA); } catch (OperatorCreationException | CertIOException e) { throw new CertificateException("Unable to create root certificate.", e.getCause()); } }
Example #19
Source File: SelfSignedP12Certificate.java From besu with Apache License 2.0 | 5 votes |
@SuppressWarnings("JdkObsolete") // JcaX509v3CertificateBuilder requires java.util.Date. private static Certificate generateSelfSignedCertificate(final KeyPair keyPair) throws CertIOException, GeneralSecurityException, OperatorCreationException { final X500Name issuer = new X500Name(distinguishedName); final X500Name subject = new X500Name(distinguishedName); final BigInteger serialNumber = new BigInteger(String.valueOf(Instant.now().toEpochMilli())); final X509v3CertificateBuilder v3CertificateBuilder = new JcaX509v3CertificateBuilder( issuer, serialNumber, Date.from(Instant.now()), Date.from(Instant.now().plus(Period.ofDays(90))), subject, keyPair.getPublic()); // extensions v3CertificateBuilder.addExtension( Extension.basicConstraints, true, new BasicConstraints(IS_CA)); v3CertificateBuilder.addExtension( Extension.subjectAlternativeName, false, getSubjectAlternativeNames()); final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate()); return new JcaX509CertificateConverter() .setProvider(BOUNCY_CASTLE_PROVIDER) .getCertificate(v3CertificateBuilder.build(contentSigner)); }
Example #20
Source File: SubjectAlternativeNameHolder.java From CapturePacket with MIT License | 5 votes |
public void fillInto(X509v3CertificateBuilder certGen) throws CertIOException { if (!sans.isEmpty()) { ASN1Encodable[] encodables = sans.toArray(new ASN1Encodable[sans .size()]); certGen.addExtension(Extension.subjectAlternativeName, false, new DERSequence(encodables)); } }
Example #21
Source File: AttestationCertificateBuilder.java From webauthn4j with Apache License 2.0 | 5 votes |
public void addSubjectAlternativeNamesExtension(String subjectAlternativeNames) { try { DERSequence derSequence = new DERSequence(new ASN1Encodable[]{ new GeneralName(GeneralName.directoryName, subjectAlternativeNames) }); certificateBuilder.addExtension(Extension.subjectAlternativeName, true, derSequence); } catch (CertIOException e) { throw new UncheckedIOException(e); } }
Example #22
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 #23
Source File: AttestationCertificateBuilder.java From webauthn4j with Apache License 2.0 | 5 votes |
public void addKeyUsageExtension() { try { certificateBuilder.addExtension( Extension.keyUsage, // Key Usage false, new KeyUsage(KeyUsage.keyCertSign) ); } catch (CertIOException e) { throw new UncheckedIOException(e); } }
Example #24
Source File: AttestationCertificateBuilder.java From webauthn4j with Apache License 2.0 | 5 votes |
public void addExtendedKeyUsageExtension(KeyPurposeId keyPurposeId) { try { certificateBuilder.addExtension( Extension.extendedKeyUsage, // Extended Key Usage true, new ExtendedKeyUsage(keyPurposeId) // tcg-kp-AIKCertificate OID ); } catch (CertIOException e) { throw new UncheckedIOException(e); } }
Example #25
Source File: AttestationCertificateBuilder.java From webauthn4j with Apache License 2.0 | 5 votes |
public void addExtension(ASN1ObjectIdentifier oid, boolean isCritical, ASN1Encodable value) { try { certificateBuilder.addExtension(oid, isCritical, value); } catch (CertIOException e) { throw new UncheckedIOException(e); } }
Example #26
Source File: PackedAttestationStatementValidatorTest.java From webauthn4j with Apache License 2.0 | 5 votes |
private static AttestationCertificatePath generateCertPath(KeyPair pair, String signAlg) { try { Provider bcProvider = new BouncyCastleProvider(); //Security.addProvider(bcProvider); long now = System.currentTimeMillis(); Date from = new Date(now); Date to = new Date(from.getTime() + TimeUnit.DAYS.toMillis(1)); X500Name dnName = new X500Name("C=ORG, O=Dummy Org, OU=Authenticator Attestation, CN=Dummy"); BigInteger certSerialNumber = BigInteger.ZERO; Calendar calendar = Calendar.getInstance(); calendar.setTime(from); calendar.add(Calendar.YEAR, 1); ContentSigner contentSigner = new JcaContentSignerBuilder(signAlg).build(pair.getPrivate()); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(dnName, certSerialNumber, from, to, dnName, pair.getPublic()); BasicConstraints basicConstraints = new BasicConstraints(false); certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints); X509Certificate certificate = new JcaX509CertificateConverter().setProvider(bcProvider).getCertificate(certBuilder.build(contentSigner)); return new AttestationCertificatePath(Collections.singletonList(certificate)); } catch (OperatorCreationException | CertificateException | CertIOException e) { throw new UnexpectedCheckedException(e); } }
Example #27
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 #28
Source File: TLSCertificateBuilder.java From fabric-sdk-java with Apache License 2.0 | 4 votes |
private void addSAN(X509v3CertificateBuilder certBuilder, String san) throws CertIOException { ASN1Encodable[] subjectAlternativeNames = new ASN1Encodable[]{new GeneralName(GeneralName.dNSName, san)}; certBuilder.addExtension(Extension.subjectAlternativeName, false, new DERSequence(subjectAlternativeNames)); }
Example #29
Source File: BouncyCastleSecurityProviderTool.java From Dream-Catcher with MIT License | 4 votes |
@Override public CertificateAndKey createServerCertificate(CertificateInfo certificateInfo, X509Certificate caRootCertificate, PrivateKey caPrivateKey, KeyPair serverKeyPair, String messageDigest) { // make sure certificateInfo contains all fields necessary to generate the certificate if (certificateInfo.getCommonName() == null) { throw new IllegalArgumentException("Must specify CN for server certificate"); } if (certificateInfo.getNotBefore() == null) { throw new IllegalArgumentException("Must specify Not Before for server certificate"); } if (certificateInfo.getNotAfter() == null) { throw new IllegalArgumentException("Must specify Not After for server certificate"); } // create the subject for the new server certificate. when impersonating an upstream server, this should contain // the hostname of the server we are trying to impersonate in the CN field X500Name serverCertificateSubject = createX500NameForCertificate(certificateInfo); // get the algorithm that will be used to sign the new certificate, which is a combination of the message digest // and the digital signature from the CA's private key String signatureAlgorithm = EncryptionUtil.getSignatureAlgorithm(messageDigest, caPrivateKey); // get a ContentSigner with our CA private key that will be used to sign the new server certificate ContentSigner signer = getCertificateSigner(caPrivateKey, signatureAlgorithm); // generate a serial number for the new certificate. serial numbers only need to be unique within our // certification authority; a large random integer will satisfy that requirement. BigInteger serialNumber = EncryptionUtil.getRandomBigInteger(CERTIFICATE_SERIAL_NUMBER_SIZE); // create the X509Certificate using Bouncy Castle. the BC X509CertificateHolder can be converted to a JCA X509Certificate. X509CertificateHolder certificateHolder; try { certificateHolder = new JcaX509v3CertificateBuilder(caRootCertificate, serialNumber, certificateInfo.getNotBefore(), certificateInfo.getNotAfter(), serverCertificateSubject, serverKeyPair.getPublic()) .addExtension(Extension.subjectAlternativeName, false, getDomainNameSANsAsASN1Encodable(certificateInfo.getSubjectAlternativeNames())) .addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(serverKeyPair.getPublic())) .addExtension(Extension.basicConstraints, false, new BasicConstraints(false)) .build(signer); } catch (CertIOException e) { throw new CertificateCreationException("Error creating new server certificate", e); } // convert the Bouncy Castle certificate holder into a JCA X509Certificate X509Certificate serverCertificate = convertToJcaCertificate(certificateHolder); return new CertificateAndKey(serverCertificate, serverKeyPair.getPrivate()); }
Example #30
Source File: BouncyCastleSecurityProviderTool.java From Dream-Catcher with MIT License | 4 votes |
@Override public CertificateAndKey createCARootCertificate(CertificateInfo certificateInfo, KeyPair keyPair, String messageDigest) { if (certificateInfo.getNotBefore() == null) { throw new IllegalArgumentException("Must specify Not Before for server certificate"); } if (certificateInfo.getNotAfter() == null) { throw new IllegalArgumentException("Must specify Not After for server certificate"); } // create the X500Name that will be both the issuer and the subject of the new root certificate X500Name issuer = createX500NameForCertificate(certificateInfo); BigInteger serial = EncryptionUtil.getRandomBigInteger(CERTIFICATE_SERIAL_NUMBER_SIZE); PublicKey rootCertificatePublicKey = keyPair.getPublic(); String signatureAlgorithm = EncryptionUtil.getSignatureAlgorithm(messageDigest, keyPair.getPrivate()); // this is a CA root certificate, so it is self-signed ContentSigner selfSigner = getCertificateSigner(keyPair.getPrivate(), signatureAlgorithm); ASN1EncodableVector extendedKeyUsages = new ASN1EncodableVector(); extendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth); extendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth); extendedKeyUsages.add(KeyPurposeId.anyExtendedKeyUsage); X509CertificateHolder certificateHolder; try { certificateHolder = new JcaX509v3CertificateBuilder( issuer, serial, certificateInfo.getNotBefore(), certificateInfo.getNotAfter(), issuer, rootCertificatePublicKey) .addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(rootCertificatePublicKey)) .addExtension(Extension.basicConstraints, true, new BasicConstraints(true)) .addExtension(Extension.keyUsage, false, new KeyUsage( KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign)) .addExtension(Extension.extendedKeyUsage, false, new DERSequence(extendedKeyUsages)) .build(selfSigner); } catch (CertIOException e) { throw new CertificateCreationException("Error creating root certificate", e); } // convert the Bouncy Castle X590CertificateHolder to a JCA cert X509Certificate cert = convertToJcaCertificate(certificateHolder); return new CertificateAndKey(cert, keyPair.getPrivate()); }