-1

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) {
}
RoyHSIEH
  • 855
  • 1
  • 6
  • 8
  • You *are* generating a CSR from an existing keystore. You can't generate a CSR from a certificate, as it doesn't have a private key. Your question doesn't make sense. – user207421 Dec 02 '16 at 18:41
  • Thank for your answer, I solved it~ – RoyHSIEH Dec 07 '16 at 07:36
  • 1
    Does this answer your question? [Create Certificate Signing Request inside an Android app](https://stackoverflow.com/questions/36361218/create-certificate-signing-request-inside-an-android-app) – Josh Correia Jul 25 '20 at 05:44

1 Answers1

2

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

pedrofb
  • 37,271
  • 5
  • 94
  • 142