RSA算法的加密、解密
实现思路
具体步骤
- 在给定范围内随机选择两个不相等的质数p和q
- 计算p和q的乘积n
- 计算n的欧拉函数 φ(n)=(p-1)*(q-1)
- 遍历求模反元素d
- 得到公钥和私钥
- 分别进行加密解密操作
下面贴出代码
import random
import math
from random import choice
def getRandomPrime(Nmax):
isPrime = [0]*(Nmax+1)
primeList = []
isPrime[2] = 1
for i in range(3,Nmax,2):
isPrime[i] = 1
for i in range(3,int(math.sqrt((Nmax+1)))+1,2):
if(isPrime[i] == 1):
for j in range(i*i,Nmax+1,2*i):
isPrime[j] = 0
for i in range(2,Nmax+1):
if (isPrime[i]==1):
primeList.append(i)
#使用全局变量,将while里面的取值,取出
global a,b
while True:
p,q = (random.sample(primeList,2))
if(p!=q):
a,b = p,q
break
return a,b
def gcd(a,b):
if a < b:
a, b = b, a
if(b == 0):
return a
while b != 0:
temp = a % b
a = b
b = temp
return a
def selectE(res):
while True:
e = choice(range(100))
#print(e)
x = gcd(e,res)
if ( x == 1 ):
break
return e
def findD(e,res):
for d in range(100000000):
x = (e*d) % res
if x==1:
return d
def encryption(plaintext,public_key):
ciphertext = pow(plaintext,public_key[1])%public_key[0]
return ciphertext
def decryption(ciphertext,private_key):
plaintext = pow(ciphertext,private_key[1])%private_key[0]
return plaintext
if __name__ == "__main__":
#在某个范围内随机选取两个不一样的质数
p,q = getRandomPrime(200)
n= p*q
res = (p - 1) * (q - 1)
e = selectE(res)
d = findD(e,res)
print("公钥:(n,e) = ","(", n,",", e,")")
print("公钥:(n,d) = ","(", n,",", d,")")
public_key = (n,e)
private_key = (n,d)
plaintext = choice(range(100))
ciphertext = encryption(plaintext,public_key)
verification = decryption(ciphertext,private_key)
print("明文:",plaintext)
print("加密后的密文:",ciphertext)
print("解密后的明文:",verification)
下面贴出运行截图
RSA算法的签名和验证签名#
直接贴出代码
import rsa
# 生成密钥
(pubkey, privkey) = rsa.newkeys(1024)
# 明文
message = 'goodmorning'
# 私钥签名
signature = rsa.sign(message.encode(), privkey, 'SHA-1')
# 公钥验证
rsa.verify(message.encode(), signature, pubkey)