use crate::rubase::ruentity;
use aes_gcm::{
aead::{Aead, KeyInit},
Aes256Gcm, Nonce,
};
use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
const KEY: &[u8; 32] = b"my-32-byte-11secret-key-123456!!";
#[derive(Debug, Default, Clone)]
pub struct RuEnc {}
impl ruentity::BaseEntitySingle for RuEnc {
}
impl RuEnc {
pub fn new() -> RuEnc {
RuEnc {}
}
pub fn enc(&self, plain: &str) -> String {
let cipher = Aes256Gcm::new_from_slice(KEY).unwrap();
let nonce_bytes: [u8; 12] = rand::random(); let nonce = Nonce::from_slice(&nonce_bytes);
let ciphertext = cipher.encrypt(nonce, plain.as_bytes()).unwrap();
let mut combined = nonce_bytes.to_vec();
combined.extend_from_slice(&ciphertext);
BASE64.encode(&combined)
}
pub fn dec(&self, encoded: &str) -> String {
let cipher = Aes256Gcm::new_from_slice(KEY).unwrap();
let combined = BASE64.decode(encoded).unwrap();
let (nonce_bytes, ciphertext) = combined.split_at(12);
let nonce = Nonce::from_slice(nonce_bytes);
let plaintext = cipher.decrypt(nonce, ciphertext).unwrap();
String::from_utf8(plaintext).unwrap()
}
}