openssl initialize RSA public key

c, encryption, ios, openssl

Solution

You might try the following:

const char *pub_key_pem = ...;

BIO *bio = BIO_new_mem_buf((void*)pub_key_pem, strlen(pub_key_pem));
RSA *rsa_pub = PEM_read_bio_RSAPublicKey(bio, NULL, NULL, NULL);

Note: `PEM_read_bio_RSAPublicKey()` expects PKCS#1 PEM format (with "BEGIN/END RSA PUBLIC KEY" dash lines in the first/last lines); if you have PEM with "BEGIN/END PUBLIC KEY", you should try `PEM_read_bio_RSA_PUBKEY()` instead. See explanation of the difference here and here.

If you don't have any of these dash lines in your base64 string, you may find it easier to decode the base64 string into a binary buffer, then use one of the `d2i_RSAPublicKey()` or `d2i_RSA_PUBKEY()` to get the `RSA*` public key from it.

Problem

I have RSA base64 encoded public key that I need to use to verify digital signature. I don't understand how to initialize RSA with public key. My code looks something like: ``` unsigned char *signature = ""; //signature string char *original = ""; // my original string unsigned char sha2HashDigest[SHA256_DIGEST_LENGTH]; SHA256(original, strlen(original), sha2HashDigest); char *key = "base64encodedKey"; RSA *r = RSA_new(); //SET RSA public key?! how? int result = RSA_verify(NID_sha256, sha2HashDigest, SHA256_DIGEST_LENGTH, signature, strlen(signatrue), r); if (result != 1) // handle error ``` Note: I am doing this in iOS application, but I think it is irrelevant for the question. UPDATE: I ended up using EVP as suggested by vond. Public key is PEM formatted file. This is my code: ``` FILE *fp = fopen([keyFilePath UTF8String], "r"); if (!fp) return NO; EVP_PKEY *pubKey = PEM_read_PUBKEY(fp,NULL,NULL,NULL); EVP_MD_CTX md_ctx; EVP_MD_CTX_init(&md_ctx); EVP_VerifyInit(&md_ctx, EVP_sha256()); EVP_VerifyUpdate (&md_ctx, (unsigned char*)[msgData bytes], [msgData length]); int err = EVP_VerifyFinal (&md_ctx, (unsigned char*) sigData, (unsigned int)[sigData length], pubKey); EVP_PKEY_free (pubKey); ```

Original source

Related problems