aboutsummaryrefslogtreecommitdiff
path: root/src/auth.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/auth.rs')
-rw-r--r--src/auth.rs29
1 files changed, 29 insertions, 0 deletions
diff --git a/src/auth.rs b/src/auth.rs
new file mode 100644
index 0000000..153f0a9
--- /dev/null
+++ b/src/auth.rs
@@ -0,0 +1,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
+}