Search in sources :

Example 21 with X500Name

use of org.bouncycastle.asn1.x500.X500Name 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 22 with X500Name

use of org.bouncycastle.asn1.x500.X500Name 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)

Example 23 with X500Name

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

the class X509Utils method newCertificateAuthority.

/**
	 * Creates a new certificate authority PKCS#12 store.  This function will
	 * destroy any existing CA store.
	 *
	 * @param metadata
	 * @param storeFile
	 * @param keystorePassword
	 * @param x509log
	 * @return
	 */
public static X509Certificate newCertificateAuthority(X509Metadata metadata, File storeFile, X509Log x509log) {
    try {
        KeyPair caPair = newKeyPair();
        ContentSigner caSigner = new JcaContentSignerBuilder(SIGNING_ALGORITHM).setProvider(BC).build(caPair.getPrivate());
        // clone metadata
        X509Metadata caMetadata = metadata.clone(CA_CN, metadata.password);
        X500Name issuerDN = buildDistinguishedName(caMetadata);
        // Generate self-signed certificate
        X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder(issuerDN, BigInteger.valueOf(System.currentTimeMillis()), caMetadata.notBefore, caMetadata.notAfter, issuerDN, caPair.getPublic());
        JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        caBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(caPair.getPublic()));
        caBuilder.addExtension(X509Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caPair.getPublic()));
        caBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(true));
        caBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
        JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BC);
        X509Certificate cert = converter.getCertificate(caBuilder.build(caSigner));
        // confirm the validity of the CA certificate
        cert.checkValidity(new Date());
        cert.verify(cert.getPublicKey());
        // Delete existing keystore
        if (storeFile.exists()) {
            storeFile.delete();
        }
        // Save private key and certificate to new keystore
        KeyStore store = openKeyStore(storeFile, caMetadata.password);
        store.setKeyEntry(CA_ALIAS, caPair.getPrivate(), caMetadata.password.toCharArray(), new Certificate[] { cert });
        saveKeyStore(storeFile, store, caMetadata.password);
        x509log.log(MessageFormat.format("New CA certificate {0,number,0} [{1}]", cert.getSerialNumber(), cert.getIssuerDN().getName()));
        // update serial number in metadata object
        caMetadata.serialNumber = cert.getSerialNumber().toString();
        return cert;
    } catch (Throwable t) {
        throw new RuntimeException("Failed to generate Gitblit CA certificate!", t);
    }
}
Also used : JcaX509ExtensionUtils(org.bouncycastle.cert.jcajce.JcaX509ExtensionUtils) KeyPair(java.security.KeyPair) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) X500Name(org.bouncycastle.asn1.x500.X500Name) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) 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)

Example 24 with X500Name

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

the class X509Utils method revoke.

/**
	 * Revoke a certificate.
	 *
	 * @param cert
	 * @param reason
	 * @param caRevocationList
	 * @param caPrivateKey
	 * @param x509log
	 * @return true if the certificate has been revoked
	 */
public static boolean revoke(X509Certificate cert, RevocationReason reason, File caRevocationList, PrivateKey caPrivateKey, X509Log x509log) {
    try {
        X500Name issuerDN = new X500Name(PrincipalUtil.getIssuerX509Principal(cert).getName());
        X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuerDN, new Date());
        if (caRevocationList.exists()) {
            byte[] data = FileUtils.readContent(caRevocationList);
            X509CRLHolder crl = new X509CRLHolder(data);
            crlBuilder.addCRL(crl);
        }
        crlBuilder.addCRLEntry(cert.getSerialNumber(), new Date(), reason.ordinal());
        // build and sign CRL with CA private key
        ContentSigner signer = new JcaContentSignerBuilder("SHA1WithRSA").setProvider(BC).build(caPrivateKey);
        X509CRLHolder crl = crlBuilder.build(signer);
        File tmpFile = new File(caRevocationList.getParentFile(), Long.toHexString(System.currentTimeMillis()) + ".tmp");
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(tmpFile);
            fos.write(crl.getEncoded());
            fos.flush();
            fos.close();
            if (caRevocationList.exists()) {
                caRevocationList.delete();
            }
            tmpFile.renameTo(caRevocationList);
        } finally {
            if (fos != null) {
                fos.close();
            }
            if (tmpFile.exists()) {
                tmpFile.delete();
            }
        }
        x509log.log(MessageFormat.format("Revoked certificate {0,number,0} reason: {1} [{2}]", cert.getSerialNumber(), reason.toString(), cert.getSubjectDN().getName()));
        return true;
    } catch (IOException | OperatorCreationException | CertificateEncodingException e) {
        logger.error(MessageFormat.format("Failed to revoke certificate {0,number,0} [{1}] in {2}", cert.getSerialNumber(), cert.getSubjectDN().getName(), caRevocationList));
    }
    return false;
}
Also used : JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) CertificateEncodingException(java.security.cert.CertificateEncodingException) X500Name(org.bouncycastle.asn1.x500.X500Name) IOException(java.io.IOException) Date(java.util.Date) FileOutputStream(java.io.FileOutputStream) X509CRLHolder(org.bouncycastle.cert.X509CRLHolder) X509v2CRLBuilder(org.bouncycastle.cert.X509v2CRLBuilder) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) File(java.io.File)

Example 25 with X500Name

use of org.bouncycastle.asn1.x500.X500Name in project j2objc by google.

the class PKCS7 method populateCertIssuerNames.

/**
     * Populate array of Issuer DNs from certificates and convert
     * each Principal to type X500Name if necessary.
     */
private void populateCertIssuerNames() {
    if (certificates == null)
        return;
    certIssuerNames = new Principal[certificates.length];
    for (int i = 0; i < certificates.length; i++) {
        X509Certificate cert = certificates[i];
        Principal certIssuerName = cert.getIssuerDN();
        if (!(certIssuerName instanceof X500Name)) {
            // types of String attribute values to be changed)
            try {
                X509CertInfo tbsCert = new X509CertInfo(cert.getTBSCertificate());
                certIssuerName = (Principal) tbsCert.get(CertificateIssuerName.NAME + "." + CertificateIssuerName.DN_NAME);
            } catch (Exception e) {
            // error generating X500Name object from the cert's
            // issuer DN, leave name as is.
            }
        }
        certIssuerNames[i] = certIssuerName;
    }
}
Also used : X509CertInfo(sun.security.x509.X509CertInfo) X500Name(sun.security.x509.X500Name) X509Certificate(java.security.cert.X509Certificate) X500Principal(javax.security.auth.x500.X500Principal) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateParsingException(java.security.cert.CertificateParsingException) CertificateException(java.security.cert.CertificateException) CertificateExpiredException(java.security.cert.CertificateExpiredException) CRLException(java.security.cert.CRLException) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Aggregations

X500Name (org.bouncycastle.asn1.x500.X500Name)54 X509Certificate (java.security.cert.X509Certificate)39 X500Name (sun.security.x509.X500Name)30 IOException (java.io.IOException)23 Date (java.util.Date)22 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)20 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)19 BigInteger (java.math.BigInteger)18 SecureRandom (java.security.SecureRandom)16 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)16 JcaX509v3CertificateBuilder (org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder)15 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)15 KeyPair (java.security.KeyPair)12 PrivateKey (java.security.PrivateKey)12 CertificateEncodingException (java.security.cert.CertificateEncodingException)12 RDN (org.bouncycastle.asn1.x500.RDN)12 ContentSigner (org.bouncycastle.operator.ContentSigner)12 KeyStore (java.security.KeyStore)11 ArrayList (java.util.ArrayList)10 GeneralName (org.bouncycastle.asn1.x509.GeneralName)10