使用现有的中间CA密钥和带有keytool的证书来生成客户端证书

时间:2017-10-20 19:35:44

标签: java ssl

我接管了一个现有项目,其中我有使用openssl创建的密钥/证书(根CA和中间CA)。我被告知尝试使用keytool为Java中的SSL客户端身份验证生成客户端证书。

我不是一个加密人,所以这一切都很新,但我在这个poc中使用了Bouncy Castle,正确生成客户端证书,客户端可以通过我们的服务进行身份验证并建立SSL连接。

public X509Certificate buildEndEntityCert(PublicKey entityKey, PrivateKey caKey, X509Certificate caCert, String clientName)
        throws Exception {
    String name = "CN=Test";
    X509v3CertificateBuilder certBldr = new JcaX509v3CertificateBuilder(
            caCert.getSubjectX500Principal(),
            BigInteger.ONE,
            new Date(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() + VALIDITY_PERIOD),
            new X500Principal(name),
            entityKey);

    JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();

    certBldr.addExtension(Extension.authorityKeyIdentifier, false, extUtils.createAuthorityKeyIdentifier(caCert))
            .addExtension(Extension.subjectKeyIdentifier, false, extUtils.createSubjectKeyIdentifier(entityKey))
            .addExtension(Extension.basicConstraints, false, new BasicConstraints(false))
            .addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation))
            .addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));

    ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(caKey);

    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certBldr.build(signer));
}

我在启动时使用middleCredential I加载caKey和caCert参数来调用此方法。有没有类似的方法我可以用keytool做到这一点?

如果没有一个命令或一组命令可以做到这一点,有没有一种方法可以做到这一点?与创建新的信任库一样,导入这些证书,然后从充当CA的信任库创建新证书?

1 个答案:

答案 0 :(得分:0)

在java 7和8中(但不是更早),是the -gencert option of keytool可以做到这一点。我还没有测试过java 9,但我希望它会保留这个;新的javas几乎从不丢弃有用的功能。

信任库仅包含证书,没有密钥。要签署任何内容,包括子证书,您需要一个证书和密钥,或者根据您的观点,密钥和证书,即密钥库。

java 7和8都可以使用JKS或PKCS12格式作为密钥库(j8也可以用于truststore,j7只能用于JKS)但是如果你当前拥有PEM格式的CA密钥和证书,正如OpenSSL通常使用的那样,你需要让他们进入keytool支持的格式之一。这个问题已经被多次提出和回答:
How to import an existing x509 certificate and private key in Java keystore to use in SSL?
How do I import the private and public keys (pvk,spc) and certificates (cer) into the keystore?
How can i create keystore from an existing certificate (abc.crt) and abc.key files?
Importing the private-key/public-certificate pair in the Java KeyStore
convert certificate from pem into jks
How to create keystore from cer files
Is it possible to convert an SSL certificate from a .key file to a .pfx?
Convert a CERT/PEM certificate to a PFX certificate
using OpenSSL to create .pfx file
How to create .pfx file from certificate and private key?
How to use .key and .crt file in java that generated by openssl?
How can I set up a letsencrypt SSL certificate and use it in a Spring Boot application?