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

时光毁灭记忆、已成空白 提交于 2019-12-21 01:06:56

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/24506246/java-how-to-save-a-private-key-in-a-pem-file-with-password-protection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!