JAVA:如何将私钥保存在具有密码保护的 pem 文件中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24506246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:39:40  来源:igfitidea点击:

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

javarsabouncycastle

提问by Snox

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

我正在尝试将私钥保存在pem受密码保护的文件中。问题是,pem文件已创建,我什至可以用 openssl 打开它,但是没有要求密码!

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

执行后,我尝试打开pk.pem文件

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?

假设在访问私钥之前要求输入密码!有人可以帮帮我吗?

采纳答案by Robert

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

那么您应该仔细阅读 BouncyCastle 文档。它说明您使用的构造函数:

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

因此,您使用构造函数创建一个未加密的 PKCS8Generator 实例。您设置的密码无效。

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.

注意:问题中的代码需要过时版本的 BouncyCastle (1.4x?),因为当前版本 (1.5x) 具有不同的构造函数,与本答案中提供的构造函数不兼容。



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 PrintWriterwith any other Writerof course.

当然可能会用PrintWriter任何其他替换Writer