我已经尝试过以下问题的答案:
Bouncy Castle : PEMReader => PEMParser
Read an encrypted private key with bouncycastle/spongycastle
但是由于我调用时我的加密密钥已编码为DER
Object object = pemParser.readObject();
对象为null.
我可以使用openssl的命令将其转换为PEM(它也会解密密钥)
openssl pkcs8 -inform der -in pkey.key -out pkey.pem
但我需要读取其原始文件中的密钥
解决方法:
这两个问题都是关于使用OpenSSL的“旧版PEM”加密来解析和解密文件的.您使用的是PKCS8加密,尽管类似,但有所不同,因此Reading PKCS8 in PEM format: Cannot find provider更近了.您可以在此处使用大多数方法,但是可以跳过PEM解析:
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());