/* RSA encryption with the public key */ public static void ENCRYPT(rsa_public_key PUB, sbyte[] F, sbyte[] G) { int n = PUB.n.getlen(); FF f = new FF(n); FF.fromBytes(f, F); f.power(PUB.e, PUB.n); f.toBytes(G); }
public static void Main(string[] args) { int i; int RFS = RSA.RFS; string message = "Hello World\n"; rsa_public_key pub = new rsa_public_key(ROM.FFLEN); rsa_private_key priv = new rsa_private_key(ROM.HFLEN); sbyte[] ML = new sbyte[RFS]; sbyte[] C = new sbyte[RFS]; sbyte[] RAW = new sbyte[100]; RAND rng = new RAND(); rng.clean(); for (i = 0; i < 100; i++) { RAW[i] = (sbyte)(i); } rng.seed(100, RAW); //for (i=0;i<10;i++) //{ Console.WriteLine("Generating public/private key pair"); RSA.KEY_PAIR(rng, 65537, priv, pub); sbyte[] M = message.GetBytes(); Console.Write("Encrypting test string\n"); sbyte[] E = RSA.OAEP_ENCODE(M, rng, null); // OAEP encode message M to E RSA.ENCRYPT(pub, E, C); // encrypt encoded message Console.Write("Ciphertext= 0x"); RSA.printBinary(C); Console.Write("Decrypting test string\n"); RSA.DECRYPT(priv, C, ML); sbyte[] MS = RSA.OAEP_DECODE(null, ML); // OAEP decode message message = StringHelperClass.NewString(MS); Console.Write(message); //} RSA.PRIVATE_KEY_KILL(priv); }
/* 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; }