def getGateway(seq=0): sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) sock.settimeout(SETUP_ACK_TIMEOUT) msg = struct.pack(SETUP_FORMAT, BROADCAST, ID, seq) IV = getrandbits(128) CIPHER = AES(KEY, AES.MODE_CFB, IV) msg = IV + CIPHER.encrypt(msg) wait_for_ack = True errors_count = 0 while wait_for_ack and errors_count < SETUP_ACK_RETRIES: sock.send(msg) try: ack = sock.recv(16 + struct.calcsize(SETUP_ACK_FORMAT)) if len(ack): tmp_cipher = AES(GATEWAY_KEY, AES.MODE_CFB, ack[:16]) ack = tmp_cipher.decrypt(ack[16:]) id, gateway, ack_seq = struct.unpack(SETUP_ACK_FORMAT, ack) if id == ID and ack_seq == seq: wait_for_ack = False else: LOG.warning('Recieved message not mine: {} {} {}'.format( id, gateway, ack_seq)) except TimeoutError: errors_count += 1 if errors_count == SETUP_ACK_RETRIES: LOG.error('Message couldn\'t be sended. Switching off.') sock.close() sys.exit(-1) else: time.sleep(5) time.sleep(2) sock.close() LOG.info('My gateway is {0}'.format(gateway)) return gateway
def recieveData(): sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) sock.setblocking(False) time0 = time.time() while (time.time() - time0 < RECIEVING_WAIT_TIME): data = sock.recv(16 + struct.calcsize(DATA_FORMAT)) if data: tmp_cipher = AES(NODE_KEY, AES.MODE_CFB, data[:16]) data = tmp_cipher.decrypt(data[16:]) if len(data) == struct.calcsize(DATA_FORMAT): id, node, data_seq, temp, hum, soil = struct.unpack( DATA_FORMAT, data) if id == ID: sendData(temp, hum, soil) msg = struct.pack(DATA_ACK_FORMAT, node, data_seq) IV = getrandbits(128) CIPHER = AES(KEY, AES.MODE_CFB, IV) msg = IV + CIPHER.encrypt(msg) sock.send(msg) else: LOG.warning('Message not mine: {} {} {} {} {}'.format( id, node, data_seq, temp, hum, soil)) elif len(data) == struct.calcsize(SETUP_FORMAT): id, node, data_seq = struct.unpack(SETUP_FORMAT, data) msg = struct.pack(SETUP_ACK_FORMAT, node, ID, data_seq) IV = getrandbits(128) CIPHER = AES(KEY, AES.MODE_CFB, IV) msg = IV + CIPHER.encrypt(msg) sock.send(msg) time.sleep_ms(50)
def sendData(data, seq): sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) sock.settimeout(SETUP_ACK_TIMEOUT) msg = struct.pack(DATA_FORMAT, GATEWAY, ID, seq, data[0], data[1], data[2]) IV = getrandbits(128) CIPHER = AES(KEY, AES.MODE_CFB, IV) msg = IV + CIPHER.encrypt(msg) wait_for_ack = True errors_count = 0 while wait_for_ack and errors_count < DATA_ACK_RETRIES: sock.send(msg) LOG.debug('Data sended: {} as temp, {} as hum, {} as soil hum'.format( data[0], data[1], data[2])) try: ack = sock.recv(16 + struct.calcsize(DATA_ACK_FORMAT)) if len(ack): tmp_cipher = AES(GATEWAY_KEY, AES.MODE_CFB, ack[:16]) ack = tmp_cipher.decrypt(ack[16:]) id, ack_seq = struct.unpack(DATA_ACK_FORMAT, ack) if id == ID and ack_seq == seq: wait_for_ack = False LOG.info('Message sended successfully.') else: LOG.warning('Recieved message not mine: {} {}'.format( id, ack_seq)) except TimeoutError: errors_count += 1 if errors_count == DATA_ACK_RETRIES: LOG.error('Message couldn\'t be sended. Switching off.') sock.close() sys.exit(-1) else: time.sleep(5) time.sleep(2) sock.close()
def crypt(self, data): iv = crypto.getrandbits( 128) # hardware generated random IV (never reuse it) cipher = AES(self.key, AES.MODE_CFB, iv) msg = iv + cipher.encrypt(data) print(msg) return msg
def reciveData(self): self.s.setblocking(False) msg = self.s.recv(128) #Get any data recieved #If there's any data, decrypt if (len(msg) > 0): try: #print("encriptat: ",msg) cipher = AES(self.key, AES.MODE_CFB, msg[:16]) # on the decryption side original = cipher.decrypt(msg[16:]) print("original ", original) if "Config" in original or "stop" in original or "Discover" in original or "Hello" in original or "Info" in original or "Token" in original or "Alarm" in original: crc_OK, msg = self.check_crc(original) if crc_OK: return (msg) else: print("CRC not OK") return ("error") else: return ("error") except Exception as e: print(e) return ("error") else: return ("error")
def _send_with_session(self, to, session, msg_type, data): print("_send:", to._unit_addr, msg_type, session, to._counter_send, data) if session == None: raise Exception('No session') plain = bytearray() plain.append(to._unit_addr) plain.append(self._unit_addr) plain.append(msg_type) plain.extend(session) plain.extend(struct.pack('>H', to._counter_send)) if data: plain.append(len(data)) plain.extend(data) else: plain.append(0) plain.extend(CRC.crc16(plain)) pads = (16 - (len(plain) % 16)) % 16 plain.extend(pads * '=') print("sending:", plain) iv = crypto.getrandbits(32)[:2] aes = AES(self._crypto_key, AES.MODE_CBC, iv * 8) self._sock.send(self._site_id + iv + aes.encrypt(plain)) to._counter_send = (to._counter_send + 1) % 0x10000 if to._counter_send == 0: print("Reset after counter overflow") to._reset_trial = 0 to._reset_next = time.ticks_ms()
def reciveData(self,rtc,f): self.s.setblocking(False) msg=self.s.recv(128)#Get any data recieved #If there's any data, decrypt if (len(msg)>0): try: #print("encriptat: ",msg) cipher = AES(self.key, AES.MODE_CFB, msg[:16]) # on the decryption side original = cipher.decrypt(msg[16:]) print("original ",original) if "Config" in original or "stop" in original or "Discover" in original or "Hello" in original or "Info" in original or "Token" in original or "Alarm" in original or "Hay" in original: crc_OK,msg=self.check_crc(original) if crc_OK: f=open('msg_received_middle2.txt','a') f.write("{}/{}/{} {}:{}:{} msg {} stats {}\n".format(rtc.now()[2],rtc.now()[1],rtc.now()[0],rtc.now()[3],rtc.now()[4],rtc.now()[5],msg,self.lora.stats())) f.close() return(msg) else: print("CRC not OK") return("error") else: return("error") except Exception as e: print(e) return("error") else: return("error")
def decrypt(self, data): iv = crypto.getrandbits( 128) # hardware generated random IV (never reuse it) cipher = AES(self.key, AES.MODE_CFB, data[:16]) # on the decryption side original = cipher.decrypt(data[16:]) print(original) return original
def sendData(self, misg): self.s.setblocking(True) iv = crypto.getrandbits( 128) # hardware generated random IV (never reuse it) cipher = AES(self.key, AES.MODE_CFB, iv) msg = iv + cipher.encrypt(misg) self.s.send(msg) self.s.setblocking(False)
def _encrypt(self, id, message): gc.collect() try: iv = crypto.getrandbits(128) cipher = AES(self._module['metrics'][id]['key'].encode('utf-8'), AES.MODE_CFB, iv) return b2a_base64(iv + cipher.encrypt(message.encode('utf-8'))).decode('utf-8') except: print("ERROR encrypting message for metric: " + str(id) + " of sensor " + str(self._module['name']) + ". Cannot proceed!") return None
def sendData(self,msg,rtc,f): f=open('msg_sent_middle2.txt','a') f.write("{}/{}/{} {}:{}:{} msg {} stats {}\n".format(rtc.now()[2],rtc.now()[1],rtc.now()[0],rtc.now()[3],rtc.now()[4],rtc.now()[5],msg,self.lora.stats())) f.close() self.s.setblocking(True) iv = crypto.getrandbits(128) # hardware generated random IV (never reuse it) cipher = AES(self.key, AES.MODE_CFB, iv) misg_crc=msg+" "+str(self.calculate_crc(msg)) msg = iv + cipher.encrypt(misg_crc) self.s.send(msg) self.s.setblocking(False)
def reciveData(self): self.s.setblocking(False) msg=self.s.recv(128)#Get any data recieved #If there's any data, decrypt if len(msg)>0: print("encriptat: ",msg) cipher = AES(self.key, AES.MODE_CFB, msg[:16]) # on the decryption side original = cipher.decrypt(msg[16:]) print("original ",original) return(original) else: return
def decode(self, data): counter = data[self.iv_layer]["ctr"] cipher = AES(self.enc_key, AES.MODE_CTR, None, counter) ciphertext = b"" for item in self.dec_attr_generator(data): ciphertext += item plaintext = cipher.decrypt(ciphertext) self.update_dec_data(data, plaintext) return data
def encode(self, data): counter = getrandbits(128) data[self.iv_layer][-1] = counter cipher = AES(self.enc_key, AES.MODE_CTR, None, counter) plaintext = b"" for item in self.enc_attr_generator(data): plaintext += item ciphertext = cipher.encrypt(plaintext) self.update_enc_data(data, ciphertext) return data
def _recv(self): while True: p = self._sock.recv(128) p_len = len(p) if p_len == 0: break print("recv:", p) site_id_len = len(self._site_id) if (p_len >= (site_id_len + 16) and p[:site_id_len] == self._site_id): iv = p[site_id_len:2 + site_id_len] * 8 aes = AES(self._crypto_key, AES.MODE_CBC, iv) plain = aes.decrypt(p[2 + site_id_len:]) print("plain:", plain) to_addr = plain[0] from_addr = plain[1] if to_addr == from_addr: print("Error: from == to") return msg_type = plain[2] sent_session = plain[3:11] sent_counter = struct.unpack('>H', plain[11:13])[0] data_len = plain[13] if data_len > 0: data = plain[14:14 + data_len] else: data = None crc = plain[14 + data_len:14 + data_len + 2] if crc != CRC.crc16(plain[:14 + data_len]): print("Error: crc") return if self._unit_addr == to_addr: sender = self._nodes[from_addr] if sender: sender._lora_stats = self._lora.stats() self._process_message(sender, msg_type, sent_session, sent_counter, data)
def send(clearSend): key = encryptionKey iv = bytes(map(ord, accessToken[0:16])) if len(clearSend) % 16 != 0: pad = 16 - (len(clearSend) % 16) clearSend = clearSend + (pad * chr(pad)) #pad PKCS#7 cryptor = AES(key, AES.MODE_CBC, iv) ciphertext = cryptor.encrypt(clearSend) toSend = binascii.b2a_base64(ciphertext)[:-1] a = urequests.post("http://" + serverAddress + ':' + str(serverPort) + '/exchange', headers={ "Connection": "close", "Content-Type": "text/plain", "User-Agent": "iotway-product", "Host": serverAddress, "Authorization": "Bearer " + productId }, data=toSend)
# Simple example for working with encrypting data # import sys # First, make sure this is running on a WiPy (pycom) try: import pycom from crypto import AES except ImportError: print("ERROR: not on a WiPy (or Pycom) board!") sys.exit(-1) # Setup encryption using simple, basic encryption # NOTICE: you normally would protect this key! my_key = b'monkeybreadyummy' # 128 bit (16 bytes) key cipher = AES(my_key, AES.MODE_ECB) # Create the file and encrypt the data new_file = open("secret_log.txt", "w") # use "write" mode new_file.write(cipher.encrypt("1,apples,2.5 \n")) # write some data new_file.write(cipher.encrypt("2,oranges,1 \n")) # write some data new_file.write(cipher.encrypt("3,peaches,3 \n")) # write some data new_file.write(cipher.encrypt("4,grapes,21 \n")) # write some data new_file.close() # close the file # Step 2: Open the file and read data old_file = open("secret_log.txt", "r") # use "read" mode # Use a loop to read all rows in the file for row in old_file.readlines(): data = cipher.decrypt(row).decode('ascii') columns = data.strip("\n").split(",") # split row by commas
def decrypt(recv_pkg): cipher = AES(key, AES.MODE_CFB, recv_pkg[:16]) # on the decryption side recv_pkg = cipher.decrypt(recv_pkg[16:]) return (recv_pkg)
def encrypt(send_pkg): cipher = AES(key, AES.MODE_CFB, iv) send_pkg = iv + cipher.encrypt(send_pkg) return (send_pkg)
def _crypt(self, data, key): """Crypt a data with the key, key. add the iv at the beginning of the message""" iv = crypto.getrandbits(128) cipher = AES(key, AES.MODE_CFB, iv) return (iv + cipher.encrypt(data))
def _decrypt(self, data, key): """Decrypt a message""" print(data[:16]) cipher = AES(key, AES.MODE_CFB, data[:16]) return (cipher.decrypt(data[16:]))
def join_request(_sf): global lora global DevEUI global lora_sock global active_tx global active_rx global my_slot global AppKey global DevNonce global AppSKey rmsg = DevEUI+":"+JoinEUI+":"+str(DevNonce)+":"+str(_sf) pkg = struct.pack(_LORA_PKG_FORMAT % len(rmsg), MY_ID, len(rmsg), rmsg) i = 0 while (i == 0): pycom.rgbled(blue) lora.init(mode=LoRa.LORA, tx_iq=True, region=LoRa.EU868, frequency=freqs[0], power_mode=LoRa.TX_ONLY, bandwidth=LoRa.BW_125KHZ, sf=12, tx_power=7) start = time.ticks_us() # while(lora.ischannel_free(-90) == False): # time.sleep(1) lora_sock.send(pkg) active_tx += time.ticks_us()-start print("Request sent!", pkg) time.sleep_ms(100) lora_sock.setblocking(True) lora.init(mode=LoRa.LORA, rx_iq=True, region=LoRa.EU868, frequency=freqs[1], power_mode=LoRa.ALWAYS_ON, bandwidth=LoRa.BW_125KHZ, sf=12) start = time.ticks_us() pycom.rgbled(green) lora_sock.settimeout(5) try: while (True): recv_pkg = lora_sock.recv(50) if (len(recv_pkg) > 2): recv_pkg_len = recv_pkg[1] recv_pkg_id = recv_pkg[0] if (int(recv_pkg_id) == 1): dev_id, leng, rmsg = struct.unpack(_LORA_RCV_PKG_FORMAT % recv_pkg_len, recv_pkg) print('Device: %d - Pkg: %s' % (dev_id, rmsg)) rmsg = str(rmsg)[2:] rmsg = rmsg[:-1] (dev_id, DevAddr, JoinNonce) = str(rmsg).split(":") if (int(dev_id) == int(MY_ID)): pycom.rgbled(blue) lora.power_mode(LoRa.SLEEP) active_rx += time.ticks_us()-start start = -10000 i = 1 break except: if (i == 0): lora.power_mode(LoRa.SLEEP) active_rx += time.ticks_us()-start random_sleep(5) DevNonce += 1 # AppSKey generation text = "".join( [AppKey[:2], JoinNonce, JoinEUI, str(DevNonce)] ) while (len(str(text)) < 32): text = "".join([str(text),"0"]) encryptor = AES(AppKey, AES.MODE_ECB) AppSKey = encryptor.encrypt(binascii.unhexlify(text)) # slot generation text = "".join([DevAddr, DevEUI]) thash = uhashlib.sha256() thash.update(text) thash = int(ubinascii.hexlify(thash.digest()), 16) my_slot = thash % S print("Slot =", my_slot, "DevAddr = ", DevAddr) print("joining the network lasted (s):", (time.ticks_us()-join_start)/1e6) sync()