java - 如何在 JAVA 中为 RSAPrivateKey 使用密码?

标签 java security encryption aes rsa

我使用 RSA 2048 key 加密和解密。但为了提高安全性,我需要使用 AES 128 方法为 RSAPrivateKey 使用密码。

我可以生成这个 key ,但我不知道如何在 JAVA 中使用它们。

在我的代码中,我初始化了私钥(没有密码)(公钥是一样的):

String PRIVATE_KEY_FILE_RSA = "src/pri.der";
File privKeyFile = new File(PRIVATE_KEY_FILE_RSA);

// read private key DER file
DataInputStream dis = new DataInputStream(new FileInputStream(privKeyFile));
byte[] privKeyBytes = new byte[(int) privKeyFile.length()];
dis.read(privKeyBytes);
dis.close();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");

// decode private key
PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privKeyBytes);
RSAPrivateKey privKey =(RSAPrivatKey) keyFactory.generatePublic(pubSpec);

并使用:

Algorithm algorithm = Algorithm.RSA256(pubKey, privKey);
...

我需要有关如何输入密码的任何信息或示例。

最佳答案

This解决方案对我来说更好。

更新

如果链接无效,请查找 not-yet-commons-ssl

我用于 not-yet-commons-ssl-0.3.11.jar。 例如:

//path to private key file
String PRIVATE_KEY_FILE_RSA = "C:\\Users\\Adey";
FileInputStream in = new FileInputStream(PRIVATE_KEY_FILE_RSA);
// passphrase - the key to decode private key
String passphrase = "somepass";
PKCS8Key pkcs8 = new PKCS8Key(in, passphrase.toCharArray());
byte[] decrypted = pkcs8.getDecryptedBytes();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decrypted);
RSAPrivateKey privKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(spec);

关于java - 如何在 JAVA 中为 RSAPrivateKey 使用密码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46342535/

相关文章:

java - 为什么线程在main方法执行后才运行?

java - 如何访问线程中 Runnable 对象的字段

.net - 解密字符串 C#

java - 地址在本地计算机上无效 [仅限 Windows 8]

java - 创建一个可以输入数据的数组

java - 托管签名 jar 时的安全注意事项

oracle - 确定使用 Oracle utl_http 执行 https post 需要哪个证书

html - html5中的音频标签安全

javascript - 如果您拥有同一字符串的解密和加密版本,是否可以反向生成 RSA/AES key ? (JS客户端加密)

php - 在数据库中存储具有不同算法的哈希是否有意义?