Created
January 5, 2023 11:47
-
-
Save kuboon/a2cea88f8a88cd9b7e79d7e362e01663 to your computer and use it in GitHub Desktop.
chacha rust sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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