コード例 #1
0
ファイル: funcs.py プロジェクト: twinkleMing/CIS753_PA2
def RSA_keygen(num):
	rng = Random.new().read
	p = number.getRandomNBitInteger(num/2, rng)
	while Primality_Test(p) == False:
		p = number.getRandomNBitInteger(num/2, rng)
	q = number.getRandomNBitInteger(num/2, rng)
	while Primality_Test(q) == False or q == p:
		q = number.getRandomNBitInteger(num/2, rng)
	n = p * q
	phi_n = (p-1) * (q-1)
	k = 0
	while True:
		while  True: 
			e = random.randint(1, phi_n)
			##k = k + 1
			##print k
			r = Ex_Eulidean(e, phi_n)
			if r[0] == 1: break
		d = r[1] % phi_n
		d_bit = BitArray(bin(d))
		l = len(d_bit)
		#print "l is: " + str(l)
		if l > num - 4: break


	nn = BitArray(uint = n, length = num).hex
	ee = BitArray(uint = e, length = num).hex
	dd = BitArray(uint = d, length = num).hex
        pp = BitArray(bin(p)).hex
	qq = BitArray(bin(q)).hex
	return [pp, qq, nn, ee, dd]
コード例 #2
0
    def __init__(self, qq, pp, gg):
        # if a g value is given that means we have the values
        if gg is not None:
            self.p = pp
            self.q = qq
            self.g = gg
        # if g is not given we have to create our own values
        else:
            # get the sizes of P and Q that are requested
            np = number.size(pp)
            nq = number.size(qq)
            # create the Q first since we will use it first to construct everything else
            self.q = number.getPrime(nq)
            # get a random number which will if multiplied with Q will result in 2**np number
            T = number.getRandomNBitInteger(np - nq)
            # check while T*Q + 1 is not prime and not size of np
            while True:
                # create the T and test again
                T = number.getRandomNBitInteger(np - nq)
                # create the P
                self.p = self.q * T + 1
                if number.isPrime(self.p) and number.size(self.p) == np:
                    break

            self.g = 1
            # keep on checking until G is not 1
            while self.g == 1:
                h = number.getRandomRange(2, self.p - 1)
                self.g = pow(h, (self.p - 1) // self.q, self.p)
コード例 #3
0
ファイル: DS.py プロジェクト: Poyraz-Ozmen/Cryptography
    def __init__(self, qq, pp, gg):
        # if a g value is given that means we have the values
        if gg is not None:
            self.p = pp
            self.q = qq
            self.g = gg
        # if g is not given we have to create our own values
        else:
            np = number.size(pp)
            nq = number.size(qq)
            # given p and q size\ generate q
            self.q = number.getPrime(nq)
            # random number resulting from 2**np
            T = number.getRandomNBitInteger(np - nq)
            # checking T*Q + 1 is not prime
            while True:
                #previous operation for random number
                T = number.getRandomNBitInteger(np - nq)
                # generate the P
                self.p = self.q * T + 1
                if number.isPrime(self.p) and number.size(self.p) == np:
                    break

            self.g = 1
            # while g is not 1 stop
            while self.g == 1:
                h = number.getRandomRange(2, self.p - 1)
                self.g = pow(h, (self.p - 1) // self.q, self.p)
コード例 #4
0
def GetPrimes(spub, spriv):
    p1 = GenPrimeWithOracle(spriv, k / 2, e)
    while True:
        s0 = getRandomNBitInteger(o - m - 1)
        s = int_add(s0, spub)
        t = pi_sit_x(o, s)
        r2 = getRandomNBitInteger(k - o)
        nc = int_add(t, r2)
        q1 = nc / p1
        if isPrime(q1):
            return (p1, q1)
コード例 #5
0
ファイル: rsa3.py プロジェクト: Hcamael/ctf-library
def GetPrimes(spub, spriv):
	p1 = GenPrimeWithOracle(spriv, k/2, e)
	while True:
		s0 = getRandomNBitInteger(o - m - 1)
		s = int_add(s0, spub)
		t = pi_sit_x(o, s)
		r2 = getRandomNBitInteger(k-o)
		nc = int_add(t, r2)
		q1 = nc / p1
		if isPrime(q1):
			return (p1, q1)
コード例 #6
0
def generate_p_and_q(bits):
    p = 2
    q = 2
    while True:
        p = number.getRandomNBitInteger(bits)
        if number.isPrime(p):
            break

    while True:
        q = number.getRandomNBitInteger(bits)
        if number.isPrime(q):
            break

    return p, q
コード例 #7
0
ファイル: keygen.py プロジェクト: r4ph4e1/ROCA_SAS
def _get_candidate_prime(keysize):
    """Generate a candidate prime based on formula (1) in section 2.1."""
    prime_count = _prime_count_for_keysize(keysize)
    primes = _first_n_primes(prime_count)
    M = reduce(mul, primes)  # the primorial M in the paper
    M_bits = int(log(M, 2)) + 1

    k_bits = (keysize // 2) - M_bits
    a_bits = {
        39: 62, 71: 134, 126: 255, 225: 434
    }[prime_count]  # Table 1 - Naive BF # attempts gives order of group
    k = getRandomNBitInteger(k_bits)
    a = getRandomNBitInteger(a_bits)

    return k * M + pow(e, a, M)
コード例 #8
0
    def handShake(self):
        handShake = bytes("h", "utf-8")
        self.privateKey = number.getRandomNBitInteger(224)
        prime = number.getPrime(2048)
        generatorOfP = number.getRandomNBitInteger(224)
        publicKey = pow(generatorOfP, self.privateKey, prime)

        prime = prime.to_bytes(256, byteorder='big')  # From int to byteString
        generatorOfP = generatorOfP.to_bytes(28, byteorder='big')
        publicKey = publicKey.to_bytes(256, byteorder='big')

        data = handShake + prime + generatorOfP + publicKey  # 1 + 256 + 28 + 256 bytes

        self.UDPClientSocket.sendto(data, (self.localAdress, 5005))
        print("Sent Handshake to establish secure connection")
コード例 #9
0
def prime_gen():
    i = getRandomNBitInteger(1024)
    d = getRandomNBitInteger(8)
    for _ in range(d):
        i = find_next_prime(i)
    p = find_next_prime(i)
    d = getRandomNBitInteger(8)
    for _ in range(d):
        i = find_next_prime(i)
    q = find_next_prime(i)
    d = getRandomNBitInteger(8)
    for _ in range(d):
        i = find_next_prime(i)
    r = find_next_prime(i)
    return (p,q,r)
コード例 #10
0
def encrypt_data_CBC(data):
    n,e,d = generate_keys()
    private_key = (n,d)
    size_of_block = 64 # rozmiar bloku w bajtach
    data = bytearray(data)
    initialization_vector = number.getRandomNBitInteger(size_of_block * 8)
    previous_vector = initialization_vector

    pixels = []
    for i in range(0,len(data),size_of_block):
        bytes_to_encrypt = data[i: i + size_of_block]
        int_cipher = int.from_bytes(bytes_to_encrypt, 'big')

        previous_vector = previous_vector.to_bytes(int(n.bit_length()/8), 'big')
        previous_vector = int.from_bytes(previous_vector[0:len(bytes_to_encrypt)], 'big') # dopasowanie wektora inizjalizujacego do rozmiaru liczby z bloku
        int_cipher = int_cipher ^ previous_vector

        cipher_text = pow(int_cipher, e, n) # kodowanie do kryptogramu
        previous_vector = cipher_text # podmiana wektora
        block = cipher_text.to_bytes(int(n.bit_length()/8), 'big') # tworzony jest blok o długości n w bajtach

        for j in range(0,len(block)):
            pixels.append(block[j])   # każy bajt jest osobno dodawany do tablicy pikseli

    return pixels[:len(data)], pixels[len(data):], private_key, size_of_block, initialization_vector
コード例 #11
0
def generatekey():
    global h, g, x, y, p, q
    q = num.getPrime(160)
    p = 0
    h = 0
    x = num.getRandomRange(0, q)
    y = 0
    multi = 1
    while 1:
        print("trying to generate a new num")
        while multi % 2 == 1:
            multi = num.getRandomNBitInteger(512 - 160)
        for i in range(1, 50):
            multi = multi + 2 * i
            p1 = multi * q
            p = p1 + 1
            if num.isPrime(p) and num.size(p) == 512:
                break
        if num.isPrime(p) and num.size(p) == 512:
            break
    power = divmod(p - 1, q)[0]
    while not pow(h, power, p) > 1:
        h = num.getRandomRange(2, p - 1)
    g = pow(h, power, p)
    y = pow(g, x, p)
コード例 #12
0
ファイル: pg.py プロジェクト: mmuszkow/wtwCrypto
def find_generator_and_safe_prime(bits, gen_max_bits = False):
    stdout.write('Trying to find prime p ')
    while(1):
        stdout.write('.')
        q = number.getPrime(bits-1) # zeby pomnozona przez 2 byla na pewno mniejsza od p, (+1 pomijam, zakladam ze nie przekroczy)
        p = (q << 1) + 1
        if number.isPrime(p):
            print '\n' + str(number.size(p)) + ' bits prime p found'
            p_sub_1 = p - 1
            
            stdout.write('Trying to find generator g ')
            while(1):
                if gen_max_bits: # generator moze miec dowolna liczbe bitow
                    g = number.getRandomNBitInteger(bits)
                    if g >= p:
                        continue
                else:
                    g = number.getRandomRange(2, p)
                
                if pow(g, 2, p) == 1 or pow(g, q, p) == 1:
                    stdout.write('.')
                    continue
                    
                print '\n' + str(number.size(g)) + ' bits generator g found'
                return p, g
コード例 #13
0
def generate_safe_prime(nbits):
    """ Finds a safe prime of nbits using probabilistic method rather than deterministic;
    because a large prime number is required. """
    q = number.getRandomNBitInteger(nbits)
    while not gmpy.is_prime(q):
        q = gmpy.next_prime(q)
    return int(q)
コード例 #14
0
def getLargeDLprime(q, bitsize):
    while True:
        k = crypt.getRandomNBitInteger(bitsize)
        # using q here because q|p-1, where p must be also prime
        p = q * k + 1
        if crypt.isPrime(p):
            return p
コード例 #15
0
def GenerateKey(db):
    security_parameter = {
        'a': str(number.getPrime(600)),
        'p': str(number.getPrime(8192)),
        's': str(number.getRandomNBitInteger(8190))
    }
    db.security_parameter.insert_one(security_parameter)
コード例 #16
0
ファイル: elgamal.py プロジェクト: pombredanne/pol-1
def _find_safe_prime(bits, randfunc=None):
    """ Finds a safe prime of `bits` bits """
    r = gmpy.mpz(number.getRandomNBitInteger(bits-1, randfunc))
    q = gmpy.next_prime(r)
    p = 2*q+1
    if gmpy.is_prime(p):
        return p
コード例 #17
0
 def gen_ed(self, bits):
     while True:
         d = getRandomNBitInteger(int(bits*0.4))
         if GCD(d, self.lbd) == 1:
             e = inverse(d, self.lbd)
             self.e, self.d = e, d
             break
コード例 #18
0
ファイル: rsa3.py プロジェクト: Hcamael/ctf-library
def get_pkey():
	print "DH key exchange system:"
	P = getPrime(m)
	print "P: ", hex(P)
	G = getRandomNBitInteger(m)
	a = getRandomNBitInteger(m/4)
	Ya = pow(G, a, P)
	print "Please enter you secret key: "
	try:
		b = raw_input()
		b = int(b)
		assert size(b) == m/4
	except:
		m_exit(-1)
	Yb = pow(G, b, P)
	K = pow(Yb, a, P)
	return (Ya, K)
コード例 #19
0
 def encrypt(self, s, a, p):
     encrypted_transaction = {}
     for i, value in enumerate(self.item):
         r = number.getRandomNBitInteger(100)
         encrypted_transaction['item' +
                               str(i)] = str(s * (a + r) %
                                             p if value else s * r % p)
     return encrypted_transaction
コード例 #20
0
def randomIntegerNbit(bitLength):
    # Usage
    # randomInteger = randomIntegerNbit(256)

    # Old version
    # return random.getrandbits(bitLength)

    return number.getRandomNBitInteger(bitLength)
コード例 #21
0
def get_pkey():
    print "DH key exchange system:"
    P = getPrime(m)
    print "P: ", hex(P)
    G = getRandomNBitInteger(m)
    a = getRandomNBitInteger(m / 4)
    Ya = pow(G, a, P)
    print "Please enter you secret key: "
    try:
        b = raw_input()
        b = int(b)
        assert size(b) == m / 4
    except:
        m_exit(-1)
    Yb = pow(G, b, P)
    K = pow(Yb, a, P)
    return (Ya, K)
コード例 #22
0
def main():
    ptx = re.findall(r'^redmask{(\w+)}$', flag)[0].encode()
    rsa = RSA.generate(1024)
    oaep = PKCS1_OAEP.new(rsa)
    lfsr = LFSR64(getRandomNBitInteger(64), 0xC936000000000000)
    with open('output.txt', 'w') as f:
        f.write(f"{lfsr.encrypt(ptx[:len(ptx)//2]).hex()}\n")
        f.write(f"{oaep.encrypt(ptx[len(ptx)//2:]).hex()}\n")
        f.write(f"{lfsr.encrypt(rsa.export_key('PEM')).hex()}\n")
        f.close()
コード例 #23
0
def createMemKey( K, U, prvKey):
	v = number.getRandomNBitInteger(vBit)
	e = 4
	while(not number.isPrime(e)):
		e = number.getRandomRange( E, EPerp)
	S_v = safePow( prvKey.S, v, prvKey.RSAN)
	A   = prvKey.Z * number.inverse( U * S_v, prvKey.RSAN)
	power = number.inverse( e, (prvKey.pPrime-1)*(prvKey.qPrime-1))
	A   = safePow(A, power, prvKey.RSAN)
	return( A, e, v)
コード例 #24
0
def test_32bit():
    start = current_time_ms()
    tries = 0
    while True:
        tries += 1
        num = number.getRandomNBitInteger(32)

        if not rabin_miller(num):
            if rabin_miller(num, 64):
                end = current_time_ms()
                return num, tries, end - start
コード例 #25
0
    def __init__(self, pk = None, sk = None):
        self.MsgDir = './messages/'
        if pk is None:
            from gensafeprime import generate
            p, q = generate(1024), generate(1024)
            pk = p * q
        self.pk = pk

        if sk is None:
            sk = 2 * number.getRandomNBitInteger(255) + 1
        self.sk = sk
コード例 #26
0
ファイル: IBM.py プロジェクト: vngkv123/sctf2017
    def __init__(self, pk=None, sk=None):
        self.MsgDir = 'messages/'
        if pk is None:
            from Crypto.PublicKey.RSA import generate
            rsa = generate(2048)
            pk = rsa.n
        self.pk = pk

        if sk is None:
            sk = 2 * number.getRandomNBitInteger(255) + 1
        self.sk = sk
コード例 #27
0
def task(p, q, cipher):
    n = p * q
    assert p.bit_length() >= 254 and p.bit_length(
    ) <= 256, "p is not 254-256 bit long"
    assert q.bit_length() >= 254 and q.bit_length(
    ) <= 256, "q is not 254-256 bit long"
    assert number.isPrime(p), "p is not prime"
    assert number.isPrime(q), "q is not prime"

    e = number.getRandomNBitInteger(256)
    while number.GCD(e, (p - 1) * (q - 1)) != 1:
        e = number.getRandomNBitInteger(256)

    d = number.inverse(e, (p - 1) * (q - 1))

    msg = decrypt(cipher, d, n)

    if msg == b'justGiveTheFlag!!':
        return FLAG
    else:
        return "justTryALittleHarder"
コード例 #28
0
def keygen_dh(key_size, use_group, dh_group, dh_mod_size, dh_p, dh_g):
    if use_group == True:        
        dh_p = modp_groups[dh_group]['p']
        dh_g = modp_groups[dh_group]['g']
        dh_mod_size = size(dh_p)
    else:
        # check parameters, assign defaults if necessary
        if dh_p != None:
            dh_mod_size = size(dh_p)
        
        # print('###########:', key_size, dh_mod_size, flush = True)
        # generate new safe prime to define finite field
        # This is pretty efficient
        if dh_p == None:
            dh_p = 0
            count = 0
            while not isPrime(dh_p):
                count += 1
                q = getPrime(dh_mod_size - 1)
                dh_p = (2 * q) + 1
            #print('Fresh q:', count, q, flush = True)
            #print('Fresh p:', count, dh_p, flush = True) 

        #define new generator for the finite field
        if dh_g == None:
            dh_g = 2
            generator_found = False
            count2 = 0
            while (generator_found == False) and (dh_g < dh_p):
                count2 += 1
                generator_found = True
                #print('&&&&&&&&&&:', count2, 1)
                if pow(dh_g, 2, dh_p) == 1:
                    generator_found = False
                    #print('&&&&&&&&&&:', count2, 2)
                if generator_found == True and pow(dh_g, q, dh_p) == 1:
                    generator_found = False
                    #print('&&&&&&&&&&:', count2, 3)
                if generator_found == False:
                    dh_g += 1
                    #print('&&&&&&&&&&:', count2, 4)
            #print('Fresh g:', count2, dh_g)
    #DH Group Parameters have now been established
    
    #generate new exponent (secret key derivation value)
    dh_x = getRandomNBitInteger(key_size)

    #generate dh_X = dh_g ** dh_x (mod dh_p) (public key derivation value)
    dh_X = pow(dh_g, dh_x, dh_p)

    #first value must remain secret, the rest is public
    return (dh_x, dh_X, dh_g, dh_p)
コード例 #29
0
def count_safe_primes(bits):
    randfunc = Crypto.Random.new().read
    started = time.time()
    ret = []
    while True:
        r = gmpy.mpz(number.getRandomNBitInteger(bits-1, randfunc))
        q = gmpy.next_prime(r)
        p = 2*q + 1
        germain = gmpy.is_prime(p)
        ret.append((germain, int(q - r)))
        if time.time() - started > 60:
            break
    return ret
コード例 #30
0
ファイル: qloq.py プロジェクト: pvial00/QloQ
def oaep_encrypt(m, mod):
    # This is for testing purposes only
    n = len(bin(abs(mod))[2:]) 
    k0 = 1
    k1 = 0
    ks0 = len(bin(abs(k0))[2:])
    ks1 = len(bin(abs(k1))[2:])
    r = number.getRandomNBitInteger(n)
    G = number.bytes_to_long(hashlib.sha256(number.long_to_bytes(r)).digest())
    X = m ^ G
    H = number.bytes_to_long(hashlib.sha256(number.long_to_bytes(X)).digest())
    Y = r ^ H
    return X, Y
コード例 #31
0
def test_512bit():
    start = current_time_ms()
    tries = 0
    while True:
        tries += 1
        num = number.getRandomNBitInteger(512)
        print(f"try {num}")
        if rabin_miller(num, 2):
            end = current_time_ms()
            print(
                f" {num} is a pseudo-prime, found after {tries} tries in {end-start}ms"
            )
            return
コード例 #32
0
ファイル: rsa3.py プロジェクト: Hcamael/ctf-library
def GenPrimeWithOracle(spriv, L, e):
	'''
	Generate p
	'''
	T = L/2 + 64
	T1 = L - T
	PRF = random.Random()
	PRF.seed(spriv)
	while True:
		u = PRF.randint(2**(T-1), 2**T)
		l = getRandomNBitInteger(T1)
		p1 = int_add(u, l)
		if isPrime(p1):
			return p1
コード例 #33
0
ファイル: rsa3_payload.py プロジェクト: Hcamael/ctf-library
def main():
	r = remote("120.27.4.96", 14000)
	# r = process("rsa3.py")
	verify(r)
	r.readuntil("token: ")
	token = "d58c9a2aca58a3f2faf17ec5e7deaec6ZHSBHK6e"
	r.sendline(token)
	r.readuntil("P: ")
	P = r.readline().strip()
	P = int(P[2:-1], 16)

	r.readuntil('key:')
	b = getRandomNBitInteger(m/4)
	r.sendline(str(b))

	r.readuntil("n: ")
	n = r.readline().strip()
	n = int(n[2:-1], 16)
	e = 0x10001
	r.readuntil("e2: ")
	e2 = r.readline().strip()
	e2 = int(e2[2:], 16)
	r.readuntil("flag is: ")
	flag = r.readline().strip()
	flag = int(flag[2:-1], 16)
	r.close()
	print "n: ", hex(n)
	print "e: ", hex(e)
	print "e2: ", hex(e2)
	print "flag: ", hex(flag)
	print "=======start attack====="
	t = get_bit(n, 1024, 1)
	print "t: ", hex(t)
	s = pi_sit_x1(o, t)
	print "s: ", hex(s)
	attack_spub = get_bit(s, m, 0)
	# if attack_spub == spub:
	# 	return True
	# else:
	# 	t += 1
	# 	s = pi_sit_x1(o, t)
	# 	attack_spub = get_bit(s, m, 0)
	# 	if attack_spub == spub:
	# 		return True
	# 	else:
	# 		raw_input()
	# 		return False
	attack_spriv = pow(attack_spub, b, P)
	print "spub: ", hex(attack_spub)
	print "spriv: ", hex(attack_spriv)
コード例 #34
0
def GenPrimeWithOracle(spriv, L, e):
    '''
	Generate p
	'''
    T = L / 2 + 64
    T1 = L - T
    PRF = random.Random()
    PRF.seed(spriv)
    while True:
        u = PRF.randint(2**(T - 1), 2**T)
        l = getRandomNBitInteger(T1)
        p1 = int_add(u, l)
        if isPrime(p1):
            return p1
コード例 #35
0
ファイル: rsa3_payload.py プロジェクト: zjguang/ctf-library
def main():
    r = remote("120.27.4.96", 14000)
    # r = process("rsa3.py")
    verify(r)
    r.readuntil("token: ")
    token = "d58c9a2aca58a3f2faf17ec5e7deaec6ZHSBHK6e"
    r.sendline(token)
    r.readuntil("P: ")
    P = r.readline().strip()
    P = int(P[2:-1], 16)

    r.readuntil('key:')
    b = getRandomNBitInteger(m / 4)
    r.sendline(str(b))

    r.readuntil("n: ")
    n = r.readline().strip()
    n = int(n[2:-1], 16)
    e = 0x10001
    r.readuntil("e2: ")
    e2 = r.readline().strip()
    e2 = int(e2[2:], 16)
    r.readuntil("flag is: ")
    flag = r.readline().strip()
    flag = int(flag[2:-1], 16)
    r.close()
    print "n: ", hex(n)
    print "e: ", hex(e)
    print "e2: ", hex(e2)
    print "flag: ", hex(flag)
    print "=======start attack====="
    t = get_bit(n, 1024, 1)
    print "t: ", hex(t)
    s = pi_sit_x1(o, t)
    print "s: ", hex(s)
    attack_spub = get_bit(s, m, 0)
    # if attack_spub == spub:
    # 	return True
    # else:
    # 	t += 1
    # 	s = pi_sit_x1(o, t)
    # 	attack_spub = get_bit(s, m, 0)
    # 	if attack_spub == spub:
    # 		return True
    # 	else:
    # 		raw_input()
    # 		return False
    attack_spriv = pow(attack_spub, b, P)
    print "spub: ", hex(attack_spub)
    print "spriv: ", hex(attack_spriv)
コード例 #36
0
def createPrimeOrderGroup(pPrime, qPrime, MOD):
	while(1):   
		q = number.getPrime(qGroupBit)
		r = 0
		for i in range(10000000):
			r = number.getRandomNBitInteger(pGroupBit-qGroupBit)
			p = (r*q+1) % MOD
			if(number.isPrime(p)):
				u = number.getRandomInteger(nBit)
				u1 = safePow(u,p-1,MOD)
				qInv = number.inverse( q, (pPrime-1)*(qPrime-1))
				u2 = safePow(u1,qInv,MOD)
				if(u2 != 0):
					return ( q, p, u)
コード例 #37
0
ファイル: pg.py プロジェクト: mmuszkow/wtwCrypto
def find_generator_and_prime(bits, n, gen_max_bits = False):
    # p - 1 = q1 * q2 * q3 * ... * qn
    p_sub_1 = 0 # p - 1
    p = 0
    stdout.write('Trying to find prime p ')
    while(not number.isPrime(p)): # sprawdzamy czy liczba p jest pierwsza, inaczej nie ma sensu szukac generatora
        stdout.write('.')
        qs = [2] # lista q, inicjowana q1 = 2, bez 2 p+1 bylaby zawsze liczba parzysta czyli nie pierwsza
        p_sub_1 = qs[0] # p - 1 = q1
        for i in range(0, n):
            q = number.getPrime(bits/n)
            tmp_p_sub_1 = p_sub_1 * q
            tmp_p = tmp_p_sub_1 + 1
            if number.size(tmp_p) <= bits: # sprawdzamy czy liczba p ma tyle bitow ile chcemy
                p_sub_1 = tmp_p_sub_1
                p = tmp_p
                qs.append(q)
            else:
                break
        
        if(number.size(p_sub_1) != bits): # dopelniamy do oczekiwanej liczby bitow mnozac kilkukrotnie przez 2
            p_sub_1 <<= bits-number.size(p_sub_1)
            p = p_sub_1 + 1
    
    stdout.write('\n' + str(number.size(p)) + ' bits prime p found\n')

    stdout.write("Trying to find generator g ")
    while(1): # kazda grupa cykliczna ma generator
        stdout.write('.')
        
        if gen_max_bits:
            g = number.getRandomNBitInteger(bits) # generator moze miec dowolna liczbe bitow
            if g >= p:
                continue
        else:
            g = number.getRandomRange(2, p)
        
        isGenerator = True
        for q in qs:
            if pow(g, p_sub_1/q, p) == 1: # nie jest generatorem jesli g ^ ((p-1) / q) mod p == 1
                isGenerator = False
                break;
        
        if isGenerator:
            stdout.write('\n' + str(number.size(g)) + ' bits generator g found\n')
            return p, g
コード例 #38
0
ファイル: dh.py プロジェクト: aaron-otis/Security
 def __init__(self, p, g):
     self.p = p
     self.g = g
     self.priv = getRandomNBitInteger(2048)
コード例 #39
0

# It's OK for p to be larger than q, but let's be
# kind to the function that will invert it for
# the calculation of u.
if p > q:
        (p, q)=(q, p)

n = p * q
phi = (p - 1)*(q - 1)

# generate encryption key
# we don't generate a decryption key
e = phi
while number.GCD(e, phi) != 1 or e >= n :
	e = number.getRandomNBitInteger(keybits, None) 


stdout = sys.stdout

# Generate public config file
if cfg_fname == "":
	print "Generating public config file"
	fname = name + ".pub.cfg"
	pfname = name + ".priv.cfg"
	sys.stdout = open(fname, 'w')

	print "[sampling]"
	print "sample_rate= 1.0"
	print "salt=", salt
	print ""
コード例 #40
0
ファイル: encryptMe.py プロジェクト: chris-clm09/rsa
def getS():
   return number.getRandomNBitInteger(500)
コード例 #41
0
ファイル: Sig.py プロジェクト: Crypticator/ModDiv
  print('Invalid Arguments')

if l + q + r >= p :
   print("")
   print("Public Parameter l = %d" %l)
   print("Public Parameter m = %d" %m)
   print("Public Parameter p = %d" %p)
   print("Public Parameter q = %d" %q)
   print("Public Parameter r = %d" %r)
   print("")
   print('Condition (p > l + q + r) is not fulfilled !')

else :

   " Size in bits of public pararameter Z is l "
   Z = getRandomNBitInteger(l,randfunc=None)

   " a hash value of a hypothetical file "
   H = getRandomNBitInteger(l,randfunc=None)

   " Size in bits of private parameters X and Y is m "
   X = getRandomNBitInteger(m,randfunc=None)
   Y = getRandomNBitInteger(m,randfunc=None)

   M = pow(2,p)

   M1 = pow(2,p-q)

   D = pow(2,q)

   D1 = pow(2,l + r)