Some Hardware Guy
Some Hardware Guy

Reputation: 164

load openssl RSA key from a string in C

I'm having a little trouble understanding what function to use to load my key into an RSA.

I get the key in string form like this from a local database:

-----begin public key----- migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqdcz4npasjgxrcv8fwqcrdw+cze 76l3inzil3mquizvuyyn5heqqsrvg7/4mu1czc5fghcuk2pbfjgk9ev3xz6soxpk pkhkxot87xgkmi1hulszcyouhvrtgkgcbk/kuktqozklgbolxf+cxigdptpgareg dp+6ieuziwsfpjrkjwidaqab -----end public key-----

then I try something like this (in objective-c):

long len = [key length];
const unsigned char *p = (unsigned char *)[key UTF8String];
RSA *r = d2i_RSA_PUBKEY(NULL, &p, len);

r always comes back null so I'm doing something wrong there. I've tried a few other things but I'm just missing it I guess. The ultimate goal is to create an RSA from my public key, and then use something like

RSA_public_encrypt ( 1, hash,    secret,     r, RSA_PKCS1_OAEP_PADDING );

To encrypt a hash, but I'm stuck on loading my keys :) Any help is appreciated.

Thank you.

Upvotes: 2

Views: 6839

Answers (1)

Some Hardware Guy
Some Hardware Guy

Reputation: 164

After a day of banging my head against the wall I finally found the solution. It didn't help that I had accidentally lower cased the key when I stored it...

Anyway here's what I did, assuming your key is in a NSString called key this code will load it for you.

const char *p = (char *)[key UTF8String];

BIO *bufio;
RSA *rsa;
NSUInteger byteCount = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];

bufio = BIO_new_mem_buf((void*)p, byteCount);
RSA *myRSA = PEM_read_bio_RSA_PUBKEY(bufio, 0, 0, 0);

Upvotes: 3

Related Questions