问题描述
通常,用户将拥有 PEM 编码的 RSA 私钥.Crypto++ 要求这些密钥为 DER 格式才能加载.我一直在要求人们事先使用 openssl 手动将他们的 PEM 文件转换为 DER,如下所示:
Often times, user will have PEM encoded RSA private keys. Crypto++ requires that these keys be in DER format to load. I've been asking people to manually convert their PEM files to DER beforehand using openssl like this:
openssl pkcs8 -in in_file.pem -out out_file.der -topk8 -nocrypt -outform der
这很好,但有些人不明白如何做,也不想这样做.所以我想在程序中自动将 PEM 文件转换为 DER 文件.
That works fine, but some people don't understand how to do that nor do they want to. So I would like to convert PEM files to DER files automatically within the program.
是否像从 PEM 中剥离-----BEGIN CERTIFICATE-----"和-----END CERTIFICATE-----"一样简单,还是还需要其他一些转换?有人告诉我,在这些标记之间,它只是 b64 编码的 DER.下面是一些演示该问题的代码:
Is it as simple as striping the "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----" from the PEM or is some other transformation required as well? I've been told that between those markers that it's just b64 encoded DER. Here's some code that demonstrates the issue:
// load the private key
CryptoPP::RSA::PrivateKey PK;
CryptoPP::ByteQueue bytes;
try
{
CryptoPP::FileSource File( rsa.c_str(), true, new CryptoPP::Base64Decoder() );
File.TransferTo( bytes );
bytes.MessageEnd();
// This line Causes BERDecodeError when a PEM encoded file is used
PK.Load( bytes );
}
catch ( CryptoPP::BERDecodeErr )
{
// Convert PEM to DER and try to load the key again
}
我想避免对 openssl 进行系统调用并完全在 Crypto++ 中进行转换,以便用户可以提供任何一种格式和正常工作"的东西.感谢您的建议.
I'd like to avoid making system calls to openssl and do the transformation entirely in Crypto++ so that users can provide either format and things "just work". Thanks for any advice.
推荐答案
是的,这是一个使用 Base64 编码的 DER 流.但请注意,除了剥离 BEGIN 和 END 标记外,在 RSA 密钥格式的情况下,您还需要剥离可能插入 BEGIN 标记和编码数据之间的任何标志.只有剩下的部分才能成功Base64解码.您似乎将完整的证书文件提供给解码器,需要修复.
Yes, it's a DER stream encoded with Base64. Note though, in addition to striping both BEGIN and END markers, in case of RSA key format you also need to strip any flags that may be inserted between the BEGIN marker and the encoded data. Only the remaining part can be successfully Base64 decoded. It appears that you feed the full certificate file to the decoder and that needs fixing.
这篇关于在 Crypto++ 中加载 PEM 编码的私有 RSA 密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!