use aes_gcm::aead::{Aead, KeyInit};
use aes_gcm::{Aes256Gcm, Key, Nonce};
use dusa_collection_utils::core::types::stringy::Stringy;
use rand::Rng;
use simple_comms::protocol::encryption::generate_key;
#[allow(unused_assignments)]
const NONCE_SIZE: usize = 12; const KEY_SIZE: usize = 32;
pub fn encrypt_with_embedded_key(data: &[u8]) -> Result<Stringy, String> {
let mut key: [u8; 32] = [0u8; 32];
generate_key(&mut key);
let cipher = Aes256Gcm::new(&key.into());
let nonce_bytes = rand::thread_rng().r#gen::<[u8; NONCE_SIZE]>();
let nonce = Nonce::from_slice(&nonce_bytes);
let ciphertext = cipher.encrypt(nonce, data).map_err(|e| e.to_string())?;
let mut result = Vec::with_capacity(KEY_SIZE + NONCE_SIZE + ciphertext.len());
result.extend_from_slice(&key);
result.extend_from_slice(nonce);
result.extend_from_slice(&ciphertext);
let cipher_text = Stringy::from(hex::encode(result));
Ok(cipher_text)
}
pub fn decrypt_with_embedded_key(encrypted_cipher_data: &[u8]) -> Result<Vec<u8>, String> {
let encrypted_data: Vec<u8> =
hex::decode(encrypted_cipher_data).map_err(|err| err.to_string())?;
if encrypted_data.len() <= KEY_SIZE + NONCE_SIZE {
return Err("Encrypted data is too short".to_string());
}
let key = Key::<Aes256Gcm>::from_slice(&encrypted_data[..KEY_SIZE]);
let cipher = Aes256Gcm::new(key);
let nonce = Nonce::from_slice(&encrypted_data[KEY_SIZE..KEY_SIZE + NONCE_SIZE]);
let ciphertext = &encrypted_data[KEY_SIZE + NONCE_SIZE..];
cipher.decrypt(nonce, ciphertext).map_err(|e| e.to_string())
}