Rabin公钥密码算法简单实现
作者:互联网
def Square_and_Multiply(m,e,n): ##模重复平方算法
c=1
k=bin(e)[2:]
for i in range(0,len(k)):
c=c*c%n
if(k[i]=='1'):
c=c*m%n
return c
def encode_Rabin(m,p,q): ##加密算法
c=m*m%(p*q)
return c
def decode_Rabin(c,p,q): ##解密算法
s,t=extend_Euclid(p,q)
u=Square_and_Multiply(c,int((p+1)/4),p)
v=Square_and_Multiply(c,int((q+1)/4),q)
m1=(u*t*q+v*s*p)%(p*q)
m2=(u*t*q-v*s*p)%(p*q)
return m1,p*q-m1,m2,p*q-m2
def extend_Euclid(a,b): #扩展欧几里得算法
r,s,t=a,1,0
r1,s1,t1=b,0,1
while r1!=0:
q=int(r/r1)
tem1,tem2,tem3=r-q*r1,s-q*s1,t-q*t1
r,s,t=r1,s1,t1
r1,s1,t1=tem1,tem2,tem3
return s,t
if __name__=='__main__':
m,p,q=map(int,input("请输入:m,p,q (以空格分隔,要求p≡q≡3(mod4))\n").split())
c=encode_Rabin(m,p,q)
print("加密后密文为: ",c)
print("解密后可能的明文为: ",decode_Rabin(c,p,q))
标签:__,公钥,return,r1,int,s1,算法,Rabin 来源: https://blog.csdn.net/kwist_jay/article/details/120616640