]> git.lizzy.rs Git - PAKEs.git/blob - srp/src/types.rs
e8024fc4d84cb3fd874e8cd97dd7a0598969f3b7
[PAKEs.git] / srp / src / types.rs
1 //! Additional SRP types.
2 use digest::Digest;
3 use num::BigUint;
4 use std::{error, fmt};
5 use tools::powm;
6
7 /// SRP authentification error.
8 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
9 pub struct SrpAuthError {
10     pub(crate) description: &'static str,
11 }
12
13 impl fmt::Display for SrpAuthError {
14     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
15         write!(f, "SRP authentification error")
16     }
17 }
18
19 impl error::Error for SrpAuthError {
20     fn description(&self) -> &str {
21         self.description
22     }
23 }
24
25 /// Group used for SRP computations
26 #[derive(Debug, Clone, Eq, PartialEq)]
27 pub struct SrpGroup {
28     /// A large safe prime (N = 2q+1, where q is prime)
29     pub n: BigUint,
30     /// A generator modulo N
31     pub g: BigUint,
32 }
33
34 impl SrpGroup {
35     pub(crate) fn powm(&self, v: &BigUint) -> BigUint {
36         powm(&self.g, v, &self.n)
37     }
38
39     /// Compute `k` with given hash function and return SRP parameters
40     pub(crate) fn compute_k<D: Digest>(&self) -> BigUint {
41         let n = self.n.to_bytes_be();
42         let g_bytes = self.g.to_bytes_be();
43         let mut buf = vec![0u8; n.len()];
44         let l = n.len() - g_bytes.len();
45         buf[l..].copy_from_slice(&g_bytes);
46
47         let mut d = D::new();
48         d.input(&n);
49         d.input(&buf);
50         BigUint::from_bytes_be(&d.result())
51     }
52 }
53
54 #[cfg(test)]
55 mod tests {
56     use groups::G_1024;
57     use sha_1::Sha1;
58
59     #[test]
60     fn test_k_1024_sha1() {
61         let k = G_1024.compute_k::<Sha1>().to_bytes_be();
62         assert_eq!(&k, include_bytes!("k_sha1_1024.bin"));
63     }
64 }