user3670011
user3670011

Reputation: 194

RSA encryption with OpenSSL using char array public key

I have a public key stored in a variable like so:

static const char publicKey[] =
"-----BEGIN PUBLIC KEY-----\n\
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCKFctVrhfF3m2Kes0FBL/JFeO\
cmNg9eJz8k/hQy1kadD+XFUpluRqa//Uxp2s9W2qE0EoUCu59ugcf/p7lGuL99Uo\
SGmQEynkBvZct+/M40L0E0rZ4BVgzLOJmIbXMp0J4PnPcb6VLZvxazGcmSfjauC7\
F3yWYqUbZd/HCBtawwIDAQAB\n\
-----END PUBLIC KEY-----";

I would like to encrypt with PKCS #1 v1.5 padding (RSA_PKCS1_PADDING) but I can't figure out how to load the key from memory instead of a file:

void init()
{
    RSA* rsa = RSA_new();

    //what now?
    //rsa = PEM_read_RSA_PUBKEY(file, &rsa, NULL, NULL); //requires a file
}

void encrypt(unsigned char* data, int length)
{
    //can input buffer and output buffer be the same?
    RSA_public_encrypt(length, data, data, rsa, RSA_PKCS1_PADDING);
}

Also, do I need to call any cleanup code?

Upvotes: 0

Views: 660

Answers (1)

Slava
Slava

Reputation: 44248

You need to create bio and use functions that work with them:

BIO *mem = BIO_new_mem_buf(publicKey, -1);
RSA *rsa = PEM_read_bio_RSA_PUBKEY( mem, nullptr, nullptr, nullptr );
BIO_free( mem );
... // using rsa

error handling is ommited obviously.

Also, do I need to call any cleanup code?

Yes you always should. I would use RAII with smart pointers:

using BIO_ptr = std::unique_ptr<BIO,int(BIO *)>;

BIO_ptr createMemBio( const char *str )
{
    return BIO_ptr{ BIO_new_mem_buf(str, -1), BIO_free };
}

and so on

Upvotes: 2

Related Questions