# SPDX-License-Identifier: MIT """Host decryption of a cart's encrypted loader frame: the no-boot-ROM path. Owner's decision 2 (2026-11-12): the real boot ROM by hash is the reference path; host decryption, written from the published description of the scheme, is the no-ROM path. No replacement ROM is shipped. The scheme (DOC: docs/cartridge.md "The boot path"; the description and the public modulus as published in HAMLET, MIT, Copyright (c) 2022 Waldemar Pawlaszek, whose notice is kept in NOTICE): - byte 0 of the frame is ``256 - n`` for ``n`` blocks of 51 bytes; - each block is a number held least significant byte first; the boot ROM raises it to the public exponent 3 modulo the 51-byte public modulus; - of the result, bytes 0-49 are running differences (each output byte is the previous output byte plus this one), byte 50 is ``$15``; - the output bytes go to RAM one after another. Where the boot ROM puts them, and where it jumps, is read from running the real ROM on this board (OBSERVED on this board, M1): see ``LOAD_ADDRESS``. """ from __future__ import annotations # The public modulus, as published in HAMLET (MIT), most significant digit first. MODULUS = int( "35b5a3942806d8a22695d771b23cfd561c4a19b6a3b02600365a306e3c4d63381bd41c136489364c" "f2ba2a58f4fee1fdac7e79", 16, ) BLOCK = 51 PLAIN = 50 class DecryptError(ValueError): pass def frame_blocks(payload: bytes) -> int: count = (256 - payload[0]) & 0xFF if not 1 <= count <= 5 or len(payload) < 1 + count * BLOCK: raise DecryptError(f"first byte ${payload[0]:02X} is not a frame of 1-5 blocks") return count def decrypt(payload: bytes) -> bytes: """The bytes the boot ROM writes to RAM from the frame at the start of ``payload``.""" count = frame_blocks(payload) out = bytearray() accumulator = 0 for i in range(count): chunk = payload[1 + i * BLOCK : 1 + (i + 1) * BLOCK] plain = pow(int.from_bytes(chunk, "little"), 3, MODULUS).to_bytes(BLOCK, "little") for delta in plain[:PLAIN]: accumulator = (accumulator + delta) & 0xFF out.append(accumulator) return bytes(out)