4

I'm struggling with generating a RSA private key using given params e,n,d.

m_pKey = EVP_PKEY_new();
RSA* rsa = RSA_new();

rsa->e = e;
rsa->n = n;
rsa->d = d;


EVP_PKEY_assign_RSA(m_pKey, rsa);

this works well for public key generation - I can easily create a .pem file, check it with command line and verify it's correct. However, a private key .pem file seems to lack some additional params.

sudo openssl rsa -noout -text -inform PEM -in priv_test.pem 
unable to load Private Key
139753508435600:error:0D078079:asn1 encoding routines:ASN1_ITEM_EX_D2I:field missing:tasn_dec.c:519:Field=p, Type=RSA
139753508435600:error:04093004:rsa routines:OLD_RSA_PRIV_DECODE:RSA lib:rsa_ameth.c:115:
139753508435600:error:0606F091:digital envelope routines:EVP_PKCS82PKEY:private key decode error:evp_pkey.c:95:
139753508435600:error:0907B00D:PEM routines:PEM_READ_BIO_PRIVATEKEY:ASN1 lib:pem_pkey.c:132:
jww
  • 97,681
  • 90
  • 411
  • 885
Leśny Rumcajs
  • 2,259
  • 2
  • 17
  • 33
  • 1
    @jww: when given n, e, *and* d, factoring is easy. I'll see if I can find the link on stackoverflow. You probably didn't see he slipped *d* in the question. EDIT: The link is http://stackoverflow.com/questions/5747013/how-to-factor-rsa-modulus-given-the-public-and-private-exponent – President James K. Polk Sep 16 '15 at 00:07
  • 1
    @James - you're right, my bad. I made the comment based on the title (if you have `n`, `e` and `d`, then there's nothing got generate; so I took it to mean he only had `n` and `e`). Let me tweak the tile. Also, for OpenSSL, you need all of them - `n`, `e`, `d`, `p`, `q`, `d mod p-1`, `d mod q-1` and `q inv` (IIRC). Otherwise, `RSA_check_key` will segfault. – jww Sep 16 '15 at 00:20
  • Yes, I want to _recreate_ my key from `n`, `e` and `d`. They do completely define my RSA key pair, am I right? Given the link from JamesKPolk it seems that the other params are redundant (plus they don't take part in the encryption / decryption process). So it seems strange that library such as OpenSSL doesn't have any functions to calculate them in case they are not present. – Leśny Rumcajs Sep 16 '15 at 07:30
  • Anyway, jww's explanation + James's solution did the trick, so I guess one of you can change the comment to an answer. – Leśny Rumcajs Sep 17 '15 at 07:16
  • can u share the code @LeśnyRumcajs – Abhishek Garg Nov 01 '19 at 04:38
  • @AbhishekGarg Unfortunately no, sorry. – Leśny Rumcajs Nov 13 '19 at 12:46
  • You can look at the file librsaconverter.c from project RsaConverter on SourceForge: sourceforge.net/p/rsaconverter/code/HEAD/tree/Trunk/src/…. There you will find the implementation of the function SfmToCrt that calculate RSA primes from public modulus and private exponent – Abhishek Garg Nov 18 '19 at 06:50

0 Answers0