Bouncy Castle:PEMReader => PEMParser [英] Bouncy Castle : PEMReader => PEMParser

查看:699
本文介绍了Bouncy Castle:PEMReader => PEMParser的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用PEM证书,如

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-256-CBC,B9846B5D1803E.....

使用BC 1.46,我使用以下代码提取密钥对:

using BC 1.46, I extract the keypair with the following code :

int myFunc(String pemString, char [] password) {

    ByteArrayInputStream tube = new ByteArrayInputStream(pemString.getBytes());

    Reader fRd = new BufferedReader(new InputStreamReader(tube));

    PEMReader pr = new PEMReader(fRd, new Password (password), "BC");

     try {
            Object o = pr.readObject();
            if (o instanceof KeyPair)
    .....

现在我刚刚安装了BC 1.48,他们告诉我PEMReader已被弃用,必须由PEMParser替换。

Now I just installed BC 1.48, and they tell me that PEMReader is deprecated and must be replaced by PEMParser.

我的问题是,AFAIK,PEMParser中没有密码的地方。

My problem is, AFAIK, there is no place for a password in PEMParser.

有人能举例说明如何将我的代码迁移到PEMParser版本吗?

Could someone give me an example how to migrate my code to a PEMParser version ?

TIA

推荐答案

我只需要解决同样的问题,但没有找到答案。
所以我花了一些时间学习BC API,找到了适合我的解决方案。
我需要从文件中读取私钥,所以在myFunc方法中有privateKeyFileName参数而不是pemString参数。

I just needed to solve the same problem and found no answer. So I spent some time studying BC API and found a solution which works for me. I needed to read the private key from file so there is privateKeyFileName parameter instead pemString parameter in the myFunc method.

使用BC 1.48和PEMParser:

Using BC 1.48 and PEMParser:

int myFunc(String privateKeyFileName, char [] password) {
     File privateKeyFile = new File(privateKeyFileName); // private key file in PEM format
     PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile));
     Object object = pemParser.readObject();
     PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(password);
     JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
     KeyPair kp;
     if (object instanceof PEMEncryptedKeyPair) {
        System.out.println("Encrypted key - we will use provided password");
        kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
    } else {
        System.out.println("Unencrypted key - no password needed");
        kp = converter.getKeyPair((PEMKeyPair) object);
    }
}

这篇关于Bouncy Castle:PEMReader => PEMParser的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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