我的C程序使用RSA_genarate_key()函数创建RSA公钥和私钥。然后,使用i2d_RSA_PUBKEY()将公钥转换为DER格式后,会将其保存在文件中。

带有公钥的文件似乎还可以

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-----


当我尝试将其读回并用于加密时出现问题。这是代码:

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);


运行程序结果为Segmentation fault

这是gdb所说的:

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


请帮忙。

最佳答案

如果仔细查看d2i_RSA_PUBKEY()的签名

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


那么,为什么要将第一个参数填充为0而不是NULL?

不应该是这样吗?

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


让我知道这个是否奏效?

关于c - OpenSSL d2i_RSA_PUBKEY导致段错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36604601/

10-11 00:28