Search code examples
c++encryptionrsacrypto++

How to load Base64 RSA keys in Crypto++


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.


Solution

  • 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.