Lolly
Lolly

Reputation: 36462

Extracting private key in java

I have certificate created using java class CertAndKeyGen and X500Name and I am able to generate the certificate which is in byte array. Now I want the private key I used in certificate and convert it into readable format. Below is the code I used to create the certificate,

    CertAndKeyGen keypair = new CertAndKeyGen("RSA", "SHA1WithRSA", null); 
    X500Name x500Name = new X500Name(commonName, organizationalUnit, organization, city, state, country);
    keypair.generate(keysize);
    PrivateKey privKey = keypair.getPrivateKey();
    PKCS10 certReq = keypair.getCertRequest(x500Name);
    X509Certificate[] chain = new X509Certificate[1];
    chain[0] = keypair.getSelfCertificate(x500Name, new Date(), (long) validity * 24 * 60 * 60);
    keyStore.setKeyEntry(alias, privKey, keyStorePassword.toCharArray(), chain);                    
    ByteArrayOutputStream bs = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(bs);
    certReq.print(ps);
    byte[] certReqPrintable = bs.toByteArray(); 

I have got no clues, please help me to go in right direction to get private key and convert it into readable format. Thanks in advance.

Upvotes: 3

Views: 9113

Answers (2)

Hiro2k
Hiro2k

Reputation: 5597

BouncyCastle has the useful PEMWriter class that you can use to write the private key to a file in PEM format (this is what tools like OpenSSH and curl expect).

PEMWriter privatepemWriter = new PEMWriter(new FileWriter(filename)));
privatepemWriter.writeObject(privKey);
privatepemWriter.close();

Otherwise you can just save the byte array from the private key which is the DER format also used by many tools.

Finally you can write it to a JKS keystore used by other java programs using this:

KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null);
keyStore.setKeyEntry("some alias", privKey, somePassword.toCharArray(), chain[0]));
FileOutputStream fos = new FileOutputStream(filename);
keyStore.store(fos, somePassword.toCharArray());
fos.close();

Upvotes: 1

Robert
Robert

Reputation: 42829

If you want to save the private key to a file use

byte[] privateKeyBytes = privKey.getEncoded();

This returns the key in DER encoded (binary) format.

In case you want just to display the contained values on the console just print it using toString():

System.out.println(privKey);

Upvotes: 1

Related Questions