# How to generate private SSH RSA key from given primes?

I have two primes and public exponent. How I can generate private key with this values and "ssh-rsa" format?

• If you are asking how to find the private key, that is easy; calculate $\phi(n) = (p-1)(q-1)$ then find $d \cdot e = 1 \bmod \phi(n)$ by Ext-GCD, then the RSA private key with CRT enabled is $(n,e,d,p,q,d_p$ where $d_p = D \bmod (p-1)$. If you are asking how to use this in SSH then better to be asked in SuperUser.SE. Jan 27 '21 at 19:48
• @kelalaka: not quite; standard CRT (PKCS1) requires both $d \mod (p-1)$ and $d \mod (q-1)$ plus $q^{-1} \mod p$. (PGP skips the first two which are cheaper to recompute, and reverses p and q and stores $p^{-1} \mod q$.) I don't know any implementation with a user function for this; OpenSSH/OpenSSL, NSS, gnutls, Java all require programming which is probably better on stackoverflow than superuser. Jan 28 '21 at 0:29
• @dave_thompson_085 so; all generated by default during key-gen . $(n,e,d,p,q,d_p,d_q,q_p^{-1})$ where $d_p:=d \bmod{p−1}$, $d_q:= d \bmod{q−1}$ and $q_p^{-1} := q^{-1} \bmod {q-1}$. AFAIK it was still working if some missing. Jan 28 '21 at 1:00
• Probably best just find a key generation implementation, strip out the part where random primes are generated and then inject the static primes and the public exponent into the function. Once you have a key pair you can simply store it as PKCS#1 encoded private key, if I'm not mistaken. But storing it as a SSH private key is more secure, which means you'd need a SSH library as well. Sep 8 '21 at 21:20