Ejemplo n.º 1
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-m', type=int, default=1)
    args = parser.parse_args(sys.argv[1:])
    with open('file_to_signature.txt') as f:
        file = json.load(f)

    m = open(file['file'], 'rb').read()

    if args.m == 1:  # публичные параметры
        len_p = read_param('len_p.j', 'l')
        p, q, g = get_public_params(len_p)
        save_param('p.json', 'p', p)
        save_param('q.json', 'q', q)
        save_param('g.json', 'g', g)
    elif args.m == 2:  # частные парметры
        p = read_param('p.json', 'p')
        q = read_param('q.json', 'q')
        g = read_param('g.json', 'g')
        x, y = get_private_params(p, q, g)
        save_param('x.json', 'x', x)
        save_param('y.json', 'y', y)
    elif args.m == 3:  # Алиса генерит k < q
        q = read_param('q.json', 'q')
        k = utils.get_big_prime(2, q)
        save_param('k.json', 'k', k)
        # elif args.m == 4:  # Алиса подписывает
        g = read_param('g.json', 'g')
        k = read_param('k.json', 'k')
        p = read_param('p.json', 'p')
        q = read_param('q.json', 'q')
        x = read_param('x.json', 'x')
        r = pow(g, k, p) % q
        s = (utils.inverse(k, q) * (get_hash(m) + x * r)) % q
        save_param('signature.json', 'r', r)
        save_param('signature.json', 's', s)
    elif args.m == 4:  # боб проверяет
        s = read_param('signature.json', 's')
        r = read_param('signature.json', 'r')
        q = read_param('q.json', 'q')
        p = read_param('p.json', 'p')
        g = read_param('g.json', 'g')
        y = read_param('y.json', 'y')
        w = utils.inverse(s, q)
        u1 = get_hash(m) * w % q
        u2 = r * w % q
        v = ((pow(g, u1, p) * pow(y, u2, p)) % p) % q
        save_param('v.json', 'v', v)
        if v == r:
            print("Подпись верна")
            input()
        else:
            print("Подпись не верна")
    # 2.3
    else:
        write_log('Bad args')
Ejemplo n.º 2
0
def get_private_params_Bob(p, g):
    while True:
        y = utils.get_big_digit() % p
        if gcd(y, p - 1) == 1 and utils.inverse(y, p - 1) >= 0:
            break
    d = pow(g, y, p)
    z = utils.inverse(y, p - 1)

    with open('log.log', 'a') as f:
        f.write("Бобом вычислен закрытый параметр y: {}\n".format(y))
        f.write(
            "Бобом вычислен параметр z (обратный элемент к y): {}\n".format(z))
        f.write("Бобом сгенерирован открытый параметр d: {}\n".format(d))
    return y, d, z
Ejemplo n.º 3
0
 def sum(P, Q, a, p):
     if EllipticPoint.iszero(P):
         return Q
     elif EllipticPoint.iszero(Q):
         return P
     if EllipticPoint.equal_inv(P, Q, p):
         return EllipticPoint(p, -1, -1)
     if not EllipticPoint.equal(P, Q):
         m = ((P.y - Q.y) % p) * inverse((P.x - Q.x) % p, p) % p
     else:
         m = (3 * P.x * P.x + a) * inverse((2 * P.y) % p, p) % p
     r = EllipticPoint(p)
     r.x = (m * m - P.x - Q.x) % p
     r.y = (-P.y + m * (P.x - r.x)) % p
     return r
Ejemplo n.º 4
0
def gauss(n, SOLE, m, changable):
    for i in range(n):
        if i < n:
            if SOLE[i][i] == 0:
                change_matrix(SOLE, changable, i, i)
            else:
                changable.remove(i)
            elem = SOLE[i][i]
            if elem != 1:
                obr_elem = utils.inverse(elem, m)
                for j in range(len(SOLE[i])):
                    SOLE[i][j] *= obr_elem
                    SOLE[i][j] %= m
            for k in range(i + 1, n):
                mult = SOLE[k][i]
                mult = -mult
                for a in range(len(SOLE[i])):
                    SOLE[k][a] += mult * SOLE[i][a]
                    SOLE[k][a] %= m
            if i != 0:
                for k in range(0, i):
                    mult = SOLE[k][i]
                    mult = -mult
                    for a in range(len(SOLE[i])):
                        SOLE[k][a] += mult * SOLE[i][a]
                        SOLE[k][a] %= m
            for j in range(n):
                c = collections.Counter(SOLE[j])
                if c[0] == len(SOLE[j]):
                    SOLE.remove(SOLE[j])
                    n -= 1
        not_solved(SOLE)
    return SOLE
Ejemplo n.º 5
0
def gprod_verify_outer(current_hash, crs, A, len_gprod, gprod, gprod_proof, n, logn):

    [crs_g, u, crs_se1, crs_se2] = crs[:]
    [B, blinder] = gprod_proof[:]

    current_hash = hash_integers([current_hash, gprod, blinder, int(B[0]), int(B[1]), int(B[2])])
    x = current_hash % curve_order; inv_x =inverse(x);

    C = crs_g[0]
    for i in range(1,len_gprod):
        C = add( C, crs_g[i])

    C = multiply(C, curve_order - inv_x)
    C = add(C, A)

    vec_crs_h_exp = [1]*n; pow_inv_x = inv_x
    for i in range(1,len_gprod):
        vec_crs_h_exp[i] = pow_inv_x
        pow_inv_x = pow_inv_x * inv_x % curve_order

    vec_crs_h_exp[0] = pow_inv_x

    pow_inv_x = pow_inv_x * inv_x % curve_order
    for i in range(len_gprod, n):
        vec_crs_h_exp[i] = pow_inv_x

    inner_prod = (blinder * (x ** (len_gprod+1)) + gprod * (x ** len_gprod) - 1) % curve_order

#    [current_hash, b] = gprod_verify_inner(current_hash, crs[:], vec_crs_h_exp[:], C, inner_prod, inner_proof[:],
#    len_gprod, n, logn)

    inner_prod_info = [vec_crs_h_exp[:], B, C, inner_prod, len_gprod]

    return [current_hash, inner_prod_info[:]]
Ejemplo n.º 6
0
def gprod_verify_inner(current_hash, crs, vec_crs_h_exp, C, inner_prod, inner_proof, len_gprod, n, logn):
    [crs_g, crs_h, u] = crs[:]

    ### Adding in zero knowledge
    [R, blinder_2,proof, last_b, last_c] = inner_proof[:]


    current_hash = hash_integers([current_hash,int(R[0]),int(R[1]), int(R[2]), blinder_2])
    x = current_hash % curve_order

    inner_prod = (inner_prod + blinder_2 * x ) % curve_order
    C = add(C, multiply(R,x))

    ### Putting inner_prod into exponent.
    current_hash = hash_integers([current_hash,inner_prod])
    x = current_hash % curve_order;

    u = multiply(u, x)
    C = add(C, multiply(u,inner_prod))

    vec_crs_g_exp = [1] * n;
    vec_crs_h_shifted = [1] * n;

    n_var = n
    for j in range(logn):
        n_var = n_var // 2
        [CL, CR] = proof[j]

        current_hash = hash_integers([current_hash,int(CL[0]),int(CL[1]), int(CL[2]),
                int(CR[0]), int(CR[1]), int(CR[2])])

        x = current_hash % curve_order; inv_x =inverse(x)

        for i in range(n):
            bin_i = int_to_binaryintarray(i,logn)
            if bin_i[logn - j - 1] == 1:
                vec_crs_g_exp[i] = (vec_crs_g_exp[i] * inv_x) % curve_order
                vec_crs_h_shifted[i] = (vec_crs_h_shifted[i] * x) % curve_order

        C = add(add(multiply(CR, inv_x), C), multiply(CL, x))

    vec_crs_h_exp[0] = (vec_crs_h_exp[0] * vec_crs_h_shifted[len_gprod - 1]) % curve_order
    for i in range(1,len_gprod):
        vec_crs_h_exp[i] = (vec_crs_h_exp[i] * vec_crs_h_shifted[i-1]) % curve_order
    for i in range(len_gprod,n):
        vec_crs_h_exp[i] = (vec_crs_h_exp[i] * vec_crs_h_shifted[i]) % curve_order

    inner_prod = last_b * last_c % curve_order
    final_g = compute_multiexp(crs_g[:], vec_crs_g_exp[:])
    final_h = compute_multiexp(crs_h[:], vec_crs_h_exp[:])

    expected_outcome = multiply(final_g, curve_order - last_b)
    expected_outcome = add(expected_outcome, multiply(final_h, curve_order - last_c))
    expected_outcome = add(expected_outcome, multiply(u, curve_order - inner_prod))

    if add( expected_outcome, C) != (1,1,0):
        print("ERROR: final exponent is incorrect")
        return [current_hash, 0]

    return [current_hash, 1]
Ejemplo n.º 7
0
    def attitude_control(self, quad, Ts, config):

        # Current thrust orientation e_z and desired thrust orientation e_z_d
        e_z = quad.dcm[:, 2]
        e_z_d = -utils.vectNormalize(self.thrust_sp)
        if (config.orient == "ENU"):
            e_z_d = -e_z_d

        # Quaternion error between the 2 vectors
        qe_red = np.zeros(4)
        qe_red[0] = np.dot(e_z, e_z_d) + sqrt(norm(e_z)**2 * norm(e_z_d)**2)
        qe_red[1:4] = np.cross(e_z, e_z_d)
        qe_red = utils.vectNormalize(qe_red)

        # Reduced desired quaternion (reduced because it doesn't consider the desired Yaw angle)
        self.qd_red = utils.quatMultiply(qe_red, quad.quat)

        # Mixed desired quaternion (between reduced and full) and resulting desired quaternion qd
        q_mix = utils.quatMultiply(utils.inverse(self.qd_red), self.qd_full)
        q_mix = q_mix * np.sign(q_mix[0])
        q_mix[0] = np.clip(q_mix[0], -1.0, 1.0)
        q_mix[3] = np.clip(q_mix[3], -1.0, 1.0)
        self.qd = utils.quatMultiply(
            self.qd_red,
            np.array([
                cos(self.yaw_w * np.arccos(q_mix[0])), 0, 0,
                sin(self.yaw_w * np.arcsin(q_mix[3]))
            ]))

        # Resulting error quaternion
        self.qe = utils.quatMultiply(utils.inverse(quad.quat), self.qd)

        # Create rate setpoint from quaternion error
        #@ self.rate_sp = (2.0*np.sign(self.qe[0])*self.qe[1:4])*att_P_gain
        self.rate_sp = (2.0 * np.sign(self.qe[0]) *
                        self.qe[1:4]) * self.cTune_att_P_gain * att_P_gain

        # Limit yawFF
        self.yawFF = np.clip(self.yawFF, -rateMax[2], rateMax[2])

        # Add Yaw rate feed-forward
        self.rate_sp += utils.quat2Dcm(utils.inverse(
            quad.quat))[:, 2] * self.yawFF

        # Limit rate setpoint
        self.rate_sp = np.clip(self.rate_sp, -rateMax, rateMax)
Ejemplo n.º 8
0
def shanks(m, g, h):
    # Step 1
    r = square_root(m) + 1
    pairs = {pow(g, a, m): a for a in range(r)}
    # Step 2
    g1 = pow(utils.inverse(g, m), r, m)
    for b in range(r):  # r-1 ?
        value = (pow(g1, b, m) * h) % m
        if value in pairs:
            return pairs[value] + r * b
Ejemplo n.º 9
0
def get_private_params_Alice(p, g):
    while True:
        x = utils.get_big_digit() % p
        if gcd(x, p - 1) == 1 and utils.inverse(x, p - 1) >= 0:
            break
    k = pow(g, x, p)
    with open('log.log', 'a') as f:
        f.write("Алисой вычислен закрытый параметр x: {}\n".format(x))
        f.write("Алисой сгенерирован открытый параметр k: {}\n".format(k))
    return x, k
Ejemplo n.º 10
0
def generateSignature(p, q, g, x, message):
    H = int(hexlify(CryptoBox.generateHash(message, 1)), 16)
    k = number.getRandomRange(1, q)
    r = utils.mod_exp(g, k, p) % q
    k_inv = utils.inverse(k, q)
    s = (k_inv * (H + x * r)) % q

    if (r == 0 or s == 0):
        # since it is very unlikely to make a recursive call, function will terminate eventually
        return generateSignature(p, q, g, x, message)

    return r, s
Ejemplo n.º 11
0
    def setup(self, nbits=512):
        p = get_rand_prime(nbits)
        q = get_rand_prime(nbits)
        while p == q:
            q = get_rand_prime(nbits)
        n = p * q
        phi = (p-1) * (q-1)
        e = randrange(2**16, 2**17)
        d = inverse(e, phi)
        while d == -1:
            e = randrange(2**16, 2**17)
            d = inverse(e, phi)

        return {
            "p": p,
            "q": q,
            "n": n,
            "phi": phi,
            "e": e,
            "d": d
        }
Ejemplo n.º 12
0
def gprod_prove_inner(current_hash, crs, vec_b, vec_c,inner_prod, n, logn):
    [crs_g, crs_h, u] = crs[:]
    proof = []

    ### Adding in zero knowledge
    vec_r = [0]*n;
    for i in range(n):
        vec_r[i] = randbelow(curve_order)

    R = compute_multiexp(crs_h[:], vec_r[:])
    blinder_2 = compute_innerprod(vec_b[:], vec_r[:])

    current_hash = hash_integers([current_hash,int(R[0]),int(R[1]), int(R[2]), blinder_2])
    x = current_hash % curve_order

    inner_prod = (inner_prod + blinder_2 * x ) % curve_order
    for i in range(n):
        vec_c[i] = (vec_c[i] + vec_r[i] * x) % curve_order


    ### Inserting inner_prod into exponent.
    current_hash = hash_integers([current_hash,inner_prod])
    x = current_hash % curve_order;
    u = multiply(u, x)

    for j in range(logn):
        n = n // 2

        zL = compute_innerprod(vec_b[n:], vec_c[:n])
        zR = compute_innerprod(vec_b[:n], vec_c[n:])

        CL = add(compute_multiexp(crs_g[:n], vec_b[n:]), compute_multiexp(crs_h[n:],vec_c[:n]))
        CL = add(CL, multiply(u, zL))
        CR = add(compute_multiexp(crs_g[n:], vec_b[:n]), compute_multiexp(crs_h[:n],vec_c[n:]))
        CR = add(CR, multiply(u, zR))

        proof.append([CL, CR])

        current_hash = hash_integers([current_hash,int(CL[0]),int(CL[1]), int(CL[2]),
        int(CR[0]), int(CR[1]), int(CR[2])])

        x = current_hash % curve_order; inv_x =inverse(x);

        for i in range(n):
            crs_g[i] = add(multiply(crs_g[n + i],inv_x), crs_g[i] )
            crs_h[i] = add(multiply(crs_h[n + i],x), crs_h[i] )
            vec_b[i] =  (vec_b[i] + x * vec_b[n + i] ) % curve_order
            vec_c[i] =  (vec_c[i] + inv_x * vec_c[n + i] ) % curve_order

        crs_g = crs_g[:n]; crs_h = crs_h[:n]
        vec_b = vec_b[:n]; vec_c = vec_c[:n]

    return [current_hash, [R, blinder_2, proof[:], vec_b[0], vec_c[0]]]
Ejemplo n.º 13
0
def verifySignature(p, q, g, y, r, s, message):
    if r <= 0 or r >= q or s <= 0 or s >= q:
        print "Rejected!"
        return

    H = int(hexlify(CryptoBox.generateHash(message, 1)), 16)
    w = utils.inverse(s, q)
    u1 = (H * w) % q
    u2 = (r * w) % q
    v = ((utils.mod_exp(g, u1, p) * utils.mod_exp(y, u2, p)) % p) % q

    return True if v == r else False
Ejemplo n.º 14
0
def generateSignature(p, q, g, x, message):
    H = int(hexlify(CryptoBox.generateHash(message, 1)), 16)
    k = number.getRandomRange(1, q)
    r = utils.mod_exp(g, k, p) % q
    k_inv = utils.inverse(k, q)
    s = (k_inv * (H + x * r)) % q

    if (r == 0 or s == 0):
        # since it is very unlikely to make a recursive call, function will terminate eventually
        return generateSignature(p, q, g, x, message)
    
    return r, s
Ejemplo n.º 15
0
def verifySignature(p, q, g, y, r, s, message):
    if r <= 0 or r >= q or s <= 0 or s >= q:
        print "Rejected!"
        return

    H = int(hexlify(CryptoBox.generateHash(message, 1)), 16)
    w = utils.inverse(s, q)
    u1 = (H * w) % q
    u2 = (r * w) % q
    v = ((utils.mod_exp(g, u1, p) * utils.mod_exp(y, u2, p)) % p) % q

    return True if v == r else False
Ejemplo n.º 16
0
def ifft(b, m, n, k):
    w = utils.inverse(primitive_root(m, n), m) % m
    r = {(0, k): b}
    for s in range(k - 1, -1, -1):
        t = 0
        while t < n - 1:
            b_new = [r[(t, s + 1)][j] for j in range(pow(2, s + 1))]
            e = int(bin(t // pow(2, s))[2:].zfill(k)[::-1], 2)
            r[(t, s)] = [(b_new[j] + pow(w, e) * b_new[j + pow(2, s)]) % m
                         for j in range(pow(2, s))]
            r[(t + pow(2, s), s)] = [
                (b_new[j] + pow(w, e + n // 2) * b_new[j + pow(2, s)]) % m
                for j in range(pow(2, s))
            ]
            t += pow(2, s + 1)
    a = [0] * n
    for i in range(n):
        # print(int(bin(i)[2:].zfill(k)[::-1], 2))
        # print(utils.inverse(m, n % m))
        a[int(bin(i)[2:].zfill(k)[::-1],
              2)] = (utils.inverse(n % m, m) * r[(i, 0)][0]) % m
    print('Вектор a = {}'.format(str(a)))
Ejemplo n.º 17
0
def signature(M, G, a, n, p, x):
    r, k, R = 0, None, None
    while r == 0:
        k = random.randint(1, n - 1)
        R = ep.mul(G, k, a, p)
        r = R.x % p

    e = hsh(M, n)
    assert 0 <= e < n
    s = (e + r*x) * inverse(k, n) % n
    print('Данные подписаны')
    print('R={}, s={}'.format(R, s))
    return R, s
Ejemplo n.º 18
0
def create_keys(cnt, l):
    result = []
    t = []
    n = sympy.randprime(2 ** (l - 1), 2 ** l)
    for i in range(cnt):
        e = random.randint(2, n - 1)
        while sympy.gcd(e, n - 1) != 1 and e not in t:
            e = random.randint(2, n - 1)
        t.append(e)
        d = utils.inverse(e, n - 1)
        result.append([[e, n], [d, n]])

    return result
Ejemplo n.º 19
0
def gprod_prove_outer(current_hash, crs, vec_a, len_gprod, gprod, n, logn):

    [crs_g, u, crs_se1, crs_se2] = crs[:]

    vec_b = [0] * n
    vec_b[0] = 1
    for i in range(1,len_gprod):
        vec_b[i] = vec_a[i] * vec_b[i-1] % curve_order

    for i in range(len_gprod,n):
        vec_b[i] = randbelow(curve_order)

    B = compute_multiexp(crs_g[:], vec_b[:])
    blinder = compute_innerprod(vec_a[len_gprod:],vec_b[len_gprod:])

    current_hash = hash_integers([current_hash, gprod, blinder, int(B[0]), int(B[1]), int(B[2])])
    x = current_hash % curve_order; inv_x =inverse(x);

    vec_c = [0] * n;
    pow_x = x;
    pow_x2 = 1
    for i in range(len_gprod-1):
        vec_c[i] = ( vec_a[i+1] * pow_x  - pow_x2) % curve_order
        pow_x = pow_x * x % curve_order
        pow_x2 = pow_x2 * x % curve_order

    vec_c[len_gprod-1] = (vec_a[0] * pow_x - pow_x2) % curve_order

    pow_x = pow_x * x % curve_order
    for i in range(len_gprod, n):
        vec_c[i] = (vec_a[i] * pow_x) % curve_order

    crs_h = [0]*n; pow_inv_x = inv_x
    for i in range(len_gprod - 1):
        crs_h[i] = multiply(crs_g[i+1], pow_inv_x)
        pow_inv_x = pow_inv_x * inv_x % curve_order
    crs_h[len_gprod-1] = multiply(crs_g[0], pow_inv_x)

    pow_inv_x = pow_inv_x * inv_x % curve_order
    for i in range(len_gprod, n):
        crs_h[i] = multiply(crs_g[i], pow_inv_x)

    inner_prod = (blinder * (x ** (len_gprod+1)) + gprod * (x ** len_gprod) - 1) % curve_order

    crs = [crs_g[:],crs_h[:],u]

#    [current_hash, inner_proof] = gprod_prove_inner(current_hash, crs[:], vec_b[:], vec_c[:], inner_prod, n, logn)

    inner_prod_info = [crs_h[:], vec_b[:], vec_c[:], inner_prod]

    return [current_hash, [B, blinder], inner_prod_info[:]]
Ejemplo n.º 20
0
def garner(r, m):
    n = len(m)
    c = [0] * n
    for i in range(1, n):
        c[i] = 1
        for j in range(0, i):
            u = utils.inverse(m[j], m[i])
            c[i] = u * c[i] % m[i]
    u = r[0]
    x = u
    for i in range(1, n):
        u = (r[i] - x) * c[i] % m[i]
        x = x + u * functools.reduce(mul, (m[idx] for idx in range(i)), 1)
    return x
Ejemplo n.º 21
0
def generator_elliptic_curve(l, m):
    while True:
        while True:
            p = get_prime(l)
            if p % 4 == 1:
                break

        a, b = complex_decomposition(1, p)
        assert a * a + b * b == p
        T = [-2 * a, -2 * b, 2 * a, 2 * b]
        for t in T:
            N = p + 1 + t
            if isprime(N // 2):
                r = N // 2
                break
            if isprime(N // 4):
                r = N // 4
                break
        else:
            continue

        good = True
        for i in range(1, m):
            if (p**i) % r == 1:
                good = False
        if p == r or not good:
            continue

        while True:
            e = EllipticPoint(p)
            A = ((e.y**2 - e.x**3) * inverse(e.x, p)) % p
            good = False
            if N == r * 2:
                if legendre_symbol(-A, p) == -1:
                    good = True
            if N == r * 4:
                if legendre_symbol(-A, p) == 1:
                    good = True
            if not good:
                continue

            m = EllipticPoint.mul(e, N, A, p)
            if m == EllipticPoint(p, -1, -1):
                break
        Q = EllipticPoint.mul(e, N // r, A, p)
        return p, A, Q, r
Ejemplo n.º 22
0
def generateKeys(security_level=1):
    bit_count = None

    if security_level == 1:
        bit_count = 1024 / 2
    elif security_level == 2:
        bit_count = 2048 / 2
    elif security_level == 3:
        bit_count = 3072 / 2

    p, q = number.getPrime(bit_count), number.getPrime(bit_count)

    #p = utils.gen_random(bit_count)
    #count = 3 # test primality thrice

    #while utils.rm_primality(p) == False or (utils.rm_primality(p) == True and count != 0):
    #    p = utils.gen_random(bit_count)

    #    if utils.rm_primality(p) == True:
    #        count -= 1

    #q = utils.gen_random(bit_count)
    #count = 3 # test primality thrice

    #while utils.rm_primality(q) == False or (utils.rm_primality(q) == True and count != 0):
    #    q = utils.gen_random(bit_count)

    #    if utils.rm_primality(q) == True:
    #        count -= 1

    N = p * q

    phi_N = (p - 1) * (q - 1)

    e = randint(1, phi_N - 1)

    while gcd(e, phi_N) != 1:
        e = randint(1, phi_N - 1)

    d = utils.inverse(e, phi_N)

    return e, N, d, p, q
Ejemplo n.º 23
0
def generateKeys(security_level = 1):
    bit_count = None

    if security_level == 1:
        bit_count = 1024 / 2
    elif security_level == 2:
        bit_count = 2048 / 2
    elif security_level == 3:
        bit_count = 3072 / 2

    p, q = number.getPrime(bit_count), number.getPrime(bit_count)

    #p = utils.gen_random(bit_count)
    #count = 3 # test primality thrice

    #while utils.rm_primality(p) == False or (utils.rm_primality(p) == True and count != 0):
    #    p = utils.gen_random(bit_count)

    #    if utils.rm_primality(p) == True:
    #        count -= 1

    #q = utils.gen_random(bit_count)
    #count = 3 # test primality thrice

    #while utils.rm_primality(q) == False or (utils.rm_primality(q) == True and count != 0):
    #    q = utils.gen_random(bit_count)

    #    if utils.rm_primality(q) == True:
    #        count -= 1

    N = p * q

    phi_N = (p-1) * (q-1)

    e = randint(1, phi_N - 1)

    while gcd(e, phi_N) != 1:
        e = randint(1, phi_N - 1)

    d = utils.inverse(e, phi_N)

    return e, N, d, p, q
Ejemplo n.º 24
0
 def __init__(self, terminals, query):
     self.variables = [Variable("S"), Variable("C")]
     self.terminals = terminals[:]
     self.productions = [
         CFGRule(
             Variable("S"),
             [Variable("C"), Terminal(query),
              Variable("C")]),
         CFGRule(Variable("C"),
                 [Variable("C"), Variable("C")]),
         CFGRule(Variable("C"), [])
     ]
     for terminal in self.terminals:
         self.productions.append(
             CFGRule(Variable("C"), [
                 Terminal(terminal),
                 Variable("C"),
                 Terminal(inverse(terminal))
             ]))
     self.start = Variable("S")
     self.__empty = None
Ejemplo n.º 25
0
    def generate_all_states_rec(bs, functions, n_added=0):
        if bs.total_length() >= max_size or len(
                functions) == 0 or n_added >= 2:
            res.append(bs)
            return
        cp_temp = bs.get_constraint_path()
        function = functions[0]
        f_l = function.to_list()
        f_str = " ".join(f_l)
        if starts_with(f_str, cp) and\
                starts_with(f_str, cp_temp):
            generate_all_states_rec(
                BackwardState(bs.backward_paths[:] +
                              [BackwardPath(f_str, "f")]), functions[1:],
                n_added + 1)
        f_str = " ".join(function.get_inverse_function())
        if starts_with(f_str, cp) and \
                starts_with(f_str, cp_temp):
            generate_all_states_rec(
                BackwardState(bs.backward_paths[:] +
                              [BackwardPath(function, "b")]), functions[1:],
                n_added + 1)
        # kinks
        for i in range(1, len(f_l)):
            f_left = f_l[:i]
            f_right = f_l[i:]
            f_str_right = " ".join(f_right)
            f_left_inv = " ".join(map(lambda x: inverse(x, "-"), f_left[::-1]))
            if starts_with(f_str_right, cp) and \
                    starts_with(f_str_right, cp_temp) and \
                    starts_with(f_left_inv, cp) and \
                    starts_with(f_left_inv, cp_temp) and \
                    starts_with(f_str_right, f_left_inv):
                generate_all_states_rec(
                    BackwardState(bs.backward_paths[:] + [
                        BackwardPath(f_left[::-1], "b"),
                        BackwardPath(f_right, "f")
                    ]), functions, n_added)

        generate_all_states_rec(bs, functions[1:], n_added)
Ejemplo n.º 26
0
    def decryption(self, message):
        n = self.parameters['p'] * self.parameters['q']

        # 1- Convert to CRT domain
        yp = message % self.parameters['p']
        yq = message % self.parameters['q']

        # 2- Do the computations
        dp = self.parameters['d'] % (self.parameters['p'] - 1)
        dq = self.parameters['d'] % (self.parameters['q'] - 1)

        xp = pow(yp, dp, self.parameters['p'])
        xq = pow(yq, dq, self.parameters['q'])

        # 3- Inverse transform
        inv = inverse(self.parameters['p'], self.parameters['q'])
        print(inv)
        cp = pow(self.parameters['q'], self.parameters['p'] - 2, self.parameters['p'])
        cq = pow(self.parameters['p'], self.parameters['q'] - 2, self.parameters['q'])

        result = ((self.parameters['q'] * cp * xp) + (self.parameters['p'] * cq * xq)) % n
        return result
def verify_multiexp_and_gprod_inner(current_hash, crs, vec_crs_h_exp,
                                    len_gprod, B, C, inner_prod, ciphertexts_1,
                                    ciphertexts_2, commit_exps, multiexp_1,
                                    multiexp_2, inner_proof, n, logn):
    [crs_g, u, crs_se1, crs_se2] = crs[:]

    ### Adding in zero knowledge
    [zkinfo, proof, final_values] = inner_proof[:]
    [Rgp, Sgp, Rme, blgp1, blgp2, Bl1me, Bl2me] = zkinfo[:]

    current_hash = hash_integers([
        current_hash,
        int(Rgp[0]),
        int(Rgp[1]),
        int(Rgp[2]),
        int(Sgp[0]),
        int(Sgp[1]),
        int(Sgp[2]), blgp1, blgp2,
        int(Rme[0]),
        int(Rme[1]),
        int(Rme[2]),
        int(Bl1me[0]),
        int(Bl1me[1]),
        int(Bl1me[2]),
        int(Bl2me[0]),
        int(Bl2me[1]),
        int(Bl2me[2])
    ])
    x = current_hash % curve_order

    inner_prod = (inner_prod + blgp1 * x + blgp2 * x**2) % curve_order
    B = add(B, multiply(Rgp, x))
    C = add(C, multiply(Sgp, x))
    commit_exps = add(commit_exps, multiply(Rme, x))
    multiexp_1 = add(multiexp_1, multiply(Bl1me, x))
    multiexp_2 = add(multiexp_2, multiply(Bl2me, x))

    ### Putting inner_prod into exponent.
    current_hash = hash_integers([current_hash, inner_prod])
    x = current_hash % curve_order

    u = multiply(u, x)
    B = add(B, multiply(u, inner_prod))

    [final_b, final_c, final_exp] = final_values[:]
    vec_crs_g_exp = [final_b] * n
    vec_crs_h_shifted = [1] * n

    n_var = n
    for j in range(logn):
        n_var = n_var // 2

        [CLgp_b, CLgp_c, CRgp_b, CRgp_c, zLme, zRme, CLme, CRme] = proof[j]

        current_hash = hash_integers([
            current_hash,
            int(CLgp_b[0]),
            int(CLgp_b[1]),
            int(CLgp_b[2]),
            int(CLgp_c[0]),
            int(CLgp_c[1]),
            int(CLgp_c[2]),
            int(CRgp_b[0]),
            int(CRgp_b[1]),
            int(CRgp_b[2]),
            int(CRgp_c[0]),
            int(CRgp_c[1]),
            int(CRgp_c[2]),
            int(zLme[0][0]),
            int(zLme[0][1]),
            int(zLme[0][2]),
            int(zRme[0][0]),
            int(zRme[0][1]),
            int(zRme[0][2]),
            int(CLme[0]),
            int(CLme[1]),
            int(CLme[2]),
            int(CRme[0]),
            int(CRme[1]),
            int(CRme[2])
        ])

        x = current_hash % curve_order
        inv_x = inverse(x)

        for i in range(n):
            bin_i = int_to_binaryintarray(i, logn)
            if bin_i[logn - j - 1] == 1:
                vec_crs_g_exp[i] = (vec_crs_g_exp[i] * inv_x) % curve_order
                vec_crs_h_shifted[i] = (vec_crs_h_shifted[i] * x) % curve_order

        B = add(add(multiply(CRgp_b, inv_x), B), multiply(CLgp_b, x))
        C = add(add(multiply(CRgp_c, inv_x), C), multiply(CLgp_c, x))
        multiexp_1 = add(add(multiply(zLme[0], x), multiexp_1),
                         multiply(zRme[0], inv_x))
        multiexp_2 = add(add(multiply(zLme[1], x), multiexp_2),
                         multiply(zRme[1], inv_x))

        commit_exps = add(add(multiply(CRme, inv_x), commit_exps),
                          multiply(CLme, x))

    ciphertexts_1_final = compute_multiexp(ciphertexts_1[:],
                                           vec_crs_h_shifted[:])
    ciphertexts_2_final = compute_multiexp(ciphertexts_2[:],
                                           vec_crs_h_shifted[:])

    if add(multiply(ciphertexts_1_final, curve_order - final_exp),
           multiexp_1) != (1, 1, 0):
        print("ERROR: final ciphertext 1 is incorrect")
        return [current_hash, 0]

    if add(multiply(ciphertexts_2_final, curve_order - final_exp),
           multiexp_2) != (1, 1, 0):
        print("ERROR: final ciphertext 2 is incorrect")
        return [current_hash, 0]

    current_hash = hash_integers([current_hash, final_b, final_c, final_exp])
    x = current_hash % curve_order

    vec_crs_h_exp[0] = (x**2 * vec_crs_g_exp[0] +
                        x * vec_crs_h_shifted[0] * final_exp +
                        vec_crs_h_exp[0] * vec_crs_h_shifted[len_gprod - 1] *
                        final_c) % curve_order
    for i in range(1, len_gprod):
        vec_crs_h_exp[i] = (x**2 * vec_crs_g_exp[i] +
                            x * vec_crs_h_shifted[i] * final_exp +
                            vec_crs_h_exp[i] * vec_crs_h_shifted[i - 1] *
                            final_c) % curve_order

    for i in range(len_gprod, n):
        vec_crs_h_exp[i] = (
            x**2 * vec_crs_g_exp[i] + x * vec_crs_h_shifted[i] * final_exp +
            vec_crs_h_exp[i] * vec_crs_h_shifted[i] * final_c) % curve_order

    inner_prod = final_b * final_c % curve_order

    expected_outcome = compute_multiexp(crs_g[:], vec_crs_h_exp[:])
    expected_outcome = add(expected_outcome,
                           multiply(u, (inner_prod * x**2) % curve_order))
    expected_outcome = add(expected_outcome,
                           multiply(commit_exps, curve_order - x))
    expected_outcome = add(expected_outcome, multiply(C, curve_order - 1))
    expected_outcome = add(expected_outcome, multiply(B,
                                                      (-x**2) % curve_order))

    if expected_outcome != Z1:
        print("ERROR: final exponent is incorrect")
        return [current_hash, 0]

    return [current_hash, 1]
def prove_multiexp_and_gprod_inner(current_hash, crs, vec_b, vec_c, inner_prod,
                                   ciphertexts_1, ciphertexts_2, vec_exp, n,
                                   logn):
    [crs_g, crs_h_scaled, u] = crs[:]
    crs_h = crs_g[:]

    proof = []

    ### Adding in zero knowledge
    vec_rgp = [0] * n
    vec_sgp = [0] * n
    vec_rme = [0] * n
    for i in range(n):
        vec_rgp[i] = randbelow(curve_order)
        vec_sgp[i] = randbelow(curve_order)
        vec_rme[i] = randbelow(curve_order)

    Rgp = compute_multiexp(crs_g[:], vec_rgp[:])
    Sgp = compute_multiexp(crs_h_scaled[:], vec_sgp[:])
    blgp1 = (compute_innerprod(vec_b[:], vec_sgp[:]) +
             compute_innerprod(vec_c[:], vec_rgp[:])) % curve_order
    blgp2 = compute_innerprod(vec_rgp[:], vec_sgp[:])

    Rme = compute_multiexp(crs_h[:], vec_rme[:])
    Bl1me = compute_multiexp(ciphertexts_1[:], vec_rme[:])
    Bl2me = compute_multiexp(ciphertexts_2[:], vec_rme[:])

    zkinfo = [Rgp, Sgp, Rme, blgp1, blgp2, Bl1me, Bl2me]

    current_hash = hash_integers([
        current_hash,
        int(Rgp[0]),
        int(Rgp[1]),
        int(Rgp[2]),
        int(Sgp[0]),
        int(Sgp[1]),
        int(Sgp[2]), blgp1, blgp2,
        int(Rme[0]),
        int(Rme[1]),
        int(Rme[2]),
        int(Bl1me[0]),
        int(Bl1me[1]),
        int(Bl1me[2]),
        int(Bl2me[0]),
        int(Bl2me[1]),
        int(Bl2me[2])
    ])
    x = current_hash % curve_order

    inner_prod = (inner_prod + blgp1 * x + blgp2 * x**2) % curve_order
    for i in range(n):
        vec_b[i] = (vec_b[i] + vec_rgp[i] * x) % curve_order
        vec_c[i] = (vec_c[i] + vec_sgp[i] * x) % curve_order
        vec_exp[i] = (vec_exp[i] + vec_rme[i] * x) % curve_order

    ### Inserting inner_prod into exponent.
    current_hash = hash_integers([current_hash, inner_prod])
    x = current_hash % curve_order
    u = multiply(u, x)

    for j in range(logn):
        n = n // 2

        zLgp = compute_innerprod(vec_b[n:], vec_c[:n])
        zRgp = compute_innerprod(vec_b[:n], vec_c[n:])
        zLme = [
            compute_multiexp(ciphertexts_1[n:], vec_exp[:n]),
            compute_multiexp(ciphertexts_2[n:], vec_exp[:n])
        ]
        zRme = [
            compute_multiexp(ciphertexts_1[:n], vec_exp[n:]),
            compute_multiexp(ciphertexts_2[:n], vec_exp[n:])
        ]

        CLgp_b = add(compute_multiexp(crs_g[:n], vec_b[n:]), multiply(u, zLgp))
        CLgp_c = compute_multiexp(crs_h_scaled[n:], vec_c[:n])

        CRgp_b = add(compute_multiexp(crs_g[n:], vec_b[:n]), multiply(u, zRgp))
        CRgp_c = compute_multiexp(crs_h_scaled[:n], vec_c[n:])
        CLme = compute_multiexp(crs_h[n:], vec_exp[:n])
        CRme = compute_multiexp(crs_h[:n], vec_exp[n:])

        proof.append([CLgp_b, CLgp_c, CRgp_b, CRgp_c, zLme, zRme, CLme, CRme])

        current_hash = hash_integers([
            current_hash,
            int(CLgp_b[0]),
            int(CLgp_b[1]),
            int(CLgp_b[2]),
            int(CLgp_c[0]),
            int(CLgp_c[1]),
            int(CLgp_c[2]),
            int(CRgp_b[0]),
            int(CRgp_b[1]),
            int(CRgp_b[2]),
            int(CRgp_c[0]),
            int(CRgp_c[1]),
            int(CRgp_c[2]),
            int(zLme[0][0]),
            int(zLme[0][1]),
            int(zLme[0][2]),
            int(zRme[0][0]),
            int(zRme[0][1]),
            int(zRme[0][2]),
            int(CLme[0]),
            int(CLme[1]),
            int(CLme[2]),
            int(CRme[0]),
            int(CRme[1]),
            int(CRme[2])
        ])

        x = current_hash % curve_order
        inv_x = inverse(x)

        for i in range(n):
            crs_g[i] = add(multiply(crs_g[n + i], inv_x), crs_g[i])
            crs_h_scaled[i] = add(multiply(crs_h_scaled[n + i], x),
                                  crs_h_scaled[i])
            vec_b[i] = (vec_b[i] + x * vec_b[n + i]) % curve_order
            vec_c[i] = (vec_c[i] + inv_x * vec_c[n + i]) % curve_order

            crs_h[i] = add(multiply(crs_h[n + i], x), crs_h[i])
            ciphertexts_1[i] = add(multiply(ciphertexts_1[n + i], x),
                                   ciphertexts_1[i])
            ciphertexts_2[i] = add(multiply(ciphertexts_2[n + i], x),
                                   ciphertexts_2[i])

            vec_exp[i] = (vec_exp[n + i] * inv_x + vec_exp[i]) % curve_order

        crs_g = crs_g[:n]
        crs_h_scaled = crs_h_scaled[:n]
        vec_b = vec_b[:n]
        vec_c = vec_c[:n]

        crs_h = crs_h[:n]
        ciphertexts_1 = ciphertexts_1[:n]
        ciphertexts_2 = ciphertexts_2[:n]

        vec_exp = vec_exp[:n]

    final_values = [vec_b[0], vec_c[0], vec_exp[0]]
    current_hash = hash_integers(
        [current_hash, vec_b[0], vec_c[0], vec_exp[0]])

    return [current_hash, [zkinfo[:], proof[:], final_values[:]]]
Ejemplo n.º 29
0
from utils import pgcd, bezout, inverse, theoreme_chinois, elements_inversibles, rabin_miller, generer_cle_RSA, signature_RSA_CRT_faute, RSA_CRT_Bellcore

if __name__ == '__main__':
	print "Hello world!"

	print "pgcd(6, 9) should be equal 3 :", pgcd(6, 9)
	print "pgcd(3, 1) should be equal 1 :", pgcd(3, 1)

	print "bezout(57, 33) should be equal (3, -4, 7) :", bezout(57, 33)
	print "bezout(2, -4) should be equal (2, -1, -1) :", bezout(2, -4)
	
	print "inverse(2,7) should be equal 4 :", inverse(2, 7)
	print "inverse(-2,7) should be equal 3 :", inverse(-2, 7)
	print "inverse(-9,7) should be equal 3 :", inverse(-9, 7)
	
	print "theoreme_chinois([3, 4, 5], [17, 11, 6]) should return 785 :", theoreme_chinois([3, 4, 5], [17, 11, 6])

	print "len(elements_inversibles(60)) should return 16 :",  len(elements_inversibles(60))

	print "rabin_miller(13, 10) should return True :", rabin_miller(13, 10)
	print "rabin_miller(60, 10) should return False :", rabin_miller(60, 10)

	K = generer_cle_RSA(1024)
	s = signature_RSA_CRT_faute(42, K)
	(p, q, N, e, d) = K
	(p_, q_) = RSA_CRT_Bellcore(42, K)
	print (p == p_) and (q == q_)
Ejemplo n.º 30
0
 def received_message(self, message):
     message = json.loads(message.data)
     message_type = inverse(MESSAGES, head(message))
     method = getattr(self, message_type.lower(),
                      self.raise_not_implemented)
     method(*tail(message))
Ejemplo n.º 31
0
def chinese_theorem(a, e):
    m = functools.reduce(mul, e)
    u = 0
    for idx in range(len(a)):
        u += a[idx] * (m // e[idx]) * utils.inverse(m // e[idx], e[idx])
    return u % m
Ejemplo n.º 32
0
#!/usr/bin/env python
# coding: utf-8

from utils import multiplication_entiere, produit, affiche_table_multiplicative, exp, inverse, subgroup, generateurs

if __name__ == '__main__':
	print "Hello world!"

	print "multiplication_entiere(2, 5) =", multiplication_entiere(2, 5)

	n = 8
	poly = (0b1 << 8) ^ (0b1 << 4) ^ (0b1 << 3) ^ (0b1 << 1) ^ 0b1
	print produit(n, poly, 45, 72)

	affiche_table_multiplicative(3, poly & 0b1111)

	alpha = 0b10
	for i in xrange(1, 2**3):
		print "alpha **", i, ":", exp(3, poly & 0b1111, alpha, i)
	
	print inverse(3, poly & 0b1111, 1)
	print inverse(3, poly & 0b1111, 0b10)
	print inverse(3, poly & 0b1111, 0b11)
	print inverse(3, poly & 0b1111, 0b100)

	print subgroup(3, poly & 0b1111, 0b10)
	
	print generateurs(3, poly & 0b1111)
	print generateurs(8, poly)
Ejemplo n.º 33
0
 def received_message(self, message):
     message = json.loads(message.data)
     message_type = inverse(MESSAGES, head(message))
     method = getattr(self, message_type.lower(),
                      self.raise_not_implemented)
     method(*tail(message))
Ejemplo n.º 34
0
def decrypt(p, q, x, r, t):
    k = utils.inverse(utils.mod_exp(r, x, p), p)
    message = (t * k) % p

    return message