Learn more  » Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Bower components Debian packages RPM packages NuGet packages

aroundthecode / pycryptodome   python

Repository URL to install this package:

Version: 3.7.2 

/ SelfTest / Cipher / test_CBC.py

# ===================================================================
#
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in
#    the documentation and/or other materials provided with the
#    distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ===================================================================

import unittest
from binascii import unhexlify

from Crypto.SelfTest.loader import load_tests
from Crypto.SelfTest.st_common import list_test_cases
from Crypto.Util.py3compat import tobytes, _memoryview, is_string
from Crypto.Cipher import AES, DES3, DES
from Crypto.Hash import SHAKE128

def get_tag_random(tag, length):
    return SHAKE128.new(data=tobytes(tag)).read(length)

class BlockChainingTests(unittest.TestCase):

    key_128 = get_tag_random("key_128", 16)
    key_192 = get_tag_random("key_192", 24)
    iv_128 = get_tag_random("iv_128", 16)
    iv_64 = get_tag_random("iv_64", 8)
    data_128 = get_tag_random("data_128", 16)

    def test_loopback_128(self):
        cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
        pt = get_tag_random("plaintext", 16 * 100)
        ct = cipher.encrypt(pt)

        cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
        pt2 = cipher.decrypt(ct)
        self.assertEqual(pt, pt2)

    def test_loopback_64(self):
        cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64)
        pt = get_tag_random("plaintext", 8 * 100)
        ct = cipher.encrypt(pt)

        cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64)
        pt2 = cipher.decrypt(ct)
        self.assertEqual(pt, pt2)

    def test_iv(self):
        # If not passed, the iv is created randomly
        cipher = AES.new(self.key_128, self.aes_mode)
        iv1 = cipher.iv
        cipher = AES.new(self.key_128, self.aes_mode)
        iv2 = cipher.iv
        self.assertNotEqual(iv1, iv2)
        self.assertEqual(len(iv1), 16)

        # IV can be passed in uppercase or lowercase
        cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
        ct = cipher.encrypt(self.data_128)

        cipher = AES.new(self.key_128, self.aes_mode, iv=self.iv_128)
        self.assertEquals(ct, cipher.encrypt(self.data_128))

        cipher = AES.new(self.key_128, self.aes_mode, IV=self.iv_128)
        self.assertEquals(ct, cipher.encrypt(self.data_128))

    def test_iv_must_be_bytes(self):
        self.assertRaises(TypeError, AES.new, self.key_128, self.aes_mode,
                          iv = u'test1234567890-*')

    def test_only_one_iv(self):
        # Only one IV/iv keyword allowed
        self.assertRaises(TypeError, AES.new, self.key_128, self.aes_mode,
                          iv=self.iv_128, IV=self.iv_128)

    def test_iv_with_matching_length(self):
        self.assertRaises(ValueError, AES.new, self.key_128, self.aes_mode,
                          b"")
        self.assertRaises(ValueError, AES.new, self.key_128, self.aes_mode,
                          self.iv_128[:15])
        self.assertRaises(ValueError, AES.new, self.key_128, self.aes_mode,
                          self.iv_128 + b"0")

    def test_block_size_128(self):
        cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
        self.assertEqual(cipher.block_size, AES.block_size)

    def test_block_size_64(self):
        cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64)
        self.assertEqual(cipher.block_size, DES3.block_size)

    def test_unaligned_data_128(self):
        cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
        for wrong_length in range(1,16):
            self.assertRaises(ValueError, cipher.encrypt, b"5" * wrong_length)

        cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
        for wrong_length in range(1,16):
            self.assertRaises(ValueError, cipher.decrypt, b"5" * wrong_length)

    def test_unaligned_data_64(self):
        cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64)
        for wrong_length in range(1,8):
            self.assertRaises(ValueError, cipher.encrypt, b"5" * wrong_length)

        cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64)
        for wrong_length in range(1,8):
            self.assertRaises(ValueError, cipher.decrypt, b"5" * wrong_length)

    def test_IV_iv_attributes(self):
        data = get_tag_random("data", 16 * 100)
        for func in "encrypt", "decrypt":
            cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
            getattr(cipher, func)(data)
            self.assertEqual(cipher.iv, self.iv_128)
            self.assertEqual(cipher.IV, self.iv_128)

    def test_unknown_parameters(self):
        self.assertRaises(TypeError, AES.new, self.key_128, self.aes_mode,
                          self.iv_128, 7)
        self.assertRaises(TypeError, AES.new, self.key_128, self.aes_mode,
                          iv=self.iv_128, unknown=7)
        # But some are only known by the base cipher (e.g. use_aesni consumed by the AES module)
        AES.new(self.key_128, self.aes_mode, iv=self.iv_128, use_aesni=False)

    def test_null_encryption_decryption(self):
        for func in "encrypt", "decrypt":
            cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
            result = getattr(cipher, func)(b"")
            self.assertEqual(result, b"")

    def test_either_encrypt_or_decrypt(self):
        cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
        cipher.encrypt(b"")
        self.assertRaises(TypeError, cipher.decrypt, b"")

        cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
        cipher.decrypt(b"")
        self.assertRaises(TypeError, cipher.encrypt, b"")

    def test_data_must_be_bytes(self):
        cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
        self.assertRaises(TypeError, cipher.encrypt, u'test1234567890-*')

        cipher = AES.new(self.key_128, self.aes_mode, self.iv_128)
        self.assertRaises(TypeError, cipher.decrypt, u'test1234567890-*')

    def test_bytearray(self):
        data = b"1" * 16
        data_ba = bytearray(data)

        # Encrypt
        key_ba = bytearray(self.key_128)
        iv_ba = bytearray(self.iv_128)

        cipher1 = AES.new(self.key_128, self.aes_mode, self.iv_128)
        ref1 = cipher1.encrypt(data)

        cipher2 = AES.new(key_ba, self.aes_mode, iv_ba)
        key_ba[:3] = b'\xFF\xFF\xFF'
        iv_ba[:3] = b'\xFF\xFF\xFF'
        ref2 = cipher2.encrypt(data_ba)

        self.assertEqual(ref1, ref2)
        self.assertEqual(cipher1.iv, cipher2.iv)

        # Decrypt
        key_ba = bytearray(self.key_128)
        iv_ba = bytearray(self.iv_128)

        cipher3 = AES.new(self.key_128, self.aes_mode, self.iv_128)
        ref3 = cipher3.decrypt(data)

        cipher4 = AES.new(key_ba, self.aes_mode, iv_ba)
        key_ba[:3] = b'\xFF\xFF\xFF'
        iv_ba[:3] = b'\xFF\xFF\xFF'
        ref4 = cipher4.decrypt(data_ba)

        self.assertEqual(ref3, ref4)

    def test_memoryview(self):
        data = b"1" * 16
        data_mv = memoryview(bytearray(data))

        # Encrypt
        key_mv = memoryview(bytearray(self.key_128))
        iv_mv = memoryview(bytearray(self.iv_128))

        cipher1 = AES.new(self.key_128, self.aes_mode, self.iv_128)
        ref1 = cipher1.encrypt(data)

        cipher2 = AES.new(key_mv, self.aes_mode, iv_mv)
        key_mv[:3] = b'\xFF\xFF\xFF'
        iv_mv[:3] = b'\xFF\xFF\xFF'
        ref2 = cipher2.encrypt(data_mv)

        self.assertEqual(ref1, ref2)
        self.assertEqual(cipher1.iv, cipher2.iv)

        # Decrypt
        key_mv = memoryview(bytearray(self.key_128))
        iv_mv = memoryview(bytearray(self.iv_128))

        cipher3 = AES.new(self.key_128, self.aes_mode, self.iv_128)
        ref3 = cipher3.decrypt(data)

        cipher4 = AES.new(key_mv, self.aes_mode, iv_mv)
        key_mv[:3] = b'\xFF\xFF\xFF'
        iv_mv[:3] = b'\xFF\xFF\xFF'
        ref4 = cipher4.decrypt(data_mv)

        self.assertEqual(ref3, ref4)
    
    def test_output_param(self):

        pt = b'5' * 16
        cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
        ct = cipher.encrypt(pt)

        output = bytearray(16)
        cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
        res = cipher.encrypt(pt, output=output)
        self.assertEqual(ct, output)
        self.assertEqual(res, None)
        
        cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
        res = cipher.decrypt(ct, output=output)
        self.assertEqual(pt, output)
        self.assertEqual(res, None)

    def test_output_param_memoryview(self):
        
        pt = b'5' * 16
        cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
        ct = cipher.encrypt(pt)

        output = memoryview(bytearray(16))
        cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
        cipher.encrypt(pt, output=output)
        self.assertEqual(ct, output)
        
        cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
        cipher.decrypt(ct, output=output)
        self.assertEqual(pt, output)

    def test_output_param_neg(self):

        pt = b'5' * 16
        cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
        ct = cipher.encrypt(pt)

        cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
        self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*16)
        
        cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
        self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*16)

        shorter_output = bytearray(15)
        cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
        self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
        cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128)
        self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)


    import sys
    if sys.version[:3] == "2.6":
        del test_memoryview
        del test_output_param_memoryview


class CbcTests(BlockChainingTests):
    aes_mode = AES.MODE_CBC
    des3_mode = DES3.MODE_CBC


class NistBlockChainingVectors(unittest.TestCase):

    def _do_kat_aes_test(self, file_name):
        test_vectors = load_tests(("Crypto", "SelfTest", "Cipher", "test_vectors", "AES"),
                                  file_name,
                                  "AES KAT",
                                  { "count" : lambda x: int(x) } )
        assert(test_vectors)

        direction = None
        for tv in test_vectors:

            # The test vector file contains some directive lines
            if is_string(tv):
                direction = tv
                continue

            self.description = tv.desc

            cipher = AES.new(tv.key, self.aes_mode, tv.iv)
            if direction == "[ENCRYPT]":
                self.assertEqual(cipher.encrypt(tv.plaintext), tv.ciphertext)
            elif direction == "[DECRYPT]":
                self.assertEqual(cipher.decrypt(tv.ciphertext), tv.plaintext)
            else:
                assert False

    # See Section 6.4.2 in AESAVS
    def _do_mct_aes_test(self, file_name):
        test_vectors = load_tests(("Crypto", "SelfTest", "Cipher", "test_vectors", "AES"),
                                  file_name,
                                  "AES Montecarlo",
                                  { "count" : lambda x: int(x) } )
        assert(test_vectors)

        direction = None
        for tv in test_vectors:

            # The test vector file contains some directive lines
            if is_string(tv):
                direction = tv
                continue

            self.description = tv.desc
            cipher = AES.new(tv.key, self.aes_mode, tv.iv)

            if direction == '[ENCRYPT]':
                cts = [ tv.iv ]
                for count in range(1000):
Loading ...