Debian Codegraph @

src/bthome_ble/bthome_v1_encryption.py

raw symbols SCIP
1 """Example showing encoding and decoding of BTHome v1 advertisement"""
2
3 from __future__ import annotations
4
5 import binascii
6
7 from cryptography.hazmat.primitives.ciphers.aead import AESCCM
8
9
10 def parse_value(data: bytes) -> dict[str, float]:
11 """Parse decrypted payload to readable BTHome data"""
12 vlength = len(data)
13 if vlength >= 3:
14 temp = round(int.from_bytes(data[2:4], "little", signed=False) * 0.01, 2)
15 humi = round(int.from_bytes(data[6:8], "little", signed=False) * 0.01, 2)
16 print("Temperature:", temp, "Humidity:", humi)
17 return {"temperature": temp, "humidity": humi}
18 print("MsgLength:", vlength, "HexValue:", data.hex())
19 return {}
20
21
22 def decrypt_payload(
23 payload: bytes, mic: bytes, key: bytes, nonce: bytes
24 ) -> dict[str, float] | None:
25 """Decrypt payload."""
26 print("Nonce:", nonce.hex())
27 print("CryptData:", payload.hex())
28 print("Mic:", mic.hex())
29 cipher = AESCCM(key, tag_length=4)
30 print()
31 print("Starting Decryption data")
32 try:
33 data = cipher.decrypt(nonce, payload + mic, b"\x11")
34 except ValueError as error:
35 print()
36 print("Decryption failed:", error)
37 return None
38 print("Decryption succeeded, decrypted data:", data.hex())
39 print()
40 return parse_value(data=data)
41
42
43 def decrypt_aes_ccm(key: bytes, mac: bytes, data: bytes) -> dict[str, float] | None:
44 """Decrypt AES CCM."""
45 print("MAC:", mac.hex())
46 print("Bindkey:", key.hex())
47 adslength = len(data)
48 if adslength > 12 and data[0] == 0x1E and data[1] == 0x18:
49 pkt = data[: data[0] + 1]
50 uuid = pkt[0:2]
51 encrypted_data = pkt[2:-8]
52 count_id = pkt[-8:-4]
53 mic = pkt[-4:]
54 # nonce: mac [6], uuid16 [2], count_id [4] # 6+2+4 = 12 bytes
55 nonce = b"".join([mac, uuid, count_id])
56 return decrypt_payload(encrypted_data, mic, key, nonce)
57 else:
58 print("Error: format packet!")
59 return None
60
61
62 def encrypt_payload(
63 data: bytes, mac: bytes, uuid16: bytes, count_id: bytes, key: bytes
64 ) -> bytes:
65 """Encrypt payload."""
66 nonce = b"".join([mac, uuid16, count_id]) # 6+2+4 = 12 bytes
67 cipher = AESCCM(key, tag_length=4)
68 associated_data = b"\x11"
69 result = cipher.encrypt(nonce, data, associated_data)
70 ciphertext = result[:-4]
71 mic = result[-4:]
72 print("MAC:", mac.hex())
73 print("Binkey:", key.hex())
74 print("Data:", data.hex())
75 print("Nonce:", nonce.hex())
76 print("CryptData:", ciphertext.hex(), "Mic:", mic.hex())
77 return b"".join([uuid16, ciphertext, count_id, mic])
78
79
80 # =============================
81 # main()
82 # =============================
83 def main() -> None:
84 """Example to encrypt and decrypt BTHome payload."""
85 print()
86 print("====== Test encode -----------------------------------------")
87 data = bytes(bytearray.fromhex("2302CA090303BF13")) # BTHome data (not encrypted)
88 parse_value(data) # Print temperature and humidity
89
90 print()
91 print("Preparing data for encryption")
92 count_id = bytes(bytearray.fromhex("00112233")) # count id (change every message)
93 mac = binascii.unhexlify("5448E68F80A5") # MAC
94 uuid16 = b"\x1e\x18"
95 bindkey = binascii.unhexlify("231d39c1d7cc1ab1aee224cd096db932")
96
97 payload = encrypt_payload(
98 data=data, mac=mac, uuid16=uuid16, count_id=count_id, key=bindkey
99 )
100 print()
101 print("Encrypted data:", payload.hex())
102 print()
103 print("====== Test decode -----------------------------------------")
104 decrypt_aes_ccm(key=bindkey, mac=mac, data=payload)
105
106
107 if __name__ == "__main__":
108 main()