如何在Java中解密私钥(不使用BC openssl) [英] How to decrypt a private key in Java (without BC openssl)

查看:258
本文介绍了如何在Java中解密私钥(不使用BC openssl)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用JCE和/或BouncyCastle提供程序(不使用openssl捆绑包)解密加密的RSA(或其他无关紧要的)私钥?

Is it possible decrypt an encrypted RSA (or others, shouldn't matter) private keys using JCE and/or BouncyCastle provider (not using openssl bundle)?

我可以使用PrivateKeyFactory读取未加密的密钥.

I can read unencrypted keys just fine using PrivateKeyFactory.

通过谷歌搜索,可以了解使用PEMReader(来自BC openssl捆绑包)的示例,该示例已对其应用了密码,但是-不想使用openssl捆绑包,不一定要使用PEM格式,我可以使用PemReader(来自提供程序包)对PEM进行解码.问题是我该怎么办.

Googling this gets me through examples of using PEMReader (from BC openssl bundle) that has a password applied to it, but - don't want to use openssl bundle, don't necessarily want to use PEM format, and I can decode PEM using PemReader (from provider bundle). It's what can I do with it afterwards is the question.

我正在寻找某种宏功能,或其一系列可以实现的功能,即我不是在分析解析加密密钥的ASN1,弄清楚加密方法,将输入内容通过密码传递等等.

I'm looking for some mega-function, or a series thereof that can do it, i.e. I am not looking into parsing the ASN1 of the encrypted key, figuring out the encryption method, passing the input through the cipher, etc.

推荐答案

如果您具有二进制格式(即非PEM格式)的加密PKCS#8密钥,则以下代码显示如何检索私钥:

If you have an encrypted PKCS#8 key in binary format (i.e. not in PEM format) the following code shows how to retrieve the private key:

public PrivateKey decryptKey(byte[] pkcs8Data, char[] password) throws Exception {
    PBEKeySpec pbeSpec = new PBEKeySpec(password);
    EncryptedPrivateKeyInfo pkinfo = new EncryptedPrivateKeyInfo(pkcs8Data);
    SecretKeyFactory skf = SecretKeyFactory.getInstance(pkinfo.getAlgName());
    Key secret = skf.generateSecret(pbeSpec);
    PKCS8EncodedKeySpec keySpec = pkinfo.getKeySpec(secret);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePrivate(keySpec);
}

如果您使用的是PEM格式,请删除标头(第一行),页脚(最后一行),然后将其余内容从base64转换为常规字节数组.

If you have a PEM format, remove the header (first line), the footer(last line) et convert the remaining content from base64 to regular byte array.

这篇关于如何在Java中解密私钥(不使用BC openssl)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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