Fix hexadecimal master key decoding

This commit is contained in:
2026-10-26 12:06:17 +08:00
parent 4adf7c4882
commit dd6d20e3a3
2 changed files with 16 additions and 6 deletions
@@ -28,6 +28,12 @@ def decode_master_key(value: str) -> bytes:
text = (value or "").strip()
if not text:
raise ValueError("KCA_MASTER_KEY is empty")
is_hex = len(text) == KEY_BYTES * 2 and all(
char in "0123456789abcdefABCDEF" for char in text
)
if is_hex:
raw = bytes.fromhex(text)
else:
try:
raw = base64.b64decode(text, validate=True)
except Exception: # noqa: BLE001
@@ -553,6 +553,10 @@ class ExportImportTest(unittest.TestCase):
class CryptoTest(unittest.TestCase):
def test_decode_hex_master_key(self) -> None:
expected = bytes(range(crypto.KEY_BYTES))
self.assertEqual(crypto.decode_master_key(expected.hex()), expected)
def test_envelope(self) -> None:
master = crypto.generate_master_key()
blob = crypto.encrypt_private_key(b"secret", "key-id", crypto.decode_master_key(master))