use aes::Aes256;
use base64::{engine::general_purpose, Engine as _};
use block_modes::block_padding::Pkcs7;
use block_modes::{BlockMode, Cbc};
use generic_array::GenericArray;
use std::str;
use typenum::U16;
type Aes256Cbc = Cbc<Aes256, Pkcs7>;
pub struct AesEncryption;
impl AesEncryption {
pub fn to_aes_secret_key(base64_key: &str) -> Vec<u8> {
general_purpose::STANDARD
.decode(base64_key)
.expect("Base64 decode failed, please check your secret key")
}
pub fn decrypt_to_string(key: &[u8], encrypted_text: &str) -> String {
let decoded = general_purpose::STANDARD
.decode(encrypted_text)
.expect("Base64 decode failed");
let iv: &GenericArray<u8, U16> = GenericArray::from_slice(&decoded[..16]);
let ciphertext = &decoded[16..];
let cipher = Aes256Cbc::new_from_slices(key, iv).expect("AES CBC initialization failed");
let decrypted_ciphertext = cipher.decrypt_vec(ciphertext).expect("Decryption failed");
str::from_utf8(&decrypted_ciphertext)
.expect("UTF-8 conversion failed")
.to_string()
}
}