【问题标题】:The result of BN_hex2bn and BN_bn2hex dosen't match?BN_hex2bn 和 BN_bn2hex 的结果不匹配?
【发布时间】:2018-04-24 09:37:23
【问题描述】:

我在我的 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

那么,为什么值会改变?我应该怎么做才能更正我的代码?

【问题讨论】:

  • 我怀疑在打印rsa-&gt;n 等时,您正在打印指针的值,而不是n 指向的大数的值。如果没有看到 RSA 结构,我无法确定。
  • 是的,你的怀疑是对的。感谢您的帮助!

标签: c++ openssl bignum


【解决方案1】:

您正在打印指针地址。

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

【讨论】:

  • 感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-27
  • 2014-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-25
相关资源
最近更新 更多