如何读取也用bouncycastle在DER中编码的PKCS8加密私钥? [英] How read a PKCS8 encrypted Private key which is also encoded in DER with bouncycastle?

查看:353
本文介绍了如何读取也用bouncycastle在DER中编码的PKCS8加密私钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了以下问题的答案:

I have tried answers of these questions:

Bouncy Castle:PEMReader => PEMParser

使用bouncycastle / spongycastle读取加密的私钥

但是,当我呼叫

Object object = pemParser.readObject(); 

对象为空。

我可以使用openssl的命令将其转换为PEM(它也解密密钥)

I can convert it to PEM with this openssl's command (it decrypts the key too)

openssl pkcs8 -inform der -in pkey.key -out pkey.pem 

但我需要读取其原始文件中的密钥

but I need to read the key in its original file

推荐答案

这两个问题都是关于使用OpenSSL的旧版PEM加密来解析和解密文件的。您所使用的PKCS8加密虽然相似,但有所不同,因此在PEM中读取PKCS8格式:找不到提供者。您可以在此处使用大多数方法,但是跳过PEM解析:

Both those Qs are about parsing, and decrypting, files using OpenSSL's 'legacy PEM' encryption. You are using PKCS8 encryption which is different though similar, so Reading PKCS8 in PEM format: Cannot find provider is closer. You can use most of the approach there, but skipping the PEM parse:

import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo; // NOT the 
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;       // javax ones!
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder;
import org.bouncycastle.operator.InputDecryptorProvider;
import org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo;

    // args[0] = filename args[1] = password
    FileInputStream fis = new FileInputStream(args[0]);
    byte[] buff = new byte[9999]; int len = fis.read(buff); fis.close();
    // could use File.readAllBytes in j8 but my dev machine is old

    // create what PEMParser would have 
    ASN1Sequence derseq = ASN1Sequence.getInstance (Arrays.copyOf(buff,len));
    PKCS8EncryptedPrivateKeyInfo encobj = new PKCS8EncryptedPrivateKeyInfo(EncryptedPrivateKeyInfo.getInstance(derseq));
    // decrypt and convert key
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
    InputDecryptorProvider decryptionProv = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(args[1].toCharArray());
    PrivateKeyInfo keyInfo = encobj.decryptPrivateKeyInfo(decryptionProv);
    PrivateKey key = converter.getPrivateKey(keyInfo);

    // now actually use key, this is just a dummy
    System.out.println (key.getAlgorithm());

这篇关于如何读取也用bouncycastle在DER中编码的PKCS8加密私钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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