diff --git a/ipv8/attestation/communication_manager.py b/ipv8/attestation/communication_manager.py index d6f1ae859..a3fb59aae 100644 --- a/ipv8/attestation/communication_manager.py +++ b/ipv8/attestation/communication_manager.py @@ -140,12 +140,11 @@ def _drop_attestation_table_data(self, attestation_hashes: list[bytes]) -> None: if not attestation_hashes: return - self.attestation_overlay.database.execute(("DELETE FROM %s" # noqa: S608 - % self.attestation_overlay.database.db_name) - + " WHERE hash IN (" - + ", ".join(c for c in "?" * len(attestation_hashes)) - + ")", - attestation_hashes) + self.attestation_overlay.database.execute( + f"DELETE FROM {self.attestation_overlay.database.db_name}" # noqa: S608 + " WHERE hash IN (" + ", ".join(c for c in "?" * len(attestation_hashes)) + ")", + attestation_hashes + ) self.attestation_overlay.database.commit() def remove(self) -> None: @@ -353,7 +352,9 @@ async def unload(self, name: str) -> None: self.channels.pop(communication_channel.public_key_bin) await self.ipv8_instance.unload_overlay(communication_channel.identity_overlay) await communication_channel.attestation_overlay.unload() - communication_channel.identity_overlay.endpoint.close() + aw_closing = communication_channel.identity_overlay.endpoint.close() + if aw_closing is not None: + await aw_closing async def remove(self, name: str) -> None: """ diff --git a/ipv8/attestation/default_identity_formats.py b/ipv8/attestation/default_identity_formats.py index e12d6fb4c..d6384e82b 100644 --- a/ipv8/attestation/default_identity_formats.py +++ b/ipv8/attestation/default_identity_formats.py @@ -1,5 +1,3 @@ -from .wallet.irmaexact.keydump import nijmegen_pk_1568208470 - FORMATS = { "id_metadata": { "algorithm": "bonehexact", @@ -21,39 +19,5 @@ "key_size": 32, # Pairings over 1024 bit space "min": 18, "max": 200 - }, - "id_irma_nijmegen_address_1568208470": { - "algorithm": "irmaexact", - "issuer_pk": nijmegen_pk_1568208470, # Valid until Wednesday 11 September 2019 13:27:50 GMT - "order": ["street", "houseNumber", "zipcode", "municipality", "city"], - "credential": "pbdf.nijmegen.address", - "keyCounter": 0, - "validity": 13 - - }, - "id_irma_nijmegen_personalData_1568208470": { - "algorithm": "irmaexact", - "issuer_pk": nijmegen_pk_1568208470, # Valid until Wednesday 11 September 2019 13:27:50 GMT - "order": ["initials", "firstnames", "prefix", "familyname", "surname", - "fullname", "dateofbirth", "gender", "nationality"], - "credential": "pbdf.nijmegen.personalData", - "keyCounter": 0, - "validity": 13 - }, - "id_irma_nijmegen_ageLimits_1568208470": { - "algorithm": "irmaexact", - "issuer_pk": nijmegen_pk_1568208470, # Valid until Wednesday 11 September 2019 13:27:50 GMT - "order": ["over12", "over16", "over18", "over21", "over65"], - "credential": "pbdf.nijmegen.ageLimits", - "keyCounter": 0, - "validity": 13 - }, - "id_irma_nijmegen_bsn_1568208470": { - "algorithm": "irmaexact", - "issuer_pk": nijmegen_pk_1568208470, # Valid until Wednesday 11 September 2019 13:27:50 GMT - "order": ["bsn"], - "credential": "pbdf.nijmegen.bsn", - "keyCounter": 0, - "validity": 13 } } diff --git a/ipv8/attestation/schema/manager.py b/ipv8/attestation/schema/manager.py index 597cd5608..1ad285db7 100644 --- a/ipv8/attestation/schema/manager.py +++ b/ipv8/attestation/schema/manager.py @@ -41,9 +41,6 @@ def get_algorithm_class(self, algorithm_name: str) -> type[IdentityAlgorithm]: elif algorithm_name == "pengbaorange": from ..wallet.pengbaorange.algorithm import PengBaoRangeAlgorithm algorithm = PengBaoRangeAlgorithm - elif algorithm_name == "irmaexact": - from ..wallet.irmaexact.algorithm import IRMAExactAlgorithm - algorithm = IRMAExactAlgorithm else: msg = f"Attempted to load unknown proof algorithm {algorithm_name}!" raise RuntimeError(msg) @@ -73,10 +70,6 @@ def register_default_schemas(self) -> None: - id_metadata_big: 4096 bit space "exact" value match - id_metadata_huge: 9216 bit space "exact" value match - id_metadata_range_18plus: NIZKP over a commitment, showing it lies within [0, 18] - - id_irma_nijmegen_address_1568208470: IRMA address data match, valid until 11 Sept 2019 13:27:50 GMT - - id_irma_nijmegen_personalData_1568208470: IRMA personal data match, valid until 11 Sept 2019 13:27:50 GMT - - id_irma_nijmegen_ageLimits_1568208470: IRMA age data match, valid until 11 Sept 2019 13:27:50 GMT - - id_irma_nijmegen_bsn_1568208470: IRMA bsn data match, valid until 11 Sept 2019 13:27:50 GMT """ from ..default_identity_formats import FORMATS for schema in FORMATS: diff --git a/ipv8/attestation/wallet/irmaexact/__init__.py b/ipv8/attestation/wallet/irmaexact/__init__.py deleted file mode 100644 index f9a3c606a..000000000 --- a/ipv8/attestation/wallet/irmaexact/__init__.py +++ /dev/null @@ -1,14 +0,0 @@ -import os -from functools import reduce - - -def secure_randint(bitspace: int) -> int: - """ - Generate an integer in a given bitspace using the OS rng. - """ - delbits = 8 - (bitspace % 8) - bytez = os.urandom(bitspace // 8) - if delbits > 0: - b = (os.urandom(1)[0] & (0xFF >> delbits)).to_bytes(1, 'big', signed=False) - bytez = b + bytez - return reduce(lambda a, b: (a << 8) + b, bytez, 0) diff --git a/ipv8/attestation/wallet/irmaexact/algorithm.py b/ipv8/attestation/wallet/irmaexact/algorithm.py deleted file mode 100644 index 70002c5d2..000000000 --- a/ipv8/attestation/wallet/irmaexact/algorithm.py +++ /dev/null @@ -1,226 +0,0 @@ -from __future__ import annotations - -import binascii -import json -import os -from typing import Any, cast - -from ...identity_formats import Attestation, IdentityAlgorithm -from ..primitives.structs import ipack, iunpack -from .gabi.attributes import make_attribute_list -from .gabi.keys import DefaultSystemParameters -from .gabi.proofs import ProofD, createChallenge -from .wrappers import challenge_response, serialize_proof_d, unserialize_proof_d - -# ruff: noqa: N803,N806 - - -class IRMAAttestation(Attestation): - """ - IPv8 wrapper for IRMA-based attestations. - """ - - def __init__(self, sign_date: int, proofd: ProofD, z: int | None = None) -> None: - """ - Create a new IPv8 attestation for the given diclosure proof and Z value. - """ - self.sign_date = sign_date - self.proofd = proofd - self.z = z - - def serialize(self) -> bytes: - """ - Make this attestation transferrable. - """ - return ipack(self.sign_date) + serialize_proof_d(self.proofd) - - def serialize_private(self, PK: None) -> bytes: - """ - We don't use a base key for serialization. - """ - return ipack(cast(int, self.z)) + ipack(self.sign_date) + serialize_proof_d(self.proofd) - - @classmethod - def unserialize(cls: type[IRMAAttestation], s: bytes, id_format: str) -> IRMAAttestation: # noqa: ARG003 - """ - Read an attestation from its serialized form. - """ - sign_date, rem = iunpack(s) - return IRMAAttestation(sign_date, unserialize_proof_d(rem)) - - @classmethod - def unserialize_private(cls: type[IRMAAttestation], SK: None, # noqa: ARG003 - s: bytes, id_format: str) -> IRMAAttestation: # noqa: ARG003 - """ - Read the secret part of an attestation from its serialized form. - """ - z, rem = iunpack(s) - sign_date, rem = iunpack(rem) - return IRMAAttestation(sign_date, unserialize_proof_d(rem), z) - - -class KeyStub: - """ - We don't use an IPv8 key for this algorithm. - """ - - def public_key(self) -> KeyStub: - """ - The public part of this key. - """ - return self - - def serialize(self) -> bytes: - """ - The serialized form of this key. - """ - return b'' - - @classmethod - def unserialize(cls: type[KeyStub], s: bytes) -> KeyStub: # noqa: ARG003 - """ - Load the key from the given bytes. - """ - return KeyStub() - - -class IRMAExactAlgorithm(IdentityAlgorithm): - """ - IPv8 wrapper around the IRMA business logic. - """ - - def __init__(self, id_format: str, formats: dict[str, dict[str, Any]]) -> None: - """ - Create a new IRMA wrapper. - """ - super().__init__(id_format, formats) - - # Check algorithm match - if formats[id_format]["algorithm"] != "irmaexact": - msg = "Identity format linked to wrong algorithm" - raise RuntimeError(msg) - - self.issuer_pk = formats[self.id_format]["issuer_pk"] - self.attribute_order = formats[self.id_format]["order"] - self.validity = formats[self.id_format]["validity"] - - self.base_meta = { - "credential": formats[self.id_format]["credential"], - "keyCounter": formats[self.id_format]["keyCounter"], - "validity": formats[self.id_format]["validity"] - } - - self.system_parameters = DefaultSystemParameters[1024] - self.challenge_count = 8 - - def generate_secret_key(self) -> KeyStub: - """ - Generate a fake secret key, we need none. - """ - return KeyStub() - - def load_secret_key(self, serialized: bytes) -> KeyStub: - """ - Load a fake secret key, we need none. - """ - return KeyStub() - - def load_public_key(self, serialized: bytes) -> KeyStub: - """ - Load a fake public key, we need none. - """ - return KeyStub() - - def get_attestation_class(self) -> type[IRMAAttestation]: - """ - Get our class. - """ - return IRMAAttestation - - def attest(self, PK: KeyStub, value: bytes) -> bytes: - """ - Not implemented. - """ - raise NotImplementedError("Only import_blob is supported (now) for IRMA.") - - def certainty(self, value: bytes, aggregate: dict) -> float: - """ - Get the certainty that the given value is equal to the attestation in the aggregate. - """ - value_json = {"attributes": json.loads(value)} - value_json.update(self.base_meta) - attestation = cast(IRMAAttestation, aggregate['attestation']) - attr_ints, sign_date = make_attribute_list(value_json, self.attribute_order, - (self.validity, attestation.sign_date)) - reconstructed_attr_map = {} - for i in range(len(attr_ints)): - reconstructed_attr_map[i + 1] = attr_ints[i] - - verified = 0.0 - failure = False - for k, v in aggregate.items(): - if k != 'attestation' and v: - challenge_verif, _ = iunpack(k) - p = attestation.proofd.Copy() - p.ADisclosed = reconstructed_attr_map - Ap, Zp = p.ChallengeContribution(self.issuer_pk) - p.C, _ = iunpack(v) - reconstructed_challenge = createChallenge(challenge_verif, challenge_verif, [Ap, Zp], False) - if p.VerifyWithChallenge(self.issuer_pk, reconstructed_challenge): - verified += 1.0 - else: - failure = True - - return 0.0 if failure else (verified / self.challenge_count) - - def create_challenges(self, PK: KeyStub, attestation: IRMAAttestation) -> list[bytes]: - """ - Generate the raw messages to be sent over the Internet as challenges. - """ - return [ipack(int(binascii.hexlify(os.urandom(32)), 16) % self.issuer_pk.N) - for _ in range(self.challenge_count)] - - def create_challenge_response(self, SK: KeyStub, attestation: IRMAAttestation, challenge: bytes) -> bytes: - """ - Create a response to a given challenge to our attestation. - """ - return challenge_response(attestation.proofd, cast(int, attestation.z), challenge) - - def create_certainty_aggregate(self, attestation: IRMAAttestation | None) -> dict: - """ - Create the aggregation dictionary (just one key with the attestation). - """ - return {'attestation': attestation} - - def create_honesty_challenge(self, PK: KeyStub, value: int) -> bytes: - """ - Not implemented. - """ - raise NotImplementedError - - def process_honesty_challenge(self, value: int, response: bytes) -> bool: - """ - Not implemented. - """ - raise NotImplementedError - - def process_challenge_response(self, aggregate: dict, challenge: bytes, response: bytes) -> dict: - """ - Process the response to our challenge. - """ - aggregate[challenge] = response - return aggregate - - def import_blob(self, blob: bytes) -> tuple[bytes, KeyStub]: - """ - Import raw data needed to construct an attestation for this algorithm. - """ - blob_json = json.loads(blob) - - sign_date = blob_json["sign_date"] - proofd = unserialize_proof_d(binascii.unhexlify(blob_json["proofd"])) - z = blob_json["z"] - - inst = self.get_attestation_class()(sign_date, proofd, z) - - return inst.serialize_private(None), KeyStub() diff --git a/ipv8/attestation/wallet/irmaexact/enroll_script.py b/ipv8/attestation/wallet/irmaexact/enroll_script.py deleted file mode 100644 index b66235f88..000000000 --- a/ipv8/attestation/wallet/irmaexact/enroll_script.py +++ /dev/null @@ -1,224 +0,0 @@ -""" -Additional dependencies: - -python3 -m pip install PyQtWebEngine - -To run: -export PYTHONPATH=. -python3 -m ipv8.attestation.wallet.irmaexact.enroll_script -""" - -# ruff: noqa - -import base64 -import binascii -import json -import sys -import time - -from PyQt5.QtCore import * -from PyQt5.QtWebEngineWidgets import * -from PyQt5.QtWidgets import QApplication - -import urllib3 - -from .gabi.attributes import make_attribute_list -from .gabi.builder import BuildDistributedProofList, Challenge, CredentialBuilder, IssueCommitmentMessage, IssueSignatureMessage -from .gabi.keys import CLSignature, DefaultSystemParameters -from .gabi.proofs import ProofP, ProofPCommitment, ProofS -from .keydump import nijmegen_pk_1623505755 as nijmegen_pk -from .wrappers import serialize_proof_d -from ..primitives.cryptography_wrapper import generate_safe_prime -from ....util import int2byte - -my_app = QApplication(sys.argv) -my_web = QWebEngineView() -profile = QWebEngineProfile("storage", my_web) -cookie_store = profile.cookieStore() -cookie_store.deleteAllCookies() - -token = None - - -def print_result(r): - global token - if r: - u = json.loads(r)["u"].encode() - token = u.split(b'/')[-1].decode() - my_web.hide() - my_app.quit() - - -def page_loaded(ok): - if ok and my_web.url() == QUrl('https://services.nijmegen.nl/irma/gemeente/issue?'): - my_web.page().runJavaScript("window.irmaSessionPtr", print_result) - - -my_web.loadFinished.connect(page_loaded) -my_web.load(QUrl("https://services.nijmegen.nl/irma/gemeente/issue")) -my_web.setWindowTitle("Annoying Pop-up") -my_web.show() - -my_app.exec_() - -secret = generate_safe_prime(DefaultSystemParameters[1024].Lm) - -no_pin = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\\n' - - -def do_get(u): - http = urllib3.PoolManager() - headers = {'Content-Type': 'application/json', - "X-IRMA-MinProtocolVersion": "2.4", - "X-IRMA-MaxProtocolVersion": "2.4"} - - r = http.request('GET', u, headers=headers) - try: - out = json.loads(r.data) - except ValueError: - out = r.data - - return out - - -def do_post(u, content, extra_headers={}): - http = urllib3.PoolManager() - headers = {'Content-Type': 'application/json'} - headers.update(extra_headers) - - r = http.request('POST', u, headers=headers, body=content) - try: - out = json.loads(r.data) - except ValueError: - out = r.data - - return out - - -u = "https://keyshare.privacybydesign.foundation/tomcat/irma_keyshare_server/api/v1/client/register" -u = do_post(u, "{\"username\":\"\",\"pin\":\"%s\",\"email\":null,\"language\":\"en\"}" % no_pin)['u'] -response = do_get(u) -context = int(binascii.hexlify(base64.b64decode(response["context"])), 16) -nonce = int(binascii.hexlify(base64.b64decode(response["nonce"])), 16) - -irmaid = response["credentials"][0]["attributes"]["pseudonym"] -u = "https://keyshare.privacybydesign.foundation/tomcat/irma_keyshare_server/api/v1/users/verify/pin" -jwt = do_post(u, f"{{\"id\":\"{irmaid}\",\"pin\":\"{no_pin}\"}}")["message"] - -extra_headers = {"Authorization": jwt, "X-IRMA-Keyshare-Username": ""} -u = "https://keyshare.privacybydesign.foundation/tomcat/irma_keyshare_server/api/v1/prove/getCommitments" -response = do_post(u, "[" - "{\"issuer\":{\"identifier\":\"pbdf.gemeente\"},\"counter\": 1}," - "{\"issuer\":{\"identifier\":\"pbdf.gemeente\"},\"counter\": 1}" - "]", extra_headers=extra_headers) -Pcommit = response['c'][0][1]['Pcommit'] -P = response['c'][0][1]['P'] - -# Get nijmegen issuance -u = 'https://gw.nijmegen.nl/irma/session/%s/' % token -issuance_output = do_get(u) -context = int(binascii.hexlify(base64.b64decode(issuance_output['context'])), 16) -nonce1 = int(binascii.hexlify(base64.b64decode(issuance_output['nonce'])), 16) - -u = "https://keyshare.privacybydesign.foundation/tomcat/irma_keyshare_server/api/v1/prove/getResponse" -# 2 because: 'pbdf.gemeente.address' and 'pbdf.gemeente.personalData' -cbs = [CredentialBuilder(nijmegen_pk, context, secret, nonce1) for _ in range(2)] -for cb in cbs: - cb.MergeProofPCommitment(ProofPCommitment(P, Pcommit)) -challenge = Challenge(cbs, context, nonce1, False) -commit_jwt = do_post(u, str(challenge), extra_headers=extra_headers) - -proofP_d = commit_jwt.split(b'.')[1] -lens = len(proofP_d) -lenx = lens - (lens % 4 if lens % 4 else 4) -proofP_d = json.loads(base64.decodebytes(proofP_d[:lenx]) + b'}')["ProofP"] -P = proofP_d["P"] -c = proofP_d["c"] -s_response = proofP_d["s_response"] -proofP = ProofP(P, c, s_response) - -u = 'https://gw.nijmegen.nl/irma/session/%s/status' % token - -while do_get(u) != "CONNECTED": - time.sleep(0.5) - -u = 'https://gw.nijmegen.nl/irma/session/%s/commitments' % token - -proofs = BuildDistributedProofList(cbs, challenge, []) -commitMsg = IssueCommitmentMessage(None, proofs, nonce1) - - -def proof_to_str(proof): - return ('{"U": ' + str(proof.U) - + ', "c": ' + str(proof.C) - + ', "v_prime_response": ' + str(proof.VPrimeResponse) - + ', "s_response": ' + str(proof.SResponse) + '}') - - -outjson = '{' -outjson += '"U": null,' -outjson += '"combinedProofs": [' + ', '.join(proof_to_str(p) for p in commitMsg.Proofs) + '],' -outjson += '"indices": [],' -outjson += '"n_2": ' + str(commitMsg.Nonce2) + "," -outjson += '"proofPJwt": "",' -outjson += '"proofPJwts": {"pbdf": "' + commit_jwt.decode() + '"}' -outjson += '}' - -output_proof = do_post(u, outjson) - - -def b64_to_int(s): - return str_to_int(base64.b64decode(s)) - - -def str_to_int(s): - if isinstance(s, str): - s = b''.join(int2byte(ord(c)) for c in s) - if s is None: - return 0 - if s == b"": - return 1 - return int(binascii.hexlify(s), 16) - - -isms = [] -for ism in output_proof: - proof_s_desc = ism["proof"] - sig_desc = ism["signature"] - proof_s = ProofS(b64_to_int(proof_s_desc["c"]), b64_to_int(proof_s_desc["e_response"])) - signature = CLSignature(b64_to_int(sig_desc["A"]), b64_to_int(sig_desc["e"]), b64_to_int(sig_desc["v"])) - isms.append(IssueSignatureMessage(signature, proof_s)) - - -order_map = { - 'pbdf.gemeente.address': ["street", "houseNumber", "zipcode", "municipality", "city"], - 'pbdf.gemeente.personalData': ["initials", "firstnames", "prefix", "familyname", "fullname", "gender", - "nationality", "surname", "dateofbirth", "cityofbirth", "countryofbirth", "over12", - "over16", "over18", "over21", "over65", "bsn", "digidlevel"] -} - - -for i in range(len(cbs)): - cb = cbs[i] - ism = isms[i] - ordering = order_map[issuance_output["credentials"][i]['credential']] - attribute_ints, signing_date = make_attribute_list(issuance_output["credentials"][i], ordering) - - credential = cb.ConstructCredential(ism, attribute_ints) - builder = credential.CreateDisclosureProofBuilder(list(range(1, len(attribute_ints) + 1))) - builder.MergeProofPCommitment(ProofPCommitment(P, Pcommit)) - commit_randomizer = generate_safe_prime(nijmegen_pk.Params.LmCommit) - A, Z = builder.Commit(commit_randomizer) - p = builder.CreateProof(challenge) - p.MergeProofP(proofP, nijmegen_pk) - - attr_output = '{\n' - attr_output += '\t"sign_date": ' + str(signing_date) + ',\n' - attr_output += '\t"proofd": "' + binascii.hexlify(serialize_proof_d(p)).decode() + '",\n' - attr_output += '\t"z": ' + str(Z) + '\n' - attr_output += '}' - - print("*" * 20) # noqa: T201 - print("Attribute:", issuance_output["credentials"][i]['credential']) # noqa: T201 - print(attr_output) # noqa: T201 - print("*" * 20) # noqa: T201 diff --git a/ipv8/attestation/wallet/irmaexact/gabi/__init__.py b/ipv8/attestation/wallet/irmaexact/gabi/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/ipv8/attestation/wallet/irmaexact/gabi/attributes.py b/ipv8/attestation/wallet/irmaexact/gabi/attributes.py deleted file mode 100644 index d89f1c1ff..000000000 --- a/ipv8/attestation/wallet/irmaexact/gabi/attributes.py +++ /dev/null @@ -1,209 +0,0 @@ -""" -Copyright (c), Privacy By Design Foundation -All rights reserved. - -This source code has been ported from https://github.com/privacybydesign/irmago -The authors of this file are not -in any way- affiliated with the original authors or organizations. -""" -from __future__ import annotations - -import binascii -import calendar -import datetime -import hashlib -import time -from typing import Any - -from .....util import int2byte - -# ruff: noqa: N801,N802,N803,N806,N816 - -ExpiryFactor = 60 * 60 * 24 * 7 -metadataLength = 1 + 3 + 2 + 2 + 16 - - -class metadataField: - """ - Metadata position information. - """ - - def __init__(self, length: int, offset: int) -> None: - """ - Create a new metadata field descriptor. - """ - self.length = length - self.offset = offset - - -versionField = metadataField(1, 0) -signingDateField = metadataField(3, 1) -validityField = metadataField(2, 4) -keyCounterField = metadataField(2, 6) -credentialID = metadataField(16, 8) - - -def int_to_str(n: int) -> bytes: - """ - Covert an integer of unbounded size to bytes. - """ - hexInt = hex(n).lstrip('0x').rstrip('L') - if (len(hexInt) % 2) == 1: - hexInt = '0' + hexInt - return binascii.unhexlify(hexInt) - - -def shortToByte(x: int) -> bytes: - """ - Convert a short (stored in a Python int type) to bytes. - """ - return int_to_str(x)[-2:] - - -class MetadataAttribute: - """ - Metadata values. - """ - - def __init__(self, version: bytes) -> None: - """ - Create a new empty metadata container. - """ - self.Int = 0 - self.pk = None - self.Conf = None - - self.setField(versionField, version) - self.setSigningDate() - self.setKeyCounter(0) - self.setExpiryDate() - - def Bytes(self) -> bytes: - """ - Convert this metadata to bytes. - """ - bytez = int_to_str(self.Int) - if len(bytez) < metadataLength: - bytez += b'\x00' * (metadataLength - len(bytez)) - return bytez - - def setField(self, field: metadataField, value: bytes) -> None: - """ - Set a given metadata field position to a given value. - """ - bytez_array = [int2byte(c) if isinstance(c, int) else c for c in self.Bytes()] - startindex = field.length - len(value) - for i in range(field.length): - if i < startindex: - bytez_array[i + field.offset] = b'\x00' - else: - bytez_array[i + field.offset] = value[i - startindex:i - startindex + 1] - - self.Int = int(binascii.hexlify(b''.join(bytez_array)), 16) - - def field(self, field: metadataField) -> bytes: - """ - Retrieve the value of a given field. - """ - return self.Bytes()[field.offset:field.offset + field.length] - - def setSigningDate(self, timestamp: int | None = None) -> None: - """ - Set the date of signing in the metadata. - - Note that the timestamp is a short in units of ``ExpiryFactor``. - """ - if timestamp: - self.setField(signingDateField, shortToByte(timestamp)) - else: - self.setField(signingDateField, shortToByte(int(time.time() / ExpiryFactor))) - - def setKeyCounter(self, i: int) -> None: - """ - Set the key counter field to a given value. - """ - self.setField(keyCounterField, shortToByte(i)) - - def SigningDate(self) -> int: - """ - Get the signing date in seconds since the epoch (like ``int(time.time())``). - """ - bytez_array = [int2byte(c) if isinstance(c, int) else c for c in self.field(signingDateField)] - bytez_array = bytez_array[1:] - return int(binascii.hexlify(b''.join(bytez_array)), 16) * ExpiryFactor - - def setValidityDuration(self, weeks: int) -> None: - """ - Set the value of the validity duration field (in weeks). - """ - self.setField(validityField, shortToByte(weeks)) - - def setExpiryDate(self) -> None: - """ - Set the default validity duration. - """ - expiry = datetime.datetime.now() # noqa: DTZ005 - month = expiry.month - 1 + 6 - year = expiry.year + month // 12 - month = month % 12 + 1 - day = min(expiry.day, calendar.monthrange(year, month)[1]) - fexpiry = time.mktime(datetime.date(year, month, day).timetuple()) - signing = self.SigningDate() - self.setValidityDuration(int((fexpiry - signing) / ExpiryFactor)) - - def setExpiryDateFromTimestamp(self, expiry: float) -> None: - """ - Set the validity duration from a given expiry timestamp (like ``time.time()``). - """ - signing = self.SigningDate() - self.setValidityDuration(int((expiry - signing) / ExpiryFactor)) - - def setCredentialTypeIdentifier(self, the_id: bytes) -> None: - """ - Set the credential type field. - """ - bytez = hashlib.sha256(the_id).digest() - self.setField(credentialID, bytez[:16]) - - -def make_attribute_list(cr: dict[str, Any], attribute_order: list[str] | None = None, - validity_signing: tuple[int, int | None] | None = None) -> tuple[list[int], int]: - """ - cr = - { - u'attributes': { ... "name": "value" ... }, - u'credential': u'pbdf.nijmegen.address', - u'keyCounter': 0, - u'validity': 1570123936 - }. - - :param attribute_order: the order in which to handle the keys - :type attribute_order: list - """ - meta = MetadataAttribute(b'\x03') - meta.setKeyCounter(cr['keyCounter']) - meta.setCredentialTypeIdentifier(cr['credential'].encode('utf-8')) - if validity_signing: - meta.setValidityDuration(validity_signing[0]) - meta.setSigningDate(validity_signing[1]) - else: - meta.setSigningDate() - meta.setExpiryDateFromTimestamp(cr['validity']) - signing_date = int(binascii.hexlify(meta.field(signingDateField)), 16) - - attrs = [meta.Int] - attr_map = cr["attributes"] - attribute_order = attribute_order or attr_map.keys() - - for k in attribute_order: - if attr_map.get(k, None) is None: - attrs.append(0) - elif not attr_map[k]: - attrs.append(1) - else: - encoded = attr_map[k].encode('utf-8') - v = int(binascii.hexlify(b''.join(int2byte(c) if isinstance(c, int) else c for c in encoded)), 16) - v <<= 1 - v += 1 - attrs.append(v) - - return attrs, signing_date diff --git a/ipv8/attestation/wallet/irmaexact/gabi/builder.py b/ipv8/attestation/wallet/irmaexact/gabi/builder.py deleted file mode 100644 index 33e4691eb..000000000 --- a/ipv8/attestation/wallet/irmaexact/gabi/builder.py +++ /dev/null @@ -1,328 +0,0 @@ -""" -Copyright (c) 2016, Maarten Everts -All rights reserved. - -This source code has been ported from https://github.com/privacybydesign/gabi -The authors of this file are not -in any way- affiliated with the original authors or organizations. -""" -from __future__ import annotations - -from random import randint -from typing import cast - -from cryptography.hazmat.primitives.asymmetric.rsa import _modinv - -from ...primitives.value import FP2Value -from .. import secure_randint -from .credential import Credential -from .keys import CLSignature, DefaultSystemParameters, PrivateKey, PublicKey, signMessageBlockAndCommitment -from .proofs import ProofP, ProofPCommitment, ProofS, ProofU, createChallenge, hashCommit - -# ruff: noqa: N802,N803,N806 - - -class Issuer: - """ - A signature issuer. - """ - - def __init__(self, Sk: PrivateKey, Pk: PublicKey, Context: int) -> None: - """ - Create a new issuer. - """ - self.Sk = Sk - self.Pk = Pk - self.Context = Context - - def IssueSignature(self, U: int, attributes: list[int], nonce2: int) -> IssueSignatureMessage: - """ - Generate an issued signature message. - """ - signature = self.signCommitmentAndAttributes(U, attributes) - proof = self.proveSignature(signature, nonce2) - return IssueSignatureMessage(signature, proof) - - def signCommitmentAndAttributes(self, U: int, attributes: list[int]) -> CLSignature: - """ - Sign the commitment to the U value and given attribute values. - """ - return signMessageBlockAndCommitment(self.Sk, self.Pk, U, [0, *attributes]) - - def randomElementMultiplicativeGroup(self, modulus: int) -> int: - """ - Generate a random number that is relatively coprime to the modulus. - """ - r = 0 - while r <= 0 or _modinv(r, modulus) == 1: - r = randint(1, modulus - 1) - return r - - def proveSignature(self, signature: CLSignature, nonce2: int) -> ProofS: - """ - Create a proof of signature issuance. - """ - Q = FP2Value(self.Pk.N, signature.A).intpow(signature.E).a - groupModulus = self.Sk.PPrime * self.Sk.QPrime - d = FP2Value(groupModulus, signature.E).inverse().normalize().a - - eCommit = self.randomElementMultiplicativeGroup(groupModulus) - ACommit = FP2Value(self.Pk.N, Q).intpow(eCommit).a - - c = hashCommit([self.Context, Q, signature.A, nonce2, ACommit], False) - eResponse = (eCommit - c * d) % groupModulus - - return ProofS(c, eResponse) - - -def GetProofU(pl: list, n: int) -> ProofU | None: - """ - Get the i'th (starting at 0) ProofU instance from a list of proof instances. - """ - count = 0 - for proof in pl: - if isinstance(proof, ProofU): - if count == n: - return proof - count += 1 - return None - - -def GetFirstProofU(pl: list) -> ProofU | None: - """ - Get the first ProofU from a given list of proofs. - """ - return GetProofU(pl, 0) - - -def challengeContributions(pl: list, publicKeys: list[PublicKey], context: int, nonce: int) -> list[int]: - """ - Aggregate all challenge contributions of a given proof list. - """ - contributions = [] - for i in range(len(pl)): - proof = pl[i] - contributions.extend(proof.ChallengeContribution(publicKeys[i])) - return contributions - - -def Verify(pl: list, publicKeys: list[PublicKey], context: int, nonce: int, issig: bool, - keyshareServers: list | None = None) -> bool: - """ - Verify a list of proofs for a list of public keys. - """ - if keyshareServers is None: - keyshareServers = [] - if not pl or len(pl) != len(publicKeys) or (len(keyshareServers) > 0 and len(pl) != len(keyshareServers)): - return False - - secretkeyResponses = {} - - contributions = challengeContributions(pl, publicKeys, context, nonce) - expectedChallenge = createChallenge(context, nonce, contributions, issig) - - kss = "" - - for i in range(len(pl)): - proof = pl[i] - if not proof.VerifyWithChallenge(publicKeys[i], expectedChallenge): - return False - if len(keyshareServers) > 0: - kss = keyshareServers[i] - if kss not in secretkeyResponses: - secretkeyResponses[kss] = proof.SecretKeyResponse() - elif secretkeyResponses[kss] != proof.SecretKeyResponse(): - return False - - return True - - -def Challenge(builders: list[CredentialBuilder], context: int, nonce: int, issig: bool) -> int: - """ - Create a challenge. - """ - skCommitment = secure_randint(DefaultSystemParameters[1024].LmCommit) - - commitmentValues = [] - for pb in builders: - commitmentValues.extend(pb.Commit(skCommitment)) - - return createChallenge(context, nonce, commitmentValues, issig) - - -def BuildDistributedProofList(builders: list[CredentialBuilder], challenge: int, - proofPs: list[ProofP]) -> list[ProofU] | None: - """ - Create a proof list from multiple partial proofs. - """ - if proofPs and len(builders) != len(proofPs): - return None - - proofs = [] - - for i in range(len(builders)): - v = builders[i] - proofs.append(v.CreateProof(challenge)) - if proofPs and proofPs[i]: - proofs[i].MergeProofP(proofPs[i], v.PublicKey()) - - return proofs - - -def BuildProofList(builders: list[CredentialBuilder], context: int, nonce: int, issig: bool) -> list[ProofU] | None: - """ - Create a list of U proofs without distributed partial proofs. - """ - challenge = Challenge(builders, context, nonce, issig) - return BuildDistributedProofList(builders, challenge, []) - - -class IssueCommitmentMessage: - """ - JWT commitment information. - """ - - def __init__(self, U: int | None, Proofs: list[ProofU] | None, Nonce2: int, - ProofPjwt: None = None, ProofPjwts: None = None) -> None: - """ - Create a new issued commitment message container. - """ - self.U = U - self.Nonce2 = Nonce2 - self.Proofs = Proofs - self.ProofPjwt = ProofPjwt - self.ProofPjwts = ProofPjwts - - -class IssueSignatureMessage: - """ - Issued signature information. - """ - - def __init__(self, Signature: CLSignature, Proof: ProofS) -> None: - """ - Create a new signature message container. - """ - self.Proof = Proof - self.Signature = Signature - - -def commitmentToSecret(pk: PublicKey, secret: int) -> tuple[int, int]: - """ - Create a commitment for a given value. - """ - vPrime = secure_randint(pk.Params.LvPrime) - - Sv = FP2Value(pk.N, pk.S).intpow(vPrime).a - R0s = FP2Value(pk.N, pk.R[0]).intpow(secret).a - - return vPrime, (Sv * R0s) % pk.N - - -class CredentialBuilder: - """ - Helper class to create credentials. - """ - - def __init__(self, pk: PublicKey, context: int, secret: int, nonce2: int) -> None: - """ - Create a new credential builder. - """ - vPrime, U = commitmentToSecret(pk, secret) - self.pk = pk - self.context = context - self.secret = secret - self.vPrime = vPrime - self.u = U - self.uCommit = 1 - self.nonce2 = nonce2 - - self.proofPcomm: ProofPCommitment | None = None - self.skRandomizer: int | None = None - self.vPrimeCommit: int | None = None - - def CommitToSecretAndProve(self, nonce1: int) -> IssueCommitmentMessage: - """ - Create a commitment and associated message. - """ - proofU = self.proveCommitment(self.u, nonce1) - return IssueCommitmentMessage(self.u, [proofU], self.nonce2) - - def CreateIssueCommitmentMessage(self, proofs: list[ProofU]) -> IssueCommitmentMessage: - """ - Create the associated message for given U commitments. - """ - return IssueCommitmentMessage(self.u, proofs, self.nonce2) - - def ConstructCredential(self, msg: IssueSignatureMessage, attributes: list[int]) -> Credential | None: - """ - Create a credential from the given signature message and our attributes. - """ - if not msg.Proof.Verify(self.pk, msg.Signature, self.context, self.nonce2): - return None - - signature = CLSignature(msg.Signature.A, msg.Signature.E, msg.Signature.V + self.vPrime) - if self.proofPcomm: - signature.KeyshareP = self.proofPcomm.P - - exponents = [self.secret, *attributes] - - if not signature.Verify(self.pk, exponents): - return None - - return Credential(self.pk, exponents, signature) - - def proveCommitment(self, U: int, nonce1: int) -> ProofU: - """ - Create a proof for the commitment to U. - """ - sCommit = secure_randint(self.pk.Params.LsCommit) - vPrimeCommit = secure_randint(self.pk.Params.LvPrimeCommit) - - Sv = FP2Value(self.pk.N, self.pk.S).intpow(vPrimeCommit).a - R0s = FP2Value(self.pk.N, self.pk.R[0]).intpow(sCommit).a - Ucommit = (Sv * R0s) % self.pk.N - - c = hashCommit([self.context, U, Ucommit, nonce1], False) - sResponse = (c * self.secret) + sCommit - vPrimeResponse = (c * self.vPrime) + vPrimeCommit - - return ProofU(U, c, vPrimeResponse, sResponse) - - def MergeProofPCommitment(self, commitment: ProofPCommitment) -> None: - """ - Merge in a given commitment to a ProofP. - """ - self.proofPcomm = commitment - self.uCommit = (self.uCommit * commitment.Pcommit) % self.pk.N - - def PublicKey(self) -> PublicKey: - """ - Our public key. - """ - return self.pk - - def Commit(self, skRandomizer: int) -> list[int]: - """ - Create a new commitment for the given randomizer value. - """ - self.skRandomizer = skRandomizer - self.vPrimeCommit = secure_randint(self.pk.Params.LvPrimeCommit) - - sv = FP2Value(self.pk.N, self.pk.S).intpow(self.vPrimeCommit).a - r0s = FP2Value(self.pk.N, self.pk.R[0]).intpow(self.skRandomizer).a - self.uCommit = (self.uCommit * sv * r0s) % self.pk.N - - ucomm = self.u - if self.proofPcomm: - ucomm = (ucomm * self.proofPcomm.P) % self.pk.N - - return [ucomm, self.uCommit] - - def CreateProof(self, challenge: int) -> ProofU: - """ - Create a new proof for U for the given challenge. - """ - sResponse = cast(int, self.skRandomizer) + challenge * self.secret - vPrimeResponse = cast(int, self.vPrimeCommit) + challenge * self.vPrime - - return ProofU(self.u, challenge, vPrimeResponse, sResponse) diff --git a/ipv8/attestation/wallet/irmaexact/gabi/credential.py b/ipv8/attestation/wallet/irmaexact/gabi/credential.py deleted file mode 100644 index c841d378d..000000000 --- a/ipv8/attestation/wallet/irmaexact/gabi/credential.py +++ /dev/null @@ -1,179 +0,0 @@ -""" -Copyright (c) 2016, Maarten Everts -All rights reserved. - -This source code has been ported from https://github.com/privacybydesign/gabi -The authors of this file are not -in any way- affiliated with the original authors or organizations. -""" -from __future__ import annotations - -from typing import TYPE_CHECKING - -from ...primitives.attestation import sha256_as_int -from ...primitives.value import FP2Value -from .. import secure_randint -from .proofs import ProofD, ProofPCommitment, hashCommit - -if TYPE_CHECKING: - from .keys import CLSignature, PublicKey - -# ruff: noqa: N802,N803,N806 - - -class Credential: - """ - A credential (attributes + public key + signature). - """ - - def __init__(self, Pk: PublicKey, Attributes: list[int], Signature: CLSignature) -> None: - """ - Create a new credential. - """ - self.Signature = Signature - self.Pk = Pk - self.Attributes = Attributes - - def CreateDisclosureProof(self, disclosedAttributes: dict[int, int], context: int, nonce1: int) -> ProofD: - """ - Create a disclosure proof for the specified attributes and their values. - """ - undisclosedAttributes = getUndisclosedAttributes(disclosedAttributes, len(self.Attributes)) - - randSig = self.Signature.Randomize(self.Pk) - - eCommit = secure_randint(self.Pk.Params.LeCommit) - vCommit = secure_randint(self.Pk.Params.LvCommit) - - aCommits = {} - - for v in undisclosedAttributes: - aCommits[v] = secure_randint(self.Pk.Params.LmCommit) - - Ae = FP2Value(self.Pk.N, randSig.A).intpow(eCommit).a - Sv = FP2Value(self.Pk.N, self.Pk.S).intpow(vCommit).a - Z = (Ae * Sv) % self.Pk.N - - for v in undisclosedAttributes: - Z = (Z * FP2Value(self.Pk.N, self.Pk.R[v]).intpow(aCommits[v]).a) % self.Pk.N - - c = hashCommit([context, randSig.A, Z, nonce1], False) - - ePrime = randSig.E - (1 << (self.Pk.Params.Le - 1)) - eResponse = c * ePrime + eCommit - vResponse = c * randSig.V + vCommit - - aResponses = {} - for v in undisclosedAttributes: - exp = self.Attributes[v] - if exp.bit_length() > self.Pk.Params.Lm: - exp = sha256_as_int(str(exp)) - t = c * exp - aResponses[v] = t + aCommits[v] - - aDisclosed = {} - for v in disclosedAttributes: - aDisclosed[v] = self.Attributes[v] - - return ProofD(c, randSig.A, eResponse, vResponse, aResponses, aDisclosed) - - def CreateDisclosureProofBuilder(self, disclosedAttributes: dict[int, int]) -> DisclosureProofBuilder: - """ - Create a disclosure proof builder for the specified attributes and their values. - """ - return DisclosureProofBuilder(self.Signature.Randomize(self.Pk), - secure_randint(self.Pk.Params.LeCommit), - secure_randint(self.Pk.Params.LvCommit), - {v: secure_randint(self.Pk.Params.LmCommit) for v - in getUndisclosedAttributes(disclosedAttributes, len(self.Attributes))}, - 1, - disclosedAttributes, - getUndisclosedAttributes(disclosedAttributes, len(self.Attributes)), - self.Pk, - self.Attributes) - - -class DisclosureProofBuilder: - """ - Helper to create disclosure proofs. - """ - - def __init__(self, randomizedSignature: CLSignature, # noqa: PLR0913 - eCommit: int, vCommit: int, - attrRandomizers: dict[int, int], - z: int, - disclosedAttributes: dict[int, int], undisclosedAttributes: list[int], - pk: PublicKey, attributes: list[int]) -> None: - """ - Create a new helper for the given information. - """ - self.randomizedSignature = randomizedSignature - self.eCommit = eCommit - self.vCommit = vCommit - self.attrRandomizers = attrRandomizers - self.z = z - self.disclosedAttributes = disclosedAttributes - self.undisclosedAttributes = undisclosedAttributes - self.pk = pk - self.attributes = attributes - - def MergeProofPCommitment(self, commitment: ProofPCommitment) -> None: - """ - Merge in a partial proof to reconstruct Z. - """ - self.z = (self.z * commitment.Pcommit) % self.pk.N - - def PublicKey(self) -> PublicKey: - """ - Get the public key. - """ - return self.pk - - def Commit(self, skRandomizer: int) -> list[int]: - """ - Get A and Z for the given randomizer. - """ - self.attrRandomizers[0] = skRandomizer - - Ae = FP2Value(self.pk.N, self.randomizedSignature.A).intpow(self.eCommit).a - Sv = FP2Value(self.pk.N, self.pk.S).intpow(self.vCommit).a - self.z = (self.z * Ae * Sv) % self.pk.N - - for v in self.undisclosedAttributes: - self.z = (self.z * FP2Value(self.pk.N, self.pk.R[v]).intpow(self.attrRandomizers[v]).a) % self.pk.N - - return [self.randomizedSignature.A, self.z] - - def CreateProof(self, challenge: int) -> ProofD: - """ - Create a disclosure proof for the given challange. - """ - ePrime = self.randomizedSignature.E - (1 << (self.pk.Params.Le - 1)) - eResponse = challenge * ePrime + self.eCommit - vResponse = challenge * self.randomizedSignature.V + self.vCommit - - aResponses = {} - for v in self.undisclosedAttributes: - exp = self.attributes[v] - if exp.bit_length() > self.pk.Params.Lm: - exp = sha256_as_int(str(exp)) - aResponses[v] = challenge * exp + self.attrRandomizers[v] - - aDisclosed = {v: self.attributes[v] for v in self.disclosedAttributes} - - return ProofD(challenge, self.randomizedSignature.A, eResponse, vResponse, aResponses, aDisclosed) - - def TimestampRequestContributions(self) -> tuple[int, list[int]]: - """ - Fill in the disclosed attributes into a complete list (0 when undisclosed). - """ - disclosed = [0] * len(self.attributes) - for i in self.disclosedAttributes: - disclosed[i] = self.attributes[i] - return self.randomizedSignature.A, disclosed - - -def getUndisclosedAttributes(disclosedAttributes: dict[int, int], numAttributes: int) -> list[int]: - """ - Get the keys of undisclosed attributes. - """ - return list(set(range(numAttributes)) - set(disclosedAttributes)) diff --git a/ipv8/attestation/wallet/irmaexact/gabi/keys.py b/ipv8/attestation/wallet/irmaexact/gabi/keys.py deleted file mode 100644 index 9585f5246..000000000 --- a/ipv8/attestation/wallet/irmaexact/gabi/keys.py +++ /dev/null @@ -1,328 +0,0 @@ -""" -Copyright (c) 2016, Maarten Everts -All rights reserved. - -This source code has been ported from https://github.com/privacybydesign/gabi -The authors of this file are not -in any way- affiliated with the original authors or organizations. -""" -from __future__ import annotations - -from binascii import hexlify -from os import urandom -from typing import cast - -from cryptography.hazmat.primitives.asymmetric.rsa import _modinv - -from .....util import byte2int, int2byte -from ...primitives.attestation import sha256_as_int -from ...primitives.cryptography_wrapper import generate_safe_prime, is_prime -from ...primitives.value import FP2Value -from .. import secure_randint - -DefaultEpochLength = 432000 - -# ruff: noqa: N802,N803,N806,N816 - - -class BaseParameters: - """ - Algorithm parameters for Gabi. - """ - - def __init__(self, LePrime: int, Lh: int, Lm: int, Ln: int, Lstatzk: int) -> None: - """ - Create new base parameters. - """ - self.LePrime = LePrime - self.Lh = Lh - self.Lm = Lm - self.Ln = Ln - self.Lstatzk = Lstatzk - - self.Lv = Ln + 2 * Lstatzk + Lh + Lm + 4 - self.Le = Lstatzk + Lh + Lm + 5 - self.LeCommit = LePrime + Lstatzk + Lh - self.LmCommit = Lm + Lstatzk + Lh - self.LRA = Ln + Lstatzk - self.LsCommit = Lm + Lstatzk + Lh + 1 - self.LvCommit = self.Lv + Lstatzk + Lh - self.LvPrime = Ln + Lstatzk - self.LvPrimeCommit = Ln + 2 * Lstatzk + Lh - - -DefaultSystemParameters = { - 1024: BaseParameters(120, 256, 256, 1024, 80), - 2048: BaseParameters(120, 256, 256, 2048, 128), - 4096: BaseParameters(120, 256, 512, 4096, 128) -} - - -class PrivateKey: - """ - Gabi private key. - """ - - def __init__(self, p: int, q: int, counter: int, expiryDate: int) -> None: - """ - Create a new private key. - """ - self.Counter = counter - self.ExpiryData = expiryDate - self.P = p - self.Q = q - self.PPrime = (p - 1) >> 1 - self.QPrime = (q - 1) >> 1 - - -class PublicKey: - """ - Gabi public key. - """ - - def __init__(self, N: int, Z: int, S: int, R: list[int], counter: int, expiryDate: int, # noqa: PLR0913 - param: BaseParameters | None = None) -> None: - """ - Create a new Gabi public key. - """ - self.Counter = counter - self.ExpiryDate = expiryDate - self.N = N - self.Z = Z - self.S = S - self.R = R - self.EpochLength = DefaultEpochLength - self.Params: BaseParameters = param or DefaultSystemParameters[N.bit_length()] - self.Issuer = "-" - - -def findMatch(safeprimes: list[int], param: BaseParameters, p: int) -> int | None: - """ - Select a safe prime from the given list that fits the Gabi protocol's requirements. - """ - for q in safeprimes: - if (p * q).bit_length() == param.Ln and (p % 8) != 0 and (q % 8) != 0: - return q - return None - - -def generateSafePrimePair(param: BaseParameters) -> tuple[int, int]: - """ - Generate a prime pair that fits Gabi's protocol requirements. - """ - primeSize = param.Ln // 2 - safeprimes: list[int] = [] - q = None - while True: - p = generate_safe_prime(primeSize) - pPrime = p >> 1 - pPrimeMod8 = pPrime % 8 - if pPrimeMod8 == 1: - continue - q = findMatch(safeprimes, param, p) - if not safeprimes or q is None: - safeprimes.append(p) - continue - break - return p, cast(int, q) - - -def legendreSymbol(a: int, p: int) -> int: - """ - Calculate the Legendre Symbol for numbner a and prime p. - """ - j = 1 - n = a % p - m = p - while n != 0: - t = 0 - while (n & 1) == 0: - n >>= 1 - t += 1 - tmp = m % 8 - if (t & 1) == 1 and tmp in {3, 5}: - j = -j - if (m % 4) == 3 or (n % 4) == 3: - j = -j - m = m % n - n, m = m, n - if m == 1: - return j - return 0 - - -def GenerateKeyPair(param: BaseParameters, numAttributes: int, counter: int, - expiryDate: int) -> tuple[PrivateKey, PublicKey]: - """ - Generate a new key pair for a given number of attributes. - """ - p, q = generateSafePrimePair(param) - priv = PrivateKey(p, q, counter, expiryDate) - - N = p * q - - while True: - S = secure_randint(param.Ln) - if S > N: - continue - if legendreSymbol(S, p) == 1 and legendreSymbol(S, q) == 1: - break - - primeSize = param.Ln // 2 - while True: - x = secure_randint(primeSize) - if x > 2 and x < N: - break - - Z = FP2Value(N, S).intpow(x).a - - R = [] - - for _i in range(numAttributes): - while True: - x = secure_randint(primeSize) - if x > 2 and x < N: - break - R.append(FP2Value(N, S).intpow(x).a) - - pubk = PublicKey(N, Z, S, R, counter, expiryDate, param=param) - - if not SignMessageBlock(priv, pubk, [1]).Verify(pubk, [1]): - return GenerateKeyPair(param, numAttributes, counter, expiryDate) - return priv, pubk - - -class CLSignature: - """ - A Camenisch-Lysyanskaya signature. - """ - - def __init__(self, A: int, E: int, V: int, KeyshareP: int | None = None) -> None: - """ - Represent the given signature data. - """ - self.A = A - self.E = E - self.V = V - self.KeyshareP = KeyshareP - - def Verify(self, pk: PublicKey, ms: list[int]) -> bool: - """ - Verify the signature for the given public key. - """ - start = 1 << (pk.Params.Le - 1) - end = 1 << (pk.Params.LePrime - 1) - end = end + start - - if start > self.E or end < self.E: - return False - - Ae = FP2Value(pk.N, self.A).intpow(self.E).a - R = RepresentToPublicKey(pk, ms) - - if self.KeyshareP is not None: - R = R * self.KeyshareP - - Sv = FP2Value(pk.N, pk.S).intpow(self.V).a - Q = Ae * R - Q = (Q * Sv) % pk.N - - return pk.Z == Q - - def Randomize(self, pk: PublicKey) -> CLSignature: - """ - Mask the signature without changing its underlying data. - """ - r = secure_randint(pk.Params.LRA) - APrime = (FP2Value(pk.N, self.A) * FP2Value(pk.N, pk.S).intpow(r)).a - t = self.E * r - VPrime = self.V - t - return CLSignature(APrime, self.E, VPrime, None) - - -def representToBases(bases: list[int], exps: list[int], modulus: int, maxMessageLength: int) -> int: - """ - CRT the given exponents (or their hashes if they are bigger than the max length). - """ - r = 1 - for i in range(len(exps)): - exp = exps[i] - if exp.bit_length() > maxMessageLength: - exp = sha256_as_int(str(exp)) - tmp = FP2Value(modulus, bases[i]).intpow(exp).a - r = (r * tmp) % modulus - return r - - -def RepresentToPublicKey(pk: PublicKey, exps: list[int]) -> int: - """ - CRT the given exponents using public key information. - """ - return representToBases(pk.R, exps, pk.N, pk.Params.Lm) - - -smallPrimes = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53] -smallPrimesProduct = 16294579238595022365 - - -def randomPrimeInRange(start: int, length: int) -> int: - """ - Generate a prime in a given range. - """ - b = length % 8 - if b == 0: - b = 8 - startVal = 1 << start - endVal = (1 << length) + startVal - - while True: - bytez = urandom((length + 7) // 8) - bytez = int2byte(byte2int(bytez[0:1]) & (1 << b) - 1) + bytez[1:] - bytez = bytez[:-1] + int2byte(byte2int(bytez[-1:]) | 1) - offset = int(hexlify(bytez), 16) - p = startVal + offset - bigMod = p % smallPrimesProduct - mod = bigMod - - delta = 0 - while delta < (1 << 20): - m = mod + delta - if any(m % prime == 0 and (start > 6 or m != prime) for prime in smallPrimes): - break - if delta > 0: - bigMod = delta - p += bigMod - delta += 2 - - if is_prime(p) and p < endVal: - return p - - -def signMessageBlockAndCommitment(sk: PrivateKey, pk: PublicKey, U: int, ms: list[int]) -> CLSignature: - """ - Sign a bunch of messages using our key material. - """ - R = RepresentToPublicKey(pk, ms) - vTilde = secure_randint(pk.Params.Lv) - twoLv = 1 << (pk.Params.Lv - 1) - v = twoLv + vTilde - - numerator = FP2Value(pk.N, pk.S).intpow(v).a - numerator = (numerator * R * U) % pk.N - - invNumerator = _modinv(numerator, pk.N) - Q = (pk.Z * invNumerator) % pk.N - - e = randomPrimeInRange(pk.Params.Le - 1, pk.Params.LePrime - 1) - - order = sk.PPrime * sk.QPrime - d = _modinv(e, order) - A = FP2Value(pk.N, Q).intpow(d).a - - return CLSignature(A, e, v, None) - - -def SignMessageBlock(sk: PrivateKey, pk: PublicKey, ms: list[int]) -> CLSignature: - """ - Sign a bunch of messages using our key material. - """ - return signMessageBlockAndCommitment(sk, pk, 1, ms) diff --git a/ipv8/attestation/wallet/irmaexact/gabi/proofs.py b/ipv8/attestation/wallet/irmaexact/gabi/proofs.py deleted file mode 100644 index 1aefb7e11..000000000 --- a/ipv8/attestation/wallet/irmaexact/gabi/proofs.py +++ /dev/null @@ -1,279 +0,0 @@ -""" -Copyright (c) 2016, Maarten Everts -All rights reserved. - -This source code has been ported from https://github.com/privacybydesign/gabi -The authors of this file are not -in any way- affiliated with the original authors or organizations. -""" -from __future__ import annotations - -from typing import TYPE_CHECKING - -from cryptography.hazmat.primitives.asymmetric.rsa import _modinv -from pyasn1.codec.ber.encoder import encode -from pyasn1.type import univ - -from ...primitives.attestation import sha256_as_int -from ...primitives.value import FP2Value - -if TYPE_CHECKING: - from .keys import CLSignature, PublicKey - -# ruff: noqa: N802,N803,N806,N815 - - -class Record(univ.SequenceOf): - """ - PyASN1 container for records (of integers). - """ - - componentType = univ.Integer() - - -def custom_asn1_marshal(values: list[int]) -> bytes: - """ - Use ASN1 marshalling with universal integer encoding. - """ - return encode(values, asn1Spec=Record()) - - -def hashCommit(values: list[int], issig: bool) -> int: - """ - Hash a list of values. - """ - tmp = [1] if issig else [] - tmp = [*tmp, len(values), *values] - r = custom_asn1_marshal(tmp) - if issig: - indx = r.find(b'\x02\x01\x01') - r = r[:indx] + b'\x01\x01\xFF' + r[indx + 3:] - return sha256_as_int(r) - - -def createChallenge(context: int, nonce: int, contributions: list[int], issig: bool) -> int: - """ - Create a challenge for the given contributions. - """ - return hashCommit([context, *contributions, nonce], issig) - - -class ProofU: - """ - A proof of commitment to a value for U. - """ - - def __init__(self, U: int, C: int, VPrimeResponse: int, SResponse: int) -> None: - """ - Store the proof information. - """ - self.U = U - self.C = C - self.VPrimeResponse = VPrimeResponse - self.SResponse = SResponse - - def MergeProofP(self, proofP: ProofP, pk: PublicKey) -> None: - """ - Merge in a partial proof to reconstruct U. - """ - self.U = (self.U * proofP.P) % pk.N - self.SResponse = self.SResponse + proofP.SResponse - - def Verify(self, pk: PublicKey, context: int, nonce: int) -> bool: - """ - Verify this proof for a given public key. - """ - return self.VerifyWithChallenge(pk, createChallenge(context, nonce, self.ChallengeContribution(pk), False)) - - def correctResponseSizes(self, pk: PublicKey) -> bool: - """ - Check if our stored responses conform to the format of the given public key. - """ - maximum = (1 << (pk.Params.LvPrimeCommit + 1)) - 1 - minimum = -maximum - return self.VPrimeResponse >= minimum and self.VPrimeResponse <= maximum - - def VerifyWithChallenge(self, pk: PublicKey, reconstructedChallenge: int) -> bool: - """ - Check if a given challenge is equal to our challenge. - """ - return self.correctResponseSizes(pk) and reconstructedChallenge == self.C - - def reconstructUcommit(self, pk: PublicKey) -> int: - """ - Construct the value for U from our challenge and responses. - """ - Uc = FP2Value(pk.N, self.U).intpow(-self.C) - Sv = FP2Value(pk.N, pk.S).intpow(self.VPrimeResponse) - R0s = FP2Value(pk.N, pk.R[0]).intpow(self.SResponse) - return (Uc * Sv * R0s).a - - def SecretKeyResponse(self) -> int: - """ - The secret key response. - """ - return self.SResponse - - def Challenge(self) -> int: - """ - The challenge. - """ - return self.C - - def ChallengeContribution(self, pk: PublicKey) -> list[int]: - """ - Get our value for U and our reconstructed value for U, given the public key. - """ - return [self.U, self.reconstructUcommit(pk)] - - -class ProofS: - """ - A proof of signature issuance. - """ - - def __init__(self, C: int, EResponse: int) -> None: - """ - Get a proof of issuance. - """ - self.C = C - self.EResponse = EResponse - - def Verify(self, pk: PublicKey, signature: CLSignature, context: int, nonce: int) -> bool: - """ - Verify the issuance of the signature by a public key. - """ - exponent = self.EResponse * signature.E + self.C - ACommit = FP2Value(pk.N, signature.A).intpow(exponent).a - Q = FP2Value(pk.N, signature.A).intpow(signature.E).a - cPrime = hashCommit([context, Q, signature.A, nonce, ACommit], False) - return cPrime == self.C - - -class ProofD: - """ - A disclosure proof for identity information. - """ - - def __init__(self, C: int, A: int, EResponse: int, VResponse: int, AResponses: dict[int, int], # noqa: PLR0913 - ADisclosed: dict[int, int]) -> None: - """ - Create a container for the necessary values. - """ - self.C = C - self.A = A - self.EResponse = EResponse - self.VResponse = VResponse - self.AResponses = AResponses - self.ADisclosed = ADisclosed - - def MergeProofP(self, proofP: ProofP, pk: PublicKey) -> None: - """ - Merge in a partial proof. - """ - self.AResponses[0] += proofP.SResponse - - def correctResponseSizes(self, pk: PublicKey) -> bool: - """ - Check if our responses conform to the public key format. - """ - maximum = (1 << (pk.Params.LmCommit + 1)) - 1 - minimum = -maximum - - for aResponse in self.AResponses: - if aResponse < minimum or aResponse > maximum: - return False - - maximum = (1 << (pk.Params.LeCommit + 1)) - 1 - minimum = -maximum - - if self.EResponse < minimum or self.EResponse > maximum: - return False - - return True - - def reconstructZ(self, pk: PublicKey) -> int: - """ - Reconstruct the value of Z using our information. - """ - numerator = 1 << (pk.Params.Le - 1) - numerator = FP2Value(pk.N, self.A).intpow(numerator).a - - for i, exp in self.ADisclosed.items(): - short_exp = sha256_as_int(str(exp)) if exp.bit_length() > pk.Params.Lm else exp - numerator *= FP2Value(pk.N, pk.R[i]).intpow(short_exp).a - numerator = numerator % pk.N - - known = pk.Z * _modinv(numerator, pk.N) - knownC = FP2Value(pk.N, known).intpow(-self.C).a - Ae = FP2Value(pk.N, self.A).intpow(self.EResponse).a - Sv = FP2Value(pk.N, pk.S).intpow(self.VResponse).a - Rs = 1 - for i, response in self.AResponses.items(): - Rs *= FP2Value(pk.N, pk.R[i]).intpow(response).a - return (knownC * Ae * Rs * Sv) % pk.N - - def Verify(self, pk: PublicKey, context: int, nonce1: int, issig: bool) -> bool: - """ - Verify this proof for the given public key. - """ - return self.VerifyWithChallenge(pk, createChallenge(context, nonce1, self.ChallengeContribution(pk), issig)) - - def VerifyWithChallenge(self, pk: PublicKey, reconstructedChallenge: int) -> bool: - """ - Verify that the given challenge matches our challenge value. - """ - return self.correctResponseSizes(pk) and reconstructedChallenge == self.C - - def ChallengeContribution(self, pk: PublicKey) -> list[int]: - """ - Get our A and reconstructed Z. - """ - return [self.A, self.reconstructZ(pk)] - - def SecretKeyResponse(self) -> int: - """ - Get the secret key response value. - """ - return self.AResponses[0] - - def Challenge(self) -> int: - """ - Get our challenge. - """ - return self.C - - def Copy(self) -> ProofD: - """ - Create an exact copy of this instance. - """ - ADisclosed = {} - for k, v in self.ADisclosed.items(): - ADisclosed[k] = v - return ProofD(self.C, self.A, self.EResponse, self.VResponse, self.AResponses, ADisclosed) - - -class ProofP: - """ - Partial proof to reconstruct values. - """ - - def __init__(self, P: int, C: int, SResponse: int) -> None: - """ - Create new partial proof information. - """ - self.P = P - self.C = C - self.SResponse = SResponse - - -class ProofPCommitment: - """ - A commitment to a value of P. - """ - - def __init__(self, P: int, Pcommit: int) -> None: - """ - Create a new container. - """ - self.P = P - self.Pcommit = Pcommit diff --git a/ipv8/attestation/wallet/irmaexact/keydump.py b/ipv8/attestation/wallet/irmaexact/keydump.py deleted file mode 100644 index 05def9ac0..000000000 --- a/ipv8/attestation/wallet/irmaexact/keydump.py +++ /dev/null @@ -1,277 +0,0 @@ -from .gabi.keys import PublicKey - -nijmegen_pk_1568208470 = PublicKey( - N=int('2308348848654989734244578214426041886640615814122935371977453710985760251753196836056566560946748' - '1891447560624076815171902701100966287957305108165359561949360083877250239403854264718766611914546' - '5983868616125697173427199707335341092599142246418277955830441980542151914035129234648171907401150' - '8459221819623715511085696053823212351612883718721394810895094818932648408689461753177565463293150' - '0640447614251158847855339740827820438899588758225795818551948536549559056010847714888366215223136' - '3141036604721458880786083668245067520249065498387425311119804000358363153021274980315713632955880' - '11197449677663889969586928901072313'), - Z=int('2199609756246298607806226676057083963236866633693044910071021919308316960263882823593619964064537' - '7909935072520733183249240046130457636624442062243451440224778516450621326296645864383200575465261' - '3907708842578693271132499949444529467266970688138378463096115220250151061144601661878493868383591' - '1431073683517984208253507796074815246217982868450141955584599266175536058204734870815648739982239' - '9815666486200072325009844109861305319650267857884072236845579743902589253922700333979232264274987' - '6321584627818590791302427374037279869752628442278406291657207159347478586408658614571313687477343' - '46685714519020418873843104916228280'), - S=int('4947862832753626546478602156656842202057521619994473351955549881889207602254515780579851896480785' - '8661764805671481925869861003345057677813382759005635057461486719790767782454434835913993738820393' - '2875202801785491737907905489152022245550886672114380690284771639239830090793780087364614275310057' - '1799865902982609152983892345581161682905177159947490777005402885835320472385464433388646950557370' - '4258131359405986308857038410928264651936385008727561139009364270317508945798702929714876197686463' - '4171081370289785955903644862808549558832826327434873109403771551901803321180257078774567219108911' - '3391287690457105331872557937999400'), - R=[ - int('15808696382313521029498302941766526733977729427883195983125245826826173818975313729372504098991' - '54849565855506971526121926088845280587631701518528995987387178184797042142409226739085128611780' - '52547931496724234628243193655137772971086360203036218606556807730417085521019007815251159545766' - '33405037433294629405969757284000898223126408183516585343155580898696332575988626360125678311971' - '99833083638507671722597466723921302208173367996782845196717924663948287833925886120534949025054' - '17079892095961900500655481952457892968099914504420341647288031587915804086882541942582945586746' - '14912364910799520973505863309010350337215071224'), - int('36239795282829737092419476558753351666995882795044016158341725945725469768654442313854527122300' - '07383017790497510891709286264355728528335715792264895893532503216602953246487428262314577721458' - '74742266507392726954505926473497209960321196518756123619557667210297719714510423463887488675730' - '37146458105378615356807869337865757390660788781567679607948126326459126314554895412066696474754' - '76724281623495179298853536283827207003887936413165816406471338678833479248684553011735775444279' - '63032101771656876918422785316335326696295017676517426637640615065810447370882234807232604456851' - '8460450501415193543098773066630972969788013002'), - int('22634256348927655722809815085233043745100944436342687926925925166398759108895605190764701434213' - '97677107490711181808518322135152163839325541861598162207320763754837238073850365199178327930737' - '81632016198271671044151914112617919122912653449782443236325407400363550667837707913473030117677' - '16391683073397404369518856172096009614285174710104499165398313371122195804230932387723694099372' - '17942584638302664105518842217307544307999205765854855954366387529916590642670957830351659272718' - '29565570928647564233903315602855867789749084440204422432024856562638637221883956933925945997396' - '32680951999133849820821173711471766582009195439'), - int('11256596166935038108949994481938338728879804608226903525770235886820923575210250920976759175243' - '52896624575873916279282491797910137860489303279084863186690637365811653535823523507457328656990' - '18513716500391301549207047470593950186693427961331147225344117979790113141082843892244852985914' - '18449728740439726045288445930406868719223280098143922546665466959899646725590912597165695347871' - '41247610528269772446939014116218926175321654771486741792685827695221783074382102437681278027084' - '02591097464992967241117616761728290117943936202800436872345823706167796731862820942269297894792' - '04464203053094534288794186523063142779201894812'), - int('83288828405225591053728401147645242457182808455846851495817501749323022887018235751474829303661' - '12298226726472752350080975180244394004398805171543926196382234066664952109484506329930824644533' - '54908752560970389526552492843352022969970180696177558800450210801343755392161177101762382319546' - '37222023491403683311152610140652538913955426314516163828467137748390171857544614787207064286656' - '49514040991350008856161748333406823614376753398812607792116603973034251918948312260051426641059' - '12403665808754563741680578604656967933568079488632198428032961391348322091961814670586569442014' - '2678597766708270682100539809060232034633157315'), - int('21170789466690102838632546687993921962308420400595254298711868265896203763830365698155519482420' - '36265410326016276499049267233642994547718954929068939320693434769586581733160207524153888885579' - '72364254936614146989079777214120935199499980974883183551638739482789407039381273155045613132106' - '92529033436007408586602681313079608495041092870860944363935133957510959127813352687125808100809' - '19529931424169780998318998112619779201028335969144202816428868762466352991257136576050671090076' - '89633214417441126840291862463066063385124371855652973099573935698492056086388658076576010683384' - '32857181424572424357245790895221117697058139826'), - int('10743091358051163282888319641158178222007853022746226381673423512038649550116152372190187805754' - '43586987560746211508487532595627252211195463247215659351539420977018705755324269356839011668877' - '13301292899327278900534668201648188225762179495791170588322546503114624873085638197539841019965' - '21813342907961887183986147788687147668485770090147885060032854725601975887337251351742724369148' - '33933053531446560380339871209403975392692944908024512325290974102968484449661318267351166045708' - '52375293789505047987398614172719979094063552705377865696408481804525589672549936050983958198003' - '80780542985539304878743636609895472837905829857'), - int('13954717378778863603049418529292770756960957248343333831581492269206254951318518524286447415699' - '47661277459726447475315433543249983178272062142570764870758053723193621482041978031320628910883' - '86063630808240490989797390309939383012455378159965816743970031558246865257889483347864208710539' - '68883552124636160465384477247266664808733278591248005498265577288919452308345548894026029694941' - '94663167553762278580154805267354881143581197603187424726890907377778882699257535346634402616095' - '37732202005611033740170530127626504081110537153582169736213480639043756102194179374821260742893' - '34511065850104108414883527126340024310084989841'), - int('65644078014385939458697201714216628609804746606649120563368136483920747821725693036929434274036' - '33010179611385500339485480724546120895967125348215906627085831722646363576045050751022001001004' - '01826921640066453728944729346734665785141257036652074072526840126858354030791753490073202777731' - '22780537952713272792353550441173614266626145694131158290882876041403010015790542307302173495209' - '50741153305990045836495773978758060736798138577240198325950284023757866614052697256816013755334' - '38692848478486670146839614495581328366632773601933493125265143287564187252236098365589072267911' - '5901173952441306550920672709866788344702434515'), - int('11960039745946413574575165760501519771761280866219418953799590332246981162251355061638728968538' - '17799997379694199977554900924678038537862215766583961873924226784039897907152222466112746243486' - '06004304119682203362119595069180381983759234362164204968285981227619254598347356478788351539773' - '89407295750761805192690045462871979781026769840452126114961957912496156665661892810971228552308' - '47492986435484454362466434280298281920078637948143957259377590593973052396278919133383127273339' - '13392229260404028386465227726645931365503832973628855102186886669923036337306526630392507217657' - '87074794716042677430164026113135574648911385189'), - int('19746269179718038947278382817926391502718844818429850256586173048766493358468885936787505416464' - '92396807126222240860681403677852869062978334067584965923389710478211001565704590845495682910529' - '37396882496875603624360951525060284150220719184962938268022705708543451183210918303474916021374' - '21804369573635578071648060553452797048525836302279651741167693077200627547740823827109115161684' - '75159232989818045133915414306017995186087868315757845445001215126620524567867407581001095411726' - '12922051075086039936242736476321443545711080804376606180642161335306567617593549489906692283456' - '93878682087351857365630142712523683195538415066'), - int('20033800821189856314352012966459139215459636510156321137813391257932532690918586903371473262651' - '79667337790562755284413657986118980442288594602304795486830071144422407947819054979311671126176' - '41127131248648287143561164037105415897177930774049732377545462724498964659506406027322227651737' - '87933649776578728711763181270363320950252470013730228575929539188340728297366348723368571151256' - '52081741132488497023951574408826833727206429758574931539845573035036540277011775703945690440408' - '99417598738594786487168846024461663973049043307095568844005788587634917987307890484853924788551' - '79155064983293617316398128615926445893453575449') - ], - counter=0, expiryDate=1568208470) - -nijmegen_pk_1623505755 = PublicKey( - N=int('2120960261707180788080488315913866858493156931542981287563958341669647678580361901123624051189893' - '0394606582042700753832505689439414361658603647923260277397985847211023109365939242676185355817329' - '4046859216788742309004199386854707500183082723616173429216476806456381486066227258887909466520391' - '8744422585113063326359501158737693616803255637973475228801563692215980683814241093341407926639729' - '9087825941218343336590143323252767226399923647015880929009263948902981257434462300653007377993538' - '9961372665351133135924516066625443445399621226967380522879279238246929825489705254460196861849116' - '12085872536132071530413192045702061'), - Z=int('5105347469152055311494283674026066167021173251222318001380911136699767935422539291771818900991392' - '8324274679844000038244141589018480648750925678974981124092627576821658469023242183787805274381204' - '3074129771640006040536632630354134381628904272634383848753842140165363733421253837827866946831481' - '2153374914229930291018989231866066189505679069704615638423308013150626146677870164704057872831516' - '4396164701665160314976133198637879547545717071189535707184250952905148950003610600296783021197483' - '3427935681052831864084136169467636456036680535683830383749682277693142842067331945397646511315594' - '3591191287631363913560062822422802'), - S=int('8057374000468959733648417442414373467394512008917350989826594554878730860535792847565298640885854' - '7100597589625131869760805345159427948907025601254632116052868864831814039258764756377090036778122' - '4042877654966730203820839929941649688634394656057678867524763079223592906704116836397837715570422' - '8810693261357938895778722190774128089943948462317767918164286984623478680890428981001095481033528' - '1676017408143761685095474357343318484650324399805753286507657415147425828796448452715418976871214' - '6252657624654304408659745878198800340012441748429449464774877231020131743947590023842933603341163' - '3303549324312710889302139498497011'), - R=[ - int('97572920786787946903881805885518401622999840786175174308499028381507856979247857821199555745421' - '70240379802574027415537015955537648355428444810099175785605292673934723573373366026547042161558' - '38099913310328703326627892920378081515175361576156946110579045435823456104271819085838484227422' - '49537044532613969910107129325766124275519888131687827537135700338730858884293115163173946950355' - '79337524553280282241982426020431000374654233934946317741354637279428606937851113394662819895053' - '81675483366550237287906013685986174241377414523038274601189794228550241767516763367287794890350' - '7161783991613256771839764805167497286640275654'), - int('13439156334647948129088192055492167047313280156696711876441510421846774222732552145897824480309' - '15724766773474316083524883956266098315376082246829947035595433224869883087484426216428261686607' - '36179303325116816070722445814830888102863436177738075910207165035607487332268621809136233777644' - '21042250935343538371584080956045997377099780242539615974416742386377790889255661462605999817295' - '51836619106802432789317740739577984514079840969968847703746987725481064080298551312498142378682' - '72799145283090894483386528379755661725405803684630931835898509886795119824215028455163692752994' - '52303227597240113667356547957319926669807144362'), - int('67545420541646345966205616149795210948339780318774596542285406940097493755381992418389313502351' - '03577993920520851987489966797349550242262508528126756564214402945283039232954400522023387475624' - '64076597585989600120017556422421672983365770398320818721007083921975327420860072008848252073980' - '67898515484153842267303760773480081687258625578977782763624538550231947323225095138023092993008' - '68973565864331845598400346015033248370060410007039455910294980726645509128862660448768345440181' - '95432123148485155449015924625428121286182396930138825817374944512826878785196802215342808769764' - '8422568260038454942854439468008726198832792038'), - int('54601248770777014877021079574292013263098242992401889804819408203180852832387539840924227676529' - '76516243652192709920189822211148829027916514795130573309051194449785649580404465436571935830632' - '99949660522426806298683842648429502978804234686686434027512426779579175529256953963896045536325' - '02976226064812955135221251707464516521239158711120739358820155723553624929913319328104602463105' - '24519526856590285395574061749320685374601448926490013549104860165506013946169069317812605451414' - '88868951211949476147420599656371276410379083940432754013220709885720804480305069588937267364004' - '6793762755754203493701987798540077783658850314'), - int('51318706876012071333135887673227235527994406134432824669112767831317277433440035162610033970609' - '49750671258524035140033299727769871450016936920968028860184488080696045722964502502585870222637' - '94997892889837577566084917865155439003452626785081615512663739437634016370930342469554735139393' - '46963313522058867566595234050721495235294475010246786136275879158580919056820949718874717869534' - '06455651086455609318727572361160522122875732203510991423558325932615886621615935056726183515226' - '25737167591062610232125816143429727909390424163438928731783197691643112785135232903189259392829' - '403886748018040759380353761772350814816878931'), - int('14549891653243585585239257405725871766199697865818317546562165855918541122994110279362263523394' - '31935289793264427529679453068593572375837249779323911450753474674564131989590275311966374429646' - '54840521672959022414987763156959492933318014463727054943683051718130573774181668437451763597600' - '40234700792404969142660953338896905012982640991560777596376093840644588626862895257468600782809' - '18422823687282954235598937560671955848141264524237123813243099993514708142022830957686571071509' - '39456116586071259070826492732329895633904370390043401679338860954659477420415255469393808447280' - '57349804106620427415402056373693026677144243146'), - int('20591446845643333971824224680904563727773113809632815776940638141164290562402400252349954362357' - '83453619397478031121541598927219975128324402712196638487725277738012382138594140095992522896511' - '85587485893896864936016687844580855408879436562404939696690202967957800486704094907606261100452' - '75294790528695934272250387913334083761741397640174236150611168368567477192508925302337415410844' - '30026654450241811630599794907025301344356960645225304296743560637275047411427667424540609823001' - '21648670907040725783702265054012279430786819238010738177552786983192199341531172705431175220981' - '95707970545178522588688455856703076284969092541'), - int('11616007002638884593912980252263299878515298906244766346468846221901394986201310848844768411016' - '94669614305095530259797634359626507236120851418097852712464638799140897398909155746057993344311' - '08333118432283187302653190800856063209159516910029480713555487107896576726806779040641918879354' - '82665700195581155064267851296269804547207325167780955261510545806769954576770458625619943192057' - '95453853479394440063282260457475667687158188087424629180660750799376953977477588917474606616470' - '42543689074811366644288275014933816967857171058933751691024891732258278460388191928090622647112' - '73244853983329822715228079824080076856169225587'), - int('19275479536993771811571317924989442877160871241973914710903961271814898456872663990363365765596' - '24210615334477512511479463209800517592802426762427569472171563629208805425072036188837645996747' - '95075536388858036550473597801042741342498977169642053512103125007449147085052308467050153773430' - '19952949591199759567251224795684559899843524880107406902071989757809871911889944978583097372814' - '76135583371419854343243754142058134767458894038557733356043428621666560906630012153293717258084' - '95559855511083870642095987218846172187714168956759386906715838893840472727112741573807395665884' - '27703440360192242381888908204393152451701069030'), - int('20828455102447948921429255913996597101808601232112263701766036109105212106159736652812242413575' - '81444476440096907240144233716825687662272465243902918243462056935354850267482355883316979881505' - '70076931976536629152791186984560947080461721383369477782771040299892126229451415015237232317444' - '71255771474499362257938504077408307108160538241576024968062274823483822343351419551636314413894' - '52939786770427578402887748443484906711299816420678518984377847375323442129596670623592724033015' - '82298608037109376787821165572093208510819530979798306130682686209224625289796060106923763332755' - '17232380071473772840431307043446764285191737376'), - int('76094297001542339402349499064004489519189855334036486879678225717686691809562182400382568477836' - '25409241607579789220890942582077099313770626292329929799777488507050072270961566863753912382078' - '11518110734359917954974861808328460777507388876180829121147036858929245896591509145508436422512' - '19516422723596161822484168420966694841457234994603947767114518677106379997191513839188231804812' - '33204561468896497012206549362548086472801618062380191368857676778216286723066421850736619423570' - '36500125031544284877299638374846528573807258941881718518449699507132765654201224376049852524250' - '1960363858631642836416487931144919013941033054'), - int('16773166790686320835564553892947995536135579072155893920906810338822282414096740482716071878160' - '09547814484737702313183707676342817358364162401899761207994380138401267140621580091061971589651' - '13030777006462002647415230520850690966250329802673724421758110927872175415054709301086315160860' - '82095383471065593149598068594192603611732127393673160748602378023384171130074769094920816618535' - '57345693400605865461342191679572481795174601950101753151700717197520939675974234685725461338094' - '68514669105601903689574891935474797907247784539788732511900655602521400966220816064776058604023' - '23730537130214198963012949663585305839496465851'), - int('64603203250954078729700184174995513946725198560658551967620858281616619372646370360420657193427' - '10658998017497869160714535688824894907106408143039758747908989910919330365190948944459163255943' - '32653136640764424150880533111135672175703103620617868513131811560670778427447972528507947847978' - '32018782170134579501959252188043088265085722723289450158065258331570001603740307013889199130245' - '46392622321161239717501086865235465746657940096535508422767405102962197184002480204168255323648' - '72921277396696066718261202284716629156653101050535437891094362285071882461245256471890497479472' - '8661267903028126136024597922994373578405741826'), - int('17720307031708923896202074746339344736955545673299875633065555167758661268267967945255134053377' - '89604408784538795301956167748235018790606293994588523560033660376718892010165527199900038874155' - '90319756188380917540912784112172491404544879757771987560154587037841464941053626457032758388990' - '90270922351389511247397322426925416150490950575001298241488581699343208068249893150567198664110' - '39842808486815996639410600292872968898820957694061503136806236383914587255522938711185180415241' - '95719301866405671325275397269796306342303184779541115046965273846492697573286282916681167588354' - '2547425156033408655889047512236440867180415538'), - int('17570419868063275948553579175927163543494926713520296795210824874879802729526687146258913820103' - '20829759649276641543970779368261899039368236739081427231085494115833547699704974757246277730370' - '09020110786042364559798866249209059045117728801427131790606924462146668522617576456660673306113' - '15807666445538548284847939892964610155986766807769351350390676762283298044893434967984963756053' - '23128408219860740895386617428006177717939061169654789034347218128600199700274640809114879351902' - '41282278089167411046408872643475687104929876258890588242834945641155330604028991768541945169708' - '12255735497879323518679714061556795135294041725'), - int('80927409062440289584332349115624574443816121026569014321622044097956294449591499651625575826996' - '87805047917622106086492123282557444079780540852253093977112239076168903237837595618667930215968' - '19410566351413228770192114649621103018327906811382702450729612422117122668855854637702428237438' - '29242622978796365165655747530439925072245355898608733663022999504149971218774237646309890217991' - '04599573009268328116036356960682236915130576125650162600855905632049831289135977567776360789503' - '85003916577355417953712471036789951484177952363324909966943779255986359589221433478694444961389' - '9609226688994276838876807872991352192285080289'), - int('53794422264657634216253100374252935824864024524531930948578601617776161911387003496949802237946' - '53382084297229214068674937076614254512629257542029410423705882259999278361592716643713825627080' - '31070418623420929537533055579908714972519396921841140852415274120515095509317820503518410562293' - '63375972066281840582065837068320404452206709405839968376284976562267373206770611754845303100293' - '02682427970671988975196225696811342576560884429978341053096225364660806965685856327798585938705' - '11153349657938559616519907831429761498989401942645621124001507344790644523739384774317371764373' - '2957187838216872541910039033152782791482190490'), - int('79900399509541297638692951822822342323339819450490993887813828316883085073258980581578597396082' - '56691329611954626701473249204787425137241863354297205964614496134385401071751795760628441074649' - '90948523429705092778312757454034846688907552651544108875832342904687002660974284771139169262605' - '20559076889078678161023099026371399471608319773398090449551300092341417706803424252696162502820' - '81114819852380020016766795630842803769030924160615237890558763127261070146879057340655730716175' - '22335082748789327405284436155823241088061887492822789470754368553932644857591522460216714936821' - '1906502824287221427463165461517761171124544021'), - int('28140982191601412513755024837896733957937041514071572509364239994574697814208014117060105819255' - '46236172160309196573457813109838872715921883054154625384576047139228883491381102707923871673006' - '61391067061276351639510643519440109637176343914466186798135916154962774227535542361263228472700' - '93788263105171273290900851943387032817752972157189740128311877877658124260481314687084760849999' - '26111437224699156113881428074597853442355579006575344689110195992094343984827404176953804041852' - '17046877426311349399267627575330232040958471779500812371986795590443697230850400216824390846872' - '5581214592781450033243605265100819562205939746'), - int('57520971369538808248414784950443461664058589095787708034042707990098676422631253905496281125757' - '08618489168970910411471027246680723096707925512054447098812548702378250871821000225396137308972' - '90732280029582636158901578318262341352063847017308642348112104124200734554344099332861377428013' - '40190041289812118562285075495062812383693766131155941668265735075273909241392724130972946785085' - '57306933657206253490215536606225723533062484366655138026863803992728609563726437534643235016377' - '35498700169377403895834704102159201104800144399326525753773054833424456352335170924572821237481' - '1465324017466761927336431733130372541971273339') - ], - counter=1, expiryDate=1623505755) diff --git a/ipv8/attestation/wallet/irmaexact/wrappers.py b/ipv8/attestation/wallet/irmaexact/wrappers.py deleted file mode 100644 index 4ce911a85..000000000 --- a/ipv8/attestation/wallet/irmaexact/wrappers.py +++ /dev/null @@ -1,35 +0,0 @@ -from ..primitives.structs import ipack, iunpack -from .gabi.proofs import ProofD, createChallenge - -# ruff: noqa: N803,N806 - - -def serialize_proof_d(proof_d: ProofD) -> bytes: - """ - Serialize a ProofD value. - """ - return (ipack(proof_d.C) - + ipack(proof_d.A) - + ipack(proof_d.EResponse) - + ipack(proof_d.VResponse) - + ipack(proof_d.AResponses[0])) - - -def unserialize_proof_d(s: bytes) -> ProofD: - """ - Convert bytes to a ProofD. - """ - C, rem = iunpack(s) - A, rem = iunpack(rem) - EResponse, rem = iunpack(rem) - VResponse, rem = iunpack(rem) - fa_response, rem = iunpack(rem) - return ProofD(C, A, EResponse, VResponse, {0: fa_response}, {}) - - -def challenge_response(my_proof_d: ProofD, Z: int, challenge: bytes) -> bytes: - """ - Create a challenge to a given ProofD. - """ - challenge_verif, _ = iunpack(challenge) - return ipack(createChallenge(challenge_verif, challenge_verif, [my_proof_d.A, Z], False)) diff --git a/ipv8/test/attestation/wallet/irmaexact/__init__.py b/ipv8/test/attestation/wallet/irmaexact/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/ipv8/test/attestation/wallet/irmaexact/test_algorithm.py b/ipv8/test/attestation/wallet/irmaexact/test_algorithm.py deleted file mode 100644 index e722e8d0a..000000000 --- a/ipv8/test/attestation/wallet/irmaexact/test_algorithm.py +++ /dev/null @@ -1,81 +0,0 @@ -from .....attestation.default_identity_formats import FORMATS -from .....attestation.wallet.irmaexact.algorithm import IRMAExactAlgorithm -from ....base import TestBase - - -class TestAlgorithm(TestBase): - """ - Tests related to the IRMA algorithm definition. - """ - - def setUp(self) -> None: - """ - Create a dummy blob for testing. - """ - super().setUp() - self.blob = """ - { - "sign_date": 2586, - "proofd": "0120ae8c08383eb6326ed4d690472c14167157ba95bddfc6eb961475d11146c78b7702010014ca54a5ca54059afa2ef17b9a8826082f01dc75a58cae5ec18a3b3f93b5de357dbb5b7a326f9ffb67aef043f7706dddd272c9b5e46d48598975bbb22ad28fbeda52e1384fc39edbfae6d48d6cb03148dd0b3bc7cf13b594529c3d9c9f325e847add7d8cf1007e8f8fb5cc4cedca88e9f4ebcc69eba22741e8ede9744677be96df68ad0f689052264e8ddd67f15b89ca106f9424efe0936fc3ea567573900a39254c28b9fcb4c805de6a55d13b716aac4669ed9f4620e98ed54012f4dfa633769e510961296e228f5152c1152b760ff58ebe964dd84bf9a6b39da9b4acee1cedcab3576d95dcffbd9cdea6bf61726f0468b2f405e825103bcb20763d0f69decb013f2425ecd45cf8d8a8e6feabcb2c7dbddce283c494fc309451dc310f3ca36de5e2bab532d50734bcbe250bcdae7cc7b6e978e2dfe5c4c11521aa4326b7683c91020191083b68a01f222fa9a6260d0b40bce3669a7dad64c9ec6bdb7418865f6c07aa616e06fbeb314f32f6f8d9773acc4cf96667044007a5e8f8364c67884219ddc84057f94f06c8c3677f8483da72a99ed05976856ca1597ecc3164d7f4236736b64b6b656e7bef4bfd30cfd51bcb4bef990ca0ff88b5b0cae9df789acb34dc6e34d3daf125e7ba13d34d70b3ba2085a85f1f5e5e39f704cd8af7787ec29f204b258abfe9fbfa644e79ac384f15817fb181255b57f1f8e3c6fae041422feb8786259356287266410ee4cf595418bcb392367ed17b8c3dbfd87c97d338dc919c99579294d301fcb54dcfde75f21ae310a390473e7801a9f5c339a861c50f5836175a92f31327c6b8fe82ff7bfb6a915cfe3a950765f5a4261ce1b22146435fe4aaf93e5a0e3e6febcc0542615dbfb0b1ab4bc09e3a1f7c4be574a268a5c9fd255cadf53d0924783965109f6de678210e6bd1ed66a3a11081e0958f20d01860208d1d2b7419576131e4e5759729defb2eceb0ec413fa2c1bb76a3f60fb1c41397c2d50f127be92d3dfc42bfd44d68dee28ce0617c0150d945cc7a583966ae5dc8e8340c24d2004eeaef1e073c6d2e71a55eb0e0cb6ffa56dc9f217631445bb8157548f7ddc735bb703f89e644d4ac6a5c5453312dae28b4c184e4b089f3c18ceec147f844b940", - "z": 21025909574607652013242068407286517850424307678122890876135156101653321984092105929057125603368801791220668605323274805950534554333885095151891554345408081373199060099202339143424919643961351117275291540867055856626869631650968369803183902895146289487368006719436569169044553294877369014424433240847941963958916265623517330529414890418453511520187847786782916076948797140109695922159477047382915875554999783288589498520057591077035129853458855982695920607696398615002875185515097109401895544388882159438043913551570342780281962902283409019706410544114516101827596857844194407086012298321703512788196253222325858419223 - } - """ - - def test_integration(self) -> None: - """ - Test whether blobs can be imported and challenged. - """ - id_format = "id_irma_nijmegen_ageLimits_1568208470" - algorithm = IRMAExactAlgorithm(id_format, FORMATS) - attestation_blob, _ = algorithm.import_blob(self.blob) - attestation = algorithm.get_attestation_class().unserialize_private(None, attestation_blob, id_format) - attestation_public = attestation.unserialize(attestation.serialize(), id_format) - - aggregate = algorithm.create_certainty_aggregate(attestation_public) - challenges = algorithm.create_challenges(None, attestation_public) - for challenge in challenges: - response = algorithm.create_challenge_response(None, attestation, challenge) - algorithm.process_challenge_response(aggregate, challenge, response) - - value = '{"over16": "Yes", "over12": "Yes", "over21": "Yes", "over65": "No", "over18": "Yes"}' - self.assertEqual(1.0, algorithm.certainty(value, aggregate)) - - def test_integration_incomplete(self) -> None: - """ - Check whether blobs can be imported and partially challenged. - """ - id_format = "id_irma_nijmegen_ageLimits_1568208470" - algorithm = IRMAExactAlgorithm(id_format, FORMATS) - - attestation_blob, _ = algorithm.import_blob(self.blob) - attestation = algorithm.get_attestation_class().unserialize_private(None, attestation_blob, id_format) - attestation_public = attestation.unserialize(attestation.serialize(), id_format) - - aggregate = algorithm.create_certainty_aggregate(attestation_public) - challenges = algorithm.create_challenges(None, attestation_public) - for challenge in challenges[:-1]: - response = algorithm.create_challenge_response(None, attestation, challenge) - algorithm.process_challenge_response(aggregate, challenge, response) - - value = '{"over16": "Yes", "over12": "Yes", "over21": "Yes", "over65": "No", "over18": "Yes"}' - self.assertEqual((algorithm.challenge_count - 1.0) / len(challenges), algorithm.certainty(value, aggregate)) - - def test_integration_wrong(self) -> None: - """ - Check whether bad responses lead to 0% certainty. - """ - id_format = "id_irma_nijmegen_ageLimits_1568208470" - algorithm = IRMAExactAlgorithm(id_format, FORMATS) - - attestation_blob, _ = algorithm.import_blob(self.blob) - attestation = algorithm.get_attestation_class().unserialize_private(None, attestation_blob, id_format) - attestation_public = attestation.unserialize(attestation.serialize(), id_format) - - aggregate = algorithm.create_certainty_aggregate(attestation_public) - challenges = algorithm.create_challenges(None, attestation_public) - for challenge in challenges: - response = algorithm.create_challenge_response(None, attestation, challenge) - algorithm.process_challenge_response(aggregate, challenge, response) - - value = '{"over16": "Yes", "over12": "Yes", "over21": "Yes", "over65": "Yes", "over18": "Yes"}' - self.assertEqual(0.0, algorithm.certainty(value, aggregate)) diff --git a/ipv8/test/attestation/wallet/irmaexact/test_builder.py b/ipv8/test/attestation/wallet/irmaexact/test_builder.py deleted file mode 100644 index 1b855b4d8..000000000 --- a/ipv8/test/attestation/wallet/irmaexact/test_builder.py +++ /dev/null @@ -1,96 +0,0 @@ -""" -Copyright (c) 2016, Maarten Everts -All rights reserved. - -This source code has been ported from https://github.com/privacybydesign/gabi -The authors of this file are not -in any way- affiliated with the original authors or organizations. -""" - -import random -import time - -from .....attestation.wallet.irmaexact.gabi.builder import CredentialBuilder, Issuer, Verify -from .....attestation.wallet.irmaexact.gabi.keys import DefaultSystemParameters, PrivateKey, PublicKey -from .....attestation.wallet.irmaexact.gabi.proofs import createChallenge -from .....attestation.wallet.primitives.value import FP2Value -from ....base import TestBase - -# ruff: noqa: N806 - - -class TestBuilder(TestBase): - """ - Tests related to the IRMA proof builder. - """ - - def setUp(self) -> None: - """ - Set up proof constants. - """ - super().setUp() - p = 10436034022637868273483137633548989700482895839559909621411910579140541345632481969613724849214412062500244238926015929148144084368427474551770487566048119 - q = 9204968012315139729618449685392284928468933831570080795536662422367142181432679739143882888540883909887054345986640656981843559062844656131133512640733759 - n = 96063359353814070257464989369098573470645843347358957127875426328487326540633303185702306359400766259130239226832166456957259123554826741975265634464478609571816663003684533868318795865194004795637221226902067194633407757767792795252414073029114153019362701793292862118990912516058858923030408920700061749321 - S = 68460510129747727135744503403370273952956360997532594630007762045745171031173231339034881007977792852962667675924510408558639859602742661846943843432940752427075903037429735029814040501385798095836297700111333573975220392538916785564158079116348699773855815825029476864341585033111676283214405517983188761136 - Z = 44579327840225837958738167571392618381868336415293109834301264408385784355849790902532728798897199236650711385876328647206143271336410651651791998475869027595051047904885044274040212624547595999947339956165755500019260290516022753290814461070607850420459840370288988976468437318992206695361417725670417150636 - R = [ - 75350858539899247205099195870657569095662997908054835686827949842616918065279527697469302927032348256512990413925385972530386004430200361722733856287145745926519366823425418198189091190950415327471076288381822950611094023093577973125683837586451857056904547886289627214081538422503416179373023552964235386251, - 16493273636283143082718769278943934592373185321248797185217530224336539646051357956879850630049668377952487166494198481474513387080523771033539152347804895674103957881435528189990601782516572803731501616717599698546778915053348741763191226960285553875185038507959763576845070849066881303186850782357485430766, - 13291821743359694134120958420057403279203178581231329375341327975072292378295782785938004910295078955941500173834360776477803543971319031484244018438746973179992753654070994560440903251579649890648424366061116003693414594252721504213975050604848134539324290387019471337306533127861703270017452296444985692840, - 86332479314886130384736453625287798589955409703988059270766965934046079318379171635950761546707334446554224830120982622431968575935564538920183267389540869023066259053290969633312602549379541830869908306681500988364676409365226731817777230916908909465129739617379202974851959354453994729819170838277127986187, - 68324072803453545276056785581824677993048307928855083683600441649711633245772441948750253858697288489650767258385115035336890900077233825843691912005645623751469455288422721175655533702255940160761555155932357171848703103682096382578327888079229101354304202688749783292577993444026613580092677609916964914513, - 65082646756773276491139955747051924146096222587013375084161255582716233287172212541454173762000144048198663356249316446342046266181487801411025319914616581971563024493732489885161913779988624732795125008562587549337253757085766106881836850538709151996387829026336509064994632876911986826959512297657067426387 - ] - self.testPubK = PublicKey(n, Z, S, R, 0, time.time() + 365 * 24 * 3600) - self.testPrivK = PrivateKey(p, q, 0, time.time() + 365 * 24 * 3600) - self.testAttributes1 = [1, 2, 3, 4] - - def test_build_proofu(self) -> None: - """ - Test building a proofU using the credential builder. - """ - keylength = 1024 - context = random.randint(0, DefaultSystemParameters[keylength].Lh) - nonce1 = random.randint(0, DefaultSystemParameters[keylength].Lstatzk) - nonce2 = random.randint(0, DefaultSystemParameters[keylength].Lstatzk) - secret = random.randint(0, DefaultSystemParameters[keylength].Lm) - - b = CredentialBuilder(self.testPubK, context, secret, nonce2) - proofU = b.CreateProof(createChallenge(context, nonce1, b.Commit(secret), False)) - - self.assertTrue(proofU.VerifyWithChallenge(self.testPubK, - createChallenge(context, nonce1, - proofU.ChallengeContribution(self.testPubK), False))) - - def test_build_proof_list(self) -> None: - """ - Test building a proofList using the credential builder. - """ - keylength = 1024 - context = random.randint(0, DefaultSystemParameters[keylength].Lh) - nonce1 = random.randint(0, DefaultSystemParameters[keylength].Lstatzk) - nonce2 = random.randint(0, DefaultSystemParameters[keylength].Lstatzk) - secret = random.randint(0, DefaultSystemParameters[keylength].Lm) - - b = CredentialBuilder(self.testPubK, context, secret, nonce2) - msg = b.CommitToSecretAndProve(nonce1) - - self.assertTrue(Verify(msg.Proofs, [self.testPubK], context, nonce1, False, [])) - - def test_build_proofs(self) -> None: - """ - Check if the proving a signature works. - """ - exponent = random.randint(0, self.testPubK.Params.Lm) - U = FP2Value(self.testPubK.N, self.testPubK.S).intpow(exponent).a - context = random.randint(0, self.testPubK.Params.Lh) - nonce = random.randint(0, self.testPubK.Params.Lstatzk) - - issuer = Issuer(self.testPrivK, self.testPubK, context) - sig = issuer.signCommitmentAndAttributes(U, self.testAttributes1) - - proof = issuer.proveSignature(sig, nonce) - - self.assertTrue(proof.Verify(self.testPubK, sig, context, nonce)) - self.assertFalse(proof.Verify(self.testPubK, sig, context, nonce + 1)) - self.assertFalse(proof.Verify(self.testPubK, sig, context + 1, nonce)) diff --git a/ipv8/test/attestation/wallet/irmaexact/test_credential.py b/ipv8/test/attestation/wallet/irmaexact/test_credential.py deleted file mode 100644 index c3409d6c5..000000000 --- a/ipv8/test/attestation/wallet/irmaexact/test_credential.py +++ /dev/null @@ -1,334 +0,0 @@ -""" -Copyright (c) 2016, Maarten Everts -All rights reserved. - -This source code has been ported from https://github.com/privacybydesign/gabi -The authors of this file are not -in any way- affiliated with the original authors or organizations. -""" -from __future__ import annotations - -import random -import time - -from .....attestation.wallet.irmaexact.gabi.attributes import make_attribute_list -from .....attestation.wallet.irmaexact.gabi.builder import ( - BuildDistributedProofList, - BuildProofList, - Challenge, - CredentialBuilder, - IssueCommitmentMessage, - Issuer, - Verify, -) -from .....attestation.wallet.irmaexact.gabi.credential import Credential -from .....attestation.wallet.irmaexact.gabi.keys import DefaultSystemParameters, PrivateKey, PublicKey, SignMessageBlock -from .....attestation.wallet.irmaexact.gabi.proofs import ProofP, ProofPCommitment, createChallenge -from .....attestation.wallet.primitives.value import FP2Value -from ....base import TestBase - -# ruff: noqa: N806 - - -class TestCredential(TestBase): - """ - Tests related to IRMA credentials. - """ - - def setUp(self) -> None: - """ - Set up proof constants. - """ - super().setUp() - self.testAttributes1 = [1, 2, 3, 4] - self.testAttributes2 = [5, 6, 7, 8] - - p = 10436034022637868273483137633548989700482895839559909621411910579140541345632481969613724849214412062500244238926015929148144084368427474551770487566048119 - q = 9204968012315139729618449685392284928468933831570080795536662422367142181432679739143882888540883909887054345986640656981843559062844656131133512640733759 - n = 96063359353814070257464989369098573470645843347358957127875426328487326540633303185702306359400766259130239226832166456957259123554826741975265634464478609571816663003684533868318795865194004795637221226902067194633407757767792795252414073029114153019362701793292862118990912516058858923030408920700061749321 - S = 68460510129747727135744503403370273952956360997532594630007762045745171031173231339034881007977792852962667675924510408558639859602742661846943843432940752427075903037429735029814040501385798095836297700111333573975220392538916785564158079116348699773855815825029476864341585033111676283214405517983188761136 - Z = 44579327840225837958738167571392618381868336415293109834301264408385784355849790902532728798897199236650711385876328647206143271336410651651791998475869027595051047904885044274040212624547595999947339956165755500019260290516022753290814461070607850420459840370288988976468437318992206695361417725670417150636 - R = [ - 75350858539899247205099195870657569095662997908054835686827949842616918065279527697469302927032348256512990413925385972530386004430200361722733856287145745926519366823425418198189091190950415327471076288381822950611094023093577973125683837586451857056904547886289627214081538422503416179373023552964235386251, - 16493273636283143082718769278943934592373185321248797185217530224336539646051357956879850630049668377952487166494198481474513387080523771033539152347804895674103957881435528189990601782516572803731501616717599698546778915053348741763191226960285553875185038507959763576845070849066881303186850782357485430766, - 13291821743359694134120958420057403279203178581231329375341327975072292378295782785938004910295078955941500173834360776477803543971319031484244018438746973179992753654070994560440903251579649890648424366061116003693414594252721504213975050604848134539324290387019471337306533127861703270017452296444985692840, - 86332479314886130384736453625287798589955409703988059270766965934046079318379171635950761546707334446554224830120982622431968575935564538920183267389540869023066259053290969633312602549379541830869908306681500988364676409365226731817777230916908909465129739617379202974851959354453994729819170838277127986187, - 68324072803453545276056785581824677993048307928855083683600441649711633245772441948750253858697288489650767258385115035336890900077233825843691912005645623751469455288422721175655533702255940160761555155932357171848703103682096382578327888079229101354304202688749783292577993444026613580092677609916964914513, - 65082646756773276491139955747051924146096222587013375084161255582716233287172212541454173762000144048198663356249316446342046266181487801411025319914616581971563024493732489885161913779988624732795125008562587549337253757085766106881836850538709151996387829026336509064994632876911986826959512297657067426387 - ] - self.testPubK = PublicKey(n, Z, S, R, 0, time.time() + 365 * 24 * 3600) - self.testPrivK = PrivateKey(p, q, 0, time.time() + 365 * 24 * 3600) - - p = 12511561644521105216249960315425509848310543851123625148071038103672749250653050780946327920540373585150518830678888836864183842100121288018131086700947919 - q = 13175754961224278923898419496296790582860213842149399404614891067426616055648139811854869087421318470521236911637912285993998784296429335994419545592486183 - n = 164849270410462350104130325681247905590883554049096338805080434441472785625514686982133223499269392762578795730418568510961568211704176723141852210985181059718962898851826265731600544499072072429389241617421101776748772563983535569756524904424870652659455911012103327708213798899264261222168033763550010103177 - S = 95431387101397795194125116418957121488151703839429468857058760824105489778492929250965841783742048628875926892511288385484169300700205687919208898288594042075246841706909674758503593474606503299796011177189518412713004451163324915669592252022175131604797186534801966982736645522331999047305414834481507220892 - Z = 85612209073231549357971504917706448448632620481242156140921956689865243071517333286408980597347754869291449755693386875207418733579434926868804114639149514414312088911027338251870409643059636340634892197874721564672349336579075665489514404442681614964231517891268285775435774878821304200809336437001672124945 - R = [ - 15948796959221892486955992453179199515496923441128830967123361439118018661581037984810048354811434050038778558011395590650011565629310700360843433067202313291361609843998531962373969946197182940391414711398289105131565252299185121868561402842968555939684308560329951491463967030905495360286851791764439565922, - 119523438901119086528333705353116973341573129722743063979885442255495816390473126070276442804547475203517104656193873407665058481273192071865721910619056848142740067272069428460724210705091048104466624895000063564223095487133194907203681789863578060886235105842841954519189942453426975057803871974937309502784, - 21036812778930907905009726679774009067486097699134635274413938052367886222555608567065065339702690960558290977766511663461460906408225144877806673612081001465755091058944847078216758263034300782760502281865270151054157854728772298542643419836244547728225955304279190350362963560596454003412543292789187837679, - 2507221674373339204944916721547102290807064604358409729371715856726643784893285066715992395214052930640947278288383410209092118436778149456628267900567208684458410552361708506911626161349456189054709967676518205745736652492505957876189855916223094854626710186459345996698113370306994139940441752005221653088, - 43215325590379490852400435325847836613513274803460964568083232110934910151335113918829588414147781676586145312074043749201037447486205927144941119404243266454032858201713735324770837218773739346063812751896736791478531103409536739098007890723770126159814845238386299865793353073058783010002988453373168625327, - 61146634020942775692657595021461289090915429142715194304483397998858712705680675945417056124974172620475325240482216550923967273908399017396442709297466408094303826941548068001214817725191465207971123378222070812822903173820970991987799984521470178624084174451047081964996323127069438975310975798326710264763 - ] - self.testPubK1 = PublicKey(n, Z, S, R, 0, time.time() + 365 * 24 * 3600) - self.testPrivK1 = PrivateKey(p, q, 0, time.time() + 365 * 24 * 3600) - - p = 11899204220405157066705854076362480104861239101931883074217284817546620402667365757487512145720112988257938861512783018148367540266552183843422556696835959 - q = 11687675946826056427944301889720810769697676393649416932482597289652868791085152984663910808816076612347241543876183667586150260004323007396424045765933627 - n = 139074042953200450756577573716087081093125755047959835310375736112120174400606581560965321655328552305330880412762069205250416578144697608952814011140599345836848582980530546248138864212612840364874312923816166397038873282769982501212640794354680085233677961149767121970163329979736254573701512654860500893293 - S = 126829853005972541969086001260986453668465797381061677444000682968013144068393822597398725937194773101762625079278987532636583109409344117202136151661601603097793537754186056937000748076167489862365768508194908399597522777250699581364596246205795577663373872577816687658275462617741670486719685398698263686551 - Z = 42734451137499583379659313067721582376262445005019898840924212896341861721344880887076647548954065511016613532399873561753770596699950716884806217151189571670373798409647535613026097425988280287210414508240665780830389936353108210951728065700426436951835936702999674654289936428229982569295227091726810208504 - R = [ - 40338259065130185314739658157310048192093670364817714952600609624607192408306024366086231626356707587756324374416236635377699775899652135471760526981946419799164489776538365542337621218846077191008645978143565824845696569002709540904092145615635620069766477253299607733404658708555482236387943774145644107155, - 87294590926764077882765166008319250454824581316986036240948880310176122397314769805046534571305547053810590771663913726538715272940723444205499052940110064720613691982665763438729000435763267929115086526907175748438671858290067669579138779857489538782552512452684382063115068635634905118784884820252032788713, - 45112630188085238903069069511798663932075329935779132383847263380203067284915894010441781813845184965705336439320602592823045182968796600558189004025038858823202813711551231906042036283775342496224178435309129468488081668058550719904823188068692199073681725733882486184478432125414991289211704253384344158081, - 22895199267295669971377907000498707372807373558129284002593860052803834778891828018872532360982520545310813792866731358720045880773782974790652802346358667674975135735260730170180413669755483849990358724482246391921757338735789576941697731958222822227522297243574534946426308507662162995899206568536028623103, - 29442357694189149206874997834969163436044466589167060785051742894686201256234721711106548932718033481872195748036017185452480637488189438942261880419540814690300046143608677755570098259230237537965383960964005848716674912279997266193234061274749285289871273401669268876576539473354504176111056568584915827297, - 131901907144475345605474419271525166840628320727233669347338800265775060322235098813990701559838451432946945231275304351611643638306679131070017823266011946014245927069041536778330134744287743396547932833493856762058626556853615297319468923040156688227503880614709468161168272362825615977596973869772839600546 - ] - self.testPubK2 = PublicKey(n, Z, S, R, 0, time.time() + 365 * 24 * 3600) - self.testPrivK2 = PrivateKey(p, q, 0, time.time() + 365 * 24 * 3600) - - def _createCredential(self, context: int, secret: int, issuer: Issuer) -> Credential | None: # noqa: N802 - """ - Have an issuer construct a credential for the given context and secret. - """ - keylength = 1024 - nonce1 = random.randint(0, DefaultSystemParameters[keylength].Lstatzk) - nonce2 = random.randint(0, DefaultSystemParameters[keylength].Lstatzk) - cb = CredentialBuilder(issuer.Pk, context, secret, nonce2) - commitMsg = cb.CommitToSecretAndProve(nonce1) - ism = issuer.IssueSignature(commitMsg.U, self.testAttributes1, nonce2) - return cb.ConstructCredential(ism, self.testAttributes1) - - def test_show_proof(self) -> None: - """ - Test showing a partial proof. - """ - signature = SignMessageBlock(self.testPrivK, self.testPubK, self.testAttributes1) - - cred = Credential(self.testPubK, self.testAttributes1, signature) - disclosed = [1, 2] - - context = random.randint(0, self.testPubK.Params.Lh) - nonce1 = random.randint(0, self.testPubK.Params.Lstatzk) - - proof = cred.CreateDisclosureProof(disclosed, context, nonce1) - - self.assertTrue(proof.Verify(self.testPubK, context, nonce1, False)) - - def test_construct_credential(self) -> None: - """ - Test constructing a credential. - """ - context = random.randint(0, 1 << (self.testPubK.Params.Lh - 1)) - nonce1 = random.randint(0, 1 << (self.testPubK.Params.Lstatzk - 1)) - nonce2 = random.randint(0, 1 << (self.testPubK.Params.Lstatzk - 1)) - secret = random.randint(0, 1 << (self.testPubK.Params.Lm - 1)) - - cb = CredentialBuilder(self.testPubK1, context, secret, nonce2) - commit_msg = cb.CommitToSecretAndProve(nonce1) - - issuer = Issuer(self.testPrivK1, self.testPubK1, context) - msg = issuer.IssueSignature(commit_msg.U, self.testAttributes1, nonce2) - - self.assertIsNotNone(cb.ConstructCredential(msg, self.testAttributes1)) - - def test_construct_credential_challenge(self) -> None: - """ - Test constructing a credential with Challenge. - """ - context = random.randint(0, 1 << (self.testPubK.Params.Lh - 1)) - nonce1 = random.randint(0, 1 << (self.testPubK.Params.Lstatzk - 1)) - nonce2 = random.randint(0, 1 << (self.testPubK.Params.Lstatzk - 1)) - secret = random.randint(0, 1 << (self.testPubK.Params.Lm - 1)) - - cb = CredentialBuilder(self.testPubK1, context, secret, nonce2) - challenge = Challenge([cb], context, nonce1, False) - proofs = BuildDistributedProofList([cb], challenge, []) - commit_msg = IssueCommitmentMessage(None, proofs, nonce1) - - self.assertTrue(Verify(commit_msg.Proofs, [self.testPubK1], context, nonce1, False)) - - issuer = Issuer(self.testPrivK1, self.testPubK1, context) - msg = issuer.IssueSignature(commit_msg.Proofs[0].U, self.testAttributes1, nonce2) - - self.assertIsNotNone(cb.ConstructCredential(msg, self.testAttributes1)) - - def test_construct_credential_challenge_pcommit(self) -> None: - """ - Test constructing a credential with Challenge and PCommit. - """ - context = random.randint(0, 1 << (self.testPubK.Params.Lh - 1)) - nonce1 = random.randint(0, 1 << (self.testPubK.Params.Lstatzk - 1)) - nonce2 = random.randint(0, 1 << (self.testPubK.Params.Lstatzk - 1)) - secret = random.randint(0, 1 << (self.testPubK.Params.Lm - 1)) - issuer = Issuer(self.testPrivK1, self.testPubK1, context) - cr = { - 'keyCounter': 0, - 'credential': 'test.credential', - 'validity': int(time.time()) + 60000, - 'attributes': { - "test1": "value1", - "test2": "value2" - } - } - - s = 1234 - s_randomizer = 5678 - pcommit = ProofPCommitment(FP2Value(issuer.Pk.N, issuer.Pk.R[0]).intpow(s).a, - FP2Value(issuer.Pk.N, issuer.Pk.R[0]).intpow(s_randomizer).a) - - cb = CredentialBuilder(self.testPubK1, context, secret, nonce2) - cb.MergeProofPCommitment(pcommit) - challenge = Challenge([cb], context, nonce1, False) - proof_p = ProofP(pcommit.P, challenge, s_randomizer + challenge * s) - - proofs = BuildDistributedProofList([cb], challenge, []) - for p in proofs: - p.MergeProofP(proof_p, self.testPubK1) - commit_msg = IssueCommitmentMessage(None, proofs, nonce1) - - self.assertTrue(Verify(commit_msg.Proofs, [self.testPubK1], context, nonce1, False)) - self.assertEqual(1, len(commit_msg.Proofs)) - - attr_list, signing_date = make_attribute_list(cr) - msg = issuer.IssueSignature(commit_msg.Proofs[0].U, attr_list, nonce2) - credential = cb.ConstructCredential(msg, attr_list) - self.assertIsNotNone(credential) - - # Verifier side - challenge_verif = random.randint(0, issuer.Pk.N) - - # Prover side - builder = credential.CreateDisclosureProofBuilder(list(range(1, len(attr_list) + 1))) - builder.MergeProofPCommitment(pcommit) - commit_randomizer = random.randint(0, 1 << (self.testPubK.Params.LmCommit - 1)) - A, Z = builder.Commit(commit_randomizer) - p = builder.CreateProof(challenge) - p.MergeProofP(proof_p, issuer.Pk) - - # Respond to challenge - secondaryChallenge = createChallenge(challenge_verif, challenge_verif, [A, Z], False) - - # Commit to p.C, p.A, p.EResponse, p.VResponse, p.AResponses - # Blank out attributes before sharing - p.ADisclosed = {} # p now resembles ProofD on Verifier side - - # Verifier side - reconstructed_attr_list, _ = make_attribute_list(cr) - reconstructed_attr_map = {} - for i in range(len(attr_list)): - reconstructed_attr_map[i + 1] = attr_list[i] - p.ADisclosed = reconstructed_attr_map - Ap, Zp = p.ChallengeContribution(issuer.Pk) - p.C = secondaryChallenge - reconstructed_challenge = createChallenge(challenge_verif, challenge_verif, [Ap, Zp], False) - self.assertTrue(p.VerifyWithChallenge(issuer.Pk, reconstructed_challenge)) - - def test_show_proof_list(self) -> None: - """ - Test showing a list of proofs. - """ - context = random.randint(0, self.testPubK.Params.Lh) - nonce1 = random.randint(0, self.testPubK.Params.Lstatzk) - secret = random.randint(0, self.testPubK.Params.Lm) - - issuer1 = Issuer(self.testPrivK1, self.testPubK1, context) - cred1 = self._createCredential(context, secret, issuer1) - - issuer2 = Issuer(self.testPrivK2, self.testPubK2, context) - cred2 = self._createCredential(context, secret, issuer2) - - builders = [cred1.CreateDisclosureProofBuilder([1, 2]), cred2.CreateDisclosureProofBuilder([1, 3])] - prooflist = BuildProofList(builders, context, nonce1, False) - - self.assertTrue(Verify(prooflist, [issuer1.Pk, issuer2.Pk], context, nonce1, False)) - - def test_issue_and_show(self) -> None: - """ - Test the full stack of issuance and showing. - """ - context = random.randint(0, self.testPubK.Params.Lh) - nonce1 = random.randint(0, self.testPubK.Params.Lstatzk) - nonce2 = random.randint(0, self.testPubK.Params.Lstatzk) - secret = random.randint(0, self.testPubK.Params.Lm) - - cb1 = CredentialBuilder(self.testPubK, context, secret, nonce2) - commitMsg = cb1.CommitToSecretAndProve(nonce1) - - issuer1 = Issuer(self.testPrivK, self.testPubK, context) - ism = issuer1.IssueSignature(commitMsg.U, self.testAttributes1, nonce2) - - cred1 = cb1.ConstructCredential(ism, self.testAttributes1) - - cb2 = CredentialBuilder(self.testPubK, context, secret, nonce2) - issuer2 = Issuer(self.testPrivK, self.testPubK, context) - - builders = [cred1.CreateDisclosureProofBuilder([1, 2]), cb2] - prooflist = BuildProofList(builders, context, nonce1, False) - - commitMsg2 = cb2.CreateIssueCommitmentMessage(prooflist) - - self.assertTrue(Verify(commitMsg2.Proofs, [self.testPubK, self.testPubK], context, nonce1, False)) - - msg = issuer2.IssueSignature(commitMsg2.U, self.testAttributes1, nonce2) - cred2 = cb2.ConstructCredential(msg, self.testAttributes1) - - nonce1s = random.randint(0, self.testPubK.Params.Lstatzk) - disclosedAttributes = [1, 3] - proof = cred2.CreateDisclosureProof(disclosedAttributes, context, nonce1s) - - self.assertTrue(proof.Verify(self.testPubK, context, nonce1s, False)) - - def test_issue_show_random(self) -> None: - """ - Test the full stack of issuance, deriving and showing. - """ - keylength = 1024 - context = random.randint(0, DefaultSystemParameters[keylength].Lh) - secret = random.randint(0, DefaultSystemParameters[keylength].Lm) - nonce2 = random.randint(0, DefaultSystemParameters[keylength].Lstatzk) - - issuer1 = Issuer(self.testPrivK1, self.testPubK1, context) - cred1 = self._createCredential(context, secret, issuer1) - - issuer2 = Issuer(self.testPrivK2, self.testPubK2, context) - cb2 = CredentialBuilder(issuer2.Pk, context, secret, nonce2) - - nonce1 = random.randint(0, DefaultSystemParameters[keylength].Lstatzk) - builders = [cred1.CreateDisclosureProofBuilder([1, 2]), cb2] - prooflist = BuildProofList(builders, context, nonce1, False) - - commitMsg = cb2.CreateIssueCommitmentMessage(prooflist) - - self.assertTrue(Verify(commitMsg.Proofs, [issuer1.Pk, issuer2.Pk], context, nonce1, False)) - - msg = issuer2.IssueSignature(commitMsg.U, self.testAttributes2, nonce2) - cred2 = cb2.ConstructCredential(msg, self.testAttributes2) - - nonce1s = random.randint(0, issuer2.Pk.Params.Lstatzk) - disclosedAttributes = [1, 3] - proof = cred2.CreateDisclosureProof(disclosedAttributes, context, nonce1s) - - self.assertTrue(proof.Verify(issuer2.Pk, context, nonce1s, False)) - - def test_big_attribute(self) -> None: - """ - Test if a big attribute value still works. - """ - attrs = [1, 2, - 139074042953200450756577573716087081093125755047959835310375736112120174400606581560965321655328552305330880412762069205250416578144697608952814011140599345836848582980530546248138864212612840364874312923816166397038873282769982501212640794354680085233677961149767121970163329979736254573701512654860500893293] - signature = SignMessageBlock(self.testPrivK, self.testPubK, attrs) - cred = Credential(self.testPubK, attrs, signature) - self.assertTrue(signature.Verify(self.testPubK, attrs)) - - context = random.randint(0, self.testPubK.Params.Lh) - nonce1 = random.randint(0, self.testPubK.Params.Lstatzk) - - proof = cred.CreateDisclosureProof([1], context, nonce1) - self.assertTrue(proof.Verify(self.testPubK, context, nonce1, False)) - - proof = cred.CreateDisclosureProof([2], context, nonce1) - self.assertTrue(proof.Verify(self.testPubK, context, nonce1, False)) diff --git a/ipv8/test/attestation/wallet/irmaexact/test_keys.py b/ipv8/test/attestation/wallet/irmaexact/test_keys.py deleted file mode 100644 index e22b2ec61..000000000 --- a/ipv8/test/attestation/wallet/irmaexact/test_keys.py +++ /dev/null @@ -1,28 +0,0 @@ -""" -Copyright (c) 2016, Maarten Everts -All rights reserved. - -This source code has been ported from https://github.com/privacybydesign/gabi -The authors of this file are not -in any way- affiliated with the original authors or organizations. -""" -import unittest - -from .....attestation.wallet.irmaexact.gabi.keys import DefaultSystemParameters, GenerateKeyPair, SignMessageBlock -from ....base import TestBase - - -class TestKeys(TestBase): - """ - Tests related to IRMA keys. - """ - - @unittest.SkipTest # Too slow and unused. - def test_generate_and_sign(self) -> None: - """ - Generate a new key and sign a message, see if the signature verifies. - """ - privkey, pubkey = GenerateKeyPair(DefaultSystemParameters[1024], 1, 0, 0) - sig = SignMessageBlock(privkey, pubkey, [1]) - - self.assertTrue(sig.Verify(pubkey, [1])) - self.assertTrue(sig.Randomize(pubkey).Verify(pubkey, [1])) diff --git a/ipv8/test/attestation/wallet/irmaexact/test_proofs.py b/ipv8/test/attestation/wallet/irmaexact/test_proofs.py deleted file mode 100644 index cced3f30b..000000000 --- a/ipv8/test/attestation/wallet/irmaexact/test_proofs.py +++ /dev/null @@ -1,94 +0,0 @@ -# ruff: noqa -""" -Copyright (c) 2016, Maarten Everts -All rights reserved. - -This source code has been ported from https://github.com/privacybydesign/gabi -The authors of this file are not -in any way- affiliated with the original authors or organizations. -""" - -import time - -from ....base import TestBase -from .....attestation.wallet.irmaexact.gabi.keys import CLSignature, PublicKey -from .....attestation.wallet.irmaexact.gabi.proofs import ProofD, ProofS, ProofU - - -class TestProofs(TestBase): - - def setUp(self): - super().setUp() - n = 96063359353814070257464989369098573470645843347358957127875426328487326540633303185702306359400766259130239226832166456957259123554826741975265634464478609571816663003684533868318795865194004795637221226902067194633407757767792795252414073029114153019362701793292862118990912516058858923030408920700061749321 - S = 68460510129747727135744503403370273952956360997532594630007762045745171031173231339034881007977792852962667675924510408558639859602742661846943843432940752427075903037429735029814040501385798095836297700111333573975220392538916785564158079116348699773855815825029476864341585033111676283214405517983188761136 - Z = 44579327840225837958738167571392618381868336415293109834301264408385784355849790902532728798897199236650711385876328647206143271336410651651791998475869027595051047904885044274040212624547595999947339956165755500019260290516022753290814461070607850420459840370288988976468437318992206695361417725670417150636 - R = [ - 75350858539899247205099195870657569095662997908054835686827949842616918065279527697469302927032348256512990413925385972530386004430200361722733856287145745926519366823425418198189091190950415327471076288381822950611094023093577973125683837586451857056904547886289627214081538422503416179373023552964235386251, - 16493273636283143082718769278943934592373185321248797185217530224336539646051357956879850630049668377952487166494198481474513387080523771033539152347804895674103957881435528189990601782516572803731501616717599698546778915053348741763191226960285553875185038507959763576845070849066881303186850782357485430766, - 13291821743359694134120958420057403279203178581231329375341327975072292378295782785938004910295078955941500173834360776477803543971319031484244018438746973179992753654070994560440903251579649890648424366061116003693414594252721504213975050604848134539324290387019471337306533127861703270017452296444985692840, - 86332479314886130384736453625287798589955409703988059270766965934046079318379171635950761546707334446554224830120982622431968575935564538920183267389540869023066259053290969633312602549379541830869908306681500988364676409365226731817777230916908909465129739617379202974851959354453994729819170838277127986187, - 68324072803453545276056785581824677993048307928855083683600441649711633245772441948750253858697288489650767258385115035336890900077233825843691912005645623751469455288422721175655533702255940160761555155932357171848703103682096382578327888079229101354304202688749783292577993444026613580092677609916964914513, - 65082646756773276491139955747051924146096222587013375084161255582716233287172212541454173762000144048198663356249316446342046266181487801411025319914616581971563024493732489885161913779988624732795125008562587549337253757085766106881836850538709151996387829026336509064994632876911986826959512297657067426387 - ] - self.testPubK = PublicKey(n, Z, S, R, 0, time.time() + 365 * 24 * 3600) - - def test_proofu(self): - """ - Test ProofU verification. - """ - context = 34911926065354700717429826907189165808787187263593066036316982805908526740809 - nonce1 = 724811585564063105609243 - c = 4184045431748299802782143929438273256345760339041229271411466459902660986200 - U = 53941714038323323772993715692602421894514053229231925255570480167011458936488064431963770862062871590815370913733046166911453850329862473697478794938988248741580237664467927006089054091941563143176094050444799012171081539721321786755307076274602717003792794453593019124224828904640592766190733869209960398955 - vPrimeResponse = 930401833442556048954810956066821001094106683380918922610147216724718347679854246682690061274042716015957693675615113399347898060611144526167949042936228868420203309360695585386210327439216083389841383395698722832808268885873389302262079691644125050748391319832394519920382663304621540520277648619992590872190274152359156399474623649137315708728792245711389032617438368799004840694779408839779419604877135070624376537994035936 - sResponse = 59776396667523329313292302350278517468587673934875085337674938789292900859071752886820910103285722288747559744087880906618151651690169988337871960870439882357345503256963847251 - - proofU = ProofU(U, c, vPrimeResponse, sResponse) - - self.assertTrue(proofU.Verify(self.testPubK, context, nonce1)) - - def test_proofs(self): - """ - Test ProofS verification. - """ - context = 34911926065354700717429826907189165808787187263593066036316982805908526740809 - n2 = 1424916368173409716606 - - A = 66389313221915836241271893803869162372470096003861448260498566798077037255866372791540928160267561756794143545532118654736979223658343806335872047371607436291528588343320128898584874264796312130159695427439025355009934986408160536404163490935544221152821545871675088845781351195696518382628790514628112517886 - e = 259344723055062059907025491480697571938277889515152306249728583105665800713306759149981690559193987143012367913206299323899696942213235956742930207251663943512715842083759814664217 - v = 32427566863312925183262683355749521096160753564085736927716798279834745436154181827687524960554513739692930154573915901486008843583586162755818099731448281905764117842382407835789897633042765641230655956290191876265377547222981221260311549695231999461733778383779100992221748503727598149536948999564401095816377323412637286891625085960745712119714441272446053177642615033258689648568679017384011895908901362352242970432640019866501367925956123252426587516554347912178721773507440862343752105273189184247444400383 - - c = 60359393410007276721785600209946099643760005142374188599509762410975853354415 - eResponse = 1139627737042307991725447845798004742853435356249558932466535799661640630812910641126155269500348608443317861800376689024557774460643901450316279085276256524076388421890909312661873221470626068394945683125859434135652717426417681918932528613003921792075852313319584079881881807505760375270399908999784672094 - - sig = CLSignature(A, e, v) - proof = ProofS(c, eResponse) - - self.assertTrue(proof.Verify(self.testPubK, sig, context, n2)) - - def test_proofd(self): - """ - Test ProofD verification. - """ - nonce1 = 356168310758183945030882 - context = 59317469690166962413036802769129097120995929488116634148207386064523180296869 - - c = 92405256824458923934294175762399873039847432841647909261385804859937404075570 - A = 66467922530801909191099602528137141713616048447732479189179865050384832390931230033112445547628606292639430708552418462959456337530534055700746138057512598497120682196611341962749384189596253759402224308748002860890211498962735924481685975488607793795169788837476493253297353146422154392391732925567178805607 - eResponse = 44022597110989879399510333540268555303613344906583879371531630680320900347240418258690335759375210734514869637566864349585531295946323809 - vResponse = 26326301830460880582628741955953428491879823201714737915103888193625032953131902593859116395461541557845953939714765660366793552012359281854190756504190064959818584175057775414324351414234450208391534497565506441579960808534266557458251190151268682500197950418141493586125049371381626638554299245282498637246703583102656876690825544275995631773170789236920674341621008537679924624747222821679128060382072191284077393034573357698475000667180794116538132628586533009732462826119381931507809052573496513689222244701991737191273263148163121236326525677935993049602389899306007664212328515456044738278420 - - aResponses = {0: 55247823867049193571627241180110605447453053126985891402640532123848293918217459966028364637387399903283634100097425890971508590427350301193682412170041146212137866279677802531} - - aDisclosed = { - 1: 1100598411265, - 2: 43098508374675488371040117572049064979183030441504364, - 3: 4919409929397552454, - } - - proof1 = ProofD(c, A, eResponse, vResponse, aResponses, aDisclosed) - - self.assertTrue(proof1.Verify(self.testPubK, context, nonce1, False)) - - aDisclosed[1] = 123 - proof2 = ProofD(c, A, eResponse, vResponse, aResponses, aDisclosed) - self.assertFalse(proof2.Verify(self.testPubK, context, nonce1, False))