1. Generation of public and private keys:

  • (1) Randomly pick two large prime numbers p and q, and construct n = p*q;
  • (2) Calculate Euler's totient function φ(n) = (p-1) * (q-1);
  • (3) Randomly pick e such that gcd(e, φ(n)) = 1, i.e., e and φ(n) are coprime; gcd refers to finding the greatest common divisor;
  • (4) Calculate d such that e*d ≡ 1 (mod φ(n)), i.e., d is the multiplicative inverse of e.

2. Encryption process:

  • (1) The information to be encrypted (plaintext) is m, m < n; (because modular arithmetic is to be performed, if m is greater than n, the subsequent operations will not hold; therefore, when the information is larger than n, it should be encrypted in blocks);

  • (2)) The generation of ciphertext c is $$ c = m^e mod (n) $$

3. Decryption

$$ c^d mod (n) = (m^e)^d mod (n) = m^(d*e) mod (n) ; $$

3. Decryption

$$ c^d mod (n) = (m^e)^d mod (n) = m^(d*e) mod (n) ; $$

Why is decryption possible?

Euler's theorem is needed (actually a generalization of Fermat's little theorem)

a^φ(n) ≡ 1 (mod n),

Further generalization: a^(φ(n)k) ≡ 1 (mod n),

We get a^(φ(n)k+1) ≡ a (mod n)

Note that ed ≡ 1 mod φ(N), i.e., ed = 1 + k*φ(N)。

Therefore, $$ M^(de) mod N = M^1 + kφ(N) mod N = M $$

4. The code is as follows

Example

#coding=utf-8 #__author__ = 'ralph' import random def extendedGCD(a, b): #a*xi + b*yi = ri if b == 0: return (1, 0, a) #a*x1 + b*y1 = a x1 = 1 y1 = 0 #a*x2 + b*y2 = b x2 = 0 y2 = 1 while b != 0: q = a / b #ri = r(i-2) % r(i-1) r = a % b a = b b = r #xi = x(i-2) - q*x(i-1) x = x1 - q*x2 x1 = x2 x2 = x #yi = y(i-2) - q*y(i-1) y = y1 - q*y2 y1 = y2 y2 = y return(x1, y1, a) def computeD(fn, e): (x, y, r) = extendedGCD(fn, e) #y maybe < 0, so convert it if y < 0: return fn + y return y def keyGeneration(p,q,e): #generate public key and private key n = p * q fn = (p-1) * (q-1) d = computeD(fn, e) return (d,n) p_v = int(raw_input('Please enter the value of p (decimal)\n')) q_v = int(raw_input('Please enter the value of q (decimal)\n')) e_v = int(raw_input('Please enter the value of e (decimal)\n')) c_v = int(raw_input('Please enter the value of ciphertext c (decimal)\n')) (d,n) = keyGeneration(p_v,q_v,e_v) # Generate d and n m = pow(c_v,d,n) print ("The obtained plaintext m is:"+str(m))

When p value: 18443, q value: 49891, e value: 19,

Ciphertext c value:

70479679275221115227470416418414022368270835483295235263072905459788476483295235459788476663551792475206804459788476428313374475206804459788476425392137704796792458265677341524652483295235534149509425392137428313374425392137341524652458265677263072905483295235828509797341524652425392137475206804428313374483295235475206804459788476306220148

The result obtained will show

The obtained plaintext m is: 88455713