forked from wrenn/wrenn
22
envd-rs/src/crypto/hmac_sha256.rs
Normal file
22
envd-rs/src/crypto/hmac_sha256.rs
Normal file
@ -0,0 +1,22 @@
|
||||
use hmac::{Hmac, Mac};
|
||||
use sha2::Sha256;
|
||||
|
||||
type HmacSha256 = Hmac<Sha256>;
|
||||
|
||||
pub fn compute(key: &[u8], data: &[u8]) -> String {
|
||||
let mut mac = HmacSha256::new_from_slice(key).expect("HMAC accepts any key length");
|
||||
mac.update(data);
|
||||
let result = mac.finalize();
|
||||
hex::encode(result.into_bytes())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_hmac_sha256() {
|
||||
let result = compute(b"key", b"message");
|
||||
assert_eq!(result.len(), 64); // SHA-256 hex = 64 chars
|
||||
}
|
||||
}
|
||||
3
envd-rs/src/crypto/mod.rs
Normal file
3
envd-rs/src/crypto/mod.rs
Normal file
@ -0,0 +1,3 @@
|
||||
pub mod sha256;
|
||||
pub mod sha512;
|
||||
pub mod hmac_sha256;
|
||||
33
envd-rs/src/crypto/sha256.rs
Normal file
33
envd-rs/src/crypto/sha256.rs
Normal file
@ -0,0 +1,33 @@
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD_NO_PAD;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
pub fn hash(data: &[u8]) -> String {
|
||||
let h = Sha256::digest(data);
|
||||
let encoded = STANDARD_NO_PAD.encode(h);
|
||||
format!("$sha256${encoded}")
|
||||
}
|
||||
|
||||
pub fn hash_without_prefix(data: &[u8]) -> String {
|
||||
let h = Sha256::digest(data);
|
||||
STANDARD_NO_PAD.encode(h)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_hash_format() {
|
||||
let result = hash(b"test");
|
||||
assert!(result.starts_with("$sha256$"));
|
||||
assert!(!result.contains('='));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_hash_without_prefix() {
|
||||
let result = hash_without_prefix(b"test");
|
||||
assert!(!result.starts_with("$sha256$"));
|
||||
assert!(!result.contains('='));
|
||||
}
|
||||
}
|
||||
24
envd-rs/src/crypto/sha512.rs
Normal file
24
envd-rs/src/crypto/sha512.rs
Normal file
@ -0,0 +1,24 @@
|
||||
use sha2::{Digest, Sha512};
|
||||
|
||||
pub fn hash_access_token(token: &str) -> String {
|
||||
let h = Sha512::digest(token.as_bytes());
|
||||
hex::encode(h)
|
||||
}
|
||||
|
||||
pub fn hash_access_token_bytes(token: &[u8]) -> String {
|
||||
let h = Sha512::digest(token);
|
||||
hex::encode(h)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_hash_access_token() {
|
||||
let h1 = hash_access_token("test");
|
||||
let h2 = hash_access_token_bytes(b"test");
|
||||
assert_eq!(h1, h2);
|
||||
assert_eq!(h1.len(), 128); // SHA-512 hex = 128 chars
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user