| 1 |
#!/usr/bin/env python |
| 2 |
# -*- coding: UTF-8 -*- |
| 3 |
# |
| 4 |
# Copyright 2019-2024 NXP |
| 5 |
# |
| 6 |
# SPDX-License-Identifier: BSD-3-Clause |
| 7 |
|
| 8 |
"""OpenSSL implementation for symmetric key encryption.""" |
| 9 |
|
| 10 |
# Used security modules |
| 11 |
from typing import Optional |
| 12 |
|
| 13 |
from cryptography.hazmat.primitives import keywrap |
| 14 |
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes |
| 15 |
|
| 16 |
from ..utils.misc import Endianness |
| 17 |
|
| 18 |
|
| 19 |
class Counter: |
| 20 |
"""AES counter with specified counter byte ordering and customizable increment.""" |
| 21 |
|
| 22 |
@property |
| 23 |
def value(self) -> bytes: |
| 24 |
"""Initial vector for AES encryption.""" |
| 25 |
return self._nonce + self._ctr.to_bytes(4, self._ctr_byteorder_encoding.value) |
| 26 |
|
| 27 |
def __init__( |
| 28 |
self, |
| 29 |
nonce: bytes, |
| 30 |
ctr_value: Optional[int] = None, |
| 31 |
ctr_byteorder_encoding: Endianness = Endianness.LITTLE, |
| 32 |
) -> None: |
| 33 |
"""Constructor. |
| 34 |
|
| 35 |
:param nonce: last four bytes are used as initial value for counter |
| 36 |
:param ctr_value: counter initial value; it is added to counter value retrieved from nonce |
| 37 |
:param ctr_byteorder_encoding: way how the counter is encoded into output value |
| 38 |
:raises SPSDKError: When invalid byteorder is provided |
| 39 |
""" |
| 40 |
assert isinstance(nonce, bytes) and len(nonce) == 16 |
| 41 |
self._nonce = nonce[:-4] |
| 42 |
self._ctr_byteorder_encoding = ctr_byteorder_encoding |
| 43 |
self._ctr = int.from_bytes(nonce[-4:], ctr_byteorder_encoding.value) |
| 44 |
if ctr_value is not None: |
| 45 |
self._ctr += ctr_value |
| 46 |
|
| 47 |
def increment(self, value: int = 1) -> None: |
| 48 |
"""Increment counter by specified value. |
| 49 |
|
| 50 |
:param value: to add to counter |
| 51 |
""" |
| 52 |
self._ctr += value |
| 53 |
|
| 54 |
|
| 55 |
def aes_key_unwrap(kek: bytes, wrapped_key: bytes) -> bytes: |
| 56 |
"""Unwraps a key using a key-encrypting key (KEK). |
| 57 |
|
| 58 |
:param kek: The key-encrypting key |
| 59 |
:param wrapped_key: Encrypted data |
| 60 |
:return: Un-wrapped key |
| 61 |
""" |
| 62 |
return keywrap.aes_key_unwrap(kek, wrapped_key) |
| 63 |
|
| 64 |
|
| 65 |
def aes_ctr_decrypt(key: bytes, encrypted_data: bytes, nonce: bytes) -> bytes: |
| 66 |
"""Decrypt encrypted data with AES in CTR mode. |
| 67 |
|
| 68 |
:param key: The key for data decryption |
| 69 |
:param encrypted_data: Input data |
| 70 |
:param nonce: Nonce data with counter value |
| 71 |
:return: Decrypted data |
| 72 |
""" |
| 73 |
cipher = Cipher(algorithms.AES(key), modes.CTR(nonce)) |
| 74 |
enc = cipher.decryptor() |
| 75 |
return enc.update(encrypted_data) + enc.finalize() |