|
| 1 | +// region: --- Modules |
| 2 | + |
| 3 | +pub mod error; |
| 4 | +pub mod password; |
| 5 | +pub use error::{Error, Result}; |
| 6 | + |
| 7 | +use hmac::{Hmac, Mac}; |
| 8 | +use sha2::Sha256; |
| 9 | + |
| 10 | +// endregion: --- Modules |
| 11 | + |
| 12 | +pub struct EncryptContent { |
| 13 | + pub content: String, // Clear content. |
| 14 | + pub salt: String, // Clear salt. |
| 15 | +} |
| 16 | + |
| 17 | +// We normalise into b64 url as it is portable and a reliable character set. |
| 18 | +pub fn encrypt_into_b64u(key: &[u8], enc_content: &EncryptContent) -> Result<String> { |
| 19 | + let mut hmac = Hmac::<Sha256>::new_from_slice(key).map_err(|_| Error::KeyFailHmac)?; |
| 20 | + |
| 21 | + let EncryptContent { content, salt } = enc_content; |
| 22 | + |
| 23 | + hmac.update(content.as_bytes()); |
| 24 | + hmac.update(salt.as_bytes()); |
| 25 | + |
| 26 | + let result = hmac.finalize(); |
| 27 | + |
| 28 | + let result_bytes = result.into_bytes(); |
| 29 | + |
| 30 | + Ok(base64_url::encode(&result_bytes)) |
| 31 | +} |
| 32 | + |
| 33 | +// region: --- Tests |
| 34 | + |
| 35 | +#[cfg(test)] |
| 36 | +mod tests { |
| 37 | + use super::*; |
| 38 | + use anyhow::Result; |
| 39 | + use rand::RngCore; |
| 40 | + |
| 41 | + #[test] |
| 42 | + fn test_encrypt_into_b64u_ok() -> Result<()> { |
| 43 | + let mut fx_key = [0u8; 64]; // 512 bits = 64 bytes |
| 44 | + rand::rng().fill_bytes(&mut fx_key); |
| 45 | + |
| 46 | + let fx_enc_content = EncryptContent { |
| 47 | + content: "Hey there".to_string(), |
| 48 | + salt: "don't be salty".to_string(), |
| 49 | + }; |
| 50 | + let result = encrypt_into_b64u(&fx_key, &fx_enc_content)?; |
| 51 | + |
| 52 | + let result2 = encrypt_into_b64u(&fx_key, &fx_enc_content)?; |
| 53 | + |
| 54 | + // Basic indempotency test |
| 55 | + assert_eq!(result, result2); |
| 56 | + |
| 57 | + Ok(()) |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +// endregion: --- Tests |
0 commit comments