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
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.