def __init__(self, crypto_dir): """ __init__ imports the long term required values from files """ self.n = 4 self.crypto_dir = crypto_dir if not os.path.exists(crypto_dir): os.makedirs(crypto_dir) try: with open(self.crypto_dir + '/params', 'rb') as f: self.params = decode(f.read()) except IOError: self.params = cred_setup() with open(self.crypto_dir + '/params', 'wb+') as f: f.write(encode(self.params)) try: with open(self.crypto_dir + '/isec', 'rb') as f: self.isec = decode(f.read()) with open(self.crypto_dir + '/ipub', 'rb') as f: self.ipub = decode(f.read()) except IOError: self.ipub, self.isec = cred_CredKeyge(self.params, self.n) with open(self.crypto_dir + '/isec', 'wb+') as f: f.write(encode(self.isec)) with open(self.crypto_dir + '/ipub', 'wb+') as f: f.write(encode(self.ipub))
def handle_PIR(self, decrypted_msg, client_pk): time_queued = time.perf_counter() - self.t_accepted log_info(">>>>> TIME QUEUED: {}".format(time_queued)) t1 = time.perf_counter() print("TRYING TO FETCH") answer = self.dbnode.fetch_answer(decrypted_msg) print("ANSWER:", answer) reply = encode(answer) encrypted_reply = encode(self.dbnode.encrypt(reply, client_pk)) nymtuple = decrypted_msg['nymtuple'] first_node = decode(nymtuple[0]) header, delta = package_surb(getGlobalSphinxParams(), nymtuple, encrypted_reply) self.dbnode.get_mixnode_list() json_data, dest = RequestCreator().post_msg_to_mix( { 'ip': first_node[1], 'port': self.mixport }, { 'header': header, 'delta': delta }) t2 = time.perf_counter() elapsed_time = (t2 - t1) log_info("TIME ELAPSED: {}".format(elapsed_time)) self.network_sender.send_data(json_data, dest)
def dataReceived(self, data): #Function called when some data is received from the made connection print "SP: Data received", self.transport.getPeer() #, data #Decode and Parse meta data name, op, vs, turn, option, nbpack, nbtot, content = pack.decode( data) # operation, request id, content print "rec:", name, op, vs, turn, nbpack, nbtot #Stop connection if function not triggered by the server itself if nbpack >= nbtot - 1: print "cutting connection", [ self.factory.mix.name, "END", vs, turn, "", nbpack, nbtot, [] ] self.transport.write( pack.encode([ self.factory.mix.name, "END", vs, turn, "", nbpack, nbtot, [] ])) self.transport.loseConnection() else: print "asking for next packet", [ self.factory.mix.name, "ACK", vs, turn, "", nbpack, nbtot, [] ] self.transport.write( pack.encode([ self.factory.mix.name, "ACK", vs, turn, "", nbpack, nbtot, [] ])) if "ACK" not in op and "END" not in op: reactor.callInThread(self.dataParser, data)
def encode_claim(nonce, claim_label, claim_content): """Encode claim. :param bytes nonce: Nonce :param bytes claim_label: Claim label :param bytes claim_content: Claim content """ nonce = ensure_binary(nonce) claim_label = ensure_binary(claim_label) claim_content = ensure_binary(claim_content) pp = PublicParams.get_default() salted_label = _salt_label(nonce, claim_label) vrf = compute_vrf(salted_label) lookup_key = _compute_claim_key(vrf.value, mode='lookup') enc_key = _compute_claim_key(vrf.value, mode='enc') claim = encode([vrf.proof, claim_content]) enc_body, tag = pp.enc_cipher.quick_gcm_enc(enc_key, b"\x00" * pp.enc_key_size, claim) tag = _fix_bytes(tag) enc_claim = encode([enc_body, tag]) return (vrf.value, lookup_key, enc_claim)
def encode_binary(self, l): string_conversion = "".join([str(x) for x in l]) string_conversion = bytearray(string_conversion.encode()) result = [] while string_conversion: temporary_encoder = bytearray(string_conversion[:self.size]) x = int(temporary_encoder, 2) petlib_encode = encode(x) string_conversion = string_conversion[self.size:] result.append(petlib_encode) return encode(result)
def test_credential_post_wrong_user_token(self): self.add_user('test', '*****@*****.**') user_token = self.user_cs.get_encrypted_attribute() rv = self.app.post('unlimitID/credential', data=encode(('*****@*****.**', 'pass', full_scope, user_token))) user_token = cred_secret_issue_user(self.user_cs.params, self.user_cs.keypair, self.user_cs.private_attr) rv = self.app.post('unlimitID/credential', data=encode(('*****@*****.**', 'pass', full_scope, user_token))) print rv assert b"Unknown user token" in rv.data
def __init__(self, crypto_dir, info_url=None, params=None, ipub=None): """ Loads long term values from files. If the server's public values are missing an Exception is raised. If any of the client's public values are missing, they are created. """ self.crypto_dir = crypto_dir if not os.path.exists(crypto_dir): os.makedirs(crypto_dir) self.delete_expired_credentials() if params is not None and ipub is not None: self.params = params self.ipub = ipub else: import requests if info_url is not None: try: r = requests.post(info_url) if r.status_code == 200: self.params, self.ipub = decode(r.content) else: raise Exception("Could not access {}".format(info_url)) except: raise Exception("Could not access {}".format(info_url)) try: with open(self.crypto_dir + '/keypair', 'rb') as f: self.keypair = decode(f.read()) except IOError: self.keypair = cred_UserKeyge(self.params) with open(self.crypto_dir + '/keypair', 'wb+') as f: f.write(encode(self.keypair)) try: with open(self.crypto_dir + '/private_attr', 'rb') as f: self.private_attr = decode(f.read()) except IOError: (_, _, _, o) = self.params self.private_attr = [o.random()] with open(self.crypto_dir + '/private_attr', 'wb+') as f: f.write(encode(self.private_attr)) try: with open(self.crypto_dir + '/user_token', 'rb') as f: self.user_token = decode(f.read()) except IOError: self.user_token = cred_secret_issue_user(self.params, self.keypair, self.private_attr) self.save_user_token(self.user_token)
def setup_machine(): # set serial baud # os.system('stty -F /dev/ttyAMA0 19200') # election information # (consider either reading this from config file, # allowing user to input at setup stage) session["d"] = {'ALICE': 1, 'BETTY': 2, 'CHARLIE': 3} session["rev_d"] = {v: k for k, v in session["d"].items()} session["candidates"] = [ session["d"]['ALICE'], session["d"]['BETTY'], session["d"]['CHARLIE'] ] # for autogenerating challenges # with open('/usr/share/dict/words') as f: # session["dictionary_words"] = list(map(str.strip,f.readlines())) # session["dictionary_words"] = ["hello", "these", "are", "challenge", "words", "which", "should", "later", "be", "replaced", "by", "a", "dictionary"] # from https://github.com/first20hours/google-10000-english # (google-10000-english-usa-no-swears.txt) # with stopwords removed using nltk with open('interface_words.txt', 'r') as iw: words = iw.readlines() # http://stackoverflow.com/questions/3277503/how-do-i-read-a-file-line-by-line-into-a-list words = [w.strip() for w in words] session["dictionary_words"] = words session["lenChallenge"] = 3 # where votes are stored # gradually filled as more users use machine # needs to be encoded because will contain material that will need to be encoded session["vote_data"] = encode([])
def create_forward_message(params, nodelist, keys, dest, msg, assoc=None): """Creates a forward Sphix message, ready to be processed by a first mix. It takes as parameters a node list of mix information, that will be provided to each mix, forming the path of the message; a list of public keys of all intermediate mixes; a destination and a message; and optinally an array of associated data (byte arrays).""" p = params # pki = p.pki nu = len(nodelist) assert len(dest) < 128 and len(dest) > 0 assert p.k + 1 + len(dest) + len(msg) < p.m # Compute the header and the secrets final = Route_pack((Dest_flag, )) header, secrets = create_header(params, nodelist, keys, final, assoc) payload = pad_body(p.m - p.k, encode((dest, msg))) mac = p.mu(p.hpi(secrets[nu - 1]), payload) body = mac + payload # Compute the delta values delta = p.pi(p.hpi(secrets[nu - 1]), body) for i in range(nu - 2, -1, -1): delta = p.pi(p.hpi(secrets[i]), delta) return header, delta
def handleCache(self, backlog_lock): while 1: toRemove = [] with backlog_lock: # print('Cache size: {}'.format(len(self.client_cache))) for entry in self.client_backlog: client_id, socket = entry if client_id in self.client_cache: toRemove.append(entry) start = time.time() operation = '' response = self.client_cache.get(client_id) response = encode({ "id": client_id, "response": response }) socket.sendall(response) self.client_cache.pop(client_id) operation = '[CLIENT_POLL] send' end = time.time() timestamp = datetime.fromtimestamp( end - start).strftime('%M:%S:%f') logger.log_info( '[TIME] MIX LISTENER {} TOOK {}'.format( operation, timestamp)) for entry in toRemove: self.client_backlog.remove(entry) time.sleep(0.05)
def credential(*args, **kwargs): """ A endpoint for users to request credentials """ try: (email, password, keys, user_token) = decode(request.data) (_, enc_secret, _) = user_token except Exception: return "Invalid Data in Request" # Checking the user's email and password if keys == []: return 'Cannot issue credential with no attributes' user = User.query.filter_by(email=email.lower()).first() if user is not None and user.check_password(password): # Checking the users ciphertext if user.check_enc_secret(enc_secret): # Setting values, keys and timeout for the issued credential values = user.get_values_by_keys(keys) timeout_date = date.today() + \ timedelta(days=app.config['CREDENTIAL_LIFETIME']) timeout = timeout_date.isoformat() cred_issued = cs.issue_credential(user_token, keys, values, timeout) return encode((cred_issued, keys, values, timeout)) else: return "Unknown user token" else: return "Invalid email or password"
def prepare_forward_message(mixnodes_dict, message, dest, key, portEnum): params = getGlobalSphinxParams() group = params.group.G use_nodes_forward = rand_subset(mixnodes_dict.keys(), SecurityParameters.NUMBER_OF_MIXES) use_nodes_backward = rand_subset( mixnodes_dict.keys(), SecurityParameters.NUMBER_OF_MIXES) nodes_routing_forward = list(map(Nenc, use_nodes_forward)) nodes_routing_backward = list(map(Nenc, use_nodes_backward)) pks_chosen_nodes_forward = [ EcPt.from_binary(mixnodes_dict[key], group) for key in use_nodes_forward ] pks_chosen_nodes_backward = [ EcPt.from_binary(mixnodes_dict[key], group) for key in use_nodes_backward ] surbid, surbkeytuple, nymtuple = create_surb( params, nodes_routing_backward, pks_chosen_nodes_backward, self.ip) self.surbDict[surbid] = {'surbkeytuple': surbkeytuple} message['nymtuple'] = nymtuple message = encode(message) json_msg = self.encryptForDB(message, key, self.session_name) print(json_msg, len(json_msg)) header, delta = create_forward_message(params, nodes_routing_forward, pks_chosen_nodes_forward, dest, json_msg) return (header, delta, use_nodes_forward[0], surbid, use_nodes_backward[-1])
def test_authorized_post_expired_credential(self): show_proof = self.get_expired_credential('Service_name', 'Service_name', 'test') rv = self.app.post( self.testing_url, data={'show': (StringIO(encode(show_proof)), 'show')}) assert b'Credential expired' in rv.data
def encode_capability(reader_dh_pk, nonce, claim_label, vrf_value): """Encode capability. :param petlib.EcPt reader_dh_pk: Reader's VRF public key :param bytes nonce: Nonce :param bytes claim_label: Corresponding claim label :param bytes vrf_value: Exported VRF value (hash) """ claim_label = ensure_binary(claim_label) pp = PublicParams.get_default() cipher = pp.enc_cipher params = LocalParams.get_default() shared_secret = params.dh.sk * reader_dh_pk lookup_key = _compute_capability_key(nonce, shared_secret, claim_label, mode='lookup') enc_key = _compute_capability_key(nonce, shared_secret, claim_label, mode='enc') enc_body, tag = cipher.quick_gcm_enc(enc_key, b"\x00" * pp.enc_key_size, vrf_value) tag = _fix_bytes(tag) return lookup_key, encode([enc_body, tag])
def compute_vrf(message): pp = PublicParams.get_default() local_params = LocalParams.get_default() G = pp.ec_group g = G.generator() k = local_params.vrf.sk pub = local_params.vrf.pk h = G.hash_to_point(b"1||" + message) v = k * h r = G.order().random() R = r * g Hr = r * h s = Bn.from_binary(sha256(encode([g, h, pub, v, R, Hr])).digest()) t = (r - s * k) % G.order() return VrfContainer(value=v.export(), proof=encode((s, t)))
def test_authorize_post_invalid_service_name(self): show_proof = self.prepare_authorize('Invalid_service', 'Service_name', 'test') rv = self.app.post( self.testing_url, data={'show': (StringIO(encode(show_proof)), 'show')}) assert b'Invalid Service Name' in rv.data
def test_credential_post_no_attr(self): self.add_user('test', '*****@*****.**') user_token = self.user_cs.get_encrypted_attribute() rv = self.app.post('unlimitID/credential', data=encode( ('*****@*****.**', 'pass', [], user_token))) assert b'Cannot issue credential with no attributes' in rv.data
def test_credential_post_invalid_email(self): self.add_user('test', '*****@*****.**') user_token = self.user_cs.get_encrypted_attribute() rv = self.app.post('/unlimitID/credential', data=encode(('*****@*****.**', 'pass', full_scope, user_token))) assert b'Invalid email or password' in rv.data
def get_credential(): """ The page for the user to obtain credentials. The encrypted private attribute is given to the server along with the public attributes """ all_keys = [ 'name', 'given_name', 'family_name', 'email', 'gender', 'zoneinfo', 'birthdate' ] form = CredentialForm(request.form) form.keys.choices = zip(all_keys, all_keys) if request.method == 'POST' and form.validate(): email = form.email.data password = form.password.data keys = form.keys.data if keys == []: form.keys.errors.append( 'A credential needs to contain at least 1 key') return render_template('credential.html', form=form) try: user_token = cs.get_user_token() r = requests.post(credential_url, data=encode( (email, password, keys, user_token))) cred_token = decode(r.content) except Exception: flash('Could not get credential') return redirect(url_for('home')) cs.issue_verify(cred_token, user_token) flash('Got a credential for you') return redirect(url_for('home')) return render_template('credential.html', form=form)
def test_authorized_post_happy_path(self): show_proof = self.prepare_authorize('Service_name', 'Service_name', 'test') rv = self.app.post( self.testing_url, data={'show': (StringIO(encode(show_proof)), 'show')}, follow_redirects=False) assert rv.status_code == 302 assert b'http://localhost:8000/oauth/authorize?code=' in rv.headers[ 'Location'] import urlparse parsed = urlparse.urlparse(rv.headers['Location']) [code] = urlparse.parse_qs(parsed.query)['code'] rv = self.app.get( '/oauth/token', data=dict(grant_type='authorization_code', code=code, client_secret='pass', client_id='test', redirect_uri='http://localhost:8000/oauth/authorize')) # String to dict import ast token = ast.literal_eval(rv.data) rv = self.app.get( '/api/userinfo', headers={'Authorization': 'Bearer ' + token['access_token']}) assert 'pseudonym' in rv.data assert 'name' in rv.data assert 'birthdate' in rv.data assert 'zoneinfo' in rv.data assert 'gender' in rv.data rv = self.app.get( '/api/client', headers={'Authorization': 'Bearer ' + token['access_token']}) assert 'client' in rv.data
def connectionMade(self): print "--- CP: Connection made", self.factory.data, self.transport.getPeer( ) self.factory.c_protos.append(self) self.cdata = self.factory.data self.transport.write(pack.encode(self.factory.data)) print "--- CP: Connection done", self.factory.data, self.transport.getPeer( )
def encode_claim(nonce, claim_label, claim_content): claim_label = ensure_binary(claim_label) claim_content = ensure_binary(claim_content) pp = PublicParams.get_default() salted_label = _salt_label(nonce, claim_label) vrf = compute_vrf(salted_label) lookup_key = _compute_claim_key(vrf.value, mode='lookup') enc_key = _compute_claim_key(vrf.value, mode='enc') claim = encode([vrf.proof, claim_content]) enc_body, tag = pp.enc_cipher.quick_gcm_enc(enc_key, b"\x00" * pp.enc_key_size, claim) enc_claim = encode([enc_body, tag]) return (vrf.value, lookup_key, enc_claim)
def produce_step_output(self): commitments = [] for (md_index, md) in enumerate(self.md_list): commitment = mpcMD(md.gk, md.alpha, md.beta, self.elem_state[md_index]) commitments.append(commitment) self.elem_state[md_index] = commitment[0] return pack.encode(commitments)
def add_user_and_get_credential(self): self.add_user('test', '*****@*****.**') user_token = self.user_cs.get_encrypted_attribute() rv = self.app.post('unlimitID/credential', data=encode(('*****@*****.**', 'pass', full_scope, user_token))) cred_token = decode(rv.data) self.user_cs.issue_verify(cred_token, user_token)
def pet2ascii(p): """ >>> from petlib.ec import EcGroup, EcPt >>> G = EcGroup() >>> pt = EcPt(G) >>> pet2ascii(pt) '3Xw3vNAdCmDLs' """ return ensure_text(b58encode(encode(p)))
def check_enc_secret(self, enc_secret): _enc_secret = hexlify(encode(enc_secret)) if self._enc_secret is None: self._enc_secret = _enc_secret db.session.commit() return True elif self._enc_secret == _enc_secret: return True else: return False
def test_authorize_post_invalid_timeout(self): show_proof = self.prepare_authorize('Service_name', 'Service_name', 'test') creds, sig_o, sig_openID, service_name, uid, keys, values, timeout = show_proof dummy_timeout = date.today().isoformat() dummy_show_proof = creds, sig_o, sig_openID, service_name, uid, keys, values, dummy_timeout rv = self.app.post( self.testing_url, data={'show': (StringIO(encode(dummy_show_proof)), 'show')}) assert b'Credential verification failed' in rv.data
def post_msg_to_mix(self, destination, data): request = { 'type': RequestType.push_to_mix.value, 'payload': encode(data) } data_string = pickle.dumps(request) serialized_destination = { 'ip': destination['ip'], 'port': int(destination['port']) } return (data_string, serialized_destination)
def test_authorize_post_invalid_uid(self): (_, _, _, o) = self.IdP_cs.params show_proof = self.prepare_authorize('Service_name', 'Service_name', 'test') creds, sig_o, sig_openID, Service_name, uid, keys, values, timeout = show_proof dummy_uid = o.random() dummy_show_proof = creds, sig_o, sig_openID, Service_name, dummy_uid, keys, values, timeout rv = self.app.post( self.testing_url, data={'show': (StringIO(encode(dummy_show_proof)), 'show')}) assert b'EC+exception' in rv.data
def __init__(self, ip, port, n, m): #, arch, enc, el1, el2, el3, el4, ports): print("CF: init") self.done = Deferred() self.c_proto = None self.name = "C" self.ip = ip # ['34.251.168.214','34.249.66.110','34.250.248.33'] self.port = port #[8001,8002,8003] self.n = n self.m = m 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))) nn = int(math.ceil(self.n / self.m) * self.m) #self.data = pack.encode([self.name, "STT", 9842, -1, "", 0, 1, [1, 1, [[ Actor("DB", "127.0.0.1", 8000, ""), int(nn/self.m)], ["", Bn.from_binary(base64.b64decode("z7yGAen5eAgHBRB9nrafE6h9V0kW/VO2zC7cPQ=="))*self.g], nn, 1, [Actor("M1", "127.0.0.1",8001, ""), Actor("M2", "127.0.0.1",8002, ""), Actor("M3", "127.0.0.1", 8003, "")]]]]) # cascade layered self.data = pack.encode([ self.name, "STT", 1342, -1, "", 0, 1, [ 1, 0, [[Actor("DB", "127.0.0.1", 8000, ""), int(nn / self.m)], [ Bn.from_binary( base64.b64decode( "z7yGAen5eAgHBRB9nrafE6h9V0kW/VO2zC7cPQ==")) * self.g, Bn.from_binary( base64.b64decode( "z7yGAen5eAgHBRB9nrafE6h9V0kW/VO2zC7cPQ==")) * self.g ], nn, 1, [ Actor("M1", "127.0.0.1", 8001, ""), Actor("M2", "127.0.0.1", 8002, ""), Actor("M3", "127.0.0.1", 8003, "") ]] ] ]) #cascade rebuild #rounds= int(math.ceil(m *math.log(math.sqrt(nn)) /2)) #self.data = pack.encode([self.name, "STT", 98621, -1, "", 0, 1, [0, 1, [[ Actor("DB", "127.0.0.1", 8000, ""), int(nn/self.m)], ["", Bn.from_binary(base64.b64decode("z7yGAen5eAgHBRB9nrafE6h9V0kW/VO2zC7cPQ=="))*self.g], ["", Bn.from_binary(base64.b64decode("266YjC8rEyiEpqXCNXCz1qXTEnwAsqz/tCyzcA=="))*self.g], nn, rounds, [Actor("M1", "127.0.0.1",8001, ""), Actor("M2", "127.0.0.1",8002, ""), Actor("M3", "127.0.0.1", 8003, "")]]]]) #parallel layered #rounds= int(math.ceil(4 * m *(math.log(nn)+1))) #self.data = pack.encode([self.name, "STT", 91864, -1,"", 0, 1, [0,0,[[ Actor("DB", "localhost", 8000, ""), int(nn/self.m)], [Bn.from_binary(base64.b64decode("z7yGAen5eAgHBRB9nrafE6h9V0kW/VO2zC7cPQ=="))*self.g, Bn.from_binary(base64.b64decode("z7yGAen5eAgHBRB9nrafE6h9V0kW/VO2zC7cPQ=="))*self.g], [Bn.from_binary(base64.b64decode("266YjC8rEyiEpqXCNXCz1qXTEnwAsqz/tCyzcA=="))*self.g, Bn.from_binary(base64.b64decode("266YjC8rEyiEpqXCNXCz1qXTEnwAsqz/tCyzcA=="))*self.g], nn, rounds, [Actor("M1", "localhost",8001, ""), Actor("M2", "localhost",8002, ""), Actor("M3", "localhost", 8003, "")]]]]) #parallel rebuild '34.251.168.214','34.249.55.110','34.250.248.33' print(nn / self.m, self.m, nn, int(math.ceil(2 * self.m * math.log(nn))), math.log(nn))
def _handle_client(self, client_reader, client_writer): global paramsReceived while True: try: # data = (yield from client_reader.readline()).decode("utf-8") startWait = time.time() data = yield from client_reader.readuntil(separator=b'fireintheboof') endWait = time.time() print('IO wait: ', data[0:4], endWait - startWait) cmd = data[0:4] strippedData = data[4:-13] except asyncio.streams.IncompleteReadError: data = None if not data: # an empty string means the client disconnected break # cmd, *args = str(data).rstrip().split(' ') if cmd == 'id': """secrets = [3, 645, 3430, 420] seriSecrets = pickle.dumps(secrets) params = setup() C, r = commit(params, secrets) G = params[0] exportedC = C.export() retval = 'IDCONFIRMED' #client_writer.write("{!r}\n".format(retval).encode("utf-8")) #Interesting asyncio thingy here, if I send the data to the client first, the proof is never correct #THe client completes and sends the proof to the service provider before the SP receives the C from here.""" print(literal_eval(args[0])) print(type(literal_eval(args[0]))) reader_sp, writer_sp = yield from asyncio.streams.open_connection("localhost", 12345, loop = loop) params = BL_setup() LT_idp_state, idp_pub = BL_idp_keys(params) #conv_user_commit = bytes(args[0], "utf8") #user_commit = encdec.decode(conv_user_commit) user_commit = encdec.decode(literal_eval(args[0])) msg_to_user = BL_idp_prep(LT_idp_state, user_commit) elif cmd == b'para': #reader_sp, writer_sp = yield from asyncio.streams.open_connection("localhost", 12345, loop=loop) start = time.time() paramsReceived = True print('Starting...') params = decode(strippedData) G, q, g, h, z, hs = params LT_idp_state, idp_pub = BL_idp_keys(params) #send public key to user and service provider #writer_sp.write(b'ipub' + encode(idp_pub) + b'fireintheboof') client_writer.write(b'mypb' + encode(idp_pub) + b'fireinthepub') elif cmd == b'ucmt': user_commit, C, c, responses, L2, Age = decode(strippedData) rR, rx = responses H = G.hash_to_point(b'service_name') ID = L2 * H Cprime = C - Age * hs[2] Wprime = rR * hs[0] + rx * hs[1] + c * Cprime Wxprime = rx * H + c * ID stuffToHash = (Wprime, Wxprime, C, g, h, z, hs[0], hs[1], hs[2], hs[3], H) cstr = b",".join([hexlify(x.export()) for x in stuffToHash]) chash = sha256(cstr).digest() cprime = Bn.from_binary(chash) if c == cprime: print("success") else: print("no") #generate message to user msg_to_user = BL_idp_prep(LT_idp_state, user_commit) client_writer.write(encode(msg_to_user) + b'fireintheboof') elif cmd == b'prep': msg_to_user2 = BL_idp_validation(LT_idp_state) client_writer.write(encode(msg_to_user2) + b'fireintheboof') elif cmd == b'msgi': msg_to_idp = decode(strippedData) # generate 3rd message to user msg_to_user3 = BL_idp_validation_2(LT_idp_state, msg_to_idp) client_writer.write(encode(msg_to_user3) + b'fireintheboof') end = time.time() finalTime = end - start print('Total time taken: ', finalTime) else: #print("Bad command {!r}".format(data), file=sys.stderr) pass # This enables us to have flow control in our connection. yield from client_writer.drain()
def client(): reader, writer = yield from asyncio.streams.open_connection( '127.0.0.1', 12345, loop=loop)#Service Provider reader2, writer2 = yield from asyncio.streams.open_connection( '127.0.0.1', 7878, loop=loop)#Identity Provider def send(msg, writer): print("> " + str(msg)) writer.write((msg + '\n').encode("utf-8")) print(msg) print(type(msg.encode("utf8"))) def sendBin(data, writer): #print("bin>" + str(data)) writer.write(data + b'fireintheboof') #writer.write_eof() def recv(reader): msgback = (yield from reader.readline()).decode("utf-8").rstrip() #print("< " + msgback) return msgback # send a line #send("buy", writer) sendBin(b'buys', writer) msg = yield from recv(reader) #if repr('id') == msg: if True: startWait = time.time() print("ok i go get ID") #generating, encoding, and sending parameters to both sp and idp params = BL_setup() G, q, g, h, z, hs = params endWait = time.time() sendBin(b'para' + encode(params), writer) sendBin(b'para' + encode(params), writer2) print('Time to generate params: ', endWait-startWait) seri_enc_idp_pub = yield from reader2.readuntil(separator=b'fireinthepub') if seri_enc_idp_pub[0:4] == b'mypb': #idp_pub = tuple(list_enc_idp_pub) idp_pub = decode(seri_enc_idp_pub[4:-12]) sendBin(b'ipub' + encode(idp_pub) + b'fireintheboof', writer) #h = Hmac(b'sha256', b'ServiceProviderID') L2 = q.random() Age = 21 #new #N = params[0].hash_to_point('service_name') #pseudonym = x * N #encode and send user_commit to idp LT_user_state, user_commit = BL_user_setup(params, [L2, Age]) startTimeProof = time.time() C = LT_user_state.C R = LT_user_state.R q = LT_user_state.params[1] H = params[0].hash_to_point(b'service_name') ID = L2 * H wR_id = q.random() wx_id = q.random() Wit = wR_id * hs[0] + wx_id * hs[1] WID_id = wx_id * H print(hs) stuffToHash = (Wit, WID_id, C, g, h, z, hs[0], hs[1], hs[2], hs[3], H) cstr = b",".join([hexlify(x.export()) for x in stuffToHash]) chash = sha256(cstr).digest() c = Bn.from_binary(chash) rR_id = wR_id - c * R rx_id = wx_id - c * L2 endTimeProof = time.time() print('Proof took: ', endTimeProof - startTimeProof) responses = (rR_id, rx_id) values = (user_commit, C, c, responses, L2, Age) sendBin(b'ucmt' + encode(values), writer2) msg2 = yield from reader2.readuntil(separator=b'fireintheboof') msg_to_user = decode(msg2[:-13]) BL_user_prep(LT_user_state, msg_to_user) #request idp's pubkey #sendBin(b'pubk', writer2) #inform idp Im prepped and ready to go sendBin(b'prep', writer2) msg3 = yield from reader2.readuntil(separator=b'fireintheboof') msg_to_user2 = decode(msg3[:-13]) #generate msg to idp msg_to_idp = BL_user_validation(LT_user_state, idp_pub, msg_to_user2) #encode, serialise, and send msg to idp sendBin(b'msgi' + encode(msg_to_idp), writer2) #receive last message from idp, generate signature msg4 = yield from reader2.readuntil(separator=b'fireintheboof') msg_to_user3 = decode(msg4[:-13]) sig = BL_user_validation_2(LT_user_state, msg_to_user3) sendBin(b'vsig' + encode(sig) + b'fireintheboof', writer) print('idppub: ', idp_pub) signature_gamhs = BL_user_prove_cred(LT_user_state) signature = signature_gamhs[0] gam_hs = signature_gamhs[1] gam_g = signature_gamhs[2] sendBin(b'vsg2' + encode(signature) + b'fireintheboof', writer) zet1p = LT_user_state.zet1 - Age * gam_hs[2] newStuff = (gam_hs, Age) #prove age #get variabels rnd = LT_user_state.rnd R = LT_user_state.R q = LT_user_state.params[1] wrnd = q.random() wR = q.random() wx = q.random() Wzet1p = wrnd * gam_g + wR * gam_hs[0] + wx * gam_hs[1] #remember to get gam_g WID = wx * params[0].hash_to_point(b'service_name') stuffToHash = (gam_g, Wzet1p, WID, zet1p, gam_hs[0], gam_hs[1], gam_hs[2], H) cstr = b",".join([hexlify(x.export()) for x in stuffToHash]) chash = sha256(cstr).digest() c = Bn.from_binary(chash) rrnd = wrnd - c*rnd rR = wR - c*R rx = wx - c*L2 responses = (rrnd, rR, rx) newStuff = (c, responses, gam_g, gam_hs, Age, L2) """Wprime = rrnd * gam_g + rR * gam_hs[0] + rx * gam_hs[1] + c * zet1p print(Wzet1p) print(Wprime)""" sendBin(b'page' + encode(newStuff) + b'fireintheboof', writer) #Close the connections to get rid of IncompleteReadError cmd = "asd" #cmd, *args = msg2.rstrip().split(' ') if repr('IDCONFIRMED') == cmd: #for encryption """key = keyGen() print(repr(key)) ciphertext = encrypt_AES(key, "HAUHEUheuahehaeuhUAEHUHEAUh") serialisedCiphertext = pickle.dumps(ciphertext) send(('key ' + repr(key)) + " " + repr(serialisedCiphertext), writer)""" """params = setup() G = params[0] C = EcPt.from_binary(literal_eval(args[0]), G) r = Bn.from_binary(literal_eval(args[1])) secrets = pickle.loads(literal_eval(args[2])) proof = proveCommitment(params, C, r, secrets) c, responses = proof #Here is where I send the proof to the service provider seriRes = pickle.dumps(responses) send('Proof ' + repr(c) + " " + repr(seriRes), writer) print("the end")""" end = time.time() print("Time: ", end-start) writer.close() writer2.close()
def put(self, obj): """ Write an object to the channel. """ self.writer.write(encode(obj))
def test_openID_blind(): ## Setup from credential issuer. params = cred_setup() (G, g, h, o) = params data = encode(params) params = decode(data) ## Derive a fresh, long term secret for user LT_user_ID = o.random() timeout = 100 ## Attriutes we want to encode public_attr = [ timeout ] private_attr = [ LT_user_ID ] n = len(public_attr) + len(private_attr) ipub, isec = cred_CredKeyge(params, n) ## User generates keys and encrypts some secret attributes # the secret attributes are [10, 20] keypair = cred_UserKeyge(params) keypair = decode(encode(keypair)) user_token = cred_secret_issue_user(params, keypair, private_attr) pub, EGenc, sig_u = decode(encode(user_token)) ## The issuer checks the secret attributes and encrypts a amac # It also includes some public attributes, namely [30, 40]. assert cred_secret_issue_user_check(params, pub, EGenc, sig_u) cred_issued = cred_secret_issue(params, pub, EGenc, ipub, isec, public_attr) u, EncE, sig_s = decode(encode(cred_issued)) ## The user decrypts the amac mac = cred_secret_issue_user_decrypt(params, keypair, u, EncE, ipub, public_attr, EGenc, sig_s) mac = decode(encode(mac)) ## User Shows back full credential to issuer (creds, sig_o, zis) = cred_show(params, ipub, mac, sig_s, public_attr + private_attr, export_zi=True) ## The credential contains a number of commitments to the attributes (u, Cmis, Cup) = creds assert len(Cmis) == 2 assert Cmis[0] == timeout * u + zis[0] * h assert Cmis[1] == LT_user_ID * u + zis[1] * h # Derive a service specific User ID Gid = G.hash_to_point(b"ServiceNameRP") Uid = LT_user_ID * Gid # Define the statements to be proved zk = define_proof(G) # Define the proof environemnt env = ZKEnv(zk) env.u, env.h = u, h env.Cm0p, env.Cm1 = Cmis[0] - (timeout * u), Cmis[1] env.Uid, env.Gid = Uid, Gid env.LT_ID = LT_user_ID env.z0, env.z1 = zis[0], zis[1] sig_openID = zk.build_proof(env.get()) creds, sig_o, sig_openID = decode(encode( (creds, sig_o, sig_openID) )) ## Issuer / IdP checks the credential is valid assert cred_show_check(params, ipub, isec, creds, sig_o) # Execute the verification on the proof 'sig' env2 = ZKEnv(zk) env2.u, env2.h = u, h env2.Cm0p, env2.Cm1 = Cmis[0] - (timeout * u), Cmis[1] env2.Uid, env2.Gid = Uid, Gid assert zk.verify_proof(env2.get(), sig_openID)