How to load Base64 RSA keys in Crypto++

微笑、不失礼 提交于 2020-01-04 09:09:28

问题


I'm trying to write helper functions for a program I'm making and I need to return the keys as strings. Found a way to convert the RSA keys from PrivateKey/PublicKey to Base64 string.

int main()
{
    //Generate params
    AutoSeededRandomPool rng;
    InvertibleRSAFunction params;
    params.Initialize(rng, 4096);

    //Generate Keys
    RSA::PrivateKey privKey(params);
    RSA::PublicKey pubKey(params);

    //Encode keys to Base64
    string encodedPriv, encodedPub;

    Base64Encoder privKeySink(new StringSink(encodedPriv));
    privKey.DEREncode(privKeySink);

    Base64Encoder pubKeySink(new StringSink(encodedPub));
    privKey.DEREncode(pubKeySink);

    RSA::PrivateKey pvKeyDecoded;
    RSA::PublicKey pbKeyDecoded;

    //how to decode...

    system("pause");
    return 0;
}

Now, how do I load the encoded keys back? I wasn't able to find any information on that.


回答1:


RSA::PrivateKey pvKeyDecoded;
RSA::PublicKey pbKeyDecoded;

//how to decode...

You can do something like:

StringSource ss(encodedPriv, true, new Base64Decoder);
pvKeyDecoded.BERDecode(ss);

You should also fix this:

Base64Encoder pubKeySink(new StringSink(encodedPub));
privKey.DEREncode(pubKeySink);  // pubKey.DEREncode

And you should call MessageEnd() once the key is written:

Base64Encoder privKeySink(new StringSink(encodedPriv));
privKey.DEREncode(privKeySink);
privKeySink.MessageEnd();

Base64Encoder pubKeySink(new StringSink(encodedPub));
pubKey.DEREncode(pubKeySink);
pubKeySink.MessageEnd();

You might also find Keys and Formats helpful from the Crypto++ wiki.



来源:https://stackoverflow.com/questions/42044531/how-to-load-base64-rsa-keys-in-crypto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!