[openssl-users] how to import external rsa public key in openssl.

Matt Caswell matt at openssl.org
Fri Jun 8 13:03:57 UTC 2018

On 08/06/18 11:29, Sangsub wrote:
> 		char buf[2] = {0,};
> 		memcpy(buf, pStr, sizeof(buf));
> 		out[i] = (unsigned char)strtol(buf, NULL, 16);

This looks wrong. "buf" is not NUL terminated so strtol could give an
incorrect result.

> // raw_data is a string. Not in hex state. So I changed the contents of
> raw_data [] to hex in pArr.
> // The implementation of this function is above main function.
> 	fnStr2Hex(pArr, raw_data);		

The function is converting from a hex string to binary data so I find it
confusingly named. But it seems to be doing the right thing AFAICT aside
from the issue I noted above, although I haven't tested it.

> 	fnStr2Hex(pArr, raw_data);  // for converting hex
> 	bufio = BIO_new_mem_buf((void*)pArr, data_len);
> 	if(bufio == NULL) {
> 		printf("Error (1) \n");
> 		return -1;
> 	} 
> 	PEM_read_bio_RSAPublicKey(bufio, &pub_rsa, 0, NULL);

PEM_read_bio_RSAPublicKey() expects a PEM encoded string which is what
is contained in your raw_data buffer. It is incorrect to call
fnStr2Hex() on it first - this will cause it to fail.

As I mentioned in my previous email you should be using
PEM_read_RSA_PUBKEY() instead (or PEM_read_bio_RSA_PUBKEY() etc). If you
use the "non bio" version there is no need to create the mem BIO first.
It will just read directly from your memory buffer.


More information about the openssl-users mailing list