blob: 153f0a9604448b6e08011a1c9fb8a610470d5fc9 (
plain)
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
|
use hmac::{Hmac, Mac};
use rand::{rngs::OsRng, RngCore};
use sha2::Sha256;
// Generate a random nonce
pub fn generate_nonce() -> String {
let mut bytes = [0u8; 16];
OsRng.fill_bytes(&mut bytes);
hex::encode(bytes)
}
// Calculate HMAC using the shared secret
pub fn calculate_hmac(secret: &str, data: &str) -> String {
type HmacSha256 = Hmac<Sha256>;
let mut mac = HmacSha256::new_from_slice(secret.as_bytes())
.expect("HMAC can take key of any size");
mac.update(data.as_bytes());
let result = mac.finalize();
let code_bytes = result.into_bytes();
hex::encode(code_bytes)
}
// Verify an HMAC token
pub fn verify_hmac(secret: &str, data: &str, expected: &str) -> bool {
let calculated = calculate_hmac(secret, data);
calculated == expected
}
|