From b1032918daa3f3919ae7838ea72c37acd4e3bbb3 Mon Sep 17 00:00:00 2001 From: viraladmin <00purple@gmail.com> Date: Fri, 13 Oct 2023 14:53:00 -0600 Subject: [PATCH] Update text.rs Added timing attack protection for encryption, was overlooked. This changed the type from &str to Option. --- src/encryption/text.rs | 36 ++++++++++++++++++++++++------------ 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/src/encryption/text.rs b/src/encryption/text.rs index ebe4aa6..1ea50b7 100644 --- a/src/encryption/text.rs +++ b/src/encryption/text.rs @@ -1,6 +1,3 @@ - use openssl::symm::{encrypt, Cipher}; - use base64::encode; - use crate::encryption::text::hmac::calculate_hmac; /// Encrypts the input text with an optional encryption key. /// /// The `input` parameter is the text to be encrypted. @@ -18,7 +15,7 @@ /// let key = Some("your_secret_key"); /// let encrypted = encrypts(input, key); /// - /// assert!(encrypted.len() > 0); + /// assert!(encrypted.as_ref().unwrap().len() > 0); /// ``` /// /// Encrypt a text without providing a custom key: @@ -29,25 +26,40 @@ /// let input = "ThisIsJustaTestString"; /// let encrypted = encrypts(input, None); /// - /// assert!(encrypted.len() > 0); + /// assert!(encrypted.as_ref().unwrap().len() > 0); /// ``` - pub fn encrypts(input: &str, key: Option<&str>) -> String { + use openssl::symm::{encrypt, Cipher}; + use base64::encode; + use crate::encryption::text::hmac::calculate_hmac; + use subtle::ConstantTimeEq; + + pub fn encrypts(input: &str, key: Option<&str>) -> Option { let cipher = Cipher::aes_128_cbc(); let key = key.unwrap_or("welovenfts"); let iv_bytes = &input.to_string()[..10]; let iv = base64::encode(iv_bytes); let mut padded_key = key.as_bytes().to_vec(); while padded_key.len() < 16 { - padded_key.push(b'\0'); + padded_key.push(b'\0'); } let ciphertext = encrypt(cipher, &padded_key, Some(iv.as_bytes()), input.as_bytes()).unwrap(); + + // Calculate HMAC let hmac = calculate_hmac(&ciphertext, &padded_key); - let mut result = iv.into_bytes(); - result.extend_from_slice(&hmac); - result.extend_from_slice(&ciphertext); - let encoded_result = encode(&result); - encoded_result + + // Constant-time compare HMAC to protect against timing attacks + if hmac.ct_eq(&calculate_hmac(&ciphertext, &padded_key)).unwrap_u8() == 1 { + let mut result = iv.into_bytes(); + result.extend_from_slice(&hmac); + result.extend_from_slice(&ciphertext); + let encoded_result = encode(&result); + Some(encoded_result) + } else { + println!("Encryption HMAC validation failed"); + None + } } + pub mod hmac { pub(crate) fn calculate_hmac(data: &[u8], key: &[u8]) -> Vec { use openssl::hash::MessageDigest;