rns-crypto 0.1.9

Cryptographic primitives for the Reticulum Network Stack
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
use alloc::vec;
use alloc::vec::Vec;
use core::cmp::Ordering;
use core::ops::{Add, BitAnd, BitOr, Mul, Rem, Shl, Shr, Sub};

/// Variable-width unsigned big integer, Vec<u64> limbs (little-endian).
/// limbs[0] is the least significant 64-bit word.
#[derive(Clone, Debug)]
pub struct BigUint {
    limbs: Vec<u64>,
}

impl BigUint {
    pub fn zero() -> Self {
        BigUint { limbs: vec![0] }
    }

    pub fn one() -> Self {
        BigUint { limbs: vec![1] }
    }

    pub fn from_u64(v: u64) -> Self {
        BigUint { limbs: vec![v] }
    }

    fn normalize(&mut self) {
        while self.limbs.len() > 1 && *self.limbs.last().unwrap() == 0 {
            self.limbs.pop();
        }
    }

    pub fn is_zero(&self) -> bool {
        self.limbs.iter().all(|&x| x == 0)
    }

    pub fn bit(&self, i: usize) -> bool {
        let limb_idx = i / 64;
        let bit_idx = i % 64;
        if limb_idx >= self.limbs.len() {
            false
        } else {
            (self.limbs[limb_idx] >> bit_idx) & 1 == 1
        }
    }

    pub fn bits(&self) -> usize {
        if self.is_zero() {
            return 0;
        }
        let top = self.limbs.len() - 1;
        let top_bits = 64 - self.limbs[top].leading_zeros() as usize;
        top * 64 + top_bits
    }

    pub fn from_bytes_le(bytes: &[u8]) -> Self {
        if bytes.is_empty() {
            return Self::zero();
        }
        let mut limbs = Vec::with_capacity((bytes.len() + 7) / 8);
        for chunk in bytes.chunks(8) {
            let mut buf = [0u8; 8];
            buf[..chunk.len()].copy_from_slice(chunk);
            limbs.push(u64::from_le_bytes(buf));
        }
        let mut r = BigUint { limbs };
        r.normalize();
        r
    }

    pub fn from_bytes_be(bytes: &[u8]) -> Self {
        if bytes.is_empty() {
            return Self::zero();
        }
        let mut reversed = bytes.to_vec();
        reversed.reverse();
        Self::from_bytes_le(&reversed)
    }

    pub fn to_bytes_le(&self, size: usize) -> Vec<u8> {
        let mut bytes = Vec::with_capacity(self.limbs.len() * 8);
        for &limb in &self.limbs {
            bytes.extend_from_slice(&limb.to_le_bytes());
        }
        bytes.resize(size, 0);
        bytes.truncate(size);
        bytes
    }

    pub fn to_bytes_be(&self, size: usize) -> Vec<u8> {
        let mut bytes = self.to_bytes_le(size);
        bytes.reverse();
        bytes
    }

    /// Set a specific bit
    pub fn set_bit(&mut self, i: usize, val: bool) {
        let limb_idx = i / 64;
        let bit_idx = i % 64;
        while self.limbs.len() <= limb_idx {
            self.limbs.push(0);
        }
        if val {
            self.limbs[limb_idx] |= 1u64 << bit_idx;
        } else {
            self.limbs[limb_idx] &= !(1u64 << bit_idx);
        }
        self.normalize();
    }

    /// Clear a specific bit
    pub fn clear_bit(&mut self, i: usize) {
        self.set_bit(i, false);
    }
}

impl PartialEq for BigUint {
    fn eq(&self, other: &Self) -> bool {
        // Compare normalized forms
        let a = {
            let mut c = self.clone();
            c.normalize();
            c
        };
        let b = {
            let mut c = other.clone();
            c.normalize();
            c
        };
        a.limbs == b.limbs
    }
}

impl Eq for BigUint {}

impl PartialOrd for BigUint {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for BigUint {
    fn cmp(&self, other: &Self) -> Ordering {
        let a_bits = self.bits();
        let b_bits = other.bits();
        if a_bits != b_bits {
            return a_bits.cmp(&b_bits);
        }
        // Same number of significant bits, compare from most significant limb
        let max_len = self.limbs.len().max(other.limbs.len());
        for i in (0..max_len).rev() {
            let a = if i < self.limbs.len() { self.limbs[i] } else { 0 };
            let b = if i < other.limbs.len() { other.limbs[i] } else { 0 };
            match a.cmp(&b) {
                Ordering::Equal => continue,
                other => return other,
            }
        }
        Ordering::Equal
    }
}

impl Add for &BigUint {
    type Output = BigUint;
    fn add(self, rhs: &BigUint) -> BigUint {
        let max_len = self.limbs.len().max(rhs.limbs.len());
        let mut result = Vec::with_capacity(max_len + 1);
        let mut carry = 0u64;
        for i in 0..max_len {
            let a = if i < self.limbs.len() { self.limbs[i] } else { 0 };
            let b = if i < rhs.limbs.len() { rhs.limbs[i] } else { 0 };
            let (sum1, c1) = a.overflowing_add(b);
            let (sum2, c2) = sum1.overflowing_add(carry);
            result.push(sum2);
            carry = (c1 as u64) + (c2 as u64);
        }
        if carry > 0 {
            result.push(carry);
        }
        let mut r = BigUint { limbs: result };
        r.normalize();
        r
    }
}

impl Add for BigUint {
    type Output = BigUint;
    fn add(self, rhs: BigUint) -> BigUint {
        &self + &rhs
    }
}

impl Sub for &BigUint {
    type Output = BigUint;
    fn sub(self, rhs: &BigUint) -> BigUint {
        assert!(self >= rhs, "BigUint subtraction underflow");
        let mut result = Vec::with_capacity(self.limbs.len());
        let mut borrow = 0i64;
        for i in 0..self.limbs.len() {
            let a = self.limbs[i] as i128;
            let b = if i < rhs.limbs.len() { rhs.limbs[i] as i128 } else { 0 };
            let diff = a - b - borrow as i128;
            if diff < 0 {
                result.push((diff + (1i128 << 64)) as u64);
                borrow = 1;
            } else {
                result.push(diff as u64);
                borrow = 0;
            }
        }
        let mut r = BigUint { limbs: result };
        r.normalize();
        r
    }
}

impl Sub for BigUint {
    type Output = BigUint;
    fn sub(self, rhs: BigUint) -> BigUint {
        &self - &rhs
    }
}

impl Mul for &BigUint {
    type Output = BigUint;
    fn mul(self, rhs: &BigUint) -> BigUint {
        if self.is_zero() || rhs.is_zero() {
            return BigUint::zero();
        }
        let mut result = vec![0u64; self.limbs.len() + rhs.limbs.len()];
        for i in 0..self.limbs.len() {
            let mut carry = 0u128;
            for j in 0..rhs.limbs.len() {
                let prod = (self.limbs[i] as u128) * (rhs.limbs[j] as u128)
                    + result[i + j] as u128
                    + carry;
                result[i + j] = prod as u64;
                carry = prod >> 64;
            }
            // Propagate carry upward through remaining result limbs
            let mut c = carry;
            let mut k = i + rhs.limbs.len();
            while c > 0 && k < result.len() {
                let sum = result[k] as u128 + c;
                result[k] = sum as u64;
                c = sum >> 64;
                k += 1;
            }
        }
        let mut r = BigUint { limbs: result };
        r.normalize();
        r
    }
}

impl Mul for BigUint {
    type Output = BigUint;
    fn mul(self, rhs: BigUint) -> BigUint {
        &self * &rhs
    }
}

/// Returns (quotient, remainder)
fn divmod(a: &BigUint, b: &BigUint) -> (BigUint, BigUint) {
    assert!(!b.is_zero(), "division by zero");

    if a < b {
        return (BigUint::zero(), a.clone());
    }

    if b.limbs.len() == 1 && b.limbs[0] != 0 {
        // Optimize single-limb divisor
        return divmod_single(a, b.limbs[0]);
    }

    let a_bits = a.bits();

    let mut quotient = BigUint::zero();
    let mut remainder = BigUint::zero();

    for i in (0..a_bits).rev() {
        // Shift remainder left by 1 and add the next bit of a
        remainder = &remainder << 1;
        if a.bit(i) {
            remainder = &remainder + &BigUint::one();
        }
        if remainder >= *b {
            remainder = &remainder - b;
            quotient.set_bit(i, true);
        }
    }

    quotient.normalize();
    remainder.normalize();
    (quotient, remainder)
}

fn divmod_single(a: &BigUint, b: u64) -> (BigUint, BigUint) {
    let mut result = vec![0u64; a.limbs.len()];
    let mut remainder = 0u128;
    for i in (0..a.limbs.len()).rev() {
        let dividend = (remainder << 64) | (a.limbs[i] as u128);
        result[i] = (dividend / b as u128) as u64;
        remainder = dividend % b as u128;
    }
    let mut q = BigUint { limbs: result };
    q.normalize();
    (q, BigUint::from_u64(remainder as u64))
}

impl Rem for &BigUint {
    type Output = BigUint;
    fn rem(self, rhs: &BigUint) -> BigUint {
        divmod(self, rhs).1
    }
}

impl Rem for BigUint {
    type Output = BigUint;
    fn rem(self, rhs: BigUint) -> BigUint {
        &self % &rhs
    }
}

impl Shl<usize> for &BigUint {
    type Output = BigUint;
    fn shl(self, shift: usize) -> BigUint {
        if self.is_zero() || shift == 0 {
            return self.clone();
        }
        let word_shift = shift / 64;
        let bit_shift = shift % 64;
        let mut result = vec![0u64; self.limbs.len() + word_shift + 1];
        if bit_shift == 0 {
            for i in 0..self.limbs.len() {
                result[i + word_shift] = self.limbs[i];
            }
        } else {
            let mut carry = 0u64;
            for i in 0..self.limbs.len() {
                let shifted = (self.limbs[i] as u128) << bit_shift;
                result[i + word_shift] = shifted as u64 | carry;
                carry = (shifted >> 64) as u64;
            }
            if carry > 0 {
                result[self.limbs.len() + word_shift] = carry;
            }
        }
        let mut r = BigUint { limbs: result };
        r.normalize();
        r
    }
}

impl Shl<usize> for BigUint {
    type Output = BigUint;
    fn shl(self, shift: usize) -> BigUint {
        &self << shift
    }
}

impl Shr<usize> for &BigUint {
    type Output = BigUint;
    fn shr(self, shift: usize) -> BigUint {
        if self.is_zero() || shift == 0 {
            return self.clone();
        }
        let word_shift = shift / 64;
        let bit_shift = shift % 64;
        if word_shift >= self.limbs.len() {
            return BigUint::zero();
        }
        let new_len = self.limbs.len() - word_shift;
        let mut result = vec![0u64; new_len];
        if bit_shift == 0 {
            for i in 0..new_len {
                result[i] = self.limbs[i + word_shift];
            }
        } else {
            for i in 0..new_len {
                result[i] = self.limbs[i + word_shift] >> bit_shift;
                if i + word_shift + 1 < self.limbs.len() {
                    result[i] |= self.limbs[i + word_shift + 1] << (64 - bit_shift);
                }
            }
        }
        let mut r = BigUint { limbs: result };
        r.normalize();
        r
    }
}

impl Shr<usize> for BigUint {
    type Output = BigUint;
    fn shr(self, shift: usize) -> BigUint {
        &self >> shift
    }
}

impl BitAnd for &BigUint {
    type Output = BigUint;
    fn bitand(self, rhs: &BigUint) -> BigUint {
        let min_len = self.limbs.len().min(rhs.limbs.len());
        let mut result = vec![0u64; min_len];
        for i in 0..min_len {
            result[i] = self.limbs[i] & rhs.limbs[i];
        }
        let mut r = BigUint { limbs: result };
        r.normalize();
        r
    }
}

impl BitAnd for BigUint {
    type Output = BigUint;
    fn bitand(self, rhs: BigUint) -> BigUint {
        &self & &rhs
    }
}

impl BitOr for &BigUint {
    type Output = BigUint;
    fn bitor(self, rhs: &BigUint) -> BigUint {
        let max_len = self.limbs.len().max(rhs.limbs.len());
        let mut result = vec![0u64; max_len];
        for i in 0..max_len {
            let a = if i < self.limbs.len() { self.limbs[i] } else { 0 };
            let b = if i < rhs.limbs.len() { rhs.limbs[i] } else { 0 };
            result[i] = a | b;
        }
        let mut r = BigUint { limbs: result };
        r.normalize();
        r
    }
}

impl BitOr for BigUint {
    type Output = BigUint;
    fn bitor(self, rhs: BigUint) -> BigUint {
        &self | &rhs
    }
}

/// Modular exponentiation: base^exp mod modulus
pub fn mod_pow(base: &BigUint, exp: &BigUint, modulus: &BigUint) -> BigUint {
    assert!(!modulus.is_zero(), "modulus cannot be zero");
    if modulus == &BigUint::one() {
        return BigUint::zero();
    }

    let mut result = BigUint::one();
    let mut base = base % modulus;
    let exp_bits = exp.bits();

    for i in 0..exp_bits {
        if exp.bit(i) {
            result = &(&result * &base) % modulus;
        }
        base = &(&base * &base) % modulus;
    }

    result
}

/// Modular inverse using Fermat's little theorem: a^(p-2) mod p
/// Only works when p is prime.
pub fn mod_inv(a: &BigUint, p: &BigUint) -> BigUint {
    let exp = p - &BigUint::from_u64(2);
    mod_pow(a, &exp, p)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_biguint_from_to_bytes_le_roundtrip() {
        let bytes: Vec<u8> = (0..32).collect();
        let n = BigUint::from_bytes_le(&bytes);
        assert_eq!(n.to_bytes_le(32), bytes);
    }

    #[test]
    fn test_biguint_from_to_bytes_be_roundtrip() {
        let bytes: Vec<u8> = (0..32).collect();
        let n = BigUint::from_bytes_be(&bytes);
        assert_eq!(n.to_bytes_be(32), bytes);
    }

    #[test]
    fn test_biguint_add() {
        let a = BigUint::from_u64(u64::MAX);
        let b = BigUint::from_u64(1);
        let c = &a + &b;
        assert_eq!(c.limbs, vec![0, 1]);
    }

    #[test]
    fn test_biguint_sub() {
        let a = BigUint { limbs: vec![0, 1] }; // 2^64
        let b = BigUint::from_u64(1);
        let c = &a - &b;
        assert_eq!(c, BigUint::from_u64(u64::MAX));
    }

    #[test]
    fn test_biguint_mul() {
        let a = BigUint::from_u64(u64::MAX);
        let b = BigUint::from_u64(2);
        let c = &a * &b;
        // u64::MAX * 2 = 2^65 - 2
        assert_eq!(c.limbs, vec![u64::MAX - 1, 1]);
    }

    #[test]
    fn test_biguint_div_rem() {
        let a = BigUint::from_u64(100);
        let b = BigUint::from_u64(7);
        let (q, r) = divmod(&a, &b);
        assert_eq!(q, BigUint::from_u64(14));
        assert_eq!(r, BigUint::from_u64(2));
    }

    #[test]
    fn test_mod_pow() {
        // 2^10 mod 1000 = 1024 mod 1000 = 24
        let base = BigUint::from_u64(2);
        let exp = BigUint::from_u64(10);
        let modulus = BigUint::from_u64(1000);
        assert_eq!(mod_pow(&base, &exp, &modulus), BigUint::from_u64(24));
    }

    #[test]
    fn test_mod_inv() {
        // For prime p=17, inv(3) = 3^15 mod 17 = 6, since 3*6=18≡1 mod 17
        let a = BigUint::from_u64(3);
        let p = BigUint::from_u64(17);
        let inv = mod_inv(&a, &p);
        assert_eq!(inv, BigUint::from_u64(6));
        // Verify: a * inv mod p == 1
        let product = &(&a * &inv) % &p;
        assert_eq!(product, BigUint::one());
    }

    #[test]
    fn test_biguint_shift() {
        let a = BigUint::from_u64(1);
        let b = &a << 64;
        assert_eq!(b.limbs, vec![0, 1]);
        let c = &b >> 64;
        assert_eq!(c, BigUint::from_u64(1));
    }

    #[test]
    fn test_biguint_bitops() {
        let a = BigUint::from_u64(0xFF);
        let b = BigUint::from_u64(0x0F);
        assert_eq!(&a & &b, BigUint::from_u64(0x0F));
        assert_eq!(&a | &b, BigUint::from_u64(0xFF));
    }

    #[test]
    fn test_biguint_512bit() {
        // 64-byte value (for Ed25519 Hint)
        let bytes: Vec<u8> = (0..64).collect();
        let n = BigUint::from_bytes_be(&bytes);
        let roundtrip = n.to_bytes_be(64);
        assert_eq!(roundtrip, bytes);
    }

    #[test]
    fn test_biguint_mul_carry_propagation() {
        // Test that multiplication carry propagation works for large numbers
        // where result[i + rhs.limbs.len()] += carry can overflow
        let a = BigUint { limbs: vec![u64::MAX, u64::MAX, u64::MAX, u64::MAX] };
        let b = BigUint { limbs: vec![u64::MAX, u64::MAX, u64::MAX, u64::MAX] };
        let c = &a * &b;
        // Verify by checking: (2^256 - 1)^2 = 2^512 - 2^257 + 1
        let two_512 = &BigUint::one() << 512;
        let two_257 = &BigUint::one() << 257;
        let expected = &(&two_512 - &two_257) + &BigUint::one();
        assert_eq!(c, expected, "Large multiplication carry propagation failed");
    }

    #[test]
    fn test_biguint_bit() {
        let a = BigUint::from_u64(0b1010);
        assert!(!a.bit(0));
        assert!(a.bit(1));
        assert!(!a.bit(2));
        assert!(a.bit(3));
        assert!(!a.bit(100));
    }
}