读书人

openssl中关于RSA加密的灵异有关问题

发布时间: 2012-03-02 14:40:29 作者: rapoo

openssl中关于RSA加密的灵异问题
//取得公钥:
FILE *fpubkey = NULL;
fpubkey = fopen(PUBLIC_KEY_FILE, "rb");//已存在的密钥
if(fpubkey == NULL)
{
return -1;
}

fseek(fpubkey, 0, SEEK_END);
int len_PK = ftell(fpubkey);
fseek(fpubkey, 0, SEEK_SET);
ucPubKey = new unsigned char[len_PK];
fread(ucPubKey, 1, len_PK, fpubkey);
fclose(fpubkey);

RSA *pRsa = NULL;
pRsa = RSA_new();

const unsigned char *Pt = ucPubKey;
pRsa = d2i_RSAPublicKey(&pRsa, &Pt, len_PK);//出错 pRsa 为NULL
if(pRsa == NULL)
{

return -2;
}
encrypted_len = RSA_public_encrypt(KLENGTH, m_byKey, ucEncryptedKey, pRsa, 1);

为什么会这样的呢?pRsa = d2i_RSAPublicKey(&pRsa, &Pt, len_PK);//出错 pRsa 为NULL??
请各位指教下啊,谢谢啊,这个是调用win下编译好的openssl做成的。



[解决办法]
d2i_RSAPublicKey 要求第二参数为ASN1编码,der格式
试了下可以

用pem格式的文件读取后,执行到你处为NULL。
虽然为der格式文件,但公钥前还含有其他数据,即d2i_RSAPublicKey的第二参数指向的位置开始还含有其他数据时,一样也会执行失败返回NULL。

可以转一下只含公钥文件的格式,即转之前删除-----BEGIN PUBLIC KEY-----等

结帖率好低啊
[解决办法]
fseek(fpubkey, 0, SEEK_END);
int len_PK = ftell(fpubkey);

fseek(fpubkey, 0, SEEK_SET); //这是从当前位置读的, 但此时的当前位置是END,应该从文件的BEGIN读。

ucPubKey = new unsigned char[len_PK];
fread(ucPubKey, 1, len_PK, fpubkey);
fclose(fpubkey);

对于1024BIT来说, 公钥数据的长度一般是140左右的字节。
[解决办法]

探讨
fseek(fpubkey, 0, SEEK_END);
int len_PK = ftell(fpubkey);

fseek(fpubkey, 0, SEEK_SET); //这是从当前位置读的, 但此时的当前位置是END,应该从文件的BEGIN读。

ucPubKey = new unsigned char[len_PK];
fread(ucPubKey, 1, len_PK, ……

[解决办法]
d2i_RSAPublicKey

d2i der to internal 读入的即是DER编码的码流了

你读PEM文件的话肯定不行了

读书人网 >服务器安全

热点推荐