Encryption RSA_public_解密失败

Encryption RSA_public_解密失败,encryption,openssl,rsa,Encryption,Openssl,Rsa,我已经为您创建了一个演示程序 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 <opens

我已经为您创建了一个演示程序

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;
}
第一个参数是签名的长度,而不是要提取的摘要的长度。所以这条线应该是这样的:

int result2 = RSA_public_decrypt(RSA_size(publicKey), encrypted, decrypted, publicKey, padding);

此外,您可能应该打开警告。您有一个未初始化的循环变量,它可能会导致问题(我认为循环有时会被完全优化):

for(int i;i)
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];
}