forked from RustCrypto/crypto-bigint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconst_monty_form.rs
74 lines (61 loc) · 2.1 KB
/
const_monty_form.rs
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
//! Equivalence tests between `crypto_bigint::ConstMontyForm` and `num-bigint`.
mod common;
use common::to_biguint;
use crypto_bigint::{impl_modulus, modular::ConstMontyParams, Invert, Inverter, U256};
use num_bigint::BigUint;
use num_modular::ModularUnaryOps;
use proptest::prelude::*;
impl_modulus!(
Modulus,
U256,
"ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"
);
type ConstMontyForm = crypto_bigint::modular::ConstMontyForm<Modulus, { U256::LIMBS }>;
fn retrieve_biguint(monty_form: &ConstMontyForm) -> BigUint {
to_biguint(&monty_form.retrieve())
}
fn reduce(n: &U256) -> ConstMontyForm {
ConstMontyForm::new(&n)
}
prop_compose! {
fn uint()(bytes in any::<[u8; 32]>()) -> U256 {
U256::from_le_slice(&bytes)
}
}
proptest! {
#[test]
fn inv(x in uint()) {
let x = reduce(&x);
let actual = Option::<ConstMontyForm>::from(x.invert());
let x_bi = retrieve_biguint(&x);
let n_bi = to_biguint(&Modulus::MODULUS);
let expected = x_bi.invm(&n_bi);
match (expected, actual) {
(Some(exp), Some(act)) => {
let res = x * act;
prop_assert_eq!(res.retrieve(), U256::ONE);
prop_assert_eq!(exp, retrieve_biguint(&act).into());
}
(None, None) => (),
(_, _) => panic!("disagreement on if modular inverse exists")
}
}
#[test]
fn precomputed_inv(x in uint()) {
let x = reduce(&x);
let inverter = Modulus::precompute_inverter();
let actual = Option::<ConstMontyForm>::from(inverter.invert(&x));
let x_bi = retrieve_biguint(&x);
let n_bi = to_biguint(&Modulus::MODULUS);
let expected = x_bi.invm(&n_bi);
match (expected, actual) {
(Some(exp), Some(act)) => {
let res = x * act;
prop_assert_eq!(res.retrieve(), U256::ONE);
prop_assert_eq!(exp, retrieve_biguint(&act).into());
}
(None, None) => (),
(_, _) => panic!("disagreement on if modular inverse exists")
}
}
}