Exemplo n.º 1
0
    def computeProducts(self):
        lf = DEFAULT_PRECISION
        # Compute LCA encrypted
        prod_LCA = Mult3Matrix(self.enc_L, self.enc_C, self.enc_A,
                               self.enc_bLC, self.enc_bLA, self.enc_bCA)
        self.enc_LCA = prod_LCA

        # Compute Gamma2 = (I-LC)BK = BK - LCBK = Gamma3*K
        enc_Gamma2 = np.dot(self.enc_Gamma3, self.enc_K)

        rGamma2 = [[
            gmpy2.mpz_urandomb(gmpy2.random_state(), self.l + lf + self.sigma)
            for i in range(self.n)
        ] for j in range(self.n)]

        self.rGamma2 = util_fpv.vfp(rGamma2, -lf)

        # Compute Gamma = (I-LC)(A+BK) = A + BK - LCA - LCBK, they have different precisions
        enc_Gamma = (
            np.dot(self.enc_A, 2**(2 * lf) * np.eye(self.n, dtype=object)) -
            prod_LCA +
            np.dot(enc_Gamma2, 2**lf * np.eye(self.n, dtype=object)))

        rGamma = [[
            gmpy2.mpz_urandomb(gmpy2.random_state(),
                               self.l + 2 * lf + self.sigma)
            for i in range(self.n)
        ] for j in range(self.n)]

        self.rGamma = util_fpv.vfp(rGamma, -2 * lf)

        return enc_Gamma + rGamma, enc_Gamma2 + rGamma2
Exemplo n.º 2
0
def get_gpq():
    randnum = gmpy2.random_state(int(1000 * time.time()))

    Len_p = 1024
    Len_q = 256
    Len_t = 768

    p = 4

    q = gmpy2.mpz_urandomb(randnum, Len_q)
    q = gmpy2.next_prime(q)
    while not gmpy2.is_prime(p):
        t = gmpy2.mpz_urandomb(randnum, Len_t)
        p = t * q + 1

        g = 1
        while not g > 1:
            r = gmpy2.mpz_urandomb(randnum, Len_p)
            g = gmpy2.powmod(r, t, p)

    f = open('gpq.txt', 'w')
    print('g = ', g)
    print('p = ', p)
    print('q = ', q)
    f.write('g = ' + str(g) + '\n')
    f.write('p = ' + str(p) + '\n')
    f.write('q = ' + str(q))
    f.close()
 def gen_big_random(self, l=0, r=1024):
     """ generates a large random number m: 2**l <= m < 2**r """
     assert l < r, 'Lower border of the range should be strictly less than the upper one!'
     lv, rv = mpz(1) << l, mpz(1) << r
     lh = mpz_urandomb(self.random_state, l)
     rh = mpz_urandomb(self.random_state, r - l) << l
     b = (lh + lv + rh) % rv
     return b
Exemplo n.º 4
0
def generate_q():
    q = gmp.mpz_urandomb(gmp.random_state(random.randint(0, 367263292)), N)
    while not gmp.is_prime(q):
        q = gmp.next_prime(q)
        if no_bits(q) != N:
            q = gmp.mpz_urandomb(
                gmp.random_state(random.randint(0, 367263292)), N)

    return q
Exemplo n.º 5
0
Arquivo: laba5.py Projeto: 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
Exemplo n.º 6
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)
Exemplo n.º 7
0
def generate_prime(bits):
    """Will generate an integer of b bits that is prime 
    using the gmpy2 library  """    
    while True:
        possible =  mpz(2)**(bits-1)   + mpz_urandomb(rand, (bits-1) ) 
        if is_prime(possible):
            return possible
Exemplo n.º 8
0
def enc(pub, plain):
    while True:
        r = mpz_urandomb(rand, pub.bits)
        if r < pub.n and r > 0 and gcd(r, pub.n) == 1:
            break
    cipher = (powmod(pub.g, plain, pub.n_sq) * powmod(r, pub.n, pub.n_sq)) % pub.n_sq
    return cipher
Exemplo n.º 9
0
def gp(bits):
    bits -= 1
    base = 2 ** (bits)
    while True:
        add = mpz_urandomb(rand, (bits))
        possible = base + add
        print("%d + %d = %d" %(base, add, possible))
Exemplo n.º 10
0
def get_prime(rs):
    p = int(gmpy2.mpz_urandomb(rs, 4096))
    if p % 2 != 1:
        p = p + 1
    while not gmpy2.is_prime(p):
        p = p + 2
    return p
Exemplo n.º 11
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)
Exemplo n.º 12
0
 def p_q_gen(self, bits):
     self.p = mpz(2)**(bits - 1) + mpz_urandomb(rand, bits - 1)
     while True:
         self.p = next_prime(self.p)
         self.q = f_div(self.p - 1, 2)
         if is_prime(self.q):
             break
Exemplo n.º 13
0
 def DGK_s1(self, b):
     l = self.l
     nc = self.nc
     self.delta_A = [0] * nc
     c_all = [[0] * l] * nc
     for k in range(0, nc):
         beta = b[k]
         alpha = self.alpha[k]
         DGK_pubkey = self.DGK_pubkey
         delta_A = np.random.randint(0, 2)
         self.delta_A[k] = delta_A
         prod = [0] * l
         c = [DGK_pubkey.raw_encrypt(0)] * l
         # index 0 is the MSB
         for i in range(0, l):
             if (int(alpha[i]) == 0):
                 prod[i] = beta[i]
             else:
                 prod[i] = DGK.diff_encrypted(
                     DGK_pubkey.raw_encrypt(1, self.coinsDGK.pop()),
                     beta[i], DGK_pubkey)
             if (int(delta_A) == int(alpha[i])):
                 if i == 0:
                     c[i] = DGK_pubkey.raw_encrypt(0, self.coinsDGK.pop())
                 else:
                     for iter in range(0, i):
                         c[i] = DGK.add_encrypted(c[i], prod[iter],
                                                  DGK_pubkey)
                 if (int(delta_A) == 0):
                     diff = DGK.diff_encrypted(
                         DGK_pubkey.raw_encrypt(1, self.coinsDGK.pop()),
                         beta[i], DGK_pubkey)
                     c[i] = DGK.add_encrypted(c[i], diff, DGK_pubkey)
                 else:
                     c[i] = DGK.add_encrypted(c[i], beta[i], DGK_pubkey)
         for i in range(0, l):
             if (int(delta_A) == int(alpha[i])):
                 r = gmpy2.mpz_urandomb(gmpy2.random_state(),
                                        self.sigma + self.sigma)
                 c[i] = DGK.mul_sc_encrypted(c[i], r, DGK_pubkey)
             else:
                 c[i] = DGK_pubkey.raw_encrypt(
                     gmpy2.mpz_urandomb(gmpy2.random_state(),
                                        self.sigma + self.sigma),
                     self.coinsDGK.pop())
         c_all[k] = np.random.permutation(c)
     return c_all
Exemplo n.º 14
0
def generate_prime(bits):
    bits -= 1
    base = mpz(2)**(bits)
    while True:
        add = mpz_urandomb(rand, (bits))
        possible = base + add
        if is_prime(possible):
            return possible
Exemplo n.º 15
0
Arquivo: mqv.py Projeto: trushev/chat
def _encrypt_params():
    g, p = None, None
    q = gmpy2.mpz_urandomb(rs, 256)
    q = gmpy2.next_prime(q)
    while True:
        t = gmpy2.mpz_urandomb(rs, 768)
        p = gmpy2.mul(q, t)
        p = gmpy2.add(p, 1)
        if gmpy2.is_prime(p):
            break

    for r in itertools.count(2):
        g = gmpy2.powmod(r, t, p)
        if g > 1:
            break

    return g, p, q
Exemplo n.º 16
0
Arquivo: laba4.py Projeto: boggad/labs
def gen_keys():
    rs = gmpy2.random_state(hash(gmpy2.random_state()))
    P = gmpy2.mpz_urandomb(rs, mpz('256'))
    P = gmpy2.next_prime(P)
    Q = gmpy2.mpz_urandomb(rs, mpz('256'))
    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)
    print('Публичный ключ: ')
    print(Pkey)
    print('Приватный ключ:')
    print(Skey)
    print('N:')
    print(N)
Exemplo n.º 17
0
def encrypt(pub, plain):
    while True:
        r = mpz_urandomb(rand, pub.bits)
        if r > 0 and r < pub.n and gcd(r, pub.n) == 1:
            break
    x = powmod(r, pub.n, pub.n_sq)
    # if plain < 0:
    #     plain = plain + pub.n_sq
    cipher = (powmod(pub.g, plain, pub.n_sq) * x) % pub.n_sq
    return cipher
Exemplo n.º 18
0
def keygen(size):
    rs = gmpy2.random_state(int(time.time()))
    p = gmpy2.next_prime(gmpy2.mpz_urandomb(rs, size))
    while p % 4 != 3:
        p = gmpy2.next_prime(p)
    q = gmpy2.next_prime(p)
    while q % 4 != 3:
        q = gmpy2.next_prime(q)
    n = p * q
    x = n - 1
    return (x, n), (p, q)
Exemplo n.º 19
0
def keygen(size):
    rs = gmpy2.random_state(int(time.time()))
    p = gmpy2.next_prime(gmpy2.mpz_urandomb(rs, size))
    while p % 4 != 3:
        p = gmpy2.next_prime(p)
    q = gmpy2.next_prime(p)
    while q % 4 != 3:
        q = gmpy2.next_prime(q)
    n = p*q
    x = n-1
    return (x, n), (p, q)
Exemplo n.º 20
0
 def generateRandomness(self):
     n = self.n
     m = self.m
     T = self.T
     state = gmpy2.random_state()
     rk = [
         gmpy2.mpz_urandomb(state, self.l + self.sigma)
         for i in range(n * T)
     ]
     self.rk = rk
     self.rkf = util_fpv.vfp(rk, -DEFAULT_PRECISION)
Exemplo n.º 21
0
    def Setup(self, b=1024):
        state = self.random_state

        #generate the random integer between 0~2^b, b=1024,2048,...
        tmp1 = gmpy2.mpz_urandomb(state, b)
        tmp2 = gmpy2.mpz_urandomb(state, b)
        p = gmpy2.next_prime(tmp1)  #generate random prime number
        q = gmpy2.next_prime(tmp2)

        N = p * q
        k = gmpy2.mpz_random(state, random_SIZE)
        g = gmpy2.mpz_random(state, random_SIZE)
        g_k = g**k

        ####private parameters
        self.N = N
        self.k = k
        ###public parameters
        self.PP = {'p': p, 'g': g, 'g_k': g_k}

        return self.PP
Exemplo n.º 22
0
def encrypt(pub, plain):
    while True:
        r=mpz_urandomb(rand, pub.bits)
        if r > 0 and r < pub.n and gcd(r,pub.n)==1:
            break
#        else: 
#            print r
# for sufficiently large pub.bits comment the previous while True loop and uncomment the following line 
#    r=mpz_urandomb(rand, pub.bits)
    x = powmod(r, pub.n, pub.n_sq)
    cipher = (powmod(pub.g, plain, pub.n_sq) * x) % pub.n_sq
    return cipher
Exemplo n.º 23
0
def break_keygen(n):

    start_val = 1475784906
    while True:
        rs = gmpy2.random_state(start_val)
        p = gmpy2.next_prime(gmpy2.mpz_urandomb(rs, 2048))
        while p % 4 != 3:
            p = gmpy2.next_prime(p)

        if n % p == 0:
            print p
            break
        start_val -= 1
Exemplo n.º 24
0
    def __init__(self, seed):
        super(HomoEnc, self).__init__()

        # seed = 99999
        state = gmpy2.random_state(1)
        tmp1 = gmpy2.mpz_urandomb(state, 1024)
        tmp2 = gmpy2.mpz_urandomb(state, 1024)
        p = gmpy2.next_prime(tmp1)  #generate random prime number
        q = gmpy2.next_prime(tmp2)

        N = p * q

        k = gmpy2.mpz_random(state, 999)
        g = gmpy2.mpz_random(state, 999)
        g_k = g**k

        ####private parameters
        self.N = N
        self.k = k
        ###public parameters
        self.random_state = state
        self.PP = {'p': p, 'g': g, 'g_k': g_k}
Exemplo n.º 25
0
def encrypt(pub, plain):
    #    while True:
    #        r = generate_prime(pub.bits)
    #        if r > 0 and r < pub.n:
    #            break
    r = mpz_urandomb(rand, pub.bits)
    #        if gcd(r,pub.n)==1:
    #            break
    #        else:
    #            print r
    x = powmod(r, pub.n, pub.n_sq)
    cipher = (powmod(pub.g, plain, pub.n_sq) * x) % pub.n_sq
    return cipher
Exemplo n.º 26
0
def break_keygen(n):
    
    start_val = 1475784906
    while True:
        rs = gmpy2.random_state(start_val)
        p = gmpy2.next_prime(gmpy2.mpz_urandomb(rs, 2048))
        while p % 4 != 3:
            p = gmpy2.next_prime(p)
    
        if n % p == 0:
            print p
            break
        start_val -= 1
Exemplo n.º 27
0
def encrypt(pub, plain):
    while True:
        r = mpz_urandomb(rand, pub.bits)
        if r > 0 and r < pub.n and gcd(r, pub.n) == 1:
            break


#        else:
#            print r
# for sufficiently large pub.bits comment the previous while True loop and uncomment the following line
#    r=mpz_urandomb(rand, pub.bits)
    x = powmod(r, pub.n, pub.n_sq)
    cipher = (powmod(pub.g, plain, pub.n_sq) * x) % pub.n_sq
    return cipher
Exemplo n.º 28
0
    def __init__(self, usk_setup, usk_client, key_length=DEFAULT_KEYSIZE):
        """Need one usk for each client, and a usk for the actuator, for 
		assigning the labels for the refreshed values. For simplicity, in 
		this implementation, we have one client representing the setup and 
		one client representing the sensors."""
        self.usk = usk_setup, usk_client
        self.usk_a = gmpy2.mpz_urandomb(gmpy2.random_state(), DEFAULT_SEEDSIZE)
        pubkey, privkey = LabHE.generate_LabHE_keypair(self.usk, key_length)
        msk = privkey.msk
        upk = privkey.upk
        self.msk = msk
        self.mpk = pubkey.Pai_key
        self.upk = upk
        self.privkey = privkey
        self.pubkey = pubkey
Exemplo n.º 29
0
 def gen_rands(self):
     n = self.n
     Kc = self.Kc
     Kw = self.Kw
     nc = self.nc
     T = self.T
     N_len = self.pubkey.n.bit_length()
     random_state = gmpy2.random_state(seed)
     coinsP = [
         gmpy2.mpz_urandomb(random_state, N_len - 1)
         for i in range(0, T * n + (T - 1) * nc * Kw + nc * Kc)
     ]
     coinsP = [
         gmpy2.powmod(x, self.pubkey.n, self.pubkey.nsquare) for x in coinsP
     ]
     self.coinsP = coinsP
Exemplo n.º 30
0
    def computeGamma3(self):
        lf = DEFAULT_PRECISION
        # Compute LCB encrypted
        prod_LCB = Mult3Matrix(self.enc_L, self.enc_C, self.enc_B,
                               self.enc_bLC, self.enc_bLB, self.enc_bCB)
        self.enc_LCB = prod_LCB

        # Compute Gamma3 = (I-LC)B = B - LCB, they have different precisions
        enc_Gamma3 = np.dot(
            self.enc_B, 2**(2 * lf) * np.eye(self.m, dtype=object)) - prod_LCB

        rGamma3 = [[
            gmpy2.mpz_urandomb(gmpy2.random_state(),
                               self.l + 2 * lf + self.sigma)
            for i in range(self.m)
        ] for j in range(self.n)]

        self.rGamma3 = util_fpv.vfp(rGamma3, -2 * lf)

        return enc_Gamma3 + rGamma3
Exemplo n.º 31
0
 def gen_rands(self, DGK_pubkey):  ### CHECK SIZES
     self.DGK_pubkey = DGK_pubkey
     T = self.T
     nc = self.nc
     m = self.m
     l = self.l
     lf = DEFAULT_PRECISION
     sigma = self.sigma
     Kc = self.Kc
     Kw = self.Kw
     random_state = gmpy2.random_state(seed)
     filePath = Path('Randomness/' + str(l + sigma) + '.txt')
     if filePath.is_file():
         with open(filePath) as file:
             # Noise for updating the iterate
             rn1 = [[[int(next(file)), int(next(file))]
                     for x in range(0, 2 * nc)]
                    for y in range(0, Kc + (T - 1) * Kw)]
             # Noise for comparison
             rn2 = [[int(next(file)) for x in range(0, nc)]
                    for y in range(0, 2 * Kc + 2 * (T - 1) * Kw)]
     else:
         rn1 = [[[
             gmpy2.mpz_urandomb(random_state, l + sigma),
             gmpy2.mpz_urandomb(random_state, l + sigma)
         ] for i in range(0, 2 * nc)] for k in range(0, Kc + (T - 1) * Kw)]
         rn2 = [[
             gmpy2.mpz_urandomb(random_state, l + sigma)
             for i in range(0, nc)
         ] for k in range(0, 2 * Kc + 2 * (T - 1) * Kw)]
     self.obfuscations = rn1
     self.rn = rn2
     # Noise for Paillier encryption
     filePath = Path('Randomness/' + str(self.N_len) + '.txt')
     if filePath.is_file():
         with open(filePath) as file:
             coinsP = [
                 int(next(file))
                 for x in range(0, 4 * (T - 1) * nc * Kw + 4 * nc * Kc)
             ]
     else:
         coinsP = [
             gmpy2.mpz_urandomb(random_state, self.N_len - 1)
             for i in range(0, 4 * (T - 1) * nc * Kw + 4 * nc * Kc)
         ]
     coinsP = [
         gmpy2.powmod(x, self.Np, self.pubkey.nsquare) for x in coinsP
     ]
     # Noise for DGK encryption
     filePath = Path('Randomness/' + str(2 * DEFAULT_DGK) + '.txt')
     if filePath.is_file():
         with open(filePath) as file:
             coinsDGK = [
                 int(next(file)) for x in range(
                     0, 3 * (l + 1) * nc * Kc + 3 * (l + 1) * nc * Kw *
                     (T - 1))
             ]
     else:
         coinsDGK = [
             gmpy2.mpz_urandomb(random_state, 2 * DEFAULT_DGK)
             for i in range(
                 0, 3 * (l + 1) * nc * Kc + 3 * (l + 1) * nc * Kw * (T - 1))
         ]
     coinsDGK = [
         gmpy2.powmod(self.DGK_pubkey.h, x, self.DGK_pubkey.n)
         for x in coinsDGK
     ]
     self.coinsDGK = coinsDGK
     # Noise for truncation
     filePath = Path('Randomness/' + str(l + 2 * lf + sigma) + '.txt')
     if filePath.is_file():
         with open(filePath) as file:
             rn = [
                 int(next(file))
                 for x in range(0, nc * Kc + nc * Kw * (T - 1))
             ]
     else:
         rn = [
             gmpy2.mpz_urandomb(random_state, l + 2 * lf + sigma)
             for i in range(0, nc * Kc + nc * Kw * (T - 1))
         ]
     self.fixedNoise = encrypt_vector(self.pubkey, rn)  # ,coinsP[-2*nc*K:])
     er = [-fp(x, -2 * lf) for x in rn]
     er = encrypt_vector(self.pubkey, er)  # ,coinsP[-2*nc*K:-nc*K])
     self.er = er
     # coinsP = coinsP[:-3*nc*K]
     self.coinsP = coinsP
Exemplo n.º 32
0
def random_from_interval(random_state, low, high, m=32):
    M = int(g.ceil(g.log2(high)))
    random = g.mpz_urandomb(random_state, M + m)
    c = g.add(g.f_mod(random, g.add(g.sub(high, low), 1)), low)
    return c
Exemplo n.º 33
0
def getprime(rs):
    # 生成长度为1024比特的素数
    p = gmpy2.mpz_urandomb(rs, 1024)
    while not gmpy2.is_prime(p):
        p = p + 1
    return p
Exemplo n.º 34
0
Arquivo: PVSS.py Projeto: dat96le/rng
def findPrime(nbits):
    rs = gmpy2.random_state(gmpy2.f_mod(mpz(time.time()), 60))
    test = mpz(1)
    while not gmpy2.is_prime(test):
        test = gmpy2.mpz_urandomb(rs, nbits - 1) + 2**(nbits - 1)
    return test
Exemplo n.º 35
0
def get_prime(rs):
    p = gmpy2.mpz_urandomb(rs, 1024)
    while not gmpy2.is_prime(p):
        p = p + 1
    return p
Exemplo n.º 36
0
def generate_random(bits):
    possible = mpz(2)**(bits - 1) + mpz_urandomb(rand, bits - 1)
    return possible
Exemplo n.º 37
0
    return P


def E(P, p, x):
    s = Num(0, 0)
    for e in P.keys():
        s += x.powmod(e, p) * Num(P[e], 0)
        s %= p
    return s


if __name__ == "__main__":
    n = 256
    s = gmpy2.random_state(int(os.urandom(128).encode("hex"), 16))
    while True:
        p = gmpy2.next_prime(gmpy2.mpz_urandomb(s, n) | (o << (n - 1)))
        if p.num_digits(2) == n and p % 4 == 3:
            break

    print "here is a prime number"
    print p

    print "give me a polynomial and ill make some shares and a secret based on your polynomial"
    i = raw_input("> ")
    i = i.strip().replace(" ", "")

    print "what is the threshold?"
    t = int(raw_input("> "))

    if t <= 9000:
        print "it's not over 9000"