Search in sources :

Example 16 with GeneralNames

use of org.gudy.bouncycastle.asn1.x509.GeneralNames in project robovm by robovm.

the class AttributeCertificateIssuer method match.

public boolean match(Certificate cert) {
    if (!(cert instanceof X509Certificate)) {
        return false;
    }
    X509Certificate x509Cert = (X509Certificate) cert;
    if (form instanceof V2Form) {
        V2Form issuer = (V2Form) form;
        if (issuer.getBaseCertificateID() != null) {
            return issuer.getBaseCertificateID().getSerial().getValue().equals(x509Cert.getSerialNumber()) && matchesDN(x509Cert.getIssuerX500Principal(), issuer.getBaseCertificateID().getIssuer());
        }
        GeneralNames name = issuer.getIssuerName();
        if (matchesDN(x509Cert.getSubjectX500Principal(), name)) {
            return true;
        }
    } else {
        GeneralNames name = (GeneralNames) form;
        if (matchesDN(x509Cert.getSubjectX500Principal(), name)) {
            return true;
        }
    }
    return false;
}
Also used : V2Form(org.bouncycastle.asn1.x509.V2Form) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X509Certificate(java.security.cert.X509Certificate)

Example 17 with GeneralNames

use of org.gudy.bouncycastle.asn1.x509.GeneralNames in project robovm by robovm.

the class AttributeCertificateIssuer method getNames.

private Object[] getNames() {
    GeneralNames name;
    if (form instanceof V2Form) {
        name = ((V2Form) form).getIssuerName();
    } else {
        name = (GeneralNames) form;
    }
    GeneralName[] names = name.getNames();
    List l = new ArrayList(names.length);
    for (int i = 0; i != names.length; i++) {
        if (names[i].getTagNo() == GeneralName.directoryName) {
            try {
                l.add(new X500Principal(((ASN1Encodable) names[i].getName()).toASN1Primitive().getEncoded()));
            } catch (IOException e) {
                throw new RuntimeException("badly formed Name object");
            }
        }
    }
    return l.toArray(new Object[l.size()]);
}
Also used : V2Form(org.bouncycastle.asn1.x509.V2Form) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) ArrayList(java.util.ArrayList) X500Principal(javax.security.auth.x500.X500Principal) ArrayList(java.util.ArrayList) List(java.util.List) GeneralName(org.bouncycastle.asn1.x509.GeneralName) IOException(java.io.IOException)

Example 18 with GeneralNames

use of org.gudy.bouncycastle.asn1.x509.GeneralNames in project robovm by robovm.

the class TestKeyStore method createCertificate.

private static X509Certificate createCertificate(PublicKey publicKey, PrivateKey privateKey, X500Principal subject, X500Principal issuer, int keyUsage, boolean ca, List<KeyPurposeId> extendedKeyUsages, List<Boolean> criticalExtendedKeyUsages, List<GeneralName> subjectAltNames, List<GeneralSubtree> permittedNameConstraints, List<GeneralSubtree> excludedNameConstraints) throws Exception {
    // Note that there is no way to programmatically make a
    // Certificate using java.* or javax.* APIs. The
    // CertificateFactory interface assumes you want to read
    // in a stream of bytes, typically the X.509 factory would
    // allow ASN.1 DER encoded bytes and optionally some PEM
    // formats. Here we use Bouncy Castle's
    // X509V3CertificateGenerator and related classes.
    long millisPerDay = 24 * 60 * 60 * 1000;
    long now = System.currentTimeMillis();
    Date start = new Date(now - millisPerDay);
    Date end = new Date(now + millisPerDay);
    BigInteger serial = BigInteger.valueOf(1);
    String keyAlgorithm = privateKey.getAlgorithm();
    String signatureAlgorithm;
    if (keyAlgorithm.equals("RSA")) {
        signatureAlgorithm = "sha1WithRSA";
    } else if (keyAlgorithm.equals("DSA")) {
        signatureAlgorithm = "sha1WithDSA";
    } else if (keyAlgorithm.equals("EC")) {
        signatureAlgorithm = "sha1WithECDSA";
    } else if (keyAlgorithm.equals("EC_RSA")) {
        signatureAlgorithm = "sha1WithRSA";
    } else {
        throw new IllegalArgumentException("Unknown key algorithm " + keyAlgorithm);
    }
    X509V3CertificateGenerator x509cg = new X509V3CertificateGenerator();
    x509cg.setSubjectDN(subject);
    x509cg.setIssuerDN(issuer);
    x509cg.setNotBefore(start);
    x509cg.setNotAfter(end);
    x509cg.setPublicKey(publicKey);
    x509cg.setSignatureAlgorithm(signatureAlgorithm);
    x509cg.setSerialNumber(serial);
    if (keyUsage != 0) {
        x509cg.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(keyUsage));
    }
    if (ca) {
        x509cg.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    }
    for (int i = 0; i < extendedKeyUsages.size(); i++) {
        KeyPurposeId keyPurposeId = extendedKeyUsages.get(i);
        boolean critical = criticalExtendedKeyUsages.get(i);
        x509cg.addExtension(X509Extensions.ExtendedKeyUsage, critical, new ExtendedKeyUsage(keyPurposeId));
    }
    for (GeneralName subjectAltName : subjectAltNames) {
        x509cg.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(subjectAltName).getEncoded());
    }
    if (!permittedNameConstraints.isEmpty() || !excludedNameConstraints.isEmpty()) {
        x509cg.addExtension(X509Extensions.NameConstraints, true, new NameConstraints(permittedNameConstraints.toArray(new GeneralSubtree[permittedNameConstraints.size()]), excludedNameConstraints.toArray(new GeneralSubtree[excludedNameConstraints.size()])));
    }
    if (privateKey instanceof ECPrivateKey) {
        /*
             * bouncycastle needs its own ECPrivateKey implementation
             */
        KeyFactory kf = KeyFactory.getInstance(keyAlgorithm, "BC");
        PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(privateKey.getEncoded());
        privateKey = kf.generatePrivate(ks);
    }
    X509Certificate x509c = x509cg.generateX509Certificate(privateKey);
    if (StandardNames.IS_RI) {
        /*
             * The RI can't handle the BC EC signature algorithm
             * string of "ECDSA", since it expects "...WITHEC...",
             * so convert from BC to RI X509Certificate
             * implementation via bytes.
             */
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream bais = new ByteArrayInputStream(x509c.getEncoded());
        Certificate c = cf.generateCertificate(bais);
        x509c = (X509Certificate) c;
    }
    return x509c;
}
Also used : ECPrivateKey(java.security.interfaces.ECPrivateKey) NameConstraints(com.android.org.bouncycastle.asn1.x509.NameConstraints) KeyPurposeId(com.android.org.bouncycastle.asn1.x509.KeyPurposeId) ExtendedKeyUsage(com.android.org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyUsage(com.android.org.bouncycastle.asn1.x509.KeyUsage) DEROctetString(com.android.org.bouncycastle.asn1.DEROctetString) CertificateFactory(java.security.cert.CertificateFactory) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) X509V3CertificateGenerator(com.android.org.bouncycastle.x509.X509V3CertificateGenerator) GeneralNames(com.android.org.bouncycastle.asn1.x509.GeneralNames) ByteArrayInputStream(java.io.ByteArrayInputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) BigInteger(java.math.BigInteger) GeneralName(com.android.org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(com.android.org.bouncycastle.asn1.x509.BasicConstraints) ExtendedKeyUsage(com.android.org.bouncycastle.asn1.x509.ExtendedKeyUsage) KeyFactory(java.security.KeyFactory) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 19 with GeneralNames

use of org.gudy.bouncycastle.asn1.x509.GeneralNames in project gitblit by gitblit.

the class X509Utils method newClientCertificate.

/**
	 * Creates a new client certificate PKCS#12 and PEM store.  Any existing
	 * stores are destroyed.
	 *
	 * @param clientMetadata a container for dynamic parameters needed for generation
	 * @param caKeystoreFile
	 * @param caKeystorePassword
	 * @param targetFolder
	 * @return
	 */
public static X509Certificate newClientCertificate(X509Metadata clientMetadata, PrivateKey caPrivateKey, X509Certificate caCert, File targetFolder) {
    try {
        KeyPair pair = newKeyPair();
        X500Name userDN = buildDistinguishedName(clientMetadata);
        X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());
        // create a new certificate signed by the Gitblit CA certificate
        X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuerDN, BigInteger.valueOf(System.currentTimeMillis()), clientMetadata.notBefore, clientMetadata.notAfter, userDN, pair.getPublic());
        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(pair.getPublic()));
        certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false));
        certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()));
        certBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature));
        if (!StringUtils.isEmpty(clientMetadata.emailAddress)) {
            GeneralNames subjectAltName = new GeneralNames(new GeneralName(GeneralName.rfc822Name, clientMetadata.emailAddress));
            certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
        }
        ContentSigner signer = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPrivateKey);
        X509Certificate userCert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certBuilder.build(signer));
        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) pair.getPrivate();
        bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId, extUtils.createSubjectKeyIdentifier(pair.getPublic()));
        // confirm the validity of the user certificate
        userCert.checkValidity();
        userCert.verify(caCert.getPublicKey());
        userCert.getIssuerDN().equals(caCert.getSubjectDN());
        // verify user certificate chain
        verifyChain(userCert, caCert);
        targetFolder.mkdirs();
        // save certificate, stamped with unique name
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String id = date;
        File certFile = new File(targetFolder, id + ".cer");
        int count = 0;
        while (certFile.exists()) {
            id = date + "_" + Character.toString((char) (0x61 + count));
            certFile = new File(targetFolder, id + ".cer");
            count++;
        }
        // save user private key, user certificate and CA certificate to a PKCS#12 store
        File p12File = new File(targetFolder, clientMetadata.commonName + ".p12");
        if (p12File.exists()) {
            p12File.delete();
        }
        KeyStore userStore = openKeyStore(p12File, clientMetadata.password);
        userStore.setKeyEntry(MessageFormat.format("Gitblit ({0}) {1} {2}", clientMetadata.serverHostname, clientMetadata.userDisplayname, id), pair.getPrivate(), null, new Certificate[] { userCert });
        userStore.setCertificateEntry(MessageFormat.format("Gitblit ({0}) Certificate Authority", clientMetadata.serverHostname), caCert);
        saveKeyStore(p12File, userStore, clientMetadata.password);
        // save user private key, user certificate, and CA certificate to a PEM store
        File pemFile = new File(targetFolder, clientMetadata.commonName + ".pem");
        if (pemFile.exists()) {
            pemFile.delete();
        }
        JcePEMEncryptorBuilder builder = new JcePEMEncryptorBuilder("DES-EDE3-CBC");
        builder.setSecureRandom(new SecureRandom());
        PEMEncryptor pemEncryptor = builder.build(clientMetadata.password.toCharArray());
        JcaPEMWriter pemWriter = new JcaPEMWriter(new FileWriter(pemFile));
        pemWriter.writeObject(pair.getPrivate(), pemEncryptor);
        pemWriter.writeObject(userCert);
        pemWriter.writeObject(caCert);
        pemWriter.flush();
        pemWriter.close();
        // save certificate after successfully creating the key stores
        saveCertificate(userCert, certFile);
        // update serial number in metadata object
        clientMetadata.serialNumber = userCert.getSerialNumber().toString();
        return userCert;
    } catch (Throwable t) {
        throw new RuntimeException("Failed to generate client certificate!", t);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) FileWriter(java.io.FileWriter) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) PKCS12BagAttributeCarrier(org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier) PEMEncryptor(org.bouncycastle.openssl.PEMEncryptor) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) JcePEMEncryptorBuilder(org.bouncycastle.openssl.jcajce.JcePEMEncryptorBuilder) KeyPair(java.security.KeyPair) ContentSigner(org.bouncycastle.operator.ContentSigner) SecureRandom(java.security.SecureRandom) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) SimpleDateFormat(java.text.SimpleDateFormat) File(java.io.File)

Example 20 with GeneralNames

use of org.gudy.bouncycastle.asn1.x509.GeneralNames in project gitblit by gitblit.

the class X509Utils method newSSLCertificate.

/**
	 * Creates a new SSL certificate signed by the CA private key and stored in
	 * keyStore.
	 *
	 * @param sslMetadata
	 * @param caPrivateKey
	 * @param caCert
	 * @param targetStoreFile
	 * @param x509log
	 */
public static X509Certificate newSSLCertificate(X509Metadata sslMetadata, PrivateKey caPrivateKey, X509Certificate caCert, File targetStoreFile, X509Log x509log) {
    try {
        KeyPair pair = newKeyPair();
        X500Name webDN = buildDistinguishedName(sslMetadata);
        X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(caCert).getName());
        X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuerDN, BigInteger.valueOf(System.currentTimeMillis()), sslMetadata.notBefore, sslMetadata.notAfter, webDN, pair.getPublic());
        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        certBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(pair.getPublic()));
        certBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false));
        certBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()));
        // support alternateSubjectNames for SSL certificates
        List<GeneralName> altNames = new ArrayList<GeneralName>();
        if (HttpUtils.isIpAddress(sslMetadata.commonName)) {
            altNames.add(new GeneralName(GeneralName.iPAddress, sslMetadata.commonName));
        }
        if (altNames.size() > 0) {
            GeneralNames subjectAltName = new GeneralNames(altNames.toArray(new GeneralName[altNames.size()]));
            certBuilder.addExtension(X509Extension.subjectAlternativeName, false, subjectAltName);
        }
        ContentSigner caSigner = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPrivateKey);
        X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC).getCertificate(certBuilder.build(caSigner));
        cert.checkValidity(new Date());
        cert.verify(caCert.getPublicKey());
        // Save to keystore
        KeyStore serverStore = openKeyStore(targetStoreFile, sslMetadata.password);
        serverStore.setKeyEntry(sslMetadata.commonName, pair.getPrivate(), sslMetadata.password.toCharArray(), new Certificate[] { cert, caCert });
        saveKeyStore(targetStoreFile, serverStore, sslMetadata.password);
        x509log.log(MessageFormat.format("New SSL certificate {0,number,0} [{1}]", cert.getSerialNumber(), cert.getSubjectDN().getName()));
        // update serial number in metadata object
        sslMetadata.serialNumber = cert.getSerialNumber().toString();
        return cert;
    } catch (Throwable t) {
        throw new RuntimeException("Failed to generate SSL certificate!", t);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) KeyPair(java.security.KeyPair) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ArrayList(java.util.ArrayList) ContentSigner(org.bouncycastle.operator.ContentSigner) X500Name(org.bouncycastle.asn1.x500.X500Name) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints)

Aggregations

GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)72 GeneralName (org.bouncycastle.asn1.x509.GeneralName)61 IOException (java.io.IOException)31 X509Certificate (java.security.cert.X509Certificate)22 ArrayList (java.util.ArrayList)19 X500Name (org.bouncycastle.asn1.x500.X500Name)19 DERIA5String (org.bouncycastle.asn1.DERIA5String)15 DEROctetString (org.bouncycastle.asn1.DEROctetString)14 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)14 DistributionPoint (org.bouncycastle.asn1.x509.DistributionPoint)14 Date (java.util.Date)13 List (java.util.List)13 X500Principal (javax.security.auth.x500.X500Principal)12 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)12 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)12 GeneralNames (sun.security.x509.GeneralNames)12 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)11 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)11 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)11 Test (org.junit.Test)11