예제 #1
0
    def test_receive_direct_bad_tag(self):
        # Input
        message = "hello"
        sender = "bob"
        recipient = "alice"

        contacts = {
            'bob': {
                'public_key':
                b'-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoNd3g3mkIOmsKHfzAEDs\n34oqVz71+ZhbyyQ4wfkKjWHCbz9js7iXt5uerTLso+CivkxRE4cx3stUWFtIc9Jq\nlAiOrkPjuOZrW1qvTUI/g4EuNpBIN1UKrQTjnInVLLXD8ko5fgu38xlPMhOU2Owi\nSo6EXskByHFQVuktQxmVIdGvLf8r5sBAImtdsROxR/owjiZ4mGz7yLiOKwV9Hik4\ndQMpkHduCH5H6P0kki1B2+3pnIP3vdAXoSvfxUcL9xkb8+KpX/idwrB06hftBO9i\n6MmknI5RFwquirF1bxnuEMByWTsywvg50qCyaM+TsgMtucUkwCnkDvSL7vk5IJe7\nQwIDAQAB\n-----END PUBLIC KEY-----',
                'aes_key': b'/\x9ei\xa0\xa9\xeclp;r[\xea\xad\x99\x009',
                'hmac_key': b'\x1ca\x93\xe5\x94?\xe4C\xa2N\xa4\xe1\xe5:\xceB'
            }
        }

        # Expected
        timestamp = '1607040000.0'
        enc_msg = b'\xbf\xebdMr\x9f\xdb\x94\\\x86A\xf4\xaa\x99n\xb1'
        iv = b'mVw\xc1\x93\x04Q\xb3?%\x1e\x87\x86\xd2`\xe2'
        tag = ""
        enc_msg_b64 = base64.b64encode(enc_msg)
        iv_b64 = base64.b64encode(iv)

        request = Requests.direct_message(sender, recipient, str(enc_msg_b64),
                                          str(iv_b64), timestamp, str(tag))
        parsed_request = Requests.parse_request(request)

        # Actual test
        with self.assertRaises(Exception) as context:
            Receive.receive_direct(parsed_request.data, contacts, timestamp)
예제 #2
0
    def test_receive_group_bad_enc_msg(self):
        # Input
        message = "hello"
        sender = "alice"
        group_name = "test"
        group_members = ["alice", "bob", "mark"]
        groups = {
            "test": {
                "aes_key":
                b'e\xcfO\xdc&\x8d\x87\xe0q\xf7\x1a\xeas\x05\x98\x0b',
                "hmac_key":
                b'\x89\x07\xadl\xa7bS\xbe\xf3\xb7\xc8\xb9\xbe\x95\xb6\xc9'
            }
        }

        # Expected
        timestamp = '1607040000.0'
        enc_msg = b""
        iv = b'\x81\xc0\xd4\xa7\x06\x91\xdb\xea$\x99\xba\xdf\xae\xc1Q\xf1'
        tag = b'aY2BArPfzsEnjqd4m0UlKkFIIP7ExD5nLxR2GWJLHUg='
        enc_msg_b64 = base64.b64encode(enc_msg)
        iv_b64 = base64.b64encode(iv)

        request = Requests.group_message(sender, ",".join(group_members),
                                         group_name, str(enc_msg_b64),
                                         str(iv_b64), timestamp, str(tag))
        parsed_request = Requests.parse_request(request)

        # Actual test
        with self.assertRaises(Exception) as context:
            Receive.receive_group(parsed_request.data, groups, dict())
예제 #3
0
    def test_receive_group_bad_tag(self):
        # Input
        message = "hello"
        sender = "alice"
        group_name = "test"
        group_members = ["alice", "bob", "mark"]
        groups = {
            "test": {
                "aes_key":
                b'e\xcfO\xdc&\x8d\x87\xe0q\xf7\x1a\xeas\x05\x98\x0b',
                "hmac_key":
                b'\x89\x07\xadl\xa7bS\xbe\xf3\xb7\xc8\xb9\xbe\x95\xb6\xc9'
            }
        }

        # Expected
        timestamp = '1607040000.0'
        enc_msg = b'\x96\xeet\xef\xd8\xffD\xf9\xc4\xdb^\xd2\xbc\xf3\xa4k'
        iv = b'\xa4\xd58\xee\x8fu\x937y\xb6\xfd\x13\xf8\xe8j@'
        tag = ""
        enc_msg_b64 = base64.b64encode(enc_msg)
        iv_b64 = base64.b64encode(iv)

        request = Requests.group_message(sender, ",".join(group_members),
                                         group_name, str(enc_msg_b64),
                                         str(iv_b64), timestamp, str(tag))
        parsed_request = Requests.parse_request(request)

        # Actual test
        with self.assertRaises(Exception) as context:
            Receive.receive_group(parsed_request.data, groups, dict())
예제 #4
0
    def test_receive_group(self, mock_print):
        # Input
        message = "hello"
        sender = "alice"
        group_name = "test"
        group_members = ["alice", "bob", "mark"]
        groups = {
            "test": {
                "aes_key":
                b'e\xcfO\xdc&\x8d\x87\xe0q\xf7\x1a\xeas\x05\x98\x0b',
                "hmac_key":
                b'\x89\x07\xadl\xa7bS\xbe\xf3\xb7\xc8\xb9\xbe\x95\xb6\xc9'
            }
        }

        # Expected
        timestamp = '1607040000.0'
        enc_msg = b'\x96\xeet\xef\xd8\xffD\xf9\xc4\xdb^\xd2\xbc\xf3\xa4k'
        iv = b'\x81\xc0\xd4\xa7\x06\x91\xdb\xea$\x99\xba\xdf\xae\xc1Q\xf1'
        tag = b'aY2BArPfzsEnjqd4m0UlKkFIIP7ExD5nLxR2GWJLHUg='
        enc_msg_b64 = base64.b64encode(enc_msg)
        iv_b64 = base64.b64encode(iv)

        request = Requests.group_message(sender, ",".join(group_members),
                                         group_name, str(enc_msg_b64),
                                         str(iv_b64), timestamp, str(tag))
        parsed_request = Requests.parse_request(request)

        # Actual test
        Receive.receive_group(parsed_request.data, groups, dict())
        mock_print.assert_called_with(sender + " to " + group_name + ": " +
                                      message)
예제 #5
0
파일: Main.py 프로젝트: zgame/PythonCode
def recv_loop(s):
    while True:
        # print("receive")
        msg = s.recv(1024 * 80)  # 接收字节的数据
        # print("msg", msg)
        buf_len = len(msg)
        buf_head = 0
        while buf_head < buf_len:
            deal_buffer = msg[buf_head:buf_len]
            main_cmd, sub_cmd, buffer_size, ver = Receive.deal_recv_tcp_deader_data(deal_buffer)
            buf_head = buf_head + buffer_size + 10
            Receive.deal_recv_protocol_data(main_cmd, sub_cmd, deal_buffer[10:10+buffer_size], buffer_size)
예제 #6
0
import sys
import serial
import Receive
from Crypto.Hash import MD5


zb = serial.Serial('COM4', timeout=1)
while True:
	try:
		data = zb.readline()
		if not (data == b''):
			check = Receive.Receive(data[:-2])
	except KeyboardInterrupt:
		print("KeyboardInterrupt")
		zb.close()
		sys.exit()

# def sendpacket():
# 	header = b'\x01\x00\x07\x2c\x04\x12\xff'
# 	secret = 'HkdW54vs4FrSUS2Y'
# 	temp = header + secret.encode()
# 	ht = MD5.new()
# 	ht.update(temp)
# 	final = ht.hexdigest()
# 	packet = header + bytes.fromhex(final)
# 	eol = b'\r\n'
# 	zb = serial.Serial('COM9')
# 	zb.write(packet+eol)
# 	zb.close()

# sendpacket()
예제 #7
0
def receive():
    while True:
        receive_data = Receive.receive()
예제 #8
0
def callback(ch, method, properties, body):
    Receive.Receive(body)
''' A testing module for checking bidirectional communication '''
import Queue
import threading

import Receive
import Send

if __name__ == '__main__':

    PERSONAL_COMPUTER_IP = '173.250.180.118'
    CSE208_IP = '128.208.5.218'

    RECEIVE_MESSAGE_QUEUE = Queue.Queue()
    SEND_MESSAGE_QUEUE = Queue.Queue()
    RECEIVE_OBJECT = Receive.Receive(
        port=13000, receive_message_queue=RECEIVE_MESSAGE_QUEUE)
    SEND_OBJECT = Send.Send(host_ip=CSE208_IP,
                            port=13001,
                            send_message_queue=SEND_MESSAGE_QUEUE)
    threading.Thread(target=RECEIVE_OBJECT.receive_from_queue).start()
    threading.Thread(target=SEND_OBJECT.run_send_from_queue).start()

    while True:
        data = RECEIVE_MESSAGE_QUEUE.get()
        print "Received message: " + data
        SEND_MESSAGE_QUEUE.put(data + '-- Resent')
                    fp.Multicast_Packet(n)
                if model == 3:
                    fp.Multicast_Check_Packet(n)
                if model == 4:
                    fp.Op_Multicast_Packet(n,4) #4 - number of nodes to do forward
            
    
        #short global bufffer (based on the timestapm -- correct order of sending
        settings.networkbuffer = sorted(settings.networkbuffer, key=lambda Packets: Packets.timestamp)
         

        
        #2) Receive <--
        print("------------RECEIVE PROCESS-------------")
        for n in range(0,len(settings.nodesList)):
            rp.Receive(n,i,b)
        
        


        #GraphPlot.plot_Graph("slot"+str(i))   
        #NetworkAnimation.animate()

        settings.graphlist.append(copy.deepcopy(GlobalGraph.G))
        #FINISH OF TIME SLOT - SET DIFFERENT STATE FOR THE NEXT TIME SLOT 
        sas.set_active_state(90) #state of the nodes (80% active-20% inactive)

    ########################################################################

  
    #count the proportion of successful transmissions and store it in a file 
예제 #11
0
def linearcode_simulate(bg_setting,input_file, output_file, n, packet_group, gb, bg, epsilon, max_delay):

    # This array stores the data for all the packets
    packet = []
    f = open(input_file + ".ts", "rb")
    g = open(str(bg_setting) + "/" + output_file+"_"+str(bg)+"_"+str(n)+".ts", "wb")
    #g = 0
    data = f.read()
    num = 0
    
    unrecov = 0
    total = 0

    # Make a list that indicate which packets have dropped
    
    # When each nth packet is transmitted, another nth parity packet is sent out
    # If any of the nth, n+1st, n+2nd packet is lost, the nth packet is not recoverable
    packet_status = []
    parity_status = []
    frame_type = []
    
    # Counter identifies labels the nth packet
    counter  = -1
    initial = 1
    initial_data = ""
    state = 0
    lost = 0

    
    # for burst erasure keep track of last state
    last_markov_state = 0
    
    # byte checker to check for picture type (keeps track of 5 bytes)
    byte_checker = 0x0000000000
    
    # initialize arrays first
    for elem in data:
        packet.append("")
        packet_status.append(0)
        parity_status.append(0)
        frame_type.append(0)
    
    for elem in data:

        # get binary packed data from string
        unpacked_byte = (struct.unpack("B",elem))[0] 

        # check bytechecker
        if ((byte_checker>>8)&(0xFFFFFFFF)) == 0x00000100:
            #print("Picture start byte found\n")
            current_frame_type = ((unpacked_byte & 0x38)>>3)
            frame_type[counter] = current_frame_type
                
        if unpacked_byte == 0x47:
            # no longer in initial stage
            initial = 0
            # new packet, increase counter
            counter += 1
            # Initialize data text element
            packet[counter] = ""
            # Check for possibility of packet loss (channel could be isolated or burst erasure type)

            (state, lost) = Erasure.gilbert_channel(last_markov_state, gb, bg, epsilon)
            last_markov_state = state;
            #elif channel_type == 1:
            #    lost = Erasure.isolated_erasure_channel(gb)
            
            packet_status[counter] = lost

                                         
            # For every (num_parity)th packet (3 in the case of rate 4/3), we also simulate sending out a parity packet
            # which contains num_parityth sets of bits
  
            # Example (using rate 4/3) imagine splitting each information packet into three parts a, b, c
            # 1/3 of Parity packet will be a linear combination of a[k], a[k-1], a[k-2], b[k], b[k-1], b[k-2], c[k], c[k-1], c[k-2]
            # 1/3 of Parity packet will be a linear combination of a[k+1], a[k], a[k-1], b[k+1], b[k], b[k-2], c[k], c[k-1], c[k-2]
            # 1/3 of Parity packet will be a liner combination of a[k+2], a[k+1], a[k], b[k+2], b[k+1], b[k], c[k+2], c[k+1], c[k]
            # Thus, we need parity packet of k/3 and the contents of information packet k+1, k+2, k-1, k-2          
            
            if counter%packet_group == 0:
                (state,lost) = Erasure.gilbert_channel(last_markov_state, gb, bg, epsilon)
                last_markov_state = state  
                #elif channel_type == 1:
                #    lost = Erasure.isolated_erasure_channel(gb)
                parity_status[counter/packet_group] = lost   
               
        # shift into byte_checker
        # shift up and remask
        byte_checker = (byte_checker << 8) & 0xFFFFFFFF00
        #print("after shift" +   hex(byte_checker))
        byte_checker = (byte_checker | unpacked_byte) & 0xFFFFFFFFFF            

        # Current byte being written
        repacked_byte = struct.pack("B",unpacked_byte)
        if initial == 1:
            initial_data = initial_data + repacked_byte
        else:
            # Writing data to appropriate packet 
            packet[counter] = packet[counter] + repacked_byte
  
  
    # close file stream        
    f.close()
    
    # After all packets are sent out, we send the data to the receiver and a simulated
    # reconstruction of lost packets will take place on the packets that were lost
    # All the packets that made it will be written to a file

    (unrecov, total, i_f, p_f, b_f) = Receive.linearcode_receive(packet, packet_status, parity_status, g, initial_data, packet_group, max_delay, frame_type)
    # There are 2514 packets in the testqcif.ts
    # close output file stream
    g.close()
    
    return (int(unrecov), int(total), int(i_f),int(p_f),int(b_f) )
예제 #12
0
def callback(ch, method, properties, body):
    #print(" [x] %r" % body)
    Receive.Receive(body)
예제 #13
0
파일: Client.py 프로젝트: MWRose/Accord
    def handle_receive(self):
        """
        Handles all of the different receiving requests from server
        """
        while True:
            data = self.s.recv(4096)
            request = Requests.parse_request(data)
            with self.console_lock:
                # Handle different message types
                if request.is_direct_message():
                    Receive.receive_direct(request.data, self.contacts,
                                           self.received_timestamps)
                elif request.is_group_message():
                    Receive.receive_group(request.data, self.groups,
                                          self.received_timestamps)
                elif request.is_broadcast():
                    print(request.data["message"])

                # Initiate the group chat and save keys
                elif request.is_initiate_group_chat():
                    print("Initiating new group chat...")

                    requester = request.data["requester"]
                    # Make sure we have the contact
                    if requester not in self.contacts or "public_key" not in self.contacts[
                            requester].keys():
                        self.populate_public_keys(requester)

                    # Recieve the handshake
                    keys = Receive.receive_group_handshake(
                        request.data, self.username, self.groups,
                        self.contacts, self.private_key)
                    group_name = keys["group_name"]
                    aes_key = keys["aes"]
                    hmac_key = keys["hmac"]
                    members = keys["members"]

                    # This will completely overwrite or add a new one
                    self.groups[group_name] = {
                        "aes_key": aes_key,
                        "hmac_key": hmac_key,
                        "members": members
                    }

                    email = self.username

                    # Get encrypted aes under self.password_aes
                    group_aes = str(base64.b64encode(aes_key))
                    enc_goup_aes, iv_aes = Crypto_Functions.aes_encrypt(
                        group_aes, self.password_aes)
                    enc_goup_aes = str(base64.b64encode(enc_goup_aes))
                    iv_aes = str(base64.b64encode(iv_aes))

                    # get encrypted hmac under self.password_aes
                    hmac_key = str(base64.b64encode(hmac_key))
                    enc_hmac_key, iv_hmac = Crypto_Functions.aes_encrypt(
                        hmac_key, self.password_aes)
                    enc_hmac_key = str(base64.b64encode(enc_hmac_key))
                    iv_hmac = str(base64.b64encode(iv_hmac))

                    # Add line for each member
                    for member in members:
                        contact = member
                        signature_contents = email + contact + enc_goup_aes + enc_hmac_key + iv_aes + iv_hmac
                        signature = str(
                            Crypto_Functions.hmac_b64(
                                signature_contents.encode(),
                                self.password_hmac))

                        Database.add_group(self.username, group_name, contact,
                                           signature, enc_goup_aes, iv_aes,
                                           enc_hmac_key, iv_hmac)

                elif request.is_initiate_direct_message():
                    requester = request.data["requester"]
                    if requester not in self.contacts:
                        self.populate_public_keys(requester)

                    keys = Receive.receive_direct_handshake(
                        request.data, self.contacts,
                        self.contacts[requester]["public_key"],
                        self.private_key)
                    aes_key = keys["aes"]
                    hmac_key = keys["hmac"]

                    # This will add or overwrite two fields to the requester's contact, leaving the others
                    self.contacts[requester]["aes_key"] = aes_key
                    self.contacts[requester]["hmac_key"] = hmac_key

                    email = self.username
                    contact = requester

                    # Get encrypted aes under self.password_aes
                    contact_aes = str(base64.b64encode(aes_key))
                    enc_contact_aes, iv_aes = Crypto_Functions.aes_encrypt(
                        contact_aes, self.password_aes)
                    enc_contact_aes = str(base64.b64encode(enc_contact_aes))
                    iv_aes = str(base64.b64encode(iv_aes))

                    # Get encrypted hmac under self.password_aes
                    hmac_key = str(base64.b64encode(hmac_key))
                    enc_hmac_key, iv_hmac = Crypto_Functions.aes_encrypt(
                        hmac_key, self.password_aes)
                    enc_hmac_key = str(base64.b64encode(enc_hmac_key))
                    iv_hmac = str(base64.b64encode(iv_hmac))

                    # Create the signature
                    signature_contents = self.username + contact + enc_contact_aes + enc_hmac_key + iv_aes + iv_hmac
                    signature = str(
                        Crypto_Functions.hmac_b64(signature_contents.encode(),
                                                  self.password_hmac))

                    Database.add_contact_info(email, contact, enc_contact_aes,
                                              signature, iv_aes, enc_hmac_key,
                                              iv_hmac)
예제 #14
0
 def __init__(self, dispContent):
     super(ReceiveThread, self).__init__()
     self.dispContent = dispContent
     self.udp_read = Receive.receiveByUdp()