From a0c754fc727a35d775c25857898986f4273db0a5 Mon Sep 17 00:00:00 2001 From: Kablersalat Date: Thu, 5 Jun 2025 00:14:27 +0200 Subject: Imported and sanetized dev server to publish on gitter --- src/auth.rs | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/auth.rs (limited to 'src/auth.rs') 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; + 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 +} -- cgit v1.2.3-70-g09d2