from math import sqrt
def Cnotrol():
d = 0
x = int(input('请输入你的选择的功能::RSA加密为0,RSA解密为1,分解查找P与Q为2,退出请按9:'))
qt = 1
while qt:
if x == 0:
print('----------------加密----------------')
print('---------请输入P,Q,E,M(明文)---------')
p = int(input('输入P:'))
q = int(input('输入Q:'))
e = int(input('输入E:'))
Flag = apnjudg(p, q, e)
if Flag == 0:
m = int(input('请输入M:'))
encryption(m, e, p * q)
Cnotrol()
else:
break
elif x == 1:
print('----------------解密----------------')
print('---------请输入P,Q,E,C(密文)---------')
p = int(input('输入P:'))
q = int(input('输入Q:'))
e = int(input('输入E:'))
fi = (p - 1) * (q - 1)
for i in range(fi): # 求逆元d
if e * i % fi == 1:
d = i
break
print("逆元d的值为:", d)
apnjudg(p, q, d)
c = int(input('请输入C:'))
decode(c, d, p * q)
Cnotrol()
elif x == 2:
print('----------------拆解素数乘积----------------')
n = int(input('输入乘积N:'))
broken(n)
Cnotrol()
else:
print("感谢您的使用")
break
qt = 0
def encryption(m, e, n):
s = m % n
for i in range(1, e):
s = (s * (m % n)) % n
print('你所加密的密文是:', s)
# 解密
def decode(c, d, n):
s = c % n
for i in range(1, d):
s = (s * (c % n)) % n
print('你所解密的明文是:', s)
# p,q,e质数判断
def apnjudg(p, q, e):
Li = [p, q, e]
flag = 0
for x in range(0, 3):
if int(Li[x]) > 2:
# 查看因子
# sqrt()平方根函数减小计算周期
for i in range(2, int(sqrt(Li[x]))+1):
if (int(Li[x]) % i) == 0:
print(int(Li[x]), "不是质数")
print(i, "乘于", int(Li[x]) // i, "是", int(Li[x]))
flag += 1
break
else:
continue
if flag == 0:
print(int(Li[x]), "是质数")
else:
print("QAQ您的输入有误(存在非质数),程序退出QAQ")
break
# 如果输入的数字小于或等于 2,不是质数
else:
print(int(Li[x]), "不是质数")
flag += 1
continue
return flag
# 拆解获得素数p,q
def broken(n):
if n < 10000000:
for i in range(1, 10000):
for t in range(1, 10000):
if n == i * t:
print(i, t)
break
if __name__ == '__main__':
Cnotrol()
apnjudg(p, q, e)n=p * q
s = m % n
for i in range(1, e):
s = (s * (m % n)) % n
解密密钥d,在讲解解密函数之前,我们先讲讲如何得到d
由一个函数de=1 mod Φ(n)---->即满足条件(de)%Φ(n)=1, 我们可以将d求出来(这个公式用到了欧拉定理)
根据公式我们就好求d了,d即e的逆元
功能代码如下:
for i in range(fi): #求逆元d
if e * i % fi == 1:
d = i
break