org.bouncycastle.asn1.x509.BasicConstraints Java Examples
The following examples show how to use
org.bouncycastle.asn1.x509.BasicConstraints.
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: AbstractKeyStoreManager.java From DeviceConnect-Android with MIT License | 7 votes |
private X509Certificate generateX509V3Certificate(final KeyPair keyPair, final X500Principal subject, final X500Principal issuer, final Date notBefore, final Date notAfter, final BigInteger serialNumber, final GeneralNames generalNames, final boolean isCA) throws GeneralSecurityException { X509V3CertificateGenerator generator = new X509V3CertificateGenerator(); generator.setSerialNumber(serialNumber); generator.setIssuerDN(issuer); generator.setSubjectDN(subject); generator.setNotBefore(notBefore); generator.setNotAfter(notAfter); generator.setPublicKey(keyPair.getPublic()); generator.setSignatureAlgorithm("SHA256WithRSAEncryption"); generator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(isCA)); generator.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(160)); generator.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); if (generalNames != null) { generator.addExtension(X509Extensions.SubjectAlternativeName, false, generalNames); } return generator.generateX509Certificate(keyPair.getPrivate(), SecurityUtil.getSecurityProvider()); }
Example #2
Source File: RootCertificateBuilderImpl.java From java-certificate-authority with Apache License 2.0 | 6 votes |
@Override public RootCertificate build() { signer.addExtension(KeyUsageExtension.create( KeyUsage.KEY_CERT_SIGN, KeyUsage.CRL_SIGN)); if (crlUri != null) { signer.addExtension(CrlDistPointExtension.create(crlUri)); } // This is a CA signer.addExtension(Extension.basicConstraints, false, new BasicConstraints(true)); final X509Certificate rootCertificate = signer.sign().getX509Certificate(); return new RootCertificateImpl(rootCertificate, pair.getPrivate()); }
Example #3
Source File: X509Ext.java From portecle with GNU General Public License v2.0 | 6 votes |
/** * Get Basic Constraints (2.5.29.19) extension value as a string. * * <pre> * BasicConstraints ::= SEQUENCE { * cA BOOLEAN DEFAULT FALSE, * pathLenConstraint INTEGER (0..MAX) OPTIONAL } * </pre> * * @param bValue The octet string value * @return Extension value as a string */ private String getBasicConstraintsStringValue(byte[] bValue) { BasicConstraints bc = BasicConstraints.getInstance(bValue); StringBuilder strBuff = new StringBuilder(); strBuff.append(RB.getString(bc.isCA() ? "SubjectIsCa" : "SubjectIsNotCa")); strBuff.append("<br><br>"); BigInteger pathLen = bc.getPathLenConstraint(); if (pathLen != null) { strBuff.append(MessageFormat.format(RB.getString("PathLengthConstraint"), pathLen)); } return strBuff.toString(); }
Example #4
Source File: TlsResourceBuilder.java From qpid-broker-j with Apache License 2.0 | 6 votes |
private static X509Certificate createSelfSignedCertificate(final KeyPair keyPair, final String dn, final ValidityPeriod period, final AlternativeName... alternativeName) throws CertificateException { try { final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder( new X500Name(RFC4519Style.INSTANCE, dn), generateSerialNumber(), new Date(period.getFrom().toEpochMilli()), new Date(period.getTo().toEpochMilli()), new X500Name(RFC4519Style.INSTANCE, dn), keyPair.getPublic()); builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false)); builder.addExtension(createKeyUsageExtension()); builder.addExtension(createSubjectKeyExtension(keyPair.getPublic())); builder.addExtension(createAlternateNamesExtension(alternativeName)); return buildX509Certificate(builder, keyPair.getPrivate()); } catch (OperatorException | IOException e) { throw new CertificateException(e); } }
Example #5
Source File: TlsResourceBuilder.java From qpid-broker-j with Apache License 2.0 | 6 votes |
private static X509Certificate createRootCACertificate(final KeyPair keyPair, final String dn, final ValidityPeriod validityPeriod) throws CertificateException { try { final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder( new X500Name(RFC4519Style.INSTANCE, dn), generateSerialNumber(), new Date(validityPeriod.getFrom().toEpochMilli()), new Date(validityPeriod.getTo().toEpochMilli()), new X500Name(RFC4519Style.INSTANCE, dn), keyPair.getPublic()); builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true)); builder.addExtension(createSubjectKeyExtension(keyPair.getPublic())); builder.addExtension(createAuthorityKeyExtension(keyPair.getPublic())); return buildX509Certificate(builder, keyPair.getPrivate()); } catch (OperatorException | IOException e) { throw new CertificateException(e); } }
Example #6
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 #7
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 #8
Source File: CaEmulator.java From xipki with Apache License 2.0 | 6 votes |
public X509Cert generateCert(SubjectPublicKeyInfo pubKeyInfo, X500Name subjectDn, Date notBefore) throws Exception { Args.notNull(pubKeyInfo, "pubKeyInfo"); Args.notNull(subjectDn, "subjectDn"); Args.notNull(notBefore, "notBefore"); Date notAfter = new Date(notBefore.getTime() + 730 * DAY_IN_MS); BigInteger tmpSerialNumber = BigInteger.valueOf(serialNumber.getAndAdd(1)); X509v3CertificateBuilder certGenerator = new X509v3CertificateBuilder(caSubject, tmpSerialNumber, notBefore, notAfter, subjectDn, pubKeyInfo); X509KeyUsage ku = new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.dataEncipherment | X509KeyUsage.keyAgreement | X509KeyUsage.keyEncipherment); certGenerator.addExtension(Extension.keyUsage, true, ku); BasicConstraints bc = new BasicConstraints(false); certGenerator.addExtension(Extension.basicConstraints, true, bc); String signatureAlgorithm = ScepUtil.getSignatureAlgorithm(caKey, HashAlgo.SHA256); ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(caKey); X509Cert cert = new X509Cert(certGenerator.build(contentSigner)); serialCertMap.put(tmpSerialNumber, cert); reqSubjectCertMap.put(subjectDn, cert); return cert; }
Example #9
Source File: ExtensionsChecker.java From xipki with Apache License 2.0 | 6 votes |
private void checkExtnBasicConstraints(StringBuilder failureMsg, byte[] extensionValue) { BasicConstraints bc = BasicConstraints.getInstance(extensionValue); CertLevel certLevel = certprofile.getCertLevel(); boolean ca = (CertLevel.RootCA == certLevel) || (CertLevel.SubCA == certLevel); if (ca != bc.isCA()) { addViolation(failureMsg, "ca", bc.isCA(), ca); } if (!bc.isCA()) { return; } BigInteger tmpPathLen = bc.getPathLenConstraint(); Integer pathLen = certprofile.getPathLen(); if (pathLen == null) { if (tmpPathLen != null) { addViolation(failureMsg, "pathLen", tmpPathLen, "absent"); } } else { if (tmpPathLen == null) { addViolation(failureMsg, "pathLen", "null", pathLen); } else if (!BigInteger.valueOf(pathLen).equals(tmpPathLen)) { addViolation(failureMsg, "pathLen", tmpPathLen, pathLen); } } }
Example #10
Source File: SelfSignedCaCertificate.java From nomulus with Apache License 2.0 | 6 votes |
/** Returns a self-signed Certificate Authority (CA) certificate. */ static X509Certificate createCaCert(KeyPair keyPair, String fqdn, Date from, Date to) throws Exception { X500Name owner = new X500Name("CN=" + fqdn); ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate()); X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder( owner, new BigInteger(64, RANDOM), from, to, owner, keyPair.getPublic()); // Mark cert as CA by adding basicConstraint with cA=true to the builder BasicConstraints basicConstraints = new BasicConstraints(true); builder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints); X509CertificateHolder certHolder = builder.build(signer); return new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certHolder); }
Example #11
Source File: SignedCertificateGeneratorTest.java From credhub with Apache License 2.0 | 6 votes |
@Test public void getSignedByIssuer_generatesACertificateWithTheRightValues() throws Exception { final X509Certificate generatedCertificate = subject .getSignedByIssuer(generatedCertificateKeyPair, certificateGenerationParameters, certificateAuthorityWithSubjectKeyId, issuerKey.getPrivate()); assertThat(generatedCertificate.getIssuerDN().getName(), containsString("CN=ca DN")); assertThat(generatedCertificate.getIssuerDN().getName(), containsString("O=credhub")); assertThat(generatedCertificate.getSerialNumber(), equalTo(BigInteger.valueOf(1337L))); assertThat(generatedCertificate.getNotBefore().toString(), equalTo(Date.from(now).toString())); assertThat(generatedCertificate.getNotAfter().toString(), equalTo(Date.from(later).toString())); assertThat(generatedCertificate.getSubjectDN().toString(), containsString("CN=my cert name")); assertThat(generatedCertificate.getPublicKey(), equalTo(generatedCertificateKeyPair.getPublic())); assertThat(generatedCertificate.getSigAlgName(), equalTo("SHA256WITHRSA")); generatedCertificate.verify(issuerKey.getPublic()); final byte[] isCaExtension = generatedCertificate.getExtensionValue(Extension.basicConstraints.getId()); assertThat(Arrays.copyOfRange(isCaExtension, 2, isCaExtension.length), equalTo(new BasicConstraints(true).getEncoded())); }
Example #12
Source File: CertificateHandler.java From development with Apache License 2.0 | 6 votes |
private X509Certificate generateSignedCertificate( PKCS10CertificationRequest csr) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, CertificateParsingException, CertificateEncodingException, SignatureException { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(rootCert.getSubjectX500Principal()); Calendar c = Calendar.getInstance(); certGen.setNotBefore(c.getTime()); c.add(Calendar.YEAR, 1); certGen.setNotAfter(c.getTime()); certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject()); certGen.setPublicKey(csr.getPublicKey("BC")); certGen.setSignatureAlgorithm(ALGORITHM_SHA256_RSA); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(rootCert.getPublicKey())); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(csr.getPublicKey("BC"))); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage( KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); X509Certificate issuedCert = certGen.generate(rootPrivateKeyEntry .getPrivateKey()); return issuedCert; }
Example #13
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 #14
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 #15
Source File: CertificateGenerator.java From NetBare with MIT License | 5 votes |
/** * Generate a root keystore by a given {@link JKS}. * * @param jks A java keystore object. * @return A root {@link KeyStore}. */ public KeyStore generateRoot(JKS jks) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, OperatorCreationException { KeyPair keyPair = generateKeyPair(ROOT_KEY_SIZE); X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); nameBuilder.addRDN(BCStyle.CN, jks.commonName()); nameBuilder.addRDN(BCStyle.O, jks.organization()); nameBuilder.addRDN(BCStyle.OU, jks.organizationalUnitName()); X500Name issuer = nameBuilder.build(); PublicKey pubKey = keyPair.getPublic(); X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder( issuer, BigInteger.valueOf(randomSerial()), NOT_BEFORE, NOT_AFTER, issuer, 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(KEY_STORE_TYPE); result.load(null, null); result.setKeyEntry(jks.alias(), keyPair.getPrivate(), jks.password(), new Certificate[] { cert }); return result; }
Example #16
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 #17
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 #18
Source File: CertificateModel.java From Spark with Apache License 2.0 | 5 votes |
private String basicConstraintsExtractor(ASN1Primitive primitive) { BasicConstraints bc = BasicConstraints.getInstance(primitive); String value = Res.getString("cert.extension.basic.constraints.is.ca") + ": " + bc.isCA(); if (bc.getPathLenConstraint() != null) { value += "\n" + Res.getString("cert.extension.basic.constraints.path.length") + ": " + bc.getPathLenConstraint(); } return value; }
Example #19
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 #20
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 #21
Source File: DBasicConstraints.java From keystore-explorer with GNU General Public License v3.0 | 5 votes |
private void prepopulateWithValue(byte[] value) throws IOException { BasicConstraints basicConstraints = BasicConstraints.getInstance(value); jcbSubjectIsCa.setSelected(basicConstraints.isCA()); if (basicConstraints.getPathLenConstraint() != null) { jtfPathLengthConstraint.setText("" + basicConstraints.getPathLenConstraint().intValue()); jtfPathLengthConstraint.setCaretPosition(0); } }
Example #22
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 #23
Source File: TlsResourceBuilder.java From qpid-broker-j with Apache License 2.0 | 5 votes |
private static X509Certificate generateIntermediateCertificate(final KeyPair keyPair, final KeyCertificatePair rootCA, final String dn, final ValidityPeriod validityPeriod, final String crlUri) throws CertificateException { try { final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder( rootCA.getCertificate(), generateSerialNumber(), new Date(validityPeriod.getFrom().toEpochMilli()), new Date(validityPeriod.getTo().toEpochMilli()), new X500Name(RFC4519Style.INSTANCE, dn), keyPair.getPublic()); //builder.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign)); builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true)); builder.addExtension(createSubjectKeyExtension(keyPair.getPublic())); builder.addExtension(createAuthorityKeyExtension(rootCA.getCertificate().getPublicKey())); if (crlUri != null) { builder.addExtension(createDistributionPointExtension(crlUri)); } return buildX509Certificate(builder, rootCA.getPrivateKey()); } catch (OperatorException | IOException e) { throw new CertificateException(e); } }
Example #24
Source File: CertificateServiceImpl.java From graviteeio-access-management with Apache License 2.0 | 5 votes |
private X509Certificate generateCertificate(String dn, KeyPair keyPair, int validity, String sigAlgName) throws GeneralSecurityException, IOException, OperatorCreationException { Provider bcProvider = new BouncyCastleProvider(); Security.addProvider(bcProvider); // Use appropriate signature algorithm based on your keyPair algorithm. String signatureAlgorithm = sigAlgName; X500Name dnName = new X500Name(dn); Date from = new Date(); Date to = new Date(from.getTime() + validity * 1000L * 24L * 60L * 60L); // Using the current timestamp as the certificate serial number BigInteger certSerialNumber = new BigInteger(Long.toString(from.getTime())); ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(keyPair.getPrivate()); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( dnName, certSerialNumber, from, to, dnName, keyPair.getPublic()); // true for CA, false for EndEntity BasicConstraints basicConstraints = new BasicConstraints(true); // Basic Constraints is usually marked as critical. certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints); return new JcaX509CertificateConverter().setProvider(bcProvider).getCertificate(certBuilder.build(contentSigner)); }
Example #25
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 #26
Source File: CertificateHelper.java From signer with GNU Lesser General Public License v3.0 | 5 votes |
public static KeyStore createServerCertificate(String commonName, SubjectAlternativeNameHolder subjectAlternativeNames, Authority authority, Certificate caCert, PrivateKey caPrivKey) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, OperatorCreationException, CertificateException, InvalidKeyException, SignatureException, KeyStoreException { KeyPair keyPair = generateKeyPair(FAKE_KEYSIZE); X500Name issuer = new X509CertificateHolder(caCert.getEncoded()).getSubject(); BigInteger serial = BigInteger.valueOf(initRandomSerial()); X500NameBuilder name = new X500NameBuilder(BCStyle.INSTANCE); name.addRDN(BCStyle.CN, commonName); name.addRDN(BCStyle.O, authority.certOrganisation()); name.addRDN(BCStyle.OU, authority.certOrganizationalUnitName()); X500Name subject = name.build(); X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE, NOT_AFTER, subject, keyPair.getPublic()); builder.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(keyPair.getPublic())); builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false)); subjectAlternativeNames.fillInto(builder); X509Certificate cert = signCertificate(builder, caPrivKey); cert.checkValidity(new Date()); cert.verify(caCert.getPublicKey()); KeyStore result = KeyStore.getInstance("PKCS12" /* , PROVIDER_NAME */); result.load(null, null); Certificate[] chain = { cert, caCert }; result.setKeyEntry(authority.alias(), keyPair.getPrivate(), authority.password(), chain); return result; }
Example #27
Source File: TLSCertificateBuilder.java From fabric-sdk-java with Apache License 2.0 | 5 votes |
private X509Certificate createSelfSignedCertificate(CertType certType, KeyPair keyPair, String san) throws Exception { X509v3CertificateBuilder certBuilder = createCertBuilder(keyPair); // Basic constraints BasicConstraints constraints = new BasicConstraints(false); certBuilder.addExtension( Extension.basicConstraints, true, constraints.getEncoded()); // Key usage KeyUsage usage = new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature); certBuilder.addExtension(Extension.keyUsage, false, usage.getEncoded()); // Extended key usage certBuilder.addExtension( Extension.extendedKeyUsage, false, certType.keyUsage().getEncoded()); if (san != null) { addSAN(certBuilder, san); } ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm) .build(keyPair.getPrivate()); X509CertificateHolder holder = certBuilder.build(signer); JcaX509CertificateConverter converter = new JcaX509CertificateConverter(); converter.setProvider(new BouncyCastleProvider()); return converter.getCertificate(holder); }
Example #28
Source File: DeviceCertificateManager.java From enmasse with Apache License 2.0 | 5 votes |
public DeviceCertificateManager(final Mode mode, final X500Principal baseName) throws Exception { this.mode = mode; this.baseName = baseName; this.keyPairGenerator = KeyPairGenerator.getInstance(mode.getGeneratorAlgorithm()); this.keyPairGenerator.initialize(mode.getSpec()); this.keyPair = keyPairGenerator.generateKeyPair(); final Instant now = Instant.now(); final ContentSigner contentSigner = new JcaContentSignerBuilder(mode.getSignatureAlgorithm()) .build(this.keyPair.getPrivate()); final X509CertificateHolder certificate = new JcaX509v3CertificateBuilder( baseName, BigInteger.valueOf(this.serialNumber.getAndIncrement()), Date.from(now), Date.from(now.plus(Duration.ofDays(365))), baseName, this.keyPair.getPublic()) .addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyId(this.keyPair.getPublic())) .addExtension(Extension.authorityKeyIdentifier, false, createAuthorityKeyId(this.keyPair.getPublic())) .addExtension(Extension.basicConstraints, true, new BasicConstraints(true)) .build(contentSigner); this.certificate = new JcaX509CertificateConverter() .setProvider(new BouncyCastleProvider()) .getCertificate(certificate); }
Example #29
Source File: CertificateReader.java From credhub with Apache License 2.0 | 5 votes |
public boolean isCa() { final Extensions extensions = certificateHolder.getExtensions(); BasicConstraints basicConstraints = null; if (extensions != null) { basicConstraints = BasicConstraints .fromExtensions(Extensions.getInstance(extensions)); } return basicConstraints != null && basicConstraints.isCA(); }
Example #30
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); }