0

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?

1
  • Just create bio associated with memory and use PEM_read_bio_PUBKEY or PEM_read_bio_RSA_PUBKEY Commented Sep 13, 2018 at 20:08

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.