# pike.git/lib/modules/Crypto.pmod/RSA.pike

Branch: Tag:

## 2012-12-07

#### 2012-12-07 16:54:52 by Henrik GrubbstrĂ¶m (Grubba) <grubba@grubba.org>

• 15c1487e5a30e46614151c9ea4f3384d10152060 (22 lines) (+18/-4) [ Show | Annotate ]
Branch: 7.9
Crypto.RSA: generate_key() now ensures that the key has the correct size.

Compensate for that multiplication of two n-bit values is most likely to
result in a (2n-1)-bit value.

Fixes [bug 6620 (#6620)].

303: Inside #if constant(Gmp) && constant(Gmp.mpz) && constant(Crypto.Hash)
if (bits < 128)    error( "Ridiculously small key.\n" );    +  /* NB: When multiplying two n-bit integers, +  * you're most likely to get an (2n - 1)-bit result. +  * We therefore add an extra bit to s2. +  * +  * cf [bug 6620]. +  */ +     int s1 = bits / 2; /* Size of the first prime */ -  int s2 = bits - s1; +  int s2 = 1 + bits - s1;       string msg = "This is a valid RSA key pair\n";       do    { -  Gmp.mpz p = get_prime(s1, r); -  Gmp.mpz q = get_prime(s2, r); +  Gmp.mpz p; +  Gmp.mpz q; +  Gmp.mpz mod; +  do { +  p = get_prime(s1, r); +  q = get_prime(s2, r); +  mod = [object(Gmp.mpz)](p * q); +  } while (mod->size() != bits);    Gmp.mpz phi = [object(Gmp.mpz)](Gmp.mpz([object(Gmp.mpz)](p-1))*    Gmp.mpz([object(Gmp.mpz)](q-1)));
328: Inside #if constant(Gmp) && constant(Gmp.mpz) && constant(Crypto.Hash)
if (gs[1] < 0)    gs[1] += phi;    -  set_public_key( [object(Gmp.mpz)](p * q), pub); +  set_public_key(mod, pub);    set_private_key(gs[1], ({ p, q }));       } while (!sha_verify(msg, sha_sign(msg, r)));