Generate an RSA key pair Given a positive integer \$N &gt;= 4\$, output an RSA key pair (both the private and the public key) whose key length is \$N\$ bits.

The RSA key generation algorithm is as follows:


Choose an \$N\$-bit semiprime \$n\$. Let the prime factors of \$n\$ be \$p\$ and \$q\$.
Compute \$\lambda(n) = LCM(p-1, q-1)\$.
Choose an integer \$e\$ such that \$1 &lt; e &lt; \lambda(n)\$ and \$GCD(e, \lambda(n)) = 1\$.
Compute \$d \equiv e^{−1} \pmod {\lambda(n)}\$.


The public key is composed of \$n\$ and \$e\$. The private key is \$d\$.

Rules


You may assume that there exists at least one semiprime \$n\$ with bit length \$N\$.
Output may be in any consistent and unambiguous format.
\$e\$ and \$n\$ must be chosen from discrete uniform distributions.
You may assume that \$N\$ is less than or equal to the maximum number of bits for integers representable in your language, if your language has such a restriction.
JavaScript (ES7), 190 bytes
Returns [n,e,d].

f=N=&gt;(R=Math.random,g=d=&gt;d&amp;&amp;p%--d?g(d):d)(p=g(p=n=R()*2**N|0))&lt;2&amp;n&gt;1&amp;(L=(q=n/p-1)*--p/(G=(a,b)=&gt;b?G(b,a%b):a)(p,q))&gt;2?(g=_=&gt;G(L,e=R()*(L-2)+2|0)&lt;2?(h=d=&gt;d*e%L&lt;2?[n,e,d]:h(-~d))():g())():f(N)

Try it online!
Because of the limited size of the call stack, this may fail for \$N&gt;13\$.
Commented
f = N =&gt;
  (
    R = Math.random,
    // helper function returning the highest divisor of p
    g = d =&gt; d &amp;&amp; p % --d ? g(d) : d
  )(
    // choose n and compute its highest divisor p
    p = g(p = n = R() * 2 ** N | 0)
  )
  // make sure that p is prime
  &lt; 2 &amp;
  // and that n is greater than 1
  n &gt; 1 &amp;
  // compute L = λ(n) = LCM(p - 1, q - 1) = (p - 1) * (q - 1) / GCD(p - 1, q - 1),
  // using the helper function G that returns GCD(a, b)
  (L = (q = n / p - 1) * --p / (G = (a, b) =&gt; b ? G(b, a % b) : a)(p, q))
  // make sure that L &gt; 2
  &gt; 2 ?
    // helper function to choose e such that GCD(e, L) = 1
    (g = _ =&gt; G(L, e = R() * (L - 2) + 2 | 0) &lt; 2 ?
      // helper function to compute d such that d * e mod L = 1
      (h = d =&gt; d * e % L &lt; 2 ? [n, e, d] : h(-~d))()
    :
      g()
    )()
  :
    f(N)