gm_rs/
sm2.rs

1pub mod error;
2pub mod exchange;
3pub(crate) mod formulas;
4pub mod key;
5mod macros;
6pub mod montgomery;
7pub(crate) mod operation;
8pub mod p256_ecc;
9pub mod p256_field;
10pub mod p256_pre_table;
11pub mod util;
12
13/// Fp 的加法,减法,乘法并不是简单的四则运算。其运算结果的值必须在Fp的有限域中,这样保证椭圆曲线变成离散的点
14///
15/// 这里我们规定一个有限域Fp
16///
17/// * 取大质数p,则有限域中有p-1个有限元:0,1,2...p-1
18/// * Fp上的加法为模p加法`a+b≡c(mod p)`
19/// * Fp上的乘法为模p乘法`a×b≡c(mod p)`
20/// * Fp上的减法为模p减法`a-b≡c(mod p)`
21/// * Fp上的除法就是乘除数的乘法逆元`a÷b≡c(mod p)`,即 `a×b^(-1)≡c (mod p)`
22/// * Fp的乘法单位元为1,零元为0
23/// * Fp域上满足交换律,结合律,分配律
24pub trait FeOperation {
25    /// Returns `(self + other) % modulus`.
26    ///
27    /// Panics if the modulus is zero.
28    ///
29    fn mod_add(&self, other: &Self, modulus: &Self) -> Self;
30
31    /// Returns `(self - other) % modulus`.
32    ///
33    /// Panics if the modulus is zero.
34    ///
35    fn mod_sub(&self, other: &Self, modulus: &Self) -> Self;
36
37    /// Returns `(self * other) % modulus`.
38    ///
39    /// Panics if the modulus is zero.
40    ///
41    fn mod_mul(&self, other: &Self, modulus: &Self) -> Self;
42
43    /// Extended Eulidean Algorithm(EEA) to calculate x^(-1) mod p
44    fn inv(&self, modulus: &Self) -> Self;
45
46    /// Self >>= carry
47    fn right_shift(&self, carry: u32) -> Self;
48}
49
50#[cfg(test)]
51mod test_sm2 {
52    use crate::sm2::exchange;
53    use crate::sm2::key::{gen_keypair, CompressModle};
54
55    #[test]
56    fn test_gen_keypair() {
57        gen_keypair(CompressModle::Compressed).unwrap();
58    }
59
60    #[test]
61    fn test_encrypt_decrypt() {
62        let (pk, sk) = gen_keypair(CompressModle::Compressed).unwrap();
63        let msg = "你好 world,asjdkajhdjadahkubbhj12893718927391873891,@@!! world,1231 wo12321321313asdadadahello world,hello world".as_bytes();
64        let encrypt = pk.encrypt(msg).unwrap();
65        let plain = sk.decrypt(&encrypt).unwrap();
66        assert_eq!(msg, plain)
67    }
68
69    #[test]
70    fn test_sign_verify() {
71        let msg = b"hello";
72        let (pk, sk) = gen_keypair(CompressModle::Compressed).unwrap();
73        let signature = sk.sign(None, msg).unwrap();
74        pk.verify(None, msg, &signature).unwrap();
75    }
76
77    #[test]
78    fn test_key_exchange() {
79        let id_a = "alice123@qq.com";
80        let id_b = "bob456@qq.com";
81
82        let (mut alice, mut bob) = exchange::build_ex_pair(8, id_a, id_b).unwrap();
83
84        let ra_point = alice.exchange_1().unwrap();
85        let (rb_point, sb) = bob.exchange_2(&ra_point).unwrap();
86        let sa = alice.exchange_3(&rb_point, sb).unwrap();
87        let succ = bob.exchange_4(sa, &ra_point).unwrap();
88        assert_eq!(succ, true);
89        assert_eq!(alice.k, bob.k);
90    }
91
92}