Search code examples
c++encryptionopensslrsacrypto++

Using Crypto++ generated RSA keys on OpenSSL


Is there a way to use the RSA keys I've generated with the Crypto++ API in OpenSSL? What I am looking for is a way to store the keys in a format that both Crypto++ and OpenSSL can easily open them.

I'm writing a licensing scheme and would want to verify signatures and decrypt files using the Crypto++ API, but to generate the license files I would want to use a web interface (probably using PHP, which only supports OpenSSL) to generate and encrypt/sign the licenses.

I would write both applications using Crypto++ and call it from the PHP, but since the private key will be stored in a encrypted form, a password must be passed to the application and passing it on the command line doesn't seems to be a good idea to me.


Solution

  • Both Crypto++ and OpenSSL can handle PKCS#8 encoded keys. In crypto++, you can generate keys and convert to PKCS#8 buffer like this,

    AutoSeededRandomPool rng;
    RSAES_OAEP_SHA_Decryptor priv(rng, 2048);
    string der;
    StringSink der_sink(der);
    priv.DEREncode(der_sink);
    der_sink.MessageEnd();
    
    // der.data() is the bytes you need
    

    Now you just need to pass the bytes to PHP. You can save it in a file, send in a message.

    The only gotcha is that PHP's OpenSSL interface only accepts PEM encoded PKCS#8. You can easily convert DER-encoded buffer into PEM like this in PHP,

    <?php
    function pkcs8_to_pem($der) {
    
        static $BEGIN_MARKER = "-----BEGIN PRIVATE KEY-----";
        static $END_MARKER = "-----END PRIVATE KEY-----";
    
        $value = base64_encode($der);
    
        $pem = $BEGIN_MARKER . "\n";
        $pem .= chunk_split($value, 64, "\n");
        $pem .= $END_MARKER . "\n";
    
        return $pem;
    }
    ?>
    

    You can also convert PKCS#8 to PEM in C++ if you prefer. The algorithm is very simple as you can see from the PHP code.

    OpenSSL is so prevalent nowadays. I don't see any reason to use Crypto++ for common crypto applications like this.