簡體   English   中英

rsa_public_encrypt返回-1,錯誤0x0406B07A

[英]rsa_public_encrypt returns -1, error 0x0406B07A

我正在嘗試使用RSA_public_encrypt加密數據,但是它似乎不起作用( retEnc始終為-1)。 我還嘗試使用ERR_get_errorERR_error_string查找有關該錯誤的更多信息。

這是代碼:

RSA *rsaPkey = NULL;

FILE *pemFile;
fopen_s(&pemFile, filename.c_str(), "r");
rsaPkey         = PEM_read_RSA_PUBKEY(pemFile, &rsaPkey, NULL, NULL);
fclose(pemFile);

if(rsaPkey == NULL)
    throw "Error pubkey file";

int size = RSA_size(rsaPkey);
unsigned char *encrypted;
encrypted = new unsigned char[size];

string instr  = "test";
int length = instr.length();
unsigned char *in = (unsigned char *)(instr.c_str());

unsigned long errorTrack = ERR_get_error() ;

int retEnc = RSA_public_encrypt(length, in, (unsigned char *)encrypted, rsaPkey, RSA_NO_PADDING);
errorTrack = ERR_get_error() ;
char *errorChar = new char[120];
errorChar = ERR_error_string(errorTrack, errorChar);

ERR_error_string給我error:0406B07A:lib(4):func(107):reason(122)

我如何找到有關此的更多詳細信息,在哪里可以找到庫4和函數107?

當我嘗試使用openssl cli和相同的公鑰文件進行加密時,加密工作正常。

 ERR_error_string gives me error:0406B07A:lib(4):func(107):reason(122) 

我如何找到有關此的更多詳細信息,在哪里可以找到庫4和函數107?

我發現從OpenSSL錯誤代碼中了解更多信息的最簡單方法是:

$ openssl errstr 0406B07A
error:0406B07A:rsa routines:RSA_padding_add_none:data too small for key size

char *errorChar = new char[120];
errorChar = ERR_error_string(errorTrack, errorChar);

另外,在ERR_error_string手冊頁中

ERR_error_string()生成代表錯誤代碼e的人類可讀字符串,並將其放在buf處。 buf必須至少為256個字節長。 如果buf為NULL,則錯誤字符串將放置在靜態緩沖區中。 請注意,該函數不是線程安全的,並且不檢查緩沖區的大小。 請改用ERR_error_string_n()。

由於您使用的是C ++,類似這樣的操作可能會更容易:

std::string errorMsg;
errorMsg.resize(256);

(void)ERR_error_string(errorTrack, &errorMsg[0]);

上面,您正在使用std::string來管理資源。 要獲取非常量指針,請獲取第一個元素的地址。

如果需要,可以使用以下方法正確調整errorMsg大小:

(void)ERR_error_string(errorTrack, &errorMsg[0]);
errorMsg.resize(std::strlen(errorMsg.c_str()));

這是另一個使C ++易於使用的技巧。

typedef unsigned char byte;
...

std::string encrypted;
int size = RSA_size(rsaPkey);

if (size < 0)
    throw std::runtime_error("RSA_size failed");

// Resize to the maximum size
encrypted.resize(size);
...

int retEnc = RSA_public_encrypt(length, in, (byte*)&encrypted[0], rsaPkey, RSA_NO_PADDING);

if (retEnc < 0)
    throw std::runtime_error("RSA_public_encrypt failed");

// Resize the final string now that the size is known
encrypted.resize(retEnc );

上面,您正在使用std::string來管理資源。 要獲取非常量指針,請獲取第一個元素的地址。

同樣, NO_PADDING通常不是一個好主意。 您通常需要OAEP填充。 有關填充如何影響最大大小的信息,請參見RSA_public_encrypt手冊頁中的注釋。


C ++可以使使用OpenSSL更容易。 您可以使用unique_ptr避免顯式調用EVP_CIPHER_CTX_free的函數。 請參閱EVP對稱加密和解密| OpenSSL Wiki上的C ++程序unique_ptr和OpenSSL的STACK_OF(X509)*如何將PKCS7_sign結果獲取為char *或std :: string等。

在您的情況下,這些似乎對管理資源很有幫助

using FILE_ptr = std::unique_ptr<FILE, decltype(&::fclose)>;
using RSA_ptr = std::unique_ptr<RSA, decltype(&::RSA_free)>;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM