Search code examples
javasslcsr

How to use java to generate csr from exist keystore


How to use java code to generate csr from exist keystore?

The function affect would be as same as(but not genearate the file)

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

I just found out "Generating a Certificate Signing Request using Java API"

But I already have X.509 certificate, how can I use this certificate to generate csr in java?

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

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

How can I use above info to generate CSR?

I Just solve it~

To share all my code to generate csr from exist certificate.

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) {
}

Solution

  • You need the public key from certificate and the private key to sign the CSR. A JKS can contain x509 certificates and key pairs. So, ensure you have it

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

    Once the CSR is signed, the CA will issue a new X509Certificate. But is not usual to reuse existing keys ( that could have been compromised) to issue a new certificate. It is recommended to generate a new key pair