Esempio n. 1
0
 def __init__(self, x=0, y=None):
     self.z = 1
     if x == 0:
         self.x, self.y = 0, 0
     elif x is None:
         while True:
             self.x = random.randint(0, P)
             if gmpy2.jacobi((self.x**3 + A * (self.x**2) + self.x) *
                             gmpy2.invert(B, P), P) == 1:
                 self.y = int(
                     sqrt1((self.x**3 + A * (self.x**2) + self.x) *
                           gmpy2.invert(B, P), P)) % P
                 break
     else:
         self.x = x % P
         if gmpy2.jacobi(
             (self.x**3 + A *
              (self.x**2) + self.x) * gmpy2.invert(B, P), P) != 1:
             print("Bad x coordinates:", self.x)
             exit(0)
         if y is None:
             self.y = None
         else:
             self.y = y
             tmp1 = (B * self.y**2) % P
             tmp2 = (self.x**3 + A * (self.x**2) + self.x) % P
             if tmp1 != tmp2:
                 print("Bad y coordinates:", y)
                 exit(0)
Esempio n. 2
0
def test_pkg_extract():
    cocks_pkg = CocksPKG()
    _, a = cocks_pkg.extract("test")
    assert gmpy2.jacobi(a, cocks_pkg.n) == 1
    _, a = cocks_pkg.extract("012345678938")
    assert gmpy2.jacobi(a, cocks_pkg.n) == 1
    _, a = cocks_pkg.extract("this is a longer user identity string")
    assert gmpy2.jacobi(a, cocks_pkg.n) == 1
    _, a = cocks_pkg.extract("111111111111111111111111111111111111111111111111")
    assert gmpy2.jacobi(a, cocks_pkg.n) == 1
    pytest.raises(InvalidIdentityString, cocks_pkg.extract, "")
Esempio n. 3
0
def generate_montgomery_curve():
    while True:
        b = 1  # random.randint(2, P)
        if gmpy2.jacobi(b, P) != 1:
            continue

        x = random.randint(2, P)
        a = random.randint(2, P)
        if b * (a ** 2 - 4) == 0 \
                or a == 2 \
                or a == P - 2 \
                or gmpy2.jacobi((x ** 3 + a * (x ** 2) + x) * gmpy2.invert(b, P), P) != 1:
            continue
        y = sqrt1((x**3 + a * (x**2) + x) * gmpy2.invert(b, P), P)
        return a, b, x, int(y)
    def biprimality_check(self):
        ggt = self.gen_coprime(self.N)
        while gmpy2.jacobi(ggt, self.N) != 1:
            ggt = self.gen_coprime(self.N)
        self.gg = ggt
        self.send_data(self.gg, 2)
        self.send_data(11112222, 2)
        self.send_data(self.gg, 3)
        self.send_data(11113333, 3)
        self.Q = gmpy2.powmod(self.gg,
                              gmpy2.f_div((self.N + 1 - self.pi - self.qi), 4),
                              self.N)

        self.send_data(self.Q, 2)
        self.send_data(11112222, 2)
        self.send_data(self.Q, 3)
        self.send_data(11113333, 3)
        while True:
            if self.flag_send_1_to_3.value == 0:
                break
        Q_list = self.receive_Q_list()
        # print("Q_list = ", Q_list)
        # print("Q_list = ", Q_list)

        Q1 = Q_list[0]
        Q2 = Q_list[1]
        Q3 = Q_list[2]
        Q2_inv = gmpy2.invert(Q2, self.N)
        Q3_inv = gmpy2.invert(Q3, self.N)

        check_data = gmpy2.f_mod((Q1 * Q2_inv * Q3_inv), self.N)
        if check_data == gmpy2.f_mod(
                mpz(1), self.N) or check_data == gmpy2.f_mod(mpz(-1), self.N):
            return True
        return False
Esempio n. 5
0
def generate_montgomery_curve_from_weierstrass(wa, wb, wx, wy, p):
    from sympy.polys.domains import ZZ
    import sympy
    from sympy.polys.galoistools import gf_factor
    f = [1, 0, wa, wb]
    sympy.Poly.from_list(f, sympy.Symbol('x'))
    factor = gf_factor(f, p, ZZ)
    x = None
    for r in factor:  # f*****g sympy
        if isinstance(r, list):
            for root in r:
                if len(root) == 2 \
                        and len(root[0]) == 2 \
                        and gmpy2.jacobi(3 * ((p - root[0][-1]) ** 2) + wa, p) == 1:
                    x = p - root[0][-1]
                    break

    assert x is not None

    s = sqrt1(gmpy2.invert(3 * x**2 + wa, p), p)
    mb = s
    ma = (3 * x * s) % p
    mx = (s * (wx - x)) % p
    my = (s * wy) % p
    return (ma, p - ma), (mb, p - mb), (mx, p - mx), (my, p - my)
Esempio n. 6
0
def test_gen_keys(iters = 1):
    print "test_gen_keys:"
    for i in range(iters):
        keys = generate_keys()
            
        n = keys['pub']
        p, q = keys['priv']
            
        assert(jacobi(n-1, n) == 1)
    print "test_gen_keys pass"
Esempio n. 7
0
def decrypt_gm(cipher_numbers, priv_key):
    p, q = priv_key
    n = p * q
    
    sk_gm = (p-1)*(q-1) / 4
    
    for c in cipher_numbers:
        if c >= n or jacobi(c, n) != 1:
            # rejct
            return None
                    
    bits_str = ''.join([decrypt_bit_gm(c, sk_gm, n) for c in cipher_numbers])
    return int(bits_str, 2)
Esempio n. 8
0
    def _encrypt_bit(self, m_bit, a):
        """
        Encrypts an individual message bit.

        Inputs:
        m_bit : Message bit in {-1,1}
        a : Hashed identity value

        Output:
        (c1, c2) : Ciphertext tuple
        """
        t1 = t2 = gmpy2.mpz_random(random_state, self.n)

        while gmpy2.jacobi(t1, self.n) != m_bit:
            t1 = gmpy2.mpz_random(random_state, self.n)

        while gmpy2.jacobi(t2, self.n) != m_bit or t1 == t2:
            t2 = gmpy2.mpz_random(random_state, self.n)

        c1 = (t1 + a * gmpy2.invert(t1, self.n)) % self.n
        c2 = (t2 - a * gmpy2.invert(t2, self.n)) % self.n
        return (c1, c2)
Esempio n. 9
0
 def receive_gg(self):
     q31_list = []
     while True:
         while not self.q31.empty():
             q31_list.append(mpz(self.q31.get()))
             if q31_list:
                 if q31_list[-1] == 11113333:
                     break
         if q31_list:
             if q31_list[-1] == 11113333:
                 break
     ggt = q31_list[0]
     if gmpy2.jacobi(ggt, self.N) == 1:
         self.gg = ggt
     else:
         raise Exception("gg generation Error!")
Esempio n. 10
0
    def _decrypt_bit(self, c1, c2, r, a):
        """
        Decrypts an individual message bit from a ciphertext tuple,
        given the user's private key and their hashed ID value.

        Inputs:
        (c1, c2) : Ciphertext tuple
        r : User's secret key
        a : Hashed identity value

        Output:
        (x|n) : Decrypted message bit in {-1,1}
        """

        r2 = (r * r) % self.n
        x = c1 + 2 * r if r2 == a else c2 + 2 * r
        return gmpy2.jacobi(x, self.n)
Esempio n. 11
0
 def kronecker(x, y):
     """Return the Kronecker symbol (x|y)."""
     k = 1
     if y == 0:
         if abs(x) != 1:
             k = 0
         y = 1
     if y < 0:
         if x < 0:
             k = -k
         y = -y
     if y & 1 == 0:
         t = (y & -y).bit_length() - 1
         if x & 1 == 0:
             k = 0
         elif t & 1 and (x & 7 == 3 or x & 7 == 5):
             k = -k
         y = y >> t
     return k * jacobi(x, y)
Esempio n. 12
0
def IsMember(x, secparams):
    """
    Algorithm 7.2: Checks if x is an element of G_q.
    The core of the algorithm is the computation of the Jacobi symbol for which we refer to existing algorithms

    Args:
       x (mpz):                             The number to test x \in N
       secparams (SecurityParams):          Collection of public security parameters

    Returns:
       bool:                                True if x is a member of G_q, False if not
    """

    AssertNumeric(x)
    AssertClass(secparams, SecurityParams)

    if 1 <= x and x < secparams.p:
        return jacobi(x, secparams.p) == 1

    return False
Esempio n. 13
0
def IsMemberOfGroupe(x, param):
    """
    Algorithm 7.2 extended: Checks if x is in the same groupe as param .
    The core of the algorithm is the computation of the Jacobi symbol for which we refer to existing algorithms

    Args:
       x (mpz):                             The number to test x \in N
       param (Element of SecurityParams):   Element of Collection of public security parameters

    Returns:
       bool:                                True if x is in the same groupe as param, False if not
    """

    AssertNumeric(x)
    AssertNumeric(param)

    if 1 <= x and x < param:
        return jacobi(x, param) == 1

    return False
 def is_prime(n, k=4):
     if not n & 1:
         return False
     var = []
     for _ in range(k):
         a = random.randint(1, n-1)
         while a in var:
             a = random.randint(1, n-1)
         var.append(a)
         if math.gcd(a, n) != 1:
             return False
         r = powmod(a, (n - 1) // 2, n)
         if r != 1 and r != n-1:
             return False
         s=jacobi(a, n)
         if s < 0:
             s += n
         if r != s:
             return False
     return True
Esempio n. 15
0
    def extract(self, id_str):
        """
        Extracts a user's private key from their identity string.

        If necessary, the ID string, a, is hashed iteratively until (a|n)==1.
        
        Input:
        id_str : Identity string
        
        Output:
        r : User's secret key
        a : Hashed identity value such that (a | n) == 1
        """
        if id_str == "" or id_str == None:
            raise InvalidIdentityString("Invalid user identity string")

        id_mpz = str_to_mpz(id_str)
        a = hash_mpz(id_mpz, self.f)
        a_tmp = 0

        while gmpy2.jacobi(a_tmp, self.n) != 1:
            a_tmp = hash_mpz(a_tmp, self.f)
        a = a_tmp

        logging.debug(f"Jacobi (a/n) = {gmpy2.jacobi(a, self.n)}")
        logging.debug(f"Jacobi (-a/n) = {gmpy2.jacobi(-a, self.n)}")

        r = pow(a, (self.n + 5 - (self.p + self.q)) // 8, self.n)
        r2 = (r * r) % self.n

        logging.debug(f"a = {a % self.n}")
        logging.debug(f"-a = {-a %self.n}")
        logging.debug(f"r = {r}")
        logging.debug(f"r**2 = {r2}")

        if r2 != (a % self.n) and r2 != (-a % self.n):
            raise ExtractFailure(
                "Error deriving r: r^2 != a (mod n) and r^2 != -a (mod n)!")
        return (r, a)
 def receive_gg(self):
     ggt = 0
     if gmpy2.jacobi(ggt, self.N) == 1:
         self.gg = ggt
     else:
         raise Exception("gg generation Error!")
Esempio n. 17
0
N = 9931755185060178541819350703860525202998395176620817326533726321103289514714482398301463938123540046323657927466230539048399765245482297315320621294942552040969779600220746703802727865488282400532525716200713822333260195215975219729008945628323420484667363474732308988705045216466104088114390575938974751250735732965167191025807650844438927688743083443181909932562840801876087928020419912615909929547090716236393628363582762357491323519758592285176474021090624649128022651674058738105123425788673915904447407748389441605828693561972112169848435886546096942841894411370737399277884692796708444598630421441967316945299
e = 0x10001
f = open('enc.txt')
cipher = f.readlines()

jacob = [0 for i in range(128)]
given = 'KOREA{WOW!!_You_'
given = bin(bytes_to_long(given))[2:].rjust(128, '0')

cipher.append('0')
for i in range(128):
    t = given[(i - 128) % 128]
    if (i % 8 == 0):
        jacob[127 - i] = 0
    elif (t == '0'):
        jacob[127 - i] = gmpy2.jacobi(int(cipher[((i + 1) * -1)]), N) * 1
    else:
        jacob[127 - i] = gmpy2.jacobi(int(cipher[(i + 1) * -1]), N) * -1

mes = ''

check = 8
for i in range(0, len(cipher)):
    if (i % 8 == 7):
        mes = '0' + mes
        check += 1
        continue
    jacobi = gmpy2.jacobi(int(cipher[i]), N) * jacob[check % 128]
    check += 1
    if (jacobi == 1):
        mes = '0' + mes
Esempio n. 18
0
def legendre(x):
    return gmpy2.jacobi(x, MODULUS)
Esempio n. 19
0
from pwn import *
from gmpy2 import jacobi
while (1):
    r = remote('crypto.ctf.zer0pts.com', 10463)
    r.recvuntil('g: ')
    g = int(r.recvuntil(',')[:-1])
    r.recvuntil('p: ')
    p = int(r.recvline()[:-1])

    li = [jacobi(1, p), jacobi(2, p), jacobi(3, p)]
    val = 0
    win = 0
    if li != [1, -1, -1] or jacobi(g, p) != 1:
        print("ERROR")
        continue

    else:
        while (1):
            r.recvuntil(' my commitment is=(')
            a = int(r.recvuntil(',')[:-1])
            b = int(r.recvuntil(')')[:-1])
            a1 = jacobi(a, p)
            b1 = jacobi(b, p)
            if a1 == b1:

                r.sendline('3')
            else:
                r.sendline('2')
            r.recvline()
            r.recvline()
            r.recvline()
Esempio n. 20
0
def jacobi_bit_mpz(a, n):
    global legendre_evals
    legendre_evals += 1
    return (gmpy2.jacobi(a, n) + 1) // 2
Esempio n. 21
0
def get_factor_base(n, B=4):
  # note that gmpy2.is_prime is *probabilistic*
  primes = [p for p in range(3,50) if gmpy2.is_prime(p)]
  fac_base = [2] + [p for p in primes if gmpy2.jacobi(p,n) == 1]
  return fac_base[:B]
Esempio n. 22
0
def jacobi_bit_mpz(a, n):
    return 1 if jacobi(a, n) >= 0 else 0
Esempio n. 23
0
 def legendre(x, y):
     """Return the Legendre symbol (x|y), assuming y is an odd prime."""
     return jacobi(x, y)  # ignore if y is not prime, like gmpy2 does
Esempio n. 24
0
from Crypto.Util.number import long_to_bytes
import gmpy2
plaintext = ''
with open('output.txt') as f:
    n = int(f.readline())
    for line in f:
        cipher = int(line)
        if gmpy2.jacobi(cipher, n) == -1:
            plaintext += '1'
        else:
            plaintext += '0'
print(long_to_bytes(int(plaintext, 2)))
Esempio n. 25
0
def quad_residue(c, priv_key):
    p, q = priv_key
    n = p * q
    sk_gm = (p-1)*(q-1) / 4
    return jacobi(c, n) == 1 and powmod(c, sk_gm, n) == 1
Esempio n. 26
0
def get_rand_Jn1(n, rand_gen=random):
    r = rand_gen.randint(0, int(n-1))
    while jacobi(r, n) != 1:
        r = rand_gen.randint(0, int(n-1))
    return r 
def jacobi_bit_mpz(a, n):
    return (gmpy2.jacobi(a, n) + 1) // 2
Esempio n. 28
0
def legendre_bit_mpz(a, n):
    return True if gmpy2.jacobi(a, n) >= 0 else False