From 7a4344608ef647648cd90e74e8de6005f562b0cc Mon Sep 17 00:00:00 2001 From: Sosthene Date: Mon, 7 Oct 2024 11:15:22 +0200 Subject: [PATCH] Modify fields encryption, can selectively encrypt and fields that are not decrypted stay as they are --- src/pcd.rs | 46 ++++++++++++++++++++++++++-------------------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/src/pcd.rs b/src/pcd.rs index ad34021..ef55f56 100644 --- a/src/pcd.rs +++ b/src/pcd.rs @@ -92,6 +92,7 @@ pub trait Pcd<'a>: Serialize + Deserialize<'a> { fn encrypt_fields( &self, + fields_to_encrypt: &[String], fields2keys: &mut Map, fields2cipher: &mut Map, ) -> Result<()> { @@ -102,28 +103,32 @@ pub trait Pcd<'a>: Serialize + Deserialize<'a> { let mut rng = thread_rng(); for (field, value) in as_map { - let aes_key = Aes256Gcm::generate_key(&mut rng); - let nonce = Aes256Gcm::generate_nonce(&mut rng); - fields2keys.insert( - field.to_owned(), - Value::String(aes_key.to_lower_hex_string()), - ); + if fields_to_encrypt.contains(field) { + let aes_key = Aes256Gcm::generate_key(&mut rng); + let nonce = Aes256Gcm::generate_nonce(&mut rng); + fields2keys.insert( + field.to_owned(), + Value::String(aes_key.to_lower_hex_string()), + ); - let encrypt_eng = Aes256Gcm::new(&aes_key); - let value_string = value.to_string(); - let payload = Payload { - msg: value_string.as_bytes(), - aad: AAD, - }; - let cipher = encrypt_eng - .encrypt(&nonce, payload) - .map_err(|e| Error::msg(format!("Encryption failed for field {}: {}", field, e)))?; + let encrypt_eng = Aes256Gcm::new(&aes_key); + let value_string = value.to_string(); + let payload = Payload { + msg: value_string.as_bytes(), + aad: AAD, + }; + let cipher = encrypt_eng + .encrypt(&nonce, payload) + .map_err(|e| Error::msg(format!("Encryption failed for field {}: {}", field, e)))?; - let mut res = Vec::with_capacity(nonce.len() + cipher.len()); - res.extend_from_slice(&nonce); - res.extend_from_slice(&cipher); + let mut res = Vec::with_capacity(nonce.len() + cipher.len()); + res.extend_from_slice(&nonce); + res.extend_from_slice(&cipher); - fields2cipher.insert(field.to_owned(), Value::String(res.to_lower_hex_string())); + fields2cipher.insert(field.to_owned(), Value::String(res.to_lower_hex_string())); + } else { + fields2cipher.insert(field.to_owned(), value.clone()); + } } Ok(()) @@ -169,7 +174,8 @@ pub trait Pcd<'a>: Serialize + Deserialize<'a> { fields2plain.insert(field.to_owned(), Value::String(decrypted_value)); } else { - fields2plain.insert(field.to_owned(), Value::Null); + // We keep the original value, that allows us to have fields that are always left unencrypted + fields2plain.insert(field.to_owned(), encrypted_value.clone()); } }