Skip to content

Commit

Permalink
Merge pull request #80 from Ernst79/decryption_fix
Browse files Browse the repository at this point in the history
fix: decryption bug fixed
  • Loading branch information
Ernst79 authored Jul 15, 2023
2 parents ab2776c + dfb12e6 commit 70dc4c7
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
10 changes: 7 additions & 3 deletions src/bthome_ble/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,9 @@ def _parse_bthome_v2(
bthome_mac = bytes.fromhex(mac_readable.replace(":", ""))
# Decode encrypted payload
try:
payload = self._decrypt_bthome(payload, bthome_mac, sw_version)
payload = self._decrypt_bthome(
payload, bthome_mac, sw_version, adv_info
)
except (ValueError, TypeError):
return True

Expand Down Expand Up @@ -500,7 +502,9 @@ def _parse_payload(self, payload: bytes, sw_version: int) -> bool:

return True

def _decrypt_bthome(self, data: bytes, bthome_mac: bytes, sw_version: int) -> bytes:
def _decrypt_bthome(
self, data: bytes, bthome_mac: bytes, sw_version: int, adv_info: int = 65
) -> bytes:
"""Decrypt encrypted BTHome BLE advertisements"""
if not self.bindkey:
self.bindkey_verified = False
Expand All @@ -521,7 +525,7 @@ def _decrypt_bthome(self, data: bytes, bthome_mac: bytes, sw_version: int) -> by
if sw_version == 1:
uuid = b"\x1e\x18"
else:
uuid = b"\xd2\xfc\x41"
uuid = b"\xd2\xfc" + bytes([adv_info])
encrypted_payload = data[:-8]
count_id = data[-8:-4]
mic = data[-4:]
Expand Down
20 changes: 18 additions & 2 deletions tests/test_parser_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,9 +454,9 @@ def test_bthome_with_mac(caplog):
def test_bthome_with_mac_encrypted():
"""Test BTHome parser with mac address in payload plus encryption."""
bindkey = "231d39c1d7cc1ab1aee224cd096db932"
data_string = b"\x43\xa5\x80\x8f\xe6\x48\x54\xa4\x72\x66\xc9\x5f\x73\x00\x11\x22\x33\x78\x23\x72\x14" # noqa: E501
data = b"\x43\xa5\x80\x8f\xe6\x48\x54\xf1\x96\xc0\x6f\xfb\x49\x00\x11\x22\x33\xf0\x8e\xcb\xde"
advertisement = bytes_to_service_info(
data_string,
data,
local_name="TEST DEVICE",
address="54:48:E6:8F:80:A5",
)
Expand Down Expand Up @@ -1571,6 +1571,22 @@ def test_bthome_invalid_button_event(caplog):
)


def test_encrypted_shelly_blu_button_event(caplog):
"""Test BTHome parser for an encrypted shelly blu button event."""
bindkey = "90bffd73cb6b26ef58a7a8eba9232036"
data_string = b"\x45\x0a\xeb\x84\x46\x7f\x85\xba\x01\x00\x00\x31\x88\x78\x8c"

advertisement = bytes_to_service_info(
data_string,
local_name="SBBT-002C",
address="B4:35:22:F5:3D:A4",
)

device = BTHomeBluetoothDeviceData(bindkey=bytes.fromhex(bindkey))
assert device.supported(advertisement)
assert device.bindkey_verified


def test_bthome_distance_millimeters(caplog):
"""Test BTHome parser for distance in millimeters."""
data_string = b"\x40\x40\x0C\x00"
Expand Down

0 comments on commit 70dc4c7

Please sign in to comment.