Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA: How to save a private key in a pem file with password protection

I am trying to save a private key in a pem file, protected with a password. The problem is, the pem file is created and I can even open it with openssl but, no password is asked!

Here is the code:

KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
keygen.initialize(2048);
KeyPair keypair = keygen.generateKeyPair();

PrivateKey privKey = keypair.getPrivate();

PKCS8Generator encryptorBuilder = new PKCS8Generator(privKey);
encryptorBuilder.setPassword("testing".toCharArray());
PEMWriter writer = new PEMWriter(new FileWriter(new File("pk.pem")));
PemObject obj = encryptorBuilder.generate();

writer.writeObject(obj);
writer.flush();
writer.close();

After it executes, I try to open the pk.pem file

openssl rsa -in pk.pem -check

and it gives:

RSA key ok
writing RSA key
-----BEGIN RSA PRIVATE KEY-----
(... some key appears here ...)
-----END RSA PRIVATE KEY-----

It was suppose to ask for the password before giving access to the private key! Can some one please help me?

like image 296
Snox Avatar asked Jul 01 '14 08:07

Snox


People also ask

Does PEM contain private key?

pem contains the private encryption key. cert. pem contains certificate information.


1 Answers

Well you should read the BouncyCastle documentation carefully. It states for the constructor you use:

// Constructor for an unencrypted private key PEM object.
PKCS8Generator(java.security.PrivateKey key)

// Constructor for an encrypted private key PEM object.
PKCS8Generator(java.security.PrivateKey key, java.lang.String algorithm, java.lang.String provider)

Hence you are using the constructor for creating an creates an unencrypted PKCS8Generator instance. The password you set as no effect.

Use one of the other constructors instead that create an encrypting instance according to the documentation.

Note: The code in the question requires an outdated version of BouncyCastle (1.4x?), because the current version (1.5x) has different constructors, incompatible with those presented in this answer.


For newer versions use:

import org.bouncycastle.openssl.jcajce.JcaPEMWriter;

JcaPEMWriter writer = new JcaPEMWriter(new PrintWriter(System.out));
writer.writeObject(sk);
writer.close();

possibly replacing the PrintWriter with any other Writer of course.

like image 92
Robert Avatar answered Oct 31 '22 20:10

Robert