我的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
请帮忙。
答案 0 :(得分:-2)
如果仔细查看d2i_RSA_PUBKEY()
的签名to
那么为什么要将第一个参数填充为0而不是NULL?
不应该是这样的吗?
RSA *d2i_RSA_PUBKEY(RSA **a, const unsigned char **pp, long length)
如果有效,请告诉我?