コード例 #1
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)
コード例 #2
0
    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()
コード例 #3
0
ファイル: Ccrypto.py プロジェクト: JoffreyHerard/Stage_2018
 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
コード例 #4
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
コード例 #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
 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)
コード例 #7
0
 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
コード例 #8
0
 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)
コード例 #9
0
    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
コード例 #10
0
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)
コード例 #11
0
def encrypt(send_pkg):
    cipher = AES(key, AES.MODE_CFB, iv)
    send_pkg = iv + cipher.encrypt(send_pkg)
    return (send_pkg)
コード例 #12
0
ファイル: main.py プロジェクト: waheb2020/ts-lora
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()
コード例 #13
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()
コード例 #14
0
 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))