Skip to content

Instantly share code, notes, and snippets.

@kuboon
Created January 5, 2023 11:47
Show Gist options
  • Save kuboon/a2cea88f8a88cd9b7e79d7e362e01663 to your computer and use it in GitHub Desktop.
Save kuboon/a2cea88f8a88cd9b7e79d7e362e01663 to your computer and use it in GitHub Desktop.
chacha rust sample
[package]
name = "chacha"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
"chacha20poly1305" = "0.10.1"
use chacha20poly1305::{
aead::{Aead, AeadCore, KeyInit, OsRng},
ChaCha20Poly1305
};
fn main() -> Result<(), Box<dyn std::error::Error>>{
let key = ChaCha20Poly1305::generate_key(&mut OsRng);
let cipher = ChaCha20Poly1305::new(&key);
let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng); // 96-bits; unique per message
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");
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment