/* generate an RSA key pair */ public static void KEY_PAIR(RAND rng, int e, rsa_private_key PRIV, rsa_public_key PUB) { // IEEE1363 A16.11/A16.12 more or less int n = PUB.n.getlen() / 2; FF t = new FF(n); FF p1 = new FF(n); FF q1 = new FF(n); for (;;) { PRIV.p.random(rng); while (PRIV.p.lastbits(2) != 3) { PRIV.p.inc(1); } while (!FF.prime(PRIV.p, rng)) { PRIV.p.inc(4); } p1.copy(PRIV.p); p1.dec(1); if (p1.cfactor(e)) { continue; } break; } for (;;) { PRIV.q.random(rng); while (PRIV.q.lastbits(2) != 3) { PRIV.q.inc(1); } while (!FF.prime(PRIV.q, rng)) { PRIV.q.inc(4); } q1.copy(PRIV.q); q1.dec(1); if (q1.cfactor(e)) { continue; } break; } PUB.n = FF.mul(PRIV.p, PRIV.q); PUB.e = e; t.copy(p1); t.shr(); PRIV.dp.set(e); PRIV.dp.invmodp(t); if (PRIV.dp.parity() == 0) { PRIV.dp.add(t); } PRIV.dp.norm(); t.copy(q1); t.shr(); PRIV.dq.set(e); PRIV.dq.invmodp(t); if (PRIV.dq.parity() == 0) { PRIV.dq.add(t); } PRIV.dq.norm(); PRIV.c.copy(PRIV.p); PRIV.c.invmodp(PRIV.q); return; }
/* Miller-Rabin test for primality. Slow. */ public static bool prime(FF p, RAND rng) { int i, j, s = 0, n = p.length; bool loop; FF d = new FF(n); FF x = new FF(n); FF unity = new FF(n); FF nm1 = new FF(n); int sf = 4849845; // 3*5*.. *19 p.norm(); if (p.cfactor(sf)) { return(false); } unity.one(); nm1.copy(p); nm1.sub(unity); nm1.norm(); d.copy(nm1); while (d.parity() == 0) { d.shr(); s++; } if (s == 0) { return(false); } for (i = 0; i < 10; i++) { x.randomnum(p, rng); x.pow(d, p); if (comp(x, unity) == 0 || comp(x, nm1) == 0) { continue; } loop = false; for (j = 1; j < s; j++) { x.power(2, p); if (comp(x, unity) == 0) { return(false); } if (comp(x, nm1) == 0) { loop = true; break; } } if (loop) { continue; } return(false); } return(true); }