rsa算法原理
1978年美国麻省理工学院的三名密码学者R.L.Rivest,A.Shamir和L.Adleman提出了一种基于大合数因子分解困难性的公开密钥密码,简称为RSA密码。RSA密码被誉为是一种风格幽雅的公开密钥密码。既可用于加密,又可用于数字签名,安全、易懂,它已成为目前应用最广泛的公开密钥密码。
RSA算法过程如下:
快速乘法算法求幂
例如求x16,直接计算的话需做15次乘法。
如果重复对每个部分结果做平方运算即求x,x2,x4,x8,x16则只需4次乘法。
在这里插入代码片
def fastExpMod(b, e, m):
result = 1
while e != 0:
if (e&1) == 1:
# ei = 1, then mul
result = (result * b) % m
e >>= 1
# b, b^2, b^4, b^8, ... , b^(2^n)
b = (b*b) % m
return result
class rsatest():
#***********Begin**************
def __init__(self,e,d,n):
self.d = d
self.e = e
self.n = n
def encrypt (self,p):
self.p = p
return fastExpMod(self.p,self.e,self.n)
def decrypt(self,enc):
self.enc = enc
return fastExpMod(self.enc,self.d,self.n)
#************End***************
def Evidence(p,e,d,n):
"""
:param p: 明文
:param e: 公钥
:param d: 私钥
:param n: 模
"""
rsa = rsatest(e,d,n)
enc = rsa.encrypt(p)
print(enc)
detext = rsa.decrypt(enc)
print(detext)
#***********Begin**************
if __name__ == "__main__":
str1, str2 ,str3,str4 = input().split()
p = int(str1)
e = int(str2)
d = int(str3)
n = int(str4)
Evidence(p,e,d,n)