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

Sangsub i_chacha at naver.com
Fri Jun 8 10:29:20 UTC 2018

Thanks Matt for your reply.

The purpose I am doing this is to find the modulus and exponent in the RSA
public key.
My sample code and the current results are shown below.

void fnStr2Hex(char* out, char* in) {
	int data_len = strlen(in);
	char * pStr = in;
	int i;
	for(i=0; i<data_len/2; i++) {
		char buf[2] = {0,};
		memcpy(buf, pStr, sizeof(buf));
		out[i] = (unsigned char)strtol(buf, NULL, 16);

		// need to check strol 2nd arguments... for error checking..
		printf("i:%d, pArr[i]:%02X \n", i, out[i]);


int main() {
	char raw_data[] =

	int data_len = strlen(raw_data);  // Q) I think this is the problem. How
many lengths should I allocate?
	unsigned char * pArr = (unsigned char *)malloc(data_len);
	memset(pArr, 0x00, data_len);
// 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);		
	if(pub_rsa == NULL) {
		printf("error : failed d2i_RSAPublicKey \n");
		return -1;
	BN_print(STDout,pub_rsa->n);   // print modulus bignum
	BN_print(STDout,pub_rsa->e);  //  print exponent bignum
	return 0;

result : error : failed d2i_RSAPublicKey

I wrote the above, but I think data_len is the problem. I do not know how
much size I should enter.
And do I have to enter the string source without the string to hex in the
d2i_RSAPublicKey function?

And you said you need prefix and postfix to do PEM format.
Is raw_data [] as shown below?

raw_data[] = {
"-----BEGIN PUBLIC KEY-----"\
"-----END PUBLIC KEY----- "

After that, I coded as follows.

	int data_len = strlen(raw_data);
	BIO *bufio = NULL;
	RSA *pub_rsa = NULL;

	unsigned char * pArr = (unsigned char *)malloc(data_len);
	memset(pArr, 0x00, data_len);
	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);
	if(pub_rsa == NULL) {
		printf("Error (2) \n");
		return -1;
} // end of main

When I execute the above code, Error (2) is output.
I want to be helped with the above two (DER, PEM) situations.
Again, I want to find the modulus and public exponent in the RSA public key.


Sent from: http://openssl.6102.n7.nabble.com/OpenSSL-User-f3.html

More information about the openssl-users mailing list