我使用openssl库编写了简单的RSA密钥函数。以下是我的代码,我找不到第二个PEM_read_RSAPrivateKey函数不起作用的原因。 有人可以帮助我吗?
{
RSA* pRSA;
RSA* pRET;
pRSA = RSA_generate_key(1024, 65535, NULL, NULL);
if ( RSA_check_key(pRSA) != 1 ) return (FALSE);
FILE* f;
char* pPIN = RAS_PINKEY;
f = fopen("testPRI.cap", "w");
PEM_write_RSAPrivateKey(f, pRSA, NULL, NULL, 0, NULL, NULL);
fclose(f);
f = fopen("testPRI.cap", "r");
pRET = PEM_read_RSAPrivateKey(f, &pRSAPRI, NULL, NULL);
fclose(f);
// pRET is valid (OK)
//-----
f = fopen("testPRI2.cap", "w");
PEM_write_RSAPrivateKey(f, pRSA, EVP_aes_128_cbc(), NULL, 0, NULL, "mypassword");
fclose(f);
f = fopen("testPRI2.cap", "r");
pRET = PEM_read_RSAPrivateKey(f, &pRSAPRI, NULL, "mypassword");
fclose(f);
// pRET is NULL (Why?)
}
testPRI.cap是
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDA1uie3e7nQSLS4q/1fj82UXtKI1wpDi+QgaGUbFoYQsXCsk6V
Gwaxq5wSf36ptUz5fbdp4D8+VpZ8WhuuSrbIwtjYeF4uD7tp1xgR56IP//GgN14V
Qv6qjLlIQC4Cf/v0tjnTj/Kuvt5RYasRHvkOaiHekdK3yocUdkLqv51T3wIDAP//
AoGBAINFzneTgugmmx8xNwDQBU+7HyxC5ktI12Gx3/OtBbFxhZhigSi5InOsSVZQ
6EXmlGCaGKjHM1Revac77fu/D9Lh0bf2grxT3tWCSrX/RkcayZPEkE80hxWjYVS5
nyWMktA/3NhZq/whe8+eCorXK+GRMTvq9eOwHnrVnzb5zFc/AkEA84HkyLBtNf0D
b4hDYqrWp5o1ciq5LnXEfNXFvTCYd7FhJIZmhUV792CfjvFHxZ6p5A/g0UOkYYjI
7mdnuBjJpwJBAMq7kU2bCSugmNYfJx3VjV/ypU62M8XOGNVb8F2EFSRszUqEzf4N
4x9EUljNlzzuRKJCUMm0vQAgOkZM2SitewkCQGosBoo+5ny2g1v+R0+mSClvd8j0
xZ41WxbA023mRABDyNyTrfq9XGAh8vNnynDGNFzyATl+tYR0Bf9n+TLPkYsCQBJt
kQmz4lBGgEruzdgHEknL8wyTolZcKyQH6GgYephzMDg3PISVPbtETBR4fHi5TRxg
zYKzHWURUv1Y15IHHtcCQQCJbMhCu4fdHdELdmjZXtcc72s6WrdO0wX12KMkkdbF
ri6nddfPYlONNiePbPudP4ZlF5ZNYxXtaPvHbVGgMV++
-----END RSA PRIVATE KEY-----
和testPRI2.cap是
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,8794CA8EE0292CBC22A52D0F8DA3F4D9
AqUAJdV8o7h2aFDWu3Xo8/mYt74GZOYr6NNTohV0GrRlhHps4ajdeKpugnC6to15
lbSiJFDkb83p07zs0s0NCaKxZAypZ1r05c6F+E5Rs5ozH+Q/hX6L/kQFmZWSd5Of
4Eo6HcBqB4zr57n7LtYdVTkbu9xqsPDYIeMraAtAKRFaysB73XeVNEszOC/JMnAR
8yM4dgMU+HP1+MBrtsfVPKBf7xKmE3WS/wbGT1FHVs3ANzH5cenThh5Mz6EnvuxW
FVgXS4Paxj6CyNKJabxoSmcbyUC/uANIcAQsD7HUhmu92rcABJw4tCCG0sbTTDyi
ioTkyzCq0vSjjxKbiqtySebb8p0aLkAJSDNmD9H5yqIl56egw3eKvduQHOCC4htW
hvMG0k0IRR0h/HsgliWUEUYRhXArpp5x5W1h9SPAcTLw1PhyCtMqd7xfstTpDaw8
/7nz7g7StZoZWKv4E8C485VAAAmaspoxUsbCOlIusJJVSmzAbfYcV+cvzgOLK6NP
F4y/0spR99VGVPr6TTQY38BBDLEo/70U3eHFBHUmRAS1fI9YGeBS5K9mACF4JHPv
hd9YfoSi8Zc90NJIXsexIQjy7e8edu4ODm2bBAKYodZx6v/xheD0BZqY6OhnZ+88
ad0TANIY7RBDF1QCtdVnThQxIXL0H4jlkQgEjnWX2SGXHM653+X3vJS04oN9+gpm
W2qR6Bnafg/adHBnDv71JCzbaLY0NaxXHJXSHFOX8AkmlXlLEDLLeFF84LN+LR+r
zhQNerFY1+Z8rAwu3q4bskQDL+nQGKeQq+gUumJm3CV1FZqK3OPWAS0VqTCNAJE3
-----END RSA PRIVATE KEY-----
答案 0 :(得分:1)
最后,我得到了答案。 如果缺少初始化函数调用,某些openSSL函数将无法正常工作。启动时需要以下代码
OpenSSL_add_all_algorithms();
OpenSSL_add_all_ciphers();
ERR_load_crypto_strings();