import hashlib
import hmac
import re
def atbash_cipher(text: str) -> str:
"""Applies the Atbash substitution cipher symmetrically (A<->Z, a<->z)."""
out: list[str] = []
for ch in text:
if "a" <= ch <= "z":
out.append(chr(ord("z") - (ord(ch) - ord("a"))))
elif "A" <= ch <= "Z":
out.append(chr(ord("Z") - (ord(ch) - ord("A"))))
else:
out.append(ch)
return "".join(out)
def stride_from_seed(seed: str) -> list[int]:
"""Extracts digits left-to-right from seed, defaulting to [6, 3, 3, 1]."""
digits = [int(d) for d in re.findall(r"\d", seed)]
return digits if digits else [6, 3, 3, 1]
def stride_shift_text(text: str, strides: list[int], direction: int = 1) -> str:
"""Shifts ASCII letters by direction * strides[i % len(strides)] mod 26."""
out: list[str] = []
for idx, ch in enumerate(text):
shift = direction * strides[idx % len(strides)]
if "a" <= ch <= "z":
out.append(chr((ord(ch) - ord("a") + shift) % 26 + ord("a")))
elif "A" <= ch <= "Z":
out.append(chr((ord(ch) - ord("A") + shift) % 26 + ord("A")))
else:
out.append(ch)
return "".join(out)
def resolve_active_seed(
ssid: str = "Monster6331",
password_key: str = "1336retsnoM",
swap_roles: bool = False,
) -> tuple[str, str]:
"""Returns (role_label, active_seed) based on swap_roles."""
if swap_roles:
return "SWAP", password_key
return "SSID", ssid
def _derive_hmac_key(ssid: str, password_key: str) -> bytes:
"""Derives an HMAC signing key from the SSID and password_key pair."""
key_material = f"{ssid}:{password_key}".encode("utf-8")
return hashlib.sha256(key_material).digest()
def compute_frame_hmac(
role_label: str,
frames: str,
ssid: str = "Monster6331",
password_key: str = "1336retsnoM",
hex_len: int = 16,
) -> str:
"""Computes an uppercase hex HMAC-SHA256 digest over role and binary frames."""
key = _derive_hmac_key(ssid, password_key)
message = f"{role_label}:{frames}".encode("utf-8")
digest = hmac.new(key, message, hashlib.sha256).hexdigest()
return digest[:hex_len].upper()
def encode_chi_with_hmac(
plaintext: str,
ssid: str = "Monster6331",
password_key: str = "1336retsnoM",
swap_roles: bool = False,
hex_len: int = 16,
) -> str:
"""
Encodes plaintext into [\Chi]^2{<8-bit binary>} frames with a keyed HMAC header:
[ROLE:<SSID|SWAP>|MAC:<HEX>] ...
"""
role_label, active_seed = resolve_active_seed(ssid, password_key, swap_roles)
strides = stride_from_seed(active_seed)
mirrored = atbash_cipher(plaintext)
shifted = stride_shift_text(mirrored, strides, direction=1)
frames = " ".join(f"[\\Chi]^2{{{b:08b}}}" for b in shifted.encode("utf-8"))
mac = compute_frame_hmac(
role_label,
frames,
ssid=ssid,
password_key=password_key,
hex_len=hex_len,
)
return f"[ROLE:{role_label}|MAC:{mac}] {frames}"
def decode_chi_with_hmac(
framed_text: str,
ssid: str = "Monster6331",
password_key: str = "1336retsnoM",
swap_roles: bool | None = None,
verify_hmac: bool = True,
) -> str:
"""
Verifies the header HMAC digest, decodes [\Chi]^2{...} blocks,
reverses the stride shift, and reapplies Atbash.
"""
header_match = re.search(
r"[ROLE:(SWAP|SSID)(?:|MAC:([0-9A-Fa-f]+))?]",
framed_text,
)
header_role = header_match.group(1) if header_match else "SSID"
embedded_mac = (
header_match.group(2).upper()
if (header_match and header_match.group(2))
else None
)
effective_swap = (
swap_roles if swap_roles is not None else (header_role == "SWAP")
)
role_label, active_seed = resolve_active_seed(ssid, password_key, effective_swap)
strides = stride_from_seed(active_seed)
token_pattern = re.compile(r"\[\\Chi\]\^2\{([^{}]*)\}")
raw_tokens: list[str] = []
raw_bytes = bytearray()
for match in token_pattern.finditer(framed_text):
bits = match.group(1).strip()
if not re.fullmatch(r"[01]{8}", bits):
raise ValueError(f"Malformed or truncated 8-bit binary block: {bits!r}")
raw_tokens.append(f"[\\Chi]^2{{{bits}}}")
raw_bytes.append(int(bits, 2))
if verify_hmac:
if not embedded_mac:
raise ValueError("Missing MAC tag in frame header.")
canonical_frames = " ".join(raw_tokens)
expected_mac = compute_frame_hmac(
role_label,
canonical_frames,
ssid=ssid,
password_key=password_key,
hex_len=len(embedded_mac),
)
if not hmac.compare_digest(embedded_mac, expected_mac):
raise ValueError(
f"HMAC verification failed: expected {expected_mac}, got {embedded_mac}."
)
shifted_text = raw_bytes.decode("utf-8")
mirrored_text = stride_shift_text(shifted_text, strides, direction=-1)
return atbash_cipher(mirrored_text)
if name == "main":
sample = "pieve_node_01"
encoded = encode_chi_with_hmac(sample, swap_roles=True)
print("Encoded:", encoded)
print("Decoded:", decode_chi_with_hmac(encoded))
# Simulate credential mismatch on decode
try:
decode_chi_with_hmac(encoded, password_key="wrong_key_9999")
except ValueError as err:
print("Rejected wrong credential:", err)
Top comments (0)