keypair java_java – 如何使用密码加密的私钥生成RSA keyPair?

我知道这有点迟了,但是我也一直在寻找一种方法来做到这一点,而我正在搜索我发现你的问题,现在我已经找到了一个方法,我决定回来分享一下:

// generate key pair

KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");

keyPairGenerator.initialize(1024);

KeyPair keyPair = keyPairGenerator.genKeyPair();

// extract the encoded private key, this is an unencrypted PKCS#8 private key

byte[] encodedprivkey = keyPair.getPrivate().getEncoded();

// 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(encodedprivkey);

// 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();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值