async def _initEqProof(self, schemaId, c1: PrimaryClaim, revealedAttrs: Sequence[str], m1Tilde, m2Tilde, claimAttributes: Dict[str, ClaimAttributeValues]) \ -> PrimaryEqualInitProof: m2Tilde = m2Tilde if m2Tilde else cmod.integer( cmod.randomBits(LARGE_MVECT)) revealedAttrs, unrevealedAttrs = splitRevealedAttrs( claimAttributes, [a.name for a in revealedAttrs]) mtilde = self._getMTilde(unrevealedAttrs) Ra = cmod.integer(cmod.randomBits(LARGE_VPRIME)) pk = await self._wallet.getPublicKey(ID(schemaId=schemaId)) A, e, v = c1.A, c1.e, c1.v Aprime = A * (pk.S**Ra) % pk.N vprime = (v - e * Ra) eprime = e - (2**LARGE_E_START) etilde = cmod.integer(cmod.randomBits(LARGE_ETILDE)) vtilde = cmod.integer(cmod.randomBits(LARGE_VTILDE)) Rur = 1 % pk.N for k, value in unrevealedAttrs.items(): if k in claimAttributes: Rur = Rur * (pk.R[k]**mtilde[k]) Rur *= pk.Rms**m1Tilde Rur *= pk.Rctxt**m2Tilde # T = ((Aprime ** etilde) * Rur * (pk.S ** vtilde)) % pk.N T = calcTeq(pk, Aprime, etilde, vtilde, mtilde, m1Tilde, m2Tilde, unrevealedAttrs.keys()) return PrimaryEqualInitProof(c1, Aprime, T, etilde, eprime, vtilde, vprime, mtilde, m1Tilde, m2Tilde, unrevealedAttrs.keys(), revealedAttrs)
async def test_ge_proof_from_to_dict(): n = cmod.integer(12345) predicate = PredicateGE(attrName='age', value=18) geProof = PrimaryPredicateGEProof(alpha=cmod.integer(1), mj=cmod.integer(12), r={'1': cmod.integer(13)}, u={'1': cmod.integer(42)}, T={'1': cmod.integer(21) % n}, predicate=predicate) proof_serialized = { 'alpha': '1', 'mj': '12', 't': {'1': '21'}, 'r': {'1': '13'}, 'u': {'1': '42'}, 'predicate': { 'p_type': 'GE', 'attr_name': 'age', 'value': 18, 'schema_seq_no': None, 'issuer_did': None } } assert geProof.to_str_dict() == proof_serialized assert geProof == PrimaryPredicateGEProof.from_str_dict( proof_serialized, n) assert geProof == PrimaryPredicateGEProof.from_str_dict( geProof.to_str_dict(), n)
async def _prepareProof(self, claims: Dict[SchemaKey, ProofClaims], nonce, requestedProof) -> FullProof: m1Tilde = cmod.integer(cmod.randomBits(LARGE_M2_TILDE)) initProofs = {} CList = [] TauList = [] # 1. init proofs for schemaId, val in claims.items(): c1, c2, revealedAttrs, predicates = val.claims.primaryClaim, val.claims.nonRevocClaim, val.revealedAttrs, val.predicates claim = await self.wallet.getClaimAttributes(ID(schemaId=schemaId)) nonRevocInitProof = None if c2: nonRevocInitProof = await self._nonRevocProofBuilder.initProof( schemaId, c2) CList += nonRevocInitProof.asCList() TauList += nonRevocInitProof.asTauList() primaryInitProof = None if c1: m2Tilde = cmod.integer(int(nonRevocInitProof.TauListParams.m2) ) if nonRevocInitProof else None primaryInitProof = await self._primaryProofBuilder.initProof( schemaId, c1, revealedAttrs, predicates, m1Tilde, m2Tilde, claim) CList += primaryInitProof.asCList() TauList += primaryInitProof.asTauList() initProof = InitProof(nonRevocInitProof, primaryInitProof) initProofs[schemaId] = initProof # 2. hash cH = self._get_hash(self._prepare_collection(CList), self._prepare_collection(TauList), nonce) # 3. finalize proofs proofs = {} for schemaId, initProof in initProofs.items(): nonRevocProof = None if initProof.nonRevocInitProof: nonRevocProof = await self._nonRevocProofBuilder.finalizeProof( schemaId, cH, initProof.nonRevocInitProof) primaryProof = await self._primaryProofBuilder.finalizeProof( schemaId, cH, initProof.primaryInitProof) schema = await self.wallet.getSchema(ID(schemaId=schemaId)) proof = Proof(primaryProof, nonRevocProof) proofInfo = ProofInfo(proof=proof, schema_seq_no=schemaId, issuer_did=schema.issuerId) proofs[str(schemaId)] = proofInfo aggregatedProof = AggregatedProof(cH, self._prepare_collection(CList)) return FullProof(proofs, aggregatedProof, requestedProof)
def testToFromDictWithStrValuesLists(): group = cmod.PairingGroup(PAIRING_GROUP) dictionary = OrderedDict( (('47', []), ('7', [cmod.integer(111) % 11, cmod.integer(222), cmod.integer(333) % 45]), ('6', [ group.init(cmod.ZR, 555), group.random(cmod.G1), group.random(cmod.G1) ]))) assert dictionary == fromDictWithStrValues(toDictWithStrValues(dictionary))
async def test_aggregated_proof_from_to_dict(prover1, nonce, claimsProver1Gvt): aggregated_proof = AggregatedProof( 1, [cmod.integer(111), cmod.integer(32321), cmod.integer(323)]) aggregated_proof_serialized = { 'c_hash': '1', 'c_list': [[111], [126, 65], [1, 67]] } assert aggregated_proof.to_str_dict() == aggregated_proof_serialized assert aggregated_proof == AggregatedProof.from_str_dict( aggregated_proof_serialized) assert aggregated_proof == AggregatedProof.from_str_dict( aggregated_proof.to_str_dict())
async def test_equal_proof_from_to_dict(): n = cmod.integer(12345) eqProof = PrimaryEqualProof(e=cmod.integer(1), v=cmod.integer(11), m={'name': cmod.integer(12)}, m1=cmod.integer(12), m2=cmod.integer(32), Aprime=cmod.integer(32) % n, revealedAttrs={'name': cmod.integer(35)}) proof_serialized = { 'a_prime': '32', 'e': '1', 'm': { 'name': '12' }, 'm1': '12', 'm2': '32', 'v': '11', 'revealed_attrs': { 'name': '35' } } assert eqProof.to_str_dict() == proof_serialized assert eqProof == PrimaryEqualProof.from_str_dict(proof_serialized, n) assert eqProof == PrimaryEqualProof.from_str_dict(eqProof.to_str_dict(), n)
def test_claim_request_from_to_dict(): n = cmod.integer(12345) u = cmod.integer(12) % n prover_did = '123456789' claim_request = ClaimRequest(userId=prover_did, U=u, Ur=None) claim_request_serialized = { 'prover_did': '123456789', 'u': '12', 'ur': None } assert claim_request.to_str_dict() == claim_request_serialized assert claim_request == ClaimRequest.from_str_dict( claim_request_serialized, n)
async def _prepareProof(self, claims: Dict[SchemaKey, ProofClaims], nonce) -> FullProof: m1Tilde = cmod.integer(cmod.randomBits(LARGE_M2_TILDE)) initProofs = {} CList = [] TauList = [] # 1. init proofs for schemaKey, val in claims.items(): c1, c2, revealedAttrs, predicates = val.claims.primaryClaim, val.claims.nonRevocClaim, val.revealedAttrs, val.predicates nonRevocInitProof = None if c2: nonRevocInitProof = await self._nonRevocProofBuilder.initProof( schemaKey, c2) CList += nonRevocInitProof.asCList() TauList += nonRevocInitProof.asTauList() primaryInitProof = None if c1: m2Tilde = cmod.integer(int( nonRevocInitProof.TauListParams.m2)) if nonRevocInitProof else None primaryInitProof = await self._primaryProofBuilder.initProof( schemaKey, c1, revealedAttrs, predicates, m1Tilde, m2Tilde) CList += primaryInitProof.asCList() TauList += primaryInitProof.asTauList() initProof = InitProof(nonRevocInitProof, primaryInitProof) initProofs[schemaKey] = initProof # 2. hash cH = self._get_hash(CList, TauList, nonce) # 3. finalize proofs proofs = [] schemaKeys = [] for schemaKey, initProof in initProofs.items(): schemaKeys.append(schemaKey) nonRevocProof = None if initProof.nonRevocInitProof: nonRevocProof = await self._nonRevocProofBuilder.finalizeProof( schemaKey, cH, initProof.nonRevocInitProof) primaryProof = await self._primaryProofBuilder.finalizeProof( schemaKey, cH, initProof.primaryInitProof) proofs.append(Proof(primaryProof, nonRevocProof)) return FullProof(cH, schemaKeys, proofs, CList)
def verifyProof(cls, credDefPks, proof, nonce, encodedAttrs, revealedAttrs): """ Verify the proof :param encodedAttrs: The encoded attributes dictionary :param revealedAttrs: The revealed attributes list :param nonce: The nonce used to have a commit :return: A boolean with the verification status for the proof """ import logging Aprime, c, Tvect = getProofParams(proof, credDefPks, encodedAttrs, revealedAttrs) logging.debug("Proof Verification 1: proof, " "credDefPks, encodedAttrs, revealedAttrs: {} {} {} {}". format(proof, credDefPks, encodedAttrs, revealedAttrs)) # Calculate the `cvect` value based on proof. # This value is mathematically proven to be equal to `c` # if proof is created correctly from credentials. Refer 2.8 in document logging.debug("Proof Verification 2: Aprime, Tvect, nonce: {} {} {}". format(Aprime, Tvect, nonce)) cvect = cmod.integer(get_hash(*get_values_of_dicts(Aprime, Tvect, {NONCE: nonce}))) logging.debug("Proof Verification 3: c, cvect: {} {}". format(c, cvect)) return c == cvect
def __init__(self, credDefPks: Dict[str, IssuerKey], masterSecret=None): """ Create a proof instance :param credDefPks: The public key of the Issuer(s) """ self.id = str(uuid.uuid4()) self.nonce = None self.credential = None self.encodedAttrs = None self.revealedAttrs = None # Generate the master secret self._ms = masterSecret or cmod.integer( cmod.randomBits(LARGE_MASTER_SECRET)) # Set the credential definition pub keys self.credDefPks = credDefPks for key, x in self.credDefPks.items(): self.credDefPks[key] = x.inFieldN() self._vprime = {} for key, val in self.credDefPks.items(): self._vprime[key] = cmod.randomBits(LARGE_VPRIME) # Calculate the `U` values using Issuer's `S`, R["0"] and master secret self._U = {} for key, val in self.credDefPks.items(): N = val.N R = val.R S = val.S self._U[key] = (S**self._vprime[key]) * (R[ZERO_INDEX]** self._ms) % N
def testIntToArrayBytes(): val = cmod.integer(1606507817390189252221968804450207070282033) res = [ 18, 113, 26, 39, 35, 240, 231, 239, 92, 226, 84, 46, 230, 174, 230, 41, 225, 49 ] assert res == intToArrayBytes(val)
def deser(v, n): if isinstance(v, cmod.integer): return v % n elif isinstance(v, int): return cmod.integer(v) % n else: raise RuntimeError("unknown type: {}".format(type(v)))
async def verify(self, schemaId, cHash, primaryProof: PrimaryProof): cH = cmod.integer(cHash) THat = await self._verifyEquality(schemaId, cH, primaryProof.eqProof) for geProof in primaryProof.geProofs: THat += await self._verifyGEPredicate(schemaId, cH, geProof) return THat
async def issuePrimaryClaim( self, schemaId: ID, attributes: Attribs, U) -> (PrimaryClaim, Dict[str, ClaimAttributeValues]): u = strToCryptoInteger(U) if isinstance(U, str) else U if not u: raise ValueError("u must be provided to issue a credential") # Generate a random prime and # Set the Most-significant-bit to 1 vprimeprime = cmod.integer( cmod.randomBits(LARGE_VPRIME_PRIME) | (2**(LARGE_VPRIME_PRIME - 1))) # Generate prime number in the range (2^596, 2^596 + 2^119) estart = 2**LARGE_E_START eend = (estart + 2**LARGE_E_END_RANGE) e = get_prime_in_range(estart, eend) encodedAttrs = attributes.encoded() A = await self._sign(schemaId, encodedAttrs, vprimeprime, u, e) m2 = await self._wallet.getContextAttr(schemaId) claimAttributes = \ {attr: ClaimAttributeValues( attributes._vals[attr], encodedAttrs[attr]) for attr in attributes.keys()} return (PrimaryClaim(m2, A, e, vprimeprime), claimAttributes)
async def _genContxt(self, schemaId: ID, iA, userId): iA = strToInt(str(iA)) userId = strToInt(str(userId)) S = iA | userId H = get_hash_as_int(S) m2 = cmod.integer(H % (2**LARGE_MASTER_SECRET)) await self.wallet.submitContextAttr(schemaId, m2) return m2
def staticPrimes(): return { "prime1": (cmod.integer( 157329491389375793912190594961134932804032426403110797476730107804356484516061051345332763141806005838436304922612495876180233509449197495032194146432047460167589034147716097417880503952139805241591622353828629383332869425029086898452227895418829799945650973848983901459733426212735979668835984691928193677469 ), cmod.integer( 151323892648373196579515752826519683836764873607632072057591837216698622729557534035138587276594156320800768525825023728398410073692081011811496168877166664537052088207068061172594879398773872352920912390983199416927388688319207946493810449203702100559271439586753256728900713990097168484829574000438573295723 )), "prime2": (cmod.integer( 150619677884468353208058156632953891431975271416620955614548039937246769610622017033385394658879484186852231469238992217246264205570458379437126692055331206248530723117202131739966737760399755490935589223401123762051823602343810554978803032803606907761937587101969193241921351011430750970746500680609001799529 ), cmod.integer( 171590857568436644992359347719703764048501078398666061921719064395827496970696879481740311141148273607392657321103691543916274965279072000206208571551864201305434022165176563363954921183576230072812635744629337290242954699427160362586102068962285076213200828451838142959637006048439307273563604553818326766703 )) }
async def verify(self, proofInput: ProofInput, schemaKey, cHash, primaryProof: PrimaryProof, allRevealedAttrs): cH = cmod.integer(cHash) THat = await self._verifyEquality(schemaKey, cH, primaryProof.eqProof, allRevealedAttrs) for geProof in primaryProof.geProofs: THat += await self._verifyGEPredicate(schemaKey, cH, geProof) return THat
def testPKFromToDict(): pk = PublicKey(N=cmod.integer(11), Rms=cmod.integer(12), Rctxt=cmod.integer(13), R={'a': cmod.integer(1), 'b': cmod.integer(2)}, S=cmod.integer(14), Z=cmod.integer(15)) assert pk == PublicKey.fromStrDict(pk.toStrDict())
def verifyPredicateProof(proof: PredicateProof, credDefPks, nonce, attrs: Dict[str, Dict[str, T]], revealedAttrs: Sequence[str], predicate: Dict[str, Sequence[str]]): """ Verify the proof for Predicate implementation :param proof: The proof which is a combination of sub-proof for credential and proof, C :param nonce: The nonce used :param attrs: The encoded attributes :param revealedAttrs: The list of revealed attributes :param predicate: The predicate to be validated :return: """ Tau = [] subProofC, subProofPredicate, C, CList = proof # Get all the random and prime numbers for verifying the proof c, evect, mvect, vvect, Aprime = subProofC alphavect, rvect, uvect = subProofPredicate Aprime, c, Tvect = getProofParams(subProofC, credDefPks, attrs, revealedAttrs) Tau.extend(get_values_of_dicts(Tvect)) for key, val in predicate.items(): p = credDefPks[key] Tval = C[key][TVAL] # Iterate over the predicates for a given credential(issuer) for k, value in val.items(): Tdeltavect1 = (Tval[DELTA] * (p.Z ** value)) Tdeltavect2 = (p.Z ** mvect[k]) * (p.S ** rvect[DELTA]) Tdeltavect = (Tdeltavect1 ** (-1 * c)) * Tdeltavect2 % p.N Tuproduct = 1 % p.N for i in range(0, ITERATIONS): Tvalvect1 = (Tval[str(i)] ** (-1 * c)) Tvalvect2 = (p.Z ** uvect[str(i)]) Tvalvect3 = (p.S ** rvect[str(i)]) Tau.append(Tvalvect1 * Tvalvect2 * Tvalvect3 % p.N) Tuproduct *= Tval[str(i)] ** uvect[str(i)] Tau.append(Tdeltavect) Qvect1 = (Tval[DELTA] ** (-1 * c)) Qvect = Qvect1 * Tuproduct * (p.S ** alphavect) % p.N Tau.append(Qvect) tauAndC = reduce(lambda x, y: x + y, [Tau, CList]) cvect = cmod.integer(get_hash(nonce, *tauAndC)) return c == cvect
def testToFromDictWithStrValuesMixed(): group = cmod.PairingGroup(PAIRING_GROUP) dictionary = OrderedDict( (('4', {'aaa', 'bbb'}), ('2', OrderedDict( (('33', OrderedDict((('45', 45), ('11', 11)))), ('23', OrderedDict( (('47', 47), ('34', 34))))))), ('1', {}), ('3', 3), ('5', cmod.integer(111) % 11), ('7', [cmod.integer(111) % 11, cmod.integer(222), cmod.integer(333) % 45]), ('6', [ group.init(cmod.ZR, 555), group.random(cmod.G1), group.random(cmod.G1) ]), ('10', group.random(cmod.G1)))) assert dictionary == fromDictWithStrValues(toDictWithStrValues(dictionary))
async def test_attribute_values_from_to_dict(): attr_values = ClaimAttributeValues(raw='Alex', encoded=cmod.integer(11)) attr_values_serialized = ['Alex', '11'] assert attr_values.to_str_dict() == attr_values_serialized assert attr_values == ClaimAttributeValues.from_str_dict( attr_values_serialized) assert attr_values == ClaimAttributeValues.from_str_dict( attr_values.to_str_dict())
def findSecretValues(encodedAttrs: Dict[str, T], unrevealedAttrs: Dict, creds: Dict[str, Credential], issuerPks: Dict[str, IssuerKey]): def getMTilde(unrevealedAttrs): mtilde = {} for key, value in unrevealedAttrs.items(): mtilde[key] = cmod.integer(cmod.randomBits(LARGE_MVECT)) mtilde[ZERO_INDEX] = cmod.integer(cmod.randomBits(LARGE_MVECT)) return mtilde def getRur(credDefPk, includedAttrs, mtilde, unrevealedAttrs): Rur = 1 % credDefPk.N for k, value in unrevealedAttrs.items(): if k in includedAttrs: Rur = Rur * (credDefPk.R[k] ** mtilde[k]) Rur *= credDefPk.R[ZERO_INDEX] ** mtilde[ZERO_INDEX] return Rur Aprime, vprime, eprime, etilde, vtilde, T = {}, {}, {}, {}, {}, {} mtilde = getMTilde(unrevealedAttrs) for issuer, credential in creds.items(): Ra = cmod.integer(cmod.randomBits(LARGE_VPRIME)) credDefPk = issuerPks[issuer] A, e, v = credential Aprime[issuer] = A * (credDefPk.S ** Ra) % credDefPk.N vprime[issuer] = (v - e * Ra) eprime[issuer] = e - (2 ** LARGE_E_START) etilde[issuer] = cmod.integer(cmod.randomBits(LARGE_ETILDE)) vtilde[issuer] = cmod.integer(cmod.randomBits(LARGE_VTILDE)) Rur = getRur(credDefPk, encodedAttrs[issuer], mtilde, unrevealedAttrs) T[issuer] = ((Aprime[issuer] ** etilde[issuer]) * Rur * ( credDefPk.S ** vtilde[issuer])) % credDefPk.N tildValue = TildValue(mtilde, etilde, vtilde) primeValue = PrimeValue(Aprime, vprime, eprime) return SecretValue(tildValue, primeValue, T)
def appendToProofCompWithPredicateData(proofComponent, predicate): for key, val in predicate.items(): x = self.credDefPks[key] # Iterate over the predicates for a given credential(issuer) for k, value in val.items(): delta = proofComponent.flatAttrs[k] - value if delta < 0: raise ValueError("Predicate is not satisfied") proofComponent.u = fourSquares(delta) for i in range(0, ITERATIONS): proofComponent.r[str(i)] = cmod.integer( cmod.randomBits(LARGE_VPRIME)) proofComponent.r[DELTA] = cmod.integer( cmod.randomBits(LARGE_VPRIME)) Tval = {} for i in range(0, ITERATIONS): Tval[str(i)] = (x.Z**proofComponent.u[i]) * ( x.S**proofComponent.r[str(i)]) % x.N proofComponent.utilde[str(i)] = cmod.integer( cmod.randomBits(LARGE_UTILDE)) proofComponent.rtilde[str(i)] = cmod.integer( cmod.randomBits(LARGE_RTILDE)) Tval[DELTA] = (x.Z**delta) * ( x.S**proofComponent.r[DELTA]) % x.N proofComponent.rtilde[DELTA] = cmod.integer( cmod.randomBits(LARGE_RTILDE)) proofComponent.CList.extend(get_values_of_dicts(Tval)) updateDict(proofComponent.C, key, TVAL, Tval) for i in range(0, ITERATIONS): proofComponent.TauList.append( (x.Z**proofComponent.utilde[str(i)]) * (x.S**proofComponent.rtilde[str(i)]) % x.N) proofComponent.TauList.append( (x.Z**proofComponent.tildeValues.mtilde[k]) * (x.S**proofComponent.rtilde[DELTA]) % x.N) proofComponent.alphatilde = cmod.integer( cmod.randomBits(LARGE_ALPHATILDE)) Q = 1 % x.N for i in range(0, ITERATIONS): Q *= Tval[str(i)]**proofComponent.utilde[str(i)] Q *= x.S**proofComponent.alphatilde % x.N proofComponent.TauList.append(Q) proofComponent.c = cmod.integer( get_hash( nonce, *reduce(lambda x, y: x + y, [proofComponent.TauList, proofComponent.CList])))
async def finalizeProof(self, schemaId, cH, initProof: PrimaryInitProof) -> PrimaryProof: if not initProof: return None cH = cmod.integer(cH) eqProof = await self._finalizeEqProof(schemaId, cH, initProof.eqProof) geProofs = [] for initGeProof in initProof.geProofs: geProof = await self._finalizeGeProof(schemaId, cH, initGeProof, eqProof) geProofs.append(geProof) return PrimaryProof(eqProof, geProofs)
def initProofComponent(issuerPks, creds, encodedAttrs, revealedAttrs, nonce): proofComponent = ProofComponent() proofComponent.flatAttrs, proofComponent.unrevealedAttrs = \ getUnrevealedAttrs( encodedAttrs, revealedAttrs) proofComponent.tildeValues, proofComponent.primeValues, \ proofComponent.T = findSecretValues( encodedAttrs, proofComponent.unrevealedAttrs, creds, issuerPks) # Calculate the `c` value as the hash result of Aprime, T and nonce. # This value will be used to verify the proof against the credential proofComponent.c = cmod.integer(get_hash( *get_values_of_dicts(proofComponent.primeValues.Aprime, proofComponent.T, {NONCE: nonce}))) return proofComponent
async def verify(self, proofRequest: ProofRequest, proof: FullProof): """ Verifies a proof from the prover. :param proofRequest: description of a proof to be presented (revealed attributes, predicates, timestamps for non-revocation) :param proof: a proof :return: True if verified successfully and false otherwise. """ if proofRequest.verifiableAttributes.keys( ) != proof.requestedProof.revealed_attrs.keys(): raise ValueError( 'Received attributes ={} do not correspond to requested={}'. format(proof.requestedProof.revealed_attrs.keys(), proofRequest.verifiableAttributes.keys())) if proofRequest.predicates.keys( ) != proof.requestedProof.predicates.keys(): raise ValueError( 'Received predicates ={} do not correspond to requested={}'. format(proof.requestedProof.predicates.keys(), proofRequest.predicates.keys())) TauList = [] for (uuid, proofItem) in proof.proofs.items(): if proofItem.proof.nonRevocProof: TauList += await self._nonRevocVerifier.verifyNonRevocation( proofRequest, proofItem.schema_seq_no, proof.aggregatedProof.cHash, proofItem.proof.nonRevocProof) if proofItem.proof.primaryProof: TauList += await self._primaryVerifier.verify( proofItem.schema_seq_no, proof.aggregatedProof.cHash, proofItem.proof.primaryProof) CHver = self._get_hash(proof.aggregatedProof.CList, self._prepare_collection(TauList), cmod.integer(proofRequest.nonce)) return CHver == proof.aggregatedProof.cHash
def generateCredential(cls, uValue, attributes, pk, sk: CredDefSecretKey): """ Issue the credential for the defined attributes :param u: The `u` value provided by the prover :param attrs: The attributes for which the credential needs to be generated :return: The presentation token as a combination of (A, e, vprimeprime) """ u = strToCryptoInteger(uValue) if isinstance(uValue, str) else uValue if not u: raise ValueError("u must be provided to issue a credential") # Generate a random prime and # Set the Most-significant-bit to 1 vprimeprime = cmod.integer( cmod.randomBits(LARGE_VPRIME_PRIME) | (2**(LARGE_VPRIME_PRIME - 1))) # Generate prime number in the range (2^596, 2^596 + 2^119) estart = 2**LARGE_E_START eend = (estart + 2**LARGE_E_END_RANGE) e = get_prime_in_range(estart, eend) A = cls._sign(pk, attributes, vprimeprime, u, e, sk.p_prime, sk.q_prime) return A, e, vprimeprime
async def _initGeProof(self, schemaId, eqProof: PrimaryEqualInitProof, c1: PrimaryClaim, predicate: Predicate, claimAttributes: Dict[str, ClaimAttributeValues]) \ -> PrimaryPrecicateGEInitProof: # gen U for Delta pk = await self._wallet.getPublicKey(ID(schemaId=schemaId)) k, value = predicate.attrName, predicate.value delta = claimAttributes[k].encoded - value if delta < 0: raise ValueError("Predicate is not satisfied") u = fourSquares(delta) # prepare C list r = {} T = {} CList = [] for i in range(0, ITERATIONS): r[str(i)] = cmod.integer(cmod.randomBits(LARGE_VPRIME)) T[str(i)] = (pk.Z**u[str(i)]) * (pk.S**r[str(i)]) % pk.N CList.append(T[str(i)]) r[DELTA] = cmod.integer(cmod.randomBits(LARGE_VPRIME)) T[DELTA] = (pk.Z**delta) * (pk.S**r[DELTA]) % pk.N CList.append(T[DELTA]) # prepare Tau List utilde = {} rtilde = {} for i in range(0, ITERATIONS): utilde[str(i)] = cmod.integer(cmod.randomBits(LARGE_UTILDE)) rtilde[str(i)] = cmod.integer(cmod.randomBits(LARGE_RTILDE)) rtilde[DELTA] = cmod.integer(cmod.randomBits(LARGE_RTILDE)) alphatilde = cmod.integer(cmod.randomBits(LARGE_ALPHATILDE)) TauList = calcTge(pk, utilde, rtilde, eqProof.mTilde[k], alphatilde, T) return PrimaryPrecicateGEInitProof(CList, TauList, u, utilde, r, rtilde, alphatilde, predicate, T)
from config.config import cmod primes = { "prime1": ( cmod.integer(int( "".join( """15732949138937579391219059496113493280403242640311079747 67301078043564845160610513453327631418060058384363049226124 95876180233509449197495032194146432047460167589034147716097 41788050395213980524159162235382862938333286942502908689845 22278954188297999456509738489839014597334262127359796688359 84691928193677469""" .split() ))), cmod.integer(int( "".join( """1513238926483731965795157528265196838367648736076320720 5759183721669862272955753403513858727659415632080076852582 5023728398410073692081011811496168877166664537052088207068 0611725948793987738723529209123909831994169273886883192079 4649381044920370210055927143958675325672890071399009716848 4829574000438573295723""" .split() ))) ) , "prime2": ( cmod.integer(int( "".join( """1506196778844683532080581566329538914319752714166209556
def generateMasterSecret(): # Generate the master secret return cmod.integer(cmod.randomBits(LARGE_MASTER_SECRET))
def strToCryptoInteger(n): if "mod" in n: a, b = n.split("mod") return cmod.integer(int(a.strip())) % cmod.integer(int(b.strip())) else: return cmod.integer(int(n))