如何在Java中向现有私钥添加密码 [英] How to add a password to an existing private key in Java

查看:77
本文介绍了如何在Java中向现有私钥添加密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我以前使用openssl创建了私钥,但是我决定不使用密码保护它:

Say I have a previously created private key using openssl, but I've decided not to protect it with a passphrase:

-----BEGIN RSA PRIVATE KEY-----
BASE64 ENCODED DATA
-----END RSA PRIVATE KEY-----

但是后来我意识到我想保护它.

But then I realised that I want to protect it.

我知道如何使用openssl保护它,但是我有一个用Java做到这一点的要求.有可能吗?

I know how to protect it using openssl, but I have a requirement to do it in Java. Is it possible ?

推荐答案

首先从pem文件中加载并提取pkcs#1未加密密钥

First load and extract the pkcs#1 unencrypted key from the pem file

String pem = new String(Files.readAllBytes(Paths.get("rsa.key")));
String privateKeyPEM = pem.replace(
        "-----BEGIN RSA PRIVATE KEY-----\n", "")
             .replace("-----END RSA PRIVATE KEY-----", "");
 byte[] encodedPrivateKey = Base64.getDecoder().decode(privateKeyPEM);

然后使用此代码的第二部分(我已经包含了它)

And then encrypt the key using the second part of this code ( I have included It)

 // We must use a PasswordBasedEncryption algorithm in order to encrypt the private key, you may use any common algorithm supported by openssl, you can check them in the openssl documentation http://www.openssl.org/docs/apps/pkcs8.html
String MYPBEALG = "PBEWithSHA1AndDESede";
String password = "pleaseChangeit!";

int count = 20;// hash iteration count
SecureRandom random = new SecureRandom();
byte[] salt = new byte[8];
random.nextBytes(salt);

// Create PBE parameter set
PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
SecretKeyFactory keyFac = SecretKeyFactory.getInstance(MYPBEALG);
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

Cipher pbeCipher = Cipher.getInstance(MYPBEALG);

// Initialize PBE Cipher with key and parameters
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);

// Encrypt the encoded Private Key with the PBE key
byte[] ciphertext = pbeCipher.doFinal(encodedPrivateKey);

// Now construct  PKCS #8 EncryptedPrivateKeyInfo object
AlgorithmParameters algparms = AlgorithmParameters.getInstance(MYPBEALG);
algparms.init(pbeParamSpec);
EncryptedPrivateKeyInfo encinfo = new EncryptedPrivateKeyInfo(algparms, ciphertext);

// and here we have it! a DER encoded PKCS#8 encrypted key!
byte[] encryptedPkcs8 = encinfo.getEncoded();

使用以下代码解密(摘录自此处)

Use the following code to decrypt (extrscted from here)

public static PrivateKey getPrivateKey(byte[]   encryptedPkcs8, String passwd) throws Exception{

        EncryptedPrivateKeyInfo encryptPKInfo = new EncryptedPrivateKeyInfo(encryptedPkcs8);

        Cipher cipher = Cipher.getInstance(encryptPKInfo.getAlgName());
        PBEKeySpec pbeKeySpec = new PBEKeySpec(passwd.toCharArray());
        SecretKeyFactory secFac = SecretKeyFactory.getInstance(encryptPKInfo.getAlgName());
        Key pbeKey = secFac.generateSecret(pbeKeySpec);
        AlgorithmParameters algParams = encryptPKInfo.getAlgParameters();
        cipher.init(Cipher.DECRYPT_MODE, pbeKey, algParams);
        KeySpec pkcs8KeySpec = encryptPKInfo.getKeySpec(cipher);
        KeyFactory kf = KeyFactory.getInstance(ALGORITHM);
        return kf.generatePrivate(pkcs8KeySpec);
}

这篇关于如何在Java中向现有私钥添加密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆