예제 #1
0
def setup():
    print("SETUP:")
    print("1. Select random l_p-bit primes and modulus n = pq")
    while True:
        p, q = randomPrime(l_p), randomPrime(l_p)
        if isPrime(p) and isPrime(q) and p != q:
            n = p * q
            phi_n = (p - 1) * (q - 1)
            break

    print("2. Choose random a, a_0, g, h in QR(n)")
    while True:
        g = random(n)
        if is_cyclic(g, n):
            g = g**2
            break
    a, a_0, h = [(g**random(n)) % n for _ in range(3)]

    print("3. Choose random secret element x and set public key y = g**x")
    x = random(phi_n)
    y = (g**x) % n

    print("4. The group public key Y: (n, a, a_0, y, g, h)")
    Y = {"n": n, "a": a, "a_0": a_0, "y": y, "g": g, "h": h}

    print("5. Corresponding secret key S: (p, q, phi_n, x)")
    S = {"p": p, "q": q, "phi_n": phi_n, "x": x}
    return (Y, S)
예제 #2
0
    def keygen(self, secparam=512, p=0, q=0):
        if (p == 0):
            pprime = randomPrime(secparam)
            while (not isPrime(2 * pprime + 1)):
                pprime = randomPrime(secparam)
            p = 2 * pprime + 1
            print(p)

        if (q == 0):
            qprime = randomPrime(secparam)
            while (not isPrime(2 * qprime + 1)):
                qprime = randomPrime(secparam)
            q = 2 * qprime + 1
            print(q)

        N = p * q

        a = randomQR(N)
        b = randomQR(N)
        c = randomQR(N)

        pk = {'N': N, 'a': a, 'b': b, 'c': c}
        sk = {'p': p, 'q': q}

        return (pk, sk)
예제 #3
0
파일: pksig_cl03.py 프로젝트: FinalF/charm
    def keygen(self, secparam=512, p=0, q=0):
        if(p == 0):
            pprime = randomPrime(secparam)
            while(not isPrime(2*pprime + 1)):
                pprime = randomPrime(secparam)
            p = 2 * pprime + 1
            print(p)

        if(q == 0):
            qprime = randomPrime(secparam)
            while(not isPrime(2*qprime + 1)):
                qprime = randomPrime(secparam)
            q = 2 * qprime + 1
            print(q)

        N = p * q

        a = randomQR(N)
        b = randomQR(N)
        c = randomQR(N)

        pk = { 'N':N, 'a':a, 'b':b, 'c':c }
        sk = { 'p':p, 'q':q }

        return (pk, sk)
예제 #4
0
파일: pkenc_rsa.py 프로젝트: FinalF/charm
 def paramgen(self, secparam):
     while True:
         p, q = randomPrime(secparam), randomPrime(secparam)
         if isPrime(p) and isPrime(q) and p != q:
             N = p * q
             phi_N = (p - 1) * (q - 1)
             break
     return (p, q, N, phi_N)
예제 #5
0
 def paramgen(self, secparam):
     while True:
         p, q = randomPrime(secparam), randomPrime(secparam)
         if isPrime(p) and isPrime(q) and p != q:
             N = p * q
             phi_N = (p - 1) * (q - 1)
             break
     return (p, q, N, phi_N)
예제 #6
0
 def setparam(self, p, q): 
     if p == (2 * q) + 1 and isPrime(p) and isPrime(q):
         self.p = integer(p)
         self.q = integer(q)
         return True
     else:
         print("p and q are not safe primes!")
     return False
예제 #7
0
 def paramgen(self, secparam):
     while True:
        p, q = randomPrime(secparam), randomPrime(secparam)
        if isPrime(p) and isPrime(q) and gcd(p * q, (p - 1) * (q - 1)) == 1:
           break
     self.p = p
     self.q = q
     return (p, q, p * q)    
예제 #8
0
 def setparam(self, p, q):
     if p == (2 * q) + 1 and isPrime(p) and isPrime(q):
         self.p = integer(p)
         self.q = integer(q)
         return True
     else:
         print("p and q are not safe primes!")
     return False
예제 #9
0
 def paramgen(self, bits, r=2):
     # determine which group
     while True:
         self.p = randomPrime(bits, 1)
         self.q = (self.p - 1) / 2
         if (isPrime(self.p) and isPrime(self.q)):
             break
     self.r = r
     return None
예제 #10
0
 def setparam(self, p, q):
     if isPrime(p) and isPrime(q) and p != q:
         self.p = integer(p)
         self.q = integer(q)
         self.n = self.p * self.q
         return True
     else:
         print("p and q are not primes!")
     return False
예제 #11
0
 def setparam(self, p, q): 
     if isPrime(p) and isPrime(q) and p != q:
         self.p = integer(p)
         self.q = integer(q)
         self.n = self.p * self.q
         return True
     else:
         print("p and q are not primes!")
     return False
예제 #12
0
 def paramgen(self, bits, r=2):
     # determine which group
     while True:
         self.p = randomPrime(bits, 1)
         self.q = (self.p - 1) / 2
         if (isPrime(self.p) and isPrime(self.q)):
             break
     self.r = r
     return None    
예제 #13
0
 def paramgen(self, secparam):
     while True:
         p, q = randomPrime(secparam), randomPrime(secparam)
         if isPrime(p) and isPrime(q) and gcd(p * q,
                                              (p - 1) * (q - 1)) == 1:
             break
     self.p = p
     self.q = q
     return (p, q, p * q)
예제 #14
0
 def testDefaultParams(self):
     p = self.params.p
     q = self.params.q
     g = self.params.g
     assert getMod(g) == p
     assert isPrime(p)
     assert isPrime(q)
     assert p != q
     assert p == 2*q + 1
     assert bitsize(p) >= 1024
     assert bitsize(q) >= 1023
예제 #15
0
    def generatePrimes(self, n):
        while True:
            p = randomPrime(n)
            if isPrime(p) and (((p - 3) % 4) == 0):
                break

        while True:
            q = randomPrime(n)
            if isPrime(q) and (((q - 3) % 4) == 0) and not (q == p):
                break

        return (p, q)
예제 #16
0
    def generatePrimes(self, n):
        while True:
            p = randomPrime(n)
            if (isPrime(p) and (((p - 3) % 4) == 0)):
                break

        while True:
            q = randomPrime(n)
            if (isPrime(q) and (((q - 3) % 4) == 0) and not (q == p)):
                break

        return (p, q)
예제 #17
0
    def paramgen(self, secparam):
        while True:
            p = randomPrime(secparam)
            if isPrime(p) and (((p-3)%4) == 0):
                break
        while True:
            q = randomPrime(secparam)
            if isPrime(q) and (((q-3)%4) == 0) and not(q == p):
                break
        N = p * q
        yp = (p % q) ** -1
        yq = (q % p) ** -1

        return (p, yp, q, yq, N)
예제 #18
0
    def verify(self, pk, message, sig):
        if debug: print("\nVERIFY\n\n")
        sigma1, r, s, e = sig['sigma1'], sig['r'], sig['s'], sig['e']
        K, L, c, keyLength, u, h, N = pk['K'], pk['L'], pk['c'], pk[
            'length'], pk['u'], pk['h'], pk['N']

        # Make sure that 0 < s < 2^{keylength/2}, else reject the signature
        if not (0 < s and s < (2**(keyLength / 2))):
            return False

        # Compute e = H_k(s) and reject the signature if it's not prime
        ei = self.HW_hash(K, c, s, keyLength) % N
        if not isPrime(ei):
            if debug: print("ei not prime")
            return False

        # Compute Y = sigma1^{2*ceil(log2(s))}
        s1 = integer(2**(math.ceil(log[2](s))))
        Y = (sigma1**s1) % N

        # Hash the mesage using the chameleon hash with fixed randomness r
        (x, r2) = self.ChameleonHash.hash(L, message, r)

        lhs = (Y**ei) % N
        rhs = ((u**x) * h) % N
        if debug:
            print("lhs =>", lhs)
            print("rhs =>", rhs)
        # Verify that Y^e = (u^x h) mod N.  If so, accept the signature
        if lhs == rhs:
            return True
        # Default: reject the signature
        return False
예제 #19
0
    def sign(self, pk, sk, message, s=0):
        if debug: print("Sign...")
        L, K, c, keyLength, u, h, N = pk['L'], pk['K'], pk['c'], pk['length'], pk['u'], pk['h'], pk['N']
        p, q = sk['p'], sk['q']
        # Use internal state counter if none was provided
        if (s == 0):
          s = self.state
          self.state += 1
          s += 1

        # Hash the message using the chameleon hash under params L to obtain (x, r)
        (x, r) = self.ChameleonHash.hash(L, message);
        # Compute e = H_k(s) and check whether it's prime. If not, increment s and repeat.
        phi_N = (p-1)*(q-1)
        e = self.HW_hash(K, c, s, keyLength)
        e1 = e % phi_N
        e2 = e % N
        
        while (not (isPrime(e2))) or (not gcd(e1, phi_N) == 1):
            s += 1
            e = self.HW_hash(K, c, s, keyLength)
            e1 = e % phi_N
            e2 = e % N
        e = e1

        # Compute B = SQRT(u^x * h)^ceil(log_2(s)) mod N
        # Note that SQRT requires the factorization p, q
        temp = ((u ** x) * h) % N
        power = ((((p-1)*(q-1))+4)/8) ** int(math.ceil(log[2](s)))
        B = temp ** power
        sigma1 = (B ** (e ** -1)) % N

        # Update internal state counter and return sig = (sigma1, r, s)
        self.state = s
        return { 'sigma1':sigma1, 'r': r, 's': s, 'e':e }
예제 #20
0
    def verify(self, pk, message, sig):
        if debug: print("\nVERIFY\n\n")
        sigma1, r, s, e = sig['sigma1'], sig['r'], sig['s'], sig['e']
        K, L, c, keyLength, u, h, N = pk['K'], pk['L'], pk['c'], pk['length'], pk['u'], pk['h'], pk['N']
    
        # Make sure that 0 < s < 2^{keylength/2}, else reject the signature
        if not (0 < s and s < (2 ** int(keyLength/2))):
            return False

        # Compute e = H_k(s) and reject the signature if it's not prime
        ei = self.HW_hash(K, c, s, keyLength) % N
        if not isPrime(ei):
            if debug: print("ei not prime")
            return False
        
        # Compute Y = sigma1^{2*ceil(log2(s))}
        s1 = integer(2 ** int(math.ceil(log[2](s))))
        Y = (sigma1 ** s1) % N
        
        # Hash the mesage using the chameleon hash with fixed randomness r
        (x, r2) = self.ChameleonHash.hash(L, message, r)

        lhs = (Y ** ei) % N
        rhs = ((u ** x) * h) % N
        if debug:
            print("lhs =>", lhs)
            print("rhs =>", rhs)
        # Verify that Y^e = (u^x h) mod N.  If so, accept the signature
        if lhs == rhs:
            return True
        # Default: reject the signature
        return False
예제 #21
0
    def __init__(self, secparam):

        # generate p,q
        while True:
            p, q = randomPrime(secparam), randomPrime(secparam)
            if isPrime(p) and isPrime(q) and p != q:
                N = p * q
                phi = (p - 1) * (q - 1)
                break

        # calculate private key and public key
        while True:
            e = random(phi)
            if not gcd(e, phi) == 1:
                continue
            d = e**-1
            break

        # prepare public key
        self.pk = {'N': N, 'e': toInt(e)}

        # prepare private key
        self.sk = {'phi': phi, 'd': d, 'N': N}
예제 #22
0
    def __init__(self, l, p, q, secparam, context):
        self.secparam = secparam
        self.l = l
        self.context = context

        self.pksig = 0

        if (p == 0):
            pprime = randomPrime(secparam)
            while (not isPrime(2 * pprime + 1)):
                pprime = randomPrime(secparam)

            self.p = integer(2 * pprime + 1)
        else:
            self.p = p

        if (q == 0):
            qprime = randomPrime(secparam)
            while (not isPrime(2 * qprime + 1)):
                qprime = randomPrime(secparam)

            self.q = integer(2 * qprime + 1)
        else:
            self.q = q
예제 #23
0
  def __init__(self, l, p, q, secparam, context):
    self.secparam = secparam
    self.l = l
    self.context = context
    
    self.pksig = 0

    if(p == 0):
      pprime = randomPrime(secparam)
      while(not isPrime(2*pprime + 1)):
        pprime = randomPrime(secparam)
      
      self.p = integer(2 * pprime + 1) 
    else:
      self.p = p  
    
    if(q == 0):
      qprime = randomPrime(secparam)
      while(not isPrime(2*qprime + 1)):
        qprime = randomPrime(secparam)
      
      self.q = integer(2 * qprime + 1)
    else:
      self.q = q
def key_gen(key_size, message_elem_bit_len, vector_len):
    """
    Generate keys for vector commitment
    :param key_size: security key size (k in the paper)
    :param message_elem_bit_len: length of message in bits (l in the paper)
    :param vector_len: length of commitment vector (q in the paper)
    :return:
    """
    k = key_size
    l = message_elem_bit_len
    q = vector_len

    private_key = rsa.generate_private_key(public_exponent=65537,
                                           key_size=k,
                                           backend=default_backend())
    private_numbers = private_key.private_numbers()

    n = private_numbers.public_numbers.n
    p_1 = private_numbers.p
    p_2 = private_numbers.q

    # logger.info(p_1)
    # logger.info(p_2)

    phi_n = (p_1 - 1) * (p_2 - 1)

    # generate list of primes [e_1,...,e_q], each has length (l+1)
    e = list()
    while True:
        tmp_prime = reduce(randomPrime(l + 1) % n)
        if isPrime(tmp_prime) and phi_n % int(tmp_prime) != 0:
            e.append(int(tmp_prime))
            if len(e) == q:
                break

    a = random(n)

    s = list()
    for i in range(q):
        tmp_exponent = integer(1) % n
        for j in range(q):
            if j != i:
                tmp_exponent = reduce(tmp_exponent * (integer(e[j]) % n))
        s_i = reduce(a**tmp_exponent)
        s.append(int(s_i))

    return n, int(a), s, e, p_1, p_2
예제 #25
0
def join_3(gm):
    print("4. GM checks C2 and computes random e_i prime")
    if not is_cyclic(gm['C_2'], gm['n']):
        raise ValueError("FUCKUP")
        return {"status": "JOIN ERROR"}

    while True:
        e = integer(rnd.randrange(T[0], T[1]))
        if not isPrime(e):
            continue

        d = (e % gm['phi_n'])**-1
        A = ((gm['C_2'] * gm['a_0'])**d) % gm['n']
        break

    gm['e'] = e
    gm['A'] = A

    print("True")

    return {'A': A, 'e': e, 'status': 'OK'}
예제 #26
0
    def sign(self, pk, sk, message, s=0):
        if debug: print("Sign...")
        L, K, c, keyLength, u, h, N = pk['L'], pk['K'], pk['c'], pk[
            'length'], pk['u'], pk['h'], pk['N']
        p, q = sk['p'], sk['q']
        # Use internal state counter if none was provided
        if (s == 0):
            s = self.state
            self.state += 1
            s += 1

        # Hash the message using the chameleon hash under params L to obtain (x, r)
        (x, r) = self.ChameleonHash.hash(L, message)
        # Compute e = H_k(s) and check whether it's prime. If not, increment s and repeat.
        phi_N = (p - 1) * (q - 1)
        e = self.HW_hash(K, c, s, keyLength)
        e1 = e % phi_N
        e2 = e % N

        while (not (isPrime(e2))) or (not gcd(e1, phi_N) == 1):
            s += 1
            e = self.HW_hash(K, c, s, keyLength)
            e1 = e % phi_N
            e2 = e % N
        e = e1

        # Compute B = SQRT(u^x * h)^ceil(log_2(s)) mod N
        # Note that SQRT requires the factorization p, q
        temp = ((u**x) * h) % N
        power = ((((p - 1) * (q - 1)) + 4) / 8)**(math.ceil(log[2](s)))
        B = temp**power
        sigma1 = (B**(e**-1)) % N

        # Update internal state counter and return sig = (sigma1, r, s)
        self.state = s
        return {'sigma1': sigma1, 'r': r, 's': s, 'e': e}
예제 #27
0
파일: party_A.py 프로젝트: eldron/AKE_chen
    bits = 2048
elif security_level == 128:
    bits = 3072
elif security_level == 256:
    bits = 15360

group_order_bits = 2 * security_level
group_p = 0  # the prime number for mod calculation

group_order = randomPrime(group_order_bits)
#print('group_order = ', group_order)

while True:
    random_k_value = randomBits(bits - group_order_bits)
    group_p = random_k_value * group_order + 1
    if isPrime(group_p):
        break
#print('group_p = ', group_p)

group_g = 0
while True:
    i = random(group_p)
    tmp1 = (group_p - 1) / group_order
    tmp2 = (i**tmp1) % group_p
    if tmp2 != 1 and i > 1:
        group_g = tmp2
        break

#print('group_g = ', group_g)
time1 = time.time()
예제 #28
0
  def roundNumber2IRMA(self, U, attr, n2):
    
    offset = integer(1 << (le - 1))

    while True:
      e = randomBits(lePrime - 1)
      e = e + offset

      if isPrime(e):
        break
    
    vTilde = integer(randomBits(lv - 1))
        
    vPrimePrime = (2 ** (lv - 1)) + vTilde    
    
    sigA = self.signAttributesLong(attr, vPrimePrime, U, e)    

    A = sigA['A']
    Q = sigA['Q']
    
    phi_N = (self.sk_i['p']-1)*(self.sk_i['q']-1)
    e2 = e % phi_N
    
    r = randomPrime(le)    
            
    Atilde = (Q ** r) % self.pk_i['N']

    list_ints = []
    list_ints.append(int(self.context))
    list_ints.append(int(Q))
    list_ints.append(int(A))
    list_ints.append(int(n2))
    list_ints.append(int(Atilde))
                  
    ber_context =  univ.Integer(list_ints[0])
    ber_q = univ.Integer(list_ints[1])
    ber_a = univ.Integer(list_ints[2])
    ber_n2 = univ.Integer(list_ints[3])
    ber_atilde = univ.Integer(list_ints[4])

    # ints

    subheader = "0201" + "{:02x}".format(len(list_ints))
      
    asn1_rep = subheader + ber_encoder.encode(ber_context).encode('hex') + \
                ber_encoder.encode(ber_q).encode('hex') + \
                ber_encoder.encode(ber_a).encode('hex') + \
                ber_encoder.encode(ber_n2).encode('hex') + \
                ber_encoder.encode(ber_atilde).encode('hex')
      
    # header
        
    asn1_rep_h = asn1_rep.decode("hex")
      
    m_len = len(asn1_rep_h)      

    i = 0
      
    len_code = []
      
    if (m_len <= 0x7f):
      len_code[i] = hex(m_len)                          
    else:
      j = 0x80;

      while (0 < m_len):
        len_code.append("{:02x}".format(m_len & 0xff))
        m_len = m_len >> 8
        j = j + 1

      len_code.append("{:02x}".format(j))
      
    len_code.reverse()

    header = "30" + "".join(len_code) # 0x30, SEQ     

    asn1_rep = header + asn1_rep
            
    s6 = hashlib.new('sha256')
    s6.update(asn1_rep.decode("hex"))

    cPrimeHex = s6.hexdigest()
    cPrime = integer(s6.digest())

    e2Prime = e2 ** - 1

    pPrimeQprime = ((self.sk_i['p'] - 1)/2)*((self.sk_i['q'] - 1)/2)

    Se = (r - (cPrime * integer(e2Prime))) % pPrimeQprime
                        
    signature = { 'A':A, 'e':e, 'vPrimePrime':vPrimePrime }
    P2 = { 'Se':Se, 'cPrime':cPrimeHex }
    
    return (signature, P2)
예제 #29
0
    bits = 3072
elif security_level == 256:
    bits = 15360

prime_bits = bits // 2
group_order_bits = 2 * security_level

# generate p, p_prime, q, q_prime
p = 0
p_prime = 0
q = 0
q_prime = 0
while True:
    p = randomPrime(prime_bits, 1)
    p_prime = (p - 1) / 2
    if (isPrime(p) and isPrime(p_prime)):
        break

while True:
    q = randomPrime(prime_bits, 1)
    q_prime = (q - 1) / 2
    if (isPrime(q) and isPrime(q_prime)):
        break
N = p * q
group_order = 2 * p_prime * q_prime  # order of L_DCR
N_square = N * N

print('p = ', p)
print('q = ', q)
# search the generator for L_DCR
tmp = 0