Search in sources :

Example 26 with X500NameBuilder

use of org.bouncycastle.asn1.x500.X500NameBuilder in project Openfire by igniterealtime.

the class CertificateManager method createX509V3Certificate.

public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, X500NameBuilder issuerBuilder, X500NameBuilder subjectBuilder, String domain, String signAlgoritm, Set<String> sanDnsNames) throws GeneralSecurityException, IOException {
    PublicKey pubKey = kp.getPublic();
    PrivateKey privKey = kp.getPrivate();
    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed((new Date().getTime()));
    random.nextBytes(serno);
    BigInteger serial = (new java.math.BigInteger(serno)).abs();
    X500Name issuerDN = issuerBuilder.build();
    X500Name subjectDN = subjectBuilder.build();
    // builder
    JcaX509v3CertificateBuilder certBuilder = new // 
    JcaX509v3CertificateBuilder(// 
    issuerDN, // 
    serial, // 
    new Date(), // 
    new Date(System.currentTimeMillis() + days * (1000L * 60 * 60 * 24)), // 
    subjectDN, // 
    pubKey);
    // add subjectAlternativeName extension that includes all relevant names.
    final GeneralNames subjectAlternativeNames = getSubjectAlternativeNames(sanDnsNames);
    final boolean critical = subjectDN.getRDNs().length == 0;
    certBuilder.addExtension(Extension.subjectAlternativeName, critical, subjectAlternativeNames);
    // add keyIdentifiers extensions
    JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();
    certBuilder.addExtension(Extension.subjectKeyIdentifier, false, utils.createSubjectKeyIdentifier(pubKey));
    certBuilder.addExtension(Extension.authorityKeyIdentifier, false, utils.createAuthorityKeyIdentifier(pubKey));
    try {
        // build the certificate
        ContentSigner signer = new JcaContentSignerBuilder(signAlgoritm).build(privKey);
        X509CertificateHolder cert = certBuilder.build(signer);
        // verify the validity
        if (!cert.isValidOn(new Date())) {
            throw new GeneralSecurityException("Certificate validity not valid");
        }
        // verify the signature (self-signed)
        ContentVerifierProvider verifierProvider = new JcaContentVerifierProviderBuilder().build(pubKey);
        if (!cert.isSignatureValid(verifierProvider)) {
            throw new GeneralSecurityException("Certificate signature not valid");
        }
        return new JcaX509CertificateConverter().getCertificate(cert);
    } catch (OperatorCreationException | CertException e) {
        throw new GeneralSecurityException(e);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) CertException(org.bouncycastle.cert.CertException) X500Name(org.bouncycastle.asn1.x500.X500Name) JcaContentVerifierProviderBuilder(org.bouncycastle.operator.jcajce.JcaContentVerifierProviderBuilder) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BigInteger(java.math.BigInteger) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ContentVerifierProvider(org.bouncycastle.operator.ContentVerifierProvider)

Example 27 with X500NameBuilder

use of org.bouncycastle.asn1.x500.X500NameBuilder 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;
}
Also used : RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) CertificateException(java.security.cert.CertificateException) GeneralName(org.bouncycastle.asn1.x509.GeneralName) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyPair(java.security.KeyPair) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) PublicKey(java.security.PublicKey) ContentSigner(org.bouncycastle.operator.ContentSigner) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) KeyStore(java.security.KeyStore) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 28 with X500NameBuilder

use of org.bouncycastle.asn1.x500.X500NameBuilder 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;
}
Also used : KeyPair(java.security.KeyPair) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) PublicKey(java.security.PublicKey) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) KeyPairGenerator(java.security.KeyPairGenerator) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) KeyStore(java.security.KeyStore) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Random(java.util.Random) SecureRandom(java.security.SecureRandom) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 29 with X500NameBuilder

use of org.bouncycastle.asn1.x500.X500NameBuilder in project gitblit by gitblit.

the class X509Utils method buildDistinguishedName.

/**
 * Builds a distinguished name from the X509Metadata.
 *
 * @return a DN
 */
private static X500Name buildDistinguishedName(X509Metadata metadata) {
    X500NameBuilder dnBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    setOID(dnBuilder, metadata, "C", null);
    setOID(dnBuilder, metadata, "ST", null);
    setOID(dnBuilder, metadata, "L", null);
    setOID(dnBuilder, metadata, "O", Constants.NAME);
    setOID(dnBuilder, metadata, "OU", Constants.NAME);
    setOID(dnBuilder, metadata, "E", metadata.emailAddress);
    setOID(dnBuilder, metadata, "CN", metadata.commonName);
    X500Name dn = dnBuilder.build();
    return dn;
}
Also used : X500NameBuilder(org.bouncycastle.asn1.x500.X500NameBuilder) X500Name(org.bouncycastle.asn1.x500.X500Name)

Example 30 with X500NameBuilder

use of org.bouncycastle.asn1.x500.X500NameBuilder in project gitblit by gitblit.

the class X509Utils method setOID.

private static void setOID(X500NameBuilder dnBuilder, X509Metadata metadata, String oid, String defaultValue) {
    String value = null;
    if (metadata.oids != null && metadata.oids.containsKey(oid)) {
        value = metadata.oids.get(oid);
    }
    if (StringUtils.isEmpty(value)) {
        value = defaultValue;
    }
    if (!StringUtils.isEmpty(value)) {
        try {
            Field field = BCStyle.class.getField(oid);
            ASN1ObjectIdentifier objectId = (ASN1ObjectIdentifier) field.get(null);
            dnBuilder.addRDN(objectId, value);
        } catch (Exception e) {
            logger.error(MessageFormat.format("Failed to set OID \"{0}\"!", oid), e);
        }
    }
}
Also used : Field(java.lang.reflect.Field) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) SignatureException(java.security.SignatureException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CertificateEncodingException(java.security.cert.CertificateEncodingException) CertPathBuilderException(java.security.cert.CertPathBuilderException) IOException(java.io.IOException)

Aggregations

X500NameBuilder (org.bouncycastle.asn1.x500.X500NameBuilder)28 X509Certificate (java.security.cert.X509Certificate)18 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)18 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)18 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)18 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)17 ContentSigner (org.bouncycastle.operator.ContentSigner)17 BigInteger (java.math.BigInteger)16 KeyPair (java.security.KeyPair)15 Date (java.util.Date)15 X500Name (org.bouncycastle.asn1.x500.X500Name)13 KeyStore (java.security.KeyStore)11 SecureRandom (java.security.SecureRandom)10 KeyPairGenerator (java.security.KeyPairGenerator)9 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)8 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)7 PrivateKey (java.security.PrivateKey)6 PublicKey (java.security.PublicKey)6 CertificateException (java.security.cert.CertificateException)6 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)6