密码学课程设计之RSA
#coding:utf=8 from libnum import * from random import * def Miller_Rabin(n): if n == 2 or n == 3: return True if n & 1 == 0: return False s , d = 0 , n-1 while d % 2 == 0: s += 1 d //= 2 for i in xrange(80):#进行80轮检验 a = randrange(2,n-1)#按递增的方式产生随机数 k = pow(a,d,n) #k = a^d mod n if k == 1 or k == n-1: continue for r in xrange(s): k = pow(k,2,n) #k = a ^[(2^r)*d] mod n if k == n-1: break else: return False return True def gcd(a,b):#求最大公因数 if a < b: a,b = b,a while(b!=0): temp = a % b a = b b = temp return a def get_prime(n): if n <= 2: return False while True: t = '1' for i in range(n-2): t += str(randint(0,1)) t += '1' t = int(t,2) if Miller_Rabin(t): return t def ModInv(a,b): if b == 0: return 1,0 else: k = a // b temp = a % b x1 , y1 = ModInv(b,temp) x , y = y1 , x1 - k * y1 return x,y def get_e(phi): while 1: e = randrange(10,50) if gcd(e,phi) == 1: return e def RSA_en(plain): plain = s2n(plain) p = get_prime(1024) q = get_prime(1024) n = p * q phi = (p-1) * (q-1) e = get_e(phi) cipher = pow(plain,e,n) return p,q,n,e,cipher def RSA_De(p,q,n,e,cipher): phi = (p-1)*(q-1) d,y = ModInv(e,phi) d = d % phi return n2s(pow(cipher,d,n)) flag = 'flag{y0u_found_it!}' p,q,n,e,cipher = RSA_en(flag) print "p=%d\nq=%d\nn=%d\ne=%d\ncipher=%d"%(p,q,n,e,cipher) print "解密后的明文:%s"%(RSA_De(p,q,n,e,cipher))