Skip to content

Commit 471e3ce

Browse files
committed
generate_hash to util
1 parent 39c9864 commit 471e3ce

File tree

2 files changed

+22
-12
lines changed

2 files changed

+22
-12
lines changed

meshtastic/node.py

Lines changed: 1 addition & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -16,22 +16,11 @@
1616
pskToString,
1717
stripnl,
1818
message_to_json,
19-
channel_hash,
19+
generate_hash,
2020
)
2121

2222
logger = logging.getLogger(__name__)
2323

24-
def generate_hash(name: str, key: str) -> int:
25-
"""generate the channel number by hashing the channel name and psk"""
26-
if key == "AQ==":
27-
key = "1PG7OiApB1nwvP+rz05pAQ=="
28-
replaced_key = key.replace("-", "+").replace("_", "/")
29-
key_bytes = base64.b64decode(replaced_key.encode("utf-8"))
30-
h_name = channel_hash(bytes(name, "utf-8"))
31-
h_key = channel_hash(key_bytes)
32-
result: int = h_name ^ h_key
33-
return result
34-
3524
class Node:
3625
"""A model of a (local or remote) node in the mesh
3726

meshtastic/util.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,27 @@ def channel_hash(data: bytes) -> int:
372372
result ^= char
373373
return
374374

375+
def generate_hash(name, key) -> int:
376+
"""generate the channel number by hashing the channel name and psk (accepts str or bytes for both)"""
377+
# Handle key as str or bytes
378+
if isinstance(key, bytes):
379+
key = key.decode("utf-8")
380+
if key == "AQ==":
381+
key = "1PG7OiApB1nwvP+rz05pAQ=="
382+
replaced_key = key.replace("-", "+").replace("_", "/")
383+
key_bytes = base64.b64decode(replaced_key.encode("utf-8"))
384+
385+
# Handle name as str or bytes
386+
if isinstance(name, bytes):
387+
name_bytes = name
388+
else:
389+
name_bytes = name.encode("utf-8")
390+
391+
h_name = channel_hash(name_bytes)
392+
h_key = channel_hash(key_bytes)
393+
result: int = h_name ^ h_key
394+
return result
395+
375396
def hexstr(barray: bytes) -> str:
376397
"""Print a string of hex digits"""
377398
return ":".join(f"{x:02x}" for x in barray)

0 commit comments

Comments
 (0)