def test_cfb128_aes192_f315(): """ From NIST special publication 800-38A, section F.3.15 """ key_str = '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b' iv_str = '000102030405060708090a0b0c0d0e0f' pt_str = ('6bc1bee22e409f96e93d7e117393172a' 'ae2d8a571e03ac9c9eb76fac45af8e51' '30c81c46a35ce411e5fbc1191a0a52ef' 'f69f2445df4f9b17ad2b417be66c3710') ct_str = ('cdc80d6fddf18cab34c25909c99a4174' '67ce7f7f81173621961a2b70171d3d7a' '2e1e8a1dd59b88b1c8e60fed1efac4c9' 'c05f9f9ca9834fa042ae8fba584b09ff') key_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', key_str)]) iv_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', iv_str)]) pt_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', pt_str)]) pt_copy = copy.copy(pt_bytes) ct_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', ct_str)]) aes_cfb = AES(mode='cfb', key=key_bytes, iv=iv_bytes) aes_cfb.encrypt(pt_bytes) assert pt_bytes == ct_bytes, "AES CFB mode encryption failure" aes_cfb.reset() aes_cfb.decrypt(pt_bytes) assert pt_bytes == pt_copy, "AES CFB mode decryption failure"
def test_wrong_input(self, key, data): with self.assertRaises(TypeError, msg='You should handle wrong input'): a = AES(key) plaintext = data encrypted = a.encrypt(plaintext) a.decrypt(encrypted)
def test_ofb_aes256_f46(): """ From NIST special publication 800-38A, section F.4.6 """ key_str = '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4' iv_str = '000102030405060708090a0b0c0d0e0f' ct_str = ( 'dc7e84bfda79164b7ecd8486985d3860' '4febdc6740d20b3ac88f6ad82a4fb08d' '71ab47a086e86eedf39d1c5bba97c408' '0126141d67f37be8538f5a8be740e484' ) pt_str = ( '6bc1bee22e409f96e93d7e117393172a' 'ae2d8a571e03ac9c9eb76fac45af8e51' '30c81c46a35ce411e5fbc1191a0a52ef' 'f69f2445df4f9b17ad2b417be66c3710' ) key_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', key_str)]) iv_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', iv_str)]) ct_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', ct_str)]) ct_copy = copy.copy(ct_bytes) pt_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', pt_str)]) aes_ofb = AES(mode='ofb', key=key_bytes, iv=iv_bytes) aes_ofb.decrypt(ct_bytes) assert ct_bytes == pt_bytes, "AES OFB mode encryption failure" aes_ofb.reset() aes_ofb.encrypt(ct_bytes) assert ct_bytes == ct_copy, "AES OFB mode decryption failure"
def test_cfb128_aes192_f315(): """ From NIST special publication 800-38A, section F.3.15 """ key_str = '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b' iv_str = '000102030405060708090a0b0c0d0e0f' pt_str = ( '6bc1bee22e409f96e93d7e117393172a' 'ae2d8a571e03ac9c9eb76fac45af8e51' '30c81c46a35ce411e5fbc1191a0a52ef' 'f69f2445df4f9b17ad2b417be66c3710' ) ct_str = ( 'cdc80d6fddf18cab34c25909c99a4174' '67ce7f7f81173621961a2b70171d3d7a' '2e1e8a1dd59b88b1c8e60fed1efac4c9' 'c05f9f9ca9834fa042ae8fba584b09ff' ) key_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', key_str)]) iv_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', iv_str)]) pt_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', pt_str)]) pt_copy = copy.copy(pt_bytes) ct_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', ct_str)]) aes_cfb = AES(mode='cfb', key=key_bytes, iv=iv_bytes) aes_cfb.encrypt(pt_bytes) assert pt_bytes == ct_bytes, "AES CFB mode encryption failure" aes_cfb.reset() aes_cfb.decrypt(pt_bytes) assert pt_bytes == pt_copy, "AES CFB mode decryption failure"
def test_cbc_128_f21(): """ Verify that 4-block CBC encryption works From NIST special publication 800-38A, section F.2.1 """ key_str = '2b7e151628aed2a6abf7158809cf4f3c' iv_str = '000102030405060708090a0b0c0d0e0f' pt_str = ('6bc1bee22e409f96e93d7e117393172a' 'ae2d8a571e03ac9c9eb76fac45af8e51' '30c81c46a35ce411e5fbc1191a0a52ef' 'f69f2445df4f9b17ad2b417be66c3710') ct_str = ('7649abac8119b246cee98e9b12e9197d' '5086cb9b507219ee95db113a917678b2' '73bed6b8e3c1743b7116e69e22229516' '3ff1caa1681fac09120eca307586e1a7') key_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', key_str)]) iv_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', iv_str)]) pt_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', pt_str)]) pt_copy = copy.copy(pt_bytes) ct_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', ct_str)]) aes_cbc = AES(mode='cbc', key=key_bytes, iv=iv_bytes) aes_cbc.encrypt(pt_bytes) assert pt_bytes == ct_bytes, "AES CBC mode encryption failure" aes_cbc.reset() aes_cbc.decrypt(pt_bytes) assert pt_bytes == pt_copy, "AES CBC mode decryption failure"
def test_ctr_aes192_f53(): """ From NIST special publication 800-38A, section F.5.3 """ key_str = '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b' counter_str = 'f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff' pt_str = ( '6bc1bee22e409f96e93d7e117393172a' 'ae2d8a571e03ac9c9eb76fac45af8e51' '30c81c46a35ce411e5fbc1191a0a52ef' 'f69f2445df4f9b17ad2b417be66c3710' ) ct_str = ( '1abc932417521ca24f2b0459fe7e6e0b' '090339ec0aa6faefd5ccc2c6f4ce8e94' '1e36b26bd1ebc670d1bd1d665620abf7' '4f78a7f6d29809585a97daec58c6b050' ) key_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', key_str)]) counter_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', counter_str)]) pt_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', pt_str)]) pt_copy = copy.copy(pt_bytes) ct_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', ct_str)]) aes_ctr = AES(mode='ctr', key=key_bytes, iv=counter_bytes) aes_ctr.encrypt(pt_bytes) assert pt_bytes == ct_bytes, "AES CTR mode encryption failure" aes_ctr.reset() aes_ctr.decrypt(pt_bytes) assert pt_bytes == pt_copy, "AES CTR mode decryption failure"
def test_cbc_128_f21(): """ Verify that 4-block CBC encryption works From NIST special publication 800-38A, section F.2.1 """ key_str = '2b7e151628aed2a6abf7158809cf4f3c' iv_str = '000102030405060708090a0b0c0d0e0f' pt_str = ( '6bc1bee22e409f96e93d7e117393172a' 'ae2d8a571e03ac9c9eb76fac45af8e51' '30c81c46a35ce411e5fbc1191a0a52ef' 'f69f2445df4f9b17ad2b417be66c3710' ) ct_str = ( '7649abac8119b246cee98e9b12e9197d' '5086cb9b507219ee95db113a917678b2' '73bed6b8e3c1743b7116e69e22229516' '3ff1caa1681fac09120eca307586e1a7' ) key_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', key_str)]) iv_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', iv_str)]) pt_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', pt_str)]) pt_copy = copy.copy(pt_bytes) ct_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', ct_str)]) aes_cbc = AES(mode='cbc', key=key_bytes, iv=iv_bytes) aes_cbc.encrypt(pt_bytes) assert pt_bytes == ct_bytes, "AES CBC mode encryption failure" aes_cbc.reset() aes_cbc.decrypt(pt_bytes) assert pt_bytes == pt_copy, "AES CBC mode decryption failure"
def test_ctr_aes192_f53(): """ From NIST special publication 800-38A, section F.5.3 """ key_str = '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b' counter_str = 'f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff' pt_str = ('6bc1bee22e409f96e93d7e117393172a' 'ae2d8a571e03ac9c9eb76fac45af8e51' '30c81c46a35ce411e5fbc1191a0a52ef' 'f69f2445df4f9b17ad2b417be66c3710') ct_str = ('1abc932417521ca24f2b0459fe7e6e0b' '090339ec0aa6faefd5ccc2c6f4ce8e94' '1e36b26bd1ebc670d1bd1d665620abf7' '4f78a7f6d29809585a97daec58c6b050') key_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', key_str)]) counter_bytes = bytearray( [int(v, 16) for v in re.findall(r'..?', counter_str)]) pt_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', pt_str)]) pt_copy = copy.copy(pt_bytes) ct_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', ct_str)]) aes_ctr = AES(mode='ctr', key=key_bytes, iv=counter_bytes) aes_ctr.encrypt(pt_bytes) assert pt_bytes == ct_bytes, "AES CTR mode encryption failure" aes_ctr.reset() aes_ctr.decrypt(pt_bytes) assert pt_bytes == pt_copy, "AES CTR mode decryption failure"
def test_ofb_aes256_f46(): """ From NIST special publication 800-38A, section F.4.6 """ key_str = '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4' iv_str = '000102030405060708090a0b0c0d0e0f' ct_str = ('dc7e84bfda79164b7ecd8486985d3860' '4febdc6740d20b3ac88f6ad82a4fb08d' '71ab47a086e86eedf39d1c5bba97c408' '0126141d67f37be8538f5a8be740e484') pt_str = ('6bc1bee22e409f96e93d7e117393172a' 'ae2d8a571e03ac9c9eb76fac45af8e51' '30c81c46a35ce411e5fbc1191a0a52ef' 'f69f2445df4f9b17ad2b417be66c3710') key_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', key_str)]) iv_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', iv_str)]) ct_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', ct_str)]) ct_copy = copy.copy(ct_bytes) pt_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', pt_str)]) aes_ofb = AES(mode='ofb', key=key_bytes, iv=iv_bytes) aes_ofb.decrypt(ct_bytes) assert ct_bytes == pt_bytes, "AES OFB mode encryption failure" aes_ofb.reset() aes_ofb.encrypt(ct_bytes) assert ct_bytes == ct_copy, "AES OFB mode decryption failure"
def __handleDecryptClick(self): try: if (len(self.__output.toPlainText()) > 0): self.__output.document().clear() aes = AES(self.__keyEdit.text(), self.__msgEdit.text()) aes.decrypt() self.__output.document().setPlainText(aes.getOutput()) except: pass
def _test_ecb(test_vals, test_key): for pt_str, ct_str in test_vals: pt_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', pt_str)]) pt_copy = copy.copy(pt_bytes) ct_bytes = bytearray([int(v, 16) for v in re.findall(r'..?', ct_str)]) aes_ecb = AES(mode='ecb', key=test_key) aes_ecb.encrypt(pt_bytes) assert pt_bytes == ct_bytes, "AES ECB mode encryption failure" aes_ecb.decrypt(pt_bytes) assert pt_bytes == pt_copy, "AES ECB mode decryption failure"
def cbc_decrypted(key, cyphertext, file_name): aes_object = AES(key) iv = cyphertext[:16] iv_previous = iv blocks_arr = split_blocks(cyphertext[16:]) with open(file_name, 'ab') as fo_dec: for block in blocks_arr[:-1]: iv_x = aes_object.decrypt(block) plaintext = bytes_xor(iv_x, iv_previous) fo_dec.write(plaintext) iv_previous = block iv_x = aes_object.decrypt(blocks_arr[-1]) plaintext = bytes_xor(iv_x, iv_previous) fo_dec.write(unpad(plaintext)) print("File was decrypted successfully by CBC MODE")
class AES_TEST(unittest.TestCase): def setUp(self): master_key = 0x2b7e151628aed2a6abf7158809cf4f3c self.AES = AES(master_key) def test_decryption(self): global plaintext ciphertext = self.AES.encrypt(plaintext) decrypted = self.AES.decrypt(ciphertext) self.assertEqual(plaintext)
def test_system(self, key, data): a = AES(int(hex(key), 16)) plaintext = data encrypted = a.encrypt(plaintext) decrypted = a.decrypt(encrypted) self.assertFalse(encrypted == decrypted, 'Data is not encrypted') self.assertEqual( decrypted, data, 'Something is wrong with encryption - decryption process')
def test_system(key, data): """ Encrypt and decrypt @key and @data """ a = AES(key) plaintext = data encrypted = a.encrypt(plaintext) decrypted = a.decrypt(encrypted) # check if data is encrypted assert encrypted != decrypted, 'Data is not encrypted!' return decrypted
class AES_TEST(unittest.TestCase): def setUp(self): master_key = 0x2b7e151628aed2a6abf7158809cf4f3c self.AES = AES(master_key) def test_encryption(self): plaintext = 0x3243f6a8885a308d313198a2e0370734 encrypted = self.AES.encrypt(plaintext) self.assertEqual(encrypted, 0x3925841d02dc09fbdc118597196a0b32) def test_decryption(self): ciphertext = 0x3925841d02dc09fbdc118597196a0b32 decrypted = self.AES.decrypt(ciphertext) self.assertEqual(decrypted, 0x3243f6a8885a308d313198a2e0370734)
def rcvAESmsg(): """ 接收AES加密的消息并解密保存在plaintext.txt """ jsonmsg = flask.request.get_json(force=True) rcvMsg = jsonmsg['AEScipherInt'] aesdecryp = AES(app.config['aesKey']) plainTextInt = aesdecryp.decrypt(rcvMsg) plainText = plainTextInt.to_bytes(128, 'big', signed=False).decode('utf-8') plainText = plainText.lstrip(b'\x00'.decode('utf-8')) with open('./plaintext.txt', 'w') as fileObj: fileObj.write(plainText) return 'Get message', 201
def get_challenge_response(self, challenge, secret_style, salt): m = hashlib.sha256() m.update(BotClient.get_shared_secret(self.password, secret_style, salt)) digest = m.digest() key = [digest[0:16], digest[16:32]] for i in range(2): key[i] = array('B', key[i]).tolist() aes = AES() challenge = aes.decrypt(challenge, key[1], 16) challenge = aes.decrypt(challenge, key[0], 16) r = unpack('>i', pack('BBBB', challenge[0], challenge[1], challenge[2], challenge[3]))[0] + 1 response = array('B', pack('>i', r)).tolist() while len(response) < 16: response.append(0) response = aes.encrypt(response, key[0], 16) response = aes.encrypt(response, key[1], 16) return response
def cbc_decrypt(cache, cipher, inv=None): if cache is None: raise ValueError('Key cache is NULL.') elif cipher is None: raise ValueError('Ciphertext is NULL.') else: aes = AES() nbr_rounds = 0 esize = len(cache) if esize == aes.ekeySize['SIZE_128']: nbr_rounds = 10 elif esize == aes.ekeySize['SIZE_192']: nbr_rounds = 12 elif esize == aes.ekeySize['SIZE_256']: nbr_rounds = 14 else: raise ValueError('Expanded key has size incorrect.' 'Size should be 176, 208, or either 240 bytes.') # the AES input/output ciphertext = [] iput = [] output = [] plaintext = [0] * 16 # the output plain text string string_out = bytes() if inv is None: inv = [0] * 16 # char firstRound first_round = True if cipher != None: for j in range(int(math.ceil(float(len(cipher))/16))): start = j * 16 end = start + 16 if j * 16 + 16 > len(cipher): end = len(cipher) ciphertext = cipher[start:end] output = aes.decrypt(ciphertext, cache, nbr_rounds) for i in range(16): if first_round: plaintext[i] = inv[i] ^ output[i] else: plaintext[i] = iput[i] ^ output[i] first_round = False string_out += struct.pack('B' *len(plaintext), *plaintext) iput = ciphertext return string_out
def cbc_decrypt(cache, cipher, inv=None): if cache is None: raise ValueError('Key cache is NULL.') elif cipher is None: raise ValueError('Ciphertext is NULL.') else: aes = AES() nbr_rounds = 0 esize = len(cache) if esize == aes.ekeySize['SIZE_128']: nbr_rounds = 10 elif esize == aes.ekeySize['SIZE_192']: nbr_rounds = 12 elif esize == aes.ekeySize['SIZE_256']: nbr_rounds = 14 else: raise ValueError('Expanded key has size incorrect.' 'Size should be 176, 208, or either 240 bytes.') # the AES input/output ciphertext = [] iput = [] output = [] plaintext = [0] * 16 # the output plain text string string_out = bytes() if inv is None: inv = [0] * 16 # char firstRound first_round = True if cipher != None: for j in range(int(math.ceil(float(len(cipher)) / 16))): start = j * 16 end = start + 16 if j * 16 + 16 > len(cipher): end = len(cipher) ciphertext = cipher[start:end] output = aes.decrypt(ciphertext, cache, nbr_rounds) for i in range(16): if first_round: plaintext[i] = inv[i] ^ output[i] else: plaintext[i] = iput[i] ^ output[i] first_round = False string_out += struct.pack('B' * len(plaintext), *plaintext) iput = ciphertext return string_out
def DecryptData(cipherText, HandlerAESKey, Server): AESfunct = AES(HandlerAESKey) stringOfCipherText = str(hex(cipherText)) stringOfCipherText = stringOfCipherText[2:] listOfBlocks = textwrap.wrap(stringOfCipherText, 32) decryptedString = "0x" i = 0 for x in listOfBlocks: #print("Decrypting Block %d = "%i,x) xHex = int(x, 16) decryptedData = AES.decrypt(AESfunct, xHex) tempStr = str(hex(decryptedData)) tempStr = tempStr[2:] decryptedString += tempStr i += 1 temp = binascii.unhexlify(((str('%00x' % int(decryptedString, 16))))) tempDecoded = str(temp, 'utf-8')[:] Server.Evidence = tempDecoded return 0
from binascii import hexlify from aes import AES # AES import os # urandom plaintext = 'this is an arbitrary string' # Quick check that we can indeed encrypt any standard ASCII padding = ''.join(chr(c) for c in range(256)) print('[ Initializing ]') salt = hexlify(os.urandom(16)).decode() password = hexlify(os.urandom(16)) cipher = AES(salt, password) print('[ Testing ]') print('Plaintext:', plaintext) # Encrypt with padding to prove that the padding works encrypted = cipher.encrypt(plaintext + padding) print('Encrypted:', encrypted) decrypted = cipher.decrypt(encrypted) decrypted_padding = decrypted[-len(padding):] # Assert instead of print because it's just padding assert padding == decrypted_padding print('Decrypted:', decrypted[:-len(padding)])
class MasterController: def __init__(self, address, txseq, rxseq, key, interface, command_queue): self.address = address self.txseq = txseq self.rxseq = rxseq self.key = [int(x) for x in key.split()] self.aes = AES() self.interface = interface self.supply_voltage = 0 self.periodic = 10 self.logger = logging.getLogger("logger") self.pressed_buttons = 0 self.command_queue = command_queue self.all_locked = False def update(self, message): if len(message) != 16: self.logger.warning("The received message is not 16 bytes long") return message = self.aes.decrypt([ord(x) for x in message], self.key, AES.keySize["SIZE_128"]) message = "".join([chr(x) for x in message]) self.logger.debug("Decoded message: %s" % str(list(message))) p = Packet.fromMessage(message) if p.cmd == 83: self.supply_voltage = ord(p.data[3]) * 0.1 pressed_buttons = ord(p.data[0]) self.logger.debug("master: pressed_buttons = %d", pressed_buttons) if pressed_buttons & 0x01 and not self.pressed_buttons & 0x01: self.pressed_buttons |= 0x01 self.command_queue.put("lock") elif not pressed_buttons & 0x01: self.pressed_buttons &= ~0x01 if pressed_buttons & 0x02 and not self.pressed_buttons & 0x02: self.pressed_buttons |= 0x02 self.command_queue.put("toggle_announce") elif not pressed_buttons & 0x02: self.pressed_buttons &= ~0x02 if pressed_buttons & 0x04 and not self.pressed_buttons & 0x04: self.pressed_buttons |= 0x04 elif not pressed_buttons & 0x04: self.pressed_buttons &= ~0x04 self.logger.info("Master state: %s" % self.get_state()) def get_state(self): state = "" state = state + " Voltage=%.1f V" % self.supply_voltage state = state.strip() return state def tick(self): self.periodic -= 1 if self.periodic == 0: self.periodic = 2 self._send_command(ord("S"), "") if self.all_locked: self._send_command(ord("L"), "\x00\x04") else: self._send_command(ord("L"), "\x00\x00") def _send_command(self, command, data): p = Packet(seq=self.txseq, cmd=command, data=data) self.logger.debug("Msg to mastercontroller: %s" % list(p.toMessage())) msg = self.aes.encrypt([ord(x) for x in p.toMessage()], self.key, AES.keySize["SIZE_128"]) msg = "".join([chr(x) for x in msg]) self.interface.writeMessage(self.address, msg) def announce_open(self): self._send_command(ord("L"), "\x02\x04") def announce_closed(self): self._send_command(ord("L"), "\x02\x01") def set_global_state(self, all_locked): self.all_locked = all_locked
def decrypt_data(ciphertext, master_key): AESfunct = AES(master_key) decrypted = AES.decrypt(AESfunct, ciphertext) return decrypted
p = psutil.Process(os.getpid()) proc_list = p.cpu_affinity() p.cpu_affinity([proc_list[-1]]) # Perform several encryption / decryption operations random_iv = bytearray(os.urandom(16)) random_key = bytearray(os.urandom(16)) data = bytearray(list(range(256))) data1 = data[:151] data2 = data[151:] # Note: __PROFILE_AES__ must be defined when building the native # module in order for the print statements below to work aes_ctr = AES(mode='ctr', key=random_key, iv=random_iv) result = aes_ctr.encrypt(data1) if result: print('Encrypted data1 in: %5d cycles' % result) result = aes_ctr.encrypt(data2) if result: print('Encrypted data2 in: %5d cycles' % result) data_new = data1 + data2 aes_ctr = AES(mode='ctr', key=random_key, iv=random_iv) result = aes_ctr.decrypt(data_new) if result: print('Decrypted data in: %5d cycles' % result) assert data == data_new, "The demo has failed."
def get_urls(url): urls = [] servers = { 1: { 'server': 'http://58.254.39.6:80/', 'cmd': '\x36\x00\x00\x00\x09\x00\x00\x00', 'key': '\xB6\xC3\x0A\xEB\x99\xCA\xF8\x49\xA7\x34\xCE\x4B\xFD\x90\x6C\x54' }, 2: { 'server': 'http://123.129.242.169:80/', 'cmd': '\x36\x00\x00\x00\x55\x00\x00\x00', 'key': '\x18\x3A\x7F\x85\xE4\x21\xC7\x58\x06\x18\x6C\x63\x32\x86\x1E\xCD' }, #3:{'server': 'http://123.129.242.168:80/', # 'cmd': '\x36\x00\x00\x00\x57\x00\x00\x00', # 'key': '\x64\x91\x63\x9D\xE8\x09\x87\x4D\xA5\x0A\x12\x02\x3F\x25\x3C\xF0'} #4:{'server': 'http://123.129.242.168:80/', # 'cmd':'\x36\x00\x00\x00\xf7\x00\x00\x00', # 'key':'\x2D\x33\xD2\x89\x46\xC3\xF8\x39\x76\x7B\xC4\x2F\x46\x1C\x45\x4C'} } for s in servers.values(): server = s['server'] cmd = s['cmd'] key = s['key'] a = AES(key) plaintext = '' plaintext += 'd\x02\x05\x00\x00\x00\xd1\x07\x00' plaintext += pack('<l', len(url)) plaintext += url plaintext += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\n\x00\x00\x00\x00\x10\x00\x00\x0000030D3F968AAYV4\x00\x00\x00\x00j\x01\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x000000\x04\x00\x00\x00' #alignment length = len(plaintext) _, extra = divmod(length, 16) if extra: plaintext += chr(extra) * (16 - extra) else: plaintext += chr(16) * 16 #printf(plaintext) #encryption ciphertext = a.encrypt(plaintext) #printf(ciphertext) #add 12 bytes[command+len] data = '' data += cmd data += pack('<l', len(ciphertext)) data += ciphertext #printf(data) headers = { 'Accept': '*/*', 'Content-type': 'application/octet-stream', 'Connection': 'Keep-Alive', } opener = urllib2.build_opener() urllib2.install_opener(opener) request = urllib2.Request(server, headers=headers, data=data) try: conn = urllib2.urlopen(request) except urllib2.URLError: continue result = conn.read() #decryption;ignore the first 12 bytes. plaintext = a.decrypt(result[12:]) #printf(plaintext) urls.extend(parse(plaintext)) return list(set(urls))
def serialize_and_deserialize(t): m, cipher, _ = t pt = " ".join(map(str, m)) ct = " ".join(map(str, cipher)) return (to_bytes(pt), to_bytes(ct), 0) for (pt, ct, _) in tuples: pt = to_bytes(pt) ct = to_bytes(ct) test = False # to test the functionality of my comparations if test: m = list(urandom(16)) cipher = aes.encrypt(m, bytes, 16) pt, ct, _ = serialize_and_deserialize((m, cipher, 0)) if len(pt) != len(ct): print("Length of messages does not match") res = aes.decrypt(ct, bytes, 16) if pt != res: print("Got {} instead of {}".format(res, pt)) break if test: print("Test passed") break
for _ in range(16): key_digit = hex(random.randint(0, 255))[2:] if len(key_digit) == 1: key_digit = "0" + key_digit private_key += key_digit # PLAINTEXT for _ in range(num_blocks * 16): text_digit = hex(random.randint(0, 127))[2:] if len(text_digit) == 1: text_digit = "0" + text_digit plaintext += text_digit aes = AES(private_key) ciphertext = aes.encrypt(plaintext) decrypted_text = aes.decrypt(ciphertext) if plaintext != decrypted_text: # Log data if there is a mismatch print("NOT MATCHING") print("Key: ", key) print("PLaintext: ", plaintext) print("Length of plaintext", len(plaintext)) print() print(decrypted_text) exit() except Exception: # Log data if there is an exception print("Met exception!") print("Key: ", key) print("PLaintext: ", plaintext)
import os, psutil from aes import AES # Pin the Python process to the last CPU to measure performance # Note: this code works for psutil 1.2.x, not 2.x! cpu_count = psutil.NUM_CPUS p = psutil.Process(os.getpid()) proc_list = p.get_cpu_affinity() p.set_cpu_affinity([proc_list[-1]]) # Perform several encryption / decryption operations random_iv = bytearray(os.urandom(16)) random_key = bytearray(os.urandom(16)) data = bytearray(list(range(256))) data1 = data[:151] data2 = data[151:] # Note: __PROFILE_AES__ must be defined when building the native # module in order for the print statements below to work aes_ctr = AES(mode='ctr', key=random_key, iv=random_iv) print('Encrypted data1 in: %5d cycles' % aes_ctr.encrypt(data1)) print('Encrypted data2 in: %5d cycles' % aes_ctr.encrypt(data2)) data_new = data1 + data2 aes_ctr = AES(mode='ctr', key=random_key, iv=random_iv) print('Decrypted data in: %5d cycles' % aes_ctr.decrypt(data_new)) print(data == data_new)
print("Testing MD5") print( f"{sum([test_md5(phrase) for phrase in test_phrases])}/{len(test_phrases)} tests successful" ) print("Testing AES") # assert AES.mult(0x57, 0x83) == 0xC1, "Issue with multiplication function, {57} . {83} = {C1}" # assert AES.xtime(0x57, 1) == 0xAE, "Issue with xtime function, xtime({57}) = {AE}" print("All tests successful") # C.1 AES-128 (Nk=4, Nr=10) - Working # test_message = 0x00112233445566778899aabbccddeeff.to_bytes(16, 'big') # test_key = 0x000102030405060708090a0b0c0d0e0f.to_bytes(16, 'big') # C.2 AES-192 (Nk=6, Nr=12) - Working # test_message = 0x00112233445566778899aabbccddeeff.to_bytes(16, 'big') # test_key = 0x000102030405060708090a0b0c0d0e0f1011121314151617.to_bytes(24, 'big') # C.3 AES-256 (Nk=8, Nr=14) - Working test_message = 0x00112233445566778899aabbccddeeff.to_bytes(16, 'big') test_key = 0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f.to_bytes( 32, 'big') # C.3 AES-256 (Nk=8, Nr=14) - Working # test_message = 0x00112233445566778899aabbccddeeff.to_bytes(16, 'big') test_message = "Hello" test_key = 0x000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f.to_bytes( 32, 'big') print(AES.decrypt(AES.encrypt(test_message, test_key), test_key))
class Door: DOOR_CLOSED = (1 << 0) LOCK_LOCKED = (1 << 1) LOCK_UNLOCKED = (1 << 2) LOCK_LOCKING = (1 << 3) LOCK_UNLOCKING = (1 << 4) HANDLE_PRESSED = (1 << 5) LOCK_PERM_UNLOCKED = (1 << 6) def __init__(self, name, address, txseq, rxseq, key, interface, initial_unlock): self.name = name self.address = address self.txseq = txseq self.rxseq = rxseq self.key = [int(x) for x in key.split()] self.aes = AES() self.interface = interface self.open = False self.closed = False self.locked = False self.unlocked = False self.supply_voltage = 0 self.command_time = 0 self.command_accepted = None self.command = None self.periodic = 10 self.relock_time = 0 self.desired_state = Door.LOCK_LOCKED self.buttons_toggle_state = None self.logger = logging.getLogger('logger') self.pressed_buttons = 0 self.initial_unlock = initial_unlock def unlock(self, relock_timeout=0): self.desired_state = Door.LOCK_UNLOCKED self.relock_time = time.time() + relock_timeout #if timeout: # self._send_command(command=ord('D'), data='\x02') #else: # self._send_command(command=ord('D'), data='\x01') def lock(self): self.desired_state = Door.LOCK_LOCKED self._send_command(command=ord('D'), data='\x00') def update(self, message): if len(message) != 16: self.logger.warning("The received message is not 16 bytes long") return message = self.aes.decrypt([ord(x) for x in message], self.key, AES.keySize["SIZE_128"]) message = ''.join([chr(x) for x in message]) self.logger.debug("Decoded message: %s" % str(list(message))) p = Packet.fromMessage(message) if p.cmd == 83: self.supply_voltage = ord(p.data[3]) * 0.1 ''' pressed_buttons = 0 if self.buttons_toggle_state == None: self.buttons_toggle_state = ord(p.data[0]) else: pressed_buttons = self.buttons_toggle_state ^ ord(p.data[0]) self.buttons_toggle_state = ord(p.data[0]) if pressed_buttons: self.logger.info('Got pressed buttons: %d' % pressed_buttons) if pressed_buttons & 0x01: ''' pressed_buttons = ord(p.data[0]) if pressed_buttons & 0x01 and not self.pressed_buttons & 0x01: self.pressed_buttons |= 0x01 if self.desired_state == Door.LOCK_LOCKED: self.desired_state = Door.LOCK_UNLOCKED elif self.desired_state == Door.LOCK_UNLOCKED: self.desired_state = Door.LOCK_LOCKED elif not pressed_buttons & 0x01: self.pressed_buttons &= ~0x01 doorstate = ord(p.data[1]) state = '' self.closed = doorstate & Door.DOOR_CLOSED \ == Door.DOOR_CLOSED self.locked = doorstate & Door.LOCK_LOCKED \ == Door.LOCK_LOCKED self.unlocked = doorstate & Door.LOCK_UNLOCKED \ == Door.LOCK_UNLOCKED self.locking = doorstate & Door.LOCK_LOCKING \ == Door.LOCK_LOCKING self.unlocking = doorstate & Door.LOCK_UNLOCKING \ == Door.LOCK_UNLOCKING self.handle_pressed = doorstate & Door.HANDLE_PRESSED \ == Door.HANDLE_PRESSED self.perm_unlocked = doorstate & Door.LOCK_PERM_UNLOCKED \ == Door.LOCK_PERM_UNLOCKED self.logger.info('Door state: %s' % self.get_state()) self.logger.info('Desired door state: %s' % self.get_desired_state()) elif p.cmd == ord('A'): accepted = ord(p.data[0]) == 1 if not self.command_accepted: if accepted: self.logger.info('Command at %d was accepted' % self.command_time) self.command_accepted = True else: self.logger.warning('Command at %d was NOT accepted' % self.command_time) def get_state(self): state = '' if self.closed: state += ' CLOSED' if self.locked: state += ' LOCKED' if self.unlocked: state += ' UNLOCKED' if self.locking: state += ' LOCKING' if self.unlocking: state += ' UNLOCKING' if self.handle_pressed: state += ' HANDLE_PRESSED' if self.perm_unlocked: state += ' PERM_UNLOCKED' state = state.strip() state = state + ' Voltage=%.1f V' % self.supply_voltage return state def get_desired_state(self): state = '' if self.desired_state & Door.LOCK_LOCKED: state += ' LOCKED' if self.desired_state & Door.LOCK_UNLOCKED: state += ' UNLOCKED' state = state.strip() return state def tick(self): self.periodic -= 1 if self.periodic == 0: self.periodic = 2 self._send_command(ord('D'), chr(self.desired_state)) if self.relock_time: if time.time() > self.relock_time: self.desired_state = Door.LOCK_LOCKED self.relock_time = 0 ''' if time.time() - self.command_time > 5: if self.command_accepted == False: print 'Error: Command at %d was not accepted!' elif self.command_accepted == None: print 'Error: Command was not received' ''' def _send_command(self, command, data): p = Packet(seq=self.txseq, cmd=command, data=data) msg = self.aes.encrypt([ord(x) for x in p.toMessage()], self.key, AES.keySize["SIZE_128"]) msg = ''.join([chr(x) for x in msg]) self.logger.debug('Msg to door %s: %s' % (self.name, list(p.toMessage()))) self.interface.writeMessage(self.address, msg) '''
class Door: DOOR_CLOSED = (1<<0) LOCK_LOCKED = (1<<1) LOCK_UNLOCKED = (1<<2) LOCK_LOCKING = (1<<3) LOCK_UNLOCKING = (1<<4) HANDLE_PRESSED = (1<<5) LOCK_PERM_UNLOCKED = (1<<6) def __init__(self, name, address, txseq, rxseq, key, interface, initial_unlock): self.name = name self.address = address self.txseq = txseq self.rxseq = rxseq self.key = [int(x) for x in key.split()] self.aes = AES() self.interface = interface self.open = False self.closed = False self.locked = False self.unlocked = False self.supply_voltage = 0 self.command_time = 0 self.command_accepted = None self.command = None self.periodic = 10 self.relock_time = 0 self.desired_state = Door.LOCK_LOCKED self.buttons_toggle_state = None self.logger = logging.getLogger('logger') self.pressed_buttons = 0 self.initial_unlock = initial_unlock def unlock(self, relock_timeout=0): self.desired_state = Door.LOCK_UNLOCKED self.relock_time = time.time() + relock_timeout #if timeout: # self._send_command(command=ord('D'), data='\x02') #else: # self._send_command(command=ord('D'), data='\x01') def lock(self): self.desired_state = Door.LOCK_LOCKED self._send_command(command=ord('D'), data='\x00') def update(self, message): if len(message) != 16: self.logger.warning("The received message is not 16 bytes long") return message = self.aes.decrypt([ord(x) for x in message], self.key, AES.keySize["SIZE_128"]) message = ''.join([chr(x) for x in message]) self.logger.debug("Decoded message: %s"%str(list(message))) p = Packet.fromMessage(message) if p.cmd==83: self.supply_voltage = ord(p.data[3])*0.1 ''' pressed_buttons = 0 if self.buttons_toggle_state == None: self.buttons_toggle_state = ord(p.data[0]) else: pressed_buttons = self.buttons_toggle_state ^ ord(p.data[0]) self.buttons_toggle_state = ord(p.data[0]) if pressed_buttons: self.logger.info('Got pressed buttons: %d' % pressed_buttons) if pressed_buttons & 0x01: ''' pressed_buttons = ord(p.data[0]) if pressed_buttons & 0x01 and not self.pressed_buttons & 0x01: self.pressed_buttons |= 0x01 if self.desired_state == Door.LOCK_LOCKED: self.desired_state = Door.LOCK_UNLOCKED elif self.desired_state == Door.LOCK_UNLOCKED: self.desired_state = Door.LOCK_LOCKED elif not pressed_buttons & 0x01: self.pressed_buttons &= ~0x01 doorstate = ord(p.data[1]) state = '' self.closed = doorstate & Door.DOOR_CLOSED \ == Door.DOOR_CLOSED self.locked = doorstate & Door.LOCK_LOCKED \ == Door.LOCK_LOCKED self.unlocked = doorstate & Door.LOCK_UNLOCKED \ == Door.LOCK_UNLOCKED self.locking = doorstate & Door.LOCK_LOCKING \ == Door.LOCK_LOCKING self.unlocking = doorstate & Door.LOCK_UNLOCKING \ == Door.LOCK_UNLOCKING self.handle_pressed = doorstate & Door.HANDLE_PRESSED \ == Door.HANDLE_PRESSED self.perm_unlocked = doorstate & Door.LOCK_PERM_UNLOCKED \ == Door.LOCK_PERM_UNLOCKED self.logger.info('Door state: %s'%self.get_state()) self.logger.info('Desired door state: %s'%self.get_desired_state()) elif p.cmd==ord('A'): accepted = ord(p.data[0]) == 1 if not self.command_accepted: if accepted: self.logger.info('Command at %d was accepted'%self.command_time) self.command_accepted = True else: self.logger.warning('Command at %d was NOT accepted'% self.command_time) def get_state(self): state = '' if self.closed: state += ' CLOSED' if self.locked: state += ' LOCKED' if self.unlocked: state += ' UNLOCKED' if self.locking: state += ' LOCKING' if self.unlocking: state += ' UNLOCKING' if self.handle_pressed: state += ' HANDLE_PRESSED' if self.perm_unlocked: state += ' PERM_UNLOCKED' state = state.strip() state = state + ' Voltage=%.1f V'%self.supply_voltage return state def get_desired_state(self): state = '' if self.desired_state & Door.LOCK_LOCKED: state += ' LOCKED' if self.desired_state & Door.LOCK_UNLOCKED: state += ' UNLOCKED' state = state.strip() return state def tick(self): self.periodic-=1 if self.periodic == 0: self.periodic = 2 self._send_command(ord('D'), chr(self.desired_state)) if self.relock_time: if time.time() > self.relock_time: self.desired_state = Door.LOCK_LOCKED self.relock_time = 0 ''' if time.time() - self.command_time > 5: if self.command_accepted == False: print 'Error: Command at %d was not accepted!' elif self.command_accepted == None: print 'Error: Command was not received' ''' def _send_command(self, command, data): p = Packet(seq=self.txseq, cmd=command, data=data) msg = self.aes.encrypt([ord(x) for x in p.toMessage()], self.key, AES.keySize["SIZE_128"]) msg = ''.join([chr(x) for x in msg]) self.logger.debug('Msg to door %s: %s'%(self.name, list(p.toMessage()))) self.interface.writeMessage(self.address, msg) '''
expandedkey = bytes.fromhex(''.join(roundkeys)) aes = AES() if len(sys.argv) > 1: p = bytes(sys.argv[1], encoding='utf8')[:16] p = p + b'\00' * (16 - len(p)) else: p = b"You got broken!!" try: p.decode('utf8') except UnicodeDecodeError: print('ERROR: Please shorten your string!') sys.exit() print("PLAIN: %s" % p.decode('utf8')) c = bytes(aes.encrypt(p, expandedkey, 32)) print("CLIENT ENC %s => %s" % (p.hex(), c.hex())) p2 = bytes(aes.decrypt(c, expandedkey, 32)) print("SERVER DEC %s => %s" % (c.hex(), p2.hex())) p2u = p2.upper() print("SERVER UP %s => %s" % (p2.hex(), p2u.hex())) c3 = bytes(aes.encrypt(p2u, expandedkey, 32)) print("SERVER ENC %s => %s" % (p2.hex(), c3.hex())) p3 = bytes(aes.decrypt(c3, expandedkey, 32)) print("CLIENT DEC %s => %s" % (c3.hex(), p3.hex())) print("PLAIN: %s" % p3.decode('utf8'))
def get_urls(url): urls = [] servers = { 1:{'server': 'http://58.254.39.6:80/', 'cmd': '\x36\x00\x00\x00\x09\x00\x00\x00', 'key': '\xB6\xC3\x0A\xEB\x99\xCA\xF8\x49\xA7\x34\xCE\x4B\xFD\x90\x6C\x54'}, 2:{'server': 'http://123.129.242.169:80/', 'cmd': '\x36\x00\x00\x00\x55\x00\x00\x00', 'key': '\x18\x3A\x7F\x85\xE4\x21\xC7\x58\x06\x18\x6C\x63\x32\x86\x1E\xCD'}, #3:{'server': 'http://123.129.242.168:80/', # 'cmd': '\x36\x00\x00\x00\x57\x00\x00\x00', # 'key': '\x64\x91\x63\x9D\xE8\x09\x87\x4D\xA5\x0A\x12\x02\x3F\x25\x3C\xF0'} #4:{'server': 'http://123.129.242.168:80/', # 'cmd':'\x36\x00\x00\x00\xf7\x00\x00\x00', # 'key':'\x2D\x33\xD2\x89\x46\xC3\xF8\x39\x76\x7B\xC4\x2F\x46\x1C\x45\x4C'} } for s in servers.values(): server = s['server'] cmd = s['cmd'] key = s['key'] a = AES(key) plaintext = '' plaintext += 'd\x02\x05\x00\x00\x00\xd1\x07\x00' plaintext += pack('<l',len(url)) plaintext += url plaintext += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\n\x00\x00\x00\x00\x10\x00\x00\x0000030D3F968AAYV4\x00\x00\x00\x00j\x01\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x000000\x04\x00\x00\x00' #alignment length = len(plaintext) _,extra = divmod(length,16) if extra: plaintext += chr(extra)*(16-extra) else: plaintext += chr(16)*16 #printf(plaintext) #encryption ciphertext = a.encrypt(plaintext) #printf(ciphertext) #add 12 bytes[command+len] data = '' data += cmd data += pack('<l',len(ciphertext)) data += ciphertext #printf(data) headers = { 'Accept':'*/*', 'Content-type':'application/octet-stream', 'Connection':'Keep-Alive', } opener = urllib2.build_opener() urllib2.install_opener(opener) request = urllib2.Request(server,headers = headers,data=data) try: conn = urllib2.urlopen(request) except urllib2.URLError: continue result = conn.read() #decryption;ignore the first 12 bytes. plaintext = a.decrypt(result[12:]) #printf(plaintext) urls.extend(parse(plaintext)) return list(set(urls))
class MasterController: def __init__(self, address, txseq, rxseq, key, interface, command_queue): self.address = address self.txseq = txseq self.rxseq = rxseq self.key = [int(x) for x in key.split()] self.aes = AES() self.interface = interface self.supply_voltage = 0 self.periodic = 10 self.logger = logging.getLogger('logger') self.pressed_buttons = 0 self.command_queue = command_queue self.all_locked = False def update(self, message): if len(message) != 16: self.logger.warning("The received message is not 16 bytes long") return message = self.aes.decrypt([ord(x) for x in message], self.key, AES.keySize["SIZE_128"]) message = ''.join([chr(x) for x in message]) self.logger.debug("Decoded message: %s"%str(list(message))) p = Packet.fromMessage(message) if p.cmd==83: self.supply_voltage = ord(p.data[3])*0.1 pressed_buttons = ord(p.data[0]) self.logger.debug('master: pressed_buttons = %d', pressed_buttons) if pressed_buttons & 0x01 and not self.pressed_buttons & 0x01: self.pressed_buttons |= 0x01 self.command_queue.put('lock') elif not pressed_buttons & 0x01: self.pressed_buttons &= ~0x01 if pressed_buttons & 0x02 and not self.pressed_buttons & 0x02: self.pressed_buttons |= 0x02 self.command_queue.put('toggle_announce') elif not pressed_buttons & 0x02: self.pressed_buttons &= ~0x02 if pressed_buttons & 0x04 and not self.pressed_buttons & 0x04: self.pressed_buttons |= 0x04 elif not pressed_buttons & 0x04: self.pressed_buttons &= ~0x04 self.logger.info('Master state: %s'%self.get_state()) def get_state(self): state = '' state = state + ' Voltage=%.1f V'%self.supply_voltage state = state.strip() return state def tick(self): self.periodic-=1 if self.periodic == 0: self.periodic = 2 self._send_command(ord('S'), '') if self.all_locked: self._send_command(ord('L'), '\x00\x04') else: self._send_command(ord('L'), '\x00\x00') def _send_command(self, command, data): p = Packet(seq=self.txseq, cmd=command, data=data) self.logger.debug('Msg to mastercontroller: %s'%list(p.toMessage())) msg = self.aes.encrypt([ord(x) for x in p.toMessage()], self.key, AES.keySize["SIZE_128"]) msg = ''.join([chr(x) for x in msg]) self.interface.writeMessage(self.address, msg) def announce_open(self): self._send_command(ord('L'), '\x02\x04') def announce_closed(self): self._send_command(ord('L'), '\x02\x01') def set_global_state(self, all_locked): self.all_locked = all_locked