|
| 1 | +use anyhow::anyhow; |
| 2 | +use base64::{prelude::BASE64_STANDARD_NO_PAD, Engine}; |
| 3 | +use chacha20poly1305::{ |
| 4 | + aead::{Aead, AeadCore, KeyInit, OsRng, Payload}, |
| 5 | + ChaCha20Poly1305, Key, Nonce, |
| 6 | +}; |
| 7 | + |
| 8 | +struct Encrypted { |
| 9 | + nonce: Vec<u8>, |
| 10 | + ciphertext: Vec<u8>, |
| 11 | +} |
| 12 | + |
| 13 | +fn encrypt(key: &[u8], plaintext: &[u8], aad: &[u8]) -> anyhow::Result<Encrypted> { |
| 14 | + let cipher = ChaCha20Poly1305::new(Key::from_slice(key)); |
| 15 | + let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng); |
| 16 | + let ciphertext = cipher |
| 17 | + .encrypt(&nonce, Payload { msg: plaintext, aad }) |
| 18 | + .map_err(|_| anyhow!("failed to encrypt"))?; |
| 19 | + Ok(Encrypted { |
| 20 | + nonce: nonce.to_vec(), |
| 21 | + ciphertext, |
| 22 | + }) |
| 23 | +} |
| 24 | + |
| 25 | +fn decrypt(key: &[u8], nonce: &[u8], ciphertext: &[u8], aad: &[u8]) -> anyhow::Result<Vec<u8>> { |
| 26 | + let cipher = ChaCha20Poly1305::new(Key::from_slice(key)); |
| 27 | + let nonce = Nonce::from_slice(nonce); |
| 28 | + let plaintext = cipher |
| 29 | + .decrypt(nonce, Payload { msg: ciphertext, aad }) |
| 30 | + .map_err(|_| anyhow!("failed to decrypt"))?; |
| 31 | + Ok(plaintext) |
| 32 | +} |
| 33 | + |
| 34 | +fn main() -> anyhow::Result<()> { |
| 35 | + let key = ChaCha20Poly1305::generate_key(&mut OsRng); |
| 36 | + let plaintext = b"Hello, World!!"; |
| 37 | + let aad = b"123"; |
| 38 | + |
| 39 | + let Encrypted { nonce, ciphertext } = encrypt(&key, plaintext, aad)?; |
| 40 | + |
| 41 | + println!("nonce = {}", BASE64_STANDARD_NO_PAD.encode(&nonce)); |
| 42 | + println!("ciphertext = {}", BASE64_STANDARD_NO_PAD.encode(&ciphertext)); |
| 43 | + |
| 44 | + let decrypted = decrypt(&key, &nonce, &ciphertext, aad)?; |
| 45 | + |
| 46 | + println!("decrypted = {}", String::from_utf8_lossy(&decrypted)); |
| 47 | + |
| 48 | + Ok(()) |
| 49 | +} |
0 commit comments