Objective-c – Initialize Public Key From Modulus & Exponent using OpenSSL

encryptionobjective copensslrsa

Trying to generate an RSA Public Key given an APIs modulus and exponent. I'm using OpenSSL on iOS 4.2.

Generating the public key manually is an option (see below) however i'm not sure how to include the exponent logic in the modulus

-----BEGIN PUBLIC KEY-----
Modulus from API
-----END PUBLIC KEY-----

Based on @James comments, I am able to write public pem but getting blank private key. Here is my code:

char szModulus = "1162" ;
char *szExp = "827655" ;
RSA* rsa = RSA_new();
int ret = BN_hex2bn(&rsa->n,szModulus) ;
ret = BN_hex2bn(&rsa->d,szExp) ;
FILE *fp = fopen("/Users/ysi/Desktop/privateKey.pem", "wb"); 
PEM_write_RSAPrivateKey(fp, rsa, NULL, NULL, 0, 0, NULL);

Best Answer

To do this make sure you have the OpenSSL library linked (instructions here http://code.google.com/p/ios-static-libraries/)

Once linked you'll have access to several BIGNUM converters. I turned the modulus into hex using the BN_hex2bn method saving the hex string into 'exponent'

Then create the BIGNUM struct and encrypt using RSA_public_encrypt

RSA *rsa = NULL;

rsa->n = BN_new();
BN_copy(rsa->n,modulus);   
rsa->e = BN_new();
BN_copy(rsa->e,exponent);     
rsa->iqmp=NULL;
rsa->d=NULL;
rsa->p=NULL;
rsa->q=NULL;

Good Luck!