Ejemplo n.º 1
0
def decode_claim(owner_vrf_pk, nonce, claim_label, vrf_value, encrypted_claim):
    """Decode claim.

    :param petlib.EcPt owner_vrf_pk: Owner's VRF public key
    :param bytes nonce: Nonce
    :param bytes claim_label: Claim label
    :param bytes vrf_value: Exported VRF value (hash)
    :param bytes encrypted_claim: Claim content
    """
    claim_label = ensure_binary(claim_label)

    pp = PublicParams.get_default()
    cipher = pp.enc_cipher
    salted_label = _salt_label(nonce, claim_label)
    (encrypted_body, tag) = decode(encrypted_claim)

    lookup_key = _compute_claim_key(vrf_value, mode='lookup')
    enc_key = _compute_claim_key(vrf_value, mode='enc')
    raw_body = cipher.quick_gcm_dec(enc_key, b"\x00" * pp.enc_key_size,
                                    encrypted_body, tag)
    (proof, claim_content) = decode(raw_body)

    vrf = VrfContainer(value=vrf_value, proof=proof)
    if not verify_vrf(owner_vrf_pk, vrf, salted_label):
        raise Exception("Wrong VRF value")

    return claim_content
Ejemplo n.º 2
0
    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))
Ejemplo n.º 3
0
    def _handle_client(self, client_reader, client_writer):

        while True:
            try:
                data = yield from client_reader.readuntil(separator=b'done')

                cmd = data[0:4]

                strippedData = data[4:-4]

            except asyncio.streams.IncompleteReadError:
                data = None
            if not data:  # an empty string means the client disconnected
                break

            if cmd == b'mypb':
                self.idp_pub, self.params = decode(strippedData)
                print("Parameters and idp's public key received")

            elif cmd == b'vsig':

                sig, signature = decode(strippedData)

                params = self.params
                idp_pub = self.idp_pub

                #assert the validity of the credential
                m = BL_verify_cred(params, idp_pub, 2, sig, signature)

                if m != False:
                    print('Signature Correct')
                else:
                    print('Signature Incorrect')

            elif cmd == b'page':

                newStuff = decode(strippedData)
                c, responses, gam_g, gam_hs, Age, ID = newStuff

                zet1 = sig[2]

                #assert user's age is correct
                if ZK_verify_age(c, responses, gam_g, gam_hs, Age, ID, params,
                                 zet1) == True:
                    print("Age & User verified")
                    client_writer.write(b'okaydone')
                else:
                    print("Proof failed")
                    client_writer.write(b'faildone')

            # This enables us to have flow control in our connection.
            yield from client_writer.drain()
Ejemplo n.º 4
0
    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)
Ejemplo n.º 5
0
 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)
Ejemplo n.º 6
0
 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"
Ejemplo n.º 7
0
 def decode_binary(self, e, record_size):
     e = decode(e)
     result = ""
     for x in e[:-1]:
         petlib_decode = decode(x)
         binary = "{0:b}".format(petlib_decode)
         pad = "0" * (min(self.size, record_size) - len(binary))
         result += pad + binary
     petlib_decode = decode(e[-1])
     binary = "{0:b}".format(petlib_decode)
     pad = "0" * (record_size - (len(result)+len(binary)))
     result += pad + binary
     l = []
     for x in result:
         l.append(int(x))
     return l
Ejemplo n.º 8
0
    def poll_index(self, pir, requested_index):
        self.client_poller = ClientPoller()
        threads = []
        messages = {}
        for surbid, data in self.surbDict.items():
            threads.append(
                self.client_poller.poll_with((surbid, data['source']), self,
                                             messages))
        for t in threads:
            t.start()
        for t in threads:
            t.join()

        decrypted_msgs = []
        if not pir:
            decrypted_msgs = {}
        try:
            for surbid, _ in self.surbDict.items():
                msg = self.surbDict[surbid]
                log_debug(msg)
                decrypted_msg = decode(
                    self.decrypt(messages[surbid][1], msg['key'][1]))
                if pir:
                    decrypted_msgs.append(decrypted_msg)
                else:
                    decrypted_msgs[messages[surbid][0]] = decrypted_msg
            if pir:
                return self.xor(decrypted_msgs)
            else:
                return decrypted_msgs[requested_index].strip()
        except Exception as e:
            PrintException()
            log_debug('[ERROR] Exception\n{}\n'.format(e))
Ejemplo n.º 9
0
def recv_timeout_petlib_pack(the_socket, timeout=0.15):
    the_socket.setblocking(0)
    total_data=[];
    data='';
    begin=time.time()
    isEmpty =0
    while 1:
        if total_data and time.time()-begin > timeout:
            break
        elif isEmpty > 20:
            break
        try:
            data = the_socket.recv(4096)
            if data:
                total_data.append(data)
                begin = time.time()
            else:
                isEmpty += 1
                time.sleep(0.05)
        except:
            pass
    string = b''.join(total_data)
    if string == b'':
        return ''
    return decode(string)
Ejemplo n.º 10
0
    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)
Ejemplo n.º 11
0
 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)
Ejemplo n.º 12
0
 def test_info_post(self):
     rv = self.app.post('/unlimitID/info')
     raised = False
     try:
         params, ipub = decode(rv.data)
     except:
         raised = True
     assert raised is False
Ejemplo n.º 13
0
 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)
Ejemplo n.º 14
0
def receive_forward(params, mac_key, delta):
    """ Decodes the body of a forward message, and checks its MAC tag."""

    if delta[:params.k] != params.mu(mac_key, delta[params.k:]):
        raise SphinxException("Modified Body")

    delta = unpad_body(delta[params.k:])
    return decode(delta)
Ejemplo n.º 15
0
def decode_claim(owner_vrf_pk, nonce, claim_label, vrf_value, encrypted_claim):
    claim_label = ensure_binary(claim_label)

    pp = PublicParams.get_default()
    cipher = pp.enc_cipher
    salted_label = _salt_label(nonce, claim_label)
    (encrypted_body, tag) = decode(encrypted_claim)

    lookup_key = _compute_claim_key(vrf_value, mode='lookup')
    enc_key = _compute_claim_key(vrf_value, mode='enc')
    raw_body = cipher.quick_gcm_dec(enc_key, b"\x00" * pp.enc_key_size,
                                    encrypted_body, tag)
    (proof, claim_content) = decode(raw_body)

    vrf = VrfContainer(value=vrf_value, proof=proof)
    if not verify_vrf(owner_vrf_pk, vrf, salted_label):
        raise Exception("Wrong VRF Value")

    return claim_content
Ejemplo n.º 16
0
def verify_vrf(pub, vrf, message):
    pp = PublicParams.get_default()

    G = pp.ec_group
    g = G.generator()
    h = G.hash_to_point(b"1||" + message)
    v = EcPt.from_binary(vrf.value, G)
    s, t = decode(vrf.proof)
    R = t * g + s * pub
    Hr = t * h + s * v
    s2 = Bn.from_binary(sha256(encode([g, h, pub, v, R, Hr])).digest())
    return s2 == s
Ejemplo n.º 17
0
 def delete_expired_credentials(self):
     for filename in os.listdir(self.crypto_dir):
         if filename.startswith("cred_"):
             with open(self.crypto_dir + '/' + filename, 'rb') as f:
                 cred = decode(f.read())
                 _, _, _, timeout = cred
                 if datetime.strptime(timeout,
                                      '%Y-%m-%d').date() < date.today():
                     os.unlink(self.crypto_dir + '/' + filename)
                     cred_id = filename.split('_')[1]
                     os.unlink(self.crypto_dir + '/mac_' + cred_id)
     return
Ejemplo n.º 18
0
 def test_credential_post(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)))
     raised = False
     try:
         cred_token = decode(rv.data)
         self.user_cs.issue_verify(cred_token, user_token)
     except:
         raised = True
     assert raised is False
Ejemplo n.º 19
0
def test_pack_unpack_g2(group_pair):
    """
    Testing packing and unpacking G2 element
    """
    group_pair = BilinearGroupPair()
    g2 = group_pair.G2
    order = g2.order()
    pt1 = order.random() * g2.generator()

    data = pack.encode(pt1)
    pt2 = pack.decode(data)

    assert pt1 == pt2
Ejemplo n.º 20
0
 def run(self):
     json_data, destination = self.request_creator.poll_mixnode(
         self.id, self.mixnode)
     response = self.network_sender.send_data_wait(json_data, destination)
     if response:
         response = decode(response)
         id = response['id']
         response = response['response']
         for entry in response:
             msg = entry['delta']
             recoveredMessage = self.client.recoverMessage(
                 msg, entry['myid'])
             self.message_pool[id] = (recoveredMessage[0],
                                      recoveredMessage[1])
Ejemplo n.º 21
0
def decode_capability(owner_dh_pk, nonce, claim_label, encrypted_capability):
    pp = PublicParams.get_default()
    cipher = pp.enc_cipher
    params = LocalParams.get_default()
    shared_secret = params.dh.sk * owner_dh_pk
    enc_key = _compute_capability_key(nonce,
                                      shared_secret,
                                      claim_label,
                                      mode='enc')
    enc_body, tag = decode(encrypted_capability)
    vrf_value = cipher.quick_gcm_dec(enc_key, b"\x00" * pp.enc_key_size,
                                     enc_body, tag)
    claim_lookup_key = _compute_claim_key(vrf_value, mode='lookup')
    return vrf_value, claim_lookup_key
Ejemplo n.º 22
0
 def list_credential_tokens(self):
     creds = []
     for filename in os.listdir(self.crypto_dir):
         if filename.startswith("cred_"):
             cred_id = filename.split('_')[1]
             with open(self.crypto_dir + '/' + filename, 'rb') as f:
                 cred = decode(f.read())
                 _, k, v, t = cred
                 attr = [
                     '{}={}'.format(key, value) for key, value in zip(k, v)
                 ]
                 creds.append(
                     (cred_id, 'Attributes: {}\n Timeout: {}'.format(
                         ', '.join(attr), t)))
     return creds
Ejemplo n.º 23
0
def finish():

    vote_data = decode(session["vote_data"])
    vote_data.sort(key=lambda x: x[6]['voter_id'])
    votes = [v[0] for v in vote_data]
    vote_commits = [v[1] for v in vote_data]
    randoms = [v[2] for v in vote_data]

    receipts = [v[6] for v in vote_data]
    # genvote.verifyChallenge(receipts[0]['challenges'], receipts[0]['vote_commitment'])

    tally = Counter(votes)
    print(tally)

    proofs = genvote.doFiatShamir(votes, vote_commits, randoms, tally)
    big_dict = {
        'G': str(genvote.GROUP_ID),
        'sleeve': genvote.sleeve,
        'g': genvote.EcPtToStr(genvote.g),
        'h': genvote.EcPtToStr(genvote.h),
        'precinct-id': '0',
        'receipts': receipts,
        'tally': tally,
        'proofs': proofs
    }
    json_str = json.dumps(big_dict)

    for candidate in tally:
        print("%s: %d" % (session["rev_d"][candidate], tally[candidate]))
    with open("./verification.json", 'w') as f:
        f.write(json_str)

    verification_file_url = os.popen(
        "curl --upload-file ./verification.json https://transfer.sh/verification.json"
    ).read()

    xmail = GMail('Verified Voting <*****@*****.**>',
                  'qyfsewfeepumeaex')
    msg = Message(
        'New Verification File',
        to=
        'Verified Voting <*****@*****.**>, Soham Sankaran <*****@*****.**>',
        text=verification_file_url)
    xmail.send(msg)

    return render_template("finished.html",
                           verification_file_url=verification_file_url)
Ejemplo n.º 24
0
def test_pack_full():
    G = BpGroup()

    # Key Generation
    private = G.order().random()
    pub = private * G.gen2() # The public key

    # Signature
    message = b"Hello World"
    sig = private * G.hashG1(message)
   
    # Verification
    gt = G.pair(sig, G.gen2())

    struct = [G, pub, sig, gt]
    data = encode( struct )
    assert struct == decode(data)
Ejemplo n.º 25
0
 def poll_recordSize(self, DummyIndex):
     self.client_poller = ClientPoller()
     messages = {}
     threads = []
     for surbid, data in self.surbDict.items():
         threads.append(
             self.client_poller.poll_with((surbid, data['source']), self,
                                          messages))
     for t in threads:
         t.start()
     for t in threads:
         t.join()
     # First one is the record size
     surbid = list(self.surbDict.keys())[0]
     self.surbDict = {}
     record_size = decode(
         self.decrypt(messages[surbid][1], self.private_key[1]))
     return record_size
Ejemplo n.º 26
0
def receive_forward(params, header, mac_key, routing, delta):
    """ Decodes the body of a forward message, and checks its MAC tag."""
    
    _, _, _, dest_key = header
    _, dest = routing

    dest_inner_key = params.derive_key(dest_key, b"dest_inner______")
    body_inner_key = params.derive_key(dest_key, b"body_inner______")

    # TODO: Encure that changing the body destroys the dest_key.

    dest = params.xor_rho(dest_inner_key, dest)
    delta = params.pii(body_inner_key, delta)

    if delta[:params.k] != params.mu(mac_key, delta[params.k:]):
        raise SphinxException("Modified Body")

    delta = unpad_body(delta[params.k:])
    return dest, decode(delta)
Ejemplo n.º 27
0
 def getDBRecordSize(self, portEnum, network_sender):
     session_name = os.urandom(16)
     self.public_key, self.private_key = self.encryptor.keyGenerate(
         session_name)
     db_dest, key = self.create_db_destination(0, portEnum.db.value)
     message = encode(
         self.create_db_message(
             None, {
                 'pir_xor': None,
                 'request_type': RequestType.get_db_size.value,
                 'pk': self.public_key
             }))
     json_msg = self.encryptForDB(message, key, session_name)
     response = network_sender.send_data_wait(json_msg, {
         'ip': db_dest[0],
         'port': db_dest[2]
     })
     response = int(decode(response))
     return response
Ejemplo n.º 28
0
    def dataReceived(self, data):
        # Function called when data received from DB
        # Forward data received to the Server
        print "CP: Receive:", self.transport.getPeer(
        ), self.factory.header  #data,
        self.factory.counter += 1

        name, op, vs, turn, option, turn, tot, content = pack.decode(data)

        if "PUT" in op:
            if turn == 0:
                self.factory.nbpack = int(tot)
            opsend = "END"
            if self.factory.counter != self.factory.nbpack:
                opsend = "ACK"
            self.cdata = [
                self.factory.name, opsend, self.factory.vs, self.factory.turn,
                [self.factory.range1, self.factory.range2],
                self.factory.counter, self.factory.nbpack, ""
            ]

        else:
            if self.factory.counter != self.factory.nbpack:
                if "PUT" in self.factory.header:
                    self.factory.header[4][0] += self.factory.nbrec
                self.cdata = self.factory.header + [
                    self.factory.counter, self.factory.nbpack
                ] + [
                    self.factory.data[self.factory.counter * self.factory.
                                      nbrec:min(len(self.factory.data),
                                                (self.factory.counter + 1) *
                                                self.factory.nbrec)]
                ]

        if "END" not in op:
            print "CP: R sending data"  #, self.cdata
            self.transport.write(pack.encode(self.cdata))
        else:
            self.transport.loseConnection()

        if "ACK" not in op and "END" not in op:
            self.factory.s_proto.dataParser(data)
Ejemplo n.º 29
0
def verify_vrf(pub, vrf, message):
    """Verify a VRF.

    Checks whether a VRF value and a proof correspond to the message.

    :param petlib.EcPt pub: VRF public key
    :param VrfContainer vrf: VRF value and proof
    :param bytes message: Message
    """

    pp = PublicParams.get_default()

    G = pp.ec_group
    g = G.generator()
    h = G.hash_to_point(b"1||" + message)
    v = EcPt.from_binary(vrf.value, G)
    s, t = decode(vrf.proof)
    R = t * g + s * pub
    Hr = t * h + s * v
    s2 = Bn.from_binary(sha256(encode([g, h, pub, v, R, Hr])).digest())
    return s2 == s
Ejemplo n.º 30
0
def decode_capability(owner_dh_pk, nonce, claim_label, encrypted_capability):
    """Decode capability.

    :param petlib.EcPt owner_dh_pk: Owder's VRF public key
    :param bytes nonce: Nonce
    :param bytes claim_label: Corresponding claim label
    :param bytes encrypted_capability: Encrypted capability
    """
    pp = PublicParams.get_default()
    cipher = pp.enc_cipher
    params = LocalParams.get_default()
    shared_secret = params.dh.sk * owner_dh_pk
    enc_key = _compute_capability_key(nonce,
                                      shared_secret,
                                      claim_label,
                                      mode='enc')
    enc_body, tag = decode(encrypted_capability)
    vrf_value = cipher.quick_gcm_dec(enc_key, b"\x00" * pp.enc_key_size,
                                     enc_body, tag)
    claim_lookup_key = _compute_claim_key(vrf_value, mode='lookup')
    return vrf_value, claim_lookup_key
Ejemplo n.º 31
0
    def _handle_client(self, client_reader, client_writer):
        global count
        global paramsReceived
        IOtime = 0
        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)
                IOtime += 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 == b'buys':

                retval = "id"
                client_writer.write("{!r}\n".format(retval).encode("utf-8"))
                start = time.time()

                count +=1
                id = count

                print(id, 'Starting...')

            elif cmd == b'para':

                params = decode(strippedData)

                paramsReceived = True

            elif cmd == b'ipub':

                idp_pub = decode(strippedData)

            elif cmd == b'vsig':

                sig = decode(strippedData)

            elif cmd == b'vsg2':

                signature = decode(strippedData)
                startSigProof = time.time()
                m = BL_verify_cred(params, idp_pub, 2, sig, signature)
                endSigProof = time.time()
                finalSigProof = endSigProof - startSigProof

                if m != False:
                    print('Signature Correct')
                else:
                    print('Signature Incorrect')

            elif cmd == b'page':

                newStuff = decode(strippedData)
                c, responses, gam_g, gam_hs, Age, xran = newStuff
                rrnd, rR, rx = responses
                #print(gam_hs, Age)

                (G, q, g, h, z, hs) = params

                startProof = time.time()

                H = G.hash_to_point(b'service_name')
                ID = xran * H

                zet1 = sig[2]

                zet1p = zet1 - Age * gam_hs[2]

                Waprime = rrnd * gam_g + rR * gam_hs[0] + rx * gam_hs[1] + c * zet1p

                Wxprime = rx * H + c * ID

                stuffToHash = (gam_g, Waprime, Wxprime, 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_prime = Bn.from_binary(chash)

                if c == c_prime:
                    end = time.time()
                    finalTime = end-start
                    timeList.append(finalTime)
                    print(id, "Age & User match, time: ", finalTime, 'Time for proof: ', end - startProof, 'Sig proof: ', finalSigProof, 'IO time: ', IOtime)
                else:
                    print("whops")


            elif cmd == 'Commitment':
                """params = setup()
                G = params[0]
                C = EcPt.from_binary(literal_eval(args[0]), G)"""
            elif cmd == 'Proof':

                """c = Bn.from_hex(literal_eval(args[0]))
                responses1 = pickle.loads(literal_eval(args[1]))
                params = setup()
                responses = []

                for res in responses1:
                    responses.append(Bn.from_hex(res))

                proof = c, responses
                print(verifyCommitments(params, C, proof))"""

            # This enables us to have flow control in our connection.
            yield from client_writer.drain()
Ejemplo n.º 32
0
    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()
Ejemplo n.º 33
0
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)
Ejemplo n.º 34
0
    def datagramReceived(self, data, (host, port)):

        # Deal with information requests
        if data[:4] == "INFO":
            self.do_INFO(data, (host, port))

        # Deal with routing requests
        if data[:4] == "ROUT":
            self.do_ROUT(data, (host, port))


    def do_INFO(self, data, (host, port)):
        print "do INFORMATION"
        hexkey = hexlify(self.ypub.export())
        resp = "RINF %s %s %s" % (self.ip.host, self.port, hexkey)

        # Respond
        self.transport.write(resp, (host, port))


    def do_ROUT(self, data, (host, port)):
        print "do ROUTING"
        msg = decode(data[4:])
        (xfrom, xto), next_msg = mix_operate(msg, (None, self.ypub, self.y), self.setup)



if __name__ == "__main__":
    port = 9999
    reactor.listenUDP(port, Echo(port))
    reactor.run()
Ejemplo n.º 35
0
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()