def create_keys(): #creates the keys e = BitVector(intVal = 65537) uno = BitVector(intVal = 1) tres = BitVector(intVal = 3)#used for checking the last two bits generator = PrimeGenerator( bits = 128, debug = 0 ) p = BitVector(intVal = generator.findPrime()) while (p[0:2] != tres and int (e.gcd(BitVector(intVal = int(p)-1))) != 1): p = BitVector(intVal = generator.findPrime()) q = BitVector(intVal = generator.findPrime()) while (q[0:2] != tres and int (e.gcd(BitVector(intVal = int(q)-1))) != 1 and p != q): q = BitVector(intVal = generator.findPrime()) n = int(p) *int( q) n = BitVector(intVal = n) to = BitVector(intVal =((int(p)-1)*(int(q)-1))) d = e.multiplicative_inverse(to) d = int(d) e = int (e) n = int (n) p = int (p) q = int (q) with open('private_key.txt', 'w') as f : f.write(str(d)+"\n") f.write(str(n)+"\n") f.write(str(p)+"\n") f.write(str(q)+"\n") with open('public_key.txt', 'w') as f: f.write(str(e)+"\n") f.write(str(n)+"\n")
def key_generate(): e = 65537 # generate p and q that satisfies all 3 conditions while True: p = PrimeGenerator(bits=128).findPrime() q = PrimeGenerator(bits=128).findPrime() if BitVector(intVal=p)[0] and BitVector(intVal=p)[0]: if p != q: if bgcd(p - 1, e) == bgcd(q - 1, e) == 1: break n = p * q totient = (p - 1) * (q - 1) d = int(BitVector(intVal=e).multiplicative_inverse(BitVector(intVal=totient))) public_key = [e, n] private_key = [d, n] # key arrangement is p q e d n with open("p.txt", "w") as f: f.write(str(p)) with open("q.txt", "w") as f: f.write(str(q)) with open("e.txt", "w") as f: f.write(str(e)) with open("d.txt", "w") as f: f.write(str(d)) with open("n.txt", "w") as f: f.write(str(n)) return public_key, private_key
def createKeys(eVAL): ## Setup the prime generator pg = PrimeGenerator(bits=128, debug=0) while(True): p = pg.findPrime() q = pg.findPrime() ## Check p and q are different if p == q: continue ## Check left two MSB's are 1 (bin command returns 0b appended at front) if not (bin(p)[2] and bin(p)[3] and bin(q)[2] and bin(q)[3]): continue ## Check that the totients of p and q are co-prime to e if (bgcd(p-1, eVAL) != 1) or (bgcd(q-1, eVAL) !=1): continue break ## Calculate modulus n = p * q ## Calculate totient of n tn = (p - 1) * (q-1) modBV = BitVector(intVal = tn) eBV = BitVector(intVal = eVAL) ## Calculate multiplicative inverse d = eBV.multiplicative_inverse(modBV) d = int(d) ## Create public and private sets public, private = [eVAL, n], [d, n] ## Return items return public, private, p, q, eVAL
def generate(): number = PrimeGenerator(bits = 128,debug = 0) flag = False while True: l = BitVector(bitstring = '11') p = number.findPrime() q = number.findPrime() p_bv = BitVector(intVal = p) q_bv = BitVector(intVal = q) #If the two left bits are set then keep it false otherwise make it true if p_bv[0:2] == l and q_bv[0:2] == l: flag = True #if the two numbers are the same than break then set the flag to true if p == q: flag == False else: flag == True #check for co prime if coprime(p-1,e) == 1 and coprime(q-1,e) == 1: flag = True if flag == True: break else: flag = False return p,q
def generateN(): ''' This function is used to generate two prime numbers p, q while guaranteeing: 1. p != q 2. p, q are coprime to e 3. 2 left most bits of p and q are set ret: p, q, n ''' generator = PrimeGenerator(bits=128) p = -1 q = -1 while (True): p = generator.findPrime() q = generator.findPrime() while (q == p): q = generator.findPrime() if gcd((p - 1), e) == 1 and gcd((q - 1), e) == 1: break with open("p.txt", "w") as fp: print(p, end='', file=fp) with open("q.txt", "w") as fp: print(q, end='', file=fp) print("p and q generated")
def key_gen(): # use e = 65537 e = 65537 # find values for p and q prime_generator = PrimeGenerator(bits=128) gcd_p = 0 gcd_q = 0 p = BitVector(size=0) q = BitVector(size=0) # while the generated primes don't meet the conditions, repeat the calculation while gcd_p != 1 and gcd_q != 1 and p == q: p = BitVector(intVal=prime_generator.findPrime()) q = BitVector(intVal=prime_generator.findPrime()) # set first two and last bit p[0:2] = BitVector(bitstring='11') p[127] = 1 q[0:2] = BitVector(bitstring='11') q[127] = 1 # check if p-1 and q-1 are co-prime to e gcd_p = gcd(p.int_val() - 1, e) gcd_q = gcd(q.int_val() - 1, e) return p.int_val(), q.int_val()
def GenerateKeys(eVAL): ## Setup the prime generator pg = PrimeGenerator(bits=128, debug=0) while (True): p = pg.findPrime() q = pg.findPrime() ## Check p and q are different if p == q: continue ## Check left two MSB's are 1 (bin command returns 0b appended at front) if not (bin(p)[2] and bin(p)[3] and bin(q)[2] and bin(q)[3]): continue ## Check that the totients of p and q are co-prime to e if (GCD(p - 1, eVAL) != 1) or (GCD(q - 1, eVAL) != 1): continue break ## Calculate modulus n = p * q ## Calculate totient of n tn = (p - 1) * (q - 1) modBV = BitVector(intVal=tn) eBV = BitVector(intVal=eVAL) ## Calculate multiplicative inverse d = eBV.multiplicative_inverse(modBV) d = int(d) ## Create public and private sets public, private = [eVAL, n], [d, n] ## Return items return public, private, p, q, eVAL
def prime_gen( e): ## compute the p and q values. Test that those are valid values. generator = PrimeGenerator(bits=32, debug=0) p = generator.findPrime() q = generator.findPrime() if p == q: ##test 1 p, q = prime_gen(e) return p, q tempp = p tempq = q test1 = 0 test2 = 0 while (tempp > 0 & tempq > 0): ##test2 if tempp == 3: test1 = 1 if tempq == 3: test2 = 1 tempp = tempp >> 1 tempq = tempq >> 1 if test1 != 1 & test2 != 1: p, q = prime_gen(e) return p, q if gcd((p - 1), e) != 1 & gcd((q - 1), e) != 1: ##test3 p, q = prime_gen(e) return p, q return p, q
def genKey(): e = 3 finish = False p = 0 q = 0 print ("###################") while (finish == False): somenum = PrimeGenerator(bits=128, debug=0) p = somenum.findPrime() q = somenum.findPrime() # print (p), #print (q) finish = True if (int(bin(p)[2]) * int(bin(p)[3]) * int(bin(q)[2]) * int(bin(q)[3]) == 0): finish = False if p == q: finish = False pb = bin(p) qb = bin(q) ''' print (pb[2]) print (qb[2]) print (pb[3]) print (qb[3]) ''' if (gcd(p - 1, e) != 1) or (gcd(q - 1, e) != 1): finish = False n = p * q # print (n) tn = (p - 1) * (q - 1) print "tn" print (tn) tnbv = BitVector(intVal=tn) ebv = BitVector(intVal=e) print ("ebv") print (ebv) print ("tnbv") print (tnbv) dbv = ebv.multiplicative_inverse(tnbv) d = dbv.int_val() print ("dbv") print (dbv) #print (d) puk = [e, n] prk = [d, n] return (puk, prk, p, q)
def startJobImpl(start, end): """ Starts a job that computes the prime numbers between 'start' and 'end' :param start: string: The start number indicates the starting number (inclusive) for the start of the prime list :param end: string: The end number indicates the ending number (inclusive) for the end of the prime list :return: string: a job ID that can be passed to queryJobImpl() """ # Run sanity checks and return suitable error if the arguments are not ints startInt = safe_int_cast(start) if startInt is None: raise HTTPStatusException.HTTPStatusException( '{0} must be an int'.format(start), HTTPStatus.BAD_REQUEST) endInt = safe_int_cast(end) if endInt is None: raise HTTPStatusException.HTTPStatusException( '{0} must be an int'.format(end), HTTPStatus.BAD_REQUEST) if endInt < startInt: raise HTTPStatusException.HTTPStatusException( 'First argument ({0}) must be less than the second argument ({1})'. format(startInt, endInt), HTTPStatus.BAD_REQUEST) if startInt < 0: raise HTTPStatusException.HTTPStatusException( 'First argument ({0}) must be greater than zero'.format(startInt), HTTPStatus.BAD_REQUEST) job_id = random.randint(0, 0x7fffffff) job_id_str = '{:02x}'.format(job_id) key = get_key(start, end) # First we store the job ID along with the request's parameters client = get_redis_client() client.set(job_id_str, key) # Do a "quick" check to see if we've already cached the primes in redis. If we have then there is no sense # calculating them again. "Quick" is in quotes since there may very well be some cases where it's faster to # simply generate the primes rather than hit the network and redis and back. But until more analysis is done # this seems reasonable. primes_as_json = client.get(key) if primes_as_json is None: # Now we generate the prime numbers asynchronously. The asyn processing will update redis by storing the # prime numbers associated with the start/end parameters. That way a '/Query' can look up the parameters # by job ID, then look up the prime numbers based on those parameters. PrimeGenerator.generate_primes_between_async(startInt, endInt, client, key) else: pass return job_id_str
def keyGeneration(): # this function randomly generate p and q for encryption and decryption myGenerator = PrimeGenerator(bits=int(blockSize / 2)) done = False while not done: pValue = myGenerator.findPrime() qValue = myGenerator.findPrime() co_prime = GCD(pValue - 1, eValue) and GCD( qValue - 1, eValue) # condition that p value and q value are co-prime to e not_equal = pValue != qValue # condition that p and q are not equal if co_prime and not_equal: done = True return pValue, qValue
def __init__(self, modSize): self.e = 65537 self.d = None self.p = None self.q = None self.n = None self.e_bv = None self.d_bv = None self.p_bv = None self.q_bv = None self.n_bv = None self.totient_n = None self.public_key = None self.private_key = None #Code for the PrimeGenerator was written by Purdue Professor Dr. Avinash Kak self.generator = PrimeGenerator(bits = (modSize/2), debug = 0)
def generate_p_q(e, num_bits_desired): p = 0 q = 0 generator = PrimeGenerator(bits = num_bits_desired) while (p == q): p = generator.findPrime() q = generator.findPrime() while(gcd(p-1, e)!=1): p = generator.findPrime() while(gcd(q-1, e)!= 1): q = generator.findPrime() return p, q
def keyGeneration(pFileName, qFileName): # this function randomly generate p and q for encryption and decryption myGenerator = PrimeGenerator(bits=int(blockSize / 2)) done = False while not done: pValue = myGenerator.findPrime() qValue = myGenerator.findPrime() co_prime = GCD(pValue - 1, eValue) and GCD( qValue - 1, eValue) # condition that p value and q value are co-prime to e not_equal = pValue != qValue # condition that p and q are not equal if co_prime and not_equal: done = True with open(pFileName, 'w') as file: file.write(str(pValue)) with open(qFileName, 'w') as file: file.write(str(qValue))
def generate_key_pair(): prime_gen = PrimeGenerator(bits=128, debug=0) while True: p = prime_gen.findPrime() q = prime_gen.findPrime() if p == q: continue # ensure that the extremely unlikely case of p=q didn't occur if not (bin(p)[2] and bin(p)[3] and bin(q)[2] and bin(q)[3]): continue # ensure leading bits are 1 if (bgcd(p - 1, e) != 1) or (bgcd(q - 1, e) != 1): continue # totients must be co-prime to e break mod_n = p * q # modulus is the product of the primes tot_n = (p - 1) * (q - 1) # totient of n mod_bv = BitVector(intVal=tot_n) e_bv = BitVector(intVal=e) d_loc = int(e_bv.multiplicative_inverse(mod_bv)) return (e, mod_n), (d_loc, mod_n), p, q
def generation(p_file, q_file): generator = PrimeGenerator(bits=128) while True: # Generate p and q using Provided Prime Generator and change to bitvector to test the first two bits p = BitVector(intVal=generator.findPrime(), size=128) q = BitVector(intVal=generator.findPrime(), size=128) # p and q can not be equal if p != q: # First two bits of p and q have to be set if q[0] and q[1] and p[1] and p[0]: # p-1 and q-1 have be co-prime to e if gcd((p.int_val() - 1), e) and gcd(q.int_val() - 1, e): # All the constraints satisfied, write to the corresponding file with open(p_file, "w") as fp: fp.write(str(p.int_val())) with open(q_file, "w") as fp: fp.write(str(q.int_val())) return
def KeyGeneratorRSA(): e = 3 #Build PrimeGenerator with 128 bits pp = PrimeGenerator(bits=128) while True: #Generate p,q and check them p = BitVector(intVal=pp.findPrime()) q = BitVector(intVal=pp.findPrime()) if p != q and p[0] & p[1] & q[0] & q[1] and bgcd( int(p) - 1, e) == 1 and bgcd(int(q) - 1, e) == 1: break #Get n n = int(p) * int(q) #public key pubKey = [e, n] return pubKey, n
def key_generate(): e = 3 # generate p and q that satisfies all 3 conditions while True: p = PrimeGenerator(bits=128).findPrime() q = PrimeGenerator(bits=128).findPrime() if BitVector(intVal=p)[0] and BitVector(intVal=p)[0]: if p != q: if bgcd(p - 1, e) == bgcd(q - 1, e) == 1: break n = p * q totient = (p - 1) * (q - 1) d = int( BitVector(intVal=e).multiplicative_inverse(BitVector(intVal=totient))) public_key = [e, n] private_key = [d, n] return public_key, private_key, p, q, d, n
def gen_key(e): while (True): prime = PrimeGenerator(bits=128) p = prime.findPrime() q = prime.findPrime() if p != q: if (bin(p)[2] and bin(p)[3] and bin(q)[2] and bin(q)[3]): #print(bin(p),bin(q)) if gcd((p - 1), e) == 1 and gcd((q - 1), e) == 1: break n = p * q tn = (p - 1) * (q - 1) e_bv = BitVector(intVal=e) tn_bv = BitVector(intVal=tn) d_bv = e_bv.multiplicative_inverse(tn_bv) d = int(d_bv) pub = [e, n] prv = [d, n] return (prv, pub, p, q)
def KeyGeneratorRSA(): e=65537 pp=PrimeGenerator(bits =128) while True: p=BitVector(intVal=pp.findPrime()) q=BitVector(intVal=pp.findPrime()) if p != q and p[0]&p[1]&q[0]&q[1] and bgcd(int(p)- 1,e) ==1 and bgcd(int(q)-1,e)==1: break n=int(p)*int(q) n_totient=(int(p)-1)*(int(q)-1) totient_modulus = BitVector(intVal=n_totient) e_bv = BitVector(intVal=e) d = e_bv.multiplicative_inverse(totient_modulus) pubKey = [e,n] priKey = [int(d),n] return pubKey,priKey,p,q
def generateN(): ''' This function is used to generate two prime numbers p, q while guaranteeing: 1. p != q 2. p, q are coprime to e 3. 2 left most bits of p and q are set ret: p, q, n ''' generator = PrimeGenerator(bits=128) p = -1 q = -1 while (True): p = generator.findPrime() q = generator.findPrime() while (q == p): q = generator.findPrime() if gcd((p - 1), e) == 1 and gcd((q - 1), e) == 1: break return p, q, p * q
def create_keys(): #creates the keys e = BitVector(intVal=65537) uno = BitVector(intVal=1) tres = BitVector(intVal=3) #used for checking the last two bits generator = PrimeGenerator(bits=128, debug=0) p = BitVector(intVal=generator.findPrime()) while (p[0:2] != tres and int(e.gcd(BitVector(intVal=int(p) - 1))) != 1): p = BitVector(intVal=generator.findPrime()) q = BitVector(intVal=generator.findPrime()) while (q[0:2] != tres and int(e.gcd(BitVector(intVal=int(q) - 1))) != 1 and p != q): q = BitVector(intVal=generator.findPrime()) n = int(p) * int(q) n = BitVector(intVal=n) to = BitVector(intVal=((int(p) - 1) * (int(q) - 1))) d = e.multiplicative_inverse(to) d = int(d) e = int(e) n = int(n) p = int(p) q = int(q) with open('private_key.txt', 'w') as f: f.write(str(d) + "\n") f.write(str(n) + "\n") f.write(str(p) + "\n") f.write(str(q) + "\n") with open('public_key.txt', 'w') as f: f.write(str(e) + "\n") f.write(str(n) + "\n")
def keygeneration(): e_val = 65537 e_bitvec = BitVector(intVal=e_val) while True: generator = PrimeGenerator(bits=128, debug=0) p = generator.findPrime() q = generator.findPrime() p_bitvec = BitVector(intVal=p, size=128) q_bitvec = BitVector(intVal=q, size=128) ##check if p and q satisfy three conditions, if not generate new p and q if p_bitvec[0] & p_bitvec[1] & q_bitvec[0] & q_bitvec[1]: if p != q: if (int(BitVector(intVal=(p - 1)).gcd(e_bitvec)) == 1) & (int( BitVector(intVal=(q - 1)).gcd(e_bitvec)) == 1): break ##calculte totient_n and d n = p * q totient_n = (p - 1) * (q - 1) tn_bitvec = BitVector(intVal=totient_n) d_bitvec = e_bitvec.multiplicative_inverse(tn_bitvec) key = [e_val, int(d_bitvec), n, p, q] return key
def generating_pandq(): prime = pg.PrimeGenerator(bits=128, debug=0, emod=65537) p = prime.findPrime() q = prime.findPrime() p1 = p - 1 q1 = q - 1 gcd1 = gcd(p1, e) gcd2 = gcd(q1, e) # Find p and q such that p!=q and gcd(p-1,e)=1 and gcd(q-1,e)=1 while p == q and gcd1 != 1 and gcd2 != 1: p = prime.findPrime() q = prime.findPrime() p1 = p - 1 q1 = q - 1 gcd1 = gcd(p1, e) gcd2 = gcd(q1, e) return p, q
def geneKey(): # Generate the public and private keys global e # Generate a random 128 bit prime generator = PrimeGenerator.PrimeGenerator(bits=128) while True: p, q = generator.findPrime(), generator.findPrime() # Check if all necessary requirements are meet if p == q or (bgcd(e, p) != 1) or (bgcd(e, q) != 1): continue n = p * q break # Calculate pair keys tn = (p - 1) * (q - 1) tn_bv = BitVector(intVal=tn) e_v = BitVector(intVal=e) d_v = e_v.multiplicative_inverse(tn_bv) # Store the keys pickle.dump((e_v.int_val(), d_v.int_val(), n, p, q), open('key.p', 'wb')) return
def findPandQ(): ## To get all the requirements for the Encryption and Decryption. ## generator = pGen.PrimeGenerator(bits=128, debug=0, emod=65537) while (True): p = generator.findPrime() q = generator.findPrime() tempVar = getGCD(e, p - 1) if (tempVar == 1): tempVar = getGCD(e, q - 1) if (p != q and tempVar == 1): break ## The Following Logic is to Store the values of P and Q for the Decryption usage. ## filePQ = open('PQValue.txt', 'w') filePQ.write(str(p) + "\n") filePQ.write(str(q)) filePQ.close() return p * q
def test__generate_primes_between(self): # we can use a fake non-thread safe redis client in these tests RedisClientFactory.use_fake_redis_client() test_redis_client = RedisClientFactory.get_redis_client(); # start and end are the same self.assertEqual(list([1]), PrimeGenerator._generate_primes_between_sync(1, 1, test_redis_client, 'Test1')) self.assertEqual(list([7]), PrimeGenerator._generate_primes_between_sync(7, 7, test_redis_client, 'Test2')) self.assertEqual(test_redis_client.get('Test1'), '[1]') self.assertEqual(test_redis_client.get('Test2'), '[7]') # start and end are different self.assertEqual(list([1, 2, 3, 5]), PrimeGenerator._generate_primes_between_sync(1, 5, test_redis_client, 'Test3')) self.assertEqual(list([5, 7, 11, 13]), PrimeGenerator._generate_primes_between_sync(5, 13, test_redis_client, 'Test4')) self.assertEqual(list([5, 7, 11, 13]), PrimeGenerator._generate_primes_between_sync(4, 14, test_redis_client, 'Test5')) self.assertEqual(test_redis_client.get('Test3'), '[1, 2, 3, 5]') self.assertEqual(test_redis_client.get('Test4'), '[5, 7, 11, 13]') self.assertEqual(test_redis_client.get('Test5'), '[5, 7, 11, 13]') # Make sure list comparison is order sensitive self.assertEqual(list([1, 2]), PrimeGenerator._generate_primes_between_sync(1, 2, test_redis_client, 'DontCare')) self.assertNotEqual(list([2, 1]), PrimeGenerator._generate_primes_between_sync(1, 2, test_redis_client, 'DontCare'))
def create_keys(): #creates the keys e = BitVector(intVal = 3) uno = BitVector(intVal = 1) tres = BitVector(intVal = 3)#used for checking the last two bits generator = PrimeGenerator( bits = 128, debug = 0 ) p = BitVector(intVal = generator.findPrime()) while (p[0:2] != tres and int (e.gcd(BitVector(intVal = int(p)-1))) != 1): p = BitVector(intVal = generator.findPrime()) q = BitVector(intVal = generator.findPrime()) while (q[0:2] != tres and int (e.gcd(BitVector(intVal = int(q)-1))) != 1 and p != q): q = BitVector(intVal = generator.findPrime()) n = int(p) *int( q) n = BitVector(intVal = n) to = BitVector(intVal =((int(p)-1)*(int(q)-1))) d = e.multiplicative_inverse(to) priv = (d, n, p, q) pub = (e,n) return (pub, priv)
class GenerateKeys(): def __init__(self, modSize): self.e = 65537 self.d = None self.p = None self.q = None self.n = None self.e_bv = None self.d_bv = None self.p_bv = None self.q_bv = None self.n_bv = None self.totient_n = None self.public_key = None self.private_key = None #Code for the PrimeGenerator was written by Purdue Professor Dr. Avinash Kak self.generator = PrimeGenerator(bits = (modSize/2), debug = 0) #Function below generates primes numbers of a given size def GenPrime(self): return self.generator.findPrime() #Binary implementation of Euclid's Algorithm #Algorithm written in the "bgcd()" method below was written by Purdue Professor Dr. Avinash Kak def bgcd(self, a, b): if a == b: return a if a == 0: return b if b == 0: return a if (~a & 1): if (b &1): return self.bgcd(a >> 1, b) else: return self.bgcd(a >> 1, b >> 1) << 1 if (~b & 1): return self.bgcd(a, b >> 1) if (a > b): return self.bgcd( (a-b) >> 1, b) return self.bgcd( (b-a) >> 1, a ) #Method below generates two prime numbers (p and q) such that they meet certain criteria to be #used in a 256-bit implementation of the RSA Encryption Algorithm def GenPQ(self): while True: #Generate Primes for P and Q self.p_bv = BitVector(intVal = self.GenPrime(), size = 128) while not (self.p_bv[0]&self.p_bv[1]): self.p_bv = BitVector(intVal = self.GenPrime(), size = 128) self.q_bv = BitVector(intVal = self.GenPrime(), size = 128) while not (self.q_bv[0]&self.q_bv[1]): self.q_bv = BitVector(intVal = self.GenPrime(), size = 128) #Check if (p-1) and (q-1) are co-prime to e and if p != q if self.p_bv != self.q_bv: if (self.bgcd((int(self.p_bv)-1), self.e) == 1) and (self.bgcd((int(self.p_bv)-1), self.e) == 1): break self.p = int(self.p_bv) self.q = int(self.q_bv) #Method below generates the "d" value which is a component of the RSA encryption algorithm public key def GenD(self): totient_n_mod = BitVector(intVal = self.totient_n) self.e_bv = BitVector(intVal = self.e) self.d_bv = self.e_bv.multiplicative_inverse(totient_n_mod) self.d = int(self.d_bv) #Method below generates both public and private keys to be used by a 256-bit implementation #of the RSA encryption algorithm def GenKeys(self): self.GenPQ() #Generate P and Q Values self.n = self.p * self.q #Set n self.n_bv = BitVector(intVal = self.n) self.totient_n = (self.p - 1) * (self.q - 1) #Set totient of n self.GenD() #Generate d value self.public_key = [copy.deepcopy(self.e), copy.deepcopy(self.n)] #Set Public-Key self.private_key = [copy.deepcopy(self.d), copy.deepcopy(self.n)] #Set Private-Key #Method below prints generated key-values for RSA encryption algorithm to output file def PrintKeys(self): keyFile = open("keys.txt", "w") keyFile.write("Public-Key: %s\n" % self.public_key) keyFile.write("Private-Key: %s\n" % self.private_key) keyFile.write("P-Value = %ld\n" % self.p) keyFile.write("Q-Value = %ld\n" % self.q) keyFile.close()
def generate_values(num_bits_for_p_q, e, private_key_file, public_key_file): # Prime number generator from given script pg = PrimeGenerator(bits=num_bits_for_p_q, debug=0) # Find a proper p value while ( True ) : p_candidate = pg.findPrime() # if the first two bits are not set, find a new prime if (p_candidate>>126) != 3 : continue # if the totient of p is not rel prime to e, find new prime if gcd( p_candidate - 1 , e ) != 1 : continue # Otherwise the number is good break # Find a proper q value while ( True ) : q_candidate = pg.findPrime() # if p and q are the same, find a new q if( p_candidate is q_candidate ) : continue # if the first two bits are not set, find a new prime if ( q_candidate>>126 ) != 3 : continue # if the totient of q is not rel prime to e, find new prime if gcd( q_candidate - 1 , e ) != 1 : continue # otherwise number is good break # the modulus n n = p_candidate * q_candidate #The totient of n tot_n = ( p_candidate - 1 ) * ( q_candidate - 1 ) # make e a BitVector for calculating the MI tot_n_bv = BitVector( intVal=tot_n ) e_bv = BitVector( intVal=e ) d_bv = e_bv.multiplicative_inverse( tot_n_bv ) d = int( d_bv ) key_set = (e, d, n, p_candidate, q_candidate) with open(private_key_file, 'w') as f : f.write("d="+str(d)+"\n") f.write("n="+str(n)+"\n") f.write("p="+str(p_candidate)+"\n") f.write("q="+str(q_candidate)+"\n") with open(public_key_file, 'w') as f: f.write("e="+str(e)+"\n") f.write("n="+str(n)+"\n")
import string import MySQLdb import hashlib import os from collections import namedtuple from fractions import gcd import re #import BitVector sqlDatabase = MySQLdb.connect(host="localhost", user="******", passwd="password", db="DigitalCash") cursor = sqlDatabase.cursor() generator = pGen.PrimeGenerator(bits=16, debug=0, emod=5) pdata1 = generator.findPrime() pdata2 = generator.findPrime() e = 5 N = pdata1 * pdata2 KeyPair = namedtuple('KeyPair', 'public private') Key = namedtuple('Key', 'exponent modulus') rsaListFiles = [] moneyOrderFiles = [] blindOrders = [] signedFiles = [] unblindedSigned = [] verfiedOutput = [] decryptList = []
#!/usr/bin/env python from BitVector import BitVector import PrimeGenerator as pg import sys import os from solve_pRoot import solve_pRoot # Importing from PrimeGenerator.py from lecture notes generator = pg.PrimeGenerator(bits=128) class BreakRSA(object): def __init__(self): self.e = 3 # p, q, n for each public key self.key_info1 = self.get_modulus() self.key_info2 = self.get_modulus() self.key_info3 = self.get_modulus() # d for each private key self.d1 = self.get_decryption_exp(self.key_info1[0], self.key_info1[1]) self.d2 = self.get_decryption_exp(self.key_info2[0], self.key_info2[1]) self.d3 = self.get_decryption_exp(self.key_info3[0], self.key_info3[1]) self.key_info = [self.key_info1, self.key_info2, self.key_info3] self.d = [self.d1, self.d2, self.d3] with open("cracked_info.txt", 'w') as f: f.write("p, q, n for three public keys") f.write('\n')
def gen_keys(): generator = PrimeGenerator.PrimeGenerator(bits=128, debug=0, emod=65537) return generator.findPrime()
padding_byte = "0"*numBytes padding = '' print("padding : "+padding_byte) for pad in padding_byte: #print("pad count : "+str(pad)) int_pad = ord(pad) #print("pad int : "+str(int_pad)) bin_pad = bin(int_pad)[2:].zfill(8) #print("pad bin : "+str(bin_pad)) padding = padding + bin_pad #print("pad size : "+str(padding)) pad_length = len(padding) print("pad length : "+str(pad_length)) primeNumGenerate = PrimeGenerator ( bits = n_rsa // 2) check = 0 while(check == 0): p = primeNumGenerate.findPrime() q = primeNumGenerate.findPrime() while ( p == q ): p = primeNumGenerate.findPrime() q = primeNumGenerate.findPrime() print("p : "+str(p)) print("q : "+str(q)) n = p*q print("n : "+str(n))