def test_aes_key_passing(self):
     c = crypto.AES()
     s = crypto.AES(False)
     key = c.GetKey()
     s.LoadKey(key)
     randstring = randomString().encode("utf-8")
     ciphertext = c.Encrypt(randstring)
     self.assertEqual(s.Decrypt(ciphertext), randstring)
Пример #2
0
    def encode(self, K, M):
        const_Bsize = 16
        const_Zero = b'\x00' * 16

        AES_128 = crypto.AES(bytearray(K), MODE_ECB)

        K1, K2 = self.gen_subkey(K)
        n = int(len(M) / const_Bsize)

        if n == 0:
            n = 1
            flag = False
        else:
            if (len(M) % const_Bsize) == 0:
                flag = True
            else:
                n += 1
                flag = False

        M_n = M[(n - 1) * const_Bsize:]
        if flag is True:
            M_last = self.xor_128(M_n, K1)
        else:
            M_last = self.xor_128(self.pad(M_n), K2)

        X = const_Zero
        for i in range(n - 1):
            M_i = M[(i) * const_Bsize:][:16]
            Y = self.xor_128(X, M_i)
            X = AES_128.encrypt(Y)
        Y = self.xor_128(M_last, X)
        T = AES_128.encrypt(Y)
        return T
Пример #3
0
    def encrypt_payload(self, key, direction, mhdr):
        a = []
        a += self.to_clear_raw()
        a += self.compute_mic(key, direction, mhdr)

        cipher = crypto.AES(bytearray(key), MODE_ECB)
        return list(map(int, cipher.decrypt(bytes(a))))
Пример #4
0
    def encrypt_payload(self, key, direction, data):
        k = int(math.ceil(len(data) / 16.0))

        a = []
        for i in range(k):
            a += [0x01]
            a += [0x00, 0x00, 0x00, 0x00]
            a += [direction]
            a += self.mac_payload.get_fhdr().get_devaddr()
            a += self.mac_payload.get_fhdr().get_fcnt()
            a += [0x00]  # fcnt 32bit
            a += [0x00]  # fcnt 32bit
            a += [0x00]
            a += [i+1]

        cipher = crypto.AES(bytearray(key), MODE_ECB)
        s = cipher.encrypt(bytes(a))

        padded_payload = []
        for i in range(k):
            idx = (i + 1) * 16
            padded_payload += (data[idx - 16:idx] + ([0x00] * 16))[:16]

        payload = []
        for i in range(len(data)):
            payload += [s[i] ^ padded_payload[i]]
        return list(map(int, payload))
Пример #5
0
    def derive_appskey(self, key, devnonce):
        a = [0x02]
        a += self.get_appnonce()
        a += self.get_netid()
        a += devnonce
        a += [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]

        cipher = crypto.AES(bytearray(key), MODE_ECB)
        return list(map(int, cipher.encrypt(bytes(a))))
Пример #6
0
	def sendUpdateToGateway(self):
		pkg = struct.pack(_LORA_PKG_FORMAT, self.config['sensorNr'], self.voltage, self.distance, self.remoteGatewayID[0], self.remoteGatewayID[1], self.remoteGatewayID[2], self.remoteGatewayID[3], self.remoteGatewayID[4], self.remoteGatewayID[5], self.ID[0], self.ID[1], self.ID[2], self.ID[3], self.ID[4], self.ID[5])

		iv = os.urandom(16) # crypto.getrandbits(128) returns 0s if WLAN or BT is not enabled
		cipher = crypto.AES(self.config["AESkey"], crypto.AES.MODE_CFB, iv)
		encryptedPkg = iv + cipher.encrypt(pkg)
		#print("voltage:%s" % (self.voltage))

		self.p("LORA", "raw: %s" % str(pkg))
		self.p("LORA", "encrypted: %s" % str(encryptedPkg))

		self.lora_sock.send(encryptedPkg)
Пример #7
0
 def __init__(self, mainqueuerecv, mainqueuesend, interparserqueue):
     super().__init__()
     self.mainqueuerecv = mainqueuerecv #Declare queue from tcp server to get the data
     self.mainqueuesend = mainqueuesend #Declare queue from tcp server to send data
     self.interparserqueue = interparserqueue #Declare queue to get the data from the other parsers
     self.parser_comms = None
     threading.Thread(target=self.GetInterParserQueue).start() #Get interparser queue to send data to other parsers
     threading.Thread(target=self.InterParser).start()
     self.client_rsa = crypto.RSA(True) #Initialize RSA creating a private key
     self.server_rsa = crypto.RSA(False) #Initialize RSA without create a key for future encryption to the server´
     self.aes = crypto.AES(True) #Initialize AES for using after the key exchange
     self.use_rsa = True #Only use RSA on the key exchange
     self.connection_encrypted = False
     self.lastheartbeat = datetime.datetime.now()
     threading.Thread(target=self.Heartbeat).start() #Start Heartbeat thread
     threading.Thread(target=self.HeartbeatTimeout).start() #Start another heartbeat thread if the server dosent respond to exit Carnotaurus 
     self.start() #Start the main parser thread
Пример #8
0
    def decrypt_payload(self, key, direction, mic):
        a = []
        a += self.encrypted_payload
        a += mic

        cipher = crypto.AES(bytearray(key), MODE_ECB)
        self.payload = cipher.encrypt(bytes(a))[:-4]

        self.appnonce = self.payload[:3]
        self.netid = self.payload[3:6]
        self.devaddr = self.payload[6:10]
        self.dlsettings = self.payload[10]
        self.rxdelay = self.payload[11]
        self.cflist = None
        if self.payload[12:]:
            self.cflist = self.payload[12:]

        return list(map(int, self.payload))
Пример #9
0
 def run(self):
     while True:
         datafromtcpserver = self.mainqueuerecv.get() #Get the data from the queue
         data = datafromtcpserver[1]
         addr = datafromtcpserver[0]
         try:
             data.decode("utf-8")
         except UnicodeDecodeError:
             data = self.DecryptData(addr, data)
         logger.debug(data)
         if data == b'conninit':
             self.mainqueuesend.put((addr, b'connrecv'))
             continue
         if data == b'hr':
             self.mainqueuesend.put((addr, b'hrok'))
             continue
         if b'-----BEGIN PUBLIC KEY-----' in data:
             rsa = crypto.RSA(False)
             rsa.LoadPublicKey(data)
             self.client_rsa[str(len(self.client_rsa))] = {'addr': addr, 'rsaobj':rsa, 'cryptocomms': False, 'use_rsa':True, 'aesobj':None}
             self.SendDataToClient(addr, self.server_rsa.GetPublicKey())
             for i in self.client_rsa:
                 if self.client_rsa[i]['addr'] == addr:
                     self.client_rsa[i]['cryptocomms'] = True
             continue
         if b'key' in data and b'iv' in data and b'aesisfkncool' in data:
             for i in self.client_rsa:
                 if self.client_rsa[i]['addr'] == addr:
                     aes = crypto.AES(False) 
                     aes.LoadKey(data) #Try to load the AES key
                     self.client_rsa[i]['aesobj'] = aes 
                     self.client_rsa[i]['use_rsa'] = False #Stop using RSA for encryption and start using AES
                     self.client_rsa[i]['rsaobj'] = None #Delete the RSA key to free up some memory
                     self.SendDataToClient(addr, b'aes_ok') #Send to client that the server accepted the aes key
                     logger.debug("{} is now using encrypted communication".format(addr))
                     break
             continue
         if data.decode("utf-8").startswith("{"): #Redirect all json to interparser queue to process it
             jsondata = json.loads(data.decode("utf-8"))
             to = jsondata['type']
             del jsondata['type']
             jsondata['to'] = to
             jsondata['addr'] = addr
             self.parser_comms.put(jsondata)
Пример #10
0
 def submit(self, event=False):
     try:
         keys = []
         aes = crypto.AES()
         for key in self.parsed:
             keys.append(
                 aes.decrypt(key, aes.keySchedule(self.password.get())))
         if (bytes.fromhex(keys[0][2:]).decode('utf-8').strip('\x00') !=
                 self.username.get()):
             raise Exception()
         try:
             if self.serverIP != self.server.get():
                 soc.connect((self.server.get(), 6969))
                 self.serverIP = self.server.get()
             req = '00|%s|%s' % (binEnc(self.username.get()), keys[1])
             soc.send(req.encode())
             code = int(soc.recv(2056))
             verificationCode = str(
                 pow(code, int(keys[2], 16), int(keys[1], 16)))
             soc.send(verificationCode.encode())
             status = soc.recv(2056)
             if status == b'01':
                 print('Connected')
                 app.key = keys[1:]
                 app.username = self.username.get()
                 app.recipient['state'] = 'readonly'
                 root.title('Private Messaging - ' + self.username.get())
                 threading.Thread(target=app.receive).start()
                 self.master.destroy()
             elif status == b'11':
                 self.status.set(
                     'Connection Failed: Client Already Logged In')
                 self.statusLabel.grid(row=6, columnspan=2)
         except Exception as e:
             print(e)
             self.status.set('Connection Failed: Server Not Found')
             self.statusLabel.grid(row=6, columnspan=2)
     except:
         self.status.set('Connection Failed: Incorrect Credentials')
         self.statusLabel.grid(row=6, columnspan=2)
     return 'break'
Пример #11
0
    def gen_subkey(self, K):
        AES_128 = crypto.AES(bytearray(K), MODE_ECB)

        L = AES_128.encrypt(('\x00' * 16).encode())

        LHigh = unpack('>Q', L[:8])[0]
        LLow = unpack('>Q', L[8:])[0]

        K1High = ((LHigh << 1) | (LLow >> 63)) & 0xFFFFFFFFFFFFFFFF
        K1Low = (LLow << 1) & 0xFFFFFFFFFFFFFFFF

        if (LHigh >> 63):
            K1Low ^= 0x87

        K2High = ((K1High << 1) | (K1Low >> 63)) & 0xFFFFFFFFFFFFFFFF
        K2Low = ((K1Low << 1)) & 0xFFFFFFFFFFFFFFFF

        if (K1High >> 63):
            K2Low ^= 0x87

        K1 = pack('>QQ', K1High, K1Low)
        K2 = pack('>QQ', K2High, K2Low)

        return K1, K2
Пример #12
0
 def generate(self):
     rsa = crypto.RSA()
     aes = crypto.AES()
     bits = int(self.bits['values'][self.bits.current()])
     keys = rsa.generateKey(bits)
     if (self.password.get() != ''):
         password = aes.keySchedule(self.password.get())
         cypher = aes.encrypt(self.username.get().encode('utf-8').hex(),
                              password)
         keyFile = filedialog.asksaveasfile(
             mode='w+',
             defaultextension='ckf',
             title='Select file',
             filetypes=(('Client Key', '*.ckf'), ('All Files', '*.*')))
         for i in range(0, len(cypher), 16):
             keyFile.write(' '.join(cypher[i:i + 16]) + '\n')
         for i in range(2):
             keyFile.write('-' * 47 + '\n')
             keys[i] = aes.encrypt(keys[i][2:], password)
             for j in range(0, len(keys[i]), 16):
                 keyFile.write(' '.join(keys[i][j:j + 16]) + '\n')
         keyFile.close()
         messagebox.showinfo('Successful', 'Key Generated Successfully')
         self.master.destroy()
Пример #13
0
	def gatewayMode(self):
		self.p("INFO", "Starting in LoRa gateway mode")
		self.targetGatewayID = bytearray(6)
		self.sensorID = bytearray(6)
		self.sensorNr = 0
		self.wlan = network.WLAN(mode=network.WLAN.STA, antenna=network.WLAN.INT_ANT)
		self.statusCoT = "STARTING"
		self.lastRequestTime = 0
		self.timeSynchonized = False

		try:
			self.wlan.ifconfig(config='dhcp')
		except Exception as e:
			self.p("WARNING", e)
		self.p("WAN", "Trying to connect to WiFi SSID %s" % (self.config['WiFiSSID']))
		self.wlan.connect(ssid=self.config['WiFiSSID'], auth=(network.WLAN.WPA2, self.config['WiFiPassword']))

		try:
			self.lora = LoRa(mode=LoRa.LORA, frequency=self.config['frequency'], tx_power=int(self.config['powerTX']), bandwidth=self.config['bandwidth'], sf=self.config['spreadingFactor'], coding_rate=self.config['codingRate'], rx_iq=True)
			self.p("INFO", "LoRa radio interface initialized at %sHz with %sdBm TX power, %skHz bandwidth, spreading factor %s and coding rate %s" % (self.config['frequency'], self.config['powerTX'], BANDWIDTH[self.config['bandwidth']], self.config['spreadingFactor'], CODING_RATE[self.config['codingRate']-1]))
		except Exception as e:
			self.p("WARNING", "Error during Lora radio interface initialization: %s" % e)

		self.lora_sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
		self.lora_sock.setblocking(False)

		while True:
			self.now = time.time()

			self.WiFiIsConnected = self.wlan.isconnected()

			if self.WiFiIsConnected and not self.WiFiIsConnectedLast:
				self.p("WAN", "Connected to WiFi SSID %s (IP address %s)" % (self.config['WiFiSSID'], self.wlan.ifconfig()[0]))

			if not self.WiFiIsConnected and self.WiFiIsConnectedLast:
				self.p("WAN", "Disconnected from WiFi SSID %s" % (self.config['WiFiSSID']))

			self.WiFiIsConnectedLast = self.WiFiIsConnected

			if self.WiFiIsConnected:

				if not self.timeSynchonized:
					try:
						self.rtc.ntp_sync("pool.ntp.org")
						self.p("INFO", "Time synchronized")
						self.timeSynchonized = True
					except:
						self.p("WARNING", "Could not synchronize time")

				if self.statusCoT != "STARTUP_FINISHED":
					self.startupPhaseCoT()

			encryptedPkg = self.lora_sock.recv(512)
			if len(encryptedPkg) > 0:
				if len(encryptedPkg) == 31:
					cipher = crypto.AES(self.config["AESkey"], crypto.AES.MODE_CFB, encryptedPkg[:16])
					recv_pkg = cipher.decrypt(encryptedPkg[16:])

					self.sensorNr, self.voltage, self.distance, self.targetGatewayID[0], self.targetGatewayID[1], self.targetGatewayID[2], self.targetGatewayID[3], self.targetGatewayID[4], self.targetGatewayID[5], self.sensorID[0], self.sensorID[1], self.sensorID[2], self.sensorID[3], self.sensorID[4], self.sensorID[5] = struct.unpack(_LORA_PKG_FORMAT, recv_pkg)

					if self.IDhex == str(binascii.hexlify(self.targetGatewayID))[2:-1]:
						self.p("INFO", "Sensor Nr:%s Sensor ID:%s Target GW:%s > Voltage:%sV Distance:%scm RSSI:%sdBm SNR:%sdB" % (self.sensorNr, str(binascii.hexlify(self.sensorID))[2:-1], str(binascii.hexlify(self.targetGatewayID))[2:-1], self.voltage, self.distance, self.lora.stats()[1], self.lora.stats()[2]))

						if self.statusCoT == "STARTUP_FINISHED":
							self.sendMeasurementToCoT(self.sensorNr, self.distance, self.voltage)

				else:
					self.p("WARNING", "Unexpected lenght of LoRa message: %sbytes (%s)" % (len(encryptedPkg), encryptedPkg))

			gc.collect()
 def test_aes_decrypt_bytes_only(self):
     c = crypto.AES()
     with self.assertRaises(TypeError):
         c.Decrypt(randomString())
 def test_aes(self):
     c = crypto.AES()
     randstring = randomString().encode("utf-8")
     ciphertext = c.Encrypt(randstring)
     self.assertEqual(c.Decrypt(ciphertext), randstring)