如何使用 java 从现有密钥库生成 csr

How to use java to generate csr from exist keystore

如何使用 java 代码从现有密钥库生成 csr?

函数影响与(但不生成文件)相同

keytool -certreq -alias certificate_alias -keystore jssecacerts -storepass changeit -file client.csr

我刚刚发现“Generating a Certificate Signing Request using Java API

但是我已经有X.509证书,如何使用这个证书在java中生成csr?

KeyStore ts = KeyStore.getInstance("JKS");
FileInputStream is = new FileInputStream(trustStoreFileName);

ts.load(is, trustStorePassword.toCharArray());
is.close();
X509Certificate x509Cert = (X509Certificate)ts.getCertificate("certificate_alias");

如何使用以上信息生成 CSR?

我就解决了~

共享我的所有代码以从现有证书生成 csr。

KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream is = new FileInputStream(trustStoreFileName);

ks.load(is, trustStorePassword.toCharArray());
is.close();

X509Certificate x509Cert = (X509Certificate)ks.getCertificate("certificate_alias");

X500Principal principal = x509Cert.getSubjectX500Principal();
X500Name x500Name = new X500Name( principal.getName() );

PublicKey publicKey = x509Cert.getPublicKey();
PrivateKey privateKey = (PrivateKey) ks.getKey("certificate_alias", trustStorePassword.toCharArray());

String sigAlg = x509Cert.getSigAlgName();
PKCS10 pkcs10 = new PKCS10(publicKey);
Signature signature = Signature.getInstance(sigAlg);
signature.initSign(privateKey);
pkcs10.encodeAndSign(new X500Signer(signature, x500Name));
ByteArrayOutputStream bs = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bs);
pkcs10.print(ps);
byte[] c = bs.toByteArray();
try {
    if (ps != null)
        ps.close();
    if (bs != null)
        bs.close();
} catch (Throwable th) {
}

您需要证书中的 public 密钥和私钥来签署 CSR。 JKS 可以包含 x509 证书和密钥对。所以,确保你有它

PrivateKey privateKey = ts.getPrivateKey("certificate_alias");

签署 CSR 后,CA 将颁发新的 X509 证书。但通常不会重复使用现有密钥(可能已经被泄露)来颁发新证书。建议生成新的密钥对