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
use cryptix_bigint::{ops::BigIntOpsExt, property::IsBigInt};

use crate::{OddModular, PrimeModular};

use super::primefield::FpElement;

/// this is the trait for faster modular multiplication, see HAC 14.36 for reference
///
/// The constraint is that gcd(base, P) = 1, we do not want to explicitly constraint the value of base, so
/// we constraint P to an odd prime, then this algorithm will be correct for all possible value of bases.
pub trait Montgomery<I>
where
    Self: PrimeModular<I> + OddModular<I> + Sized,
    I: BigIntOpsExt,
{
    /// R mod P where R = b^(I::DIG_LEN)
    const R_P: FpElement<I, Self>;
    /// R^{-1} mod P where R = b^(I::DIG_LEN)
    const R_INV_P: FpElement<I, Self>;
    /// R * R mod P where R = b^(I::DIG_LEN)
    const RR_P: FpElement<I, Self>;
    /// -P^(-1) mod b where b is base of I
    const NEG_P_INV_B: <I as IsBigInt>::Dig;
}

pub trait MontgomeryOps<I, M> 
where
    I: BigIntOpsExt,
    M: PrimeModular<I> + OddModular<I> + Montgomery<I>,
    Self: Copy + From<FpElement<I, M>>
{
    /// lhs * rhs * R^(-1) mod P
    fn mont_mul(self, rhs: Self) -> Self;

    fn mont_mul_fp(self, rhs: FpElement<I, M>) -> Self;

    /// a^2 * R^(-1) mod P
    fn mont_sqr(self) -> Self {
        self.mont_mul(self)
    }

    /// a * R^(-1) mod P
    fn mont_rdc(self) -> Self;

    /// a * R mod P
    fn mont_form(self) -> Self {
        self.mont_mul_fp(M::RR_P)
    }

    /// base^exp mod P
    fn mont_exp(self, exp: I) -> Self {
        let mut a: Self = M::R_P.into();
        let x = self.mont_mul_fp(M::RR_P);

        let t = exp.bit_len();
        for i in (0..t).rev() {
            a = a.mont_sqr();
            if exp.bit(i) {
                a = a.mont_mul(x)
            }
        }

        a.mont_rdc()
    }

    /// - input: a
    /// - output: a^(-1) * RR mod P
    ///
    /// We use algorithm 3 described in paper [Montgomery Inverse](https://cetinkayakoc.net/docs/j82.pdf) here
    fn mont_inv(self) -> Self;
}