1use sha1::Sha1;
2use hmac::{Hmac, Mac};
3
4pub const SHA1_DIGEST_BYTES: usize = 20;
6
7pub fn hmac_sha1(key: &[u8], message: &[u8]) -> [u8; SHA1_DIGEST_BYTES] {
8 let mut hasher: Hmac<Sha1> = Mac::new_from_slice(key)
10 .expect("HMAC algoritms can take keys of any size");
11
12 hasher.update(message);
14
15 hasher.finalize().into_bytes().into()
17}
18
19
20
21#[cfg(test)]
22mod tests {
23 use crate::*;
24
25 use hex::ToHex;
26
27
28 #[test]
29 fn test_vector1() {
30 let data = "Hi There".as_bytes();
32 let key = &[0x0b; 20];
33 let expected = "b617318655057264e28bc0b6fb378c8ef146be00".to_string();
34
35 let hash = hmac_sha1(key, data);
36 assert_eq!(hash.encode_hex::<String>(),expected);
37 }
38
39 #[test]
40 fn test_vector2() {
41 let data = "what do ya want for nothing?".as_bytes();
43 let key = "Jefe".as_bytes();
44 let expected = "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79".to_string();
45
46 let hash = hmac_sha1(key, data);
47 assert_eq!(hash.encode_hex::<String>(),expected);
48 }
49
50 #[test]
51 fn test_vector3() {
52 let data = &[0xdd; 50];
54 let key = &[0xaa; 20];
55 let expected = "125d7342b9ac11cd91a39af48aa17b4f63f175d3".to_string();
56
57 let hash = hmac_sha1(key, data);
58 assert_eq!(hash.encode_hex::<String>(),expected);
59 }
60
61 #[test]
62 fn test_vector4() {
63 let data = &[0xcd; 50];
65 let key = &[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];
66 let expected = "4c9007f4026250c6bc8414f9bf50c86c2d7235da".to_string();
67
68 let hash = hmac_sha1(key, data);
69 assert_eq!(hash.encode_hex::<String>(),expected);
70 }
71
72 #[test]
73 fn test_vector5() {
74 let data = "Test With Truncation".as_bytes();
76 let key = &[0x0c;20];
77 let expected = "4c1a03424b55e07fe7f27be1d58bb9324a9a5a04".to_string();
78
79 let hash = hmac_sha1(key, data);
80 assert_eq!(hash.encode_hex::<String>(),expected);
81 }
82
83 #[test]
84 fn test_vector6() {
85 let data = "Test Using Larger Than Block-Size Key - Hash Key First".as_bytes();
87 let key = &[0xaa;80];
88 let expected = "aa4ae5e15272d00e95705637ce8a3b55ed402112".to_string();
89
90 let hash = hmac_sha1(key, data);
91 assert_eq!(hash.encode_hex::<String>(),expected);
92 }
93
94 #[test]
95 fn test_vector7() {
96 let data = "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data".as_bytes();
98 let key = &[0xaa;80];
99 let expected = "e8e99d0f45237d786d6bbaa7965c7808bbff1a91".to_string();
100
101 let hash = hmac_sha1(key, data);
102 assert_eq!(hash.encode_hex::<String>(),expected);
103 }
104}