Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use keystore in Java to store private key?

Tags:

java

keystore

I have used KeyPairGenerator to generate a RSA key pair. If I'm not wrong, the KeyStore is only used to store certificates and not keys. How can I properly store the private key on the computer?

like image 208
segfault Avatar asked Mar 27 '12 13:03

segfault


People also ask

Does keystore have private key?

The SSL keystore contains a private key that is used to prove the authenticity of this SSL side to the other side of an SSL connection. The SSL truststore contains public key certificates of trusted parties.

Is private key same as keystore?

Keystore files, commonly known as UTC/JSON files, are files that are generated using a private key + a password of your choosing, essentially encrypting the private key.


1 Answers

NOTE: This code is for demonstration purposes only. Private keys must be encrypted when you store them on disk. Do not use it as is.

You can do something like this:

 KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
 kpg.initialize(2048);

 KeyPair kp = kpg.genKeyPair();

 KeyFactory fact = KeyFactory.getInstance("RSA");

 RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(),
        RSAPublicKeySpec.class);
 saveToFile(PUBLIC_KEY_FILE, 
        pub.getModulus(), pub.getPublicExponent());

 RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(),
        RSAPrivateKeySpec.class);
 saveToFile(PRIVATE_KEY_FILE, 
         priv.getModulus(), priv.getPrivateExponent());

The save function:

private static void saveToFile(String fileName,
                               BigInteger mod, BigInteger exp) 
    throws SomeException {
    ObjectOutputStream oout = new ObjectOutputStream(
            new BufferedOutputStream(new FileOutputStream(fileName)));
    try {
        oout.writeObject(mod);
        oout.writeObject(exp);
    } catch (Exception e) {
        throw new SomeException(e);
    } finally {
        oout.close();
    }
}

And read the same way back:

private static PublicKey readPublicKey() throws SomeException {
    InputStream in = new FileInputStream(PUBLIC_KEY_FILE);
    ObjectInputStream oin =
            new ObjectInputStream(new BufferedInputStream(in));
    try {
        BigInteger m = (BigInteger) oin.readObject();
        BigInteger e = (BigInteger) oin.readObject();
        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
        KeyFactory fact = KeyFactory.getInstance("RSA");
        PublicKey pubKey = fact.generatePublic(keySpec);
        return pubKey;
    } catch (Exception e) {
        throw new SomeException(e);
    } finally {
        oin.close();
    }
}

Reading private key is similar.

like image 89
Eugene Retunsky Avatar answered Oct 05 '22 07:10

Eugene Retunsky