// SPDX-License-Identifier: MIT // The public modulus below is as published in HAMLET (MIT, Copyright (c) 2022 Waldemar // Pawlaszek); its notice is kept in NOTICE. //! Host decryption of a cart's encrypted loader frame: the no-boot-ROM path //! (`cart/decrypt.py`). //! //! 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`. //! //! Differences forced by Rust: Python's arbitrary-precision `pow` is `num-bigint`'s //! `modpow`; `DecryptError` is the `Err` of a `Result`. use num_bigint::BigUint; /// The public modulus, as published in HAMLET (MIT), most significant digit first. pub const MODULUS_HEX: &str = concat!( "35b5a3942806d8a22695d771b23cfd561c4a19b6a3b02600365a306e3c4d63381bd41c136489364c", "f2ba2a58f4fee1fdac7e79" ); pub const BLOCK: usize = 51; pub const PLAIN: usize = 50; pub fn frame_blocks(payload: &[u8]) -> Result { let count = (256 - payload[0] as usize) & 0xFF; if !(1..=5).contains(&count) || payload.len() < 1 + count * BLOCK { return Err(format!( "first byte ${:02X} is not a frame of 1-5 blocks", payload[0] )); } Ok(count) } /// The bytes the boot ROM writes to RAM from the frame at the start of `payload`. pub fn decrypt(payload: &[u8]) -> Result, String> { let count = frame_blocks(payload)?; let modulus = BigUint::parse_bytes(MODULUS_HEX.as_bytes(), 16).unwrap(); let three = BigUint::from(3u32); let mut out = Vec::new(); let mut accumulator: u8 = 0; for i in 0..count { let chunk = &payload[1 + i * BLOCK..1 + (i + 1) * BLOCK]; let number = BigUint::from_bytes_le(chunk).modpow(&three, &modulus); let mut plain = number.to_bytes_le(); plain.resize(BLOCK, 0); for &delta in &plain[..PLAIN] { accumulator = accumulator.wrapping_add(delta); out.push(accumulator); } } Ok(out) }