BN_hex2bn和BN_bn2hex的结果不匹配?

时间:2018-04-24 09:37:23

标签: c++ openssl bignum

我在我的C ++项目中使用openssl,但问题让我感到困惑。

  RSA *rsa = RSA_generate_key(kBits, kExp, 0, 0);
  cout << "rsa->n: " << endl
       << rsa->n << endl
       << "rsa->d: " << endl
       << rsa->d << endl
       << "rsa->e: " << endl
       << rsa->e << endl;

  char *n_b = BN_bn2hex(rsa->n);
  char *d_b = BN_bn2hex(rsa->d);
  char *e_b = BN_bn2hex(rsa->e);

  n_s = std::string(n_b);
  d_s = std::string(d_b);
  e_s = std::string(e_b);

  RSA *pRSAKey = RSA_new();

  BN_hex2bn(&pRSAKey->n, n_s.c_str());
  BN_hex2bn(&pRSAKey->d, d_s.c_str());
  BN_hex2bn(&pRSAKey->e, e_s.c_str());

  cout << "pRSAKey->n: " << endl
       << pRSAKey->n << endl
       << "pRSAKey->d: " << endl
       << pRSAKey->d << endl
       << "pRSAKey->e: " << endl
       << pRSAKey->e << endl;

令我惊讶的是,输出结果如下:

rsa->n:
0xee2200
rsa->d:
0xee2220
rsa->e:
0xee2240
pRSAKey->n:
0xee2fa0
pRSAKey->d:
0xee2fc0
pRSAKey->e:
0xee3390

那么,为什么价值会发生变化?我该怎么做才能纠正我的代码?

1 个答案:

答案 0 :(得分:0)

您正在打印指针地址。

docs我们可以看到RSA的成员是pointersBIGNUM

struct
    {
    BIGNUM *n;              // public modulus
    BIGNUM *e;              // public exponent
    BIGNUM *d;              // private exponent
    BIGNUM *p;              // secret prime factor
    BIGNUM *q;              // secret prime factor
    BIGNUM *dmp1;           // d mod (p-1)
    BIGNUM *dmq1;           // d mod (q-1)
    BIGNUM *iqmp;           // q^-1 mod p
    // ...
    };
RSA

同样来自docs,我们了解到:

  

此库中的基本对象是BIGNUM。它用来举行   单个大整数。此类型应视为不透明和字段   不应该直接修改或访问。

使用BN_printBN_print_fp打印BIGNUM