Example #1
0
 def __init__(self, block_length, k):
     self.block_length = block_length
     self.aes_cipher = Cipher(algorithms.AES(k), modes.ECB(),
                              default_backend())
     self.pad = padding.PKCS7(8 * block_length)
    def decrypt_file(metadata,
                     encryption_material,
                     in_filename,
                     chunk_size=block_size * 4 * 1024,
                     tmp_dir=None):
        """Decrypts a file and stores the output in the temporary directory.

        Args:
            metadata: The file's metadata input.
            encryption_material: The file's encryption material.
            in_filename: The name of the input file.
            chunk_size: The size of read chunks (Default value = block_size * 4 * 1024).
            tmp_dir: Temporary directory to use, optional (Default value = None).

        Returns:
            The decrypted file's location.
        """
        logger = getLogger(__name__)
        use_openssl_only = os.getenv('SF_USE_OPENSSL_ONLY', 'False') == 'True'
        key_base64 = metadata.key
        iv_base64 = metadata.iv
        decoded_key = base64.standard_b64decode(
            encryption_material.query_stage_master_key)
        key_bytes = base64.standard_b64decode(key_base64)
        iv_bytes = base64.standard_b64decode(iv_base64)

        if not use_openssl_only:
            key_cipher = AES.new(key=decoded_key, mode=AES.MODE_ECB)
            file_key = PKCS5_UNPAD(key_cipher.decrypt(key_bytes))
            data_cipher = AES.new(key=file_key, mode=AES.MODE_CBC, IV=iv_bytes)
        else:
            backend = default_backend()
            cipher = Cipher(algorithms.AES(decoded_key),
                            modes.ECB(),
                            backend=backend)
            decryptor = cipher.decryptor()
            file_key = PKCS5_UNPAD(
                decryptor.update(key_bytes) + decryptor.finalize())
            cipher = Cipher(algorithms.AES(file_key),
                            modes.CBC(iv_bytes),
                            backend=backend)
            decryptor = cipher.decryptor()

        temp_output_fd, temp_output_file = tempfile.mkstemp(
            text=False,
            dir=tmp_dir,
            prefix=os.path.basename(in_filename) + "#")
        total_file_size = 0
        prev_chunk = None
        logger.debug('encrypted file: %s, tmp file: %s', in_filename,
                     temp_output_file)
        with open(in_filename, 'rb') as infile:
            with os.fdopen(temp_output_fd, 'wb') as outfile:
                while True:
                    chunk = infile.read(chunk_size)
                    if len(chunk) == 0:
                        break
                    total_file_size += len(chunk)
                    if not use_openssl_only:
                        d = data_cipher.decrypt(chunk)
                    else:
                        d = decryptor.update(chunk)
                    outfile.write(d)
                    prev_chunk = d
                if prev_chunk is not None:
                    total_file_size -= PKCS5_OFFSET(prev_chunk)
                if use_openssl_only:
                    outfile.write(decryptor.finalize())
                outfile.truncate(total_file_size)
        return temp_output_file
Example #3
0
            "CBCVarKey256.rsp",
            "CBCVarTxt128.rsp",
            "CBCVarTxt192.rsp",
            "CBCVarTxt256.rsp",
            "CBCMMT128.rsp",
            "CBCMMT192.rsp",
            "CBCMMT256.rsp",
        ],
        lambda key, **kwargs: algorithms.AES(binascii.unhexlify(key)),
        lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv)),
    )


@pytest.mark.supported(
    only_if=lambda backend: backend.cipher_supported(
        algorithms.AES(b"\x00" * 16), modes.ECB()
    ),
    skip_message="Does not support AES ECB",
)
class TestAESModeECB(object):
    test_ecb = generate_encrypt_test(
        load_nist_vectors,
        os.path.join("ciphers", "AES", "ECB"),
        [
            "ECBGFSbox128.rsp",
            "ECBGFSbox192.rsp",
            "ECBGFSbox256.rsp",
            "ECBKeySbox128.rsp",
            "ECBKeySbox192.rsp",
            "ECBKeySbox256.rsp",
            "ECBVarKey128.rsp",
        lambda iv, **kwargs: modes.CFB8(binascii.unhexlify(iv)),
    )

    test_mmt = generate_encrypt_test(
        load_nist_vectors,
        os.path.join("ciphers", "3DES", "CFB"),
        ["TCFB8MMT1.rsp", "TCFB8MMT2.rsp", "TCFB8MMT3.rsp"],
        lambda key1, key2, key3, **kwargs: algorithms.TripleDES(
            binascii.unhexlify(key1 + key2 + key3)),
        lambda iv, **kwargs: modes.CFB8(binascii.unhexlify(iv)),
    )


@pytest.mark.supported(
    only_if=lambda backend: backend.cipher_supported(
        algorithms.TripleDES(b"\x00" * 8), modes.ECB()),
    skip_message="Does not support TripleDES ECB",
)
class TestTripleDESModeECB(object):
    test_kat = generate_encrypt_test(
        load_nist_vectors,
        os.path.join("ciphers", "3DES", "ECB"),
        [
            "TECBinvperm.rsp",
            "TECBpermop.rsp",
            "TECBsubtab.rsp",
            "TECBvarkey.rsp",
            "TECBvartext.rsp",
        ],
        lambda keys, **kwargs: algorithms.TripleDES(binascii.unhexlify(keys)),
        lambda **kwargs: modes.ECB(),
class TestAESKeyWrap(object):
    @pytest.mark.parametrize(
        "params",
        _load_all_params(os.path.join("keywrap", "kwtestvectors"),
                         ["KW_AE_128.txt", "KW_AE_192.txt", "KW_AE_256.txt"],
                         load_nist_vectors))
    @pytest.mark.supported(
        only_if=lambda backend: backend.cipher_supported(
            algorithms.AES(b"\x00" * 16), modes.ECB()),
        skip_message="Does not support AES key wrap (RFC 3394) because AES-ECB"
        " is unsupported",
    )
    def test_wrap(self, backend, params):
        wrapping_key = binascii.unhexlify(params["k"])
        key_to_wrap = binascii.unhexlify(params["p"])
        wrapped_key = keywrap.aes_key_wrap(wrapping_key, key_to_wrap, backend)
        assert params["c"] == binascii.hexlify(wrapped_key)

    @pytest.mark.parametrize(
        "params",
        _load_all_params(os.path.join("keywrap", "kwtestvectors"),
                         ["KW_AD_128.txt", "KW_AD_192.txt", "KW_AD_256.txt"],
                         load_nist_vectors))
    @pytest.mark.supported(
        only_if=lambda backend: backend.cipher_supported(
            algorithms.AES(b"\x00" * 16), modes.ECB()),
        skip_message="Does not support AES key wrap (RFC 3394) because AES-ECB"
        " is unsupported",
    )
    def test_unwrap(self, backend, params):
        wrapping_key = binascii.unhexlify(params["k"])
        wrapped_key = binascii.unhexlify(params["c"])
        if params.get("fail") is True:
            with pytest.raises(keywrap.InvalidUnwrap):
                keywrap.aes_key_unwrap(wrapping_key, wrapped_key, backend)
        else:
            unwrapped_key = keywrap.aes_key_unwrap(wrapping_key, wrapped_key,
                                                   backend)
            assert params["p"] == binascii.hexlify(unwrapped_key)

    @pytest.mark.supported(
        only_if=lambda backend: backend.cipher_supported(
            algorithms.AES(b"\x00" * 16), modes.ECB()),
        skip_message="Does not support AES key wrap (RFC 3394) because AES-ECB"
        " is unsupported",
    )
    def test_wrap_invalid_key_length(self, backend):
        # The wrapping key must be of length [16, 24, 32]
        with pytest.raises(ValueError):
            keywrap.aes_key_wrap(b"badkey", b"sixteen_byte_key", backend)

    @pytest.mark.supported(
        only_if=lambda backend: backend.cipher_supported(
            algorithms.AES(b"\x00" * 16), modes.ECB()),
        skip_message="Does not support AES key wrap (RFC 3394) because AES-ECB"
        " is unsupported",
    )
    def test_unwrap_invalid_key_length(self, backend):
        with pytest.raises(ValueError):
            keywrap.aes_key_unwrap(b"badkey", b"\x00" * 24, backend)

    @pytest.mark.supported(
        only_if=lambda backend: backend.cipher_supported(
            algorithms.AES(b"\x00" * 16), modes.ECB()),
        skip_message="Does not support AES key wrap (RFC 3394) because AES-ECB"
        " is unsupported",
    )
    def test_wrap_invalid_key_to_wrap_length(self, backend):
        # Keys to wrap must be at least 16 bytes long
        with pytest.raises(ValueError):
            keywrap.aes_key_wrap(b"sixteen_byte_key", b"\x00" * 15, backend)

        # Keys to wrap must be a multiple of 8 bytes
        with pytest.raises(ValueError):
            keywrap.aes_key_wrap(b"sixteen_byte_key", b"\x00" * 23, backend)

    def test_unwrap_invalid_wrapped_key_length(self, backend):
        # Keys to unwrap must be at least 24 bytes
        with pytest.raises(ValueError):
            keywrap.aes_key_unwrap(b"sixteen_byte_key", b"\x00" * 16, backend)

        # Keys to unwrap must be a multiple of 8 bytes
        with pytest.raises(ValueError):
            keywrap.aes_key_unwrap(b"sixteen_byte_key", b"\x00" * 27, backend)
 def _decrypt_dek(self, key):
     """ Decrypt AES data encryption key with AES key encryption key: openpgp-do.c decrypt_dek """
     assert len(key) == AES_SIZE
     dec = Cipher(algorithms.AES(key), modes.ECB(), default_backend()).decryptor()
     return dec.update(self.dek) + dec.finalize()
Example #7
0
    def test_invalid_key_type(self):
        with pytest.raises(TypeError, match="key must be bytes"):
            SEED(u"0" * 16)


def test_invalid_backend():
    pretend_backend = object()

    with raises_unsupported_algorithm(_Reasons.BACKEND_MISSING_INTERFACE):
        ciphers.Cipher(AES(b"AAAAAAAAAAAAAAAA"), modes.ECB, pretend_backend)


@pytest.mark.supported(
    only_if=lambda backend: backend.cipher_supported(AES(b"\x00" * 16),
                                                     modes.ECB()),
    skip_message="Does not support AES ECB",
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestCipherUpdateInto(object):
    @pytest.mark.parametrize(
        "params",
        load_vectors_from_file(
            os.path.join("ciphers", "AES", "ECB", "ECBGFSbox128.rsp"),
            load_nist_vectors,
        ),
    )
    def test_update_into(self, params, backend):
        key = binascii.unhexlify(params["key"])
        pt = binascii.unhexlify(params["plaintext"])
        ct = binascii.unhexlify(params["ciphertext"])
Example #8
0
def _mysql_aes_engine(key):
    """Create MYSQL AES cipher engine."""
    return Cipher(algorithms.AES(key), modes.ECB(), default_backend())
Example #9
0
def encrypt_aes_ecb(plaintext, key):
    cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=default_backend()) 
    encryptor = cipher.encryptor()
    return encryptor.update(plaintext) + encryptor.finalize()
Example #10
0
passwd = b'password'
ivval = b'hello'

key = kdf.derive(passwd)
iv = idf.derive(ivval)

print("key", key.hex())
print("iv", iv.hex())

#####
# 2.2
#####
cipher = Cipher(
    algorithm=algorithms.AES(key),
    #mode=modes.CBC(iv),
    mode=modes.ECB(),
    backend=backend)
encryptor = cipher.encryptor()

#mydata = b'this is my long data for this task to ensure that multiple blocks are processed during the cipher'
#print("my data", mydata)
#print("my data hex", mydata.hex())

padder = padding.PKCS7(128).padder()
mydata = b'1234567812345678'
mydata_pad = padder.update(mydata) + padder.finalize()
print("padded data", mydata_pad.hex())
ciphertext = encryptor.update(mydata_pad) + encryptor.finalize()
#ciphertext = encryptor.update(mydata) + encryptor.finalize()
print("ciphertext", ciphertext.hex())
Example #11
0
from __future__ import absolute_import, division, print_function

import binascii
import os

import pytest

from cryptography.hazmat.primitives.ciphers import algorithms, modes

from .utils import generate_encrypt_test
from ...utils import load_nist_vectors


@pytest.mark.supported(
    only_if=lambda backend: backend.cipher_supported(
        algorithms.SEED("\x00" * 16), modes.ECB()),
    skip_message="Does not support SEED ECB",
)
@pytest.mark.cipher
class TestSEEDModeECB(object):
    test_ECB = generate_encrypt_test(
        load_nist_vectors,
        os.path.join("ciphers", "SEED"),
        ["rfc-4269.txt"],
        lambda key, **kwargs: algorithms.SEED(binascii.unhexlify((key))),
        lambda **kwargs: modes.ECB(),
    )


@pytest.mark.supported(
    only_if=lambda backend: backend.cipher_supported(
Example #12
0
def _calculate_iv(key, counter):
    encryptor = Cipher(algorithms.AES(key),
                       modes.ECB(),
                       backend=default_backend()).encryptor()
    return encryptor.update(int_to_bytes(counter, 16)) + encryptor.finalize()
Example #13
0
def aes_ecb_decrypt(ciphertext, key):
    cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
    decryptor = cipher.decryptor()
    unpadder = padding.PKCS7(cipher.algorithm.block_size).unpadder()
    padded = decryptor.update(b64d(ciphertext)) + decryptor.finalize()
    return unpadder.update(padded) + unpadder.finalize()
Example #14
0
 def __init__(self, key):
     super().__init__(Cipher(algorithms.AES(key), modes.ECB()))
Example #15
0
def digest_secure_bootloader(args):
    """ Calculate the digest of a bootloader image, in the same way the hardware
    secure boot engine would do so. Can be used with a pre-loaded key to update a
    secure bootloader. """
    _check_output_is_not_input(args.keyfile, args.output)
    _check_output_is_not_input(args.image, args.output)
    _check_output_is_not_input(args.iv, args.output)
    if args.iv is not None:
        print("WARNING: --iv argument is for TESTING PURPOSES ONLY")
        iv = args.iv.read(128)
    else:
        iv = os.urandom(128)
    plaintext_image = args.image.read()
    args.image.seek(0)

    # secure boot engine reads in 128 byte blocks (ie SHA512 block
    # size), but also doesn't look for any appended SHA-256 digest
    fw_image = esptool.ESP32FirmwareImage(args.image)
    if fw_image.append_digest:
        if len(plaintext_image) % 128 <= 32:
            # ROM bootloader will read to the end of the 128 byte block, but not
            # to the end of the SHA-256 digest at the end
            new_len = len(plaintext_image) - (len(plaintext_image) % 128)
            plaintext_image = plaintext_image[:new_len]

    # if image isn't 128 byte multiple then pad with 0xFF (ie unwritten flash)
    # as this is what the secure boot engine will see
    if len(plaintext_image) % 128 != 0:
        plaintext_image += b"\xFF" * (128 - (len(plaintext_image) % 128))

    plaintext = iv + plaintext_image

    # Secure Boot digest algorithm in hardware uses AES256 ECB to
    # produce a ciphertext, then feeds output through SHA-512 to
    # produce the digest. Each block in/out of ECB is reordered
    # (due to hardware quirks not for security.)

    key = _load_hardware_key(args.keyfile)
    backend = default_backend()
    cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
    encryptor = cipher.encryptor()
    digest = hashlib.sha512()

    for block in get_chunks(plaintext, 16):
        block = block[::-1]  # reverse each input block

        cipher_block = encryptor.update(block)
        # reverse and then byte swap each word in the output block
        cipher_block = cipher_block[::-1]
        for block in get_chunks(cipher_block, 4):
            # Python hashlib can build each SHA block internally
            digest.update(block[::-1])

    if args.output is None:
        args.output = os.path.splitext(
            args.image.name)[0] + "-digest-0x0000.bin"
    with open(args.output, "wb") as f:
        f.write(iv)
        digest = digest.digest()
        for word in get_chunks(digest, 4):
            f.write(word[::-1])  # swap word order in the result
        f.write(b'\xFF' * (0x1000 - f.tell()))  # pad to 0x1000
        f.write(plaintext_image)
    print("digest+image written to %s" % args.output)
Example #16
0
def decrypt_aes_ecb(ciphertext, key):
    cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=default_backend()) 
    decryptor = cipher.decryptor()
    plaintext = decryptor.update(ciphertext) + decryptor.finalize()
    return plaintext
Example #17
0
def decrypt(data, key):
    cipher = Cipher(algorithms.AES(key),
                    modes.ECB(),
                    backend=default_backend())
    decryptor = cipher.decryptor()
    return decryptor.update(data) + decryptor.finalize()
Example #18
0
 def __init__(self, key):
     backend = default_backend()
     self.cipher = Cipher(algorithms.AES(key), modes.ECB(), backend)
     self.padder = padding.PKCS7(len(key) * 8)
Example #19
0
def aes_ecb_encrypt(message, key):
    cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
    encryptor = cipher.encryptor()
    padder = padding.PKCS7(cipher.algorithm.block_size).padder()
    padded = padder.update(message) + padder.finalize()
    return b64e(encryptor.update(padded) + encryptor.finalize())
Example #20
0
KEY = b"YELLOW SUBMARINE"
BLOCK_SIZE = 16


def blocks(l, n=BLOCK_SIZE):
    for i in range(0, len(l) // n):
        yield l[i * n:(i + 1) * n]


if __name__ == "__main__":
    with open('10.txt') as f:
        ciphertext = base64.b64decode(f.read())

        backend = default_backend()
        cipher = Cipher(algorithms.AES(KEY), modes.ECB(), backend=backend)

        iv = b"\x00" * BLOCK_SIZE

        plaintext = ""
        for ciphertext_block in blocks(ciphertext):
            decryptor = cipher.decryptor()
            plaintext_block = decryptor.update(
                ciphertext_block) + decryptor.finalize()
            plaintext_block = bytes(
                [a ^ b for (a, b) in zip(iv, plaintext_block)])
            plaintext += plaintext_block.decode('utf8')

            iv = ciphertext_block

        print(plaintext)
Example #21
0
def tests(device_details, encryption_function):
    # initialize row for database entry
    new_row = {
        "device": device_details,
        "algo": None,
        "start_time": None,
        "end_time": None,
        "total_time": None,
        "sensor_data": "b'a secret message'",
        "cypher_text": None,
        "test_number": None
    }
    # convert the dictionary into a proper JSON object
    # device_data = json.dumps(device_details, indent=4, sort_keys=False)
    # generate keys
    backend = default_backend()
    salt = os.urandom(16)
    # AES key derivation function and key
    aes_kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),
                         length=32,
                         salt=salt,
                         iterations=100000,
                         backend=backend)
    aes_key = aes_kdf.derive(b"password")
    # 3DES key derivation fucntion and key
    des3_kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),
                          length=24,
                          salt=salt,
                          iterations=100000,
                          backend=backend)
    des3_key = des3_kdf.derive(b"password")
    # SEED key derivation fucntion and key
    seed_kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),
                          length=16,
                          salt=salt,
                          iterations=100000,
                          backend=backend)
    seed_key = seed_kdf.derive(b"password")

    # cycle through three encryption algorithms (AES, 3DES, and SEED)
    algos = {
        "AES_CBC": {
            'algo': algorithms.AES(aes_key),
            'mode': modes.CBC(os.urandom(16))
        },
        "AES_ECB": {
            'algo': algorithms.AES(aes_key),
            'mode': modes.ECB()
        },
        "AES_CFB": {
            'algo': algorithms.AES(aes_key),
            'mode': modes.CFB(os.urandom(16))
        },
        "AES_CTR": {
            'algo': algorithms.AES(aes_key),
            'mode': modes.CTR(os.urandom(16))
        },
        "AES_OFB": {
            'algo': algorithms.AES(aes_key),
            'mode': modes.OFB(os.urandom(16))
        },
        "3DES": {
            'algo': algorithms.TripleDES(des3_key),
            'mode': modes.CBC(os.urandom(8))
        },
        "SEED": {
            'algo': algorithms.SEED(seed_key),
            'mode': modes.CBC(os.urandom(16))
        }
    }
    print("Device OS, OS Release, Processor, Algorithm, Average")
    for selected_algo in algos:
        # go through each algorithm and run the test for each one 10x
        times_to_repeat = 10000
        i = 0
        new_row['algo'] = selected_algo
        total_run_time = 0
        while times_to_repeat >= i:
            # choose an algorithm for the test
            algorithm_with_key = algos[selected_algo]
            # record start time
            new_row['start_time'] = int(round(time.time() * 10000000))
            # encrypt the data
            new_row['cypher_text'] = encryption_function(algorithm_with_key)
            # connect to database
            # record end time
            new_row['end_time'] = int(round(time.time() * 10000000))
            # subtract end from start time
            new_row['total_time'] = (new_row['end_time'] -
                                     new_row['start_time'])
            # record test number
            new_row['test_number'] = i
            # decrement counter
            i += 1
            total_run_time += new_row['total_time']

            # print result
            #print("----\n%s algorithm on attempt %d took %d"%(selected_algo, i, new_row['total_time']))
            #print("RAW ROW DATA %s ATTEMPT %d: %s"%(selected_algo,i,new_row))
        print(
            "%s, %s, %s, %s, %s" %
            (device_details()['os']['name'], device_details()['os']['release'],
             device_details()['processor'], selected_algo,
             str(total_run_time / (times_to_repeat + 1))))


###############
#process_telemetry(device_profile())
def encrypt_aes_128_ecb(msg, key):
    padded_msg = pkcs7_padding(msg, block_size=16)
    cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
    encryptor = cipher.encryptor()
    return encryptor.update(padded_msg) + encryptor.finalize()
Example #23
0
keepassheader.check_version_support(keepass)
keepassheader.read(keepass)

m = hashlib.sha256()

m.update(b'Password01')
pwd_hash = m.digest()

m = hashlib.sha256()
m.update(pwd_hash)

composite_key = m.digest()

backend = default_backend()

cipher = Cipher(algorithms.AES(keepassheader.transform_seed), modes.ECB(),
                backend)
encryptor = cipher.encryptor()

transformed_key = composite_key
for round in range(0, keepassheader.transform_rounds):
    transformed_key = encryptor.update(transformed_key)
m = hashlib.sha256()
m.update(transformed_key)
transformed_key = m.digest()
masterkey = keepassheader.master_seed + transformed_key

cipher = Cipher(algorithms.AES(masterkey),
                modes.CBC(keepassheader.encryption_iv), backend)
encryptor = cipher.encryptor()
def block_decrypt_aes_128_ecb(ctxt, i, key):
    cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
    decryptor = cipher.decryptor()
    decrypted_data = decryptor.update(cipher_text) + decryptor.finalize()
    message = pkcs7_strip(decrypted_data)
    return message[i * 16:(i + 1) * 16]
import binascii
import os

import pytest

from cryptography.hazmat.backends.interfaces import CipherBackend
from cryptography.hazmat.primitives.ciphers import algorithms, modes

from .utils import generate_encrypt_test
from ...utils import load_cryptrec_vectors, load_nist_vectors


@pytest.mark.supported(
    only_if=lambda backend: backend.cipher_supported(
        algorithms.Camellia(b"\x00" * 16), modes.ECB()),
    skip_message="Does not support Camellia ECB",
)
@pytest.mark.requires_backend_interface(interface=CipherBackend)
class TestCamelliaModeECB(object):
    test_ecb = generate_encrypt_test(
        load_cryptrec_vectors,
        os.path.join("ciphers", "Camellia"),
        [
            "camellia-128-ecb.txt",
            "camellia-192-ecb.txt",
            "camellia-256-ecb.txt",
        ],
        lambda key, **kwargs: algorithms.Camellia(binascii.unhexlify(key)),
        lambda **kwargs: modes.ECB(),
    )
def aes_ecb(k, m):
    c = Cipher(algorithms.AES(k), modes.ECB(), backend=default_backend())
    e = c.encryptor()
    return e.update(m) + e.finalize()
    def encrypt_file(encryption_material,
                     in_filename,
                     chunk_size=block_size * 4 * 1024,
                     tmp_dir=None):
        """Encrypts a file in a temporary directory.

        Args:
            encryption_material: The encryption material for file.
            in_filename: The input file's name.
            chunk_size: The size of read chunks (Default value = block_size * 4 * 1024).
            tmp_dir: Temporary directory to use, optional (Default value = None).

        Returns:
            The encrypted file's location.
        """
        logger = getLogger(__name__)
        use_openssl_only = os.getenv('SF_USE_OPENSSL_ONLY', 'False') == 'True'
        decoded_key = base64.standard_b64decode(
            encryption_material.query_stage_master_key)
        key_size = len(decoded_key)
        logger.debug('key_size = %s', key_size)

        # Generate key for data encryption
        iv_data = SnowflakeEncryptionUtil.get_secure_random(block_size)
        file_key = SnowflakeEncryptionUtil.get_secure_random(key_size)
        if not use_openssl_only:
            data_cipher = AES.new(key=file_key, mode=AES.MODE_CBC, IV=iv_data)
        else:
            backend = default_backend()
            cipher = Cipher(algorithms.AES(file_key),
                            modes.CBC(iv_data),
                            backend=backend)
            encryptor = cipher.encryptor()

        temp_output_fd, temp_output_file = tempfile.mkstemp(
            text=False,
            dir=tmp_dir,
            prefix=os.path.basename(in_filename) + "#")
        padded = False
        logger.debug('unencrypted file: %s, temp file: %s, tmp_dir: %s',
                     in_filename, temp_output_file, tmp_dir)
        with open(in_filename, 'rb') as infile:
            with os.fdopen(temp_output_fd, 'wb') as outfile:
                while True:
                    chunk = infile.read(chunk_size)
                    if len(chunk) == 0:
                        break
                    elif len(chunk) % block_size != 0:
                        chunk = PKCS5_PAD(chunk, block_size)
                        padded = True
                    if not use_openssl_only:
                        outfile.write(data_cipher.encrypt(chunk))
                    else:
                        outfile.write(encryptor.update(chunk))
                if not padded:
                    if not use_openssl_only:
                        outfile.write(
                            data_cipher.encrypt(block_size *
                                                chr(block_size).encode(UTF8)))
                    else:
                        outfile.write(
                            encryptor.update(block_size *
                                             chr(block_size).encode(UTF8)))
                if use_openssl_only:
                    outfile.write(encryptor.finalize())

        # encrypt key with QRMK
        if not use_openssl_only:
            key_cipher = AES.new(key=decoded_key, mode=AES.MODE_ECB)
            enc_kek = key_cipher.encrypt(PKCS5_PAD(file_key, block_size))
        else:
            cipher = Cipher(algorithms.AES(decoded_key),
                            modes.ECB(),
                            backend=backend)
            encryptor = cipher.encryptor()
            enc_kek = encryptor.update(PKCS5_PAD(
                file_key, block_size)) + encryptor.finalize()

        mat_desc = MaterialDescriptor(smk_id=encryption_material.smk_id,
                                      query_id=encryption_material.query_id,
                                      key_size=key_size * 8)
        metadata = EncryptionMetadata(
            key=base64.b64encode(enc_kek).decode('utf-8'),
            iv=base64.b64encode(iv_data).decode('utf-8'),
            matdesc=matdesc_to_unicode(mat_desc),
        )
        return metadata, temp_output_file
Example #28
0
def _flash_encryption_operation_esp32(output_file, input_file, flash_address,
                                      keyfile, flash_crypt_conf, do_decrypt):
    key = _load_hardware_key(keyfile)

    if flash_address % 16 != 0:
        raise esptool.FatalError(
            "Starting flash address 0x%x must be a multiple of 16" %
            flash_address)

    if flash_crypt_conf == 0:
        print("WARNING: Setting FLASH_CRYPT_CONF to zero is not recommended")

    if esptool.PYTHON2:
        tweak_range = _flash_encryption_tweak_range(flash_crypt_conf)
    else:
        tweak_range = _flash_encryption_tweak_range_bits(flash_crypt_conf)
        key = int.from_bytes(key, byteorder='big', signed=False)

    backend = default_backend()

    cipher = None
    block_offs = flash_address
    while True:
        block = input_file.read(16)
        if len(block) == 0:
            break
        elif len(block) < 16:
            if do_decrypt:
                raise esptool.FatalError(
                    "Data length is not a multiple of 16 bytes")
            pad = 16 - len(block)
            block = block + os.urandom(pad)
            print(
                "Note: Padding with %d bytes of random data (encrypted data must be multiple of 16 bytes long)"
                % pad)

        if block_offs % 32 == 0 or cipher is None:
            # each bit of the flash encryption key is XORed with tweak bits derived from the offset of 32 byte block of flash
            block_key = _flash_encryption_tweak_key(key, block_offs,
                                                    tweak_range)

            if cipher is None:  # first pass
                cipher = Cipher(algorithms.AES(block_key),
                                modes.ECB(),
                                backend=backend)

                # note AES is used inverted for flash encryption, so
                # "decrypting" flash uses AES encrypt algorithm and vice
                # versa. (This does not weaken AES.)
                actor = cipher.encryptor() if do_decrypt else cipher.decryptor(
                )
            else:
                # performance hack: changing the key using pyca-cryptography API requires recreating
                # 'actor'. With openssl backend, this re-initializes the openssl cipher context. To save some time,
                # manually call EVP_CipherInit_ex() in the openssl backend to update the key.
                # If it fails, fall back to recreating the entire context via public API.
                try:
                    backend = actor._ctx._backend
                    res = backend._lib.EVP_CipherInit_ex(
                        actor._ctx._ctx,
                        backend._ffi.NULL,
                        backend._ffi.NULL,
                        backend._ffi.from_buffer(block_key),
                        backend._ffi.NULL,
                        actor._ctx._operation,
                    )
                    backend.openssl_assert(res != 0)
                except AttributeError:
                    # backend is not an openssl backend, or implementation has changed: fall back to the slow safe version
                    cipher.algorithm.key = block_key
                    actor = cipher.encryptor(
                    ) if do_decrypt else cipher.decryptor()

        block = block[::-1]  # reverse input block byte order
        block = actor.update(block)

        output_file.write(block[::-1])  # reverse output block byte order
        block_offs += 16
Example #29
0
import os
import string
from copy import deepcopy

key = os.urandom(16)

# vi = os.urandom(16)
#FOR TESTING PURPOSES, ENSURE THIS VI VALUE IS MORE "CONTROLLED"
vi =  bytes('xxxxxxxxxxxxxxxx', 'utf-8')

print(vi)

aesCipher = Cipher(
    algorithms.AES(key),
    modes.ECB(),
    backend=default_backend()
)


aesEncriptor = aesCipher.encryptor()
aesDecriptor = aesCipher.decryptor()

class HandmadeCBC(object):
    def __init__(self):
        aesCipher = Cipher(
            algorithms.AES(key),
            modes.ECB(),
            backend=default_backend()
        )
Example #30
0
from __future__ import absolute_import, division, print_function

import binascii
import os

import pytest

from cryptography.hazmat.primitives.ciphers import algorithms, modes

from .utils import generate_encrypt_test
from ...utils import load_nist_vectors


@pytest.mark.supported(
    only_if=lambda backend: backend.cipher_supported(
        algorithms.IDEA("\x00" * 16), modes.ECB()),
    skip_message="Does not support IDEA ECB",
)
@pytest.mark.cipher
class TestIDEAModeECB(object):
    test_ECB = generate_encrypt_test(
        load_nist_vectors,
        os.path.join("ciphers", "IDEA"),
        ["idea-ecb.txt"],
        lambda key, **kwargs: algorithms.IDEA(binascii.unhexlify((key))),
        lambda **kwargs: modes.ECB(),
    )


@pytest.mark.supported(
    only_if=lambda backend: backend.cipher_supported(