Example #1
0
def main():
    g_to_b   = powmod(G, 1048576, P)
    g_invert = invert(G, P)
    map      = {}

    time_start = time.time()
    calc_1 = t_mod(H * G, P)
    for i in range(1048576 + 1):
        calc_1 = t_mod(calc_1 * g_invert, P)
        map[calc_1] = i

    time_end = time.time()
    sys.stdout.write('\n\n')
    sys.stdout.write('Left side complete...\n')
    sys.stdout.write('Time: %0.3f ms\n' % ((time_end - time_start) * 1000.0))
    sys.stdout.flush()

    time_start = time.time()
    calc_0 = invert(g_to_b, P)
    for j in range(1048576 + 1):
        calc_0 = t_mod(calc_0 * g_to_b, P)

        if calc_0 in map:
            calc = (j * 1048576) + map[calc_0]

            sys.stdout.write('\n\n')
            sys.stdout.write('Successfully found x with a value of %s\n' % calc)
            sys.stdout.flush()

            break

    time_end = time.time()
    sys.stdout.write('Time: %0.3f ms\n' % ((time_end - time_start) * 1000.0))
    sys.stdout.flush()
Example #2
0
def get_h_pwd(coordinates):
    x = map(lambda x: x[0], coordinates)  # extract the x and y coordinates
    y = map(lambda x: x[1], coordinates)
    h_pwd_ = mpz()
    for i in xrange(config.max_features):
        h_pwd_ = gmpy2.add(h_pwd_, gmpy2.t_mod(gmpy2.mul(y[i], get_lambda_i(x, i)), config.q))
    h_pwd_ = gmpy2.t_mod(h_pwd_, config.q)
    return h_pwd_
Example #3
0
def get_lambda_i(x, i):
    lambda_i = mpz(1)
    for j in xrange(len(x)):
        if i != j:
            if x[i] == x[j] and __debug__:
                print x
                print i
                print j
                print config.q
            tmp = gmpy2.invert(gmpy2.sub(x[j], x[i]), config.q)
            tmp = gmpy2.t_mod(gmpy2.mul(x[j], tmp), config.q)
            lambda_i = gmpy2.t_mod(gmpy2.mul(lambda_i, tmp), config.q)
    return lambda_i
Example #4
0
    def _random_int(self, modulo):
        """Generate a random number modulo the supplied argument"""
        r_seed = int(os.urandom(32).encode('hex'), 16)
        r_state = gmp.random_state(r_seed)
        raw = gmp.mpz_urandomb(r_state, self.RANDOM_BITS)

        return gmp.t_mod(raw, modulo)
Example #5
0
def compute_d(e, N, p, q):
    # d * e mod phi(N) = 1
    # where phi(N) = N - p - q + 1
    phiN = phi(N, p, q)
    d = invert(mpz(e), mpz(phiN))
    x = mul(mpz(d), mpz(e))
    assert t_mod(x, mpz(phiN)) == 1
    return d.digits()
Example #6
0
def discrete_log(P, G, H):
    lookup   = {}

    g_to_b   = powmod(G, 1048576, P)
    g_invert = invert(G, P)

    calc_1   = t_mod(H * G, P)
    for i in xrange(1048576 + 1):
        calc_1 = t_mod(calc_1 * g_invert, P)
        lookup[calc_1] = i

    calc_0   = invert(g_to_b, P)
    for j in xrange(1048576 + 1):
        calc_0 = t_mod(calc_0 * g_to_b, P)
        if calc_0 in lookup:
            return (j * 1048576) + lookup[calc_0]

    return None
Example #7
0
def e_3_broadcast_attack(public_key1, public_key2, public_key3):
    enc1, e1, n1 = public_key1
    enc2, e2, n2 = public_key2
    enc3, e3, n3 = public_key3
    N = n1 * n2 * n3
    result = t_mod((enc1 * (N/n1) * invert(N/n1, n1)) + \
                (enc2 * (N/n2) * invert(N/n2, n2)) + \
                (enc3 * (N/n3) * invert(N/n3, n3)), N)
    result = iroot(result, 3)
    return result[0]
Example #8
0
def encrypt(m, key):
    (n, g) = key

    #t = int(time())
    t = 500
    rand_state = gmpy2.random_state(t)
    r = gmpy2.mpz_random(rand_state, n - 1) + 1

    c = gmpy2.t_mod(g**m * r**n, n**2)
    return c
Example #9
0
def power(lst, exponent, modulo, redix=8):
    result = 1
    while True:
        ind = exponent & (2**redix - 1)
        result = gmpy2.t_mod(gmpy2.mul(result, lst[ind]), modulo)
        exponent = exponent >> redix
        print(sys.getsizeof(exponent))
        if exponent == 0:
            break
    return result
Example #10
0
def BruteForceK(message, pub, r, s, k_min, k_max):
    (p, q, g, B) = pub
    H = mpz(getSHA1(message), base=16)
    for k in xrange(k_min, k_max):
        r_inv = invert(r, q)
        d = t_mod(((s * k) - H) * r_inv, q)
        if powmod(g, d, p) == B:
            print "[+] Found the Private Key."
            print "[+] Key(k) : %s, Priv(d) = %s" % (hex(k), hex(d))
            return (k, d)
    return (None, None)
Example #11
0
 def signcrypt(self, Reciever, params, m):
     #	R = g ** w mod p, w <-- Zq
     w, R_value = random_pick(params.p, params.q, params.g)
     #	h1_R = H1(ID_R, X_R, Y_R) <-- Zq
     h1_R = H1_hash(Reciever.uid, Reciever.X_u, Reciever.Y_u,
                    bit_length(params.q))
     #	T = (X_R * Y_R * (p_pub**h1_R)) ** w mod p
     T_value = T_compute(Reciever.X_u, Reciever.Y_u, params.p_pub, h1_R, w,
                         params.p)
     #	C = m * T mod p
     C_value = t_mod(m * T_value, params.p)
     #	h2 = H2(ID_S, T, m, C) <-- Zq
     h2_value = H2_hash(self.uid, T_value, m, C_value, bit_length(params.q))
     #	(x_S + y_S) ** -1 mod q
     x_y_invert = invert(self.x_u + self.y_u, params.q)
     #	S = h2 * w * (x_S + y_S) ** -1 mod q
     S_value = t_mod(h2_value * w * x_y_invert, params.q)
     #	signcryption_text = (R, C, S)
     Signcryption_text = (R_value, C_value, S_value)
     return Signcryption_text
Example #12
0
def crt(n, x):
    """Chinese remainder. For n = [n1, n2, ...] and x = [x1, x2, ...]
    computes an r such that:
    r \equiv x1 mod n1
    r \equiv x2 mod n2, etc."""
    sum = 0
    prod = reduce(lambda a, b: a * b, n)
    for n_i, x_i in zip(n, x):
        p = prod / n_i
        sum += x_i * gmpy2.invert(p, n_i) * p
    return gmpy2.t_mod(sum, prod)
Example #13
0
 def encrypt(self, m):
     """Returns g^mh^r mod n"""
     if m >= self.pub_key.d:
         gm = 1
     elif m == 0:
         gm = self.pub_key.g
     else:
         gm = gmpy2.powmod(self.pub_key.g, self.pub_key.b ** m, self.pub_key.n)
     r = self.rs.random_bits_nz(self.pub_key.u)
     hr = gmpy2.powmod(self.pub_key.h, r, self.pub_key.n)
     return gmpy2.t_mod(gm * hr, self.pub_key.n)
Example #14
0
def step2(p, g, A):
    q = mpz(236234353446506858198510045061214171961)
    B_knows['q'] = q
    B_knows['p'] = p
    B_knows['g'] = g
    B_knows['A'] = A
    b = t_mod(mpz_random(rstate, p - 2) + 2, q)
    B = pow(g, b, p)
    B_knows['b'] = b
    B_knows['B'] = B
    B_knows['k'] = getSHA1(format(pow(A, b, p), 'x'))[0:32]
    return B
Example #15
0
 def findDiscreteLog(self):
     x = -1
     element_powB = gmpy2.powmod(mpz(self.element), mpz(self.B), mpz(self.prime))
     for x0 in range (0, self.B + 1):
         right_x0 = gmpy2.powmod(element_powB, x0, mpz(self.prime))
         if right_x0 in self.h_by_gx_hash:
              print("x0: %d" % (x0))
              x1 = self.h_by_gx_hash[right_x0]
              print("x1: %d" % (x1))
              x = gmpy2.t_mod(gmpy2.add(gmpy2.mul(x0, self.B), x1), mpz(self.prime))
              print("x: %d" % (x))
              return str(x)
     return x
Example #16
0
File: laba5.py Project: boggad/labs
def gen_keys():
    rs = gmpy2.random_state(hash(gmpy2.random_state()))
    P = gmpy2.mpz_urandomb(rs, mpz('128'))
    P = gmpy2.next_prime(P)
    Q = gmpy2.mpz_urandomb(rs, mpz('128'))
    Q = gmpy2.next_prime(Q)
    N = P*Q
    Fi = (P-1)*(Q-1)
    Pkey = gmpy2.mpz_random(rs, Fi)
    while not (gmpy2.gcd(Fi, Pkey) == 1):
        Pkey = gmpy2.mpz_random(rs, Fi)
    Skey = gmpy2.invert(Pkey, Fi)
    assert gmpy2.t_mod(Skey*Pkey,Fi) == 1
    return Pkey, Skey, N
Example #17
0
def generate(pwd, stat):
    config.generate_r()
    pwd = mpz(crypt.get_bit_str_from_byte(pwd), base=2)
    global table
    table = []  # clear the table
    for i in xrange(config.max_features):
        x_0 = crypt.p(mpz((i + 1) << 1), config.r)  # calculate x0, x1 and y0, y1
        x_1 = crypt.p(mpz(((i + 1) << 1) + 1), config.r)
        y_0 = gmpy2.add(poly.calculate(x_0), crypt.g(mpz((i + 1) << 1), config.r ^ pwd))  # use r xor pwd as the key
        y_1 = gmpy2.add(poly.calculate(x_1), crypt.g(mpz(((i + 1) << 1) + 1), config.r ^ pwd))
        if reader.if_init():
            table.append((y_0, y_1))  # if in initialization phase, add correct value
        else:
            if stat[i][0] is None:
                table.append((y_0, y_1))  # if no statistic information is derived
            elif (stat[i][1] + stat[i][0] * config.k) < config.ti:  # if fast
                rand_value = gmpy2.t_mod(config.generate_rand(), config.q)
                table.append((y_0, rand_value))
            elif (stat[i][1] - stat[i][0] * config.k) > config.ti:  # if slow
                rand_value = gmpy2.t_mod(config.generate_rand(), config.q)
                table.append((rand_value, y_1))
            else:
                table.append((y_0, y_1))
Example #18
0
def solver():
    A, b, B, u, hash = srp("")
    fp = open("passwords.txt", "r")
    passwords = fp.readlines()
    for password in passwords:
        password = password.strip()
        print "[*] Trying Password: '******'" % (password)
        x = mpz(int(generate_hash("", password), 16))
        S = t_mod(powmod(A, b, N) * powmod(B, u * x, N), N)
        K = hash_sha256(str(S))
        h = hmac(K, "", hash_function=hash_sha256)
        if h == hash:
            print "[+] Got it. Password = '******'" % (password)
    return
Example #19
0
    def decrypt(self, pk, sk, vec, ct, max_innerprod):
        p = gp.mpz(pk['p'])
        g = gp.mpz(pk['g'])

        res = gp.mpz(1)
        for i in range(len(vec)):
            res = gp.mul(
                res,
                gp.powmod(gp.mpz(ct['ct_list'][i]), gp.mpz(vec[i]), p)
            )
        res = gp.t_mod(res, p)
        g_f = gp.divm(res, gp.powmod(gp.mpz(ct['ct0']), gp.mpz(sk['sk']), p), p)

        f = self._solve_dlog(p, g, g_f, max_innerprod)

        return f
Example #20
0
def step1():
    p = mpz(
        7199773997391911030609999317773941274322764333428698921736339643928346453700085358802973900485592910475480089726140708102474957429903531369589969318716771
    )
    g = mpz(
        4565356397095740655436854503483826832136106141639563487732438195343690437606117828318042418238184896212352329118608100083187535033402010599512641674644143
    )
    q = mpz(236234353446506858198510045061214171961)
    a = t_mod(mpz_random(rstate, p - 2) + 2, q)
    A = pow(g, a, p)
    A_knows['q'] = q
    A_knows['p'] = p
    A_knows['g'] = g
    A_knows['a'] = a
    A_knows['A'] = A
    return (p, g, A)
Example #21
0
def dlog(pgh):

	p = pgh[0]
	g = pgh[1]
	h = pgh[2]

	B = gmpy2.powmod(2,20,mpz(p))
	B_low = 0
	#B_low = gmpy2.powmod(2,18,mpz(p))
	print "B: " + repr(B)

	# build the hash
	hash_table = {}
	for i in range(B_low,B):
		left = gmpy2.divm(mpz(h),gmpy2.powmod(mpz(g),i, mpz(p)),mpz(p))
		try:
			hash_table[left]
			print "collision at " + i
		except KeyError:
			hash_table[left] = i
			continue

	print "Hash table built"
	#print "keys: " + repr(hash_table.keys())

	counter = mpz(0)
	# meet in the middle
	x0 = mpz(0)
	x1 = mpz(0)
	for i in range(B_low,B):
		counter = gmpy2.add(counter,mpz(1))
		right = gmpy2.powmod(gmpy2.powmod(mpz(g),mpz(B),mpz(p)),i,mpz(p))
		try:
			h_entry = hash_table[right] 
			print 'found x0 and x1...'
			x0 = i
			x1 = h_entry
			print 'x0=' + repr(x0)
			print 'x1=' + repr(x1)
			
			break
		except KeyError:
			continue

	print "counter: " + repr(counter)
	x = gmpy2.t_mod(gmpy2.add(gmpy2.mul(x0,B),x1), mpz(p))
	return x
Example #22
0
def generate_keypair(seed: int):
    rand_state = seed
    # m = bytes_to_long(input.encode('utf-8'))

    p, q = generate_prime(bit_count,
                          rand_state), generate_prime(bit_count, rand_state)
    flag = good_pair(p, q)
    while not flag:
        p, q = generate_prime(bit_count, rand_state), generate_prime(
            bit_count, rand_state)
        flag = good_pair(p, q)

    n = gmpy2.mul(p, q)
    phi = gmpy2.mul(p - 1, q - 1)

    # print("p:", p)
    # print("q:", q)
    print("n:", n)
    # print("phi:", phi)

    e = gmpy2.mpz_random(rand_state, phi)
    while e <= 1 or gmpy2.gcd(e, phi) != 1:
        e = gmpy2.mpz_random(rand_state, phi)

    assert (e > 1)
    assert (gmpy2.gcd(e, phi) == 1)

    d = gmpy2.invert(e, phi)
    assert (d != 1)
    assert (gmpy2.t_mod(e * d, phi) == 1)

    # print("PK(e):", e)
    # print("SK(d):", d)

    return {
        'public': {
            'n': n,
            'e': e,
        },
        'private': {
            'n': n,
            'd': d,
        }
    }
Example #23
0
def deductPlaintext(c, e, d, N):
    plaintext = ""
    lowP = 0
    highP = N - 1
    k = pow(2, e, N)
    i = 0
    while True:
        c = t_mod((c * k), N)
        p = parityOracle(c, d, N)
        if p == True:
            lowP += (highP - lowP) / 2
        else:
            highP -= (highP - lowP + 1) / 2

        if lowP == highP or lowP + 1 == highP:
            print "[+] Found Plaintext."
            plaintexts = (i2h(lowP).decode("hex"), i2h(lowP + 1).decode("hex"))
            break
    return plaintexts
Example #24
0
def test_q7():
    print('Q7: ==========================')
    n = 17499773465348445792920245778216829006647453385259330219357028485009339534285848901056303646954491391679683201149457475018294979209780247445076066287733118072880749833035123036555662856645475638596385628573834790984467990658723961995703366235550395489042651541156795624703520341275891175096132549861970720533717778174765607441287991306500525167730683267118223430735800481287357200910002893229017814289348689888719981191560197481039522195361217272138225955508782933789348420624935802805864879225862644583960675404149266618669091214585922332101569324163212845768114082503107114837675455651614832959907134061262517385017
    e = 3
    c = 321654389616150513356556055740961926749898434643413371203975850424205544792983180728606431035587667962369136768769365708509839867803424784777024270115037479965629722196457158071998101133765058618875866760958071264023592635126229531

    # The trick here is that e is so small you can just
    # get the (cubic root of c) % n  to get m
    gc = gmpy2.mpz(c)
    gn = gmpy2.mpz(n)
    ge = gmpy2.mpz(e)

    root, _ = gmpy2.iroot(gc, ge)
    m = gmpy2.t_mod(root, gn)

    assert (
        m ==
        68516708916360312322912544295994397317545815174959984970505961156625792081411
    )
Example #25
0
 def rerandomize(self, c):
     return gmpy2.t_mod(c * self.encrypt(0), self.pub_key.n)
Example #26
0
print "p_max= "
print p_max.digits(10)

# calculate p_min
p_min = proot(1, dist, -(n - 1))

print "p_min= "
print p_min.digits(10)

# start finding prime
if gmpy2.is_prime(p_min):
    p = p_min
else:
    p = gmpy2.next_prime(p_min)

# loop through prime numbers from p_min to p_max
while p < p_max:
    # get remainder of div(n, p)
    rem = gmpy2.t_mod(n, p)

    if rem == 0:
        print "\nresult= "
        print "p= "
        print p.digits(10)
        print "q= "
        print gmpy2.c_div(n, p)
        sys.exit()

    p = gmpy2.next_prime(p)
Example #27
0
def add_encrypted(a, b, pubkey):
    return gmpy2.t_mod(gmpy2.mul(a, b), pubkey.n)
Example #28
0
def p(x, key):
    if not config.simple:
        mac = HMAC.new(key=get_byte_str_from_mpz(key), msg=get_byte_str_from_mpz(x), digestmod=SHA).digest()
        return gmpy2.t_mod(mpz(get_bit_str_from_byte(mac), base=2), config.q)
    return x  # if in simple mode, return x
B = mpz(2)**20

#p = mpz(104869)
#g = mpz(103221)
#h = mpz(82257)
### x = 52
#B = mpz(2)**3

dict = {}
i = mpz(0)
g_inv = gmpy2.invert(g, p)
tmp = h

while i < B:
    dict[tmp] = i
    tmp = gmpy2.t_mod(gmpy2.mul(tmp, g_inv), p)
    i += 1

print("done with dictionary")
i = mpz(0)
gb = gmpy2.powmod(g, B, p)
tmp = mpz(1)

while i < B:
    if tmp in dict:
        print("x=", i * B + dict[tmp])
        break
    tmp = gmpy2.t_mod(gmpy2.mul(tmp, gb), p)
    i += 1

print("done")
Example #30
0
B = gmpy2.powmod(mpz('2'), mpz('20'), p)
step = B / 100
i = 0

gB = gmpy2.powmod(g, B, p)

left_side = {}

print 'Building hash table...'
for x1 in xrange(0, B):
    if x1 > step * i:
        print '%s%%' % i
        i += 1

    gx1 = gmpy2.powmod(g, x1, p)
    val = gmpy2.t_mod(gmpy2.mul(h, gmpy2.invert(gx1, p)), p)
    left_side[val] = x1

print 'Performing lookup...'
for x0 in xrange(0, B):
    gBx0 = gmpy2.powmod(gB, x0, p)
    if gBx0 in left_side:
        x1 = left_side[gBx0]
        x = x0 * B + x1
        h_guess = gmpy2.powmod(g, x, p)

        print 'x0 = %s, x1 = %s\nx = %s' % (x0, x1, x)
        print 'Guess is', h_guess == h
        break
Example #31
0
p = gmpy2.mpz('13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171')
h = gmpy2.mpz('3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333')
g = gmpy2.mpz('11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568')

B = 2**20

#buidling the table
tbl = {}
x1 = 0
x0 = 0

for i in range(0, B):
	tmp = gmpy2.powmod(g, i, p)	#get g^x1
	tmp = gmpy2.invert(tmp, p)	#get (g^x1)^-1
	tmp = gmpy2.t_mod(gmpy2.mul(h, tmp), p)
	
	hash = MD4.new(gmpy2.digits(tmp))
	tbl[hash.hexdigest()] = i
	
#start bruteforcing
for i in range(0, B):
	tmp = gmpy2.powmod(g, gmpy2.mul(B, i), p)
	hash = MD4.new(gmpy2.digits(tmp))
	
	if hash.hexdigest() in tbl:
		x1 = tbl[hash.hexdigest()]
		x0 = i
		break
		
res = (x0*B) + x1
Example #32
0
def calculate(x):
    ans = mpz()
    for c_i in c[::-1]:
        ans = gmpy2.t_mod(gmpy2.add(gmpy2.mul(ans, x), c_i), config.q)
    return ans
Example #33
0
from gmpy2 import mpz
import random
#bit_count = 64
rand_state = gmpy2.random_state()
p = int(input("Enter p:"))
q = int(input("Enter q:"))
m = int(input("Enter m:"))
#k1=int(input())
k1 = q - 1
n2 = p - 1
l = []
w = 1
rand_state = gmpy2.random_state(42)
n1 = gmpy2.mul(p, q)  #number(n)
p1 = gmpy2.mul(k1, n2)  #numberphi
e = gmpy2.next_prime(q)
if gmpy2.gcd(e, p1) == 1:
    d = gmpy2.invert(e, p1)
    #print("d:",d)
    if gmpy2.t_mod(e * d, p1) == w:
        m1 = mpz(m)
        c = gmpy2.powmod(m1, e, n1)
        m2 = gmpy2.powmod(c, d, n1)
        print(c)
        print(e)
        print(d)
        print(n1)

#with open("copy.txt", "w") as file:
#file.write(str(q))
Example #34
0
        f.write("\nm = " + m.digits(10))
        f.write("\nj(right) = " + str(j))
        f.write("\ni(left) = " + str(iCurr))
        f.write("\nanswer = " + ansEx.digits(10))
        f.write("\ncheck g = " + answer.digits(10))
        f.close()

        fi = open("iCurr.txt", "w")
        fi.write(iCurr.digits(10))
        fi.close()

        fv = open("iValue.txt", "a")
        fv.write(iCurr.digits(10) + "\n")
        fv.close()
        sys.exit()
    left = gmpy2.t_mod(gmpy2.mul(left, g), p)
    iCurr += 1

    # pi = gmpy2.c_div(iCurr, 10000000000)
    # print "\r" + pi.digits(10) + " %",
fi = open("iCurr.txt", "w")
fi.write(iCurr.digits(10))
fi.close()

fv = open("iValue.txt", "a")
fv.write(iCurr.digits(10) + "\n")
fv.close()

# leftArray = []
# leftArray.append(-1)
Example #35
0
def generate_poly():
    global c
    c = [config.h_pwd]   # first coefficient is the hardened password
    for i in xrange(config.max_features - 1):
        tmp = config.generate_rand()
        c.append(gmpy2.t_mod(tmp, config.q))
Example #36
0
p=13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171
g=11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568
h=3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333

import math  # Use sqrt, floor
import gmpy2
from gmpy2 import powmod, t_mod

hash_table1 = set()
hash_table2 = set()
b = 2**20

for i in range(b):
	abc = t_mod(powmod(g,-1* i,p)*h,p)
	hash_table1.add(abc)
	if abc == 1514665690755317733976062484822790443518716440821123165374346884821466258735252188334799940590055744229602814470651184433499215002319025125450377832374754 :
		print "x1 = ", i

print "1111111111111"
temp = powmod(g,b,p)
print "temp = ", temp

for i in range(b):
	abc = powmod(temp,i,p)
	hash_table2.add(abc)
	if abc == 1514665690755317733976062484822790443518716440821123165374346884821466258735252188334799940590055744229602814470651184433499215002319025125450377832374754 :
		print "x0 = ", i
	
print hash_table1.intersection(hash_table2)

Example #37
0
import gmpy2
from gmpy2 import mpz

x = mpz('1000000000000000000020000000')
p = mpz('1000000000000000000001000000')

while p < 1000000000000000000010000000:
    if gmpy2.is_prime(p):
        y = gmpy2.t_mod(x, p)

    p = gmpy2.next_prime(p)
Example #38
0
from gmpy2 import mpz

p = mpz('13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171')

g = mpz('11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568')

h = mpz('3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333');

end = (1<<20)

table = {}
print('Populating table...')
for x1 in range(0, end):
    print(x1 * 100 // end, end="%\r")
    gx1 = gmpy2.powmod(g, x1, p)
    gx1_invert = gmpy2.invert(gx1, p)
    value = gmpy2.t_mod(gmpy2.mul(h, gx1_invert), p)
    table[value] = x1

print('Finding x0...')
for x0 in range(0, end):
    print(x0 * 100 // end, end='%\r')
    gb = gmpy2.powmod(g, end, p)
    gbx0 = gmpy2.powmod(gb, x0, p)
    if gbx0 in table:
        x1 = table[gbx0]
        x = gmpy2.t_mod(gmpy2.add(x1, gmpy2.mul(x0, end)), p)
        print("x={0}".format(str(x)))
        break

Example #39
0
# set up left hand side of comparison
i = 0
leftArray = []

# get iCurr
fi = open('iCurr.txt', 'r')

iCurr = mpz(fi.readline())
fi.close()

# calculate first item
leftArray.append(gmpy2.powmod(g, iCurr, p))
i += 1

while i < m and i < maxList:
    leftArray.append(gmpy2.t_mod(gmpy2.mul(leftArray[i - 1], g), p))
    i += 1

# leftArray = []
# leftArray.append(-1)

# right hand side loop
# j = 0
j = 0

i = 0
for left in leftArray:
    if y == left:
        ansEx = gmpy2.mul(m, j) + i
        answer = gmpy2.powmod(g, ansEx, p)
Example #40
0
def generate_h_pwd():
    assert q, "prime not initialized!"
    global h_pwd
    h_pwd = gmpy2.t_mod(generate_rand(), q)
Example #41
0
def findfactor(x, bitlength):
    factor = []
    for i in xrange(2, 2**bitlength):
        if t_mod(x, i) == 0:
            factor.append(i)
    return factor
Example #42
0
def mod(x, m):
    remainder = gmpy2.t_mod(gmpy2.mpz(x), gmpy2.mpz(m))
    # gmpy2.t_mod can return negative values, but we want positive ones.
    if remainder < 0:
        remainder = gmpy2.add(remainder, m)
    return remainder
B = mpz(2)**20

#p = mpz(104869)
#g = mpz(103221)
#h = mpz(82257)
### x = 52
#B = mpz(2)**3

dict = {}
i = mpz(0)
g_inv = gmpy2.invert(g,p)
tmp = h

while i < B:
  dict[tmp] = i
  tmp = gmpy2.t_mod(gmpy2.mul(tmp,g_inv),p)
  i+=1

print("done with dictionary")
i = mpz(0)
gb = gmpy2.powmod(g,B,p)
tmp = mpz(1)

while i < B:
  if tmp in dict:
    print("x=",i*B + dict[tmp])
    break
  tmp = gmpy2.t_mod(gmpy2.mul(tmp,gb),p)
  i+=1

print("done")
Example #44
0
def findprimefactor(numtofactor):
    for primenum in primelist2M.primelist:
        if (gmpy2.t_mod(numtofactor, primenum) == 0):
            return (primenum)
    return (0)
Example #45
0
g = mpz(
    '11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568'
)
h = mpz(
    '3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333'
)

B = 2**20

print("Building table")
hash_table = defaultdict(list)
# build table
for x1 in range(0, B + 1):
    ginv = powmod(g, -x1, p)
    mult = mul(h, ginv)
    left_side = t_mod(mult, p)
    hashvalue = hash(left_side)

    hash_table[hashvalue] += [(left_side, x1)]

print("Table built")

g_pow_B = powmod(g, B, p)
for x0 in range(0, B + 1):
    right_side = powmod(g_pow_B, x0, p)
    hashvalue = hash(right_side)

    if (hashvalue in hash_table):
        for (left_side, x1) in hash_table[hashvalue]:
            if (left_side == right_side):
                print("Found value")
Example #46
0
from gmpy2 import mpz


P = mpz(13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171)
G = mpz(11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568)
H = mpz(3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333)


if __name__ == '__main__':
    print('hello')

    table = dict()
    low, high = 0, 2 ** 20
    B = high

    # 1. populate table with values of the left part of equation
    for x1 in range(low, high + 1):
        left = gmpy2.t_mod(gmpy2.mul(H, gmpy2.invert(gmpy2.powmod(G, x1, P), P)), P)
        table[left] = x1
    print('step 1 done')

    # 2. check each value of the right part of equation
    for x0 in range(low, high + 1):
        right = gmpy2.powmod(gmpy2.powmod(G, B, P), x0, P)
        if right in table:
            x1 = table[right]
            x = x0 * B + x1
            print('solution: {0}'.format(x))
    print('step 2 done')
    print('done')
Example #47
0
import gmpy2, time
from gmpy2 import mpz



p = mpz(13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171)
g = mpz(11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568)
h = mpz(3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333)
B = mpz(2**20)

gB = pow(g,B,p)
x0, x1 = 0, 0
d = {}

i = 2**19

start1 = time.clock()
tmp = gmpy2.invert(pow(g,i,p), p)
elapsed1 = (time.clock() - start1)

start2 = time.clock()
d[gmpy2.t_mod(gmpy2.mul(h,tmp),p)] = i
elapsed2 = (time.clock() - start2)

start3 = time.clock()
d[gmpy2.divm(h, pow(g,i,p), p)] = i
elapsed3 = (time.clock() - start2)

print(elapsed1, elapsed2, elapsed3)
Example #48
0
	m += 1

# Inverse of m
invgm = gmpy2.powmod(g, -m, p)

# to track progress
pj = mpz('0')
# pi = mpz('0')

# right hand side loop
j = 0

# Loop through right hand side
while j < m:
	if j == 0:
		rightpow = gmpy2.t_mod(gmpy2.mul(1, y), p)
		right = rightpow
	elif j == 1:
		base = invgm
		rightpow = invgm
		right = gmpy2.t_mod(gmpy2.mul(base, y), p)
	else:
		rightpow = gmpy2.t_mod(gmpy2.mul(rightpow, base), p)
		right = gmpy2.t_mod(gmpy2.mul(rightpow, y), p)

	# set up left hand side for comparison
	i = 0
	while i < m: 
		if i == 0:
			left = 1
		elif i == 1:
Example #49
0
    m += 1

# Inverse of m
invgm = gmpy2.powmod(g, -m, p)

# to track progress
pj = mpz('0')
# pi = mpz('0')

# right hand side loop
j = 0

# Loop through right hand side
while j < m:
    if j == 0:
        rightpow = gmpy2.t_mod(gmpy2.mul(1, y), p)
        right = rightpow
    elif j == 1:
        base = invgm
        rightpow = invgm
        right = gmpy2.t_mod(gmpy2.mul(base, y), p)
    else:
        rightpow = gmpy2.t_mod(gmpy2.mul(rightpow, base), p)
        right = gmpy2.t_mod(gmpy2.mul(rightpow, y), p)

    # set up left hand side for comparison
    i = 0
    while i < m:
        if i == 0:
            left = 1
        elif i == 1:
Example #50
0
 def partialkey_compute(self, User):
     r_u, User.Y_u = random_pick(self.p, self.q, self.g)
     User.y_u = t_mod((r_u + t_mod(
         self.s * H1_hash(User.uid, User.X_u, User.Y_u, bit_length(self.q)),
         self.q)), self.q)
Example #51
0
import gmpy2
from gmpy2 import mpz

x = mpz('1000000000000000000020000000')
p = mpz('1000000000000000000001000000')

while p < 1000000000000000000010000000:
	if gmpy2.is_prime(p):
		y = gmpy2.t_mod(x, p)

	p = gmpy2.next_prime(p)
Example #52
0
    indexY = random.randint(0, MAX_N - 1)
    X = arr[indexX]
    Y = arr[indexY]
    ans = gmpy2.add(X, Y)
    addition_content += generate_exp(indexX, indexY, '+')
    addition_content += generate_equal(ans)
    ans = gmpy2.sub(X, Y)
    subtraction_content += generate_exp(indexX, indexY, '-')
    subtraction_content += generate_equal(ans)
    ans = gmpy2.mul(X, Y)
    multiple_content += generate_exp(indexX, indexY, '*')
    multiple_content += generate_equal(ans)
    ans = gmpy2.t_div(X, Y)
    division_content += generate_exp(indexX, indexY, '/')
    division_content += generate_equal(ans)
    ans = gmpy2.t_mod(X, Y)
    division_content += generate_exp(indexX, indexY, '%')
    division_content += generate_equal(ans)


def write_longer(test_case_name, file_name, content):
    test_case = generate_test_case(test_case_name, 'Longer',
                                   init_content + content)
    output = open(file_name, 'w')
    output.write(generate_header())
    output.write(test_case)
    output.close()


write_longer('Addition', 'addition_longer.h', addition_content)
write_longer('Subtraction', 'subtraction_longer.h', subtraction_content)
Example #53
0
G = mpz(
    11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568
)
H = mpz(
    3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333
)

if __name__ == '__main__':
    print('hello')

    table = dict()
    low, high = 0, 2**20
    B = high

    # 1. populate table with values of the left part of equation
    for x1 in range(low, high + 1):
        left = gmpy2.t_mod(
            gmpy2.mul(H, gmpy2.invert(gmpy2.powmod(G, x1, P), P)), P)
        table[left] = x1
    print('step 1 done')

    # 2. check each value of the right part of equation
    for x0 in range(low, high + 1):
        right = gmpy2.powmod(gmpy2.powmod(G, B, P), x0, P)
        if right in table:
            x1 = table[right]
            x = x0 * B + x1
            print('solution: {0}'.format(x))
    print('step 2 done')
    print('done')
Example #54
0
# set up left hand side of comparison
i = 0
leftArray = []

# get iCurr
fi = open('iCurr.txt', 'r')

iCurr = mpz(fi.readline())
fi.close()

# calculate first item 
leftArray.append(gmpy2.powmod(g, iCurr, p))
i += 1

while i < m and i < maxList:
	leftArray.append(gmpy2.t_mod(gmpy2.mul(leftArray[i - 1], g), p))
	i += 1;

# leftArray = []
# leftArray.append(-1)

# right hand side loop
# j = 0
j = 0

i = 0
for left in leftArray:
	if y == left:
		ansEx = gmpy2.mul(m, j) + i
		answer = gmpy2.powmod(g, ansEx, p)
Example #55
0


p = mpz(13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171)
g = mpz(11717829880366207009516117596335367088558084999998952205599979459063929499736583746670572176471460312928594829675428279466566527115212748467589894601965568)
h = mpz(3239475104050450443565264378728065788649097520952449527834792452971981976143292558073856937958553180532878928001494706097394108577585732452307673444020333)
B = mpz(2**20)

gB = powmod(g,B,p)
g_inv = gmpy2.invert(powmod(g,1,p), p)
x0, x1 = 0, 0
d = {}

start1 = time.clock()
for i in range(B):
    tmp = t_mod(mul(h ,powmod(g_inv,i,p)), p)
    d[tmp] = i
##    d[gmpy2.divm(h, pow(g,i,p), p)] = i

elapsed1 = (time.clock() - start1)


test = 0

start2 = time.clock()
for i in range(B):
    test = powmod(gB, i, p)

    # search in hash table
    if test in d:
        x0, x1 = i, d[test]
Example #56
0
def T_compute(x, y, p_pub, h1_b, w, p):
    T_temp = t_mod(x * y * powmod(p_pub, h1_b, p), p)
    T_value = powmod(T_temp, w, p)
    return T_value
Example #57
0
signal.signal(signal.SIGINT, signal_handler)

n = mpz('179769313486231590772930519078902473361797697894230657273430081157732675805505620686985379449212982959585501387537164015710139858647833778606925583497541085196591615128057575940752635007475935288710823649949940771895617054361149474865046711015101563940680527540071584560878577663743040086340742855278549092581')
# n = mpz('2129754913199')

# get p value
fi = open('pCurr2.txt', 'r')
p = mpz(fi.readline())
fi.close()

print p.digits(10)

# loop for prime
while p < 15000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000:
	# get remainder of div(n, p)
	rem = gmpy2.t_mod(n, p)

	if rem == 0:
		q = gmpy2.c_div(n, p)
		f = open('pResult.txt', 'a')
		f.write("p = " + p.digits(10) + "\n")
		f.write("q = " + q.digits(10) + "\n")
		f.write("n = " + n.digits(10) + "\n")
		f.close()

		fi = open('pCurr2.txt', 'w')
		fi.write(p.digits(10))
		fi.close()

		fv = open('pValue2.txt', 'a')
		fv.write(p.digits(10) + "\n")
Example #58
0
 def buildHash_h_by_gx(self):
     for x1 in range (0, self.B + 1):
         expo_gx1 = gmpy2.powmod(mpz(self.element), x1, mpz(self.prime))
         inv_gx1 = gmpy2.invert(mpz(expo_gx1), mpz(self.prime))
         left_x1 = gmpy2.t_mod(gmpy2.mul(mpz(self.exponent), inv_gx1), mpz(self.prime))
         self.h_by_gx_hash[left_x1] = x1