public static X509CertificateHolder makeCertificate(AsymmetricCipherKeyPair subKP, String _subDN, AsymmetricCipherKeyPair issKP, String _issDN, boolean _ca) throws IOException, OperatorCreationException { RSAKeyParameters lwPubKey = (RSAKeyParameters)subKP.getPublic(); X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder( new X500Name(_issDN), allocateSerialNumber(), new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)), new X500Name(_subDN), new SubjectPublicKeyInfo(new AlgorithmIdentifier(PKCSObjectIdentifiers.rsaEncryption, DERNull.INSTANCE), new RSAPublicKey(lwPubKey.getModulus(), lwPubKey.getExponent())) ); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1WithRSAEncryption"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build((AsymmetricKeyParameter)issKP.getPrivate()); v3CertGen.addExtension( X509Extension.basicConstraints, false, new BasicConstraints(_ca)); return v3CertGen.build(sigGen); }
public static SSLKeyPair createSelfSignedSSLKeyPair(String commonsName, RSAPrivateKey caPrivateKey, RSAPublicKey caPublicKey) { try { BigInteger serial = BigInteger.valueOf(new Random().nextInt()); long end = System.currentTimeMillis() + DEFAULT_CERTIFICATE_DURATION_VALIDITY; org.bouncycastle.asn1.x500.X500Name commonsX500Name = new org.bouncycastle.asn1.x500.X500Name(COMMON_NAME_ENTRY + commonsName); JcaX509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(commonsX500Name, serial, new Date(), new Date(end), commonsX500Name, caPublicKey); JcaX509ExtensionUtils jcaX509ExtensionUtils = new JcaX509ExtensionUtils(); certificateBuilder.addExtension(subjectKeyIdentifier, false, jcaX509ExtensionUtils.createSubjectKeyIdentifier(caPublicKey)); certificateBuilder.addExtension(basicConstraints, true, new BasicConstraints(true)); addASN1AndKeyUsageExtensions(certificateBuilder); X509Certificate cert = verifyCertificate(caPrivateKey, caPublicKey, certificateBuilder); return new SSLKeyPair(caPrivateKey, caPublicKey, new X509Certificate[]{cert}); } catch (NoSuchAlgorithmException | CertIOException | CertificateException | InvalidKeyException | OperatorCreationException | SignatureException | NoSuchProviderException e) { throw new RuntimeException("Unable to generate SSL certificate for " + commonsName, e); } }
/** * 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 * @throws IOException If an I/O problem occurs */ private String getBasicConstraintsStringValue(byte[] bValue) throws IOException { 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(); }
private static X509Certificate createSelfSignedCertificate(KeyPair keyPair, AthenzIdentity identity) throws OperatorCreationException, CertIOException, CertificateException { ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSA").build(keyPair.getPrivate()); X500Name x500Name = new X500Name("CN="+ identity.getFullName()); Instant now = Instant.now(); Date notBefore = Date.from(now); Date notAfter = Date.from(now.plus(Duration.ofDays(30))); X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder( x500Name, BigInteger.valueOf(now.toEpochMilli()), notBefore, notAfter, x500Name, keyPair.getPublic() ) .addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); return new JcaX509CertificateConverter() .setProvider(new BouncyCastleProvider()) .getCertificate(certificateBuilder.build(contentSigner)); }
private static X509Certificate createSelfSignedCertificate(KeyPair keyPair, ConfigserverConfig config) throws IOException, CertificateException, OperatorCreationException { ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSA").build(keyPair.getPrivate()); X500Name x500Name = new X500Name("CN="+ config.loadBalancerAddress()); Instant now = Instant.now(); Date notBefore = Date.from(now); Date notAfter = Date.from(now.plus(Duration.ofDays(30))); GeneralNames generalNames = new GeneralNames( config.zookeeperserver().stream() .map(server -> new GeneralName(GeneralName.dNSName, server.hostname())) .toArray(GeneralName[]::new)); X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder( x500Name, BigInteger.valueOf(now.toEpochMilli()), notBefore, notAfter, x500Name, keyPair.getPublic() ) .addExtension(Extension.basicConstraints, true, new BasicConstraints(true)) .addExtension(Extension.subjectAlternativeName, false, generalNames); return new JcaX509CertificateConverter() .setProvider(provider) .getCertificate(certificateBuilder.build(contentSigner)); }
@Test public void getSignedByIssuer_generatesACertificateWithTheRightValues() throws Exception { 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.toInstant()).toString())); assertThat(generatedCertificate.getNotAfter().toString(), equalTo(Date.from(later.toInstant()).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()); byte[] isCaExtension = generatedCertificate.getExtensionValue(Extension.basicConstraints.getId()); assertThat(Arrays.copyOfRange(isCaExtension, 2, isCaExtension.length), equalTo(new BasicConstraints(true).getEncoded())); }
@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()); }
public X509V3CertRequest( final X500Principal issuerPrincipal, final BigInteger serialNumber, final Instant notBefore, final Instant notAfter, @NonNull final X500Principal subjectPrincipal, @NonNull final PublicKey subjectPublicKey, @NonNull final Collection<X509CertExtension> extensions, @NonNull final BasicConstraints basicConstraints ) { super(issuerPrincipal, serialNumber, notBefore, notAfter); checkConstraints(extensions); this.subjectPrincipal = subjectPrincipal; this.subjectPublicKey = subjectPublicKey; this.extensions = augmentExtensions(extensions, subjectPublicKey, X509CertExtension.basicConstraints(basicConstraints)); }
public CAIssuedX509V3CertRequest( @NonNull final X509Certificate caCert, @NonNull final BigInteger serialNumber, @NonNull final Instant notBefore, @NonNull final Instant notAfter, @NonNull final X500Principal subjectPrincipal, @NonNull final PublicKey subjectPublicKey, @NonNull final Collection<X509CertExtension> extensions, @NonNull final BasicConstraints basicConstraints ) { checkArgs(caCert, extensions); this.x509V3CertRequest = new X509V3CertRequest( caCert.getSubjectX500Principal(), serialNumber, notBefore, notAfter, subjectPrincipal, subjectPublicKey, augmentExtensions(extensions, caCert), basicConstraints ); }
public SelfSignedX509V3CertRequest( final X500Principal issuerPrincipal, final BigInteger serialNumber, final Instant notBefore, final Instant notAfter, @NonNull final KeyPair keyPair, @NonNull final Collection<X509CertExtension> extensions, @NonNull final BasicConstraints basicConstraints ) { this.x509V3CertRequest = new X509V3CertRequest( issuerPrincipal, serialNumber, notBefore, notAfter, issuerPrincipal, keyPair.getPublic(), extensions, basicConstraints ); this.privateKey = keyPair.getPrivate(); }
private CaCert caCert() throws NoSuchAlgorithmException, NoSuchProviderException { final DistinguishedName issuer = issuer(); final X500Principal issuerPrincipal = issuer.toX500Principal(); final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA.name(), BOUNCY_CASTLE); final KeyPair certKeyPair = keyPairGenerator.generateKeyPair(); final ImmutableList<X509CertExtension> x509CertExtensions = ImmutableList.<X509CertExtension>builder() .add(keyUsage(new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign))) .build(); final SelfSignedX509V3CertRequest selfSignedRequest = new SelfSignedX509V3CertRequest( issuerPrincipal, BigInteger.ONE, Instant.now(), Instant.ofEpochMilli(System.currentTimeMillis() + (10 * 1000)), certKeyPair, x509CertExtensions, new BasicConstraints(Integer.MAX_VALUE) ); return new CaCert(certificateService.generateSelfSignedX509CertificateV3(selfSignedRequest), certKeyPair.getPrivate()); }
private static X509Certificate generateCertificate(final String domain, final KeyPair pair) { try { final X500Name issuerName = new X500Name("CN=" + domain); final X500Name subjectName = issuerName; final BigInteger serial = BigInteger.valueOf(new Random().nextInt()); final Date notBefore = Date.from(LocalDateTime.of(2016, 1, 1, 0, 0).toInstant(ZoneOffset.UTC)); final Date notAfter = Date.from(LocalDateTime.of(2099, 1, 1, 0, 0).toInstant(ZoneOffset.UTC)); final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, notBefore, notAfter, subjectName, pair.getPublic()); builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); final ASN1EncodableVector purposes = new ASN1EncodableVector(); purposes.add(KeyPurposeId.id_kp_serverAuth); builder.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes)); return signCertificate(builder, pair.getPrivate()); } catch (final CertIOException ex) { throw new RuntimeException("Couldn't generate certificate", ex); } }
/** * intermediate cert */ private X509Certificate createIntmedCert( PublicKey pubKey, PrivateKey caPrivKey, PublicKey caPubKey, CertificatePolicies policies, Hashtable policyMap) throws Exception { String issuer = "C=JP, O=policyMappingAdditionalTest, OU=trustAnchor"; String subject = "C=JP, O=policyMappingAdditionalTest, OU=intmedCA"; v3CertGen.reset(); v3CertGen.setSerialNumber(BigInteger.valueOf(20)); v3CertGen.setIssuerDN(new X509Principal(issuer)); v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30)); v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30))); v3CertGen.setSubjectDN(new X509Principal(subject)); v3CertGen.setPublicKey(pubKey); v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); v3CertGen.addExtension(X509Extensions.CertificatePolicies, true, policies); v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); v3CertGen.addExtension(X509Extensions.PolicyMappings, true, new PolicyMappings(policyMap)); X509Certificate cert = v3CertGen.generate(caPrivKey); return cert; }
public static X509Certificate generateIntermediateCert(PublicKey intKey, PrivateKey caKey, X509Certificate caCert) throws Exception { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert)); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X509Principal("CN=Test Intermediate Certificate")); certGen.setPublicKey(intKey); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(intKey)); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); return certGen.generate(caKey, "BC"); }
public static X509Certificate generateEndEntityCert(PublicKey entityKey, PrivateKey caKey, X509Certificate caCert) throws Exception { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert)); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X509Principal("CN=Test End Certificate")); certGen.setPublicKey(entityKey); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(entityKey)); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); return certGen.generate(caKey, "BC"); }
private void checkExtensionBasicConstraints(StringBuilder failureMsg, byte[] extensionValue) { BasicConstraints bc = BasicConstraints.getInstance(extensionValue); X509CertLevel certLevel = certProfile.certLevel(); boolean ca = (X509CertLevel.RootCA == certLevel) || (X509CertLevel.SubCA == certLevel); if (ca != bc.isCA()) { addViolation(failureMsg, "ca", bc.isCA(), ca); } if (bc.isCA()) { BigInteger tmpPathLen = bc.getPathLenConstraint(); Integer pathLen = certProfile.pathLen(); 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); } } } }
private void generateDummySSLClientCertificate(KeyStore ks) throws Exception { LOG.info("Generating a Dummy SSL client certificate ..."); KeyPair pair = CertificateUtilities.generateRSAKeyPair(getCryptoStrength()); String DN = "CN=SSL dummy client cert, O=Dummy org., C=FR"; X509V3CertificateGenerator v3CertGen = CertificateUtilities.initCertificateGenerator(pair, DN, DN, true, CertificateUtilities.DEFAULT_VALIDITY_PERIOD); v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); v3CertGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false, new NetscapeCertType(NetscapeCertType.sslClient)); v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth)); X509Certificate cert = v3CertGen.generate(pair.getPrivate()); ks.setKeyEntry(DUMMY_SSL_CLIENT_ALIAS, pair.getPrivate(), KEYSTORE_PASSWORD, new Certificate[] {cert}); }
public X509Certificate getNewCertificate(String certDn, String keySigningAlgorithm, KeyPair keyPair) throws GeneralSecurityException { LOG.debug(String.format("getNewCertificate(%s, %s, %s)", certDn, keySigningAlgorithm, keyPair)); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); X500Principal dnName = new X500Principal(certDn); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(dnName); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); Calendar cal = Calendar.getInstance(); certGen.setNotBefore(cal.getTime()); cal.add(Calendar.YEAR, FIVE); certGen.setNotAfter(cal.getTime()); certGen.setSubjectDN(dnName); certGen.setPublicKey(keyPair.getPublic()); certGen.setSignatureAlgorithm(keySigningAlgorithm); return certGen.generate(keyPair.getPrivate(), PROVIDER); }
/** * intermediate cert */ private X509Certificate createIntmedCert( PublicKey pubKey, PrivateKey caPrivKey, PublicKey caPubKey, ASN1EncodableVector policies, Hashtable policyMap) throws Exception { String issuer = "C=JP, O=policyMappingAdditionalTest, OU=trustAnchor"; String subject = "C=JP, O=policyMappingAdditionalTest, OU=intmedCA"; v3CertGen.reset(); v3CertGen.setSerialNumber(BigInteger.valueOf(20)); v3CertGen.setIssuerDN(new X509Principal(issuer)); v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30)); v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30))); v3CertGen.setSubjectDN(new X509Principal(subject)); v3CertGen.setPublicKey(pubKey); v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); v3CertGen.addExtension(X509Extensions.CertificatePolicies, true, new DERSequence(policies)); v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); v3CertGen.addExtension(X509Extensions.PolicyMappings, true, new PolicyMappings(policyMap)); X509Certificate cert = v3CertGen.generateX509Certificate(caPrivKey); return cert; }
/** * Creates a <code>BasicConstraints</code> object from given * extension. * * @param ext the extension. * @return the <code>BasicConstraints</code> object. * @exception IOException if something fails. */ public static BasicConstraints getBasicConstraints(X509Extension ext) throws IOException { DERObject obj = BouncyCastleUtil.getExtensionObject(ext); if (obj instanceof ASN1Sequence) { ASN1Sequence seq = (ASN1Sequence)obj; int size = seq.size(); if (size == 0) { return new BasicConstraints(false); } else if (size == 1) { DEREncodable value = seq.getObjectAt(0); if (value instanceof DERInteger) { int length = ((DERInteger)value).getValue().intValue(); return new BasicConstraints(false, length); } else if (value instanceof DERBoolean) { boolean ca = ((DERBoolean)value).isTrue(); return new BasicConstraints(ca); } } } return BasicConstraints.getInstance(obj); }
protected int getCAPathConstraint(TBSCertificateStructure crt) throws IOException { X509Extensions extensions = crt.getExtensions(); if (extensions == null) { return -1; } X509Extension ext = extensions.getExtension(X509Extensions.BasicConstraints); if (ext != null) { BasicConstraints basicExt = BouncyCastleUtil.getBasicConstraints(ext); if (basicExt.isCA()) { BigInteger pathLen = basicExt.getPathLenConstraint(); return (pathLen == null) ? Integer.MAX_VALUE : pathLen.intValue(); } else { return -1; } } return -1; }
protected void checkUnsupportedCriticalExtensions(TBSCertificateStructure crt, int certType, X509Certificate checkedProxy) throws ProxyPathValidatorException { logger.debug("enter: checkUnsupportedCriticalExtensions"); X509Extensions extensions = crt.getExtensions(); if (extensions != null) { Enumeration e = extensions.oids(); while (e.hasMoreElements()) { DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement(); X509Extension ext = extensions.getExtension(oid); if (ext.isCritical()) { if (oid.equals(X509Extensions.BasicConstraints) || oid.equals(X509Extensions.KeyUsage) || (oid.equals(ProxyCertInfo.OID) && CertUtil.isGsi4Proxy(certType)) || (oid.equals(ProxyCertInfo.OLD_OID) && CertUtil.isGsi3Proxy(certType))) { } else { throw new ProxyPathValidatorException(ProxyPathValidatorException.UNSUPPORTED_EXTENSION, checkedProxy, "Unsuppored critical exception : " + oid.getId()); } } } } logger.debug("exit: checkUnsupportedCriticalExtensions"); }
public static X509Certificate generateCACertificate(String provider, X509Name subject, Date start, Date expired, KeyPair pair, int numberOfCAs, String signartureAlgorthm) throws InvalidKeyException, NoSuchProviderException, SignatureException, IOException { // generate the certificate X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(subject); certGen.setNotBefore(start); certGen.setNotAfter(expired); certGen.setSubjectDN(subject); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm(signartureAlgorthm); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(numberOfCAs)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo((ASN1Sequence) new DERInputStream( new ByteArrayInputStream(pair.getPublic().getEncoded())).readObject()); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(spki)); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) new DERInputStream( new ByteArrayInputStream(pair.getPublic().getEncoded())).readObject()); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(apki)); return certGen.generateX509Certificate(pair.getPrivate(), provider); }
public static X509Certificate generateCACertificate(String provider, X509Name subject, Date start, Date expired, KeyPair pair, int numberOfCAs, String signatureAlgorthm) throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException, IOException { // generate the certificate X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(subject); certGen.setNotBefore(start); certGen.setNotAfter(expired); certGen.setSubjectDN(subject); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm(signatureAlgorthm); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(numberOfCAs)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pair.getPublic().getEncoded())).readObject()); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(spki)); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pair.getPublic().getEncoded())).readObject()); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(apki)); return certGen.generate(pair.getPrivate(), provider); }
protected static void prepareNextCertK( CertPath certPath, int index) throws CertPathValidatorException { List certs = certPath.getCertificates(); X509Certificate cert = (X509Certificate)certs.get(index); // // (k) // BasicConstraints bc = null; try { bc = BasicConstraints.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, RFC3280CertPathUtilities.BASIC_CONSTRAINTS)); } catch (Exception e) { throw new ExtCertPathValidatorException("Basic constraints extension cannot be decoded.", e, certPath, index); } if (bc != null) { if (!(bc.isCA())) { throw new CertPathValidatorException("Not a CA certificate"); } } else { throw new CertPathValidatorException("Intermediate certificate lacks BasicConstraints"); } }
protected static int prepareNextCertM( CertPath certPath, int index, int maxPathLength) throws CertPathValidatorException { List certs = certPath.getCertificates(); X509Certificate cert = (X509Certificate)certs.get(index); // // (m) // BasicConstraints bc = null; try { bc = BasicConstraints.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, RFC3280CertPathUtilities.BASIC_CONSTRAINTS)); } catch (Exception e) { throw new ExtCertPathValidatorException("Basic constraints extension cannot be decoded.", e, certPath, index); } if (bc != null) { BigInteger _pathLengthConstraint = bc.getPathLenConstraint(); if (_pathLengthConstraint != null) { int _plc = _pathLengthConstraint.intValue(); if (_plc < maxPathLength) { return _plc; } } } return maxPathLength; }
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; }
private X509CertificateObject generateCert(String keyName, KeyPair kp, boolean isCertAuthority, PublicKey signerPublicKey, PrivateKey signerPrivateKey) throws IOException, CertIOException, 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 cert = certGen.build( new JcaContentSignerBuilder(SIGNING_ALGORITHM).build(signerPrivateKey)); return new X509CertificateObject(cert.toASN1Structure()); }