2

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.

jww
  • 97,681
  • 90
  • 411
  • 885
Kyojin
  • 157
  • 2
  • 12

1 Answers1

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

jww
  • 97,681
  • 90
  • 411
  • 885
  • I did try that before, from Keys And Formats link and all I'm getting is BER decode error Exception. In fact I tried almost all of the stuff from the wiki but at no avail. That's why I asked for help here. I did try it again and it didn't work. – Kyojin Feb 05 '17 at 15:37
  • @Kyojin - see the edits above. Next time, please ask a concise question. Your question asked how to load a Base64 encoded key. You did not state you experienced an exception with code that was not provided. – jww Feb 05 '17 at 16:00
  • Thanks it works! Sorry for not mentioning the exception. Will try to ask better next time. – Kyojin Feb 05 '17 at 16:41