源码如下:
class MyRSA():
def get_d(self, e, φ):
i=0
while True:
if (e*i)%φ == 1:
return i
else:
i+=1
def get_e(self, φ):
e_set = ()
for i in range(1,φ):
if self.isPrime(φ,i):
e_set += (i,)
return e_set
def isPrime(self, a, b):
if(a < b):
tmp = a
a = b
b = tmp
c = a % b
while c != 0:
a = b
b = c
c = a % b
if (b == 1):
return True
else:
return False
def get_miyue(self):
print('现在开始生成密钥')
p = int(input('请输入p:'))
q = int(input('请输入q:'))
n = p * q
φ = (p - 1) * (q - 1)
print('有如下可选的e:', self.get_e(φ))
e = int(input('选择一个e:'))
d = self.get_d(e, φ)
print('这是最小的d:', d)
self.password = (d, n)
return (n, e, d)
def jiami(self, x):
n, e, d = self.get_miyue()
return pow(x, e, n)
def jiemi(self, y):
d, n = self.password
return pow(y, d, n)
def rsaMain(self):
x = int(input('请输入明文:'))
print('现在进行加密操作')
y = self.jiami(x)
print('明文加密的结果是:',y)
print('现在进行解密操作')
print('密文解密的结果是:',self.jiemi(y))
if __name__ == '__main__':
MyRSA().rsaMain()