简体   繁体   中英

OpenSSL RSA Keypair with X509 and PKCS#8 encoding in C or Obj-C

I've been struggling for multiple days now and cannot find any accurate example/tutorial on internet so now i'm here for help.

I have a Java application that creates an RSA Keypair. This Keypair is used to encrypt and decrypt a symmetric key. (but first to test i want to use a simple text string). After generating the keypair, the keys are encoded.

PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(pbKey));

and

PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(pvBytes);

Now i'm creating an application on iOS. And i would like to do the same in thing in iOS (C or Objective-C) using OpenSSL.

Can somebody help me with this?

I'm creating the keys like this

RSA_generate_key_ex(rsa, modulus, e, NULL);

Basically what you have there is a PKCS#8 encoding of the private key (ks). Ie raw ASN.1.

I'll assume you write this out raw, encoded ( Java asymmetric encryption: preferred way to store public/private keys , Decrypted string not the same as pre encrypted string ).

So assumining that rsa is populated; and 'enc' is

    const EVP_CIPHER *enc=NULL;

or more likely

    const EVP_CIPHER *enc=EVP_aes_XXX_cbc();

where XXX is something like 128 bits you'd then call PEM_write_bio_RSAPrivateKey with something like:

    PW_CB_DATA cb_data;
    cb_data.password = passout;
    cb_data.prompt_info = outfile;

    BIO_set_fp(out,stdout,BIO_NOCLOSE);

    if (!PEM_write_bio_RSAPrivateKey(out,rsa,enc,NULL,0,
            (pem_password_cb *)password_callback,&cb_data))
            goto err;

and that should be roughly it. Code can be lifted from apps/genrsa.c in any openssl source distribuition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM