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
def collision(self, m, m1, xi, etd, pk): phi_NN1 = pk['phi_N'] * (xi['N1'] - etd['p1'] - etd['q1'] + 1) d = (xi['e'] ** -1) % (phi_NN1) print('d=>',d) if d == 1 / xi['e']: print('reverse') M1 = Conversion.bytes2integer(m1) M = Conversion.bytes2integer(m) h = (group.hash(M) * (xi['r'] ** xi['e'])) % (pk['N'] * xi['N1']) r1 = (((group.hash(M1) ** (-1)) * h) ** d) % (pk['N'] * xi['N1']) print("r1 =>", r1) return r1
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
def verifyProof(self, credential, predicate, P, nv): T_hat = {} T_hat['t-values'] = self.__verify_cl(credential, predicate, P) # print "That:", T_hat['t-values'] h_challenge = hashlib.new('sha256') h_challenge.update(Conversion.IP2OS(self.context)) h_challenge = self.__add_dict_to_hash(P['common'], h_challenge) h_challenge = self.__add_dict_to_hash(T_hat, h_challenge) # TODO: ricontrollare! h_challenge = self.__add_list_to_hash([], h_challenge) # committed, representation, nym, dnym, verenc, msg h_challenge.update(Conversion.IP2OS(nv)) c = integer(h_challenge.digest()) return c == P['c']
def verify_blind(self, cp, blind_signature): # Convert to modular integer dictionary sig = SigConversion.convert_dict_modint(json.loads(blind_signature)) cp_pubk = get_cp_pubkey(cp, self.timestamp, self.policy) verifier = BlindSignatureVerifier(cp_pubk) message = Conversion.OS2IP(self.pubk) return verifier.verify(sig, message)
def hash(self, pk, message, r = 0): N, J, e = pk['N'], pk['J'], pk['e'] if r == 0: r = group.random(N) M = Conversion.bytes2integer(message) h = ((J ** M) * (r ** e)) % N return (h, r)
def groupHash(self, msg, r): msg = Conversion.siginput2integer(msg) if isinstance(r, integer) == False: raise TypeError("Expected r to be of type 'integer', got " + type(r)) return self.group.hash(msg, r)
def hashcheck(self, pk, message, xi): M = Conversion.bytes2integer(message) h1 = group.hash(M) * (xi['r']**xi['e']) % (pk['N'] * xi['N1']) if h1 == xi['h']: return True else: return False
def encrypt(self, pk, m, salt=None): octetlen = int(ceil(int(pk['N']).bit_length() / 8.0)) EM = self.paddingscheme.encode(m, octetlen, "", salt) if debug: print("EM == >", EM) i = Conversion.OS2IP(EM) ip = integer(i) % pk['N'] #Convert to modular integer return (ip**pk['e']) % pk['N']
def signer_state3(self, input): print("SIGNER state #3") rnd = (integer(randomBits(80))) msg = integer(SHA1(Conversion.IP2OS(rnd))) z1 = (msg**((p - 1) / q)) % p (g, y, h, z) = Protocol.get(self, ['g', 'y', 'h', 'z']) z2 = z / z1 u = self.group.random() s1 = self.group.random() s2 = self.group.random() d = self.group.random() a = g**u b1 = (g**s1) * (z1**d) b2 = (h**s2) * (z2**d) Protocol.store(self, ('u', u), ('s1', s1), ('s2', s2), ('d', d)) Protocol.setState(self, 5) return {'rnd': rnd, 'a': a, 'b1': b1, 'b2': b2}
def HW_hash(self, key, c, input, keyLen): C = integer(c) input_size = bitsize(c) input_b = Conversion.IP2OS(input, input_size) # Return c XOR PRF(k, input), where the output of PRF is keyLength bits result = C ^ self.Prf.eval(key, input_b) return result
def hash_util(d: dict or list) -> int: try: assert type(d) == dict or type(d) == list except AssertionError: print(type(d), file=sys.stderr) hashable = json.dumps(d) hash_tmp = SHA256Hash().new(hashable.encode()) return Conversion.OS2IP(hash_tmp.digest())
def eval(self, k, input1): if type(k) == integer: h = hmac.new(serialize(k), b'', hashlib.sha1) else: h = hmac.new(serialize(integer(k)), b'', hashlib.sha1) h.update(input1) return Conversion.bytes2integer(h.hexdigest())
def hash_util(d: dict or list) -> int: """ Creates a SHA256 hash of dict or list. Merely a helper function. :param d: Input on which a hash needs to be generated. :return: (int) Hash of the input d. """ hash_tmp = SHA256Hash().new(json.dumps(d).encode()) return Conversion.OS2IP(hash_tmp.digest())
def setup_method(self, message=None): key = ECC.generate(curve='P-256') self.message = Conversion.OS2IP(key.public_key().export_key( format='DER')) if message is None else message challenge = self.signer.get_challenge() self.e = self.user.challenge_response(challenge, self.message) proofs = self.signer.get_proofs(self.e) self.sig = self.user.gen_signature(proofs)
def verify(serial_data_and_sig, public_key): verifier = RSA_Sig() data_and_sig = bytesToObject(serial_data_and_sig, IntegerGroup()) data, sig = data_and_sig sig = Conversion.IP2OS(sig) verdict = verifier.verify(public_key, data, sig) if verdict == True: return data else: return None
def sign(self, sk, M, salt=None): #apply encoding modbits = int(sk['N']).bit_length() k = int(ceil(modbits / 8.0)) emLen = int(ceil((modbits - 1) / 8.0)) em = self.paddingscheme.encode(M, modbits - 1, salt) m = Conversion.OS2IP(em) m = integer(m) % sk['N'] #ERRROR m is larger than N s = (m**sk['d']) % sk['N'] S = Conversion.IP2OS(s, k) if debug: print("Signing") print("k =>", k) print("emLen =>", emLen) print("m =>", m) print("em =>", em) print("s =>", s) print("S =>", S) return S
def verify(self, pk, M, S): modbits = int(pk['N']).bit_length() k = int(ceil(modbits / 8.0)) emLen = int(ceil((modbits - 1) / 8.0)) if len(S) != k: if debug: print("Sig is %s octets long, not %" % (len(S), k)) return False s = Conversion.OS2IP(S) s = integer(s) % pk['N'] #Convert to modular integer m = (s**pk['e']) % pk['N'] EM = Conversion.IP2OS(m, emLen) if debug: print("Verifying") print("k =>", k) print("emLen =>", emLen) print("s =>", s) print("m =>", m) print("em =>", EM) print("S =>", S) return self.paddingscheme.verify(M, EM, modbits - 1)
def challenge_response(self, input, message): rnd = input.get('rnd') a = input.get('a') b1 = input.get('b1') b2 = input.get('b2') msg = integer(Conversion.OS2IP(SHA1(Conversion.IP2OS(rnd)))) z1 = (msg**((self.p - 1) / self.q)) % self.p gamma = self.group.random() tau = self.group.random() t1 = self.group.random() t2 = self.group.random() t3 = self.group.random() t4 = self.group.random() t5 = self.group.random() zeta = self.z**gamma zeta1 = z1**gamma zeta2 = zeta / zeta1 alpha = a * (self.g**t1) * (self.y**t2) % self.p beta1 = (b1**gamma) * (self.g**t3) * (zeta1**t4) % self.p beta2 = (b2**gamma) * (self.h**t5) * (zeta2**t4) % self.p eta = self.z**tau epsilon = integer( hash_int([zeta, zeta1, alpha, beta1, beta2, eta, message ])) % self.q e = (epsilon - t2 - t4) % self.q self.__store__(self, ('z1', z1), ('zeta', zeta), ('zeta1', zeta1)) self.__store__(self, ('zeta2', zeta2), ('alpha', alpha), ('beta1', beta1), ('beta2', beta2)) self.__store__(self, ('t1', t1), ('t2', t2), ('t3', t3), ('t4', t4), ('t5', t5)) self.__store__(self, ('gamma', gamma), ('tau', tau), ('eta', eta)) return {'e': e}
def get_challenge(self): rnd = randomBits(80) msg = integer(Conversion.OS2IP(SHA1(Conversion.IP2OS(rnd)))) z1 = ((msg ** ((self.p - 1) / self.q)) % self.p) inv_z1 = (mulinv(z1, self.p)) % self.p z2 = (int(self.z) * int(inv_z1)) % self.p self.u = self.group.random() self.s1 = self.group.random() self.s2 = self.group.random() self.d = self.group.random() a = self.g ** self.u b1 = (self.g ** self.s1) * (z1 ** self.d) b2 = (self.h ** self.s2) * (z2 ** self.d) return {'rnd': rnd, 'a': a, 'b1': b1, 'b2': b2}
def __init__(self, group=None, p=0, q=0, secparam=512): self.group = group if group is not None else IntegerGroupQ() self.group.p, self.group.q, self.group.r = p, q, 2 if self.group.p == 0 or self.group.q == 0: self.group.paramgen(secparam) self.p = self.group.p self.q = self.group.q self.x, self.g, = self.group.random(), self.group.randomGen() self.z, self.h, = self.group.randomGen(), self.group.randomGen() self.y = (self.g ** self.x) % self.p hs1 = hashlib.new('sha256') hs1.update(Conversion.IP2OS(integer(self.p))) hs1.update(Conversion.IP2OS(integer(self.q))) hs1.update(Conversion.IP2OS(integer(self.g))) hs1.update(Conversion.IP2OS(integer(self.h))) hs1.update(Conversion.IP2OS(integer(self.y))) msg = integer(Conversion.OS2IP(hs1.digest())) self.z = ((msg ** ((self.p - 1) / self.q)) % self.p) self.u = None self.d = None self.s1 = None self.s2 = None
def signer_state1(self): print("SIGNER state #1") x, g, = self.group.random(), self.group.randomGen() z, h, = self.group.randomGen(), self.group.randomGen() y = g**x hs1 = hashlib.new('sha256') hs1.update(Conversion.IP2OS(integer(p))) hs1.update(Conversion.IP2OS(integer(q))) hs1.update(Conversion.IP2OS(integer(g))) hs1.update(Conversion.IP2OS(integer(h))) hs1.update(Conversion.IP2OS(integer(y))) msg = integer(hs1.digest()) z = (msg**((p - 1) / q)) % p Protocol.store(self, ('g', g), ('y', y), ('x', x), ('h', h), ('z', z)) Protocol.setState(self, 3) return {'g': g, 'y': y, 'h': h, 'z': z}
def encrypt(self, pk, m, salt=None): if (self.paddingscheme.name == "SAEPEncryptionPadding"): EM = self.paddingscheme.encode(m, pk['n'], pk['s0']) else: m = self.redundancyscheme.encode(m) octetlen = int(ceil(int(pk['N']).bit_length() / 8.0)) EM = self.paddingscheme.encode(m, octetlen, "", salt) if debug: print("EM == >", EM) i = Conversion.OS2IP(EM) ip = integer(i) % pk['N'] #Convert to modular integer return (ip**2) % pk['N']
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
def round_3(self, signature, P2, n2): vPrimePrime = signature['vPrimePrime'] A = signature['A'] e = signature['e'] v = vPrimePrime + self.vPrime cPrime = P2['cPrime'] Se = P2['Se'] Q2 = (self.pk_i['Z'] / ((self.pk_i['S']**v) * self.all)) % self.pk_i['N'] # tmp_u = (self.pk_i['S'] ** self.vPrime) * (self.pk_i['Ro'] ** self.ms) % self.pk_i['N'] # Q22 = (self.pk_i['Z'] / ((self.pk_i['S'] ** vPrimePrime) * self.ak * tmp_u)) % self.pk_i['N'] Qhat = (A**e) % self.pk_i['N'] q2Check = Q2 == Qhat Ahat = A**(cPrime + (Se * e)) % self.pk_i['N'] s4 = hashlib.new('sha256') s4.update(Conversion.IP2OS(self.context)) s4.update(Conversion.IP2OS(Q2)) s4.update(Conversion.IP2OS(A)) s4.update(Conversion.IP2OS(n2)) s4.update(Conversion.IP2OS(Ahat)) cHat2 = integer(s4.digest()) c2Check = cHat2 == cPrime sig = {'A': A, 'e': e, 'v': v} return sig, q2Check, c2Check
def __verify_p1(self, p1): df02_commit = CM_DF02() pk_commit = {'S': self.pk_i['S'], 'Z': self.pk_i['Ro'], 'N': self.pk_i['N']} sHat = p1['sHat'] vPrimeHat = p1['vPrimeHat'] (cA, vPrimeHat) = df02_commit.commit(pk_commit, sHat, 0, vPrimeHat) U = p1['U'] % self.pk_i['N'] c = p1['c'] Uhat = cA * (U ** (-1 * c)) s2 = hashlib.new('sha256') s2.update(Conversion.IP2OS(self.context)) s2.update(Conversion.IP2OS(U)) s2.update(Conversion.IP2OS(Uhat)) s2.update(Conversion.IP2OS(self.n1)) cHat = integer(s2.digest()) return c == cHat
def stringToInt(strID, zz, ll): '''Hash the identity string and break it up in to l bit pieces''' h = hashlib.new('sha1') h.update(bytes(strID, 'utf-8')) _hash = Bytes(h.digest()) val = Conversion.OS2IP(_hash) #Convert to integer format bstr = bin(val)[2:] #cut out the 0b header v=[] for i in range(zz): #z must be greater than or equal to 1 binsubstr = bstr[ll*i : ll*(i+1)] intval = int(binsubstr, 2) intelement = group.init(ZR, intval) v.append(intelement) return v
def hash(self, strID): '''Hash the identity string and break it up in to l bit pieces''' assert type(strID) == str, "invalid input type" hash = self.sha2(strID) val = Conversion.OS2IP(hash) #Convert to integer format bstr = bin(val)[2:] #cut out the 0b header v=[] for i in range(self._length): #z must be greater than or equal to 1 binsubstr = bstr[self._bitsize*i : self._bitsize*(i+1)] intval = int(binsubstr, 2) intelement = self._group.init(ZR, intval) v.append(intelement) return v
def test1(client, p, nonce, key_client, key_p): group_object = PairingGroup('SS512') shared_key = group_object.random(GT) crypter_a = SymmetricCryptoAbstraction( extractor(bytesToObject(key_client, group_object))) crypter_b = SymmetricCryptoAbstraction( extractor(bytesToObject(key_p, group_object))) package_b = crypter_b.encrypt( objectToBytes([shared_key, serialize_endpoint(client)], group_object)) package_a = crypter_a.encrypt( objectToBytes([ Conversion.OS2IP(nonce), shared_key, serialize_endpoint(p), package_b ], group_object)) return package_a
def check(self, signature: int): # Convert back to bytes sig = Conversion.IP2OS(signature) # Verifier setup ecc = ECC.import_key(self.pubk) verifier = DSS.new(ecc, 'fips-186-3') new_hash = SHA256.new(bytes.fromhex(self.y)) # We need to verify the signature on the hash. The verifier throws an exception if it doesn't verify. try: verifier.verify(new_hash, sig) return True except Exception as e: print(str(e), file=sys.stderr) return False
def strToId(pk, strID): getUserGlobals() hash = sha1(strID) val = Conversion.OS2IP(hash) bstr = bin(val)[2:] v = [] for i in range(pk[listIndexNoOfN_StrToId]): binsubstr = bstr[pk[listIndexNoOfl_StrToId] * i:pk[listIndexNoOfl_StrToId] * (i + 1)] print(binsubstr) intval = int(binsubstr, 2) intelement = groupObjBuiltInFuncs.init(ZR, intval) v.append(intelement) return v
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) # attr = user.gen_random_attributes(l) # ISSUING PROTOCOL n1 = issuer.round_0() # Generate nonce p1, n2 = user.round_1(n1)