# This file was *autogenerated* from the file my_rsa_pet.sage from sage.all_cmdline import * # import sage library _sage_const_2 = Integer(2); _sage_const_1 = Integer(1); _sage_const_0 = Integer(0); _sage_const_5 = Integer(5); _sage_const_100 = Integer(100); _sage_const_512 = Integer(512); _sage_const_16 = Integer(16) import hashlib from time import time def gen_prime(BITS): lb=_sage_const_2 **(BITS-_sage_const_1 ) ub=_sage_const_2 *lb return random_prime(ub,False,lb) def gen_safe_prime(BITS): qq=_sage_const_1 while not qq.is_prime(): pp=gen_prime(BITS-_sage_const_1 ) qq=_sage_const_2 *pp+_sage_const_1 return qq def RSA_KEY_GEN(BITS): p=gen_safe_prime(BITS) q=gen_safe_prime(BITS) N=p*q fi=(p-_sage_const_1 )*(q-_sage_const_1 ) e=_sage_const_2 **_sage_const_16 +_sage_const_1 d=inverse_mod(e,fi) dp=inverse_mod(e,p-_sage_const_1 ) dq=inverse_mod(e,q-_sage_const_1 ) qInv = inverse_mod(q,p) return p,q,e,d,dp,dq,qInv,N,fi def RSA_Encrypt(m,e,n): return pow(m,e,N) def RSA_Decrypt(c,p,q,d,dp,dq,qInv,N): m1=int(pow(c, dp,p)) m2=int(pow(c, dq,q)) h = (qInv * (m1 - m2)) % p return (m2 + h * q)%N BITS=_sage_const_512 print "Please wait, generating parameters..." p,q,e,d,dp,dq,qInv,N,fi=RSA_KEY_GEN(BITS) print "Done! Running tests now..." tA=_sage_const_0 tB=_sage_const_0 TESTS=_sage_const_100 for i in range(TESTS): ###Alice ts=time() lA=_sage_const_5 #2*ZZ.random_element(2**31)+1 print "lA:", int(lA) rA=ZZ.random_element(N) print "rA:", int(rA) #select a random location cA=pow(rA,lA,N) print "cA:", int(cA) tA+=time()-ts ###Bob ts=time() lB= _sage_const_5 #2*ZZ.random_element(2**31)+1 print "lB:", int(lB) e_B=inverse_mod(lB,fi) print "e_B:", int(e_B) tmp=pow(cA,e_B,N) print "tmp:", tmp res=hashlib.sha224(str(tmp)).hexdigest() tB+=time()-ts ###Alice ts=time() comp= (res==hashlib.sha224(str(rA)).hexdigest()) print "Comparison", comp tA+=time()-ts print "Average times:\nAlice:%0.5f\nBob:%0.5f"%(tA/TESTS,tB/TESTS)