def threaded_function(com_port, baud_rate): global rx_port while True: try: if rx_port.isOpen() is False: print("Opening port") rx_port = serial.Serial(com_port, baud_rate, timeout=None) raw_line = rx_port.readline().strip() print("Received message: {}".format(raw_line)) Mazda.last_seen = datetime.datetime.now() data_array = raw_line.split() if len(data_array) == 4: checksum = data_array[3] data_line = raw_line[0:len(raw_line) - len(data_array[3])] crc = Crc32.calc(data_line) if hex(crc)[2:].upper() == checksum.decode("utf-8"): Mazda.lat = float(data_array[0]) Mazda.lng = float(data_array[1]) Mazda.speed = float(data_array[2]) Mazda.error_message = None else: Mazda.error_message = "Could not decode last message" else: Mazda.error_message = raw_line.decode("utf-8") except Exception as err: print("Closing port due to exception: {}".format(err)) rx_port.close() sleep(5) pass
def threaded(c): while (True): data = c.recv(50000) if (len(data) < 3): continue # print(data) val1 = data[:data[1:].find(b'\x80')] val1 += b'.' #print(val1) val2 = data[data[1:].find(b'\x80'):] val2 = val2[1:] print('Got data') #print(val1) decryptedmessage = pickle.loads(val1) #print(decryptedmessage) crcc = pickle.loads(val2) #print(crcc) recievedmessage = decrypted(decryptedmessage, A_inverse) print(recievedmessage) print("Message got from client" + " -" + " " + str(recievedmessage)) #crcc1 = CRC(recievedmessage) recievedmessage = ''.join( format(i, 'b') for i in bytearray(recievedmessage, encoding='utf-8')) crcc1 = Crc32.calc(bytearray(recievedmessage, encoding='utf-8')) #kyuki imbuilt crc key int me ata if int(crcc1) == int(crcc): print("Received Message is correct") else: print("Wrong message Recieved") c.send('done'.encode())
def main(): while(True): data = input() #print(data) data = str(data) encryptedmessage = encodedata(data,A) #print(encryptedmessage) """ crcgenerated = CRC(data) """ #comde using inbuilt crc """ 1. pip3 install crccheck 2. from crccheck.crc import Crc32, CrcXmodem """ data = ''.join(format(i, 'b') for i in bytearray(data, encoding ='utf-8')) crcgenerated = Crc32.calc(bytearray(data,encoding = 'utf-8')) message = pickle.dumps(encryptedmessage) crcc = pickle.dumps(crcgenerated) s = socket.socket() port = 5001 #ip = sys.argv[1] s.connect(('127.0.0.1',int(port))) print("Connection established to server") s.send(message) s.send(crcc) s.recv(1023) s.close()
def check_crc(connection, local_file, remote_file): print('Calculating checksum...') response = send_ftp_msg(connection, session=3, opcode=OP_CalcFileCRC32, data=bytearray(remote_file, 'ascii'), wait_resp=True) payload_header = extract_header(response) (opcode, size) = parse_header(payload_header)[2:4] if opcode == OP_Nack: print('Failed to calculate CRC32') print(parse_error(response)) return None data = extract_data(response, size) (remote_crc, ) = struct.unpack("<I", data) f = open(local_file, mode='rb') try: content = f.read() finally: f.close() local_crc = Crc32.calc(content) print('remote\t\tlocal') print('%s\t%s' % (hex(remote_crc)[2:], hex(local_crc)[2:])) return (local_crc == remote_crc)
def __writeSamplePacket(self): if len(self.currentCapture) != len(self.fields): raise Exception('Captured data does not match number of fields.') samplePacket = bytes() # Sample ID samplePacket += struct.pack('<I', self.sampleCounter) # Fields for i in range(0, len(self.fields)): field = self.fields[i] sample = self.currentCapture[i] type = field['type'] data = sample['data'] time = sample['time'] samplePacket += struct.pack('<Hd' + type.format(), i, time, data) # CRC32 samplePacket += struct.pack('<I', Crc32.calc(samplePacket)) self.file.write(samplePacket) self.file.flush() if self.sampleCounter % 500 == 0: subprocess.Popen(['/bin/sync', '-d', self.filename]) # Force changes to disk
def readNext(self): buffer = self.file.read(4) if len(buffer) == 0: return None id = struct.unpack('<I', buffer)[0] if (id != self.sampleCounter): print(id) raise Exception('Sample count out of order. File may be corrupted :(') sample = {'id': id, 'captures': []} for i in range(0, len(self.fields)): field = self.fields[i] type = field['type'] currentBuffer = self.file.read(2) recordedId = struct.unpack_from('<H', currentBuffer)[0] if (recordedId != i): raise Exception('Field captures out of order. File may be corrupted :(') currentBuffer += self.file.read(8 + type.size()) capture = struct.unpack_from('<d' + type.format(), currentBuffer, 2) time = capture[0] data = capture[1] buffer += currentBuffer sample['captures'].append({'time': time, 'data': data}) checksum = struct.unpack('<I', self.file.read(4))[0] if (Crc32.calc(buffer) != checksum): raise Exception('Sample checksum failed! File may be corrupted :('); self.sampleCounter += 1 return sample
def threaded(c): while (True): messageMatrix = c.recv(50000) c.send("Server recieved your msg".encode('utf-8')) if (len(messageMatrix) < 3): continue crcFromClient = c.recv(50000) crcFromClient = crcFromClient.decode() messageMatrix = messageMatrix[:messageMatrix[1:].find(b'\x80')] messageMatrix += b'.' decryptedmessage = pickle.loads(messageMatrix) originalMessage = getOriginaltext(decryptedmessage, A_Inverse) print("Message received from client : ", originalMessage) originalMessage = ''.join( format(i, 'b') for i in bytearray(originalMessage, encoding='utf-8')) crcAtServer = Crc32.calc(bytearray(originalMessage, encoding='utf-8')) if int(crcAtServer) == int(crcFromClient): print( "Received Message is correct. No error is detected during the communication" ) else: print( "Received Message is incorrect. Error is detected during the communication" ) c.send("Transmission over".encode('utf-8')) print("\n\n")
def test_string2(): if sys.version_info < (3, 3, 0): raise SkipTest Crc32.calc("Teststring".encode(), )
def test_string1(): if sys.version_info < (3, 3, 0): raise SkipTest Crc32.calc(b"Teststring")
def test_bytes(): if sys.version_info < (3, 3, 0): raise SkipTest Crc32.calc(bytes.fromhex("12345678909876543210"))
def test_bytearray(): Crc32.calc(bytearray.fromhex("12345678909876543210"))
def test_list2(): Crc32.calc([n for n in range(0, 255)], 123)
def test_list1(): Crc32.calc([n for n in range(0, 255)])
def test_generator(): Crc32.calc((n for n in range(0, 255)))
list1[:] = [x if x != -32 else 27 for x in list1] arr2 = np.reshape(np.array(list1), (3, len(list1) // 3), 'F') print(arr2) return np.dot(A, arr2) s = socket.socket() s.connect((IP, PORT)) while (True): inputMessage = str(input()) encryptedmessage = encodeKar(inputMessage, A) inputMessage = ''.join( format(i, 'b') for i in bytearray(inputMessage, encoding='utf-8')) crcgenerated = Crc32.calc(bytearray(inputMessage, encoding='utf-8')) crcgenerated = str(crcgenerated).encode('utf-8') print("Connection established with server") s.send(pickle.dumps(encryptedmessage)) print(s.recv(1023).decode()) s.send(crcgenerated) print(s.recv(1023).decode()) print("\n\n") s.close()