Search in sources :

Example 1 with JcaPEMWriter

use of org.bouncycastle.openssl.jcajce.JcaPEMWriter 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 2 with JcaPEMWriter

use of org.bouncycastle.openssl.jcajce.JcaPEMWriter in project oxAuth by GluuFederation.

the class Certificate method toString.

@Override
public String toString() {
    try {
        StringWriter stringWriter = new StringWriter();
        JcaPEMWriter pemWriter = new JcaPEMWriter(stringWriter);
        try {
            pemWriter.writeObject(x509Certificate);
            pemWriter.flush();
            return stringWriter.toString();
        } finally {
            pemWriter.close();
        }
    } catch (IOException e) {
        return StringUtils.EMPTY_STRING;
    } catch (Exception e) {
        return StringUtils.EMPTY_STRING;
    }
}
Also used : StringWriter(java.io.StringWriter) IOException(java.io.IOException) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) IOException(java.io.IOException) JSONException(org.codehaus.jettison.json.JSONException)

Example 3 with JcaPEMWriter

use of org.bouncycastle.openssl.jcajce.JcaPEMWriter in project gerrit by GerritCodeReview.

the class ConvertKey method main.

public static void main(String[] args) throws GeneralSecurityException, JSchException, IOException {
    SimpleGeneratorHostKeyProvider p;
    if (args.length != 1) {
        System.err.println("Error: requires path to the SSH host key");
        return;
    } else {
        File file = new File(args[0]);
        if (!file.exists() || !file.isFile() || !file.canRead()) {
            System.err.println("Error: ssh key should exist and be readable");
            return;
        }
    }
    p = new SimpleGeneratorHostKeyProvider();
    // Gerrit's SSH "simple" keys are always RSA.
    p.setPath(args[0]);
    p.setAlgorithm("RSA");
    // forces the key to generate.
    Iterable<KeyPair> keys = p.loadKeys();
    for (KeyPair k : keys) {
        System.out.println("Public Key (" + k.getPublic().getAlgorithm() + "):");
        // From Gerrit's SshDaemon class; use JSch to get the public
        // key/type
        final Buffer buf = new Buffer();
        buf.putRawPublicKey(k.getPublic());
        final byte[] keyBin = buf.getCompactData();
        HostKey pub = new HostKey("localhost", keyBin);
        System.out.println(pub.getType() + " " + pub.getKey());
        System.out.println("Private Key:");
        // Use Bouncy Castle to write the private key back in PEM format
        // (PKCS#1)
        // http://stackoverflow.com/questions/25129822/export-rsa-public-key-to-pem-string-using-java
        StringWriter privout = new StringWriter();
        JcaPEMWriter privWriter = new JcaPEMWriter(privout);
        privWriter.writeObject(k.getPrivate());
        privWriter.close();
        System.out.println(privout);
    }
}
Also used : SimpleGeneratorHostKeyProvider(org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider) Buffer(org.apache.sshd.common.util.Buffer) KeyPair(java.security.KeyPair) HostKey(com.jcraft.jsch.HostKey) StringWriter(java.io.StringWriter) JcaPEMWriter(org.bouncycastle.openssl.jcajce.JcaPEMWriter) File(java.io.File)

Aggregations

JcaPEMWriter (org.bouncycastle.openssl.jcajce.JcaPEMWriter)3 File (java.io.File)2 StringWriter (java.io.StringWriter)2 KeyPair (java.security.KeyPair)2 HostKey (com.jcraft.jsch.HostKey)1 FileWriter (java.io.FileWriter)1 IOException (java.io.IOException)1 KeyStore (java.security.KeyStore)1 SecureRandom (java.security.SecureRandom)1 X509Certificate (java.security.cert.X509Certificate)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Date (java.util.Date)1 Buffer (org.apache.sshd.common.util.Buffer)1 SimpleGeneratorHostKeyProvider (org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider)1 X500Name (org.bouncycastle.asn1.x500.X500Name)1 BasicConstraints (org.bouncycastle.asn1.x509.BasicConstraints)1 GeneralName (org.bouncycastle.asn1.x509.GeneralName)1 GeneralNames (org.bouncycastle.asn1.x509.GeneralNames)1 KeyUsage (org.bouncycastle.asn1.x509.KeyUsage)1 X509v3CertificateBuilder (org.bouncycastle.cert.X509v3CertificateBuilder)1