Skip to content

Commit 0f4661d

Browse files
committed
Add rust-aead-sample
1 parent 1bf8831 commit 0f4661d

File tree

3 files changed

+255
-0
lines changed

3 files changed

+255
-0
lines changed

rust-aead-sample/Cargo.lock

+197
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

rust-aead-sample/Cargo.toml

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
[package]
2+
name = "rust-aead-sample"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
[dependencies]
7+
anyhow = "1.0.95"
8+
base64 = "0.22.1"
9+
chacha20poly1305 = "0.10.1"

rust-aead-sample/src/main.rs

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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

Comments
 (0)