RSA is the most important encryption algorithm,which is a Public-key algorithm. It was put forward by Ron Rivest, Adi Shamir and Len Adleman in 1977.
The content of ARS algorithm is demonstrate by the following picture:
The code of RSA is attached:
def range_prime(start, end):
l = list()
for i in range(start, end+1):
flag = True
for j in range(2, i):
if i % j == 0:
flag = False
break
if flag:
l.append(i)
return l
def generate_keys(p, q):
#numbers = (11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47)
numbers =range_prime(10, 100)
n = p * q
C = (p-1) * (q-1)
e = 0
for x in numbers:
if x < C and C % x > 0:
e = x
break
if e==0:
raise StandardError("e not found")
d = 0
for x in range(1, C):
if(e * x) % C == 1:
d = x
break
if d==0:
raise StandardError("d not found")
return ((n, e), (n, d))
def encrypt(m, pkey):
C, x = pkey
return (m ** x) % C
decrypt = encrypt
if __name__ == '__main__':
pub, pri = generate_keys(47, 79)
L = range(20, 30)
C = list(map(lambda x: encrypt(x, pub), L))
D = list(map(lambda x: decrypt(x, pri), C))
print ("keys:", pub, pri)
print ("message:", list(L))
print ("encrypt:", list(C))
print ("decrypt:", list(D))
The running result is:
keys: (3713, 11) (3713, 1631)
message: [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
encrypt: [406, 3622, 3168, 134, 3532, 263, 1313, 2743, 2603, 1025]
decrypt: [20, 21, 22, 23, 24, 25, 26, 27, 28, 29]