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
use hmac::{Hmac,NewMac,Mac};
use sha2::Sha256;
const SIGNED_KEY_LEN: usize = 32;
const BASE64_DIGEST_LEN: usize = 44;
pub struct Key (pub [u8; SIGNED_KEY_LEN]);
impl Key {
const fn zero() -> Self {
Key ( [0; SIGNED_KEY_LEN])
}
pub fn try_generate() -> Option<Key> {
use rand::RngCore;
let mut rng = rand::thread_rng();
let mut both_keys = [0; SIGNED_KEY_LEN];
rng.try_fill_bytes(&mut both_keys).ok()?;
Some(Key::from(&both_keys))
}
pub fn from(key: &[u8]) -> Key {
if key.len() < SIGNED_KEY_LEN {
panic!("bad key length: expected >= 32 bytes, found {}", key.len());
}
let mut output = Key::zero();
output.0.copy_from_slice(&key[..SIGNED_KEY_LEN]);
output
}
pub fn sign(&self, value: &str) -> String {
let mut mac = Hmac::<Sha256>::new_varkey(&self.0).expect("good key");
mac.update(value.as_bytes());
let mut new_value = base64::encode(&mac.finalize().into_bytes());
new_value.push_str(value);
new_value
}
pub fn verify(&self, value: &str) -> Result<String, String> {
if value.len() < BASE64_DIGEST_LEN {
return Err("length of value is <= BASE64_DIGEST_LEN".to_string());
}
let (digest_str, value) = value.split_at(BASE64_DIGEST_LEN);
let digest = base64::decode(digest_str).map_err(|_| "bad base64 digest")?;
let mut mac = Hmac::<Sha256>::new_varkey(&self.0).expect("good key");
mac.update(value.as_bytes());
mac.verify(&digest)
.map(|_| value.to_string())
.map_err(|_| "value did not verify".to_string())
}
}