From c8629f3378fec01fe30c0e32e01e93942f4dcbc5 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:35:18 +0200 Subject: [PATCH] Protocol: RSA public keys and PKCS#1 encryption, server hash, secrets Co-Authored-By: Claude Opus 5.5 --- crates/horizon-protocol/Cargo.toml | 3 ++ crates/horizon-protocol/src/crypto.rs | 74 ++++++++++++++++++++++++++- crates/horizon-protocol/src/lib.rs | 1 + crates/horizon-protocol/src/rsa.rs | 43 ++++++++++++++++ 4 files changed, 119 insertions(+), 2 deletions(-) diff --git a/crates/horizon-protocol/Cargo.toml b/crates/horizon-protocol/Cargo.toml index 04bb00d5b..fad282080 100644 --- a/crates/horizon-protocol/Cargo.toml +++ b/crates/horizon-protocol/Cargo.toml @@ -10,6 +10,9 @@ description = "Horizon's Minecraft Java Edition 26.3 network protocol (version 7 horizon-world = { path = "../horizon-world" } flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] } serde_json = "1.0.151" +# The shared secret and RSA padding (OS randomness) and the server hash. +getrandom = "0.3" +sha1 = "0.10" [lints] workspace = true diff --git a/crates/horizon-protocol/src/crypto.rs b/crates/horizon-protocol/src/crypto.rs index c55b003b5..b5b6fa447 100644 --- a/crates/horizon-protocol/src/crypto.rs +++ b/crates/horizon-protocol/src/crypto.rs @@ -1,7 +1,9 @@ //! Connection encryption (Crypt.getCipher: AES/CFB8/NoPadding with the shared //! secret as key and IV) and MD5 name-based UUIDs for offline-mode profiles -//! (UUIDUtil.createOfflinePlayerUUID). Only the AES forward cipher is needed: -//! CFB8 encrypts the shift register in both directions. +//! (UUIDUtil.createOfflinePlayerUUID), the online-mode server hash +//! (Crypt.digestData) and the shared secret. Only the AES forward cipher is +//! needed: CFB8 encrypts the shift register in both directions. +use sha1::{Digest, Sha1}; const SBOX: [u8; 256] = { // Generated from the AES field inverse and affine transform at compile time. @@ -138,6 +140,54 @@ impl Cfb8 { } } +/// Fill `out` with the operating system's cryptographic randomness. +pub fn random_bytes(out: &mut [u8]) -> crate::Result<()> { + getrandom::fill(out).map_err(|e| crate::Error::new(format!("No secure random source: {e}"))) +} + +/// Crypt.generateSecretKey: a random AES-128 key, the connection's shared secret. +pub fn generate_secret() -> crate::Result<[u8; 16]> { + let mut key = [0u8; 16]; + random_bytes(&mut key)?; + Ok(key) +} + +/// `new BigInteger(digest).toString(16)`: the digest read as a signed +/// two's-complement number, in lowercase hex without leading zeros. +pub fn java_hex_digest(digest: &[u8]) -> String { + let negative = digest.first().is_some_and(|b| b & 0x80 != 0); + let mut magnitude = digest.to_vec(); + if negative { + // Two's complement: invert and add one. + let mut carry = true; + for b in magnitude.iter_mut().rev() { + *b = !*b; + if carry { + let (v, c) = b.overflowing_add(1); + *b = v; + carry = c; + } + } + } + let hex: String = magnitude.iter().map(|b| format!("{b:02x}")).collect(); + let hex = hex.trim_start_matches('0'); + let hex = if hex.is_empty() { "0" } else { hex }; + if negative { format!("-{hex}") } else { hex.to_owned() } +} + +/// The server id sent to the session service when joining an online-mode +/// server: SHA-1 over the server id (ISO-8859-1), the shared secret and the +/// server's encoded public key, as a signed hex number. +pub fn server_hash(server_id: &str, secret: &[u8], public_key: &[u8]) -> String { + let mut sha = Sha1::new(); + // ISO-8859-1: characters above U+00FF become '?' like String.getBytes. + let latin1: Vec = server_id.chars().map(|c| u8::try_from(u32::from(c)).unwrap_or(b'?')).collect(); + sha.update(&latin1); + sha.update(secret); + sha.update(public_key); + java_hex_digest(&sha.finalize()) +} + /// MD5 (RFC 1321). pub fn md5(input: &[u8]) -> [u8; 16] { const S: [u32; 64] = [ @@ -256,6 +306,26 @@ mod tests { assert_eq!(data, plain); } + /// The digests of single names published with the protocol docs. + #[test] + fn server_hash_vectors() { + let hash = |name: &str| java_hex_digest(&Sha1::digest(name.as_bytes())); + assert_eq!(hash("Notch"), "4ed1f46bbe04bc756bcb17c0c7ce3e4632f06a48"); + assert_eq!(hash("jeb_"), "-7c9d5b0044c130109a5d7b5fb5c317c02b4e28c1"); + assert_eq!(hash("simon"), "88e16a1019277b15d58faf0541e11910eb756f6"); + // The three inputs are hashed in order: one update equals three. + assert_eq!(server_hash("", b"Not", b"ch"), hash("Notch")); + assert_eq!(java_hex_digest(&[0; 4]), "0"); + assert_eq!(java_hex_digest(&[0xff; 2]), "-1"); + assert_eq!(java_hex_digest(&[0x80, 0]), "-8000"); + } + + #[test] + fn secrets_are_random() { + let (a, b) = (generate_secret().unwrap(), generate_secret().unwrap()); + assert_ne!(a, b); + } + #[test] fn md5_and_offline_uuids() { assert_eq!(md5(b"").to_vec(), hex("d41d8cd98f00b204e9800998ecf8427e")); diff --git a/crates/horizon-protocol/src/lib.rs b/crates/horizon-protocol/src/lib.rs index 1f29637dd..e49031b77 100644 --- a/crates/horizon-protocol/src/lib.rs +++ b/crates/horizon-protocol/src/lib.rs @@ -12,6 +12,7 @@ pub mod ids; pub mod item; pub mod packets; pub mod registry; +pub mod rsa; pub mod servers; pub mod text; diff --git a/crates/horizon-protocol/src/rsa.rs b/crates/horizon-protocol/src/rsa.rs index fd07db851..cbc256c06 100644 --- a/crates/horizon-protocol/src/rsa.rs +++ b/crates/horizon-protocol/src/rsa.rs @@ -249,6 +249,7 @@ pub(crate) mod tests { use super::*; pub fn hex(s: &str) -> Vec { + let s = if s.len() % 2 == 1 { format!("0{s}") } else { s.to_owned() }; (0..s.len()) .step_by(2) .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()) @@ -275,4 +276,46 @@ pub(crate) mod tests { let r = m.pow(&Big(vec![b as u32, (b >> 32) as u32]), &Big(vec![3, 0])); assert_eq!(u128::from(r.0[0]) | u128::from(r.0[1]) << 32, expected); } + + #[test] + fn parses_x509_public_keys() { + let key = RsaPublicKey::from_der(&hex(TEST_SPKI)).unwrap(); + assert_eq!(key.modulus, hex(TEST_N)); + assert_eq!(key.exponent, vec![1, 0, 1]); + assert_eq!(key.size(), 128); + assert!(RsaPublicKey::from_der(&hex(TEST_SPKI)[..100]).is_err()); + assert!(RsaPublicKey::from_der(b"not a key").is_err()); + } + + /// Encrypted with the public key, decrypted with the private exponent: + /// a PKCS#1 v1.5 type 2 block with non-zero padding around the message. + #[test] + fn pkcs1_round_trip() { + let key = RsaPublicKey::from_der(&hex(TEST_SPKI)).unwrap(); + let secret = [0x5au8; 16]; + let a = key.encrypt(&secret).unwrap(); + let b = key.encrypt(&secret).unwrap(); + assert_eq!(a.len(), 128); + assert_ne!(a, b, "padding is random"); + for c in [a, b] { + let block = key.apply(&c, &hex(TEST_D)); + assert_eq!(&block[..2], &[0, 2]); + let zero = 2 + block[2..].iter().position(|&b| b == 0).unwrap(); + assert_eq!(zero, 128 - 16 - 1); + assert_eq!(&block[zero + 1..], &secret); + } + assert!(key.encrypt(&[0; 118]).is_err()); + } + + /// An OpenSSL signature checked with the public exponent: the block ends + /// with SHA-256("hello"), so the modular arithmetic agrees with OpenSSL's. + #[test] + fn verifies_an_openssl_signature() { + let key = RsaPublicKey::from_der(&hex(TEST_SPKI)).unwrap(); + let block = key.apply(&hex(TEST_SIG_HELLO), &key.exponent); + assert_eq!(&block[..2], &[0, 1]); + assert!(block.ends_with(&hex( + "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" + ))); + } }