How to Use AES Encryption in Rust

Use the aes crate with Aes256Gcm to encrypt and decrypt data securely in Rust.

Use the aes crate to encrypt data with AES-256-GCM in Rust.

use aes::Aes256;
use aes_gcm::{Aes256Gcm, KeyInit, Nonce, aead::Aead, aead::rand_core::OsRng};

fn main() {
    let cipher = Aes256Gcm::new_from_slice(b"0123456789abcdef0123456789abcdef").unwrap();
    let nonce = Nonce::from_slice(b"unique nonce");
    let ciphertext = cipher.encrypt(nonce, b"secret message").unwrap();
    let plaintext = cipher.decrypt(nonce, &ciphertext).unwrap();
    assert_eq!(plaintext, b"secret message");
}

Add aes = "0.8" and aes-gcm = "0.10" to your Cargo.toml dependencies.