C OpenSSL 1\u 1\u 0e BN\u打印\u fp不工作

C OpenSSL 1\u 1\u 0e BN\u打印\u fp不工作,c,openssl,C,Openssl,我正在使用Openssl 1_1_0e,我无法找出我的代码有什么问题: #include <openssl/rsa.h> int main(){ BIGNUM *bne = NULL; unsigned long e = RSA_F4; RSA *r = NULL; bne = BN_new(); BN_set_word(bne,e); r = RSA_new(); BIG

我正在使用Openssl 1_1_0e,我无法找出我的代码有什么问题:

#include <openssl/rsa.h>

int main(){

    BIGNUM          *bne = NULL; 
    unsigned long   e = RSA_F4;
    RSA             *r = NULL;

    bne = BN_new();
    BN_set_word(bne,e);
    r = RSA_new();

    BIGNUM *n = NULL;
    BIGNUM *d = NULL;
    RSA_get0_key((const RSA *) r, (const BIGNUM **) &n, NULL, (const BIGNUM **) &d);

    BN_print_fp(stdout, n);
    RSA_free(r);
    BN_free(bne);

    return  0;
}

我的代码有什么问题?我觉得很好。

我不能直接测试这段代码,因为我没有RSA\u get0\u密钥,但我说

调用RSA_get0_key()可以获得
n
e
d
参数如果尚未设置,则
*n
*e
*d
将设置为空。否则,它们将被设置为指向各自值的指针。
这些指针直接指向值的内部表示,因此调用方不应释放它们

您正在调用
RSA_new()
但是在RSA对象中没有设置这些BIGNUM-据我所知,
RSA_new()
没有这样做-怎么可能呢,因为生成它们需要很长时间。因此
n
被设置为
NULL
指针;当
BN\u print\u fp
试图读取偏移量16处的
BIGNUM
结构的成员时,就会出现错误。(即
*(uint32_t*)((char*)NULL+16)


最简单的例子:

#include <openssl/rsa.h>
int main(void) {
    BN_print_fp(stdout, NULL);
}

为什么要施放-如果没有明确的施放,就已经很难不射中自己的脚了…你是说
(const BIGNUM**)
部分?没有它就无法工作,因为它不是
const
。有更好的办法吗?是的
const BIGNUM*n
。这将使
n
保持不变,但不会使
&n
保持不变。我错了吗?你试过
const BIGNUM*n,*d
注意
const BIGNUM*
也是
BN\u print\u fp
所期望的:
int BN\u print\u fp(FILE*fp,const BIGNUM*a)。由于您不需要修改由
RSA\u get0\u密钥返回的BNs,这是正确的定义。“我无法直接测试这段代码,因为我没有RSA\u get0\u密钥…”-请尝试
git clonehttps://github.com/openssl/openssl.git
。默认分支是1.1.0。@jww是的,我想我不需要测试它:)
#include <openssl/rsa.h>
int main(void) {
    BN_print_fp(stdout, NULL);
}
% valgrind ./a.out
[...]
==16062== Invalid read of size 4
==16062==    at 0x4EFA5F4: BN_print (in /lib/x86_64-linux-gnu/libcrypto.so.1.0.0)
==16062==    by 0x4EFA743: BN_print_fp (in /lib/x86_64-linux-gnu/libcrypto.so.1.0.0)
==16062==    by 0x108745: main (in /home/user/tmp/a.out)
==16062==  Address 0x10 is not stack'd, malloc'd or (recently) free'd
[...]