Skip to content

Commit fe36152

Browse files
committed
[feature] Default-AES-Implementierung kann optional installiert werden.
Eine auf cryptography basierende AES-Implementierung kann optional (`bec2format[aes]`) installiert werden.
1 parent af67776 commit fe36152

File tree

4 files changed

+185
-1
lines changed

4 files changed

+185
-1
lines changed

bec2format/__init__.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,8 @@
3636
FormatError,
3737
UnsupportedLegacyFirmwareError,
3838
)
39+
40+
try:
41+
from .extras import aes
42+
except ImportError:
43+
pass

bec2format/extras/aes.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
2+
3+
from bec2format import AES128, register_AES128
4+
5+
6+
@register_AES128
7+
class AES128Proxy(AES128):
8+
def __init__(self, key: bytes, iv: bytes) -> None:
9+
super().__init__(key, iv)
10+
self._cipher = Cipher(
11+
algorithms.AES128(self._key),
12+
modes.CBC(self._iv or b"\x00" * self.BLOCK_SIZE),
13+
)
14+
15+
def encrypt(self, data: bytes) -> bytes:
16+
pad_length = -len(data) % AES128.BLOCK_SIZE
17+
pad = b"" if pad_length == 0 else bytes([0x00] * pad_length)
18+
encryptor = self._cipher.encryptor()
19+
return encryptor.update(data + pad) + encryptor.finalize()
20+
21+
def decrypt(self, data: bytes) -> bytes:
22+
decryptor = self._cipher.decryptor()
23+
plaintext_padded = decryptor.update(data) + decryptor.finalize()
24+
return plaintext_padded.rstrip(b"\0")
25+
26+
def mac(self, data: bytes) -> bytes:
27+
return self.encrypt(data)[-16:]

poetry.lock

Lines changed: 148 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,11 @@ license = "MIT"
77

88
[tool.poetry.dependencies]
99
python = ">=3.10,<3.11"
10+
cryptography = { version = "*", optional = true }
11+
12+
[tool.poetry.extras]
13+
aes = ["cryptography"]
14+
1015

1116
[tool.poetry.dev-dependencies]
1217
pytest = "*"

0 commit comments

Comments
 (0)