Esempio n. 1
0
File: rsa.py Progetto: chen2073/SHA
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
Esempio n. 2
0
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
Esempio n. 4
0
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
Esempio n. 5
0
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")
Esempio n. 6
0
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
Esempio n. 7
0
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")
Esempio n. 8
0
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
Esempio n. 9
0
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
Esempio n. 10
0
	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)
Esempio n. 11
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
Esempio n. 12
0
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))
Esempio n. 13
0
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
Esempio n. 14
0
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 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
Esempio n. 16
0
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)
Esempio n. 17
0
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)
Esempio n. 18
0
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
Esempio n. 19
0
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
Esempio n. 20
0
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
Esempio n. 21
0
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 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
Esempio n. 23
0
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
Esempio n. 24
0
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))
Esempio n. 25
0
def gen_keys():
    generator = PrimeGenerator.PrimeGenerator(bits=128, debug=0, emod=65537)
    return generator.findPrime()
Esempio n. 26
0
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 = []
Esempio n. 27
0
#!/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')