use of com.android.org.bouncycastle.asn1.x509.BasicConstraints in project cloudstack by apache.
the class CertUtils method generateV3Certificate.
public static X509Certificate generateV3Certificate(final X509Certificate caCert, final KeyPair caKeyPair, final PublicKey clientPublicKey, final String subject, final String signatureAlgorithm, final int validityDays, final List<String> dnsNames, final List<String> publicIPAddresses) throws IOException, NoSuchAlgorithmException, CertificateException, NoSuchProviderException, InvalidKeyException, SignatureException, OperatorCreationException {
final DateTime now = DateTime.now(DateTimeZone.UTC);
final BigInteger serial = generateRandomBigInt();
final JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
final X509v3CertificateBuilder certBuilder;
if (caCert == null) {
// Generate CA certificate
certBuilder = new JcaX509v3CertificateBuilder(new X500Name(subject), serial, now.minusHours(12).toDate(), now.plusDays(validityDays).toDate(), new X500Name(subject), clientPublicKey);
certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign));
} else {
// Generate client certificate
certBuilder = new JcaX509v3CertificateBuilder(caCert, serial, now.minusHours(12).toDate(), now.plusDays(validityDays).toDate(), new X500Principal(subject), clientPublicKey);
certBuilder.addExtension(Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert));
}
certBuilder.addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(clientPublicKey));
final List<ASN1Encodable> subjectAlternativeNames = new ArrayList<ASN1Encodable>();
if (publicIPAddresses != null) {
for (final String publicIPAddress : new HashSet<>(publicIPAddresses)) {
if (StringUtils.isEmpty(publicIPAddress)) {
continue;
}
subjectAlternativeNames.add(new GeneralName(GeneralName.iPAddress, publicIPAddress));
}
}
if (dnsNames != null) {
for (final String dnsName : new HashSet<>(dnsNames)) {
if (StringUtils.isEmpty(dnsName)) {
continue;
}
subjectAlternativeNames.add(new GeneralName(GeneralName.dNSName, dnsName));
}
}
if (subjectAlternativeNames.size() > 0) {
final GeneralNames subjectAltNames = GeneralNames.getInstance(new DERSequence(subjectAlternativeNames.toArray(new ASN1Encodable[] {})));
certBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
}
final ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).setProvider("BC").build(caKeyPair.getPrivate());
final X509CertificateHolder certHolder = certBuilder.build(signer);
final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);
if (caCert != null) {
cert.verify(caCert.getPublicKey());
} else {
cert.verify(caKeyPair.getPublic());
}
return cert;
}
use of com.android.org.bouncycastle.asn1.x509.BasicConstraints in project Openfire by igniterealtime.
the class KeystoreTestUtils method generateTestCertificate.
private static X509Certificate generateTestCertificate(final boolean isValid, final KeyPair issuerKeyPair, final KeyPair subjectKeyPair, int indexAwayFromEndEntity) throws Exception {
// Issuer and Subject.
final X500Name subject = new X500Name("CN=" + Base64.encodeBytes(subjectKeyPair.getPublic().getEncoded(), Base64.URL_SAFE));
final X500Name issuer = new X500Name("CN=" + Base64.encodeBytes(issuerKeyPair.getPublic().getEncoded(), Base64.URL_SAFE));
// Validity
final Date notBefore;
final Date notAfter;
if (isValid) {
// 30 days ago
notBefore = new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 30));
// 99 days from now.
notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 99));
} else {
// Generate a certificate for which the validate period has expired.
// 40 days ago
notBefore = new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 40));
// 10 days ago
notAfter = new Date(System.currentTimeMillis() - (1000L * 60 * 60 * 24 * 10));
}
// The new certificate should get a unique serial number.
final BigInteger serial = BigInteger.valueOf(Math.abs(new SecureRandom().nextInt()));
final X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, subjectKeyPair.getPublic());
// When this certificate is used to sign another certificate, basic constraints need to be set.
if (indexAwayFromEndEntity > 0) {
builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(indexAwayFromEndEntity - 1));
}
final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA1withRSA").build(issuerKeyPair.getPrivate());
final X509CertificateHolder certificateHolder = builder.build(contentSigner);
return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
}
use of com.android.org.bouncycastle.asn1.x509.BasicConstraints in project zaproxy by zaproxy.
the class SslCertificateServiceImpl method createCertForHost.
@Override
public KeyStore createCertForHost(CertData certData) throws NoSuchAlgorithmException, InvalidKeyException, CertificateException, NoSuchProviderException, SignatureException, KeyStoreException, IOException, UnrecoverableKeyException {
if (this.caCert == null || this.caPrivKey == null || this.caPubKey == null) {
throw new MissingRootCertificateException(this.getClass() + " wasn't initialized! Got to options 'Dynamic SSL Certs' and create one.");
}
CertData.Name[] certDataNames = certData.getSubjectAlternativeNames();
GeneralName[] subjectAlternativeNames = new GeneralName[certDataNames.length];
for (int i = 0; i < certDataNames.length; i++) {
CertData.Name certDataName = certDataNames[i];
subjectAlternativeNames[i] = new GeneralName(certDataName.getType(), certDataName.getValue());
}
if (certData.getCommonName() == null && subjectAlternativeNames.length == 0) {
throw new IllegalArgumentException("commonName is null and no subjectAlternativeNames are specified");
}
final KeyPair mykp = this.createKeyPair();
final PrivateKey privKey = mykp.getPrivate();
final PublicKey pubKey = mykp.getPublic();
X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
if (certData.getCommonName() != null) {
namebld.addRDN(BCStyle.CN, certData.getCommonName());
}
namebld.addRDN(BCStyle.OU, "Zed Attack Proxy Project");
namebld.addRDN(BCStyle.O, "OWASP");
namebld.addRDN(BCStyle.C, "xx");
namebld.addRDN(BCStyle.EmailAddress, "zaproxy-develop@googlegroups.com");
long currentTime = System.currentTimeMillis();
X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(new X509CertificateHolder(caCert.getEncoded()).getSubject(), BigInteger.valueOf(serial.getAndIncrement()), new Date(currentTime - Duration.ofDays(SITE_CERTIFICATE_START_ADJUSTMENT).toMillis()), new Date(currentTime + Duration.ofDays(SITE_CERTIFICATE_END_VALIDITY_PERIOD).toMillis()), namebld.build(), pubKey);
certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded()));
certGen.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));
certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_serverAuth }));
if (subjectAlternativeNames.length > 0) {
certGen.addExtension(Extension.subjectAlternativeName, certData.isSubjectAlternativeNameIsCritical(), new GeneralNames(subjectAlternativeNames));
}
ContentSigner sigGen;
try {
sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(caPrivKey);
} catch (OperatorCreationException e) {
throw new CertificateException(e);
}
final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
cert.checkValidity(new Date());
cert.verify(caPubKey);
final KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
final Certificate[] chain = new Certificate[2];
chain[1] = this.caCert;
chain[0] = cert;
ks.setKeyEntry(ZAPROXY_JKS_ALIAS, privKey, PASSPHRASE, chain);
return ks;
}
use of com.android.org.bouncycastle.asn1.x509.BasicConstraints in project zaproxy by zaproxy.
the class SslCertificateUtils method createRootCA.
/**
* Creates a new Root CA certificate and returns private and public key as {@link KeyStore}. The
* {@link KeyStore#getDefaultType()} is used.
*
* @return
* @throws NoSuchAlgorithmException If no providers are found for 'RSA' key pair generator or
* 'SHA1PRNG' Secure random number generator
* @throws IllegalStateException in case of errors during assembling {@link KeyStore}
*/
public static final KeyStore createRootCA() throws NoSuchAlgorithmException {
final Date startDate = Calendar.getInstance().getTime();
final Date expireDate = new Date(startDate.getTime() + DEFAULT_VALIDITY_IN_MS);
final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA");
g.initialize(2048, SecureRandom.getInstance("SHA1PRNG"));
final KeyPair keypair = g.genKeyPair();
final PrivateKey privKey = keypair.getPrivate();
final PublicKey pubKey = keypair.getPublic();
Security.addProvider(new BouncyCastleProvider());
Random rnd = new Random();
// using the hash code of the user's name and home path, keeps anonymity
// but also gives user a chance to distinguish between each other
X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA");
namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode()) + Integer.toHexString(System.getProperty("user.home").hashCode()));
namebld.addRDN(BCStyle.O, "OWASP Root CA");
namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA");
namebld.addRDN(BCStyle.C, "xx");
X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(namebld.build(), BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey);
KeyStore ks = null;
try {
certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded()));
certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign));
KeyPurposeId[] eku = { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth, KeyPurposeId.anyExtendedKeyUsage };
certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku));
final ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(privKey);
final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen));
ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, null);
ks.setKeyEntry(org.parosproxy.paros.security.SslCertificateService.ZAPROXY_JKS_ALIAS, privKey, org.parosproxy.paros.security.SslCertificateService.PASSPHRASE, new Certificate[] { cert });
} catch (final Exception e) {
throw new IllegalStateException("Errors during assembling root CA.", e);
}
return ks;
}
Aggregations