中加载PEM编码的私有RSA密钥

中加载PEM编码的私有RSA密钥

本文介绍了在Crypto ++中加载PEM编码的私有RSA密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,用户将具有PEM编码的RSA私钥。 Crypto ++要求这些密钥以DER格式加载。我一直要求人们手动转换他们的PEM文件到DER事先使用openssl像这样:

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.

它是简单的条带化----- BEGIN CERTIFICATE ---- - 和----- END CERTIFICATE -----从PEM或还是一些其他转型吗?我被告知,在这些标记之间,它只是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密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 20:14