c++ - OpenSSL RSA 库抛出异常

标签 c++ dll openssl

我想将 RSA 加密包括到我使用 Visual Studio 2017 用 C++ 编写的 DLL 项目中,我认为 OpenSSL 是完美的。我在 Additional Include DirectoriesAdditional 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.01.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/

相关文章:

c# - 调用具有反射和配置依赖项的 DLL

使用 OpenSSL 计算并打印文件的 SHA256 哈希值

openssl - 将表示为 HEX 字符串的 X.509 证书转换为 PEM 编码的 X.509 证书

c++ - 添加了对 .lib 项目的引用 - 项目不使用 .cpp 文件?

c++ - Qt OSX全屏窗口上层菜单栏和Dock

javascript - Emscripten 可以将 LLVM 编译为基于 Web 的程序语言的 JavaScript

c - OpenSSL AES_ecb_encrypt 填充选项?

c++ - 为什么 C++ 参数范围会影响命名空间内的函数查找?

dynamic - 从 Azure Blob 加载依赖的 DLL

c# - 如何在其他asp.net 项目中使用用C# 编写的DLL?