use aes_gcm::{
aead::{Aead, AeadCore, KeyInit, OsRng},
Aes256Gcm, Key, Nonce,
};
use crate::core::error2::Result;
#[allow(deprecated)]
pub fn aes_256_encrypt(key_str_32: &str, plaintext: &str) -> Result<String> {
let key = Key::<Aes256Gcm>::from_slice(key_str_32.as_bytes());
let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
let cipher = Aes256Gcm::new(key);
let ciphered_data = cipher
.encrypt(&nonce, plaintext.as_bytes())
.expect("failed to encrypt");
let mut encrypted_data: Vec<u8> = nonce.to_vec();
encrypted_data.extend_from_slice(&ciphered_data);
Ok(hex::encode(encrypted_data))
}
#[allow(deprecated)]
pub fn aes_256_decrypt(key_str: &str, encrypted_data: &str) -> Result<String> {
let encrypted_data = hex::decode(encrypted_data).map_err(|e| anyhow::anyhow!(e))?;
let key = Key::<Aes256Gcm>::from_slice(key_str.as_bytes());
let (nonce_arr, ciphered_data) = encrypted_data.split_at(12);
let nonce = Nonce::from_slice(nonce_arr);
let cipher = Aes256Gcm::new(key);
let plaintext = cipher
.decrypt(nonce, ciphered_data)
.map_err(|e| anyhow::anyhow!(e))?;
let l = String::from_utf8(plaintext).map_err(|e| anyhow::anyhow!(e))?;
Ok(l)
}