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?
pem contains the private encryption key. cert. pem contains certificate information.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With