Skip to content

Commit

Permalink
[feature] Default-AES-Implementierung kann optional installiert werden.
Browse files Browse the repository at this point in the history
Eine auf cryptography basierende AES-Implementierung kann optional (`bec2format[aes]`) installiert werden.
  • Loading branch information
stefan-hoelzl committed Dec 4, 2024
1 parent af67776 commit 8849db9
Show file tree
Hide file tree
Showing 4 changed files with 184 additions and 1 deletion.
5 changes: 5 additions & 0 deletions bec2format/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,8 @@
FormatError,
UnsupportedLegacyFirmwareError,
)

try:
from .extras import aes
except ImportError:
pass
26 changes: 26 additions & 0 deletions bec2format/extras/aes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

from bec2format import AES128, register_AES128


@register_AES128
class AES128Proxy(AES128):
def __init__(self, key: bytes, iv: bytes) -> None:
super().__init__(key, iv)
self._cipher = Cipher(
algorithms.AES128(self._key), modes.CBC(self._iv or b"\x00" * 16)
)

def encrypt(self, data: bytes) -> bytes:
pad_length = -len(data) % AES128.BLOCK_SIZE
pad = b"" if pad_length == 0 else bytes([0x00] * pad_length)
encryptor = self._cipher.encryptor()
return encryptor.update(data + pad) + encryptor.finalize()

def decrypt(self, data: bytes) -> bytes:
decryptor = self._cipher.decryptor()
plaintext_padded = decryptor.update(data) + decryptor.finalize()
return plaintext_padded.rstrip(b"\0")

def mac(self, data: bytes) -> bytes:
return self.encrypt(data)[-16:]
149 changes: 148 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ license = "MIT"

[tool.poetry.dependencies]
python = ">=3.10,<3.11"
cryptography = { version = "*", optional = true }

[tool.poetry.extras]
aes = ["cryptography"]


[tool.poetry.dev-dependencies]
pytest = "*"
Expand Down

0 comments on commit 8849db9

Please sign in to comment.