使用python实现rsa算法代码

rsa算法是一种非对称加密算法，是现在广泛使用的公钥加密算法，主要应用是加密信息和数字签名。

(n,e)是公钥，(n,d)是私钥。(n,d)是秘密的。alice将她的公钥(n,e)传给bob，而将她的私钥(n,d)藏起来。

#!/usr/bin/env python
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 n in numbers:
if n < c and c % n > 0:
e = n
break
if e==0:
raise standarderror(“e not found”)
d = 0
for n in range(2, c):
if(e * n) % c == 1:
d = n
break
if d==0:
raise standarderror(“d not found”)
return ((n, e), (n, d))
def encrypt(m, key):
c, x = key
return (m ** x) % c
decrypt = encrypt
if __name__ == ‘__main__’:
pub, pri = generate_keys(47, 79)
l = range(20, 30)
c = map(lambda x: encrypt(x, pub), l)
d = map(lambda x: decrypt(x, pri), c)
print “keys:”, pub, pri
print “message:”, l
print “encrypt:”, c
print “decrypt:”, d
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: [20l, 21l, 22l, 23l, 24l, 25l, 26l, 27l, 28l, 29l]

Posted in 未分类