0

I use openssl in my C++ project, but a problem make me confused.

  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;

To my surprise, the output are the following:

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

So, Why does the value changed? What should I do to correct my code?

unwind
  • 391,730
  • 64
  • 469
  • 606
Nash
  • 43
  • 9
  • 1
    I suspect that when printing `rsa->n` etc you are printing the value of the pointer, not the value of the big number pointed to by `n`. Without seeing the `RSA` structure I can't be sure. – Richard Critten Apr 24 '18 at 09:47
  • Yes, your suspicion is right. Thanks for your help! – Nash Apr 24 '18 at 11:32

1 Answers1

0

You are printing pointer addresses.

From the docs we can see that the members of RSA are pointers to BIGNUM:

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

Also from the docs, we learn that:

The basic object in this library is a BIGNUM. It is used to hold a single large integer. This type should be considered opaque and fields should not be modified or accessed directly.

Use BN_print or BN_print_fp to print a BIGNUM.

Max Vollmer
  • 8,412
  • 9
  • 28
  • 43