lambda_shield/lib.rs
1/// Lambda-Shield v2 — High-Entropy Collatz Stream Cipher
2/// Optimized for energy-constrained MCUs.
3///
4/// Better than ChaCha20 for ultra-low-gate-count environments
5/// as it avoids large constant arrays and complex rotation schedules.
6
7#[inline(always)]
8fn mix(x: u64) -> u64 {
9 let x = (x ^ (x >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
10 let x = (x ^ (x >> 27)).wrapping_mul(0x94d049bb133111eb);
11 x ^ (x >> 31)
12}
13
14fn collatz_advance(mut n: u128, steps: usize) -> u128 {
15 for _ in 0..steps {
16 if n % 2 == 0 {
17 n /= 2;
18 } else {
19 n = n.wrapping_mul(3).wrapping_add(1);
20 }
21
22 // Escape the 4-2-1 loop and keep state healthy
23 if n <= 1 {
24 n = 6;
25 }
26
27 // Keep n within reasonable bounds for the next byte's entropy
28 if n > (u64::MAX as u128) {
29 n = (n % u64::MAX as u128) + 7;
30 }
31 }
32 n
33}
34
35/// Symmetric process: Encrypts or Decrypts data using Lemma 3 trajectories.
36/// Parameters:
37/// - data: The byte slice to process
38/// - seed_hi: The upper 64 bits of the key
39/// - seed_lo: The lower 64 bits of the key
40pub fn lambda_shield_v2(data: &[u8], seed_hi: u64, seed_lo: u64) -> Vec<u8> {
41 let mut n: u128 = ((seed_hi as u128) << 64) | (seed_lo as u128);
42
43 // Seed initialization and sanitization
44 if n == 0 {
45 n = 0xdeadbeefcafe1337;
46 }
47
48 // Initial jump to decouple from linear seed values
49 n = (n % u64::MAX as u128) + 2;
50
51 let mut counter: u64 = 0;
52 let mut result = Vec::with_capacity(data.len());
53
54 for &byte in data {
55 // Core Lemma 3 Trajectory: 32 iterations per byte
56 n = collatz_advance(n, 32);
57 counter = counter.wrapping_add(1);
58
59 // State mixing: Combine Collatz state, counter, and key entropy
60 let raw = (n as u64) ^ counter ^ seed_hi.wrapping_add(seed_lo);
61 let keystream_byte = (mix(raw) & 0xFF) as u8;
62
63 // XOR Stream Cipher Operation
64 result.push(byte ^ keystream_byte);
65 }
66 result
67}