我想将 RSA 加密包括到我使用 Visual Studio 2017
用 C++ 编写的 DLL
项目中,我认为 OpenSSL 是完美的。我在 Additional Include Directories
和 Additional Library Directories
中添加了我的 OpenSSL 文件夹的正确路径,我添加了 libcrypto.lib/libeay32.lib
到 附加依赖项
。项目可以编译,但是当我想使用 rsa.h
中的某些函数(如 RSA_size
)时,我收到如下异常:
Exception thrown at 0x0F17EB64 (libcrypto-1_1.dll) in Win32Project1.exe: 0xC0000005: Access violation reading location 0x00000004.
我假设这是因为库中的某个指针变为 NULL,但我找不到原因。 This告诉我用常规的 exe 应用程序尝试这个库,但即使使用最简单的代码也会出现同样的错误
#include <openssl/rsa.h>
int main()
{
RSA *m_rsa = RSA_new();
RSA_size(m_rsa);
return 0;
}
我已经尝试在版本 1.1.0
和 1.0.2
中实现 OpenSSL,结果相同。
RSA_new 正确分配新的 RSA 实例,ERR_get_error() 返回“0”。
最佳答案
查看库文档:
If the allocation fails, RSA_new() returns NULL and sets an error code that can be obtained by ERR_get_error(3). Otherwise it returns a pointer to the newly allocated structure.
RSA_new 可以失败并返回一个空指针。
使用 RSA_size()
将使用此空指针(地址 0)访问 RSA 结构的字段。如果这个字段在偏移量4处,你会尝试访问地址4(基地址0+偏移量4),你会得到一个“访问冲突读取位置0x00000004”。
因此,检查返回的指针。如果为 null,请检查错误代码以查看发生了什么...
图书馆链接:
编辑:
另一件需要知道的事情是,在调用 RSA_size()
( see documentation ) 时,RSA->n
不应为 null。 n
用于模数,因此在生成或设置 key 之前不能调用 RSA_size()
。
请参阅此示例 ( permalink here):
#include <openssl/rsa.h>
int main ()
{
RSA* rsa = RSA_new ();
std::cout << "rsa pointer = " << rsa << std::endl;
std::cout << "rsa->n = " << rsa->n << std::endl;
RSA_size ( rsa ); // Seg fault.
return EXIT_SUCCESS;
}
输出:
rsa pointer = 0x12d9c20
rsa->n = 0
bash: line 7: 10149 Segmentation fault (core dumped) ./a.out
关于c++ - OpenSSL RSA 库抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48893717/