From 471e3ce145a2f5198f21fd7f3fd745761930c3f3 Mon Sep 17 00:00:00 2001 From: SpudGunMan Date: Thu, 6 Nov 2025 12:00:16 -0800 Subject: [PATCH] generate_hash to util --- meshtastic/node.py | 13 +------------ meshtastic/util.py | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/meshtastic/node.py b/meshtastic/node.py index 5208581..09e19b0 100644 --- a/meshtastic/node.py +++ b/meshtastic/node.py @@ -16,22 +16,11 @@ from meshtastic.util import ( pskToString, stripnl, message_to_json, - channel_hash, + generate_hash, ) logger = logging.getLogger(__name__) -def generate_hash(name: str, key: str) -> int: - """generate the channel number by hashing the channel name and psk""" - if key == "AQ==": - key = "1PG7OiApB1nwvP+rz05pAQ==" - replaced_key = key.replace("-", "+").replace("_", "/") - key_bytes = base64.b64decode(replaced_key.encode("utf-8")) - h_name = channel_hash(bytes(name, "utf-8")) - h_key = channel_hash(key_bytes) - result: int = h_name ^ h_key - return result - class Node: """A model of a (local or remote) node in the mesh diff --git a/meshtastic/util.py b/meshtastic/util.py index de09e5c..c5f44f1 100644 --- a/meshtastic/util.py +++ b/meshtastic/util.py @@ -372,6 +372,27 @@ def channel_hash(data: bytes) -> int: result ^= char return +def generate_hash(name, key) -> int: + """generate the channel number by hashing the channel name and psk (accepts str or bytes for both)""" + # Handle key as str or bytes + if isinstance(key, bytes): + key = key.decode("utf-8") + if key == "AQ==": + key = "1PG7OiApB1nwvP+rz05pAQ==" + replaced_key = key.replace("-", "+").replace("_", "/") + key_bytes = base64.b64decode(replaced_key.encode("utf-8")) + + # Handle name as str or bytes + if isinstance(name, bytes): + name_bytes = name + else: + name_bytes = name.encode("utf-8") + + h_name = channel_hash(name_bytes) + h_key = channel_hash(key_bytes) + result: int = h_name ^ h_key + return result + def hexstr(barray: bytes) -> str: """Print a string of hex digits""" return ":".join(f"{x:02x}" for x in barray)