Search code examples
crypto++

Load RSA PKCS#1 private key from memory?


I have to write a program to establish a secure communication with a USB device. I have to use the private key generated from it which is stored in PKCS#1 format. As I have used Crypto++ in order part of my program, I would like to utilize it for this purpose as well.

However, I cannot find a way to import RSA private key from memory. It accepts private key in PKCS#8 format only. Could some pro show me a sample code on how to do it? Many thanks!


Solution

  • PKCS#1 format is ASN.1 encoded. For RSAPublicKey and RSAPrivateKey, its as easy as:

    RSA::PublicKey publicKey(...);
    
    ByteQueue queue;
    publicKey.Save(queue);
    
    // The public key is now in the ByteQueue in PKCS #1 format
    
    // ------------
    
    // Load a PKCS #1 private key
    byte key[] = {...}
    ArraySource arr(key, sizeof(key));
    
    RSA::PrivateKey privateKey;
    privateKey.Load(arr);
    
    // The private key is now ready to use
    

    Saving and loading keys is discussed in more detail at the Crypto++ wiki under Keys and Formats.