Ejemplo n.º 1
0
    def round_1(self, n1):

        Ro = self.pk_i['Ro']

        df02_commit = CM_DF02()
        pk_commit = {'S': self.pk_i['S'], 'Z': Ro, 'N': self.pk_i['N']}
        (U, self.vPrime) = df02_commit.commit(pk_commit, self.ms, (ln + lo))

        mTilde = integer(randomBits(lm + lo + lh + 1))
        (Utilde, vPrimeTilde) = df02_commit.commit(pk_commit, mTilde,
                                                   (lm + lo + lh + 1))

        s1 = hashlib.new('sha256')

        s1.update(Conversion.IP2OS(self.context))
        s1.update(Conversion.IP2OS(U))
        s1.update(Conversion.IP2OS(Utilde))
        s1.update(Conversion.IP2OS(n1))

        c = integer(s1.digest())

        # Responses to challenge

        vPrimeHat = vPrimeTilde + (c * self.vPrime)
        sHat = mTilde + (c * self.ms)

        p1 = {'c': c, 'vPrimeHat': vPrimeHat, 'sHat': sHat, 'U': U}
        n2 = integer(randomBits(lo))

        return p1, n2
Ejemplo n.º 2
0
  def roundNumber1(self, n1):

    Ro = self.pk_i['Ro']
    
    df02_commit = CM_DF02()
    pk_commit = { 'S':self.pk_i['S'], 'Z':Ro, 'N':self.pk_i['N'] }
    (U, self.vPrime) = df02_commit.commit(pk_commit, self.ms, (ln + lo))
    
    mTilde = integer(randomBits(lm + lo + lh + 1))
    (Utilde, vPrimeTilde) = df02_commit.commit(pk_commit, mTilde, (lm + lo + lh + 1))

    s1 = hashlib.new('sha256')
    
    s1.update(Conversion.IP2OS(self.context))
    s1.update(Conversion.IP2OS(U))
    s1.update(Conversion.IP2OS(Utilde))
    s1.update(Conversion.IP2OS(n1))

    c = integer(s1.digest())

    # Responses to challenge
    
    vPrimeHat = vPrimeTilde + (c * self.vPrime)
    sHat = mTilde + (c * self.ms)  

    p1 = { 'c':c, 'vPrimeHat':vPrimeHat, 'sHat':sHat, 'U':U }      
    n2 = integer(randomBits(lo))
    
    return (p1, n2)
Ejemplo n.º 3
0
  def roundNumber1(self, n1):

    # U: as IRMA does ms and Ro only

    Ro = self.pk_i['Ro']
    
    df02_commit = CM_DF02()
    pk_commit = { 'S':self.pk_i['S'], 'Z':Ro, 'N':self.pk_i['N'] }
    (U, self.vPrime) = df02_commit.commit(pk_commit, self.ms, (ln + lo))
    
    #U = (self.pk_i['S'] ** self.vPrime) * (self.pk_i['Ro'] ** self.ms)

    #print "Recipient, U, round1", U
 
    #sU = deepcopy(int(U))
    #print "bakcup justo despues, sU", sU

    
    #self.vPrime = vPrime
        
    # P1:

    mTilde = integer(randomBits(lm + lo + lh + 1))
    (Utilde, vPrimeTilde) = df02_commit.commit(pk_commit, mTilde, (lm + lo + lh + 1))

    # CTilde = no lo hacemos ahora, IRMA no lo hace    
    # Fiat-Shamir challenge, c = H(context | U | UTilde | nonce)

    s1 = hashlib.new('sha256')
    
    s1.update(Conversion.IP2OS(self.context))
    s1.update(Conversion.IP2OS(U))
    s1.update(Conversion.IP2OS(Utilde))
    s1.update(Conversion.IP2OS(n1))

    c = integer(s1.digest())

    # Responses to challenge
    
    vPrimeHat = vPrimeTilde + (c * self.vPrime)
    sHat = mTilde + (c * self.ms)  

    p1 = { 'c':c, 'vPrimeHat':vPrimeHat, 'sHat':sHat, 'U':U }      
    n2 = integer(randomBits(lo))

    #print "Recipient, U, round1 - BEFORE RETURNING", U
    #print "backup", sU
    
    return (p1, n2)
Ejemplo n.º 4
0
    def keygen(self, keyLength=1024, p=0, q=0):
        # Generate a Blum-Williams integer N of 'key_length' bits with factorization p,q
        if p == 0 or q == 0:
            (p, q) = self.BWInt.generatePrimes(int(keyLength / 2))
        # Generate random u,h \in QR_N and a random c \in {0,1}^|N|
        N = p * q
        u = randomQR(N)
        h = randomQR(N)
        c = randomBits(keyLength)  #PRNG_generate_bits(key_length)

        K = self.Prf.keygen(keyLength)
        self.state = 0

        # Generate the Chameleon hash parameters.  We do not need the secret params.
        (L, secret) = self.ChameleonHash.paramgen(keyLength, p, q)

        # Assemble the public and secret keys
        pk = {
            'length': keyLength,
            'N': N,
            'u': u,
            'h': h,
            'c': c,
            'K': K,
            'L': L
        }
        sk = {'p': p, 'q': q}
        return (pk, sk)
Ejemplo n.º 5
0
    def encrypt(self, pk, ID,
                M):  # check length to make sure it is within n bits
        Q_id = group.hash(ID, G1)  #standard
        g_id = pair(Q_id, pk['P2'])
        #choose sig = {0,1}^n where n is # bits
        sig = integer(randomBits(group.secparam))
        r = h.hashToZr(sig, M)

        enc_M = self.encodeToZn(M)
        if bitsize(enc_M) <= group.messageSize():
            C = {
                'U': r * pk['P'],
                'V': sig ^ h.hashToZn(g_id**r),
                'W': enc_M ^ h.hashToZn(sig)
            }
        else:
            print("Message cannot be encoded.")
            return None

        if (debug):
            print('\nEncrypt...')
            print('r => %s' % r)
            print('sig => %s' % sig)
            print("V'  =>", g_id**r)
            print('enc_M => %s' % enc_M)
            group.debug(C)
        return C
Ejemplo n.º 6
0
    def sign(self, pk, sk, m, v=0, u=0, e=0):
            
        if (e == 0):
            e = randomPrime(le)

        lv = ln + lm + lr
    
        if (v == 0):
            v = integer(randomBits(lv))

        
        

        R = pk['R']

        Cx = 1 % pk['N']
        
        for i in range(1, len(m) + 1): 
            Cx = Cx * (R[str(i)] ** m[str(i)])

        phi_N = (sk['p']-1)*(sk['q']-1)
        e2 = e % phi_N

        if (u != 0):
            u = u % pk['N']
            Cx = Cx*u        
        
        q = pk['Z'] / (Cx*(pk['S'] ** v)) % pk['N']
        a = q ** (e2 ** -1) % pk['N']

        sig = { 'A':a, 'Q':q, 'e':e, 'v':v }

        return sig
Ejemplo n.º 7
0
    def sign(self, pk, sk, m, v=0, u=0, e=0):

        if (e == 0):
            e = randomPrime(le)

        lv = ln + lm + lr

        if (v == 0):
            v = integer(randomBits(lv))

        R = pk['R']

        Cx = 1 % pk['N']

        for i in range(1, len(m) + 1):
            Cx = Cx * (R[str(i)]**m[str(i)])

        phi_N = (sk['p'] - 1) * (sk['q'] - 1)
        e2 = e % phi_N

        if (u != 0):
            u = u % pk['N']
            Cx = Cx * u

        q = pk['Z'] / (Cx * (pk['S']**v)) % pk['N']
        a = q**(e2**-1) % pk['N']

        sig = {'A': a, 'Q': q, 'e': e, 'v': v}

        return sig
Ejemplo n.º 8
0
def prng_bits(group, bits=80):
    assert group.InitBenchmark(), "failed to init benchmark"
    group.StartBenchmark(["CpuTime"])
    for i in range(trials):
        a = group.init(ZR, randomBits(bits))
    group.EndBenchmark()
    result = (group.GetBenchmark("CpuTime") / trials) * time_in_ms
    return result
Ejemplo n.º 9
0
def prng_bits(group, bits=80):
    assert group.InitBenchmark(), "failed to init benchmark"
    group.StartBenchmark(["CpuTime"])
    for i in range(trials):
        a = group.init(ZR, randomBits(bits))
    group.EndBenchmark()
    result = (group.GetBenchmark("CpuTime") / trials) * time_in_ms
    return result
Ejemplo n.º 10
0
  def selfTest(self):
    mt = {}

    for i in range(1, self.l+1): 
      mt[str(i)] = integer(randomBits(lm)) % self.pk_i['N']
    
    signature = self.pksig.sign(self.pk_i, self.sk_i, mt)
    
    return self.verifySignature(mt, signature)
Ejemplo n.º 11
0
 def rkGen(self, params, skid, IDsrc, IDdest):
     N = integer(randomBits(group.secparam))
     K = pair(skid['skid'], group.hash(IDdest, G1))
     if(debug):
         print("\nRe-encryption key for id1 => '%s' to id2 => '%s'" % (IDsrc,IDdest))
         group.debug(skid)
         print('N => %s' % N)
         print('K => %s' % K)
     return  {'N':N, 'R':group.hash((K, IDsrc, IDdest, N), G1) * skid['skid']}
Ejemplo n.º 12
0
 def rkGen(self, params, skid, IDsrc, IDdest):
     N = integer(randomBits(group.secparam))
     K = pair(skid['skid'], group.hash(IDdest, G1))
     if(debug):
         print("\nRe-encryption key for id1 => '%s' to id2 => '%s'" % (IDsrc,IDdest))
         group.debug(skid)
         print('N => %s' % N)
         print('K => %s' % K)
     return  {'N':N, 'R':group.hash((K, IDsrc, IDdest, N), G1) * skid['skid']}
Ejemplo n.º 13
0
    def selfTest(self):
        mt = {}

        for i in range(1, self.l + 1):
            mt[str(i)] = integer(randomBits(lm)) % self.pk_i['N']

        signature = self.pksig.sign(self.pk_i, self.sk_i, mt)

        return self.verifySignature(mt, signature)
Ejemplo n.º 14
0
    def randomize(self, pk, sig):

        rA = integer(randomBits(ln + lo))
        aP = (sig['A'] * (pk['S']**rA)) % pk['N']
        vP = sig['v'] - (sig['e'] * rA)
        eP = sig['e'] - (2**(le - 1))

        sigP = {'A': aP, 'e': eP, 'v': vP}

        return sigP
Ejemplo n.º 15
0
def gen_context(apdu):
  n3 = integer(randomBits(256))
  n3 = int(n3)
  
  n3_hex = int2hex(n3)
  
  if apdu == 1:
    return map(ord, n3_hex)
  else:
    return n3_hex
Ejemplo n.º 16
0
 def randomize(self, pk, sig):
     
     rA = integer(randomBits(ln + lo))
     aP = (sig['A'] * (pk['S'] ** rA)) % pk['N'] 
     vP = sig['v'] - (sig['e'] * rA)
     eP = sig['e'] - (2 ** (le - 1))
     
     sigP = { 'A':aP, 'e':eP, 'v':vP }
     
     return sigP
Ejemplo n.º 17
0
def gen_nonce(len_nonce, apdu):
  n3 = integer(randomBits(len_nonce))
  n3 = int(n3)
  
  n3_hex = int2hex(n3)
  
  if apdu == 1:
    return map(ord, n3_hex)
  else:
    return n3_hex
Ejemplo n.º 18
0
    def S(self, pub):
        x = randomBits(448)
        x = str(x).zfill(135)

        r = hashlib.sha256(x.encode('utf-8')).digest()

        com = hashlib.sha1(x.encode('utf-8')).digest()[:128]

        dec = x

        return (r, com, dec)
Ejemplo n.º 19
0
    def S(self, pub):
        x = randomBits(448)
        x = str(x).zfill(135) 

        r = hashlib.md5(x.encode('utf-8')).digest()

        com = hashlib.sha1(x.encode('utf-8')).digest()[:128]

        dec = x

        return (r, com, dec)
Ejemplo n.º 20
0
    def build_proof(self, credentials, predicate, n1):
        # step 0.1
        for key, value in self.m.iteritems():
            self.v_tilde[key] = integer(randomBits(lm + lo + lh))
            # print self.v_hat
        self.v_tilde['0'] = integer(randomBits(lm + lo + lh))
        cl_prover = CLProver()
        # print self.all
        # step 1.1: t-values
        t_value, common_value = cl_prover.prove(self.pk_i, credentials,
                                                predicate, self.m,
                                                self.v_tilde)

        self.t_values['Z_tilde'] = t_value
        self.common_value['A_prime'] = common_value

        # step 2.1: challenge
        h_challenge = hashlib.new('sha256')
        h_challenge.update(Conversion.IP2OS(self.context))
        h_challenge = self.__add_dict_to_hash(self.common_value, h_challenge)
        h_challenge = self.__add_dict_to_hash(self.t_values, h_challenge)
        h_challenge = self.__add_list_to_hash(
            [],
            h_challenge)  # committed, representation, nym, dnym, verenc, msg
        h_challenge.update(Conversion.IP2OS(n1))
        c = integer(h_challenge.digest())

        # print "t-value:", t_value

        # step 3.1: s-values
        s_values = cl_prover.prove(self.pk_i, credentials, predicate, self.m,
                                   self.v_tilde, self.ms, c)

        # step 4.1: return proof
        proof = {}
        proof['c'] = c
        proof['s'] = s_values
        proof['common'] = self.common_value
        return proof
Ejemplo n.º 21
0
 def commit(self, pk, msg, lr, ri=0):
     S = pk['S']
     Z = pk['Z']
     
     if (lr == 0):
         r = ri
     else:
         r = integer(randomBits(lr))
     
     c = ((Z ** msg) * (S ** r)) % pk['N']        
     d = r
     
     return (c, d)    
Ejemplo n.º 22
0
    def commit(self, pk, msg, lr, ri=0):
        S = pk['S']
        Z = pk['Z']

        if (lr == 0):
            r = ri
        else:
            r = integer(randomBits(lr))

        c = ((Z**msg) * (S**r)) % pk['N']
        d = r

        return (c, d)
Ejemplo n.º 23
0
    def prove(self, pk_i, credential, cl_predicate, m, m_tilde, ms=None, c=None):
        if not c:
            r_a = integer(randomBits(ln + lo))
            A_prime = (credential['signature']['A'] * (pk_i['S'] ** r_a)) % pk_i['N']
            v_prime = credential['signature']['v'] - (credential['signature']['e'] * r_a)
            e_prime = credential['signature']['e'] - (2 ** (le - 1))

            e_tilde = integer(randomBits(lePrime + lo + lh))
            v_prime_tilde = integer(randomBits(lv + lo + lh))

            R_tot = 1 % pk_i['N']
            for id in credential['attributes']:
                if id not in cl_predicate:
                    R_tot = R_tot * (pk_i['R'][id] ** m_tilde[id])
            R_tot = R_tot * (pk_i['Ro'] ** m_tilde['0'])

            Z_tilde1 = A_prime ** e_tilde
            Z_tilde3 = pk_i['S'] ** v_prime_tilde

            Z_tilde = (Z_tilde1 * R_tot * Z_tilde3) % pk_i['N']

            self.e_tilde = e_tilde
            self.e_prime = e_prime
            self.v_prime_tilde = v_prime_tilde
            self.v_prime = v_prime

            return Z_tilde, A_prime

        else:
            e_hat = self.e_tilde + (c * self.e_prime)
            v_prime_hat = self.v_prime_tilde + (c * self.v_prime)

            m_hat = {}
            for id in credential['attributes']:  # TODO: not in Ar (not revealed!)
                if id not in cl_predicate:
                    m_hat[id] = m_tilde[id] + (c * m[id])
            m_hat['0'] = m_tilde['0'] + (c * ms)

            return {'e_hat': e_hat, 'v_prime_hat': v_prime_hat, 'm_hat': m_hat}
Ejemplo n.º 24
0
  def roundNumber2(self, U, attr, n2):
    
    # TODO: Adaptar IRMA
    
    e = randomPrime(le)
    
    vTilde = integer(randomBits(lv - 1))
    vPrimePrime = (2 ** (lv - 1)) + vTilde    

    R = self.pk_i['R']
    Cx = 1 % self.pk_i['N']
        
    for i in range(1, len(attr) + 1): 
      Cx = Cx*(R[str(i)] ** attr[str(i)])

    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

    # The issuer creates an SPK for proving the knowledge of
    # e^(-1) according to the equivalence of A and Q^{e-1}
    
    r = randomPrime(le)    
    Atilde = (Q ** r) % self.pk_i['N']

    s3 = hashlib.new('sha256')

    s3.update(Conversion.IP2OS(self.context))
    s3.update(Conversion.IP2OS(Q))
    s3.update(Conversion.IP2OS(A))
    s3.update(Conversion.IP2OS(n2))
    s3.update(Conversion.IP2OS(Atilde))

    #print "issuer Q #1", Q
    #print "issuer A", A
    #print "issuer n2", n2
    #print "issuer Atilde", Atilde

    cPrime = integer(s3.digest())
    e2Prime = e2 ** - 1

    Se = r - (cPrime * integer(e2Prime))
            
    signature = { 'A':A, 'e':e, 'vPrimePrime':vPrimePrime }
    P2 = { 'Se':Se, 'cPrime':cPrime }
    
    return (signature, P2)
Ejemplo n.º 25
0
    def sign(self, pk, sk, m):
        e = randomPrime(le)

        ls = ln + lm + l
        s = integer(randomBits(ls))

        phi_N = (sk['p'] - 1) * (sk['q'] - 1)
        e2 = e % phi_N

        v = (((pk['a']**m) * (pk['b']**s) * pk['c'])**(e2**-1)) % pk['N']

        sig = {'e': e, 's': s, 'v': v}

        return sig
Ejemplo n.º 26
0
    def signCommit(self, pk, sk, Cx):
        e = randomPrime(le)

        ls = ln + lm + l
        rprime = integer(randomBits(ls))

        phi_N = (sk['p'] - 1) * (sk['q'] - 1)
        e2 = e % phi_N

        v = (((Cx) * (pk['b']**rprime) * pk['c'])**(e2**-1)) % pk['N']

        sig = {'e': e, 'rprime': rprime, 'v': v}

        return sig
Ejemplo n.º 27
0
    def sign(self, pk, sk, m):
        e = randomPrime(le)

        ls = ln + lm + l
        s = integer(randomBits(ls))

        phi_N = (sk['p']-1)*(sk['q']-1)
        e2 = e % phi_N
    
        v = (((pk['a'] ** m)*(pk['b'] ** s)*pk['c']) ** (e2 ** -1)) % pk['N']

        sig = { 'e':e, 's':s, 'v':v }

        return sig
Ejemplo n.º 28
0
    def signCommit(self, pk, sk, Cx):
        e = randomPrime(le)

        ls = ln + lm + l
        rprime = integer(randomBits(ls))

        phi_N = (sk['p']-1)*(sk['q']-1)
        e2 = e % phi_N
    
        v = (((Cx)*(pk['b'] ** rprime)*pk['c']) ** (e2 ** -1)) % pk['N']

        sig = { 'e':e, 'rprime':rprime, 'v':v }

        return sig
Ejemplo n.º 29
0
    def round_2(self, U, p1, attr, n2):

        if self.__verify_p1(p1):
            pass
            # print "P1 verified"
        else:
            return None

        e = randomPrime(le)

        vTilde = integer(randomBits(lv - 1))
        vPrimePrime = (2 ** (lv - 1)) + vTilde

        R = self.pk_i['R']
        Cx = 1 % self.pk_i['N']

        for i in range(1, len(attr) + 1):
            Cx = Cx * (R[str(i)] ** attr[str(i)])

        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']

        s3 = hashlib.new('sha256')

        s3.update(Conversion.IP2OS(self.context))
        s3.update(Conversion.IP2OS(Q))
        s3.update(Conversion.IP2OS(A))
        s3.update(Conversion.IP2OS(n2))
        s3.update(Conversion.IP2OS(Atilde))

        cPrime = integer(s3.digest())
        e2Prime = e2 ** - 1

        Se = r - (cPrime * integer(e2Prime))

        signature = {'A': A, 'e': e, 'vPrimePrime': vPrimePrime}
        P2 = {'Se': Se, 'cPrime': cPrime}

        print signature
        print P2
        return signature, P2
Ejemplo n.º 30
0
    def commitBlock(self, pk, msg, lr, ri=0):
        Cx = 1 % pk['N']

        R = pk['R']
        S = pk['S']

        if (lr == 0):
            r = ri
        else:
            r = integer(randomBits(lr))

        for i in range(1, len(msg) + 1):
            Cx = Cx * (R[str(i)]**msg[str(i)])

        c = (Cx * (S**r)) % pk['N']
        d = r

        return (c, d)
Ejemplo n.º 31
0
  def genRandomAttributes(self, l): 
    for i in range(1, l + 1): 
      self.m[str(i)] = integer(randomBits(lm))
  
    Ak = 1 % self.pk_i['N']
    R = self.pk_i['R']

    for i in range(1, len(self.m) + 1): 
      Ak = Ak*(R[str(i)] ** self.m[str(i)])

    Ro = self.pk_i['Ro']

    All = Ak * (Ro ** self.ms)
 
    self.all = All
    self.ak = Ak
 
    return self.m
Ejemplo n.º 32
0
    def gen_random_attributes(self, l):
        for i in range(1, l + 1):
            self.m[str(i)] = integer(randomBits(lm))

        Ak = 1 % self.pk_i['N']
        R = self.pk_i['R']

        for i in range(1, len(self.m) + 1):
            Ak = Ak * (R[str(i)]**self.m[str(i)])

        Ro = self.pk_i['Ro']

        All = Ak * (Ro**self.ms)

        self.all = All
        self.ak = Ak

        return self.m
Ejemplo n.º 33
0
    def commitBlock(self, pk, msg, lr, ri=0):
        Cx = 1 % pk['N']

        R = pk['R']
        S = pk['S']

        if (lr == 0):
            r = ri
        else:
            r = integer(randomBits(lr))
        
        for i in range(1, len(msg) + 1): 
            Cx = Cx*(R[str(i)] ** msg[str(i)])
        
        c = (Cx * (S ** r)) % pk['N']
        d = r
        
        return (c, d)    
Ejemplo n.º 34
0
    def keygen(self, keyLength=1024, p=0, q=0):
        # Generate a Blum-Williams integer N of 'key_length' bits with factorization p,q
        if p == 0 or q == 0:
            (p, q) = self.BWInt.generatePrimes(int(keyLength/2))
        # Generate random u,h \in QR_N and a random c \in {0,1}^|N|
        N = p * q
        u = randomQR(N)
        h = randomQR(N)
        c = randomBits(keyLength)#PRNG_generate_bits(key_length)

        K = self.Prf.keygen(keyLength)
        self.state = 0
    
        # Generate the Chameleon hash parameters.  We do not need the secret params.
        (L, secret) = self.ChameleonHash.paramgen(keyLength, p, q);
    
        # Assemble the public and secret keys
        pk = { 'length': keyLength, 'N': N, 'u': u, 'h': h, 'c': c, 'K': K, 'L': L }
        sk = { 'p': p, 'q': q }
        return (pk, sk);
Ejemplo n.º 35
0
def test_vector_commitment():
    k = Config.benchmark_vector_commitment_key_sizes[0]
    l = Config.benchmark_vector_commitment_message_elem_bit_len
    q = Config.benchmark_vector_commitment_vector_lens[0]

    n, a, s, e, p_1, p_2 = vectorcommitment.key_gen(k, l, q)

    m = list()

    for i in range(q):
        m.append(int(randomBits(l)))

    c, aux = vectorcommitment.commit(m, s, n)

    for i in range(q):
        lamda_i = vectorcommitment.open(m, i, e[i], s, p_1, p_2)

        verification_result = vectorcommitment.verify(c, m[i], i, s, lamda_i,
                                                      e, n, l)
        logging.info(verification_result)
        assert verification_result
Ejemplo n.º 36
0
    def encrypt(self, pk, ID, M): # check length to make sure it is within n bits
        Q_id = group.hash(ID, G1) #standard
        g_id = pair(Q_id, pk['P2']) 
        #choose sig = {0,1}^n where n is # bits
        sig = integer(randomBits(group.secparam))
        r = h.hashToZr(sig, M)

        enc_M = self.encodeToZn(M)
        if bitsize(enc_M) <= group.messageSize():
            C = { 'U':r * pk['P'], 'V':sig ^ h.hashToZn(g_id ** r) , 'W':enc_M ^ h.hashToZn(sig) }
        else:
            print("Message cannot be encoded.")
            return None

        if(debug):
            print('\nEncrypt...')
            print('r => %s' % r)
            print('sig => %s' % sig)
            print("V'  =>", g_id ** r)
            print('enc_M => %s' % enc_M)
            group.debug(C)
        return C
Ejemplo n.º 37
0
    bits = 1024
elif security_level == 112:
    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)
Ejemplo n.º 38
0
from charm.core.math.integer import integer,isPrime,random,randomPrime,randomBits,bitsize
from charm.toolbox.conversion import Conversion
from smartcard.CardConnection import CardConnection
from smartcard.System import readers
from smartcard.util import toHexString
from functools import wraps
from irma import pin
from idemix import protocol_ibm12
from copy import deepcopy

import irma_util
import binascii
import time
import sys

context = integer(randomBits(256))

# constants

CMD_SELECT = [0x00, 0xA4, 0x04, 0x00, 0x09, 0xF8, 0x49, 0x52, 0x4D, 0x41, 0x63, 0x61, 0x72, 0x64, 0x18]
CMD_GET_CRED_LIST = [0x80, 0x3A, 0x00, 0x00]
CMD_VERIFY_PIN_ATTR = [0x00, 0x20, 0x00, 0x00, 0x08]

PIN_ATTR_DEFAULT = [0x30, 0x30, 0x30, 0x30, 0x00, 0x00, 0x00, 0x00]

CMD_PROVE_COMMITMENT = [0x80, 0x2A, 0x00, 0x00]
LEN_PC = [0x0A]

CMD_ISSUE_CRED = [0x80, 0x10, 0x00, 0x00, 0x2B]

CMD_PUBLIC_KEY_N = [0x80, 0x11, 0x00, 0x00, 0x80]
Ejemplo n.º 39
0
You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import hashlib

from charm.core.math.integer import integer, randomBits
from charm.toolbox.conversion import Conversion

from idemix.issuer import Issuer
from idemix.recipient import Recipient
from idemix.settings import lm, l, secparam
from idemix.verifier import Verifier

context = integer(randomBits(lm))

attr = {'1': 'student', '2': 'italian', '3': 'age'}
for id, value in attr.iteritems():
    h_challenge = hashlib.new('sha256')
    h_challenge.update(str(value))
    attr[id] = Conversion.bytes2integer(h_challenge.digest())

issuer = Issuer(len(attr), 0, 0, secparam, context)
pk_i, sk_i = issuer.gen_key_pair()
# print sk_i
assert issuer.selfTest()

user = Recipient(pk_i, context)
user.gen_master_secret()
user.set_attributes(attr)
Ejemplo n.º 40
0
    def get_nonce(self):
        nv = integer(randomBits(lo))

        return nv
Ejemplo n.º 41
0
    def round_0(self):
        self.n1 = integer(randomBits(lo))

        return self.n1
Ejemplo n.º 42
0
 def getRandomBits(self, length):
     i = randomBits(length)
     len = math.ceil(length / 8)
     return Conversion.IP2OS(i, len)
Ejemplo n.º 43
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)
Ejemplo n.º 44
0
  def roundNumber0(self):
    n1 = integer(randomBits(lo))

    return n1
Ejemplo n.º 45
0
def benchmark_vc_multiple():
    """
    Benchmark multiple configuration
    """
    num_runs = 1000
    assert 0 < num_runs
    for k in Config.benchmark_vector_commitment_key_sizes:
        for q in Config.benchmark_vector_commitment_vector_lens:
            l = Config.benchmark_vector_commitment_message_elem_bit_len

            logging.info(
                ('Benchmark k = {0}, q = {1}, l = {2}'.format(k, q, l)))

            time_gen = 0
            num_runs_gen = min(num_runs, 10)
            for _ in range(num_runs_gen):
                start_key_gen = time()
                n, a, s, e, p_1, p_2 = vectorcommitment.key_gen(k, l, q)
                end_key_gen = time()

                time_gen += end_key_gen - start_key_gen
            avg_time_gen = time_gen / num_runs_gen

            n, a, s, e, p_1, p_2 = vectorcommitment.key_gen(k, l, q)

            m = list()

            for i in range(q):
                m.append(int(randomBits(l)))

            time_commit = 0

            for num_run in range(num_runs):
                start_commit = time()
                c, aux = vectorcommitment.commit(m, s, n)
                end_commit = time()
                time_commit += end_commit - start_commit
            avg_time_commit = time_commit / num_runs

            c, aux = vectorcommitment.commit(m, s, n)
            commitment_size = int(math.ceil(c.bit_length() / 8))

            time_open = 0
            time_verify = 0
            open_size = 0

            for i in range(q):
                for num_run in range(num_runs):
                    start_open = time()
                    lamda_i = vectorcommitment.open(m, i, e[i], s, p_1, p_2)
                    end_open = time()
                    time_open += end_open - start_open
                lamda_i = vectorcommitment.open(m, i, e[i], s, p_1, p_2)
                open_size = int(math.ceil(lamda_i.bit_length() / 8))

                for num_run in range(num_runs):
                    start_verify = time()
                    verification_result = vectorcommitment.verify(
                        c, m[i], i, s, lamda_i, e, n, l)
                    end_verify = time()
                    time_verify += end_verify - start_verify

                    assert verification_result

            avg_time_open = time_open / (num_runs * q)
            avg_time_verify = time_verify / (num_runs * q)

            # write header
            if not os.path.isfile(Config.benchmark_output_file):
                # file not exist, create it and add header
                with open(Config.benchmark_output_file, 'a+') as f:
                    csv_writer = csv.writer(f, delimiter='\t')
                    header = [
                        'time', 'key_size', 'vector_len',
                        'message_elem_bit_len', 'avg_time_gen',
                        'avg_time_commit', 'avg_time_open', 'avg_time_verify',
                        'commitment_size', 'open_size'
                    ]
                    csv_writer.writerow(header)

            with open(Config.benchmark_output_file, 'a+') as f:
                csv_writer = csv.writer(f, delimiter='\t')
                row = [
                    datetime.strftime(datetime.now(),
                                      datasethelper.GOWALLA_TIME_PATTERN),
                    str(k),
                    str(q),
                    str(l), '{0:.6f}'.format(avg_time_gen),
                    '{0:.6f}'.format(avg_time_commit),
                    '{0:.6f}'.format(avg_time_open),
                    '{0:.6f}'.format(avg_time_verify),
                    str(commitment_size),
                    str(open_size)
                ]
                logging.info(str(row))
                csv_writer.writerow(row)
Ejemplo n.º 46
0
 def getRandomBits(self, length):
     i = randomBits(length)
     len = math.ceil(length / 8)
     return Conversion.IP2OS(i, len)
Ejemplo n.º 47
0
 def getRandomBytes(self, length):
     bits = length * 8;
     val = randomBits(bits)
     return Conversion.IP2OS(val, length)    
Ejemplo n.º 48
0
 def keygen(self, bits):
     return integer(randomBits(bits))
Ejemplo n.º 49
0
 def getRandomBytes(self, length):
     bits = length * 8
     val = randomBits(bits)
     return Conversion.IP2OS(val, length)
Ejemplo n.º 50
0
You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import hashlib

from charm.core.math.integer import integer, randomBits
from charm.toolbox.conversion import Conversion

from idemix.issuer import Issuer
from idemix.recipient import Recipient
from idemix.settings import lm, l, secparam
from idemix.verifier import Verifier

context = integer(randomBits(lm))

attr = {'1': 'student', '2': 'italian', '3': 'age'}
for id, value in attr.iteritems():
    h_challenge = hashlib.new('sha256')
    h_challenge.update(str(value))
    attr[id] = Conversion.bytes2integer(h_challenge.digest())

issuer = Issuer(len(attr), 0, 0, secparam, context)
pk_i, sk_i = issuer.gen_key_pair()
# print sk_i
assert issuer.selfTest()

user = Recipient(pk_i, context)
user.gen_master_secret()
user.set_attributes(attr)
Ejemplo n.º 51
0
 def genMasterSecret(self):
   self.ms = integer(randomBits(lm))
Ejemplo n.º 52
0
def prng_bits(bits=80):
    return group.init(ZR, randomBits(bits))
Ejemplo n.º 53
0
 def gen_master_secret(self):
     self.ms = integer(randomBits(lm))
Ejemplo n.º 54
0
print('val1 = ', val1)
print('toInt(val1) = ', toInt(val1))
g = N_square - toInt(val1)
g = g % N_square
print('g = ', g)

alpha_value = random(N_square / 2)  # of length bits
beta_value = random(N_square / 2)
hp_1_value = (g**alpha_value) % N_square
hp_2_value = (g**beta_value) % N_square

# t_1(k) and u(k) are calculated from the length of r and x
t_1_length = 2 * group_order_bits - 128  # length of IV is 16 bytes
u_length = 2 * group_order_bits - 128

r_1_value = randomBits(t_1_length)
r_2_value = randomBits(640)  # the length of r2 does not matter
r_1_bytes = Conversion.IP2OS(r_1_value, t_1_length // 8)
r_2_bytes = Conversion.IP2OS(r_2_value, 80)
t_value = randomBits(160)  # the length of t does not matter
t_bytes = Conversion.IP2OS(t_value, 20)

# session execution
e_value = randomBits(u_length)
e_bytes = Conversion.IP2OS(e_value, u_length // 8)
# set l_1, l_2 (length of the output of extractor 1 and extractor 2) to be 128 bits, the length of AES key

# hash alpha, beta, r_1 together to get lsk_A_prime
group_for_hash = PairingGroup("SS512")
waters = Waters(group_for_hash)
alpha_bytes = Conversion.IP2OS(alpha_value, bits // 8)
Ejemplo n.º 55
0
def SmallExp(bits=80):
    return group.init(ZR, randomBits(bits))
Ejemplo n.º 56
0
def prng_bits(bits=80):
	return group.init(ZR, randomBits(bits))