use aes_gcm::{
aead::{Aead, AeadCore, KeyInit, OsRng, generic_array::GenericArray},
Aes256Gcm, Key };
use crate::networking_utilities::ServerError;
pub fn encrypt_aes256(s: &[u8], key: &[u8]) -> (Vec<u8>, [u8;12]) {
let key = Key::<Aes256Gcm>::from_slice(key);
let cipher = Aes256Gcm::new(key);
let nonce = Aes256Gcm::generate_nonce(&mut OsRng); let ciphertext = cipher.encrypt(&nonce, s).unwrap(); (ciphertext, nonce.into())
}
pub fn decrypt_aes256(s: &[u8], key: &[u8], nonce: &[u8] ) -> Result<Vec<u8>, ServerError> {
let key = Key::<Aes256Gcm>::from_slice(key);
let cipher = Aes256Gcm::new(key);
let nonce = GenericArray::clone_from_slice(nonce); let plaintext = cipher.decrypt(&nonce, s)?;
Ok(plaintext)
}
mod tests {
#![allow(unused)]
use super::*;
#[test]
fn test_encrypt_then_decrypt() {
let key: [u8;32] = [42;32];
let plaintext = String::from("This is the text");
let (ciphertext, nonce) = encrypt_aes256(&plaintext.as_bytes(), &key);
println!("ciphertext: {:x?}", ciphertext);
let decrypted_ciphertext = decrypt_aes256(&ciphertext, &key, &nonce).unwrap();
println!("Plaintext: {}", plaintext);
assert_eq!(plaintext.as_bytes(), decrypted_ciphertext);
println!("Decrypted: {}", String::from_utf8(decrypted_ciphertext).unwrap());
}
#[test]
fn test_encryption() {
let key = Aes256Gcm::generate_key(OsRng);
let key: &[u8; 32] = &[42; 32];
let key: &Key<Aes256Gcm> = key.into();
let key: &[u8] = &[42; 32];
let key: [u8; 32] = key.try_into().unwrap();
let key = Key::<Aes256Gcm>::from_slice(&key);
let cipher = Aes256Gcm::new(&key);
let nonce = Aes256Gcm::generate_nonce(&mut OsRng); let ciphertext = cipher.encrypt(&nonce, b"plaintext message".as_ref()).unwrap();
let plaintext = cipher.decrypt(&nonce, ciphertext.as_ref()).unwrap();
assert_eq!(&plaintext, b"plaintext message");
}
}