-1

My C program using RSA_genarate_key() function creates RSA public and private key. Then public key is saved in file after converted into DER format using i2d_RSA_PUBKEY().

File with public key seems to be ok

openssl rsa -in public.der -inform DER -pubin -text    //shows up as below

Public-Key: (2048 bit)
Modulus:
   00:b5:99:9a:d3:7e:....
    .......39:86:6b:ae:29
Exponent: 3 (0x3)
writing RSA key
-----BEGIN PUBLIC KEY-----
MIIBIDANBgkqhkiG9.............
....................+1Y5lSk5hmuu
KQIBAw==
-----END PUBLIC KEY-----

Problem appears when I try to read it back and use it for encryption. Here is the code:

File* fp;
RSA *pub=NULL;
const unsigned char* public_key_buf;
int size;
fp = fopen("public.der","r");
fseek (fp , 0 , SEEK_END);
size = ftell (fp); 
size = sizeof(char)*size;
rewind (fp);
public_key_buf = malloc(size*sizeof(char));
fread(&public_key_buf,sizeof(char),size,fp);

pub = d2i_RSA_PUBKEY(0, &public_key_buf, size);

fclose(fp);

Running program results in Segmentation fault

Here is what gdb says:

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7b0fe85 in ASN1_get_object ()
from /lib/x86_64-linux-gnu/libcrypto.so.1.0.0
(gdb) bt
#0  0x00007ffff7b0fe85 in ASN1_get_object () from /lib/x86_64-linux-gnu/libcrypto.so.1.0.0
#1  0x00007ffff7b05f30 in ?? () from /lib/x86_64-linux- gnu/libcrypto.so.1.0.0
#2  0x00007ffff7b071ad in ASN1_item_ex_d2i () from /lib/x86_64-linux-gnu/libcrypto.so.1.0.0
#3  0x00007ffff7b07914 in ASN1_item_d2i () from /lib/x86_64-linux-gnu/libcrypto.so.1.0.0
#4  0x00007ffff7affa3e in d2i_PUBKEY () from /lib/x86_64-linux-gnu/libcrypto.so.1.0.0
#5  0x00007ffff7affb14 in d2i_RSA_PUBKEY () from /lib/x86_64-linux-gnu/libcrypto.so.1.0.0
#6  0x0000000000400daa in main () at rsa_1.c:99

(gdb) p pub
$1 = (RSA *) 0x0
(gdb) p public_key_buf
$2 = (const unsigned char **) 0x603250
(gdb) p *public_key_buf
$3 = (const unsigned char *) 0x9060d3020018230 <error: Cannot access memory at address 0x9060d3020018230>
(gdb) p size
$4 = 293

Any help, please.

michal
  • 115
  • 6

1 Answers1

-2

If you look closely the signature for d2i_RSA_PUBKEY()

RSA *d2i_RSA_PUBKEY(RSA **a, const unsigned char **pp, long length)

So why are you filling the first argument as 0 instead of NULL?

Shouldn't it be something like this?

pub = d2i_RSA_PUBKEY(NULL, &public_key_buf, size);

Let me know if this works?

isedev
  • 18,848
  • 3
  • 60
  • 59
Amar
  • 1