我尝试使用RSA算法加密简单文本。我的代码有问题。
RSA *_RSA ;
unsigned char text[2560] = "A";
unsigned char sectext[2560];
unsigned char decrypttext[2560];
int i = 0;
_RSA = RSA_generate_key ( 1024, 65537, NULL, NULL );
i = RSA_public_encrypt ( 1, text, sectext, _RSA, RSA_PKCS1_OAEP_PADDING );
i = RSA_private_decrypt( 1, sectext, decrypttext, _RSA, RSA_PKCS1_OAEP_PADDING);
RSA_free ( _RSA );
RSA_public_encrypt
的返回值是128,这是密文的大小。 RSA_private_decrypt
返回-1,这是一个错误。如果我尝试显示恢复的文本,那么我什么也得不到。
为什么RSA_private_decrypt
会返回-1?
答案 0 :(得分:8)
您不应该将1传递给RSA_private_decrypt
,而是要尝试解密的块的长度,即。 RSA_public_encrypt
的返回值= 128.您在解密时不知道明文的长度!
这个完整的示例程序导致:
128 from encrypt.
1 from decrypt: 'A'
来源:
#include <openssl/rsa.h>
#include <openssl/engine.h>
#include <stdio.h>
int main(int argc, char **argv)
{
RSA *myRSA;
unsigned char cleartext[2560] = "A";
unsigned char encrypted[2560] = { 0 };
unsigned char decrypted[2560] = { 0 };
int resultEncrypt = 0;
int resultDecrypt = 0;
myRSA = RSA_generate_key ( 1024, 65537, NULL, NULL );
resultEncrypt = RSA_public_encrypt ( 1 /* strlen(cleartext) */, cleartext, encrypted, myRSA, RSA_PKCS1_OAEP_PADDING );
printf("%d from encrypt.\n", resultEncrypt);
resultDecrypt = RSA_private_decrypt( 128 /* resultEncrypt */, encrypted, decrypted, myRSA, RSA_PKCS1_OAEP_PADDING);
printf("%d from decrypt: '%s'\n", resultDecrypt, decrypted);
RSA_free ( myRSA );
return 0;
}
答案 1 :(得分:0)
尝试拨打ERR_error_string()
以获取错误的文字说明。