gpt4 book ai didi

encryption - RSA_public_decrypt 失败

转载 作者:行者123 更新时间:2023-12-01 13:35:06 27 4
gpt4 key购买 nike

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

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

最佳答案

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];
}

关于encryption - RSA_public_decrypt 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44131568/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com