コード例 #1
0
    def send(self, filename, receiver='Bob'):
        with CQCConnection(self.name) as self.cqc:
            self.cqc.closeClassicalServer()
            self.receiver = receiver
            self.receiver_pkey = auth.get_public_key(receiver)

            f = open(filename, 'rb')
            message = f.read()
            f.close()

            self.n = len(message) * 8
            self.N = math.ceil((4 + self.correctness_param) * self.n) + 25
            communication.send_message(
                self.cqc, self.receiver, self.skey,
                json.dumps({
                    'n': self.n,
                    'security_param': self.security_param,
                    'correctness_param': self.correctness_param,
                    'filename': filename
                }))
            self._send_qubits()
            self._perform_basis_sift()
            can_continue = self._perform_error_estimation()
            if not can_continue:
                print('Not enough min entropy :(')
                return
            self._perform_error_correction()
            self._perform_privacy_amplification()
            cyphertext = self._encrypt(message)
            communication.send_binary_list(self.cqc, self.receiver, self.skey,
                                           cyphertext)
コード例 #2
0
    def _perform_error_estimation(self):
        print('Performing error estimation...', end='\r')
        error_estimation_indices = []
        key_part = []
        for i in range(0, self.n):
            r = random.randint(0, len(self.sifted_key) - 1)
            while r in error_estimation_indices:
                r = random.randint(0, len(self.sifted_key) - 1)
            error_estimation_indices.append(r)
            key_part.append(self.sifted_key[r])

        communication.send_message(self.cqc, self.receiver, self.skey,
                                   error_estimation_indices)
        communication.send_binary_list(self.cqc, self.receiver, self.skey,
                                       key_part)
        receiver_key_part = communication.receive_binary_list(
            self.cqc, self.receiver_pkey)

        num_errors = 0.0
        for i in range(0, len(key_part)):
            if receiver_key_part[i] != key_part[i]:
                num_errors += 1.0

        self.error_estimation = num_errors / len(key_part)
        print('Performing error estimation... Done!')
        print('Error rate = {}'.format(self.error_estimation))

        error_estimation_indices.sort()
        self.sifted_key = utils.remove_indices(self.sifted_key,
                                               error_estimation_indices)
        remaining_bits = len(self.sifted_key)
        min_entropy = remaining_bits * (1 - utils.h(self.error_estimation))
        max_key = min_entropy - 2 * utils.log(1 / self.security_param, 2) - 1

        return self.n <= max_key
コード例 #3
0
    def handle_DISCONNECT_REQUEST(self, client_socket, disconnect_request):
        logging.debug("Handling disconnect request")
        source_ip = client_socket.getpeername()[0]
        source_port = disconnect_request.port
        if not disconnect_request.check_for_unreplicated_files:
            response = messages.DisconnectResponse(False)
            
        else:            
            unreplicated = self.db.has_unreplicated_files(source_ip, source_port)
            logging.debug("Unreplicated files: " + str(unreplicated))
            response = messages.DisconnectResponse(unreplicated)

        communication.send_message(response, socket=client_socket)

        if (not disconnect_request.check_for_unreplicated_files or
                (not unreplicated and disconnect_request.check_for_unreplicated_files)):
                                
            # update db
            self.db.update_peer_state(source_ip, source_port, PeerState.OFFLINE)
            # broadcast
            peers_list = self.db.get_peers()
            logging.debug("Broadcasting message ")
            for p in peers_list:            
                if p.hostname == self.hostname and p.port == self.port:
                    continue
                if p.state != PeerState.ONLINE:
                    continue
                logging.debug("Broadcasting to peer %s, %d", p.hostname, p.port)
                communication.send_message(disconnect_request, p)
コード例 #4
0
    def handle_CONNECT_REQUEST(self, client_socket, msg):        
        response = messages.ConnectResponse(successful=False)
        
        if msg.pwd == LocalPeer.PASSWORD:
            logging.debug("Connection request - password OK")
            response.successful = True

            peer_endpoint = client_socket.getpeername()
            logging.debug("Peer address: %s %d", str(peer_endpoint[0]), msg.port) 
            self.db.add_or_update_peer(peer_endpoint[0], msg.port, peer.PeerState.ONLINE, 
                                        msg.maxFileSize, msg.maxFileSysSize, msg.currFileSysSize)
            
        else:
            logging.debug("Connection Request - wrong password")        

        communication.send_message(response, socket=client_socket)

        if response.successful:
            # broadcast
            peers_list = self.db.get_peers()
            logging.debug("Broadcasting message ")
            for p in peers_list:            
                if p.hostname == self.hostname and p.port == self.port:
                    continue
                if p.state != PeerState.ONLINE:
                    continue
                logging.debug("Broadcasting to peer %s, %d", p.hostname, p.port)
                communication.send_message(msg, p)
コード例 #5
0
def main():

    n = parse_arguments()
    basis_string = ''
    bitstring = ''

    # Initialize the connection
    with CQCConnection("Bob") as Bob:

        for i in range(0, n):

            # Receive qubit from Alice (via Eve)
            q = Bob.recvQubit()

            # Choose a random basis
            chosen_basis = random.randint(0, 1)
            basis_string += str(chosen_basis)
            if chosen_basis == 1:
                q.H()

            # Retrieve key bit
            k = q.measure()
            bitstring += str(k)
            send_message(Bob, 'Alice', 'ok'.encode('UTF-8'))

            # Receive classical encoded message from Alice
            # enc = Bob.recvClassical()[0]
            # Calculate message
            # m = (enc + k) % 2

        print("\nBob basis={}".format(basis_string))
        print("Bob retrieved the key k={} from Alice.".format(bitstring))
コード例 #6
0
ファイル: receiver.py プロジェクト: mehmetmertbese/peqi-ot
 def get_chosen_bit(self, sender, good_set_parity):
     send_message(self.cqc, sender, [self.good_index == self.decision_bit])
     parities = receive_message(self.cqc, sender)
     retrieved_bit = (
         good_set_parity + parities[self.good_index]
     ) % 2  # choose from x0+b0, x1+b1 or x0+b1, x1+b0 the one that contains the good set
     return retrieved_bit
コード例 #7
0
    def handle_NEW_FILE_AVAILABLE(self, client_socket, new_file_available_msg):
        logging.debug("Handling new file available message")
        f = new_file_available_msg.file_model
        source_ip = client_socket.getpeername()[0]
        source_port = new_file_available_msg.port
                
        self.db.add_or_update_file(f)
        self.db.add_file_peer_entry(f, source_ip, source_port)

        if source_ip == self.hostname and source_port == self.port:
            return        
        
        # for now, to find peers where the file should be replicated, 
        # just select peers that are able to replicate the file and 
        # that have the smallest fs size. limit the # by replication level
        
        peers_list = self.db.get_peers_to_replicate_file(f, source_ip, source_port, 
                                                         Tracker.REPLICATION_LEVEL)

        # broadcast
        logging.debug("Broadcasting message ")
        for p in peers_list:
            print p.port
            if p.hostname == self.hostname and p.port == self.port:
                self._download_file(f.path, peer_list=peers_list)
                continue
            logging.debug("Broadcasting to peer %s %d", p.hostname, p.port)
            communication.send_message(new_file_available_msg, p)
コード例 #8
0
def main():

    # Initialize the connection
    with CQCConnection("Alice") as Alice:
        Alice.closeClassicalServer()

        # Generate a key
        k = random.randint(0, 1)
        chosen_basis = random.randint(0, 1)

        # Create a qubit
        q = qubit(Alice)

        # Encode the key in the qubit
        if k == 1:
            q.X()

        # Encode in H basis if basis = 1
        if chosen_basis == 1:
            q.H()

        # Send qubit to Bob (via Eve)
        Alice.sendQubit(q, "Eve")

        # Encode and send a classical message m to Bob
        m = 1
        enc = (m + k) % 2
        send_message(Alice, "Bob", bytes([enc]))

        print("\nAlice basis={}".format(BASIS[chosen_basis]))
        print("Alice key={}".format(k))
        print("Alice sent the message m={} to Bob".format(m))
コード例 #9
0
def interactive():
    if "payload" in request.form:
        payload = json.loads(request.form["payload"]
                             )  # Obtain payload in JSON - the dialogue content
        values = payload["view"]["state"][
            "values"]  # Navigate to the JSON and select the values

        marketingid = values["block_id1"]["a-id"]["value"]
        channel_id = values["block_channel_id"]["channel_action"][
            "selected_option"][
                "value"]  # Reading the channel_id from Payload store it as a string
        date_from = values["block_id2"]["action_id2"][
            "selected_date"]  # Reading the date from from Payload store it as a string
        date_to = values["block_id3"]["action_id3"]["selected_date"]
        country = values["block_id4"]["action_id4"]["selected_option"]["value"]
        markchan = values["block_checkboxes"]["checkboxes_ation"][
            "selected_options"]

        # Lines 39 - 44 are obtaining a list of values from a list of dictionaries
        values = list()
        for i in markchan:
            val = {key: i[key] for key in i.keys() & {'value'}}
            val = list(val.values())
            val = val[0]
            values.append(val)

        uno = prepare_csv(date_from, date_to, country, values, marketingid)
        send_message(client, channel_id,
                     date_from)  #From the communications.py
        send_csv_file(client, channel_id, uno)  #From the communications.py

    return make_response("", 200)
コード例 #10
0
    def handle_FILE_CHANGED(self, client_socket, file_changed_msg):
        logging.debug("Handling file change")
        remote_file = file_changed_msg.file_model

        source_ip = client_socket.getpeername()[0]
        source_port = file_changed_msg.port

        db_file = self.db.get_file(remote_file.path)
        # if checksums match, that means the file wasn't actually updated
        # but the peer just downloaded it.
        if (db_file.checksum == remote_file.checksum and
            db_file.latest_version == remote_file.latest_version):
            
            logging.debug("A peer now has file " + remote_file.path)
            self.db.add_file_peer_entry(remote_file, source_ip, source_port)
        elif source_ip != self.hostname or source_port != self.port:
            # this is a file change. notify all peers that have the file
            logging.debug("Peer's file (%s) was changed. Going to notify peers", 
                          remote_file.path)
            peers_list = self.db.get_peers(remote_file.path)
            # broadcast
            logging.debug("Broadcasting message ")
            print str(peers_list)
            for p in peers_list:                            
                if p.hostname == self.hostname and p.port == self.port:
                    super(Tracker, self).handle_FILE_CHANGED(client_socket, file_changed_msg)
                    continue
                if p.hostname == source_ip and p.port == source_port:
                    continue
                if p.state != PeerState.ONLINE:
                    continue
                
                
                logging.debug("Broadcasting to peer %s %s", p.hostname, p.port)
                communication.send_message(file_changed_msg, p)
コード例 #11
0
def dieta_bambam(message, chat_id, com):
    global LAST_DIETA_BAMBAM_CALL
    if 'from' in message and 'first_name' in message[
            'from'] and 'guilherme' == message['from']['first_name'].lower():
        now = datetime.datetime.now()
        if LAST_DIETA_BAMBAM_CALL == None or (
                now - LAST_DIETA_BAMBAM_CALL).seconds > 18000:  #5 hours
            send_message('O Bambam me passa a tua dieta ai!', chat_id, com)
            LAST_DIETA_BAMBAM_CALL = now
            return True
    return False
コード例 #12
0
def send_message_command(message, text, chat_id, com):
    try:
        text.index('send_msg')
        parts_command = text.split(';')
        if len(parts_command) == 3:
            destination_chat_id = parts_command[1].strip()
            msg = parts_command[2].strip()
            send_message(msg, destination_chat_id, com)
            return True
    except:  #if no send_msg is found on text an exception will occur, in this case just return False meaning the command was not executed
        None
    return False
コード例 #13
0
def passar_mao_cabelo_david(message, chat_id, com):
    global LAST_DAVID_HAIR_CALL
    if 'from' in message and 'first_name' in message[
            'from'] and 'david' == message['from']['first_name'].lower():
        now = datetime.datetime.now()
        if LAST_DAVID_HAIR_CALL == None or (
                now - LAST_DAVID_HAIR_CALL).seconds > 18000:  #5 hours
            send_message('Oi David posso passar a mão no seu cabelo?', chat_id,
                         com)
            LAST_DAVID_HAIR_CALL = now
            return True
    return False
コード例 #14
0
ファイル: receiver.py プロジェクト: mehmetmertbese/peqi-ot
    def _execute_string_ot(self, c, n, sender="Alice", cqc=None):
        self.cqc = cqc
        c_prime, rc = self.execute_rot(n * 2)

        d = (c + c_prime) % 2
        send_message(self.cqc, sender, [d])
        e = []
        e.append([int(x) for x in receive_message(self.cqc, sender)])
        e.append([int(x) for x in receive_message(self.cqc, sender)])
        ac = list((np.asarray(e[c], dtype=np.uint8) + rc) % 2)
        #print(ac)
        return ac
コード例 #15
0
 def handle_DELETE_REQUEST(self, client_socket, delete_request):
     file_path = delete_request.file_path
     
     can_delete = False
     peer_list = []
     
     f = self.db.get_file(file_path)
     if f:
         can_delete = True
         peer_list = self.db.get_peers(file_path)
         
     delete_response = messages.DeleteResponse(file_path, can_delete, peer_list)
     
     communication.send_message(delete_response, socket=client_socket)
コード例 #16
0
    def _binary(self, block):
        alice_first_half_par = int(
            communication.receive_message(self.party.cqc,
                                          self.party.sender_pkey))

        first_half_size = math.ceil(len(block) / 2.0)
        first_half_par = utils.calculate_parity(self.party.sifted_key,
                                                block[:first_half_size])

        if first_half_par != alice_first_half_par:
            if first_half_size == 1:
                self.party.sifted_key[
                    block[0]] = (self.party.sifted_key[block[0]] + 1) % 2
                communication.send_message(self.party.cqc, self.party.sender,
                                           self.party.skey, 'DONE')
                return block[0]
            else:
                communication.send_message(self.party.cqc, self.party.sender,
                                           self.party.skey, 0)
                return self._binary(block[:first_half_size])
        else:
            if len(block) - first_half_size == 1:
                self.party.sifted_key[
                    block[-1]] = (self.party.sifted_key[block[-1]] + 1) % 2
                communication.send_message(self.party.cqc, self.party.sender,
                                           self.party.skey, 'DONE')
                return block[-1]
            else:
                communication.send_message(self.party.cqc, self.party.sender,
                                           self.party.skey, 1)
                return self._binary(block[first_half_size:])
コード例 #17
0
    def run_algorithm(self):
        n = math.ceil(0.73 / self.party.error_estimation)
        iterations = [[]]

        # 1st iteration
        for i in range(0, len(self.party.sifted_key), n):
            iterations[0].append(
                list(range(i, min(i + n,
                                  len(self.party.sifted_key) - 1))))

        parities = utils.calculate_parities(self.party.sifted_key,
                                            iterations[0])
        communication.send_binary_list(self.party.cqc, self.party.receiver,
                                       self.party.skey, parities)
        msg = communication.receive_message(self.party.cqc,
                                            self.party.receiver_pkey)
        while msg != 'ALL DONE':
            block_num = int(msg)
            self._binary(iterations[0][block_num])
            msg = communication.receive_message(self.party.cqc,
                                                self.party.receiver_pkey)

        # nth iteration
        for iter_num in range(1, 4):
            n = 2 * n
            iterations.append([])

            # Choose function fi [1...n] -> [1...n/ki], send and save in iterations[iter_num]
            temp_indices = list(range(0, len(self.party.sifted_key)))
            random.shuffle(temp_indices)
            communication.send_message(self.party.cqc, self.party.receiver,
                                       self.party.skey, temp_indices)
            for i in range(0, len(self.party.sifted_key), n):
                iterations[iter_num].append(
                    temp_indices[i:min(i + n,
                                       len(self.party.sifted_key) - 1)])

            parities = utils.calculate_parities(self.party.sifted_key,
                                                iterations[iter_num])
            communication.send_binary_list(self.party.cqc, self.party.receiver,
                                           self.party.skey, parities)

            msg = communication.receive_message(self.party.cqc,
                                                self.party.receiver_pkey)
            while msg != 'ALL DONE':
                iter_num, block_num = json.loads(msg)
                self._binary(iterations[iter_num][block_num])
                msg = communication.receive_message(self.party.cqc,
                                                    self.party.receiver_pkey)
        print(self.party.sifted_key)
コード例 #18
0
    def _execute_string_ot(self, a0, a1, receiver="Bob", cqc=None):
        self.cqc = cqc
        r = self.execute_rot(len(a0) * 2)
        d = receive_message(self.cqc, receiver)[0]
        e = []

        e.append(
            (np.asarray(a0, dtype=np.uint8) + np.asarray(r[d], dtype=np.uint8))
            % 2)
        e.append((np.asarray(a1, dtype=np.uint8) +
                  np.asarray(r[(d + 1) % 2], dtype=np.uint8)) % 2)

        send_message(self.cqc, "Bob", e[0])
        send_message(self.cqc, "Bob", e[1])
コード例 #19
0
 def _binary(self, block):
     first_half_size = math.ceil(len(block) / 2.0)
     first_half_par = utils.calculate_parity(self.party.sifted_key,
                                             block[:first_half_size])
     communication.send_message(self.party.cqc, self.party.receiver,
                                self.party.skey, first_half_par)
     msg = communication.receive_message(self.party.cqc,
                                         self.party.receiver_pkey)
     if msg != 'DONE':
         block_part = int(msg)
         if block_part == 0:
             self._binary(block[:first_half_size])
         else:
             self._binary(block[first_half_size:])
コード例 #20
0
def josias_api(message, chat_id, com):
    global LAST_JOSIAS_API_CALL
    if 'from' in message and 'first_name' in message[
            'from'] and 'josias' == message['from']['first_name'].lower():
        now = datetime.datetime.now()
        if LAST_JOSIAS_API_CALL == None or (
                now - LAST_JOSIAS_API_CALL).seconds > 18000:  #5 hours
            messages = [
                'Josias já acabou a API?',
                'Josias quer ajuda pra criar uma VM?'
            ]
            send_message(messages[randint(0, len(messages) - 1)], chat_id, com)
            LAST_JOSIAS_API_CALL = now
            return True
    return False
コード例 #21
0
def process_msg(message, text, chat_id, group_title, com):
    #    if (send_message_command(message, text, chat_id, com) or
    #        passar_mao_cabelo_david(message, chat_id, com) or
    #        dieta_bambam(message, chat_id, com) or
    #        josias_api(message, chat_id, com)):
    #        return

    text = text.lower()
    for ks in single_keywords_speaches:
        for keyword in ks[0]:
            if keyword in text:
                index = 0
                if len(ks[1]) > 1:
                    index = randint(0, len(ks[1]) - 1)
                send_message(ks[1][index], chat_id, com)
                break
コード例 #22
0
    def send_parities_addresses(self, receiver, sets):
        parities = [[], []]
        for i in range(0, len(sets)):
            for j in range(0, len(sets[i])):
                if random.randint(0, 1):
                    parities[i].append(j)

        send_message(self.cqc, receiver, parities[0])
        send_message(self.cqc, receiver, parities[1])

        calculated_parities = [0, 0]
        for i in range(0, len(parities)):
            for j in range(0, len(parities[i])):
                calculated_parities[i] = (calculated_parities[i] +
                                          sets[i][parities[i][j]]) % 2

        return calculated_parities
コード例 #23
0
    def send_message(self, message):

        #Makes sure user isn't just sending nothing
        message_no_spaces = message.replace(" ", "")
        if (len(message_no_spaces) != 0):
            return communication.send_message(message)
        else:
            raise cherrypy.HTTPRedirect('/show_user_page')
コード例 #24
0
    def _receive_qubits(self):
        for i in range(0, self.N):

            # Receive qubit from Alice (via Eve)
            q = self.cqc.recvQubit()

            # Choose a random basis
            chosen_basis = random.randint(0, 1)
            self.basis_list.append(chosen_basis)
            if chosen_basis == 1:
                q.H()

            # Retrieve key bit
            k = q.measure()
            self.raw_key.append(k)
            communication.send_message(self.cqc, self.sender, self.skey, 'ok')

        communication.send_message(self.cqc, self.sender, self.skey, 'DONE')
コード例 #25
0
    def _execute_rot(self, n, receiver="Bob", cqc=None):
        self.cqc = cqc
        r0 = [random.random() < 0.5 for _ in range(0, n)]
        r1 = [random.random() < 0.5 for _ in range(0, n)]
        for i in range(0, n):
            self.execute_bit_ot([r0[i], r1[i]])

        k = int(n / 2)
        m0 = generate_full_rank_matrix(k, n)
        m1 = generate_full_rank_matrix(k, n)

        send_message(self.cqc, receiver, list(m0.flatten()))
        send_message(self.cqc, receiver, list(m1.flatten()))

        return np.matmul(m0,
                         np.asarray(r0, dtype=np.uint8).T).T, np.matmul(
                             m1,
                             np.asarray(r1, dtype=np.uint8).T).T
コード例 #26
0
def main():

    n = parse_arguments()
    basis_list = []
    raw_key = []

    # Initialize the connection
    with CQCConnection("Bob") as Bob:
        Bob.closeClassicalServer()

        for i in range(0, n):

            # Receive qubit from Alice (via Eve)
            q = Bob.recvQubit()

            # Choose a random basis
            chosen_basis = random.randint(0, 1)
            basis_list.append(chosen_basis)
            if chosen_basis == 1:
                q.H()

            # Retrieve key bit
            k = q.measure()
            raw_key.append(str(k))
            send_message(Bob, 'Alice', 'ok'.encode('utf-8'))

        alice_basis = list(receive_message(Bob))
        send_message(Bob, "Alice", bytes(basis_list))
        for i in range(0, len(alice_basis)):
            if alice_basis[i] != basis_list[i]:
                raw_key[i] = 'X'

        sifted_key = list(filter(lambda k: k != 'X', raw_key))
        print('\nBob Sifted Key:' + ''.join(sifted_key))

        seed = list(receive_message(Bob))
        key = 0
        for i in range(0, len(seed)):
            key = (key + (int(sifted_key[i]) * seed[i])) % 2
        print("Bob extracted key={}".format(key))

        c = receive_message(Bob)[0]
        m = (c + key) % 2
        print("Bob received m={} that was encrypted as c={}".format(m, c))
コード例 #27
0
ファイル: client.py プロジェクト: 12z/Multi-Client-Server
 def __init__(self, name, host='127.0.0.1', port=9999):
     self.name = name
     # Quit flag
     self.flag = False
     self.port = int(port)
     self.host = host
     # Initial prompt
     self.prompt = '[' + '@'.join((name, socket.gethostname().split('.')[0])) + ']> '
     # Connect to server at port
     try:
         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         self.sock.connect((host, self.port))
         print('Connected to chat server@%d' % self.port)
         # Send my name...
         send_message(self.sock, 'name', self.name)
         # Set prompt with client's address
         self.prompt = '[' + '@'.join((self.name, receive_address(self.sock))) + ']> '
     except socket.error:
         print('Could not connect to chat server @%d' % self.port)
         sys.exit(1)
コード例 #28
0
    def cmdloop(self):

        if "TEST" in environ:
            inputs = [self.sock]  # For testing on Win
        else:
            inputs = [0, self.sock]

        while not self.flag:
            try:
                sys.stdout.write(self.prompt)
                sys.stdout.flush()

                # Wait for input from stdin & socket
                inputready, outputready, exceptrdy = select.select(
                    inputs, [], [])

                for i in inputready:
                    if i == 0:
                        data = sys.stdin.readline().strip()
                        if data:
                            send_message(self.sock, 'text', data)
                    elif i == self.sock:
                        data = receive(self.sock)
                        if not data:
                            print('Shutting down.')
                            self.flag = True
                            break
                        else:
                            if data.type == 'text':
                                sys.stdout.write(data.text + '\n')
                                sys.stdout.flush()
                            elif data.type == 'kick':
                                print('You were kicked by the server')
                                self.sock.close()
                                self.flag = True
                                break

            except KeyboardInterrupt:
                print('Interrupted.')
                self.sock.close()
                break
コード例 #29
0
ファイル: client.py プロジェクト: 12z/Multi-Client-Server
    def cmdloop(self):

        if "TEST" in environ:
            inputs = [self.sock]  # For testing on Win
        else:
            inputs = [0, self.sock]

        while not self.flag:
            try:
                sys.stdout.write(self.prompt)
                sys.stdout.flush()

                # Wait for input from stdin & socket
                inputready, outputready, exceptrdy = select.select(inputs, [], [])

                for i in inputready:
                    if i == 0:
                        data = sys.stdin.readline().strip()
                        if data:
                            send_message(self.sock, 'text', data)
                    elif i == self.sock:
                        data = receive(self.sock)
                        if not data:
                            print('Shutting down.')
                            self.flag = True
                            break
                        else:
                            if data.type == 'text':
                                sys.stdout.write(data.text + '\n')
                                sys.stdout.flush()
                            elif data.type == 'kick':
                                print('You were kicked by the server')
                                self.sock.close()
                                self.flag = True
                                break

            except KeyboardInterrupt:
                print('Interrupted.')
                self.sock.close()
                break
コード例 #30
0
 def handle_ARCHIVE_REQUEST(self, client_socket, archive_request):
     file_path = archive_request.file_path
     response = messages.ArchiveResponse(file_path, archived=False)
     
     logging.info("Handling Archive Request")
     
     f = self.db.get_file(file_path)
     if not f:
         communication.send_message(response, socket=client_socket)
         return
     
     self.db.add_version(f)
     f.latest_version += 1
     self.db.add_or_update_file(f)        
     
     response.archived = True
     communication.send_message(response, socket=client_socket)
             
     peers_list = self.db.get_peers(file_path)
     
     # notify all peers that have the file about the new version
     for peer in peers_list:
         if peer.hostname == self.hostname and peer.port == self.port:
             local_file_path = filesystem.get_local_path(self, file_path, f.latest_version-1)
             file_data = filesystem.read_file(local_file_path)
     
             local_file_path = filesystem.get_local_path(self, file_path, f.latest_version)
             filesystem.write_file(local_file_path, file_data)
     
         if peer.state == PeerState.OFFLINE:
             continue
         file_archived_msg = messages.FileArchived(f.path, f.latest_version)
         communication.send_message(file_archived_msg, peer)
コード例 #31
0
 def __init__(self, name, host='127.0.0.1', port=9999):
     self.name = name
     # Quit flag
     self.flag = False
     self.port = int(port)
     self.host = host
     # Initial prompt
     self.prompt = '[' + '@'.join(
         (name, socket.gethostname().split('.')[0])) + ']> '
     # Connect to server at port
     try:
         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         self.sock.connect((host, self.port))
         print('Connected to chat server@%d' % self.port)
         # Send my name...
         send_message(self.sock, 'name', self.name)
         # Set prompt with client's address
         self.prompt = '[' + '@'.join(
             (self.name, receive_address(self.sock))) + ']> '
     except socket.error:
         print('Could not connect to chat server @%d' % self.port)
         sys.exit(1)
コード例 #32
0
def recebe_mensagem_do_cliente(cliente, endereco):

    while True:
        try:
            mensagem = mensagem_pb2.Mensagem()
            recebe_mensagem = recv_message(cliente)
            mensagem.ParseFromString(recebe_mensagem)
            if not mensagem:
                raise error('Erro de comunicacao')
            logging.info(
                "[received] sender name: %s, receiver name: %s, message type: %s and thread ID: %s",
                mensagem.sender_name, mensagem.receiver_name,
                mensagem_pb2.Mensagem.Msg_type.Name(mensagem.msg_type),
                str(mensagem.thread_id))

            mensagem.dados = os.urandom(32).encode("hex")

            mensagem.msg_type = 1
            mensagem.thread_id = threading.current_thread().ident

            hmac_maker = hmac.new('chave-secreta-2018', '', hashlib.sha512)
            hmac_maker.update(str(mensagem.id_cliente))
            hmac_maker.update(mensagem.dados)
            mensagem.hmac = hmac_maker.hexdigest()

            logging.info(
                "[sending] sender name: %s, receiver name: %s, message type: %s and thread ID: %s",
                mensagem.sender_name, mensagem.receiver_name,
                mensagem_pb2.Mensagem.Msg_type.Name(mensagem.msg_type),
                str(mensagem.thread_id))
            send_message(cliente, mensagem)
        except (SocketReadError):
            cliente.close()
            return False
        except:
            traceback.print_exc()
コード例 #33
0
def main():

    n = parse_arguments()
    basis_list = []
    raw_key = []

    # Initialize the connection
    with CQCConnection("Alice") as Alice:
        Alice.closeClassicalServer()

        for i in range(0, n):
            # Generate a key
            k = random.randint(0, 1)
            raw_key.append(str(k))
            chosen_basis = random.randint(0, 1)
            basis_list.append(chosen_basis)

            # Create a qubit
            q = qubit(Alice)

            # Encode the key in the qubit
            if k == 1:
                q.X()

            # Encode in H basis if basis = 1
            if chosen_basis == 1:
                q.H()

            # Send qubit to Bob (via Eve)
            Alice.sendQubit(q, "Eve")
            receive_message(Alice)

        send_message(Alice, "Bob", bytes(basis_list))
        bob_basis = list(receive_message(Alice))
        for i in range(0, len(bob_basis)):
            if bob_basis[i] != basis_list[i]:
                raw_key[i] = 'X'
                basis_list[i] = 'X'

        sifted_key = list(filter(lambda k: k != 'X', raw_key))
        print('\nAlice Sifted Key:' + ''.join(sifted_key))

        seed = generate_seed(len(sifted_key))
        send_message(Alice, "Bob", bytes(seed))
        key = 0
        for i in range(0, len(seed)):
            key = (key + (int(sifted_key[i]) * seed[i])) % 2
        print("Alice extracted key={}".format(key))

        m = 1
        c = (m + key) % 2
        send_message(Alice, "Bob", bytes([c]))
        print("Alice sent m={} encrypted to c={}".format(m, c))
コード例 #34
0
    def send_final_strings(self, receiver, parities, decision):
        msgs = []
        msgs.append((parities[0] + self.transfer_bits[not decision]) % 2)
        msgs.append((parities[1] + self.transfer_bits[decision]) % 2)

        send_message(self.cqc, receiver, msgs)
コード例 #35
0
    def run_algorithm(self):
        n = math.ceil(0.73 / self.party.error_estimation)
        iterations = [[]]

        # 1st iteration
        for i in range(0, len(self.party.sifted_key), n):
            iterations[0].append(
                list(range(i, min(i + n,
                                  len(self.party.sifted_key) - 1))))

        parities = [
            utils.calculate_parities(self.party.sifted_key, iterations[0])
        ]
        alice_parities = [
            communication.receive_binary_list(self.party.cqc,
                                              self.party.sender_pkey)
        ]

        for i in range(0, len(alice_parities[0])):
            if parities[0][i] != alice_parities[0][i]:
                communication.send_message(self.party.cqc, self.party.sender,
                                           self.party.skey, i)
                self._binary(iterations[0][i])
                parities[0][i] ^= 1
        communication.send_message(self.party.cqc, self.party.sender,
                                   self.party.skey, 'ALL DONE')

        # nth iteration
        for iter_num in range(1, 4):
            n = 2 * n
            iterations.append([])
            temp_indices = communication.receive_list(self.party.cqc,
                                                      self.party.sender_pkey)
            for i in range(0, len(self.party.sifted_key), n):
                iterations[iter_num].append(
                    temp_indices[i:min(i + n,
                                       len(self.party.sifted_key) - 1)])
            parities.append(
                utils.calculate_parities(self.party.sifted_key,
                                         iterations[iter_num]))
            alice_parities.append(
                communication.receive_binary_list(self.party.cqc,
                                                  self.party.sender_pkey))
            for i in range(0, len(alice_parities[iter_num])):
                blocks_to_process = [(iter_num, i)]
                while blocks_to_process:
                    (correcting_iter,
                     correcting_block) = blocks_to_process.pop()
                    if parities[correcting_iter][
                            correcting_block] != alice_parities[
                                correcting_iter][correcting_block]:
                        communication.send_message(
                            self.party.cqc, self.party.sender, self.party.skey,
                            [correcting_iter, correcting_block])
                        corrected_index = self._binary(
                            iterations[correcting_iter][correcting_block])
                        for i in range(0, iter_num):
                            block_containing_index = utils.get_num_block_with_index(
                                iterations[correcting_iter], corrected_index)
                            parities[i][block_containing_index] ^= 1
                            if i != correcting_iter:
                                blocks_to_process.append(
                                    (i, block_containing_index))
            communication.send_message(self.party.cqc, self.party.sender,
                                       self.party.skey, 'ALL DONE')

        print(self.party.sifted_key)
コード例 #36
0
def main():

    n = parse_arguments()
    basis_list = []
    raw_key = []

    # Initialize the connection
    with CQCConnection("Bob") as Bob:
        Bob.closeClassicalServer()

        for i in range(0, n):

            # Receive qubit from Alice (via Eve)
            q = Bob.recvQubit()

            # Choose a random basis
            chosen_basis = random.randint(0, 1)
            basis_list.append(chosen_basis)
            if chosen_basis == 1:
                q.H()

            # Retrieve key bit
            k = q.measure()
            raw_key.append(str(k))
            send_message(Bob, 'Alice', 'ok'.encode('utf-8'))

        alice_basis = list(receive_message(Bob))
        send_message(Bob, "Alice", bytes(basis_list))
        for i in range(0, len(alice_basis)):
            if alice_basis[i] != basis_list[i]:
                raw_key[i] = 'X'
                basis_list[i] = 'X'

        sifted_key = list(
            map(lambda x: int(x), (filter(lambda x: x != 'X', raw_key))))
        sifted_basis = list(filter(lambda x: x != 'X', basis_list))

        send_message(Bob, "Alice", bytes(sifted_key))
        alice_key = list(receive_message(Bob))

        z_basis_error = 0.0
        x_basis_error = 0.0
        z_count = 0.0
        x_count = 0.0
        for i in range(0, len(sifted_basis)):
            if int(sifted_basis[i]) == 0:
                z_count += 1.0
                if int(sifted_key[i]) != alice_key[i]:
                    z_basis_error += 1.0
            else:
                x_count += 1.0
                if int(sifted_key[i]) != alice_key[i]:
                    x_basis_error += 1.0

        if z_count == 0:
            z_count = 1
        if x_count == 0:
            x_count = 1

        print(
            "\n Standard Basis Error: {}\n Hadamard Basis Error: {}\n".format(
                z_basis_error / z_count, x_basis_error / x_count))
コード例 #37
0
    def handle_LIST_REQUEST(self, client_socket, list_request):
        logging.debug("Handling list request")
        file_list = self.db.list_files(list_request.dir_path)

        list_response = messages.List(file_list)
        communication.send_message(list_response, socket=client_socket)
コード例 #38
0
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(("127.0.0.1", 5001))

    mensagem = mensagem_pb2.Mensagem()
    mensagem.tipo_operacao = 0
    for i in range(100):
        try:

            aluno = mensagem.aluno.add()
            aluno.nome = names.get_full_name()
            aluno.matriculado = randint(0, 1)
            aluno.idade = randint(15, 100)
            aluno.matricula = int(''.join([choice(digits) for n in xrange(9)]))
            aluno.curso = ''.join(
                [choice(ascii_letters + digits) for n in xrange(5)])
            aluno.semestre = randint(1, 20)
            aluno.campus = randint(1, 4)

            logging.info(
                "[Sended] Operation type: %s, Values: matriculado: %s, nome: %s, idade: %s, matricula: %s, curso: %s, semestre: %s, campus: %s",
                mensagem.tipo_operacao, aluno.matriculado, aluno.nome,
                aluno.idade, aluno.matricula, aluno.curso, aluno.semestre,
                mensagem_pb2.Mensagem.Aluno.Campus.Name(aluno.campus))

        except:
            traceback.print_exc()

    send_message(sock, mensagem)
    sock.close()
コード例 #39
0
    def serve(self):

        if "TEST" in environ:
            inputs = [self.server]  # for testing on Win
        else:
            inputs = [self.server, sys.stdin]
        self.outputs = []

        kick_command = re.compile('^kick.*')

        while True:

            try:
                inputready, outputready, exceptready = select.select(inputs, self.outputs, [])
            except select.error as e:
                print(e)
                break
            except socket.error:
                break

            for s in inputready:

                if s == self.server:
                    # handle the server socket
                    client, address = self.server.accept()
                    print('chatserver: got connection %d from %s' % (client.fileno(), address))
                    # Read the login name
                    client_name = receive_name(client)

                    # Compute client name and send back
                    self.clients += 1
                    send_message(client, 'address', str(address[0]))
                    inputs.append(client)

                    self.clientmap[client] = (address, client_name)
                    # Send joining information to other clients
                    msg = '\n(Connected: New client (%d) from %s)' % (self.clients, self.getname(client))
                    for o in self.outputs:
                        send_message(o, 'text', msg)

                    self.outputs.append(client)

                elif s == sys.stdin:
                    # handle standard input
                    line = sys.stdin.readline().strip('\n')
                    # print('got input', line)
                    if line == 'list':
                        for client in self.clientmap:
                            # print('client')
                            print(self.getname(client))
                    elif kick_command.match(line):
                        name = line.split(' ')[1]
                        # print('here we kick', line.split(' ')[1])
                        for client in self.clientmap:
                            # print(self.getname(client))
                            if self.getname(client).split('@')[0] == name:
                                # print('got him')
                                # Send client leaving information to others
                                msg = '\n(Kicked: Client from %s)' % self.getname(client)
                                for o in self.outputs:
                                    send_message(o, 'text', msg)
                                send_message(client, 'kick', '')
                                self.clients -= 1
                                inputs.remove(client)
                                self.outputs.remove(client)
                                del self.clientmap[client]
                                client.close()
                                break
                else:
                    # handle all other sockets
                    try:
                        data = receive(s)
                        if data:
                            # Send as new client's message...
                            msg = '\n#[' + self.getname(s) + ']>> ' + data.text
                            # print('text: ', data.text)
                            # print('type: ', data.type)
                            # Send data to all except ourselves
                            for o in self.outputs:
                                if o != s:
                                    send_message(o, 'text', msg)
                        else:
                            print('chatserver: %d hung up' % s.fileno())
                            self.clients -= 1
                            s.close()
                            inputs.remove(s)
                            self.outputs.remove(s)
                            # Send client leaving information to others
                            msg = '\n(Hung up: Client from %s)' % self.getname(s)
                            for o in self.outputs:
                                send_message(o, 'text', msg)

                            # Removing it later to be able to get name earlier
                            del self.clientmap[s]

                    except socket.error:
                        # Remove
                        inputs.remove(s)
                        self.outputs.remove(s)
                        del self.clientmap[s]

        self.server.close()
コード例 #40
0
 def handle_VALIDATE_CHECKSUM_REQUEST(self, client_socket, msg):
     logging.debug("Handling the check checksum request")
     valid = self.db.check_checksum(msg.file_path, msg.file_checksum)
     response = messages.ValidateChecksumResponse(msg.file_path, valid)
     communication.send_message(response, socket=client_socket)