コード例 #1
0
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
コード例 #2
0
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)
コード例 #3
0
 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")
コード例 #4
0
 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")
コード例 #5
0
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()
コード例 #6
0
ファイル: Ccrypto.py プロジェクト: JoffreyHerard/Stage_2018
 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
コード例 #7
0
 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
コード例 #8
0
    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
コード例 #9
0
    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)
コード例 #10
0
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)
コード例 #11
0
# 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
    print(" : ".join(columns))  # print the row with colon separator

old_file.close()
コード例 #12
0
 def _decrypt(self, data, key):
     """Decrypt a message"""
     print(data[:16])
     cipher = AES(key, AES.MODE_CFB, data[:16])
     return (cipher.decrypt(data[16:]))