C++ 用openssl RSA 私钥解密

微信企业号,聊天记录提取:需要提供一个公钥给微信,他们用公钥加密聊天记录,然后我们再用私钥进行解密聊天保存。
http://tool.chacuo.net/cryptrsapubkey这个网站生成了一对2048为的RSA密钥对,密钥格式为PKCS1。
公钥如下:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxGzyp9l2CbGYVu8+8T9c
XAnjNB7KCun6fH2j1u/8if29GxeJz/uU73lcIgewJN1z3gfZT29xoPSM3hlvoDG8
e4Kv20BWP63wr8cS5qwEuIno2IOwnhq0Mq09kylDdX9NwVnobLd110q34lN9iNzr
0csWzX07rYDWso4iuUuOTgXKxyQS34/Azgaea88hQLnCCw9YB2ocs1W0lSjhq5Gn
k5FZZEhMe5UwaZI2ZgdKrBqSVQvMOxB57eBb6ofLPoDyx8DEkJmz4I6b61P/S7ZL
x+Kz7nMCik/OGsJu4Cyr5CEebWyNuZzu9JyhfFc2aGGHda6Ph2/SpVjC15wGDnQL
AwIDAQAB
-----END PUBLIC KEY-----
加密字符串如下:
bESlD7OobKjYMww9swtL6zmWvXl4mrraUt/XJvQpVbpK5u8rUP25/PJDOZms+3LF/3L2sXKj5QjUDPvQbi1ZvLBHB7fcUF59qAILIuOBi8NEgVrw6lx4CClhQciDK9FedcEkRIx/T0zuPiSNJmOyUAhYaJRG2/Xh5Mn+oMJ2LPohq5QWbd9eq17eKdY9LDKmcyoMGqCEt1iBPd1KXqHOsd79ca8aHwXdVH+mrYhHJYT5gZYwylX7LloXRevbFhFxSrFFpDNRRaSuW9vecwwO5EhUun1KoxTB3MYR3cLGowyJ+LFT1iQczr/TFW7EW1egFfeAmy9v6q8ae7blnARedw==
私钥如下:

-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAxGzyp9l2CbGYVu8+8T9cXAnjNB7KCun6fH2j1u/8if29GxeJ
z/uU73lcIgewJN1z3gfZT29xoPSM3hlvoDG8e4Kv20BWP63wr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S56gnkvVDIi33yIe0b1VJtk+in7D7GACE0JdfA2M
6g70ZmVY5n3lktKXBRxaB7ULAoGAKOMLzzEYvJ+cWOx4vV3eh4miKMGqDIsTvOJL
/lSm1p04KkCAwWoMJxYJUjp6At/+7yrun/hT85mY5NNlV+yWotjGHgIVgsRU3CUe
kUjDJbWlwQfeKD1sgjwJTZyibUXbp63oOuyP8FWBMkQ8TCSMgm/cMqodiSCL4kD6
5qKvYG0CgYEAj/v1QKuEEfm1YkkgDtiD68Eq0HDl58n6VS+GM8HLPQb/nUpdFN4z
MDHY4cWb+Bt2M2csOcvx2N2Xsl3a/G0Q05q6OCmw/utCGdlHxo+ROPKZssIRYgO/
67TdgZsRggEa66U2wSIoxBmfsD/qy42k9cYdl1rarTryuU2iJm2/+Ms=
-----END RSA PRIVATE KEY-----
我利用openssl库进行解密,代码如下:
// 私钥解密,cipherText--待解密字符串; priKey--私钥
std::string rsa_pri_decrypt(const std::string &cipherText, const std::string &priKey)
{
std::string strRet;
RSA *rsa = RSA_new();
BIO *keybio;
keybio = BIO_new_mem_buf((void *)priKey.c_str(), -1);

// 读取私钥成RSA
rsa = PEM_read_bio_RSAPrivateKey(keybio, &rsa, NULL, NULL);

// 分配大小
int len = RSA_size(rsa);
char *decryptedText = (char *)malloc(len + 1);
memset(decryptedText, 0, len + 1);

// 解密函数  
int ret = RSA_private_decrypt(cipherText.length(), (const unsigned char*)cipherText.c_str(), (unsigned char*)decryptedText, rsa, RSA_PKCS1_PADDING);
unsigned long error = ERR_peek_last_error();
if (ret >= 0)
    strRet = std::string(decryptedText, ret);

// 释放内存  
free(decryptedText);
BIO_free_all(keybio);
RSA_free(rsa);

return strRet;

}
得到的解密结果是解密失败,请问是哪里需要调整?

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问