我为
创建了一个演示程序1) Generating RSA private and public key pair.
2) RSA sign with private key and then using public key to for checking.
But my RSA_public_decrypt return -1;
代码:
#include <memory>
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <cassert>
#define ASSERT assert
#include <iostream>
using namespace std;
int padding = RSA_PKCS1_PADDING;
#define NONCE_LEN 32
int main(int argc, char* argv[])
{
unsigned char encrypted[4098]={};
unsigned char decrypted[4098]={};
uint8_t nonceB[NONCE_LEN]={"FGHIJKLMNOPQRSTUVWXYZ0123456789"};
uint8_t nonceA[NONCE_LEN]={"yogendra singh the developer of"};
uint8_t nonceRes[NONCE_LEN];
int rc;
BIGNUM *e = BN_new();
rc = BN_set_word(e, RSA_F4);
assert(rc==1);
RSA *rsaKeyPair = RSA_new();
rc = RSA_generate_key_ex(rsaKeyPair, 2048, e, NULL);
ASSERT(rc ==1);
RSA *privateKey = RSA_new();
privateKey= RSAPrivateKey_dup(rsaKeyPair);
RSA *publicKey = RSA_new();
publicKey= RSAPublicKey_dup(rsaKeyPair);
for(int i;i<NONCE_LEN;i++){
nonceRes[i]=nonceA[i]^nonceB[i];
}
int result = RSA_private_encrypt(NONCE_LEN,nonceRes,encrypted,privateKey,padding);
int result2 = RSA_public_decrypt(NONCE_LEN,encrypted,decrypted,publicKey,padding);
cout<<"encrypted len:"<<result<<endl;
RSA_free(privateKey);
RSA_free(publicKey);
BN_free(e);
cout<<"decrypted len:"<<result2<<endl;
cout<<endl <<"decoded String B:";
for(int i =0;i<NONCE_LEN;i++){
char x=nonceB[i]^decrypted[i];
cout<<x;
}
cout<<endl <<"decoded String A:";
for(int i =0;i<NONCE_LEN;i++){
char x=nonceA[i]^decrypted[i];
cout<<x;
}
cout<<endl;
return 0;
}
输出
encrypted len:256
decrypted len:-1
答案 0 :(得分:3)
RSA_public_decrypt
的第一个参数是签名的长度,不将提取的摘要的长度。所以该行应该是这样的:
int result2 = RSA_public_decrypt(RSA_size(publicKey), encrypted, decrypted, publicKey, padding);
此外,你应该打开警告。你有一个未初始化的循环变量可能会导致问题(我认为循环有时会被完全优化):
for(int i;i<NONCE_LEN;i++){
nonceRes[i]=nonceA[i]^nonceB[i];
}