Exemple #1
0
def main(N):
    c=gmpy2.context()
    c.precision=len(str(N))+20
    c.real_prec=len(str(N))+20
    gmpy2.set_context(c)
    assert N==gmpy2.mpz(N)
    N=gmpy2.mpz(N)
    A=find_sqrt(N)
    A = gmpy2.mpz(A)
    assert ( (A-1)**2<N<A**2 ),'not found'
    Atag = A
    for iA in xrange(-2**20,2**20):
        A = Atag + iA
        s =A**2-N
        x = gmpy2.sqrt(s)
        try:
            x = gmpy2.mpz(x)
        except:continue
        print x**2 > s ,  x**2 < s
        '''while x**2>s:
            x-=1
            print 1,'''
        print x**2 > s ,  x**2 < s

        p = A-x
        q = A+x
        q = N/p

        if p*q==N:
            print gmpy2.is_prime(q)
            print gmpy2.is_prime(p)
            print min(p,q)
            break
Exemple #2
0
def checkFactors(p,q,N):
  x = g.f_mod( N, p )
  y = g.f_mod( N, q )
  zero = g.mpz('0')
  if g.is_prime(p) and g.is_prime(q):
    return N == g.mul(p,q) and x == zero and y == zero
  return False
Exemple #3
0
def main23(N):
    c=gmpy2.context()
    c.precision=len(str(N))+20
    c.real_prec=len(str(N))+20
    gmpy2.set_context(c)
    assert N==gmpy2.mpz(N)
    N=gmpy2.mpz(N)
    A=find_sqrt(6*N)
    A = gmpy2.mpz(A)
    assert ( (A-1)**2<6*N<A**2 ),'not found'
    Atag = A
    for iA in xrange(-2**20,2**20):
        A = Atag + iA
        s =A**2-N
        x = gmpy2.sqrt(s)
        try:
            x = gmpy2.mpz(x)
        except:continue
        '''print x**2 > s ,  x**2 < s
        while x**2>s:
            x-=1
            print 1,
        print x**2 > s ,  x**2 < s'''
        for p in [(A-x)/2,(A-x)/3,(A+x)/2,(A+x)/3   ]:
            q = N/p
            
            if p*q==N:
                print gmpy2.is_prime(q)
                print gmpy2.is_prime(p)
                print min(p,q)
                assert False,'bla'
Exemple #4
0
def factor_N3(N):
	'''Factor in correctly genrated N,
which is a product of two relatively close primes p/q such that,
|3p-2q| < N^(1/4)'''

	N = mpz(N)	
	M = 2*gmpy2.isqrt(6*N)+1	# M = (3p+2q)
	# M = (3p+2q)
	# x = (3p-2q)
	x = gmpy2.isqrt(M*M - 24*N)	# X = (3p-2q)

	# since p,q is not symmetric around M/2, we need to consider two cases
	p1 = (M+x)/6
	q1 = (M-x)/4
			
	p2 = (M-x)/6
	q2 = (M+x)/4

	if gmpy2.is_prime(p1) and gmpy2.is_prime(q1) and p1*q1 == N:
		if p1<q1:
			return p1,q1
		else:
			return q1,p1

	if gmpy2.is_prime(p2) and gmpy2.is_prime(q2) and p2*q2 == N:
		if p2<q2:
			return p2,q2
		else:
			return q2,p2
	return 0
Exemple #5
0
def factor_prime(prime):

    # p - 1 is 37-smooth
    base = 2
    k_sm = 37

    # pow(base,k_sm!) mod prime
    a = gmpy2.powmod(base, gmpy2.fac(k_sm), prime)

    # gcd(r_k - 1, prime)
    p = gmpy2.gcd(a-1, prime)

    # get second factor of prime
    q = (prime / p)

    # make sure factors (pq) are prime
    if (gmpy2.is_prime(p) and gmpy2.is_prime(q)):
        print "p = ", p
        print "q = ", q

        # make sure n = p*q = prime number
        n = gmpy2.mul(p,q)

        if (n == prime):
            print "n = ", gmpy2.mul(p,q)

    return
def confirmed(N, p, q):
    if gmpy2.is_prime(mpz(p)) and gmpy2.is_prime(mpz(q)) and N == gmpy2.mul(p, q):
        print "N =", N
        print "p =", p
        print "q =", q
        print "confirmed prime factors, smaller prime:"
        print q if p > q else p
        return True
    return False
Exemple #7
0
def get_safe_prime(bits):
    """Get a safe prime which is a specified number of bits long."""

    while True:
        # Generate a random 1024 bit number, ensuring the lowest order bit is 1 (so it's odd).
        candidate = (get_random(bits - 1) << 1) | 1
        if candidate % 12 != 11:
            continue  # all safe primes mod 12 are 11
        if not is_prime(candidate):
            continue  # obviously a safe prime must be prime
        if not is_prime((candidate - 1) // 2):
            continue  # a safe prime must be equal to 2q + 1 where q is prime
        return candidate
def challenge1 (N):
    """Factor N=p*q where abs(p-q) < 2*N**(1/4)"""
    N = mpz(N)    
    A = isqrt(N)
    while 1:
        # A = (p+q)/2 is also ceil(sqrt(N)) indeed (A-sqrt(N)) < 1
        # x integer such that p = A - x, q = A + x; x = sqrt(A*A - N)
        if pow(A, 2) > N:
            x = isqrt(pow(A, 2) - N)
            p = A - x
            q = A + x
            if ((mul(p,q) == N) and is_prime(p) and is_prime(q)):
                return (p,q)
        A = A + 1
def generate_prime(bits):
    """Will generate an integer of b bits that is prime 
    using the gmpy2 library  """    
    while True:
        possible =  mpz(2)**(bits-1)   + mpz_urandomb(rand, (bits-1) ) 
        if is_prime(possible):
            return possible
Exemple #10
0
 def __init__(self,N):
     self.N=N
     if gmpy2.is_prime(self.N):
     #if self.isPrime(N):
         self.prime=True
     else:
         self.prime=False
def checkTruncPrime(n, found, lprimes, rprimes):

  isPrime= gmpy2.is_prime(int(n))

  good = True
  
  nsl1=n[1:]
  if not rprimes.has_key(nsl1):
    good = False
  else:
    if isPrime:
     rprimes[n] = 0;

  nsr1=n[:-1]
  if not lprimes.has_key(nsr1):
    good = False
  else:
    if isPrime:
      lprimes[n] = 0;

  # is it good both ways?
  if not good:
    return False

  if not isPrime:
    return False

  if result.has_key(nsl1):
    result[nsl1] = 1 # mark as substring of bigger tprime
  if result.has_key(nsr1):
    result[nsr1] = 1 # mark as substring of bigger tprime
  result[n] = 0 # add new item

  return True
    def __init__(self, p=None, q=None, bit_length=512, e=None):
        """
        设定 p 和 q, 如果没有则根据 bit_length 来产生对应长度的素数
        :param p: 素数 p
        :param q: 素数 q
        :param bit_length: 比特位的长度
        """
        if p and q and gmpy2.is_prime(p) and gmpy2.is_prime(q):
            self.p = p
            self.q = q
        else:
            print("[*] 未给定合理的 p 和 q, 程序将自行产生")
            self.p = getPrime(bit_length)
            self.q = getPrime(bit_length)

        self.__create_rsa(e)
def check(p):
    x = p//10
    sd = sumdigits(x)

    while(x>0):
            xx = x%sd
            if xx != 0:
                return False
            sd-= x%10 
            x//=10
    x=p//10
    if not gmpy2.is_prime(x//sumdigits(x)):
            return False
    if not gmpy2.is_prime(p):
        return False
    return True
def factorize(x):
    r"""
    >>> factorize(a)
    [3, 41]
    >>> factorize(b)
    [2, 2, 2, 3, 19]
    >>>
    """
    savex = x
    prime = 2
    x = _g.mpz(x)
    factors = []
    while x >= prime:
        newx, mult = _g.remove(x, prime)
        if mult:
            factors.extend([int(prime)] * mult)
            x = newx
        prime = _g.next_prime(prime)
    for factor in factors:
        assert _g.is_prime(factor)
    from operator import mul
    from functools import reduce

    assert reduce(mul, factors) == savex
    return factors
Exemple #15
0
def new_prime():
    np = mpz(r.getrandbits(DH_Consts.bits - 1))
    np = gmpy2.next_prime(np)

    while not gmpy2.is_prime(2 * np + 1, 25):
        np = gmpy2.next_prime(np)

    return mpz(2 * np + 1)
def isTruncatable(n):
	nleft = str(n)
	nright = str(n)
	
	# check from left
	while len(nleft) > 0:
		if not is_prime(int(nleft)):
			return False
		nleft = nleft[:-1]
	
	# check from right
	while len(nright) > 0:
		if not is_prime(int(nright)):
			return False
		nright = nright[1:]
	
	return True
Exemple #17
0
def main():
    #   first make a dummy request to find the public modulus for our team
    initial_request = {"team": TEAM, "ciphertext": "00"*(n//8)}
    r = requests.post(SERVER_URL + "/decrypt", data=json.dumps(initial_request))
    try:
        N = int(r.json()["modulus"], 16)
    except:
        print(r.text)
        sys.exit(1)

    #   compute R^{-1}_N
    Rinv = gmpy2.invert(R, N)

    #   Start with a "guess" of 0, and analyze the zero-one gap, updating our
    #   guess each time. Repeat this for the (512-16) most significant bits of q
    g = 0

    # get bits 2-5
    start_bits = 2
    max_i = 0
    max_t = 0
    for i in range(1, 2**start_bits):
        t_1 = 0
        for j in range(1024):
            t_1 += time_decrypt(gmpy2.mpz(i * 2**(511 - start_bits) + 2**511 + j))
        print(i, t_1)
        if t_1 > max_t:
            max_t = t_1
            max_i = i

    print("MAX:", max_i, max_t)

    g += max_i*2**(511 - start_bits) + 2**511
    # Q -= g

    for i in range(start_bits + 2, 512-16):
        gap = compute_gap(g, i, Rinv, 50, N)
        #   TODO: based on gap, decide whether bit (512 - i) is 0 or 1, and
        #   update g accordingly

        # bit = Q // (2**(512 - i))
        # print("gap:", gap, "\t bit at index", i, "should be", bit)

        # if bit == 1:
        #     Q -= 2**(512 - i)
        #     g += 2**(512 - i)

        print("gap:", gap, "\t bit at index", i)
        if gap < threshold:
            g += 2**(512 - i)
    
    # brute-force last 16 bits
    for i in range(2**16):
        q = g + i
        if gmpy2.is_prime(q):
            if submit_guess(q):
                print("hooray:", q)
                break
Exemple #18
0
 def next_prime(x):
     """Return the next probable prime number > x."""
     if x <= 1:
         x = 2
     else:
         x += 1 + x%2
         while not is_prime(x):
             x += 2
     return x
def gen_rand_prime(bit):
    while 1:
        num = gmpy2.mpz(1)
        a = randint(0, 2, bit)
        for i in a:
            num = num * 2 + i
        if gmpy2.is_prime(num):
            break
    return num
Exemple #20
0
 def num_consecutive_primes_fitness(self, interval):
     i = interval[0]
     last_x = 0
     x = self.eval_polynomial(np.array([i]))[0]
     while is_prime(int(x)) and last_x != x and x > 0:
         i += 1
         last_x = x
         x = self.eval_polynomial(np.array([i]))[0]
     return i
Exemple #21
0
def count_valids(s, minp=1):
    if len(s) == 0:
        return 1
    nvalids = 0
    for i in range(1, len(s) + 1):
        p = int(s[:i])
        if p > minp and is_prime(p):
            nvalids += count_valids(s[i:], p)
    return nvalids
def getFactor(x):
    if gmpy2.is_prime(x):
      factor=x-1
    else:
      if len(str(x)) <= 20:
        factor=phi(x)
      else:
        factor=None    
    return factor
Exemple #23
0
def generate_m(p):
    """ Generate large pseudo prime m, which satisfy p|(m-1) .
    """
    q=1
    m=p*2*q+1
    while not gmpy2.is_prime(m):
        q=q+1
        m= p*2*q+1
    return m,q
Exemple #24
0
def p41(l):
  tmp = []
  while l > 3:
    i = list(map(str,range(1,l+1)))
    for N in map(lambda x:int("".join(list(x))), permutations(i)):
      a = is_prime(N)
      if a == True:
        tmp.append(N)
    l-=1
  return sorted(tmp)[-1]
Exemple #25
0
def createPrime(sizeOFMod):
        x = 0
        while x == 0:
            upperBit = math.pow(2, sizeOFMod) - 1

            lowerBit = math.pow(2, (sizeOFMod - 1))
            
            potentialPrime = random.randint(lowerBit, upperBit)
            if gmpy2.is_prime(potentialPrime):
                return potentialPrime
Exemple #26
0
def gen_prime(bits, s):
    #s = random.getrandbits(chunk_size)
    while True:
        s |= 0xc000000000000001
        p = 0
        for _ in range(bits // chunk_size):
            p = (p << chunk_size) + s
            s = a * s % 2**chunk_size
        if gmpy2.is_prime(p):
            return p
Exemple #27
0
def factor(A,N):
	'''Factor big number N, which is product of prime p/q'''
	'''Input: 
		N: big number, 
		A: proposed average of prime p,q
	   Output: 
		prime p,q such that N = p*q and p<q
		or 0 if A is not correct'''
	
	if A*A < N:
		return 0
	x = gmpy2.isqrt(A*A - N)
	p = A-x
	q = A+x

	if gmpy2.is_prime(p) and gmpy2.is_prime(q) and p*q == N:
		return p,q
	else:
		return 0
Exemple #28
0
def gen_prime():
    base = random.getrandbits(1024)
    off = 0
    while True:
        if gmpy2.is_prime(base + off):
            break
        off += 1
    p = base + off

    return p, off
Exemple #29
0
def solve1():
    """
    如果允许用 gmpy2 库就好说了
    :return:
    """
    for i in range(100):
        if gmpy2.is_prime(i):
            if i != 2:
                print(end=" ")
            print(i, end="")
Exemple #30
0
def next_left(cur, base, new_length):
    # Add digits to the left
    mul = base**(new_length - 1)

    new = []
    for left in range(1, base):
        temp = left * mul + cur
        if gmpy2.is_prime(temp):
            new.append(temp)
    return new
Exemple #31
0
 def __getSafePrimes(n_len):
     rng = secrets.SystemRandom()
     prime_ = gmpy2.mpz(rng.getrandbits(n_len - 1))
     prime_ = gmpy2.bit_set(prime_, n_len - 2)
     while True:
         prime_ = gmpy2.next_prime(prime_)
         prime = 2 * prime_ + 1
         if gmpy2.is_prime(prime, 25):
             break
     return prime_, prime
Exemple #32
0
def problem35():
    answer = 500000
    for i in range(3, 1000000, 2):
        number = str(i)
        for j in range(0, len(number)):
            if (not is_prime(int(number))):
                answer -= 1
                break
            number = number[1:] + number[:1]
    return answer
Exemple #33
0
def get_a_prime(l):
    random_seed = urandom(l)

    num = bytes_to_num(random_seed)

    while True:
        if is_prime(num):
            break
        num += 1
    return num
Exemple #34
0
def analyze_number(n):
    print 'Number          %-15s' % n
    print 'Prime           %-15s' % gmpy2.is_prime(n)
    print 'Is square       %-15s' % ((n ** 0.5) == n)
    print 'Square root     %-15s' % (n ** 0.5)
    print 'Cube   root     %-15s' % (n ** (1.0 / 3.0))
    print 'Sum of digits   %-15s' % eulertools.sum_of_digits(n)
    print 'Prime factors   %-15s' % eulertools.primeFactors(n)
    print '# Factors       %-15s' % len(eulertools.divisorGenerator(n))
    print 'Factors         %-15s' % eulertools.divisorGenerator(n)
Exemple #35
0
def factor(A, N):
    '''Factor big number N, which is product of prime p/q'''
    '''Input: 
		N: big number, 
		A: proposed average of prime p,q
	   Output: 
		prime p,q such that N = p*q and p<q
		or 0 if A is not correct'''

    if A * A < N:
        return 0
    x = gmpy2.isqrt(A * A - N)
    p = A - x
    q = A + x

    if gmpy2.is_prime(p) and gmpy2.is_prime(q) and p * q == N:
        return p, q
    else:
        return 0
Exemple #36
0
def getPrimes(size):
    half = random.randint(16, size // 2 - 8)
    rand = random.randint(8, half - 1)
    sizes = [rand, half, size - half - rand]

    while True:
        p, q = 0, 0
        for s in sizes:
            p <<= s
            q <<= s
            chunk = random.getrandbits(s)
            p += chunk
            if s == sizes[1]:
                chunk = random.getrandbits(s)
            q += chunk
        p |= 2**(size - 1) | 2**(size - 2) | 1
        q |= 2**(size - 1) | 2**(size - 2) | 1
        if gmpy2.is_prime(p) and gmpy2.is_prime(q):
            return p, q
Exemple #37
0
def next_right(cur, base):
    # Add digits to the right
    test = cur * base

    new = []
    for right in range(1, base, 2 - (base % 2)):
        temp = test + right
        if gmpy2.is_prime(temp):
            new.append(temp)
    return new
Exemple #38
0
def check_prime(p):
    # type: (int) -> RE
    """
    Checks if given number is a prime

    :p the potential prime
    """
    if not gmpy2.is_prime(p):
        return RSAPublicKeyResult.NON_PRIME
    return RSAPublicKeyResult.OK
Exemple #39
0
def rsa_conspicuous_check(N, p, q, d, e):
    ret = 0
    txt = ""
    nlen = int(math.log(N) / math.log(2))
    if gmpy2.is_prime(p) == False:
        ret = -1
        txt += "p IS NOT PROBABLE PRIME\n"
    if gmpy2.is_prime(q) == False:
        txt = "q IS NOT PROBABLE PRIME\n"
    if gmpy2.gcd(p, e) > 1:
        ret = -1
        txt = "p and e ARE NOT RELATIVELY PRIME\n"
    if gmpy2.gcd(q, e) > 1:
        ret = -1
        txt += "q and e ARE NOT RELATIVELY PRIME\n"
    if p * q != N:
        ret - 1
        txt += "n IS NOT p * q\n"
    if not (abs(p - q) > (2**(nlen // 2 - 100))):
        ret - 1
        txt += "|p - q| IS NOT > 2^(nlen/2 - 100)\n"
    if not (p > 2**(nlen // 2 - 1)):
        ret - 1
        txt += "p IS NOT > 2^(nlen/2 - 1)\n"
    if not (q > 2**(nlen // 2 - 1)):
        ret - 1
        txt += "q IS NOT > 2^(nlen/2 - 1)\n"
    if not (d > 2**(nlen // 2)):
        ret - 1
        txt += "d IS NOT > 2^(nlen/2)\n"
    if not (d < gmpy2.lcm(p - 1, q - 1)):
        txt += "d IS NOT < lcm(p-1,q-1)\n"
    try:
        inv = gmpy2.invert(e, lcm(p - 1, q - 1))
    except:
        inv = None
        ret = -1
        txt += "e IS NOT INVERTIBLE mod lcm(p-1,q-1)\n"
    if d != inv:
        ret = -1
        txt += "d IS NOT e^(-1) mod lcm(p-1,q-1)"
    return (ret, txt)
Exemple #40
0
def gen():
    while True:
        p = [gmpy2.next_prime(random.randrange(1 << 48)) for _ in range(50)]
        o = 2
        for pi in p:
            o *= pi
        n = o + 1
        if gmpy2.is_prime(n):
            g = 2
            if pow(g, o // 2, n) == n - 1:
                return g, n
Exemple #41
0
def gen_prime_froms(bits, s):
    p = 0
    print('s', hex(s))
    for _ in range(bits // chunk_size):
        p = (p << chunk_size) + s
        s = a * s % 2**chunk_size
        print(hex(s))
    if gmpy2.is_prime(p):
        return p
    else:
        return 0
Exemple #42
0
def minimum_number(numbers):
    s = sum(numbers)
    n = s

    while True:
        if is_prime(n):
            break
        else:
            n += 1

    return n - s
 def isprimeproof(n):
     if n % 2 == 0:
         n = str(n)[:-1]
         for s in '13579':
             if is_prime(int(n + s)):
                 return False
         return True
     else:
         n = str(n)
         for s in '123456789':
             if is_prime(int(s + n[1:])):
                 return False
         for i in range(1, len(n)-1):
             for s in '0123456789':
                 if is_prime(int(n[:i] + s + n[i+1:])):
                     return False
         for s in '13579':
             if is_prime(int(n[:-1] + s)):
                 return False
         return True
Exemple #44
0
def calcA(a,n):
    x=a**2-n
    if gmpy2.is_square(x):
        x = gmpy2.isqrt(x)
        p = a+x
        q = a-x
        if p*q == n:
            if not gmpy2.is_prime(q):
                print "not prime q"  # simple check
            return q
    return 0
def is_prime(number: int) -> bool:
    """
    Check if the input number is a prime number. Uses GMPY2 if available

    :param number: The number to check
    :return: Whether the input is prime or not
    """
    if USE_GMPY2:
        return gmpy2.is_prime(number)
    # else
    return sympy.isprime(number)
Exemple #46
0
def find_tricky_rng_seed():
    # Hand-crafted so you don't have to run Bitcoin Cash before:
    return bytes.fromhex(
        "693e14ccadf6c831ea694f6d8651d6c912c4377ecc22b2f498d2ee60b66c53bd")

    # Find a seed such that we generate a secret == 0
    rng = Rng()
    for block, base in tricky_sha_inputs():
        seed = long_to_bytes(bytes_to_long(base) - 2, 32)
        rng.set_seed(seed)

        prime = rng.getbits(512)
        secret = rng.getbits()
        assert secret == 0

        strong_prime = 2 * prime + 1
        if prime % 5 == 4 and is_prime(prime) and is_prime(strong_prime):
            log.success(f"Seed {seed.hex()} is suitable! (from block {block})")
            return seed
    raise Exception("Could not find a suitable seed!")
Exemple #47
0
def generate_CEK_prime(l, u, b, d):
    rs = PRNG()
    b_d = b ** d
    b_d_bits = int(math.ceil(math.log(b_d, 2)))
    if b == 2:
        p_t_bits = l - b_d_bits - u
        p_t = rs.random_prime(p_t_bits)
        while True:
            p_s = rs.random_prime(u)
            p = b_d * p_s * p_t + 1
            if gmpy2.is_prime(p):
                return p_s, p
    else:
        p_t_bits = l - b_d_bits - u - 1
        p_t = rs.random_prime(p_t_bits)
        while True:
            p_s = rs.random_prime(u)
            p = 2 * b_d * p_s * p_t + 1
            if gmpy2.is_prime(p):
                return p_s, p
    def __init__(self, p=None, q=None, n=None, d=None, e=DEFAULT_EXP):
        """
        Initialize RSA instance using primes (p, q)
        or modulus and private exponent (n, d)
        """

        self.e = e

        if p and q:
            assert gmpy.is_prime(p), 'p is not prime'
            assert gmpy.is_prime(q), 'q is not prime'

            self.p = p
            self.q = q
        elif n and d:   
            self.p, self.q = factor_modulus(n, d, e)
        else:
            raise ArgumentError('Either (p, q) or (n, d) must be provided')

        self._calc_values()
Exemple #49
0
    def __init__(self, p=None, q=None, n=None, d=None, e=DEFAULT_EXP):
        """
        Initialize RSA instance using primes (p, q)
        or modulus and private exponent (n, d)
        """

        self.e = e

        if p and q:
            assert gmpy2.is_prime(p), 'p is not prime'
            assert gmpy2.is_prime(q), 'q is not prime'

            self.p = p
            self.q = q
        elif n and d:
            self.p, self.q = factor_modulus(n, d, e)
        else:
            raise ValueError('Either (p, q) or (n, d) must be provided')

        self._calc_values()
Exemple #50
0
def calcA(a, n):
    x = a**2 - n
    if gmpy2.is_square(x):
        x = gmpy2.isqrt(x)
        p = a + x
        q = a - x
        if p * q == n:
            if not gmpy2.is_prime(q):
                print "not prime q"  # simple check
            return q
    return 0
Exemple #51
0
def k_thlastDigPrime(k):
    res = [0, 1, 1, 2, 4]
    total = 0
    while total < k:
        res.append(res[-1] + res[-2] - res[-3] + res[-4] - res[-5])
        temp = str(res[-1])
        if len(temp) < 10:
            continue
        if is_prime(int(temp[-9:])):
            total += 1
    return [len(res), int(temp[-9:])]
Exemple #52
0
def brentMultipleFactors(N) :
    """ Find all the prime factors of N (more than 2) by the brent's cycle finding with batch gcd
    """
    res=[]
    facts=0,0
    while(not(gmpy2.is_prime(facts[1]))) :
        facts=brentWithBatchGCD(N)
        res+=[facts[0]]
        N=facts[1]
    res+=[facts[1]]
    return res
Exemple #53
0
def random_prime(random_state, m, generator, power_range, multiple_range):
    random_power = random_from_interval(random_state, power_range[0],
                                        power_range[1])
    random_multiple = random_from_interval(random_state, multiple_range[0],
                                           multiple_range[1])

    candidate = g.powmod(generator, random_power, m) + random_multiple * m
    while not g.is_prime(candidate):
        candidate += m

    return candidate
Exemple #54
0
def gen_keys(dimension):
    """
    Функция, которая генерирует ключи абонента 

    """

    print("Parametrs: \n")

    p = primegen.prime_gen(dimension)

    while is_prime(p) == False:
        p = primegen.prime_gen(dimension)

    q = primegen.prime_gen(dimension)

    while is_prime(q) == False:
        q = primegen.prime_gen(dimension)

    print(f"p = {p}, q = {q}")

    N = p * q

    print(f"N = {N}")

    C = get_c(p, q)

    print(f"c = {C}")

    S = get_s(C, N)

    print(f"s = {S}")

    M = get_m(p, q, C)

    print(f"m = {M}")

    E, D = get_e_d(M)

    print(f"e = {E}, d = {D}\n")

    return (p, q, M, D), (N, E, C, S)
    def S(n):
        res, xmin = 0, (n-1) * n / 2
        for i in xrange(1+(xmin%2), n+1, 2):
            x = xmin + i
            if x % 3 and x % 7 and x % 11 and is_prime(x):
                univ = MIDDLE[(x%6, n%6)](x, n)        
                check = filter(is_prime, univ.keys())
                d = len(check)

                if d > 1:
                    res += x
                elif d:
                    try:
                        for y in check:
                            for z in univ[y]:
                                if is_prime(z):
                                    res += x
                                    raise ValueError
                    except:
                        pass
        return res
Exemple #56
0
def goldbach(n):
    """teste la conjecture de Golbach en tentant de décomposer n pair (>2) en 2 nb premiers"""

    x = 3
    while True:
        # calcul de y et test de primalité
        y = n-x
        if gmpy2.is_prime(y,20):
            return (n,[int(x),int(y)])

        # On prend le nombre premier suivant
        x = gmpy2.next_prime(x)
def challenge3 (N):
    """Factor N=p*q where abs(3p-2q) < N**(1/4). Indeed (3p+2q)/2  is closed to sqrt(6N). But 3p is odd and 3p+2q / 2 is not an integer. But 2(3p) is even.\
       So 6p + 4q / 2 is an integer closed to 2 * sqrt(6N) or 2==sqrt(4) so closed to sqrt(4*6*N) ie sqrt(24N)"""
    N = mpz(N)
    twentyFour_N = mul(24,N)
    A = isqrt(twentyFour_N)
    while 1:
        if pow(A, 2) > twentyFour_N:
            x = isqrt(pow(A, 2) - twentyFour_N)
            AminusX = A - x
            AplusX = A + x
            if (mul(AminusX, AplusX) == twentyFour_N):
                p,q = 0,0
                if ((AminusX % 6 == 0) and (AplusX % 4 == 0)):
                    p = AminusX // 6
                    q = AplusX // 4
                elif ((AplusX % 6 == 0) and (AminusX % 4 == 0)):
                    p = AplusX // 6
                    q = AminusX // 4
                if (is_prime(p) and is_prime(q)):
                    return (p,q)
        A = A + 1
Exemple #58
0
def generate_large_prime(bits):
    """ 
        Generate large pseudo prime .
        Args:
            bits: int, the number of bits of the prime you want to generate.
    """
    rand_prime=random.getrandbits(bits)
    if (rand_prime%2)==0 :
        rand_prime=rand_prime-1

    while not gmpy2.is_prime(rand_prime):
        rand_prime=rand_prime+2
    return rand_prime
def prime_divisor_decomp(n, rand=False):
    dlist, clist = [], []

    # 奇偶性判断
    c = 0
    while n % 2 == 0:
        n //= 2
        c += 1
    if c:
        dlist.append(2)
        clist.append(c)

    # 首先用10000以内的小素数试除
    for p in iter(P10K):
        c = 0
        while n % p == 0:
            n //= p
            c += 1
        if c:
            dlist.append(p)
            clist.append(c)

        if n == 1:
            return list(zip(dlist, clist))

        if n in P10Kset:  # set的in操作复杂度<=O(log(n))
            dlist.append(n)
            clist.append(1)
            return list(zip(dlist, clist))

        n = int(n)

    # 然后用Pollard rho方法生成素因子
    while 1:
        if n == 1:
            return list(zip(dlist, clist))

        if is_prime(n):
            dlist.append(n)
            clist.append(1)
            return list(zip(dlist, clist))

        p = _pollard_rho(n, rand)
        c = 0
        while n % p == 0:
            n //= p
            c += 1
        dlist.append(p)
        clist.append(c)

        n = int(n)