def helper_function_reconstruct(self, t, n): Gq = EcGroup() p = Gq.order() g = Gq.generator() G = Gq.hash_to_point(b'G') params = (Gq, p, g, G) # Decide on a secret to be distributed m = p.from_binary(b'This is a test') # Initiate participants, and generate their key-pairs priv_keys = [] pub_keys = [] for i in range(n): (x_i, y_i) = pvss.helper_generate_key_pair(params) priv_keys.append(x_i) pub_keys.append(y_i) # Encrypt secret, create shares and proof (pub, proof) = pvss.gen_proof(params, t, n, m, pub_keys) # Decryption # Calculate what a correct decryption should be expected_decryption = m * g # Let participants decrypt their shares and generate proofs proved_decryptions = [ pvss.participant_decrypt_and_prove(params, x_i, enc_share) for (x_i, enc_share) in zip(priv_keys, pub['Y_list']) ] if pvss.batch_verify_correct_decryption( proved_decryptions, pub['Y_list'], pub_keys, p, G) is False: print("Verification of decryption failed") S_list = [S_i for (S_i, decrypt_proof) in proved_decryptions] return (expected_decryption, S_list, p)
def mix_client_n_hop(public_keys, address, message, use_blinding_factor=False): """ Encode a message to travel through a sequence of mixes with a sequence public keys. The maximum size of the final address and the message are 256 bytes and 1000 bytes respectively. Returns an 'NHopMixMessage' with four parts: a public key, a list of hmacs (20 bytes each), an address ciphertext (256 + 2 bytes) and a message ciphertext (1002 bytes). The implementation of the blinding factor is optional and therefore only activated in the bonus tests. It can be ignored for the standard task. If you implement the bonus task make sure to only activate it if use_blinding_factor is True. """ G = EcGroup() # assert G.check_point(public_key) assert isinstance(address, bytes) and len(address) <= 256 assert isinstance(message, bytes) and len(message) <= 1000 # Encode the address and message # use those encoded values as the payload you encrypt! address_plaintext = pack("!H256s", len(address), address) message_plaintext = pack("!H1000s", len(message), message) ## Generate a fresh public key private_key = G.order().random() client_public_key = private_key * G.generator() #TODO ADD CODE HERE return NHopMixMessage(client_public_key, hmacs, address_cipher, message_cipher)
def time_scalar_mul(): # setup curve G = EcGroup(713) # NIST curve d = G.parameters() a, b, p = d["a"], d["b"], d["p"] g = G.generator() gx0, gy0 = g.get_affine() order = G.order() r = order.random() gx2, gy2 = (r * g).get_affine() # First a value with low hamming weight scalar_1 = Bn.from_hex('11111111111111111111111111111111111111111') # The second scalar value with a much higher hamming weight scalar_2 = Bn.from_hex('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF') # Scalar values with higher hamming weight will take longer to # compute the multiplication of. t1 = time.clock() x2, y2 = point_scalar_multiplication_double_and_add( a, b, p, gx0, gy0, scalar_1) t2 = time.clock() runtime = t2 - t1 print("Runtime for scalar 1: " + str(runtime)) t1 = time.clock() x2, y2 = point_scalar_multiplication_double_and_add( a, b, p, gx0, gy0, scalar_2) t2 = time.clock() runtime = t2 - t1 print("Runtime for scalar 2: " + str(runtime))
def setup(): ''' Setup the parameters of the mix crypto-system ''' G = EcGroup() o = G.order() g = G.generator() o_bytes = int(math.ceil(math.log(float(int(o))) / math.log(256))) return G, o, g, o_bytes
def mix_client_one_hop(public_key, address, message): """ Encode a message to travel through a single mix with a set public key. The maximum size of the final address and the message are 256 bytes and 1000 bytes respectively. Returns an 'OneHopMixMessage' with four parts: a public key, an hmac (20 bytes), an address ciphertext (256 + 2 bytes) and a message ciphertext (1002 bytes). """ G = EcGroup() assert G.check_point(public_key) assert isinstance(address, bytes) and len(address) <= 256 assert isinstance(message, bytes) and len(message) <= 1000 # Encode the address and message # Use those as the payload for encryption address_plaintext = pack("!H256s", len(address), address) message_plaintext = pack("!H1000s", len(message), message) ## Generate a fresh public key private_key = G.order().random() client_public_key = private_key * G.generator() #TODO ADD CODE HERE return OneHopMixMessage(client_public_key, expected_mac, address_cipher, message_cipher)
def test_Alice_encode_3_hop(): """ Test sending a multi-hop message through 1-hop """ from os import urandom G = EcGroup() g = G.generator() o = G.order() private_keys = [o.random() for _ in range(3)] public_keys = [pk * g for pk in private_keys] address = b"Alice" message = b"Dear Alice,\nHello!\nBob" m1 = mix_client_n_hop(public_keys, address, message) out = mix_server_n_hop(private_keys[0], [m1]) out = mix_server_n_hop(private_keys[1], out) out = mix_server_n_hop(private_keys[2], out, final=True) assert len(out) == 1 assert out[0][0] == address assert out[0][1] == message
def setup(): """ Generates parameters for Commitments """ G = EcGroup() g = G.hash_to_point(b'g') h = G.hash_to_point(b'h') o = G.order() return (G, g, h, o)
def __init__(self, arch, enc, el1, el2, el3, el4, ports): print("CF: init") self.done = Deferred() self.c_proto = None self.G = EcGroup(713) self.o = self.G.order() self.g = self.G.generator() self.o_bytes = int(math.ceil(math.log(float(int(self.o))) / math.log(256))) self.data = ["STT", int(urandom(2).encode('hex'),16), [ Actor("DB", "127.0.0.1", 8000, ""), 3]] if arch: if enc: self.data[2].extend([["", Bn.from_binary(base64.b64decode(el2))]]) else: self.data[2].extend([[Bn.from_binary(base64.b64decode(el2)), Bn.from_binary(base64.b64decode(el2))]]) else: if enc: self.data[2].extend([["", Bn.from_binary(base64.b64decode(el2))],[["", Bn.from_binary(base64.b64decode(el4))]]]) else: self.data[2].extend([ [Bn.from_binary(base64.b64decode(el1)), Bn.from_binary(base64.b64decode(el2))], [Bn.from_binary(base64.b64decode(el3)), Bn.from_binary(base64.b64decode(el4))]]) actors=[] for i in range(len(ports)): actors.extend([Actor("M"+str(i), "127.0.0.1", 8001+i, "")]) self.data[2].extend([[actors]])
def time_scalar_mul(): import time, pprint G = EcGroup() d = G.parameters() a, b, p = d["a"], d["b"], d["p"] g = G.generator() x, y = g.get_affine() scalars = G.order().hex() results = [] for i in range(0, len(scalars), 3): r = Bn.from_hex(scalars[:i+1]) start = time.clock() point_scalar_multiplication_double_and_add(a, b, p, x, y, r) elapsed = (time.clock() - start) results.append((r, elapsed)) pp = pprint.PrettyPrinter(indent=2, width=160) pp.pprint(results) for i in range(0, len(scalars), 3): r = Bn.from_hex(scalars[:i+1]) start = time.clock() point_scalar_multiplication_montgomerry_ladder(a, b, p, x, y, r) elapsed = (time.clock() - start) results.append((r, elapsed)) pp = pprint.PrettyPrinter(indent=2, width=160) pp.pprint(results)
def test_Pedersen_Env(): # Define an EC group G = EcGroup(713) order = G.order() ## Proof definitions zk = ZKProof(G) g, h = zk.get(ConstGen, ["g", "h"]) x, o = zk.get(Sec, ["x", "o"]) Cxo = zk.get(Gen, "Cxo") zk.add_proof(Cxo, x*g + o*h) print(zk.render_proof_statement()) # A concrete Pedersen commitment ec_g = G.generator() ec_h = order.random() * ec_g bn_x = order.random() bn_o = order.random() ec_Cxo = bn_x * ec_g + bn_o * ec_h env = ZKEnv(zk) env.g, env.h = ec_g, ec_h env.Cxo = ec_Cxo env.x = bn_x env.o = bn_o sig = zk.build_proof(env.get()) # Execute the verification env = ZKEnv(zk) env.g, env.h = ec_g, ec_h assert zk.verify_proof(env.get(), sig)
def time_scalar_mul(): G = EcGroup(713) # NIST curve d = G.parameters() a, b, p = d["a"], d["b"], d["p"] g = G.generator() gx0, gy0 = g.get_affine() def average_time(func, scalar_name, samples=20): scalar = globals()[scalar_name] times = [] for i in range(samples): t1 = clock() func(a, b, p, gx0, gy0, scalar) t2 = clock() times.append(t2 - t1) mean = reduce((lambda x, y: x + y), times) / samples print('{}, {}, mean of {} samples: {}'.format(func.__name__, scalar_name, samples, mean)) average_time(point_scalar_multiplication_double_and_add, 'R1') average_time(point_scalar_multiplication_double_and_add, 'R2') average_time(point_scalar_multiplication_montgomerry_ladder, 'R1') average_time(point_scalar_multiplication_montgomerry_ladder, 'R2')
def test_timings(): # Make 100 keys G = EcGroup() keys = [] for _ in range(100): sec = G.order().random() k = Key(sec.binary(), False) # bpub, bsec = k.export() keys += [k] msg = urandom(32) # time sign t0 = timer() sigs = [] for i in range(1000): sigs += [(keys[i % 100], keys[i % 100].sign(msg))] t1 = timer() print "\nSign rate: %2.2f / sec" % (1.0 / ((t1-t0)/1000.0)) # time verify t0 = timer() for k, sig in sigs: assert k.verify(msg, sig) t1 = timer() print "Verify rate: %2.2f / sec" % (1.0 / ((t1-t0)/1000.0)) # time hash t0 = timer() for _ in range(10000): sha256(msg).digest() t1 = timer() print "Hash rate: %2.2f / sec" % (1.0 / ((t1-t0)/10000.0))
def test_gen_polynomial(self): Gq = EcGroup() p = Gq.order() px = pvss.gen_polynomial(3, 42, p) for pi in px: assert pi < p
def test_steady(): G = EcGroup() g = G.generator() x = G.order().random() pki = {"me": (x * g, x * g)} client = KulanClient(G, "me", x, pki) ## Mock some keys client.Ks += [bytes(urandom(16))] # Decrypt a small message ciphertext = client.steady_encrypt(b"Hello World!") client.steady_decrypt(ciphertext) # Decrypt a big message ciphertext = client.steady_encrypt(b"Hello World!" * 10000) client.steady_decrypt(ciphertext) # decrypt an empty string ciphertext = client.steady_encrypt(b"") client.steady_decrypt(ciphertext) # Time it import time t0 = time.clock() for _ in range(1000): ciphertext = client.steady_encrypt(b"Hello World!" * 10) client.steady_decrypt(ciphertext) t = time.clock() - t0 print() print(" - %2.2f operations / sec" % (1.0 / (t / 1000)))
def __init__(self, name, ip, port, prvk, cascade=1, layered=1): print "Mix: init", name, ip, port, prvk, cascade, layered #Mix initialization self.name = name # Name of the mix self.port = port # Port of the mix self.ip = ip # IP of the mix #Mix keys self.G = EcGroup(713) self.o = self.G.order() self.g = self.G.generator() self.o_bytes = int( math.ceil(math.log(float(int(self.o))) / math.log(256))) self.s = (self.G, self.o, self.g, self.o_bytes) self.prvk = Bn.from_binary( base64.b64decode( "/m8A5kOfWNhP4BMcUm7DF0/G0/TBs2YH8KAYzQ==")) #mix private key self.pubk = self.prvk * self.g #mix public key self.setup = (self.G, self.o, self.g, self.o_bytes, self.prvk, self.pubk) self.sessions = {} # Eviction session self.sessionlock = threading.Lock( ) #lock for accessing any information
def setup(): """Generates the Cryptosystem Parameters.""" G = EcGroup(nid=713) g = G.hash_to_point(b"g") h = G.hash_to_point(b"h") o = G.order() return (G, g, h, o)
def setup(): """ Generates the Cryptosystem Parameters. """ G = EcGroup(nid=713) g = G.hash_to_point(b"g") hs = [G.hash_to_point(("h%s" % i).encode("utf8")) for i in range(4)] o = G.order() return (G, g, hs, o)
def test_broad(): G = EcGroup() g = G.generator() x = G.order().random() a, puba = pair(G) b, pubb = pair(G) c, pubc = pair(G) a2, puba2 = pair(G) b2, pubb2 = pair(G) c2, pubc2 = pair(G) pki = {"a":(puba,puba2) , "b":(pubb, pubb2), "c":(pubc, pubc2)} client = KulanClient(G, "me", x, pki) msgs = client.broadcast_encrypt(b"Hello!") pki2 = {"me": x * g, "b":(pubb, pubb2), "c":(pubc, pubc2)} dec_client = KulanClient(G, "a", a, pki2) dec_client.priv_enc = a2 dec_client.pub_enc = puba2 namex, keysx = dec_client.broadcast_decrypt(msgs) assert namex == "me" # print msgs
def test_broad(): G = EcGroup() g = G.generator() x = G.order().random() a, puba = pair(G) b, pubb = pair(G) c, pubc = pair(G) a2, puba2 = pair(G) b2, pubb2 = pair(G) c2, pubc2 = pair(G) pki = {"a": (puba, puba2), "b": (pubb, pubb2), "c": (pubc, pubc2)} client = KulanClient(G, "me", x, pki) msgs = client.broadcast_encrypt(b"Hello!") pki2 = {"me": x * g, "b": (pubb, pubb2), "c": (pubc, pubc2)} dec_client = KulanClient(G, "a", a, pki2) dec_client.priv_enc = a2 dec_client.pub_enc = puba2 namex, keysx = dec_client.broadcast_decrypt(msgs) assert namex == "me"
def mix_client_n_hop(public_keys, address, message): """ Encode a message to travel through a sequence of mixes with a sequence public keys. The maximum size of the final address and the message are 256 bytes and 1000 bytes respectively. Returns an 'NHopMixMessage' with four parts: a public key, a list of hmacs (20 bytes each), an address ciphertext (256 + 2 bytes) and a message ciphertext (1002 bytes). """ G = EcGroup() # assert G.check_point(public_key) assert isinstance(address, bytes) and len(address) <= 256 assert isinstance(message, bytes) and len(message) <= 1000 # Encode the address and message # use those encoded values as the payload you encrypt! address_plaintext = pack("!H256s", len(address), address) message_plaintext = pack("!H1000s", len(message), message) ## Generate a fresh public key private_key = G.order().random() client_public_key = private_key * G.generator() ## ADD CODE HERE return NHopMixMessage(client_public_key, hmacs, address_cipher, message_cipher)
def test_steady(): G = EcGroup() g = G.generator() x = G.order().random() pki = {"me":(x * g, x * g)} client = KulanClient(G, "me", x, pki) ## Mock some keys client.Ks += [bytes(urandom(16))] # Decrypt a small message ciphertext = client.steady_encrypt(b"Hello World!") client.steady_decrypt(ciphertext) # Decrypt a big message ciphertext = client.steady_encrypt(b"Hello World!"*10000) client.steady_decrypt(ciphertext) # decrypt an empty string ciphertext = client.steady_encrypt(b"") client.steady_decrypt(ciphertext) # Time it import time t0 = time.clock() for _ in range(1000): ciphertext = client.steady_encrypt(b"Hello World!"*10) client.steady_decrypt(ciphertext) t = time.clock() - t0 print() print(" - %2.2f operations / sec" % (1.0 / (t / 1000)))
def setup_ggm(nid = 713): """Generates the parameters for an EC group nid""" G = EcGroup(nid) g = G.hash_to_point(b"g") h = G.hash_to_point(b"h") o = G.order() return (G, g, h, o)
def _make_table(trunc_limit, start=conf.LOWER_LIMIT, end=conf.UPPER_LIMIT): G = EcGroup(nid=713) g = G.generator() o = G.order() i_table = {} n_table = {} ix = start * g print "Generating db with truc: " + str(trunc_limit) #trunc_limit = conf.TRUNC_LIMIT for i in range(start, end): #i_table[str(ix)] = str(i) #Uncompressed #Compression trick trunc_ix = str(ix)[:trunc_limit] #print ix #print trunc_ix if trunc_ix in i_table: i_table[trunc_ix] = i_table[trunc_ix] + "," + str(i) else: i_table[trunc_ix] = str(i) n_table[str((o + i) % o)] = str(ix) ix = ix + g #print type(ix) #print type(ix.export()) print "size: " + str(len(i_table)) return i_table, n_table
def execute_Alice_encode_hop(hops, use_blinding_factor=False): """ Test sending a multi-hop message through 1-hop """ from os import urandom G = EcGroup() g = G.generator() o = G.order() private_keys = [o.random() for _ in range(hops)] public_keys = [pk * g for pk in private_keys] address = b"Alice" message = b"Dear Alice,\nHello!\nBob" # Execute the encoding with the client implementation m1 = mix_client_n_hop(public_keys, address, message, use_blinding_factor) # Walk through the hops with the server implementation out = [m1] for hop in range(0, hops - 1): out = mix_server_n_hop(private_keys[hop], out, use_blinding_factor) out = mix_server_n_hop(private_keys[hops - 1], out, use_blinding_factor, final=True) # Check the result assert len(out) == 1 assert out[0][0] == address assert out[0][1] == message
def setup(): ''' Setup the parameters of the mix crypto-system ''' group = EcGroup() order = group.order() generator = group.generator() o_bytes = int(math.ceil(math.log(float(int(order))) / math.log(256))) return group, order, generator, o_bytes
def measure_mix_and_decrypt_execution_times(num_ciphertexts_l, m_value=4, curve_nid=415, n_repetitions=1): """Measure the execution time for mix and decrypt operations.""" group = EcGroup(curve_nid) key_pair = elgamal.KeyPair(group) pk = key_pair.pk measures = list() for num_ciphertexts in num_ciphertexts_l: LOGGER.info("Running mix and decrypt with %d ctxts.", num_ciphertexts) ctxts = [ pk.encrypt(i * group.generator()) for i in range(num_ciphertexts) ] for _ in range(n_repetitions): mixnet_per_server = MixNetPerTeller(key_pair, pk, ctxts, m_value) proof_time = mixnet_per_server.time_mixing decryption_time = mixnet_per_server.time_decrypting measures.append([num_ciphertexts, proof_time, decryption_time]) return measures
def ecdsa_key_gen(): """ Returns an EC group, a random private key for signing and the corresponding public key for verification""" G = EcGroup() priv_sign = G.order().random() pub_verify = priv_sign * G.generator() return (G, priv_sign, pub_verify)
def test_Pedersen_Env(): # Define an EC group G = EcGroup(713) order = G.order() ## Proof definitions zk = ZKProof(G) g, h = zk.get(ConstGen, ["g", "h"]) x, o = zk.get(Sec, ["x", "o"]) Cxo = zk.get(Gen, "Cxo") zk.add_proof(Cxo, x*g + o*h) # A concrete Pedersen commitment ec_g = G.generator() ec_h = order.random() * ec_g bn_x = order.random() bn_o = order.random() ec_Cxo = bn_x * ec_g + bn_o * ec_h env = ZKEnv(zk) env.g, env.h = ec_g, ec_h env.Cxo = ec_Cxo env.x = bn_x env.o = bn_o sig = zk.build_proof(env.get()) # Execute the verification env = ZKEnv(zk) env.g, env.h = ec_g, ec_h assert zk.verify_proof(env.get(), sig)
def test_Point_doubling(): """ Test whether the EC point doubling is correct. """ from pytest import raises from petlib.ec import EcGroup, EcPt G = EcGroup(713) # NIST curve d = G.parameters() a, b, p = d["a"], d["b"], d["p"] g = G.generator() gx0, gy0 = g.get_affine() gx2, gy2 = (2*g).get_affine() from Lab01Code import is_point_on_curve from Lab01Code import point_double x2, y2 = point_double(a, b, p, gx0, gy0) assert is_point_on_curve(a, b, p, x2, y2) assert x2 == gx2 and y2 == gy2 x2, y2 = point_double(a, b, p, None, None) assert is_point_on_curve(a, b, p, x2, y2) assert x2 == None and y2 == None
def test_Pedersen_Shorthand(): # Define an EC group G = EcGroup(713) order = G.order() ## Proof definitions zk = ZKProof(G) zk.g, zk.h = ConstGen, ConstGen zk.x, zk.o = Sec, Sec zk.Cxo = Gen zk.add_proof(zk.Cxo, zk.x*zk.g + zk.o*zk.h) print(zk.render_proof_statement()) # A concrete Pedersen commitment ec_g = G.generator() ec_h = order.random() * ec_g bn_x = order.random() bn_o = order.random() ec_Cxo = bn_x * ec_g + bn_o * ec_h env = ZKEnv(zk) env.g, env.h = ec_g, ec_h env.Cxo = ec_Cxo env.x = bn_x env.o = bn_o sig = zk.build_proof(env.get()) # Execute the verification env = ZKEnv(zk) env.g, env.h = ec_g, ec_h assert zk.verify_proof(env.get(), sig)
def setup(nid=713): """ generates cryptosystem parameters """ G = EcGroup() g = G.generator() hs = [G.hash_to_point(("h%s" % i).encode("utf8")) for i in range(4)] o = G.order() return (G, g, hs, o)
def mix_server_one_hop(private_key, message_list): """ Implements the decoding for a simple one-hop mix. Each message is decoded in turn: - A shared key is derived from the message public key and the mix private_key. - the hmac is checked against all encrypted parts of the message - the address and message are decrypted, decoded and returned """ G = EcGroup() out_queue = [] # Process all messages for msg in message_list: ## Check elements and lengths if not G.check_point(msg.ec_public_key) or \ not len(msg.hmac) == 20 or \ not len(msg.address) == 258 or \ not len(msg.message) == 1002: raise Exception("Malformed input message") ## First get a shared key shared_element = private_key * msg.ec_public_key key_material = sha512(shared_element.export()).digest() # Use different parts of the shared key for different operations hmac_key = key_material[:16] address_key = key_material[16:32] message_key = key_material[32:48] ## Check the HMAC h = Hmac(b"sha512", hmac_key) h.update(msg.address) h.update(msg.message) expected_mac = h.digest() print "my hmac: " + str(msg.hmac) print "ex hmac: " + str(expected_mac[:20]) if not secure_compare(msg.hmac, expected_mac[:20]): raise Exception("HMAC check failure") ## Decrypt the address and the message iv = b"\x00"*16 address_plaintext = aes_ctr_enc_dec(address_key, iv, msg.address) message_plaintext = aes_ctr_enc_dec(message_key, iv, msg.message) # Decode the address and message address_len, address_full = unpack("!H256s", address_plaintext) message_len, message_full = unpack("!H1000s", message_plaintext) output = (address_full[:address_len], message_full[:message_len]) out_queue += [output] return sorted(out_queue)
def __init__(self, curve: int = EC_NID_DEFAULT): """ Constructor for the client of a single set PSI :param curve: NID of the elliptic curve to use. """ self.group = EcGroup(curve)
def credential_setup(): """ Generates the parameters of the algebraic MAC scheme""" G = EcGroup() g = G.hash_to_point(b"g") h = G.hash_to_point(b"h") o = G.order() params = (G, g, h, o) return params
def mix_server_one_hop(private_key, message_list): """ Implements the decoding for a simple one-hop mix. Each message is decoded in turn: - A shared key is derived from the message public key and the mix private_key. - the hmac is checked against all encrypted parts of the message - the address and message are decrypted, decoded and returned """ G = EcGroup() out_queue = [] # Process all messages for msg in message_list: ## Check elements and lengths if not G.check_point(msg.ec_public_key) or \ not len(msg.hmac) == 20 or \ not len(msg.address) == 258 or \ not len(msg.message) == 1002: raise Exception("Malformed input message") ## First get a shared key shared_element = private_key * msg.ec_public_key key_material = sha512(shared_element.export()).digest() # Use different parts of the shared key for different operations hmac_key = key_material[:16] address_key = key_material[16:32] message_key = key_material[32:48] ## Check the HMAC h = Hmac(b"sha512", hmac_key) h.update(msg.address) h.update(msg.message) expected_mac = h.digest()[:20] if not secure_compare(msg.hmac, expected_mac[:20]): raise Exception("HMAC check failure") ## Decrypt the address and the message iv = b"\x00" * 16 # Why are we using an all zero IV?! # iv = urandom(16) address_plaintext = aes_ctr_enc_dec(address_key, iv, msg.address) message_plaintext = aes_ctr_enc_dec(message_key, iv, msg.message) # Decode the address and message address_len, address_full = unpack("!H256s", address_plaintext) message_len, message_full = unpack("!H1000s", message_plaintext) output = (address_full[:address_len], message_full[:message_len]) out_queue += [output] return sorted(out_queue)
class CPSIClient: """ Client for a single set PSI """ def __init__(self, curve: int = EC_NID_DEFAULT): """ Constructor for the client of a single set PSI :param curve: NID of the elliptic curve to use. """ self.group = EcGroup(curve) def query(self, kwds: List[str]) -> Tuple[Bn, List[bytes]]: """ Generate a query from the keywords. :param kwds_ms: Multi set of keywords to be queried. :return: a query """ secret = self.group.order().random() query_enc = list() for kwd in kwds: kwd_pt = self.group.hash_to_point(kwd.encode(ENCODING_DEFAULT)) kwd_enc = secret * kwd_pt kwd_enc_bytes = kwd_enc.export() query_enc.append(kwd_enc_bytes) return (secret, query_enc) def compute_cardinality(self, secret: Bn, reply: List[bytes], published) -> int: """ Compute the cardinalyty of the intersection of sets between the reply to a query and the list of points published by the server. :param reply: reply from the server :param published: list of point published by the server :return: cardinalityof the intersection of sets """ secret_inv = secret.mod_inverse(self.group.order()) kwds = list() for kwd_h in reply: kwd_pt = EcPt.from_binary(kwd_h, self.group) kwd_pt_dec = secret_inv * kwd_pt kwd_bytes = kwd_pt_dec.export() kwds.append(kwd_bytes) # The intersection of the 2 sets is the number of matches. return len(set(kwds) & set(published))
def BL_setup(Gid = 713): G = EcGroup(Gid) q = G.order() g = G.hash_to_point(b"g") h = G.hash_to_point(b"h") z = G.hash_to_point(b"z") hs = [G.hash_to_point(("h%s" % i).encode("utf-8")) for i in range(100)]#what is this return (G, q, g, h, z, hs)
def test_Decrypt(): G = EcGroup() x = G.order().random() y = x * G.generator() import random for _ in range(100): i = random.randint(-1000, 999) E = Ct.enc(y, i) assert E.dec(x) == i
def test_full(self): # Generate parameters (should be same in other parts of program) Gq = EcGroup() p = Gq.order() h = Gq.generator() G = Gq.hash_to_point(b'G') params = (Gq, p, G, h) # Decide on a secret to be distributed m = p.from_binary(b'This is a test') # Set (t,n)-threshold parameters n = 4 t = 3 # Initiate participants, and generate their key-pairs priv_keys = [] pub_keys = [] for i in range(n): (x_i, y_i) = pvss.helper_generate_key_pair(params) priv_keys.append(x_i) pub_keys.append(y_i) # Encrypt secret, create shares and proof (pub, proof) = pvss.gen_proof(params, t, n, m, pub_keys) # Prove generates shares validity print("Test verify") Y_list = pub['Y_list'] C_list = pub['C_list'] assert cpni.DLEQ_verify_list(p, h, pub_keys, C_list, Y_list, proof) is True # Decryption # Calculate what a correct decryption should be expected_decryption = m * G # Let participants decrypt their shares and generate proofs proved_decryptions = [ pvss.participant_decrypt_and_prove(params, x_i, enc_share) for (x_i, enc_share) in zip(priv_keys, pub['Y_list']) ] # Check participants proofs if pvss.batch_verify_correct_decryption( proved_decryptions, pub['Y_list'], pub_keys, p, G) is False: print("Verification of decryption failed") # Use participants decrypted shares to recreate secret S_list = [S_i for (S_i, decrypt_proof) in proved_decryptions] actual_decryption = pvss.decode(S_list[0:-1], [1, 2, 3], p) # Verify secret print("Test decrypt") assert expected_decryption == actual_decryption
def test_CountSketchCt(): G = EcGroup() x = G.order().random() y = x * G.generator() cs = CountSketchCt(50, 7, y) cs.insert(11) c, d = cs.estimate(11) est = c.dec(x) # print(est) assert est == d
def BL_setup(Gid=713): # Parameters of the BL schemes G = EcGroup(713) q = G.order() g = G.hash_to_point(b"g") h = G.hash_to_point(b"h") z = G.hash_to_point(b"z") hs = [G.hash_to_point(("h%s" % i).encode("utf8")) for i in range(100)] return (G, q, g, h, z, hs)
def CountSketchCt_unit_test(): G = EcGroup() x = G.order().random() y = x * G.generator() cs = CountSketchCt(50, 7, y) cs.insert(11) c, d = cs.estimate(11) est = c.dec(x) #assert est == d return est == d
def test_2DH(): G = EcGroup() g = G.generator() o = G.order() priv1 = o.random() priv2 = o.random() priv3 = o.random() k1 = derive_2DH_sender(G, priv1, priv2 * g, priv3 * g) k2 = derive_2DH_receiver(G, priv1 * g, priv2, priv3) assert k1 == k2
def test_3DH(): G = EcGroup() g = G.generator() o = G.order() priv1, pub1 = pair(G) priv2, pub2 = pair(G) priv3, pub3 = pair(G) priv4, pub4 = pair(G) k1 = derive_3DH_sender(G, priv1, priv2, pub3, pub4) k2 = derive_3DH_receiver(G, pub1, pub2, priv3, priv4) assert k1 == k2
def test_Point_addition(): """ Test whether the EC point addition is correct. """ from pytest import raises from petlib.ec import EcGroup, EcPt G = EcGroup(713) # NIST curve d = G.parameters() a, b, p = d["a"], d["b"], d["p"] g = G.generator() gx0, gy0 = g.get_affine() r = G.order().random() gx1, gy1 = (r*g).get_affine() from Lab01Code import is_point_on_curve from Lab01Code import point_add assert is_point_on_curve(a, b, p, gx0, gy0) assert is_point_on_curve(a, b, p, gx1, gy1) ## Test a simple addition h = (r + 1) * g hx1, hy1 = h.get_affine() x, y = point_add(a, b, p, gx0, gy0, gx1, gy1) assert is_point_on_curve(a, b, p, x, y) assert x == hx1 assert y == hy1 ## Ensure commutativity xp, yp = point_add(a, b, p, gx1, gy1, gx0, gy0) assert is_point_on_curve(a, b, p, xp, yp) assert x == xp assert y == yp ## Ensure addition with neutral returns the element xp, yp = point_add(a, b, p, gx1, gy1, None, None) assert is_point_on_curve(a, b, p, xp, yp) assert xp == gx1 assert yp == gy1 xp, yp = point_add(a, b, p, None, None, gx0, gy0) assert is_point_on_curve(a, b, p, xp, yp) assert gx0 == xp assert gy0 == yp ## An error is raised in case the points are equal with raises(Exception) as excinfo: point_add(a, b, p, gx0, gy0, gx0, gy0) assert 'EC Points must not be equal' in str(excinfo.value)
def encode_Alice_message(): """ Encode a single message """ G = EcGroup() g = G.generator() o = G.order() private_key = o.random() public_key = private_key * g m1 = mix_client_one_hop(public_key, b"Alice", b"Dear Alice,\nHello!\nBob") return private_key, m1
def _make_table(start=-10000, end=10000): G = EcGroup() g = G.generator() o = G.order() i_table = {} n_table = {} ix = start * g for i in range(start, end): i_table[ix] = i n_table[(o + i) % o] = ix ix = ix + g return i_table, n_table