4

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);
jww
  • 97,681
  • 90
  • 411
  • 885
James
  • 146
  • 1
  • 12
  • *"... but getting blank private key ..."* - `RSA *` can serve as both public and private key. You only provided the public key portions to the `RSA *`. The private key parts do not magically appear from the public key part. If you could do that then most (all?) Integer Factorization Cryptography (IFC) would collapse. – jww Feb 20 '18 at 14:50

1 Answers1

4

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!

James
  • 146
  • 1
  • 12