3

I have the n, e, d component from other devices not the OpenSSL. I want to encrypt and decrypt using the OpenSSL API. But decrypt always fails after encrypt.

I use RSA_set0_key for private key (n, e, d) setting, and RSA_private_encrypt is OK, but RSA_public_decrypt fails always. I wonder why it fails.

Why does RSA_public_decrypt fail?

jww
  • 97,681
  • 90
  • 411
  • 885
ydgoo
  • 53
  • 5
  • 1
    Fails how? Where is your code? Where is the error message? – President James K. Polk Jul 07 '17 at 12:23
  • Note 'private_encrypt' and 'public_decrypt' are really signature not encryption, and (as documented) not standard; the names are a misleading historical relic from the 1990s. That said, it works for me in 1.1.0, and the obvious variant setting n,e,d directly works in 1.0.2 1.0.1 1.0.0 and 0.9.8. mcve? – dave_thompson_085 Jul 09 '17 at 06:55

2 Answers2

3

RSA_set0_key() with N, E, D is possible?

Yes. RSA_set0_key is documented in the OpenSSL man pages. Its signature is:

int RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d);

The description is:

The n, e and d parameter values can be set by calling RSA_set0_key() and passing the new values for n, e and d as parameters to the function. The values n and e must be non-NULL the first time this function is called on a given RSA object. The value d may be NULL. On subsequent calls any of these values may be NULL which means the corresponding RSA field is left untouched. Calling this function transfers the memory management of the values to the RSA object, and therefore the values that have been passed in should not be freed by the caller after this function has been called.

Further down, under RETURN VALUES:

RSA_set0_key(), RSA_set0_factors and RSA_set0_crt_params() return 1 on success or 0 on failure.


I use RSA_set0_key for key(N, E, D) setting, and RSA_private_encrypt is OK, but RSA_public_decrypt fails always

Its hard to say what is going on with your use of RSA_public_decrypt. Perhaps you can add some code, state what the return value is, and state the value of ERR_get_err when the function fails.

In the meantime, you may need your RSA object to have the extended private key parameters, like p, q, dp, dq, and qInv. Those are the Chinese Remainder Theorem (CRT) parameters, and they are set with RSA_set0_crt_params. Also see Unable to decrypt without Chinese Remainder Theorem factors? on the OpenSSL users mailing list.

jww
  • 97,681
  • 90
  • 411
  • 885
  • OpenSSL _can_ do RSA privatekey operations with only d, albeit less efficiently. The mail you link clearly explains the problem was in _reading_ a non-CRT key (from PEM), not using a key that is correct in memory. – dave_thompson_085 Jul 09 '17 at 06:33
0

I found the reason. After inversing the order of key (n, d) with using the OS2IP, it works. Thanks for help.

ydgoo
  • 53
  • 5