コード例 #1
0
def get_prime():
    X = int(('0' * 63 + '1') * 37 + '0' * 89)

    factors_a = [2, 5, 11, 13, 23, 37, 53, 59]
    factors_b = [3, 7, 17, 19, 29, 31, 41, 47]

    prime_a = 1
    prime_b = 1

    while not isPrime(prime_a * X + prime_b):
        prime_a = 1
        while not (prime_a < 1e64 and prime_a >= 5e63):
            while prime_a < 5e63:
                prime_a *= random.choice(factors_a)
            while prime_a >= 1e64:
                factors = factorint(prime_a)
                prime_a //= random.choice(list(factors.keys()))
        print(prime_a)

        prime_b = 1
        counter = 0
        while not isPrime(prime_a * X + prime_b) and counter <= 100:
            prime_b = 1
            while not (prime_b < 1e89 and prime_b >= 5e88):
                while prime_b < 5e88:
                    prime_b *= random.choice(factors_b)
                while prime_b >= 1e89:
                    factors = factorint(prime_b)
                    prime_b //= random.choice(list(factors.keys()))
            counter += 1

    return prime_a * X + prime_b
コード例 #2
0
ファイル: unevaluated.py プロジェクト: TheBlueFlame121/CTFs
 def generate_params(prime_length):
     # Warning: this may take some time :)
     while True:
         p = getPrime(prime_length)
         if p % 4 == 3:
             if p % 3 == 2:
                 q = (p - 1) // 2
                 r = (p + 1) // 12
                 if isPrime(q) and isPrime(r):
                     break
             else:
                 q = (p - 1) // 6
                 r = (p + 1) // 4
                 if isPrime(q) and isPrime(r):
                     break
     n = p**2
     order = p * q * r
     while True:
         re = getRandomRange(1, n)
         im = getRandomRange(1, n)
         g = complex_pow(Complex(re, im), 24, n)
         if (complex_pow(g, order, n) == Complex(1, 0)
                 and complex_pow(g, order // p, n) != Complex(1, 0)
                 and complex_pow(g, order // q, n) != Complex(1, 0)
                 and complex_pow(g, order // r, n) != Complex(1, 0)):
             return g, order, n
コード例 #3
0
ファイル: solution.py プロジェクト: oioki/balccon2k20-ctf
def constellation_factorization(n, stars):
    root = iroot(stars, n)

    n_candidate = 1
    offset = (root + 1) % 2

    primes = []

    while True:
        p = root + offset
        if isPrime(p):
            n_candidate *= p
            primes.append(p)

        p = root - offset
        if isPrime(p):
            n_candidate *= p
            primes.append(p)

        if n_candidate == n:
            return primes

        if n_candidate > n:
            return []

        offset += 2
コード例 #4
0
def pollard_brute(N):
    """
    For one of N's prime p,
        1. If (p-1) is a K-smooth number. (k is small)
        2. When all (p-1)'s factor were iterated by b
    Then it can be factorization by pollard_pm1.
    """
    a = 2
    b = 1
    factors = []
    if isPrime(N) : return N
    try :
        while True:
            a = pow(a, b, N)
            p = GCD(a - 1, N)
            if 1 < p < N:
                factors.append(p)
                print(f"factor found: {p}")
                q = N // p
                if isPrime(q) :
                    print(f"factor found: {q}")
                    factors.append(q)
                    return factors
            b += 1
    except:
        return factors
コード例 #5
0
def _is_safe_prime(p, probability=params.FALSE_PRIME_PROBABILITY):
        """
        Test if the number p is a safe prime.
        
        A safe prime is one of the form p = 2q + 1, where q is also a prime.
        
        Arguments:
            p::long    -- Any integer.
            probability::int    -- The desired maximum probability that p 
                                   or q may be composite numbers and still be 
                                   declared prime by our (probabilistic) 
                                   primality test. (Actual probability is 
                                   lower, this is just a maximum provable bound)
        
        Returns:
            True    if p is a safe prime
            False    otherwise
        """
        # Get q (p must be odd)
        if(p % 2 == 0): 
            return False
        
        q = (p - 1)/2
        
        # q first to shortcut the most common False case
        return (number.isPrime(q, false_positive_prob=probability) 
                and
                number.isPrime(p, false_positive_prob=probability))
コード例 #6
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)
コード例 #7
0
def check_secret(secret):
    assert secret.bits == 512
    assert secret.p.bit_length() == secret.bits
    assert secret.q.bit_length() == secret.bits
    assert secret.e < secret.bits
    assert isPrime(secret.p) and isPrime(secret.q)
    assert GCD(secret.e, (secret.p - 1) * (secret.q - 1)) == 1
コード例 #8
0
def dec_pq(c: int, p: int, q: int, e: int) -> int:
    if not isPrime(p) or not isPrime(q):
        raise ValueError("`p` and `q` must be a prime number")
    n = p * q
    phi = (p-1)*(q-1)
    d = inv(e, phi)
    return dec(c, d, n)
コード例 #9
0
ファイル: algs.py プロジェクト: pingiun/helios-server
    def validate_pk_params(self):
        # check primality of p
        if not number.isPrime(self.p):
            raise Exception("p is not prime.")

        # check length of p
        if not (number.size(self.p) >= 2048):
            raise Exception(
                "p of insufficient length. Should be 2048 bits or greater.")

        # check primality of q
        if not number.isPrime(self.q):
            raise Exception("q is not prime.")

        # check length of q
        if not (number.size(self.q) >= 256):
            raise Exception(
                "q of insufficient length. Should be 256 bits or greater.")

        if pow(self.g, self.q, self.p) != 1:
            raise Exception("g does not generate subgroup of order q.")

        if not (1 < self.g < self.p - 1):
            raise Exception("g out of range.")

        if not (1 < self.y < self.p - 1):
            raise Exception("y out of range.")

        if pow(self.y, self.q, self.p) != 1:
            raise Exception("g does not generate proper group.")
コード例 #10
0
def _is_safe_prime(p, probability=params.FALSE_PRIME_PROBABILITY):
    """
        Test if the number p is a safe prime.
        
        A safe prime is one of the form p = 2q + 1, where q is also a prime.
        
        Arguments:
            p::long    -- Any integer.
            probability::int    -- The desired maximum probability that p 
                                   or q may be composite numbers and still be 
                                   declared prime by our (probabilistic) 
                                   primality test. (Actual probability is 
                                   lower, this is just a maximum provable bound)
        
        Returns:
            True    if p is a safe prime
            False    otherwise
        """
    # Get q (p must be odd)
    if (p % 2 == 0):
        return False

    q = (p - 1) / 2

    # q first to shortcut the most common False case
    return (number.isPrime(q, false_positive_prob=probability)
            and number.isPrime(p, false_positive_prob=probability))
コード例 #11
0
def construct_moduli():
	with open("b1") as f1, open("b2") as f2:
		b1 = long(f1.read())
		b2 = long(f2.read())

	e = long(65537)
	p1 = number.getPrime(500)
	p2 = number.getPrime(500)
	assert(p1 != p2)
	assert(number.GCD(e, p1-1) == 1)
	assert(number.GCD(e, p2-1) == 1)
	print p1
	print p2

	a1 = p1 - b1 % p1
	a2 = p2 - b2 % p2
	b0 = chinese_remainder_theorem(p1, p2, a1, a2)
	assert(b0 < p1 * p2)
	assert(number.GCD(b1 + b0, p1) == p1)
	assert(number.GCD(b2 + b0, p2) == p2)
	assert((b1 + b0) % p1 == 0)
	assert((b2 + b0) % p2 == 0)
	print b0

	k = 0
	while True:
		b = b0 + k * p1 * p2
		if b >= 2**1024:
			raise Exception('failed to find b')
		q1 = (b1 + b) / p1
		if not number.isPrime(q1) or number.GCD(e, q1-1) != 1:
			k = k + 1
			continue
		q2 = (b1 + b) / p2
		if not number.isPrime(q2) or number.GCD(e, q2-1) != 1:
			k = k + 1
			continue
		n1 = b1 + b
		n2 = b2 + b
		break
	print b
	assert(p1.bit_length() > 256)
	assert(p2.bit_length() > 256)
	assert(q1.bit_length() > 256)
	assert(q2.bit_length() > 256)
	assert(n1.bit_length() == 2047)
	assert(n2.bit_length() == 2047)

	print n1
	print p1
	print q1
	print n2
	print p2
	print q2

	with open("moduli1", 'w') as m1, open("moduli2", 'w') as m2, open("sol_3.2.5_factorsA.hex", 'w') as factors1, open("sol_3.2.5_factorsB.hex", 'w') as factors2:
		m1.write(hex(n1)[2:])
		m2.write(hex(n2)[2:])
		factors1.write(hex(p1)[2:] + "\n" + hex(q1)[2:] + "\n")
		factors2.write(hex(p2)[2:] + "\n" + hex(q2)[2:] + "\n")
コード例 #12
0
def pq_maker(b_1, b_2):
	count = 0
	while True:
		print(count)
		p_1 = number.getPrime(500)
		p_2 = number.getPrime(500)
		print("a1")
		while not coprime(p_1-1):
			p_1 = number.getPrime(500)
		print("A")
		while not coprime(p_2-1):
			p_2 = number.getPrime(500)

		b_0 = getCRT(b_1, b_2, p_1, p_2)
		print("k")
		k = 0
		while k < limit2:
			b = b_0 + k*p_1*p_2
			q_1 = (b_1 * limit1 + b)/p_1
 			q_2 = (b_2 * limit1 + b)/p_2
 			if(number.isPrime(q_1) and number.isPrime(q_2) and coprime(q_1-1) and coprime(q_2-1)):
 				return q_1, q_2, p_1, p_2
 			k = k + 1
 			if (k %10000 == 0):
 				print(k)
 		count = count + 1
コード例 #13
0
def getPrimes(bitsize):
    r = random.getrandbits(bitsize)
    p, q = r, r
    while not isPrime(p):
        p += random.getrandbits(bitsize // 4)
    while not isPrime(q):
        q += random.getrandbits(bitsize // 8)
    return p, q
コード例 #14
0
ファイル: phish.py プロジェクト: ymgve/ctf-writeups
 def auxphi(a, b, p, g, s):
     assert (len(a) - nbit)**2 + (len(b) - (nbit - 6))**2 == 0
     assert isPrime(p) and isPrime(p/2)
     assert g > 1
     q = p // 2
     if pow(g, q, p) == 1:
         h = pow(g, s, p)
         r = pow(g, int((a+b)[:nbit - 3]), p) * pow(h, int((a+b)[nbit - 3:]), p) % p
     return bin(r)[2:].zfill(nbit)
コード例 #15
0
def _generate_safe_prime(nbits,
                         probability=params.FALSE_PRIME_PROBABILITY,
                         task_monitor=None):
    """
        Generate a safe prime of size nbits.
        
        A safe prime is one of the form p = 2q + 1, where q is also a prime. 
        The prime p used for ElGamal must be a safe prime, otherwise some 
        attacks that rely on factoring the order p - 1 of the cyclic group 
        Z_{p}^{*} may become feasible if p - 1 does not have a large prime 
        factor. (p = 2q + 1, means p - 1 = 2q, which has a large prime factor,
        namely q)
        
        Arguments:
            nbits::int    -- Bit size of the safe prime p to generate. 
                           This private method assumes that the
                           nbits parameter has already been checked to satisfy 
                           all necessary security conditions.
            probability::int    -- The desired maximum probability that p 
                                   or q may be composite numbers and still be 
                                   declared prime by our (probabilistic) 
                                   primality test. (Actual probability is 
                                   lower, this is just a maximum provable bound)
            task_monitor::TaskMonitor    -- A task monitor for the process.
        
        Returns:
            p::long        -- A safe prime.
        """
    found = False

    # We generate (probable) primes q of size (nbits - 1)
    # until p = 2*q + 1 is also a prime
    while (not found):
        if (task_monitor != None): task_monitor.tick()

        q = number.getPrime(nbits - 1)
        p = 2 * q + 1

        if (not number.isPrime(p, probability)):
            continue

        # Are we sure about q, though? (pycrypto may allow a higher
        # probability of q being composite than what we might like)
        if (not number.isPrime(q, probability)):
            continue  # pragma: no cover (Too rare to test for)

        found = True

    # DEBUG CHECK: The prime p must be of size n=nbits, that is, in
    # [2**(n-1),2**n] (and q must be of size nbits - 1)
    if (params.DEBUG):
        assert 2**(nbits - 1) < p < 2**(nbits), \
                "p is not an nbits prime."
        assert 2**(nbits - 2) < q < 2**(nbits - 1), \
                "q is not an (nbits - 1) prime"

    return p
コード例 #16
0
ファイル: phiPerms.py プロジェクト: dgquintas/my-code-samples
def primesGen(ini=2L):
  if isPrime(ini):
    yield ini
  if not (ini & 0x1): #if even
    ini += 1 #make odd
  while True:
    if isPrime(ini):
      yield ini
    ini += 2
コード例 #17
0
def _generate_safe_prime(nbits, probability=params.FALSE_PRIME_PROBABILITY, 
                         task_monitor=None):
        """
        Generate a safe prime of size nbits.
        
        A safe prime is one of the form p = 2q + 1, where q is also a prime. 
        The prime p used for ElGamal must be a safe prime, otherwise some 
        attacks that rely on factoring the order p - 1 of the cyclic group 
        Z_{p}^{*} may become feasible if p - 1 does not have a large prime 
        factor. (p = 2q + 1, means p - 1 = 2q, which has a large prime factor,
        namely q)
        
        Arguments:
            nbits::int    -- Bit size of the safe prime p to generate. 
                           This private method assumes that the
                           nbits parameter has already been checked to satisfy 
                           all necessary security conditions.
            probability::int    -- The desired maximum probability that p 
                                   or q may be composite numbers and still be 
                                   declared prime by our (probabilistic) 
                                   primality test. (Actual probability is 
                                   lower, this is just a maximum provable bound)
            task_monitor::TaskMonitor    -- A task monitor for the process.
        
        Returns:
            p::long        -- A safe prime.
        """
        found = False
        
        # We generate (probable) primes q of size (nbits - 1) 
        # until p = 2*q + 1 is also a prime
        while(not found):
            if(task_monitor != None): task_monitor.tick()
        
            q = number.getPrime(nbits - 1)
            p = 2*q + 1
            
            if(not number.isPrime(p, probability)):
                continue
                
            # Are we sure about q, though? (pycrypto may allow a higher 
            # probability of q being composite than what we might like)
            if(not number.isPrime(q, probability)):
                continue    # pragma: no cover (Too rare to test for)
            
            found = True
            
        # DEBUG CHECK: The prime p must be of size n=nbits, that is, in 
        # [2**(n-1),2**n] (and q must be of size nbits - 1)
        if(params.DEBUG):
            assert 2**(nbits - 1) < p < 2**(nbits), \
                    "p is not an nbits prime."
            assert 2**(nbits - 2) < q < 2**(nbits - 1), \
                    "q is not an (nbits - 1) prime"
                    
        return p
コード例 #18
0
ファイル: solver.py プロジェクト: mcdxn/justctf-2019
def solve():

    p = b'justGiveTheFlag!!' + Random.get_random_bytes(14) + b'\x0f'
    p = number.bytes_to_long(p)

    while not number.isPrime(p) or not number.isPrime((p - 1) >> 1):
        p = b'justGiveTheFlag!!' + Random.get_random_bytes(14) + b'\x0f'
        p = number.bytes_to_long(p)

    return p, (p - 1) >> 1, hex(p).rstrip('L')
コード例 #19
0
    def isStrongPrime(p):
        nextp = p + 1
        while not number.isPrime(nextp):
            nextp = nextp + 1

        lastp = p - 1
        while not number.isPrime(lastp):
            lastp = lastp - 1

        return (p * 2 > nextp + lastp)
コード例 #20
0
 def test_isPrime(self):
     """Util.number.isPrime"""
     self.assertEqual(
         number.isPrime(-3),
         False)  # Regression test: negative numbers should not be prime
     self.assertEqual(
         number.isPrime(-2),
         False)  # Regression test: negative numbers should not be prime
     self.assertEqual(
         number.isPrime(1), False
     )  # Regression test: isPrime(1) caused some versions of PyCrypto to crash.
     self.assertEqual(number.isPrime(2), True)
     self.assertEqual(number.isPrime(3), True)
     self.assertEqual(number.isPrime(4), False)
     self.assertEqual(number.isPrime(2**1279 - 1), True)
     self.assertEqual(
         number.isPrime(-(2**1279 - 1)),
         False)  # Regression test: negative numbers should not be prime
     # test some known gmp pseudo-primes taken from
     # http://www.trnicely.net/misc/mpzspsp.html
     for composite in (43 * 127 * 211, 61 * 151 * 211, 15259 * 30517,
                       346141 * 692281, 1007119 * 2014237, 3589477 *
                       7178953, 4859419 * 9718837, 2730439 * 5460877,
                       245127919 * 490255837, 963939391 * 1927878781,
                       4186358431 * 8372716861, 1576820467 * 3153640933):
         self.assertEqual(number.isPrime(int(composite)), False)
コード例 #21
0
ファイル: ecc-rsa.py プロジェクト: AiDaiP/buu_challenges
def gen_rsa_primes(G):
	urand = bytes_to_long(urandom(521//8))
	while True:
		s = getrandbits(521) ^ urand

		Q = s*G
		if isPrime(Q.x) and isPrime(Q.y):
			print("ECC Private key:", hex(s))
			print("RSA primes:", hex(Q.x), hex(Q.y))
			print("Modulo:", hex(Q.x * Q.y))
			return (Q.x, Q.y)
コード例 #22
0
 def auxphi(a, b, p, g, s):
     assert (len(a) - nbit)**2 + (len(b) - (nbit - 6))**2 == 0
     assert isPrime(p) and isPrime(p / 2)
     assert g > 1
     q = p // 2
     if pow(g, q, p) == 1:
         h = pow(g, s, p)
         r = pow(g, int(
             (a + b)[:nbit - 3]), p) * pow(h, int(
                 (a + b)[nbit - 3:]), p) % p
     return bin(r)[2:].zfill(nbit)
コード例 #23
0
 def __init__(self, p=None, q=None, bits=8):
     if not p:
         p = number.getPrime(bits)
     if not q:
         q = number.getPrime(bits)
     self.p = p if number.isPrime(p) else exit(-1)
     self.q = q if number.isPrime(q) else exit(-1)
     self.n = p * q
     self.phi = (p - 1) * (q - 1)
     self.e = self.get_e(self.phi, bits)
     self.d = self.get_d(self.e, self.phi)
コード例 #24
0
def next_prime(s):
    if s % 6 == 0:
        s += 1
    elif s % 6 != 1:
        s = s - s % 6 + 5
    while True:
        if isPrime(s) == True:
            break
        s += 2
        if isPrime(s) == True:
            break
        s += 4
    return s
コード例 #25
0
def next_level(n):
    nsum = sum([int(x) for x in str(n)])
    hs = []
    ps = []

    for i in range(10):
        h = n * 10 + i
        if h % (nsum + i) == 0:
            hs.append(h)
        elif isPrime(h) and isPrime(n // nsum):
            ps.append(h)

    return hs, ps
コード例 #26
0
ファイル: Hanukkah.py プロジェクト: noobintheshell/ctfs
def genKey(k):

    while True:
        r = getrandbits(k)
        while (r % 2):
            r = getrandbits(k)

        p = 3 * r**2 + 2 * r + 7331
        q = 17 * r**2 + 18 * r + 1339
        n = p * q

        if (isPrime(p) and isPrime(q)):
            return (p, q), n
コード例 #27
0
 def __init__(self, p=None, q=None, bits=8):
     if not p:
         p = number.getPrime(bits)
    # print('check p;',p)
     if not q:
         q = number.getPrime(bits)
     #print('check q;',q)
     self.p = p if number.isPrime(p) else exit(-1)
     self.q = q if number.isPrime(q) else exit(-1)
     self.n = p * q # Their product n = p * q is calculated, which is called the modulus.
     self.phi = (p - 1) * (q - 1) # The value of the Euler function of the number n is calculated:
     self.e = self.get_e(self.phi, bits) # An integer is selected that is relatively prime with the value of the function phi (n)
     self.d = self.get_d(self.e, self.phi) # The number d is calculated, which is multiplicatively inverse to the number e modulo phi (n)
コード例 #28
0
ファイル: Weird RSA.py プロジェクト: r3yc0n1c/CTF-Writeups
def genPrimes(size):
    base = random.getrandbits(size // 2) << size // 2
    base = base | (1 << 1023) | (1 << 1022) | 1
    while True:
        temp = base | random.getrandbits(size // 4)
        if isPrime(temp):
            p = temp
            break
    while True:
        temp = base | random.getrandbits(size // 4)
        if isPrime(temp):
            q = temp
            break
    return (p, q)
コード例 #29
0
ファイル: test_number.py プロジェクト: zhangfp/hr_release
 def test_isPrime(self):
     """Util.number.isPrime"""
     self.assertEqual(number.isPrime(2), True)
     self.assertEqual(number.isPrime(3), True)
     self.assertEqual(number.isPrime(4), False)
     self.assertEqual(number.isPrime(2L**1279-1), True)
     # test some known gmp pseudo-primes taken from
     # http://www.trnicely.net/misc/mpzspsp.html
     for composite in (43 * 127 * 211, 61 * 151 * 211, 15259 * 30517,
                       346141L * 692281L, 1007119L * 2014237L, 3589477L * 7178953L,
                       4859419L * 9718837L, 2730439L * 5460877L,
                       245127919L * 490255837L, 963939391L * 1927878781L,
                       4186358431L * 8372716861L, 1576820467L * 3153640933L):
         self.assertEqual(number.isPrime(long(composite)), False)
コード例 #30
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
コード例 #31
0
ファイル: crypto.py プロジェクト: kcbanner/ece419
def validate(p, q, g):
    p_length = p.bit_length()

    if (p_length % 64) != 0:
        print "p's bit length not a mulitple of 64"
        return False

    if not (p_length >= 512 and p_length <= 1024):
        print "p's bit length is not between 512 and 1024"
        return False

    if not number.isPrime(p):
        print "p not prime"
        return False

    try:
        _number_new.exact_div(p - 1, q)
    except ValueError:
        print "q is not a prime factor of p"
        return False

    # g = u^{(p-1)/q}

    u = power_mod(g, 1 / _number_new.exact_div(p - 1, q), p)
    print u

    if not (u > 0 and u < p):
        print "g is invalid"
        return False
        
    return True
コード例 #32
0
ファイル: calc_mod.py プロジェクト: Toast3y/adv_sec1_labs2015
def generate_large_num2():
    # Generate another large number using pythons in built random function. Checks if it's prime.
    LargeNum = random.getrandbits(BLOCK_SIZE)
    if RandGen.isPrime(LargeNum) == True:
        tkMessageBox.showinfo("Large Number Generator 2", str(LargeNum) + " is a prime number.")
    else:
        generate_large_num2()
コード例 #33
0
ファイル: Elgamal.py プロジェクト: oneApple/CryptoAlgorithms
def GetElgamalParamqp(bits = 100):
    while 1:
        q = bignum(getPrime(bits-1, Random.new().read))
        p = 2*q+1
        if number.isPrime(p, randfunc=Random.new().read):
            break
    return q,p
コード例 #34
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
コード例 #35
0
ファイル: solve.py プロジェクト: zihuocc/public-writeup
def epicfail(n):
    x = 0
    mode = 'epicfail'
    while n:
        if n % 10000 == 0:
            print("progress: ", n)
        if mode == 'epicfail':
            if isPrime(n):
                x += 1
                mode = 'bill'
            else:
                mode = 'such'
        elif mode == 'bill':
            y = brotherman(n)
            if y % 3 == 0:
                x += 1
                mode = 'such'
            else:
                mode = 'epicfail'
            x += y
        elif mode == 'such':
            y = dootdoot_5(n)
            if y % 7 == 0:
                x += 1
                mode = 'bill'
            else:
                mode = 'epicfail'
            x += y
        n -= 1
    return x
コード例 #36
0
ファイル: calc_mod.py プロジェクト: Toast3y/adv_sec1_labs2015
def generate_large_num():
    # Generate a very large number for cryptographic purposes. Checks the number afterwards if it's prime or not. Recursively calls until it is prime.
    LargeNum = RandGen.getPrime(BLOCK_SIZE)
    if RandGen.isPrime(LargeNum) == True:
        tkMessageBox.showinfo("Large Number Generator", str(LargeNum) + " is a prime number.")
    else:
        generate_large_num()
コード例 #37
0
ファイル: helpers.py プロジェクト: boldprogressives/mist.io
def validate_dsa_key_pair(public_key, private_key):
    """ Validates a pair of dsa keys """

    # FIXME: Make this function validate private key too

    # Construct DSA key
    keystring = binascii.a2b_base64(public_key.split(" ")[1])
    keyparts = []

    while len(keystring) > 4:
        length = struct.unpack(">I", keystring[:4])[0]
        keyparts.append(keystring[4 : 4 + length])
        keystring = keystring[4 + length :]

    if keyparts[0] == "ssh-dss":
        tup = [bytes_to_long(keyparts[x]) for x in (4, 3, 1, 2)]
    else:
        return False

    key = DSA.construct(tup)

    # Validate DSA key
    fmt_error = not isPrime(key.p)
    fmt_error |= ((key.p - 1) % key.q) != 0
    fmt_error |= key.g <= 1 or key.g >= key.p
    fmt_error |= pow(key.g, key.q, key.p) != 1
    fmt_error |= key.y <= 0 or key.y >= key.p

    # The following piece of code is currently useless, because 'x' attribute is the private key
    # if hasattr(key, 'x'):
    #    fmt_error |= key.x<=0 or key.x>=key.q
    #    fmt_error |= pow(key.g, key.x, key.p)!=key.y

    return not fmt_error
コード例 #38
0
def worker(needed_count, minimal_diameter):
    while True:
        p = getPrime(1024)
        primes = [p]

        q = p + 2

        count = 1
        # print('...')

        while True:
            if isPrime(q):
                primes.append(q)
                count += 1

                if q - p > minimal_diameter.value:
                    # already worse than before
                    break

                if count == needed_count:
                    if q - p < minimal_diameter.value:
                        minimal_diameter.value = q - p
                        print('New minimal diameter =', minimal_diameter.value)
                        print(primes)
                        n = 1
                        for p in primes:
                            n *= p
                        print('n =', n)
                        print()
                    break

            q += 2
コード例 #39
0
def gen_key(bits):
    """
    鍵生成
    :param bits: 鍵の長さ
    :return: 公開鍵: (p: 素数, g: Zp*の原始元, y: g^x(mod p)), 秘密鍵: x
    """
    # 素数p
    while True:
        q = number.getPrime(bits - 1)
        p = 2 * q + 1
        if number.isPrime(p):
            break
    # 原始元g
    while True:
        g = number.getRandomRange(3, p)
        # 原始元判定
        if pow(g, 2, p) == 1:
            continue
        if pow(g, q, p) == 1:
            continue
        break
    # 秘密値x
    x = number.getRandomRange(2, p - 1)
    # 公開値y
    y = pow(g, x, p)
    return (p, g, y), x
コード例 #40
0
ファイル: calc_mod.py プロジェクト: Toast3y/adv_sec1_labs2015
def get_next_prime(possible_prime):
    # Find the next number given a prime number, and return it
    if RandGen.isPrime(possible_prime) == True:
        return possible_prime
    else:
        possible_prime = get_next_prime(possible_prime + 2)
    return possible_prime
コード例 #41
0
def generate(bits, randfunc, progress_func=None):
    obj = ElGamalobj()
    if progress_func:
        progress_func('p\n')
    while 1:
        q = bignum(getPrime(bits - 1, randfunc))
        obj.p = 2 * q + 1
        if number.isPrime(obj.p, randfunc=randfunc):
            break

    if progress_func:
        progress_func('g\n')
    while 1:
        obj.g = number.getRandomRange(3, obj.p, randfunc)
        safe = 1
        if pow(obj.g, 2, obj.p) == 1:
            safe = 0
        if safe and pow(obj.g, q, obj.p) == 1:
            safe = 0
        if safe and divmod(obj.p - 1, obj.g)[1] == 0:
            safe = 0
        ginv = number.inverse(obj.g, obj.p)
        if safe and divmod(obj.p - 1, ginv)[1] == 0:
            safe = 0
        if safe:
            break

    if progress_func:
        progress_func('x\n')
    obj.x = number.getRandomRange(2, obj.p - 1, randfunc)
    if progress_func:
        progress_func('y\n')
    obj.y = pow(obj.g, obj.x, obj.p)
    return obj
コード例 #42
0
ファイル: TD.py プロジェクト: El-gitano/TD-SECU
def DSAGenParameter():

	print "Génération des paramètres"
	
	# On génère Q
	print "Génération de Q"
	q = number.getPrime(160)
	print "Q généré"
	
	# On génère P
	print "Génération de P"
	while True:
	
		r = number.getRandomInteger(480)
		p = (q*r)+1
		
		if number.isPrime(p):
			break
	print "P généré"
	
	# On génère G
	print "Génération de G"
	while True:
	
		y = number.getRandomRange(0, p)
		g = pow(y, (p-1)/q, p)
		
		if g != 1:
			break
	print "G généré"
	
	print "Paramètres générés"
	
	return p, q, y, g
コード例 #43
0
def canbe_written( odd_composite):
   # odd_composite = prime + 2*square
   for double_square in (2*n*n for n in count(1)):
      prime = odd_composite - double_square
      if prime < 0: break # consider `1' as a prime too
      if number.isPrime( long(prime) ):
         return True     
   return False
コード例 #44
0
ファイル: goldbach.py プロジェクト: dgquintas/my-code-samples
def getPrimes(start = 2L):
  if start <= 2:
    yield 2L
    start = 3L
  n = long(start)
  while True:
    if number.isPrime(n):
      yield n
    n += 2
コード例 #45
0
ファイル: dsa.py プロジェクト: lukius/mts
 def _choose_p_from(self, q):
     i = 2
     while True:
         p = i*q + 1
         # TODO: implement Miller-Rabin
         if number.isPrime(p):
             break
         i += 1
     return p
コード例 #46
0
ファイル: p7.py プロジェクト: JeroenDeDauw/ProjectEuler
def findNthPrime( n ):
    currentCount = 1
    currentNumber = long( 2 )

    while currentCount < n:
        currentNumber += 1
        if isPrime( currentNumber ):
            currentCount += 1

    return currentNumber
コード例 #47
0
    def validate_cryptosystem(self):
        from Crypto.Util.number import isPrime
        pk = self.public_key
        if pow(pk.g, pk.q, pk.p) != 1:
            m = "g is not a generator, or q is not its order!"
            raise AssertionError(m)

        if not isPrime(pk.p):
            m = "modulus not prime!"
            raise AssertionError(m)

        if not isPrime(pk.q):
            m = "subgroup order not prime!"
            raise AssertionError(m)

        if 2*pk.q + 1 != pk.p:
            m = "modulus not in the form 2*(prime subgroup order) + 2"
            raise AssertionError(m)

        return 1
コード例 #48
0
ファイル: p3.py プロジェクト: JeroenDeDauw/ProjectEuler
def getNextPrime( lowerBound ):
    ''' Lower bound not included '''
    nextPrime = 0
    lowerBound = long( lowerBound )

    while nextPrime == 0:
        lowerBound += 1
        if isPrime( lowerBound ):
            nextPrime = lowerBound

    return nextPrime
コード例 #49
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)
コード例 #50
0
def generate(bits, randfunc, progress_func=None):
    """generate(bits:int, randfunc:callable, progress_func:callable)

    Generate an ElGamal key of length 'bits', using 'randfunc' to get
    random data and 'progress_func', if present, to display
    the progress of the key generation.
    """
    obj=ElGamalobj()
    # Generate a safe prime p
    # See Algorithm 4.86 in Handbook of Applied Cryptography
    if progress_func:
        progress_func('p\n')
    while 1:
        q = bignum(getPrime(bits-1, randfunc))
        obj.p = 2*q+1
        if number.isPrime(obj.p, randfunc=randfunc):
            break
    # Generate generator g
    # See Algorithm 4.80 in Handbook of Applied Cryptography
    # Note that the order of the group is n=p-1=2q, where q is prime
    if progress_func:
        progress_func('g\n')
    while 1:
        # We must avoid g=2 because of Bleichenbacher's attack described
        # in "Generating ElGamal signatures without knowning the secret key",
        # 1996
        #
        obj.g = number.getRandomRange(3, obj.p, randfunc)
        safe = 1
        if pow(obj.g, 2, obj.p)==1:
            safe=0
        if safe and pow(obj.g, q, obj.p)==1:
            safe=0
        # Discard g if it divides p-1 because of the attack described
        # in Note 11.67 (iii) in HAC
        if safe and divmod(obj.p-1, obj.g)[1]==0:
            safe=0
        # g^{-1} must not divide p-1 because of Khadir's attack
        # described in "Conditions of the generator for forging ElGamal
        # signature", 2011
        ginv = number.inverse(obj.g, obj.p)
        if safe and divmod(obj.p-1, ginv)[1]==0:
            safe=0
        if safe:
            break
    # Generate private key x
    if progress_func:
        progress_func('x\n')
    obj.x=number.getRandomRange(2, obj.p-1, randfunc)
    # Generate public key y
    if progress_func:
        progress_func('y\n')
    obj.y = pow(obj.g, obj.x, obj.p)
    return obj
コード例 #51
0
ファイル: _ECDSA.py プロジェクト: paulswartz/pycrypto
    def verify(self, t=None):
        # Specified in SEC1 3.1.1.2.1
        if t is not None:
            log2_ceil = math.ceil(math.log(self.p, 2))
            if 80 < t < 256:
                if log2_ceil != 2 * t:
                    return False
            elif t == 80:
                if log2_ceil != 192:
                    return False
            elif t == 256:
                if log2_ceil != 521:
                    return False

        # verify P is prime
        if not number.isPrime(self.p):
            return False

        # verify attributes are in the range [0, p-1]
        if self.a >= self.p:
            return False
        if self.b >= self.p:
            return False
        if self.G.x >= self.p:
            return False
        if self.G.y >= self.p:
            return False

        # check curve parameters
        if (4 * pow(self.a, 3, self.p) +
            27 * pow(
                self.b, 2, self.p)) % self.p == 0:
            return False
        if not self.G.verify():
            return False

        # verify N is prime
        if not number.isPrime(self.n):
            return False

        return True
コード例 #52
0
ファイル: test_number.py プロジェクト: hfalcic/google-gdata
 def test_isPrime(self):
     """Util.number.isPrime"""
     self.assertEqual(number.isPrime(-3), False)     # Regression test: negative numbers should not be prime
     self.assertEqual(number.isPrime(-2), False)     # Regression test: negative numbers should not be prime
     self.assertEqual(number.isPrime(1), False)      # Regression test: isPrime(1) caused some versions of PyCrypto to crash.
     self.assertEqual(number.isPrime(2), True)
     self.assertEqual(number.isPrime(3), True)
     self.assertEqual(number.isPrime(4), False)
     self.assertEqual(number.isPrime(2**1279-1), True)
     self.assertEqual(number.isPrime(-(2**1279-1)), False)     # Regression test: negative numbers should not be prime
     # test some known gmp pseudo-primes taken from
     # http://www.trnicely.net/misc/mpzspsp.html
     for composite in (43 * 127 * 211, 61 * 151 * 211, 15259 * 30517,
                       346141 * 692281, 1007119 * 2014237, 3589477 * 7178953,
                       4859419 * 9718837, 2730439 * 5460877,
                       245127919 * 490255837, 963939391 * 1927878781,
                       4186358431 * 8372716861, 1576820467 * 3153640933):
         self.assertEqual(number.isPrime(int(composite)), False)
コード例 #53
0
def pair(s):
	safe_prime = 0
	while(True):
		p = num.getPrime(s)
		safe_prime = 2*p+1
		if(num.isPrime(safe_prime)):
			break
	while(True):
          a = random.randint(2, safe_prime-1) 
          if((safe_prime-1)%a != 1):
            break
        
        return safe_prime, a
コード例 #54
0
ファイル: SecuPrim.py プロジェクト: galakt/RT_CTF
def get_primes_and_pp(number_from, number_to):
    result = 0
    print('======================================')
    print(number_from)
    print(number_to)
    print('======================================')
    while number_from <= number_to:
        if(sympy.perfect_power(number_from)):
            result += 1
        if(isPrime(number_from)):
            result += 1
        number_from += 1
    return result
コード例 #55
0
ファイル: phiPerms.py プロジェクト: dgquintas/my-code-samples
def factorsGenerator(n):
  primes = primesGen()
  lim = int(sqrt(n))+1
  for p in takewhile(lambda x: x <= lim, primes):
    power = 0
    while n % p == 0:
      power += 1
      n //= p
    if power > 0:
      yield (p, power)
    if isPrime(n):
      break
  yield (n,1)
コード例 #56
0
ファイル: dsa_key.py プロジェクト: manisero/SemesterIX
    def _generate(self, bits):
        if bits < 160:
            raise ValueError('Key is too short!')

        while True:
            seed, self.q = self._generate_q()
            n = divmod(bits - 1, 160)[0]
            counter, offset, v = 0, 2, {}
            b = self.q >> 5 & 15
            two_power_b = pow(2L, b)
            two_power_bits_minus_one = pow(2L, bits - 1)

            while counter < 4096:
                for k in range(0, n+1):
                    v[k] = bytes_to_long(SHA.new(
                        seed + str(offset) + str(k)).digest())

                w = v[n] % two_power_b

                for k in range(n - 1, -1, -1):
                    w = (w << 160L) + v[k]

                x = w + two_power_bits_minus_one
                c = x % (2 * self.q)
                self.p = x - (c - 1)

                if two_power_bits_minus_one <= self.p and isPrime(self.p):
                    break

                counter += 1
                offset += n + 1

            if counter < 4069:
                break

        power = divmod(self.p - 1, self.q)[0]

        while True:
            h = bytes_to_long(os.urandom(bits)) % (self.p - 1)
            self.g = pow(h, power, self.p)

            if 1 < h < self.p - 1 and self.g > 1:
                break

        while True:
            self.x = bytes_to_long(os.urandom(20))

            if 0 < self.x < self.q:
                break

        self.y = pow(self.g, self.x, self.p)
コード例 #57
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
コード例 #58
0
ファイル: primes.py プロジェクト: doomzzju/BFSSH
def _generate_prime(bits, randpool):
    "primtive attempt at prime generation"
    hbyte_mask = pow(2, bits % 8) - 1
    while True:
        # loop catches the case where we increment n into a higher bit-range
        x = randpool.get_bytes((bits+7) // 8)
        if hbyte_mask > 0:
            x = chr(ord(x[0]) & hbyte_mask) + x[1:]
        n = util.inflate_long(x, 1)
        n |= 1
        n |= (1 << (bits - 1))
        while not number.isPrime(n):
            n += 2
        if util.bit_length(n) == bits:
            return n