我正在尝试使用RSA_public_encrypt
加密数据,但它似乎不起作用(retEnc
总是-1)。我还尝试使用ERR_get_error
和ERR_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
man page:
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
来管理资源。要获取非const指针,请获取第一个元素的地址。
如果你愿意,你可以正确调整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
来管理资源。要获取非const指针,请获取第一个元素的地址。
此外,NO_PADDING
通常是一个坏主意。您通常需要OAEP填充。有关填充如何影响最大尺寸,请参阅RSA_public_encrypt
man page中的注释。
C ++可以使OpenSSL更容易使用。您可以通过使用EVP_CIPHER_CTX_free
避免显式调用unique_ptr
等函数。请参阅OpenSSL wiki,EVP Symmetric Encryption and Decryption | C++ Programs,unique_ptr and OpenSSL's STACK_OF(X509)*等上的How to get PKCS7_sign result into a char * or std::string。
在您的情况下,它看起来像these would be helpful来管理资源:
using FILE_ptr = std::unique_ptr<FILE, decltype(&::fclose)>;
using RSA_ptr = std::unique_ptr<RSA, decltype(&::RSA_free)>;