这是我写的一个RSA密钥生成脚本,其中e的生成存在严重缺陷,当时时间不够就草草了事了,有时间再改进一下。
import random
def create_pq():
prime_num = int(input('素数的数级:'))
p = 0
q = 0
r = 0
while(p==0 or q==0):
while(r==0):
r = random.randint(prime_num,prime_num*10)
for n in range(2,r):
if(r%n==0):
r = 0
break
if(p==0):
p = r
r = 0
else:
q = r
print('随机生成p:'+str(p)+',q:'+str(q))
return p,q
def gac(a,b):
if(a%b==0):
return b
else:
return(gac(b,a%b))
def euler(n):
m = 0
for i in range(1,n):
b = gac(n,i)
if(b == 1):
m += 1
return m
def create_e(Fn):
while(1):
e = random.randint(2,Fn)
if(gac(Fn,e) == 1):
print('e选取为:',e)
return e
def create_d(a,b):
if(a<=b):
c = a
a = b
b = c
X1,X2,X3 = 1,0,a
Y1,Y2,Y3 = 0,1,b
while(1):
q = X3//Y3
T1,T2,T3 = (X1-Y1*q,X2-Y2*q, X3-Y3*q)
X1,X2,X3 = Y1,Y2,Y3
Y1,Y2,Y3 = T1,T2,T3
if(Y3 == 1):
d = Y2 % a
print ("d:",d)
return d
break
elif(Y3 == 0):
print('No inverse')
break
p,q = create_pq()
n = p*q
Fn = euler(n)
e = create_e(Fn)
d = create_d(e,Fn)
print('公钥为{'+str(e),str(n)+'};秘钥为{'+str(d),str(n)+'}')