예제 #1
0
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"
예제 #2
0
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"
예제 #3
0
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"
예제 #4
0
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"
예제 #5
0
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"
예제 #6
0
class AES_TEST(unittest.TestCase):
    def setUp(self):
        lines = openfile('key.txt')
        self.AES = AES(hexline(lines))

    def test_encryption(self):
        print("(for encryption)")
        lines = openfile('en_input.txt')
        lines2 = openfile('ctr.txt')

        encrypted = self.AES.encrypt(
            int(padhexa(hex(hexline(lines2)), 64)[:32], 16))
        ciphertext = encrypted ^ int(padhexa(hex(hexline(lines)), 64)[:32], 16)
        print(output_space(padhexa(hex(ciphertext), 32)).upper())

        encrypted = self.AES.encrypt(
            int(padhexa(hex(hexline(lines2)), 64)[32:], 16))
        ciphertext2 = encrypted ^ int(
            padhexa(hex(hexline(lines)), 64)[32:], 16)
        print(output_space(padhexa(hex(ciphertext2), 32).upper()))

    def test_decryption(self):
        print("(for decryption)")
        lines = openfile('de_input.txt')
        lines2 = openfile('ctr.txt')

        decrypted = self.AES.encrypt(
            int(padhexa(hex(hexline(lines2)), 64)[:32], 16))
        plaintext = decrypted ^ int(padhexa(hex(hexline(lines)), 64)[:32], 16)
        print(output_space(padhexa(hex(plaintext), 32).upper()))

        decrypted = self.AES.encrypt(
            int(padhexa(hex(hexline(lines2)), 64)[32:], 16))
        plaintext2 = decrypted ^ int(padhexa(hex(hexline(lines)), 64)[32:], 16)
        print(output_space(padhexa(hex(plaintext2), 32).upper()))
예제 #7
0
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"
예제 #8
0
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"
예제 #9
0
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"
예제 #10
0
 def test_bad_input(self, key):
     with self.assertRaises(Exception) as context:
         AES(key)
     self.assertTrue('Key can not be < 0' in str(context.exception))
     a = AES(123)
     with self.assertRaises(Exception) as context:
         a.encrypt(key)
     self.assertTrue('Plaintext can not be < 0' in str(context.exception))
예제 #11
0
파일: main.py 프로젝트: TwoShock/AES
 def __handleEncryptClick(self):
     try:
         if (len(self.__output.toPlainText()) > 0):
             self.__output.document().clear()
         aes = AES(self.__keyEdit.text(), self.__msgEdit.text())
         aes.encrypt()
         self.__output.document().setPlainText(aes.getOutput())
     except:
         pass
예제 #12
0
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"
예제 #13
0
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"
예제 #14
0
파일: prog.py 프로젝트: ribes96/Grau-C
def ex1(M=0x3243f6a8885a308d313198a2e0370734,
        K=0x2b7e151628aed2a6abf7158809cf4f3c):
    a = AES(K)
    C = a.encrypt(M)
    l = []
    for i in range(128):
        Mi = change_i_bit(M, i)
        Ci = a.encrypt(Mi)
        changes = number_bits_change(C, Ci)
        l.append(changes)
    return l
예제 #15
0
def main():    
    k = os.urandom(16)
    cipher = AES(k)
    secret = b''.join(k[i:i+1]*4 for i in range(16))

    flag = os.environ.get('FLAG', 'hkcert21{***********************REDACTED***********************}').encode()
    assert len(flag) == 64

    flag = b''.join([cipher.encrypt(flag[i:i+16]) for i in range(0, 64, 16)])
    print(f'Hey. This is the encrypted flag you gotta decrypt: {flag.hex()}.')

    options = ['ark', 'sb', 'sr', 'mc']
    suboptions = ['data', 'secret']
    
    for _ in range(128):
        [option, suboption, *more] = input('> ').split(' ')
        if option not in options: raise Exception('invalid option!')
        if suboption not in suboptions: raise Exception('invalid suboption!')
        
        if suboption == 'secret':
            options.remove(option)
            message = secret
        else:
            message = bytes.fromhex(more[0])
            if len(message) != 16: raise Exception('invalid length!')
            message = message * 4

        if option == 'ark':
            # Stage 1: "AddRoundKey" does nothing
            cipher = AES(k)
            cipher._add_round_key = no_op
            ciphertext = cipher.encrypt(message[0:16])
        elif option == 'sb':
            # Stage 2: "SubBytes" does nothing
            cipher = AES(k)
            cipher._sub_bytes = no_op
            ciphertext = cipher.encrypt(message[16:32])
        elif option == 'sr':
            # Stage 3: "ShiftRows" does nothing
            cipher = AES(k)
            cipher._shift_rows = no_op
            ciphertext = cipher.encrypt(message[32:48])
        elif option == 'mc':
            # Stage 4: "MixColumns" does nothing
            cipher = AES(k)
            cipher._mix_columns = no_op
            ciphertext = cipher.encrypt(message[48:64])

        print(ciphertext.hex())
예제 #16
0
파일: prog.py 프로젝트: ribes96/Grau-C
def ex3(m, i, j, key=0x2b7e151628aed2a6abf7158809cf4f3c):
    normal = AES(key, customMixColumns=False)
    change = AES(key, customMixColumns=True)
    mi = change_i_bit(m, i)

    c = normal.encrypt(m)
    ci = normal.encrypt(mi)

    c2 = change.encrypt(m)
    ci2 = change.encrypt(mi)

    print("m, mi")
    print(m, ",", mi)
    print("----------------")
    print("c, ci")
    print(c, ",", ci)
예제 #17
0
 def _login(self, user, password, encrypted, ver):
     self._info("Logging in...")
     if not self._ver_check(ver):
         return None, False
     rndk = self._rndk()
     if rndk is None:
         return None, False
     if self._magic:
         hash = self._swapped_md5(
             self._swapped_md5(password, encrypted).upper() + rndk +
             self._magic)
         if rndk == "houdini":
             aes = AES(256, 256)
             hash = aes.encrypt(hash, "67L8CALPPCD4J283WL3JF3T2T32DFGZ8",
                                "ECB")
     else:
         hash = password
     if self._single_quotes:
         data = "<msg t='sys'><body action='login' r='0'><login z='w1'><nick><![CDATA[{}]]></nick><pword><![CDATA[{}]]></pword></login></body></msg>".format(
             user, hash)
     else:
         data = '<msg t="sys"><body action="login" r="0"><login z="w1"><nick><![CDATA[{}]]></nick><pword><![CDATA[{}]]></pword></login></body></msg>'.format(
             user, hash)
     if not self._send(data):
         return None, False
     packet = self._receive_packet()
     if packet is None or packet[2] == "e":
         return packet, False
     while packet[2] != "l":
         packet = self._receive_packet()
         if packet is None or packet[2] == "e":
             return packet, False
     self._info("Logged in")
     return packet, True
예제 #18
0
    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)
예제 #19
0
def ctr_decrypted(key, cyphertext, file_name):
    aes_object = AES(key)
    iv = cyphertext[:16]
    count = 0
    blocks_arr = split_blocks(cyphertext[16:])
    with open(file_name, 'ab') as fo_dec:
        for block in blocks_arr[:-1]:
            iv_count = bytes_xor(iv, count.to_bytes(16, 'big'))
            iv_x = aes_object.encrypt(iv_count)
            plaintext = bytes_xor(iv_x, block)
            fo_dec.write(plaintext)
            count += 1
        iv_count = bytes_xor(iv, count.to_bytes(16, 'big'))
        iv_x = aes_object.encrypt(iv_count)
        plaintext = bytes_xor(iv_x, blocks_arr[-1])
        fo_dec.write(unpad(plaintext))
    print("File was decrypted successfully by CTR MODE")
예제 #20
0
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)
예제 #21
0
    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')
예제 #22
0
파일: cbc_mode.py 프로젝트: AnhPC03/AES
def cbc_encrypted(key, message, iv, file_name):
    aes_object = AES(key)
    message = pad(message)
    iv_next = iv
    with open(file_name, 'ab') as fo_enc:
        fo_enc.write(iv)
        for block in split_blocks(message):
            iv_x = bytes_xor(block, iv_next)
            cyphertext = aes_object.encrypt(iv_x)
            fo_enc.write(cyphertext)
            iv_next = cyphertext
    print("File was encrpyted succesfully by CBC MODE")
예제 #23
0
파일: prog.py 프로젝트: ribes96/Grau-C
def ex1(m, i, j, key=0x2b7e151628aed2a6abf7158809cf4f3c):
    normal = AES(key, customByteSub=False)
    change = AES(key, customByteSub=True)
    mi = change_i_bit(m, i)
    mj = change_i_bit(m, j)
    mij = change_i_bit(mi, j)

    c = normal.encrypt(m)
    ci = normal.encrypt(mi)
    cj = normal.encrypt(mj)
    cij = normal.encrypt(mij)

    c2 = change.encrypt(m)
    ci2 = change.encrypt(mi)
    cj2 = change.encrypt(mj)
    cij2 = change.encrypt(mij)

    if c == ci ^ cj ^ cij:
        print("With normal it DO happen")
    else:
        print("With normal it do NOT happen")

    if c2 == ci2 ^ cj2 ^ cij2:
        print("With the change it DO happen")
    else:
        print("With the change it do NOT happen")
예제 #24
0
def ctr_encrypted(key, message, iv, file_name):
    aes_object = AES(key)
    message = pad(message)
    count = 0
    with open(file_name, 'ab') as fo_enc:
        fo_enc.write(iv)
        for block in split_blocks(message):
            iv_count = bytes_xor(iv, count.to_bytes(16, 'big'))
            iv_x = aes_object.encrypt(iv_count)
            cyphertext = bytes_xor(iv_x, block)
            fo_enc.write(cyphertext)
            count += 1
    print("File was encrypted successfully by CTR MODE")
예제 #25
0
        def generateHash(self, message):
                """
                The KMS v4 hash is a variant of CMAC-AES-128. There are two key differences:
                * The 'AES' used is modified in particular ways:
                  * The basic algorithm is Rjindael with a conceptual 160bit key and 128bit blocks.
                    This isn't part of the AES standard, but it works the way you'd expect.
                    Accordingly, the algorithm uses 11 rounds and a 192 byte expanded key.
                * The trailing block is not XORed with a generated subkey, as defined in CMAC.
                  This is probably because the subkey generation algorithm is only defined for
                  situations where block and key size are the same.
                """
                aes = AES()

                messageSize = len(message)
                lastBlock = bytearray(16) 
                hashBuffer = bytearray(16)

                # MessageSize / Blocksize.
                j = messageSize >> 4

                # Remainding bytes.
                k = messageSize & 0xf

                # Hash.
                for i in range(0, j):
                        xorBuffer(message, i << 4, hashBuffer, 16)
                        hashBuffer = bytearray(aes.encrypt(hashBuffer, key, len(key)))

                # Bit Padding.
                ii = 0
                for i in range(j << 4, k + (j << 4)):
                        lastBlock[ii] = message[i]
                        ii += 1
                lastBlock[k] = 0x80

                xorBuffer(lastBlock, 0, hashBuffer, 16)
                hashBuffer = bytearray(aes.encrypt(hashBuffer, key, len(key)))

                return hashBuffer #*2to3*
예제 #26
0
    def generateHash(self, message):
        """
		The KMS v4 hash is a variant of CMAC-AES-128. There are two key differences:
		* The 'AES' used is modified in particular ways:
		  * The basic algorithm is Rjindael with a conceptual 160bit key and 128bit blocks.
		    This isn't part of the AES standard, but it works the way you'd expect.
		    Accordingly, the algorithm uses 11 rounds and a 192 byte expanded key.
		* The trailing block is not XORed with a generated subkey, as defined in CMAC.
		  This is probably because the subkey generation algorithm is only defined for
		  situations where block and key size are the same.
		"""
        aes = AES()

        messageSize = len(message)
        lastBlock = bytearray(16)
        hashBuffer = bytearray(16)

        # MessageSize / Blocksize
        j = messageSize >> 4

        # Remainding bytes
        k = messageSize & 0xf

        # Hash
        for i in range(0, j):
            xorBuffer(message, i << 4, hashBuffer, 16)
            hashBuffer = bytearray(aes.encrypt(hashBuffer, key, len(key)))

        # Bit Padding
        ii = 0
        for i in range(j << 4, k + (j << 4)):
            lastBlock[ii] = message[i]
            ii += 1
        lastBlock[k] = 0x80

        xorBuffer(lastBlock, 0, hashBuffer, 16)
        hashBuffer = bytearray(aes.encrypt(hashBuffer, key, len(key)))

        return str(hashBuffer)
예제 #27
0
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
예제 #28
0
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)
예제 #29
0
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)
예제 #30
0
def sndAESmsg():
    """
    对要发送的消息进行AES加密并发送
    """

    with open('./plaintext.txt', 'r') as fileObj:
        plainText = fileObj.read()
    plainTextByte = plainText.encode('utf-8')
    plainTextInt = int.from_bytes(plainTextByte, 'big', signed=False)
    aesAlgo = AES(app.config['aesKey'])
    cipherTextInt = aesAlgo.encrypt(plainTextInt)

    res = {
        'AEScipherInt': cipherTextInt,
    }
    requests.post(app.config['comURL'] + '/AESmsg', data=json.dumps(res))
    return 'Send AES message', 200
예제 #31
0
 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
예제 #32
0
    def _login(self, user, password, encrypted, ver):
        self._info("Connecting to login server at {}:{}...".format(
            self.login_ip, self.login_port))
        self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            self._sock.connect((self.login_ip, self.login_port))
        except socket.error:
            self._error("Failed to connect to login server at {}:{}".format(
                self.login_ip, self.login_port))

        try:
            self._info("Logging in...")
            self._ver_check(ver)
            rndk = self._rndk()
            if self._magic:
                digest = self._swapped_md5(
                    self._swapped_md5(password, encrypted).upper() + rndk +
                    self._magic)
                if self.login_ip == "198.100.148.54":
                    aes = AES(256, 256)
                    digest = aes.encrypt(digest,
                                         "67L8CALPPCD4J283WL3JF3T2T32DFGZ8",
                                         "ECB")
            else:
                digest = password
            if self._single_quotes:
                data = "<msg t='sys'><body action='login' r='0'><login z='w1'><nick><![CDATA[{}]]></nick><pword><![CDATA[{}]]></pword></login></body></msg>".format(
                    user, digest)
            else:
                data = '<msg t="sys"><body action="login" r="0"><login z="w1"><nick><![CDATA[{}]]></nick><pword><![CDATA[{}]]></pword></login></body></msg>'.format(
                    user, digest)
            self._send(data)
            packet = self._receive_packet()
            while packet[2] != "l":
                packet = self._receive_packet()
            self._info("Logged in")
            return packet
        finally:
            try:
                self._sock.shutdown(socket.SHUT_RDWR)
            except socket.error:
                pass
            self._sock.close()
def cbc_encrypt(cache, msg, inv=None):
    if cache is None:
        raise ValueError('Key cache is NULL.')
    elif msg is None:
        raise ValueError('Message 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 incorrect size.'
                             'Size should be 176, 208, or either 240 bytes.')
        plaintext = []
        iput = [0] * 16
        output = []
        cipher = [0] * 16
        if inv is None:
            inv = [0] * 16
        first_round = True
        if msg is not None:
            for j in range(int(math.ceil(float(len(msg))/16))):
                start = j * 16
                end = start + 16
                if  end > len(msg):
                    end = len(msg)
                plaintext = msg[start:end]
                for i in range(16):
                    if first_round:
                        iput[i] = plaintext[i] ^ inv[i]
                    else:
                        iput[i] = plaintext[i] ^ cipher[i]
                first_round = False
                cipher = aes.encrypt(iput, cache, nbr_rounds)
                output.extend(cipher)
        return struct.pack('B' * len(output), *output)
예제 #34
0
def cbc_encrypt(cache, msg, inv=None):
    if cache is None:
        raise ValueError('Key cache is NULL.')
    elif msg is None:
        raise ValueError('Message 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 incorrect size.'
                             'Size should be 176, 208, or either 240 bytes.')
        plaintext = []
        iput = [0] * 16
        output = []
        cipher = [0] * 16
        if inv is None:
            inv = [0] * 16
        first_round = True
        if msg is not None:
            for j in range(int(math.ceil(float(len(msg)) / 16))):
                start = j * 16
                end = start + 16
                if end > len(msg):
                    end = len(msg)
                plaintext = msg[start:end]
                for i in range(16):
                    if first_round:
                        iput[i] = plaintext[i] ^ inv[i]
                    else:
                        iput[i] = plaintext[i] ^ cipher[i]
                first_round = False
                cipher = aes.encrypt(iput, cache, nbr_rounds)
                output.extend(cipher)
        return struct.pack('B' * len(output), *output)
예제 #35
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)])
예제 #36
0
파일: pythunder.py 프로젝트: hustluy/pytool
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))
예제 #37
0
파일: demo.py 프로젝트: BrianGladman/AES
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."
예제 #38
0
                c1 += 1
            # total += s['leak'] - (keybit ^ s['plain_bits'][i]) * 3.0 / 8

        # print 'actual', total #- n / 2.0 * 3 / 8
        # print 'actual', 1.0*total0/c0 #- n / 2.0 * 3 / 8
        # print 'actual', 1.0*t1/c1 #- n / 2.0 * 3 / 8
        return int(1.0 * total0 / c0 > 1.0 * t1 / c1)


samples = getSamples(15000)
print len(samples)

key = []
for i in range(128):
    key.append(decideBit(key, samples, i))
# for j in range(20):
#     decideBit(key, samples, i=j)
# from IPython import embed; embed()

# print key

from aes import AES
aes = AES()

key = bitsToBytes(key)
print key
m = samples[0]['plain']
cipher = aes.encrypt(m, key, 16)
print cipher
print samples[0]['cipher']
예제 #39
0
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)
예제 #40
0
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)
        '''
예제 #41
0
        #KEY
        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)
예제 #42
0
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))
예제 #43
0
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