def elemop(N=1000):
    r'''
    (Takes about 40ms on a first-generation Macbook Pro)
    '''
    for i in range(N):
        assert a+b == 579
        assert a-b == -333
        assert b*a == a*b == 56088
        assert b%a == 87
        assert divmod(a, b) == (0, 123)
        assert divmod(b, a) == (3, 87)
        assert -a == -123
        assert pow(a, 10) == 792594609605189126649
        assert pow(a, 7, b) == 99
        assert cmp(a, b) == -1
        assert '7' in str(c)
        assert '0' not in str(c)
        assert a.sqrt() == 11
        assert _g.lcm(a, b) == 18696
        assert _g.fac(7) == 5040
        assert _g.fib(17) == 1597
        assert _g.divm(b, a, 20) == 12
        assert _g.divm(4, 8, 20) == 3
        assert _g.divm(4, 8, 20) == 3
        assert _g.mpz(20) == 20
        assert _g.mpz(8) == 8
        assert _g.mpz(4) == 4
        assert a.invert(100) == 87
Exemplo n.º 2
0
def primeFactorize(n):
    orign = n
    # use memoized value if possible
    for prime in primes:
        if prime >= n:
            break
        cached_n,check = divmod(mpz(n), prime)
        if check != 0:
            continue
        if cached_n in prime_factorizations:
            factors = prime_factorizations[cached_n]
            if prime in factors:
                factors[prime] += 1
            else:
                factors[prime] = 1
            prime_factorizations[n] = factors
            print('+ '),
            #print(factors)
            return factors
    
    # otherwise:
    print('- '),
    prime = mpz(2)
    n = mpz(n)
    factors = {}
    while n >= prime:
        newn, mult = n.remove(prime)
        if mult:
            factors[prime] = mult
            n = newn
        prime = next_primes[prime]
    prime_factorizations[orign] = factors
    #print(factors)
    return factors
def pi_calc():
    global calcs,y,u,q,r,t,j,calc_uy,startTime
    digitstring = ''
    dpm = 0
    strPi = ''
    loop = 1
    elapsed=0
    elapsedStart = time.time()
    while loop:
        digitCalcTime = time.time()
        u, y = mpz(3*(3*j+1)*(3*j+2)), mpz((q*(27*j-12)+5*r)/(5*t))
        strPi = str(y)
        digitstring += strPi
        q, r, t, j = mpz((20*j**2-10*j)*q), mpz(10*u*(q*(5*j-2)+r-y*t)), mpz(t*u), j+1
        # dpm = digits per minute
        now = time.time()
        elapsed = now - elapsedStart
        if elapsed >= .5:
            break
        elif (j-2) % 1000 == 0:
            break
    dps = (1.0/elapsed)*len(digitstring)
    info = {
            "digits": digitstring,
            "digitcount": j-2,
            "dpm": round(dps*60),
            "dps":round(dps, 2)
            }
    if (j-2) % 1000 == 0:
        info['mark'] = {"digitmark":(j-2),
                       # "startTime":startTime,
                        "runtime": time.time()-startTime}
    return info
Exemplo n.º 4
0
 def __init__(self, i, n): 
     if str(i.__class__).find("mfi") != -1:
         self.val = i.val
     else:
         self.val = gmpy.mpz(i)
     self.mod = gmpy.mpz(n)
     self.val = self.val % self.mod
Exemplo n.º 5
0
def fastprime(k):
    if k <= margin:
		# Small k - generate the prime by trial division.
        while True:
            n = random.getrandbits(k-1)
            n = n<<1 | 1
            if prime_test(n):
                return n
    else:
		# k big, generate the prime recursively.
        g = c_opt * k * k
        if k > 2*margin:
            while True:
                relative_size = 2 ** (random.random() - 1)
                if k * relative_size < k - margin:
                    break
        else:
            relative_size = 0.5
        q = fastprime(int(relative_size * k)+1)
        success = False
        i = int((2**(k-1)) / (2*q))
        while not success:
            r = random.randint(i+1, 2*i)
			# using gmpy to improve performance - better representation of big integers.
			# Once you used gmpy, everywhere you use the variable, the result of that 
			# expression will also use gmpy representations.
            n = gmpy.mpz(2*r*q+1)
			# Here we sort out the most wrong numbers
            if  trial_division(n, g) and millerrabin_2(n):
                a = gmpy.mpz(random.randint(2, n-2))
                if pow(a, n-1, n) == 1:
                    if gcd(pow(a, 2*r, n)-1, n) == 1:
                        success = True
        return n
Exemplo n.º 6
0
def pow_mod(b, p, m):
    '''
    Power with modulus.

    :arg b: base
    :arg p: power
    :arg m: modulus

    For :math:`p < 0`:

    .. math::
        (b^p \mod m) \pmod m

    For :math:`p >= 0`:

    .. math::
        b^p \mod m
    '''
    if has_gmpy:
        b = gmpy.mpz(b)
        p = gmpy.mpz(p)
        m = gmpy.mpz(m)
        return long(pow(b, p, m))

    elif p < 0:
        return inv_mod(pow(b, p, m), m)

    else:
        return pow(b, p, m)
Exemplo n.º 7
0
def sample_RSA_lowexpo():
    import gmpy

    # Pubkey
    n = 0xb0a1f390acd3d43b47d39f132662f69c158925d92871e47869e2841a917c20d5102431b9a9781458d840fd29577815a41612d687a3487d26fbae256f15d4740c34591b646abcccb1a27acde299b3e71600857b455c283660e0455c68ff45c0644cfec211d7f51a16c82e91d786d92c799fb3cb48f92de342ba70dd8213056b314a8d51da9493cf1b86ec15fdf03e046e76d3f1a1ad0aabb684ce5d157e399828a63a5af5920228bb5ea1e66b8feaa3ccbbaff555e346797730ddfc1c4cf4a9dd406588629348c4c29265df9e2c3d02558be5e35cb277f4e7ac7b5158ef3903a396486371029e54a345292aba47499f1c267e680ae738195fd5af2a8075939890f5d69e6b3e94e3e560861aa6c6c69da82405dba2182e66ecff6a8a9cdf5ad5226f073e7d525e050fdd77e0bb1891a49efec2d367a693d2a6799d0d4667953d4f3ddec16ac15bb4cf6025ea58ecb6dfa572316da08d3106073973322ae7597446f2fd3043df6e1d604c6a1f0e59473d9bc182d4ec6fc4588f1c6b2aa476876a84b2d4e0d45910399118d7e1e20dcc27703f2bd3e9af722f37a7673b15d674922862c84d00fc2fc7ddddc915c4693fcb0b1789e9dcbd72ac04659e7c18dcf36254760040402bfcef11b8a3ef9c8bddbaaa8d14c6e8f518a70b036d206b809cd9b3b51a1ec0132dace96dca9451f34c38ab84ed475e7d94fbe9ffc007f2d14860bdL
    e = 0x3
    # Message
    msg_str = '\x4a\x69\x06\x21\xbd\x15\x0c\xf6\x93\xed\x8c\x85\x70\x8b\x6d\x0f\xa2\xcc\x85\x0b\x48\x73\x64\x43\x08\x23\x8f\x38\x03\x1a\x93\x31\x02\xf6\x66\xb8\x92\x68\x99\x60\x6e\x49\x1f\x36\x0a\x24\xd2\x6b\x9e\x91\x5e\xd6\xa1\x28\x49\x2b\x14\x47\x99\xe9\xee\xd2\x50\x05\x0a\x2d\xef\xa2\xac\x53\x52\xb0\x49\x2c\x98\x83\x28\xb0\x74\x36\xb8\x26\xa5\x00\xf9\x19\x35\xac\x58\x1c\x0c\x60\x66\xa7\xa9\x49\x46\xf2\x1e\x29\x0b\x1b\x2f\xbd\xf6\x73\xad\xb0\x5c\x04\x45\x90\x5b\xdd\x88\x01\xc9\x3c\xfb\x4c\xe7\x43\xcd\x62\xbf\x79\xe9\x7f\x95\x9c\xb9\x44\x9f\xc3\x7d\xbf\x5c\xd3\x15\x56\x5b\xb0\xc4\x33\x69\xe6\x47\x3b\xc9\x7d\x2d\xb5\xcc\x2c\x01\xde\x75\x0b\x99\x59\xb8\xde\x3d\x53\x95\xf1\x1f\xa8\xbb\xe8\x8b\x8d\xfe\x52\x1d\x78\x2d\xfd\x41\x66\x4c\x08\x2a\x80\x6b\xfe\x7f\x30\x0b\x56\x33\x27\x4f\xdd\x5f\x22\x93\xe0\xd0\xc2\x1e\xc6\xb1\xd2\xc9\x3f\xc0\x4d\x22\xf1\xaa\x1c\x9e\x0a\xad\xfa\x28\x54\xcf\x32\x59\x51\xfc\xfe\x84\xec\x4e\xd2\xa5\xc9\x10\xed\xb3\x2b\xba\x9f\x25\xab\xfe\x53\x42\x03\xef\x3e\xbb\x1d\x36\xfa\x3b\x12\x55\xb8\xa3\x49\xc4\xa7\x70\x66\xd1\xc3\xf2\x65\x90\x0d\x11\xca\x1b\x6a\x80\x66\xff\x01\xe4\x98\x05\x8d\x55\x7a\x15\x05\x48\x82\xdd\x13\x6c\x06\x4e\x9c\xe2\x8e\x2d\x44\x05\x35\x76\x73\xac\x23\xf6\x31\x06\x43\xdb\x0b\x93\xa3\x99\x6e\xe6\x5d\x15\xe0\x86\xea\x68\x77\x18\x01\x6b\x18\x41\x08\xa7\x2f\xc9\x79\xfa\x72\xb4\x91\x3a\xa7\x79\x28\x96\xf5\x1c\x68\xfc\x97\x91\x77\x35\xd7\xe2\x86\x4b\xd3\x84\xcf\x9b\x77\xaf\xd2\xc6\xbd\xfc\xdd\x32\x54\x13\x9a\x69\xb6\x45\xb1\x52\x42\x4b\xa9\x02\x79\xe2\x75\x56\x3a\xf5\x2f\xec\x48\x7e\x68\xd0\xba\x3c\x42\x2d\x00\x07\xe2\x6f\xfc\x9a\x03\xce\x98\x90\xdd\x38\x15\x3a\x36\x46\xd4\x9d\xc0\x71\xe1\xfd\x7a\x3c\x42\x1a\xd2\x1b\x62\xeb\x63\xce\x40\x88\x7d\xd6\x0b\x60\x13\x4a\x1e\xf0\x6c\x60\x9e\xf4\x6d\xb6\xd9\x92\x9e\xab\xfb\x15\x93\x2d\x5d\x7a\xc7\x0b\xec\xf1\xb4\xca\xf8\x55\x14\xd3\x15\x1f\x30\xce\x69\x65\xf9\xd1\x67\x21\xe8\x65\xb7\xd3\x01\x48\xf6\xb8\x46\xe5\x03\x15\xb7\x0e\x1e\xfd\x7a\xd8\xe4\xff\x9f\x1d\x84\xfb\xa4\x10\x81\x16\x71\xe5\x6d\xe2\x46\x96\x55\xce\xd0\x14\xd0\x09\xe1\x27\x97\x38\x21\xf3\x23'
    msg_num = int(msg_str.encode('hex'), 16)

    ubound = pow(int('7D' * 172,16), e)
    lbound = pow(int('20' * 172,16), e)
    # We were working on this after the hint that the plaintext was 172 characters, so we can use that here.
    # Otherwise we’d just have to try all the different lengths, starting from low values and working our way up.
    # This first calculates the result of raising the ‘smallest’ possible message (consisting entirely of spaces)
    # to the third power, and then does the same for the “largest” possible message in the ascii range.
    # Now remember that ciphertext is the remainder of the real message raised to the third power modulo n
    # (n being the modulus part of the rsa public key).

    #ciphertext = pow(plaintext, 3) % modulus
    # 'ciphertext' is the remainder, so all we need to know to take the cubic root is the quotient 'q'
    # ciphertext + modulus * q = pow(plaintext, 3)
    max_q = ubound / n
    min_q = lbound / n
    print max_q - min_q # This gives the number 732851516. That’s pretty big, but it’s certainly doable on a fast system with a good big-number library
    gs = gmpy.mpz(msg_num)
    gm = gmpy.mpz(n)
    g3 = gmpy.mpz(3)
    mask = gmpy.mpz(0x8080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808000)

    for i in xrange(min_q, max_q):
        gs += gm
        root,exact = gs.root(g3)
        if (root & mask).bit_length() < 8:
            print ('0%x' % root).decode('hex') # Turns out our assumption that spaces would be the lowest characters in the string was actually incorrect: this message starts with a linefeed!
Exemplo n.º 8
0
def emit_vcd_entry(f, timestamp, pktclass):
    global first_vcd_timestamp, last_vcd_timestamp, last_vcd_pktclass_code
    if not timestamp:
        return
    if not first_vcd_timestamp:
        first_vcd_timestamp = timestamp
    print last_vcd_timestamp, timestamp, (timestamp < last_vcd_timestamp)
    if last_vcd_timestamp and (timestamp < last_vcd_timestamp):
        f.write('$comment %s %s %s $end\n' % (hex(last_vcd_timestamp), hex(timestamp), hex(timestamp + mpz('100000000', 16))))
        timestamp = timestamp + mpz('100000000', 16)
        f.write('$comment %s %s $end\n' % (hex(timestamp), hex(timestamp - first_vcd_timestamp)))

    #timestamp = timestamp - first_vcd_timestamp

    if last_vcd_timestamp and timestamp > (last_vcd_timestamp+1):
        f.write('#%s\n0%s\n' % ((last_vcd_timestamp+mpz(1)), last_vcd_pktclass_code))
    if pktclassCodes.has_key(pktclass):
        pktclass_code = pktclassCodes[pktclass]
        f.write('#%s\n' % timestamp)
        f.write('1%s\n' % pktclass_code)
        if last_vcd_pktclass_code and last_vcd_pktclass_code != pktclass_code:
            f.write('0%s\n' % last_vcd_pktclass_code)
        last_vcd_pktclass_code = pktclass_code
        last_vcd_timestamp = timestamp
    else:
        f.write('$comment %s $end\n' % pktclass)
Exemplo n.º 9
0
def rsa_compatible(n, phi):
    phi = long(phi)
    while True:
        e = StrongRandom().randint(1, phi - 1)
        if GCD(e, phi) == 1:
            break
    return RSAKey(mpz(n), mpz(e), None, None, None, 1024)
Exemplo n.º 10
0
def main():
    #
    # First part
    #

    N1 = mpz(179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581)
    p,q = func1(N1)
    assert(p*q == N1)
    log.warning("Smallest factor: {0}".format(min([p,q])))

    #
    # Second part
    #
    N2 = mpz(648455842808071669662824265346772278726343720706976263060439070378797308618081116462714015276061417569195587321840254520655424906719892428844841839353281972988531310511738648965962582821502504990264452100885281673303711142296421027840289307657458645233683357077834689715838646088239640236866252211790085787877)

    # Setup
    ranges = create_ranges(sqrt(N2), sqrt(N2) + 2**20, 10000)
    producer = Process(target=_producer, args=(ranges,))
    consumer = Process(target=_consumer)
    pool = [Process(target=_worker, args=(func2, N2)) for _ in range(NCPU)]
    # Compute
    for p in [producer, consumer] + pool:
        p.start()
    consumer.join()
    # Teardown
    producer.terminate()
    for p in pool:
        p.terminate()
Exemplo n.º 11
0
def main(cert_path, data_path, offset):
  mod = get_modulus(cert_path)
  mod = gmpy.mpz(mod, 16)
  key_size = int(mod.bit_length() / 16)
  offset = int(offset, 16)
  print('Prime should be at offset: %x'%offset)
  print('Key size: %d\n'%key_size)
  with open(data_path, 'rb') as f:
    mm_data = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)

    print('Hexdump of surrounding data:')
    hexdump(mm_data, max(0, offset - 1024), 2048)
    p = gmpy.mpz(long(mm_data, offset, key_size))
    if gmpy.is_prime(p) and p != mod and mod % p == 0:
      print('Prime factor found: %s\n'%p)
      hexbytes = binascii.hexlify(mm_data[offset:offset+key_size]).decode('ascii').upper()
      hexbytes = re.sub(r'(..)', r'\x\1', hexbytes)
      print('Prime in greppable ascii: %s\n'%hexbytes)
      p = gmpy.mpz(p)
      e = gmpy.mpz(65537)
      q = gmpy.divexact(mod, p)
      
      assert(gmpy.is_prime(q))

      phi = (p-1) * (q-1)
      d = gmpy.invert(e, phi)
      dp = d % (p - 1)
      dq = d % (q - 1)
      qinv = gmpy.invert(q, p)
      seq = Sequence()
      for x in [0, mod, e, d, p, q, dp, dq, qinv]:
        seq.setComponentByPosition (len (seq), Integer (x))
      print("\n\n-----BEGIN RSA PRIVATE KEY-----\n%s-----END RSA PRIVATE KEY-----\n\n"%base64.encodestring(encoder.encode(seq)).decode('ascii'))
    else:
      print('Prime factor not found')
Exemplo n.º 12
0
 def test_serialize_number_binary(self):
     for number, string in (
                 (1231234,       b'12c982'),
                 (0,             b''),
                 (255,           b'ff'),
                 (1231231231232, b'011eab19a500'),
                 (13371337,      b'cc07c9'),
                 (256,           b'0100')):
         self.assertEqual(binascii.hexlify(seccure.serialize_number(number)),
                                     string)
         self.assertEqual(binascii.hexlify(seccure.serialize_number(
                     gmpy.mpz(number))), string)
         self.assertEqual(seccure.deserialize_number(
                         binascii.unhexlify(string)), number)
     for number, string in (
                 (1231234,       b'0012c982'),
                 (0,             b'00000000'),
                 (255,           b'000000ff'),
                 (13371337,      b'00cc07c9'),
                 (256,           b'00000100')):
         self.assertEqual(binascii.hexlify(
                 seccure.serialize_number(number, outlen=4)), string)
         self.assertEqual(binascii.hexlify(
                 seccure.serialize_number(gmpy.mpz(number),
                                             outlen=4)), string)
         self.assertEqual(seccure.deserialize_number(
                         binascii.unhexlify(string)), number)
Exemplo n.º 13
0
 def test_vec_pow_is_correct_2(self):
     s, k, prover_id = 3, 0, 1
     c = [None] * s
     y = [mpz(i) for i in [1, 7, 2]]
     zk = ZKProof(s, prover_id, k, RuntimeStub(), c)
     zk.e = [0, 1, 1]
     y_pow_E = zk._vec_pow_E(y, 117)
     self.assertEquals([mpz(v) for v in [1, 1, 7, 14, 2]], y_pow_E)
Exemplo n.º 14
0
 def test_vec_pow_is_correct(self):
     s, prover_id, k = 5, 1, 0
     c = [None] * s
     y = [mpz(i) for i in range(1, 6)]
     zk = ZKProof(s, prover_id, k, RuntimeStub(), c)
     zk.e = [1, 0, 1, 1, 0]
     y_pow_E = zk._vec_pow_E(y, 117)
     self.assertEquals([mpz(v) for v in [1, 2, 3, 8, 30, 12, 20, 5, 1]], y_pow_E)
Exemplo n.º 15
0
def generate_backdoor(curve,d):
    #Create a known relationship between P and Q
    Q = curve.base
    Q = Q * d

    e = gmpy.mpz(0)
    e = gmpy.invert(gmpy.mpz(d),curve.order)
    return Q
Exemplo n.º 16
0
 def _generate_u_v_and_d(self):
     self.u, self.v, self.d = [], [], []
     for i in range(self.m):
         ui = rand_int_signed(self.random, 2**(2 * self.k))
         vi, di = self.paillier.encrypt_r(ui)
         assert abs(ui) <= 2**(2 * self.k)
         self.u.append(mpz(ui))
         self.v.append(mpz(vi))
         self.d.append(mpz(di))
Exemplo n.º 17
0
 def _generate_test_ciphertexts(self, random, runtime, k, s, prover_id):
     paillier = ModifiedPaillier(runtime, random)
     xs, rs, cs = [], [], []
     for i in range(s):
         x = rand_int_signed(random, 2 ** k)
         r, c = paillier.encrypt_r(x, player_id=prover_id)
         xs.append(mpz(x))
         rs.append(mpz(r))
         cs.append(mpz(c))
     return xs, rs, cs
Exemplo n.º 18
0
 def apply(self, items, evaluation):
     'Plus[items___]'
     
     items = items.numerify(evaluation).get_sequence()
     number = mpz(0)
     leaves = []
     last_item = last_count = None
     
     def append_last():
         if last_item is not None:
             if last_count == 1:
                 leaves.append(last_item)
             else:
                 if last_item.has_form('Times', None):
                     last_item.leaves.insert(0, Number.from_mp(last_count))
                     leaves.append(last_item)
                 else:
                     leaves.append(Expression('Times', Number.from_mp(last_count), last_item))
     
     for item in items:
         if isinstance(item, Number):
             number = add(number, item.value)
         else:
             count = rest = None
             if item.has_form('Times', None):
                 for leaf in item.leaves:
                     if isinstance(leaf, Number):
                         count = leaf.value
                         rest = item.leaves[:]
                         rest.remove(leaf)
                         if len(rest) == 1:
                             rest = rest[0]
                         else:
                             rest.sort()
                             rest = Expression('Times', *rest)
                         break
             if count is None:
                 count = mpz(1)
                 rest = item
             if last_item is not None and last_item == rest:
                 last_count = add(last_count, count)
             else:
                 append_last()
                 last_item = rest
                 last_count = count
     append_last()
     if not (get_type(number) == 'z' and number == 0):
         leaves.insert(0, Number.from_mp(number))
     if not leaves:
         return Integer(0)
     elif len(leaves) == 1:
         return leaves[0]
     else:
         leaves.sort()
         return Expression('Plus', *leaves)
Exemplo n.º 19
0
 def apply_real(self, x, evaluation):
     'Floor[x_?RealNumberQ]'
     
     x = x.value
     if x < 0:
         floor = - mpz(abs(x))
         if x != floor:
             floor -= 1
     else:
         floor = mpz(x)
     return Integer(floor)
Exemplo n.º 20
0
 def _vec_pow_E(self, y, n):
     """Computes and returns the m := 2s-1 length vector y**E."""
     assert self.s == len(y), \
         "not same length: %d != %d" % (self.s, len(y))
     res = [mpz(1)] * self.m
     for j in range(self.m):
         for i in range(self.s):
             if self._E(j, i) == mpz(1):
                 # TODO: Should we reduce modulo n each time?
                 res[j] = (res[j] * y[i]) % n
     return res
Exemplo n.º 21
0
def prime_factors(x):
    prime = gmpy.mpz(2)
    x = gmpy.mpz(x)
    factors = {}
    while x >= prime:
        newx, mult = x.remove(prime)
        if mult:
            factors[prime] = mult
            x = newx
        prime = prime.next_prime()
    return factors
Exemplo n.º 22
0
def parse_for_chord (time, line):
  MAX = (gmpy.mpz (1) << 160) - 1
  RADIUS = gmpy.mpz (700)
  CX, CY = [gmpy.mpz (1000), gmpy.mpz (1000)]
  node_id = line.split(' ')[2]
  if ('node_attr2' in line):
    id = gmpy.mpz (line.rpartition(':')[2], 16)
    angle = gmpy.mpf (math.pi) * id / MAX
    x, y = CX + RADIUS * math.cos (angle), CY + RADIUS * math.sin(angle)
    add_event (time, '%ldns position %s %f %f 0 0 0 0\n' % (time, node_id, x, y))
    add_event (time, '%ldns state %s +chordRing\n' % (time, node_id))
Exemplo n.º 23
0
Arquivo: 123.py Projeto: Ballaw/MyBin
def Euler_123(low = 10**10):
	''' Returns the nth prime that has a remainder above low when using
			the given formula
	'''
	p = Primes(10**6)
	primes = p.pList()
	for x in range(0,len(primes)):
		n = mpz(x+1)
		p = mpz(primes[x]-1)**n + mpz(primes[x]+1)**n
		if p % mpz(primes[x])**2 > low:
			return n
Exemplo n.º 24
0
def find_random_prime(k):
    """Find a random *k* bit prime number.

    The prime may have fewer, but no more, than *k* significant bits:

    >>> 2 <= find_random_prime(10) < 2**10
    True
    """
    p = mpz(1)
    while not p.is_prime():
        p = mpz(rand.getrandbits(k))
    return long(p)
Exemplo n.º 25
0
	def release(self):
		with self.lock:
			connection = self.engine.connect()
			s = select([db.commonGCDTable.c.product])
			res=connection.execute(s).first()
			if not res is None:
				temp = mpz(res[0])
			else:
				temp = mpz(1)
			lcm = gmp.lcm(temp, self.product)
			s=db.commonGCDTable.update().where(db.commonGCDTable.c.id==1).values(product=str(lcm))
			connection.execute(s)
			connection.close()
def decryptRSA(inB, key, exponent):
	b = ''
	for i in range(0, len(key)/2):
		b = b + struct.pack('B', int(key[2*i]+key[2*i+1],16)) 
	mKey = gmpy.mpz(b, 256)
	b = ''
	for i in inB:
		b = struct.pack('>I', i) + b
	mIn  = gmpy.mpz(b, 256)
	mExp = gmpy.mpz(exponent)
	out = pow(mIn,mExp) % mKey
	b = out.binary()
	return b 
def test(n=100*1000):
    print("Sum of %d items of various types:" % n)
    for z in 0, 0.0, gmpy.mpz(0), gmpy.mpf(0):
        tip, tim, tot = timedsum(n, z)
        print("    %5.3f %.0f %s" % (tim, float(tot), tip))
    print("Sum of %d items of various types w/2.3 sum builtin:" % n)
    for z in 0, 0.0, gmpy.mpz(0), gmpy.mpf(0):
        tip, tim, tot = timedsum1(n, z)
        print("    %5.3f %.0f %s" % (tim, float(tot), tip))
    print("Mul of %d items of various types:" % (n//5))
    for z in 1, 1.0, gmpy.mpz(1), gmpy.mpf(1):
        tip, tim, tot = timedmul(n//5, z)
        print("    %5.3f %s" % (tim, tip))
Exemplo n.º 28
0
def powMod( x, y, mod ):
    """
    Efficiently calculate and return `x' to the power of `y' mod `mod'.

    Before the modular exponentiation, the three numbers are converted to
    GMPY's bignum representation which speeds up exponentiation.
    """

    x = gmpy.mpz(x)
    y = gmpy.mpz(y)
    mod = gmpy.mpz(mod)

    return pow(x, y, mod)
Exemplo n.º 29
0
def fermat_factor(N, minutes=10, verbose=False):
   """
   Code based on Sage code from FactHacks, a joint work by
   Daniel J. Bernstein, Nadia Heninger, and Tanja Lange.

   http://facthacks.cr.yp.to/
   
   N - integer to attempt to factor using Fermat's Last Theorem
   minutes - number of minutes to run the algorithm before giving up
   verbose - (bool) Periodically show how many iterations have been
      attempted
   """
   from time import time
   current_time = int(time())
   end_time = current_time + int(minutes * 60)

   def sqrt(n):
      return gmpy.fsqrt(n)
  
   def is_square(n):
      sqrt_n = sqrt(n)
      return sqrt_n.floor() == sqrt_n

   if verbose:
      print "Starting factorization..."
   
   gmpy.set_minprec(4096)

   N = gmpy.mpf(N)
   if N <= 0:        return [1,N]
   if N % 2 == 0:    return [2,N/2]

   a = gmpy.mpf(gmpy.ceil(sqrt(N)))
   count = 0

   while not is_square(gmpy.mpz(a ** 2 - N)):
      a += 1
      count += 1
      if verbose:
         if (count % 1000000 == 0):
            sys.stdout.write("\rCurrent iterations: %d" % count)
            sys.stdout.flush()
      if time() > end_time:
         if verbose: print "\nTime expired, returning [1,N]"
         return [1,N]

   b = sqrt(gmpy.mpz(a ** 2 - N))
   print "\nModulus factored!"
   return [long(a - b), long(a + b)]
Exemplo n.º 30
0
def getints(minint = 0, maxint = 1, number=RES_LEN):
    """Returns a list of partly random ints
    
    The list starts with the numbers from INTPOOL['mandatory'], continues with
    INTPOOL['extra'] and finishes with uniformly distributed random ints.
    
    Parameters
    ----------
    minint: int, defaults to 0
    \tLower bound of ints in ist
    maxint: int, defaults to 1
    \tUpper bound of ints in ist
    number: int, defaults to RES_LEN (1000)
    \tLength of list
    
    """
    res = INTPOOL['mandatory'][:number]
    res = [x for x in res if minint <= x <= maxint]
    left = number - len(res)
    if left > 0:
        res += INTPOOL['extra'][:left]
    res = [x for x in res if minint <= x <= maxint]
    left = number - len(res)
    while left > 0:
        res += [gmpy.rand('next', maxint - minint) + gmpy.mpz(minint)]
        left -= 1
    return res
Exemplo n.º 31
0
def check_rsa_key(sample):
   """
   Returns a 3-tuple (is_rsa_key, has_private_component, n_bit_length)
   
   is_rsa_key - a bool indicating that the sample is, in fact, an RSA key
      in a format readable by Crypto.PublicKey.RSA.importKey
   has_private_component - a bool indicating whether or not d was in the
      analyzed key, or false if the sample is not an RSA key
   n_bit_length - an int representing the bit length of the modulus found
      in the analyzed key, or False if the sample is not an RSA key
   """
   is_rsa_key = has_private_component = n_bit_length = False

   try:
      rsakey = RSA.importKey(sample.strip())
      is_rsa_key = True
      if rsakey.has_private():
         has_private_component = True
      n_bit_length = gmpy.mpz(rsakey.n).bit_length()
   # Don't really care why it fails, just want to see if it did
   except:
      is_rsa_key = False
   return (is_rsa_key, has_private_component, n_bit_length)
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=x.remove(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
Exemplo n.º 33
0
    def check_g(self, results):
        self.function_count[10] += 1
        #print "g = " + str(results[0].value)
        self.g = results[0].value
        jacobi = gmpy.jacobi(self.g, self.n_revealed) % self.n_revealed
        #print "jacobi = " + str(jacobi)

        if jacobi == 1:
            if self.runtime.id == 1:
                self.phi_i = self.n_revealed - self.p - self.q + 1
                print "((N)): " + str(self.n_revealed)
                print "((p)): " + str(self.p)
                print "((q)): " + str(self.q)
                print "<<phi_i>>: " + str(self.phi_i)
                base = gmpy.mpz(self.g)
                power = gmpy.mpz(self.phi_i / 4)
                print "<<power>>: " + str(power)
                modulus = gmpy.mpz(self.n_revealed)
                self.v = int(pow(base, power, modulus))
                #self.v = self.powermod(self.g, (self.n_revealed - self.p - self.q + 1) / 4, self.n_revealed)

            else:
                self.phi_i = -(self.p + self.q)
                self.inverse_v = int(gmpy.divm(1, self.g, self.n_revealed))

                base = gmpy.mpz(self.inverse_v)
                power = gmpy.mpz(-self.phi_i / 4)
                modulus = gmpy.mpz(self.n_revealed)
                self.v = int(pow(base, power, modulus))

            #print "self.phi_i = " + str(self.phi_i)

        else:
            self.generate_g()
            return

        #print "self.v = " + str(self.v)

        v1, v2, v3 = self.runtime.shamir_share([1, 2, 3], self.Zp, self.v)

        v_tot = v1 * v2 * v3
        self.open_v = self.runtime.open(v_tot)
        results = gather_shares([self.open_v])
        results.addCallback(self.check_v)
Exemplo n.º 34
0
 def __mul__(self, a):
     '''multiplication by a scalar
        The result is a PPATC Ciphertext which encrypts and commits on e*m
     '''
     m = gmpy.mpz(1)
     if not isinstance(a, int) and not isinstance(
             a, long) and not type(a) == type(m):
         raise Exception(
             "Multiplication of a PPATC Ciphertext by a non integer, long or mpz"
         )
     else:
         Jcoord = self.PPATCpk.PPATCpp.Jcoord
         ECG = self.PPATCpk.g1.ECG
         c1t = oEC.toTupleEFp2(self.c1, Jcoord)
         nc1t = oEC.mulECP(ECG, c1t, a, sq=True, Jcoord=Jcoord)
         newc1 = oEC.toEFp2(ECG, nc1t, Jcoord)
         c2t = oEC.toTupleEFp2(self.c2, Jcoord)
         nc2t = oEC.mulECP(ECG, c2t, a, sq=True, Jcoord=Jcoord)
         newc2 = oEC.toEFp2(ECG, nc2t, Jcoord)
         c3t = oEC.toTupleEFp2(self.c3, Jcoord)
         nc3t = oEC.mulECP(ECG, c3t, a, sq=True, Jcoord=Jcoord)
         newc3 = oEC.toEFp2(ECG, nc3t, Jcoord)
         return PPATCCiphertext(a * self.d, newc1, newc2, newc3,
                                self.PPATCpk)
Exemplo n.º 35
0
def PollardsRho(N):
    #   Pollard's Rho method for factoring
    from exercises import Alg_improved_Euclid as gcd
    from random import randint
    N = gmpy.mpz(N)
    """ generator function """
    def f(x, N):
        return (((x**2) + 1) % N)

    t = 75 * gmpy.sqrt(N)
    sqrt_t = gmpy.sqrt(t)

    factor_found = False
    while not factor_found:
        xim1 = randint(1, gmpy.sqrt(N) / 10)  # seed
        yim1 = f(f(xim1, N), N)

        i = 0
        while i < sqrt_t:
            xi = f(xim1, N)
            yi = f(f(yim1, N), N)
            # yi =    f( yim1, N )
            # xi = f( f( xim1, N ), N )
            # print( 'gcd( xi - yi ) = gcd( %d )' % abs(xi - yi) )
            d = gcd(abs(xi - yi), N)
            if d != 1:
                print('Non trivial factor found: ', d)
                factor_found = True
                break
            if xi == yi % N:
                print('Running with new seed')
                break

            xim1 = xi
            yim1 = yi
            i += 1
Exemplo n.º 36
0
def set_bits(number, position, num_bits, value, start_from='left', bits=64):
    '''
    Function to extract num_bits bits from a given
    position in a number
    '''
    # convert number into binary first
    if not isinstance(number, str):  # is str if previously binarized
        number = mpz(number).setbit(bits)
    binary = '0b' + bin(number)[-64:]

    # this is needed because mpz adds a 1 at the beginning
    # print('set_bits before:', binary)

    # remove first two characters
    binary = binary[2:]

    if start_from == 'left':
        start = position
        end = position + num_bits
    else:  # if == 'right'
        end = len(binary) - position
        start = end - num_bits

    # extract k  bit sub-string
    bin_value = bin(value)[2:]
    replacement = bin_value[max(0, len(bin_value) - (end - start)):]
    if len(replacement) < num_bits:
        pad = ''.join(['0' for _ in range(num_bits - len(replacement))])
        replacement = pad + replacement
    # print(replacement)
    binary = '0b' + binary[0:start] + replacement + binary[end:]

    # print('set_bits after:', binary)

    # convert into decimal again
    return int(binary, 2)
Exemplo n.º 37
0
    def __init__(self, x, radix=2, blocksize=None):
        _x_type = type(x)

        if _x_type in [_gmpy_mpz_type, int, long]:
            self._x = gmpy.digits(x, radix)
        elif _x_type in [FFXInteger]:
            self._x = x._x
        elif _x_type in [str]:
            self._x = x
        elif _x_type in [float, _gmpy_mpf_type]:
            self._x = gmpy.digits(gmpy.mpz(x), radix)
        else:
            raise UnknownTypeException(type(x))

        self._radix = radix
        if blocksize:
            self._blocksize = max(blocksize, len(self._x))
            self._x = '0' * (blocksize - len(self._x)) + self._x
        else:
            self._blocksize = None

        self._as_bytes = None
        self._as_int = None
        self._len = None
Exemplo n.º 38
0
    def __init__(self,
                 s,
                 prover_id,
                 k,
                 runtime,
                 c,
                 random=None,
                 paillier=None,
                 x=None,
                 r=None):
        """
        random: a random source (e.g. viff.util.Random)

        All players must submit the same vector c, but only the player
        with id prover_id should submit the corresponding x and r, e.g. where
        c_i = E_i(x_i, r_i).
        """
        assert len(c) == s
        assert prover_id in runtime.players
        if x != None:
            for xi in x:
                assert abs(xi) <= 2**k
        self.x = x
        self.r = r
        self.s = s
        self.m = 2 * s - 1
        self.prover_id = prover_id
        self.k = k
        self.runtime = runtime
        self.c = c
        self.paillier = paillier
        self.random = random
        self.prover_n = mpz(self.runtime.players[self.prover_id].pubkey['n'])

        # TODO: Use the n**2 already in the pubkey.
        self.prover_n2 = self.prover_n**2
Exemplo n.º 39
0
def main():
    if not len(args.n) == len(args.c):
        print("Modulus or congruence relation missing")
        exit()

    if args.files:
        array_mod, array_congr, pubexp = file_mode()
    else:
        array_mod = args.n
        array_congr = args.c

    if not check_coprimes_all(array_mod, len(array_mod)):
        print("Modulus integer set must be pairwise coprime")
        exit()

    M = functools.reduce(lambda x, y: int(x) * int(y), array_mod)
    Mis = compute_Mis(M, array_mod)
    Yis = compute_modular_inverses(Mis, array_mod)

    K = compute_global_congruence(array_congr, Mis, Yis) % M

    print("\n x is congruent to {} \nmod {}".format(K, M))

    if args.files:
        K_great = gmpy.mpz(K)
        main_root = K_great.root(pubexp)
        if not main_root[1] == 1:
            print(
                "\n {}th-root of m^e is not an integer. Check input message integrity."
            )
            exit()

        Solution = int(main_root[0])
        print("\n Decrypted m integer value : {}".format(Solution))
        print("\n Possible cleartext value : ")
        print(libnum.n2s(Solution))
Exemplo n.º 40
0
def calculate_seed(n):
    initial_time, final_time = calculate_seconds()
    gmp_initial_time = _g.mpz(initial_time)
    gmp_final_time = _g.mpz(final_time)
    gmp_initial_pid = _g.mpz(0)
    gmp_final_pid = _g.mpz(32768)
    gmp_initial_ppid = _g.mpz(0)
    gmp_final_ppid = _g.mpz(32768)

    while gmp_initial_time <= gmp_final_time:
        while gmp_initial_pid <= gmp_final_pid:
            # print gmp_initial_pid
            while gmp_initial_ppid <= gmp_final_ppid:
                seed = gmp_initial_time * gmp_initial_pid * gmp_initial_ppid
                # print seed
                rvalue = create_random_value(seed)
                # while _g.numdigits(rvalue,2) != 1024:
                #     rvalue = create_random_value(seed)
                calculate_division(rvalue, n)
                # print rvalue
                gmp_initial_ppid += 1
            gmp_initial_pid += 1
        # print gmp_initial_time
        gmp_initial_time += 1
Exemplo n.º 41
0
    def _hashad(self):
        from struct import pack, unpack
        import zlib
        import gmpy

        def my_parse_number(number):
            string = "%x" % number
            # if len(string) != 64:
            #    return ""
            erg = []
            while string != '':
                erg = erg + [chr(int(string[:2], 16))]
                string = string[2:]
            return ''.join(erg)

        def extended_gcd(a, b):
            x, y = 0, 1
            lastx, lasty = 1, 0
            while b:
                a, (q, b) = b, divmod(a, b)
                x, lastx = lastx - q * x, x
                y, lasty = lasty - q * y, y
            return (lastx, lasty, a)

        def chinese_remainder_theorem(items):
            N = 1
            for a, n in items:
                N *= n
            result = 0
            for a, n in items:
                m = N / n
                r, s, d = extended_gcd(n, m)
                if d != 1:
                    N = N / n
                    continue
                    # raise "Input not pairwise co-prime"
                result += a * s * m
            return result % N, N

        sessions = [{
            'e':
            17,
            'n':
            25492165341402870943193342194243878583550091830588300179983190484677536677783878770091771426745020581968485223806403482688708690916599646206863308796421682192123291604607235755107364431209342465647517951497018019170871611821471577647494718032136027446239385000016582048814012025961200909864909126220898470337474181564969111740549293849528764155308076160637626891491670481790680054394999454113154731685789729310781453533838696397873008408145290785550608424077599753426457559997966726766077860415133627965054965186926286998932683118114065698789972581403018027054849591593302510627959868541308908688742433116746685957413,
            'c':
            6666419060534882063445608631701254352058920974421822069727027885698959797948070412066328188514278918986722361742912500893728424745043197562231410354633167915385978833339701529722766937863212423943888214894271923064950171580353934178748023608466389268996754295631668202047874774966518214639701079489902676101992190471567121772228753020078695924075081945558620706927179092603126041395606016633822502612954885417984184184737630487502072507997213412593690188577996870365218951232207636278621674542750965270226225337180320970384418820119666789283194398074172939976925377054214851752639573115850958399373724855553234690869
        }, {
            'e':
            17,
            'n':
            21127940129465859529449290710465142401626099761120448822896227957140612250511186166751154941578458258054285578274511450860570540828102070111370941358023009904308008795394643585864471986075987747216086746123427597776886622933600026324537947907678164739969468650427560672262831484437166952755098875024996456298734488381416586155715216067643259554486571154930556222002298362539331180176023831109425436177078457326927485711697356496728959762158514131974253928871967648747022232011642161107225163919743383709749413596786170516661129884422397760268997322898954161891328103774133077184028190158020665184081778231669390621447,
            'c':
            3025342965063970983290961997148038673244905555308289391392896371605967574831912573039170667272658109340534212720805676884032065407092138739865486740854024452063900964324730683963944994250537553102328024132087660954040726648939149676030355851576763910670469390583200661923104138267998714166483656478619852365437776250801008285867722681155855008497404084448836122553221951674607943082229713841396761939215145379881979676835537964953725808825354819362797503568722134701601966504482232887162578922823026182148541889898696868501626860530484834082878781257554947276873624962134091380186322272011345017295000538738940807566
        }, {
            'e':
            17,
            'n':
            22563350736629808264395772922819808510705484822245634475903533464108273973359621048788502042378085143059458230242646589967392945320090987067961491654357416853755261074531634683509015394347409817614889849143844247148479574777870355411207636748917532445668322051861338052906797819332259215278552079454184458015646487703430124222965707626399501332317111449272813630361908462924849723439803107908568327484445685641242797481816740336203447956828486867818411976997494338407256234593013250778655132122780432402623365698921928370817670245911505312288465537126236680323692662919137486755722237256218345361985595174086335811073,
            'c':
            20135971165126329834498721501784512951499984648652660104821647741072871489936836442504197592142991669369919035304425516258391511301425226375564892415339365148509645261565560913559856659645387805198871549146172257882053281268795760344994001608956789940307816388486468042693545041073838774812997395437209060397149458050765177205158052575861667488415782153713633691372314235926019032628836133660245109281683465499593548858659962576728675714563027957143405441096816687188373864658407934159173393698714390810577718268693096568336071207238450039773940104963444157704166286892082172461258702049072827677476706096904316460964
        }, {
            'e':
            17,
            'n':
            19697677554331221267369641184167188448335213481430897452143918418367154993523756864868509098839783053011355139590418269119504715550443490754762988015861768839038067134509092125205376509678043881070558825637905431885254727168679069330416776166369184375970521838169214107508952264240335498312849019213361951991190975616614804433716772411184993774461040690673753098373736933084616647869336141707774024488317582512216162403209135110515778522772939206567850540704356683976987508523230996026019768603629874558741038975853009975048175519392495212857366577161641687502674304846608725983145033337187267988999492371626182417551,
            'c':
            14300174742950957133230867352717457897986205104543265825218842008467109972830138620119291505539500355334723376879888409251809364632635010202950500050892997355318105884900306620239365641681252935777362167024611054220484107153146560621083009306565476636270883588514007454668850327310521718849400741849368048026759782889674614052640379573508042637071620721869972662416840328750772187247907576009995766111841008793044576343182936834713229276992314777759684829492003814595802694592792453101320053268786720734738162720052909591108493186651733642823133001888727983206566194875945734575411295063088173363528901413605439659186
        }, {
            'e':
            17,
            'n':
            22840174333461757597258965063503187552495604936013453813620970124752854692025931772152482715744058240571638175460349150353012889988723597821978579743499713766809084692254297539180932689148176677208822562008650864838388158004011554059006621226560748426334342736035675518932164604927602370423087532589029111052023317750367568915149473019058579728528211621618516222534404936592529521724927756742450435643292165615017136698859157488474841102297647488008004924900405006989945846311096537399030509947027554824768198503677139485403433484337602107191422279674605462427176871354240310242684337649527314815937448142118014471869,
            'c':
            7269879938285087105060326068602691458154834670489063661854932312114567012381462325708324462473335735747751985833951832304054546004436096189761282474552769255043106817537407079708725883409397856635437608590617899532129476884853580275762892523609169600551500977086971018619327642914168273376084417345670925345416864822282780628646416374712921155883117431305185117831110048721693951865267141962666069350614792416053836803149161735632213430960384988586996269807413280397202373128437527421378900814241234271529460443131737298476049472736692048979564047934967259654010923397531158463241672904787724046355796318156683211693
        }, {
            'e':
            17,
            'n':
            26181530231990596208912553982832841408036769882768643576772592303571004331051012292548525104394717484252349998434031623438917061404178468743247357634872314865905132523154238118481540371615056806756673945897771283881615017345596477766231957968854622033499073650939380455320632540323169565251694316300843433445667057555206872698949047971459662093473609973167299463621536822302820363096764742010575821082948519766535657152613824870739004432505303862201505469354785224205708777422229564239113870271947768783809029625932248575272642464554827073657622048405963388795704112995209429712517330431946725366254154641804680636843,
            'c':
            6596498503473090384156122948918457693225694527543771961484972133896304927525029433085731957072789891646290597692421323936231128201822432631159176346646447011338805190482179145913035869942714613486895588754112366313438192851954663748505238329830016450238817308208066971617432717047936473721490905750275563930145038394216747562079905090073621918898708464447477835510214346908545028865672847041949340101722558962541612836311085196500521238354347015877914823677634283521373575663416167402249149782097385550791425270622816978948552969790013217066937461634555711434991830871731594480554761087920979267051612013063691897091
        }, {
            'e':
            17,
            'n':
            18375116136153390105382127878395045588105857107246922094470216545244337357987681718168448429849698069981688291927806366721855289976121993055091218569849787514394507275481429728206429948836923251296672175100798033529862498578044854162615314211321712132747044363074981129056925717085204066189560133707352709019771792017200539059204024262019592851381317279368957556414371834469907989489823310736060223258994989400405121984031058976855896631117913090748375198718936570595983429517914008170697730495897896134771484309035561040862223201385431761693343426402858632921946359721016131084165400212811848077899966364178485645209,
            'c':
            14450411368079644952604705871870024872670263251365527266862703716230778731191117713744962010138824834514424908701300856449356388617430510950535877723758382120583446269291649779277478125202353436896123871466945681583403794725306243733343462009791759823657466902546992816090954580754519785729524996046358307197773786618439603452776474869740548426942373102466687002398105444228516302695737600836706505822006007382861266883167162032588362091247091029707841718663522787461434574458986841049123553142254769053444081497788062775004085437066317446657655214417638414799100287660747244854718117257942197065271633812453504802118
        }, {
            'e':
            17,
            'n':
            18856599160001833299560082802925753595735945621023660831294740454109973698430284916320395522883536507135735383517926050963512440162483065097256884040938259092582892259657340825971260278387406398529168309426241530551396056450450728728601248269612166083300938497235910244979946020059799495231539400114422748104072550004260736766137354572252872437140063474603268146956570787143010441293268321641092743010805639953103578977668248726500636191043930770036787317928372179939360510179438436665591755940224156131460271763912868322774604558314812111335691108887319827579162188169744014973478052491398688611046800951698773893393,
            'c':
            9537600333774561965347809713893729543607050845183365456822389928272539309054686047543168922742589173859871008938711574330675462024831693796734766356934966684018899382045308313458440052017835494802986355673813464215184924837019853399388984893499187144821922554214143314640377079505897680854314880035458832414257859211958802973880776732222536460326269825765449639225220135735729106020282618914111685220841901015367575108920943148006106714487046602965253293770388951872741849791157534395777330833976209975828865170184061768114280467192574451716204110866562270737220078456700440400847759035001437357717203367869014507886
        }, {
            'e':
            17,
            'n':
            27658060678038715780470429570597987144542213875178081185638364125349217264266787337266356239252353691015124430930507236433817624156361120645134956689683794554169169254645287613480048966030722812191823753459580311585866523664171185580520752591976764843551787247552790540802105791272457516072210641470817920157370947681970410336005860197552073763981521526496955541778866864446616347452950889748333309771690509856724643918258831575902389005661750464296924818808365029037591660424882588976607197196824985084365272217072807601787578262208488572448451271800547820717066767396857464594301327160705353075064322975430897551911,
            'c':
            11433488612991990768536086698965180146550356348457563234735402111134701115830423042016221831657484325065472609147436229496479358788735270448637824809543880271526735635196884978639585020518147152207002685868984199742884443523231593245377292570809368330956970290791633106067116466080014631110596564728982066569618319541351401820732547227122970369299780366876340403436785218211729531092484723580223801525992510782266856454394478372421830988205823368541860973674259795969870252832216828042174346473447490557323038031625277043161510854825069681462499200978561823301487118145650943076528233694749306585201212677836363102350
        }, {
            'e':
            17,
            'n':
            22946690762018202432990887189358840679847544298138130593179782494313283235656708793278294817370704179431587028797820098265221065047094111469387707851755805572030960917620048531944164128853858185996116085402185608208505862268300069081634690281361741089802822427014733500818400628218120217701065238981427409232531524810373504821405505784194458324112411450898914981925380408035843501140943840375415504531028291728110941191868468403264579853022847273710668909241386840084506302813524686512443804790681324357699954553042087787664048340322301999798211625015533291431249576149925507273846582715275085720997988716732564925247,
            'c':
            22114155655659890875804525321139229042160702983880183010190613534988342335473532979092956071940843014846115113869717993343361412775761899123003515398037548495421246487341345482541093940292149812612966738017954607042366694074210348507360409383994155996445275183175086308877643260816760841714256410898269814908129813108551478627448054932601176813323889809069498060147451905095827442175810001123067159848367040168783825044279052630935945891964134230385303127654483691228319146427451587693985548002268250053416426728753739573823133295951972853182187229046285977320129680613905801285437766686995325893960172376926445625122
        }, {
            'e':
            17,
            'n':
            24196427886175544349183151853220199349004334700026598710073455177858086301574503667298550711896472441115488666905450709605686892168468755356865839253905196330957826522203721667534054840325504585224175556167326100374628995111103938603447308160978852917872087343333848311844292367100647648063686677699135973596041567307784602998888789211145238333237613511049640509935260207585999606022736214748154785163367146044878537220691272581381812904389596150391959046627047758159235384420979630615278721284429066540058110867810807414175942667916940934372027878979861244401198531405584211810881235860988295519048177492135610751359,
            'c':
            22296229997452473240404864600165019763565238056149885081619043661295445875270023158334098350603026725837611396891344057244652143898149482532106315521575872089742565470821567522946361662445964027209388657746191967435348044945947483621482721538186361050633595041353278781238956486769506373730884495108039610798833232749139421109269053404110580969203157360738738757856465985684697862079893042321411866940484105462672034009048091117594209570962168395344960105313171255329582011213721766675322731331965794652525786585751148977132545042466983433106614477836969990881581169493890539450115893703987635774477858244270608426284
        }, {
            'e':
            17,
            'n':
            24360507764722702236982664735328841420311376027120399241078325497875531961885056309904114723678048613901842270612025644417215018351512175660269184968149109110209563435463873211914594529847294730496535258882010197028842516927468678843924092706088182566726725380495130934316582041447010080540555792802432876873205758297773353354773400601269072565235285553745651262991130015382601486699000167692446155692416347390954126585612460075052988874628884097103408004610717498543307677173210168954439627061348158046928463114067813191846253937179490050784167037265795606665046543869952157800016132040847485597002954075447344679099,
            'c':
            2091608690891505258645949208946395204695041893228619053197065370886625848151228416356718762070352835427065857428605476603762875777761221509564315249418937215791628816353819422446178413024109351330646491084678357651148045128554746141683169277567849074245394149157710582616155738686711539953583528181614701953172972027101545253676978964454897005216320952879719740377602813279137554307680715749682175447559417772077472349519490785782899751615833622828868651966927604858524345638792811839384317780948838203430577334783095834911402913673850996431719159112716370014509918436690080118494876223156361387987999829094801210890
        }, {
            'e':
            17,
            'n':
            20991361604317638769781823650579915779070848318189821239839863416933546421097820271887796260918963289144354691357223973152195364244222103627141268032857145421152363842224398828703305592221616019678102879125957325674007444034541160527072712208844228077449624475289619712846717432293230773279322231288635231839457560272849165524911202814516841260722542666841002263011069065414760944278124011800036869640840312097012211808948108758865722731922057521488153991477824974687229720412552981052793827211890557079895492457992364345889589127536307112174252490433421772585442393590767593690124636778449673348970938028847369589017,
            'c':
            1176089662945377859394485590647428302230902074038834532187683920441006896963622996580792552532208518328678256998366963208028743204946660302538358531574765644007432906847438011315702121691613005078019506672007476291213237939507650616659336489497035998458925997634519034425449883103272960672562772204663037400144823802245320606039938019714906919958257594477982151857672916895153818922550365638890064326384677879791487276278839159022778493427572161764299809764447703117493013786755368150005501909964140795978310287946809348754988288402304994584145696550845106776916203635572397815715801968943287729470010695704992513284
        }, {
            'e':
            17,
            'n':
            23536517244565831304957548822169291652207666754083340160306298208076886665065064843803465469409961704414510544566548897045751559184520942970858445270483458341528037499088946028024476760938334724064432942414803725235245083424464022066205458380170453189950900307248048617678876232312945996520402058770976469558803007764420552804210174247648614671097046399148333316029580244153775977135880775921663886951776404864678251750085264792097984094013284691977749495264267344834078278955171634785277609298558886471141768976455150174601039402280137908104589898954351484608783306378026577123527889651575952772820003380025546341093,
            'c':
            2787570158312133794000264568955228362505478580337508384369847495327630702109418180218855630800765419691714135680571469213835542379448821209732447589306506369895651911135089075762137873889141680195343215032414145506957429427948190720862478335515596644926205381293106417410261520242246013085300698437878525197927303400003852408888917470597700285690342597850461091636279688711415205788329646890595805415907084665612141657880165938739423616058100283432682214722969192114128403177592988697839575450529126584549296274365360257579336454484779207708578834457262472129009056129647722165160424055970728939468425924742795247404
        }, {
            'e':
            17,
            'n':
            22418240669078782395650685709211154715963189697089263104799144782938556049238670824036504767273510569815649054522706833230147726835488621722481390416868271627116267103118088021697808807092496788890564153300558617457948161343658932652189856049810225397121264480931341652674373238956664385611007077903271999938666531870525476577337484325119704138317723687164049779101614572637615019989722168840820998326371954897496744184510021746784303032310300111064058399012572181069622479162656626630666689745901678446100898000876596201969536772169761074060718581442841244466714693693744538078059538322489346225247976911833748299831,
            'c':
            12741916458848035965674277226994440579915129055105462698845221890770558867890065973150125863687106455321192524282688850919026924493363241183706112792662939894532011809709158105688708409813198696055548036573709488504352009446189240170056000380659861236761237694775468132858916502459186242385986053427650331045218524574666652583364331482577973877822911369427036861116411565934292335204172142173748941863013032301778764886328258476195697934305418334527182261876183838908107190767800857337092015153451318295610430683371731834190637342265695335154669307530426675001781782217407160875559782488264585128426108095378548497650
        }, {
            'e':
            17,
            'n':
            23980852037830754961843810384842109198680213599160124627608485316452067979221814287579031744661623974638029208789156178351485676131492416093947908129410491693261731404401473508295054358751129977958761373804386612048163148740071525591509234298601816819182717519183021983010112798883286143566969631969002952806398266165159329990930567027893909276078886841121244401773915309649928992691723658667402744292184927500507621943557420540056270730461740897601661594495028880708798531876866777269713984635553934853524715534003465120928659881608776745499441872048908380726942161563974610455635903901327036597201663594811207962219,
            'c':
            6500753041357449855790208700753809194331642408448330624975108109751859721113916040913210608530117147284032825775613945416295553599499663257233673509345038912634968979540222246220460441613513695959331196716737175735741187191935319073270722811433035516074289343637773607521789970734447289501012767670625043452129332667983332570596510412510389935486708833483704894688513193020406791505432203906745860054901025547265075193156070642716676601268698224891768784422675343094235950805128869705790800102590177489342374151286188584127528879203511712056047898651580309669143955726928687269246843562481439718815596302692298516533
        }, {
            'e':
            17,
            'n':
            20692935323456318857339636506121661409781600706918188791579569287363925379425076174758120076604134447812506062875425652061813752876711066070389233324351070782264123950482732919402628782987702034544299244918439112034234610691454353578647793100554890386226509128280993176780063155185886470116528236906519407444238424523493151082789442134440461004320839591569157239343299865825958454617581990948186838151424941117137818356712476559230872711658730923799079308488965817006179693410669320825141974869847267757553830878658559853061666130127729833856270147578804267991192625989184535593836836877723580138193263333297569871679,
            'c':
            3149880252209031344712912478150309339789690396685866282400905925814536568350616764434288908486968492252351255022161340923513529850192573780350157980373627989388396346845656970516353356298790654832486310492079962338672745285854665147406015543850517102001543987674241995267846019477920439984122318278402925428057397039652213642437095694526592410641576952281061504190238132151689288080423425867830015832927809704559212420233819682781217618789216812964682441589327621971863380979777355679805008775337364919278947618188598427198109821307637144473819840409743353235834034795849314936322245339378447572244022235758755318197
        }, {
            'e':
            17,
            'n':
            22182114562385985868993176463839749402849876738564142471647983947408274900941377521795379832791801082248237432130658027011388009638587979450937703029168222842849801985646044116463703409531938580410511097238939431284352109949200312466658018635489121157805030775386698514705824737070792739967925773549468095396944503293347398507980924747059180705269064441084577177316227162712249300900490014519213102070911105044792363935553422311683947941027846793608299170467483012199132849683112640658915359398437290872795783350944147546342693285520002760411554647284259473777888584007026980376463757296179071968120796742375210877789,
            'c':
            16279989825796156802547712583633798298339885806436476356497796047229021124610630851145390462136716298450342674217575569196543919171078736243934669612002081179432014315465408489156509075853163302037413161239227506465361288161349464334942343016752593577869091378915378775289174914088843177811858916838452126433042585745992994815140378356718198629815818784659700720051966660786554920296721138381405607252098516473395177368859057746002895683463397630717358844874557866924382768279446164993249061647243362602307728771126094369384362246840728274885512559106673543101063171808938427459691773785819336680808200730383909434687
        }, {
            'e':
            17,
            'n':
            21996468204721630460566169654781925102402634427772676287751800587544894952838038401189546149401344752771866376882226876072201426041697882026653772987648569053238451992877808811034545463363146057879646485465730317977739706776287970278094261290398668538232727000322458605289913900919015380904209692398479885177984131014170652915222062267448446642158394150657058846328033404309210836219241651882903083719822769947131283541299760283547938795574020478852839044803553093825730447126796668238131579735916546235889726257184058908852902241422169929720898025622336508382492878690496154797198800699611812166851455110635853297883,
            'c':
            18919626944919001746434424216626233185707755539125451453498872012547818089480281584466165481221804279035723497497262166426771134459922980759121024951390547522550510734782168869364945944106404378597344695227319394862905382593128694330512816879360904284025740295670026092938765777154761403682710878968080966485091090198109371223563090698724814081281842426885356314840392128767155541449360105460941384985904101420698734690361896580259169275867969219822351776569430617405034594385605780084981880407657528516176335362438505224655581522137130777263875034088903829280901936110414932437809315770012018024957989707333743935907
        }]
        data = []
        for session in sessions:
            e = session['e']
            n = session['n']
            msg = session['c']
            data = data + [(msg, n)]
            print("-" * 80)
        print("Please wait, performing CRT")
        x, n = chinese_remainder_theorem(data)
        e = session['e']
        realnum = gmpy.mpz(x).root(e)[0].digits()
        print(my_parse_number(int(realnum)))
        raw_input("执行完毕,按任意键继续...")
Exemplo n.º 42
0
for power in (15, 16, 30, 32, 45, 48, 60, 64, 75, 90, 96, 105, 120, 128):
    for i in (-2, -1, 0, 1, 2):
        valueList.append(2**power + i)

valueList.append('123456789012345678901234567890')
valueList.append(
    '10000000000000000000000000000000000000000000000000000000000000000')

testValues = []
mpzValues = []
for i in valueList:
    for t in intTypes:
        testValues.append(t(i))
        testValues.append(-t(i))
    mpzValues.append(gmpy.mpz(i))
    mpzValues.append(-gmpy.mpz(i))

testValues.extend(mpzValues)

for i in testValues:
    for z in mpzValues:
        # Test all permutations of addition
        assert int(i) + int(z) == i + z, (repr(i), repr(z))
        assert int(z) + int(i) == z + i, (repr(i), repr(z))

        # Test all permutations of subtraction
        assert int(i) - int(z) == i - z, (repr(i), repr(z))
        assert int(z) - int(i) == z - i, (repr(i), repr(z))

        # Test all permutations of multiplication
Exemplo n.º 43
0
def str2mpz(string):
    return mpz(string, 256)
Exemplo n.º 44
0
 def __init__(self):
     self.p = mpz("DD4ABECC719B945481602AD72BA43B7E5998C07EB", 16)
     self.q = mpz("6C5CF455F6FEE7B8DE5D2D041E80821A207F440253", 16)
     self.prn = ""
Exemplo n.º 45
0
def createBoard(number):
    return mpz(number)
Exemplo n.º 46
0
from Crypto.PublicKey import RSA
import gmpy


def crt(n, a):
    sum = 0
    prod = reduce(lambda a, b: a * b, n)

    for n_i, a_i in zip(n, a):
        p = prod / n_i
        sum += a_i * inverse(p, n_i) * p
    return sum % prod


keys = []
data = []

for line in open('output').read().split():
    key, cipher = line.split(':')

    keys.append(int(key))
    data.append(bytes_to_long(cipher.decode('base64')))

m = crt(keys, data)

# ce que la double encryption fait est equivalente a
# (m^e mod n)^e mod n = m ^ (e*e) mod n
# on cherche donc la racine e^2 soit 3^2 = 9

print long_to_bytes(gmpy.mpz(m).root(9)[0])
Exemplo n.º 47
0
)

C.getcontext().prec = C.MAX_PREC

for n in [100000, 1000000, 10000000, 100000000]:

    print("n = %d\n" % n)

    start_calc = time.time()
    x = factorial(C.Decimal(n), 0)
    end_calc = time.time()
    start_conv = time.time()
    sx = str(x)
    end_conv = time.time()
    print("cdecimal:")
    print("calculation time: %fs" % (end_calc - start_calc))
    print("conversion time: %fs\n" % (end_conv - start_conv))

    start_calc = time.time()
    y = factorial(mpz(n), 0)
    end_calc = time.time()
    start_conv = time.time()
    sy = str(y)
    end_conv = time.time()

    print("gmpy:")
    print("calculation time: %fs" % (end_calc - start_calc))
    print("conversion time: %fs\n\n" % (end_conv - start_conv))

    assert (sx == sy)
import sys
try:
    m = sys.hash_info.modulus
except NameError:
    print("new-style hash is not supported")
    sys.exit(0)

for s in [0, m // 2, m, m * 2, m * m]:
    for i in range(-10, 10):
        for k in [
                -1, 1, 7, 11, -(2**15), 2**16, 2**30, 2**31, 2**32, 2**33,
                2**61, -(2**62), 2**63, 2**64
        ]:
            val = k * (s + i)
            assert hash(val) == hash(gmpy.mpz(val))

print("hash tests for integer values passed")

for d in [1, -2, 3, -47, m, m * 2]:
    for s in [0, m // 2, m, m * 2, m * m]:
        for i in range(-10, 10):
            for k in [
                    -1, 1, 7, 11, -(2**15), 2**16, 2**30, 2**31, 2**32, 2**33,
                    2**61, -(2**62), 2**63, 2**64
            ]:
                val = k * (s + i)
                if val:
                    assert hash(fractions.Fraction(d, val)) == hash(
                        gmpy.mpq(d, val)), (d, val,
                                            hash(fractions.Fraction(d, val)),
Exemplo n.º 49
0
from functools import reduce
import gmpy
import json, binascii


def modinv(a, m):
    return int(gmpy.invert(gmpy.mpz(a), gmpy.mpz(m)))


def chinese_remainder(n, a):
    sum = 0
    prod = reduce(lambda a, b: a * b, n)
    for n_i, a_i in zip(n, a):
        p = prod // n_i
        sum += a_i * modinv(p, n_i) * p
    return int(sum % prod)


with open("mayday.json") as dfile:
    data = json.loads(dfile.read())
data = {k: [d.get(k) for d in data] for k in {k for d in data for k in d}}
t_to_e = chinese_remainder(data['n'], data['c'])
t = int(gmpy.mpz(t_to_e).root(7)[0])
print(binascii.unhexlify(hex(t)[2:]))
Exemplo n.º 50
0
def modinv(a, m):
    return int(gmpy.invert(gmpy.mpz(a), gmpy.mpz(m)))
Exemplo n.º 51
0
#!/bin/python
import gmpy
import base64
from Crypto.Util.number import *
n64 =
e64 =
n = bytes_to_long(base64.b64decode(n64))
e = bytes_to_long(base64.b64decode(e64))
file64 =
chiper = bytes_to_long(base64.b64decode(file64))
gs = gmpy.mpz(chiper)
gm = gmpy.mpz(n)
g3 = gmpy.mpz(3)
print 'n : ', n
print 'e : ', e
mask =
gmpy.mpz(0x8080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808000)
test = 0
while True:
	if test == 0:
		gs = gs
	else:
		gs += gm
	root,exact = gs.root(g3)
	if (root & mask).bit_length() < 8:
		print root
		break
print '\n',hex(int(root))[2:-1].decode('hex')
Exemplo n.º 52
0
def round(value, k):
    n = value / k
    n = mpz(n + 0.5)
    return n * k
Exemplo n.º 53
0
# relies on Tim Peters' "doctest.py" test-driver
r'''
>>> filter(lambda x: not x.startswith('__'), dir(f))
['_copy', 'binary', 'ceil', 'digits', 'f2q', 'floor', 'getprec', 'getrprec', 'qdiv', 'reldiff', 'round', 'setprec', 'sign', 'sqrt', 'trunc']
>>>
'''
try:
    import decimal as _d
except ImportError:
    _d = None

import gmpy as _g, doctest, sys
__test__ = {}
f = _g.mpf('123.456')
q = _g.mpq('789123/1000')
z = _g.mpz('234')
if _d: d = _d.Decimal('12.34')

__test__['elemop']=\
r'''
>>> print _g.mpz(23) == _d.Decimal(23)
True
>>> print _g.mpz(d)
12
>>> print _g.mpq(d)
617/50
>>> print _g.mpf(d)
12.34
>>> print f+d
135.796
>>> print d+f
Exemplo n.º 54
0
#!/usr/bin/env python
import gmpy
print str(gmpy.mpz(2**20996011 - 1))[-15:]
Exemplo n.º 55
0
_PyHASH_INF = sys.hash_info.inf
_PyHASH_NAN = sys.hash_info.nan

# _PyHASH_10INV is the inverse of 10 modulo the prime _PyHASH_MODULUS
_PyHASH_10INV = pow(10, _PyHASH_MODULUS - 2, _PyHASH_MODULUS)


def xhash(coeff, exp):
    sign = 1
    if coeff < 0:
        sign = -1
        coeff = -coeff
    if exp >= 0:
        exp_hash = pow(10, exp, _PyHASH_MODULUS)
    else:
        exp_hash = pow(_PyHASH_10INV, -exp, _PyHASH_MODULUS)
    hash_ = coeff * exp_hash % _PyHASH_MODULUS
    ans = hash_ if sign == 1 else -hash_
    return -2 if ans == -1 else ans


x = mpz(10)**425000000 - 1
coeff = int(x)

d = Decimal('9' * 425000000 + 'e-849999999')

h1 = xhash(coeff, -849999999)
h2 = hash(d)

assert h2 == h1
Exemplo n.º 56
0
#!/usr/bin/env python

import gmpy

n = 29331922499794985782735976045591164936683059380558950386560160105740343201513369939006307531165922708949619162698623675349030430859547825708994708321803705309459438099340427770580064400911431856656901982789948285309956111848686906152664473350940486507451771223435835260168971210087470894448460745593956840586530527915802541450092946574694809584880896601317519794442862977471129319781313161842056501715040555964011899589002863730868679527184420789010551475067862907739054966183120621407246398518098981106431219207697870293412176440482900183550467375190239898455201170831410460483829448603477361305838743852756938687673

e = 3

c = 2205316413931134031074603746928247799030155221252519872650082343781881947286623459260358458095368337105247516735006016223547924074432814737081052371203373104854490121754016011241903971190586239974732476290129461147622505210058893325312869

gs = gmpy.mpz(c)
gm = gmpy.mpz(n)
g3 = gmpy.mpz(e)

mask = gmpy.mpz(
    0x8080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808080808000
)
test = 0
while True:
    if test == 0:
        gs = gs
    else:
        gs += gm
    root, exact = gs.root(g3)
    if (root & mask).bit_length() < 8:
        print root
        break

print '\n', hex(int(root))[2:-1].decode('hex')
Exemplo n.º 57
0
 def powMod(base, power, modulus):
     base = gmpy.mpz(base)
     power = gmpy.mpz(power)
     modulus = gmpy.mpz(modulus)
     result = pow(base, power, modulus)
     return int(result)
Exemplo n.º 58
0
#! /bin/env python
#-*- coding:utf-8; python-indent: 2; -*-

import gmpy
import sys
import sortsmill.linalg as lin

write = sys.stdout.write

rows = int(sys.argv[1])
cols = int(sys.argv[2])
x = gmpy.mpz(sys.argv[3])

A = lin.mpz_matrix_set_all(rows, cols, x)

B = [[None for i in range(0, cols)] for j in range(0, rows)]
C = lin.mpz_matrix_set_all(B, x)
for i in range(0, rows):
    for j in range(0, cols):
        if A[i][j] != B[i][j]:
            exit(10)
for i in range(0, rows):
    for j in range(0, cols):
        if A[i][j] != C[i][j]:
            exit(20)

for i in range(0, rows):
    for j in range(0, cols):
        if type(A[i][j]) != type(gmpy.mpz(0)):
            exit(100)
        if type(B[i][j]) != type(gmpy.mpz(0)):
Exemplo n.º 59
0
import gmpy
from gmpy import mpz
print(mpz("12").is_prime())
Exemplo n.º 60
0
def nthroot(n, a, NOISY=False):
    m0 = gmpy.mpz(a)
    res = m0.root(n)
    if NOISY:
        print(">> success? %s" % res[1])
    return res[0]