Created
November 24, 2025 06:34
-
-
Save Celeo/5e7778b52f455104681536df34f31cb1 to your computer and use it in GitHub Desktop.
Playing with encryption in Rust
This file contains hidden or 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
| //! Example of E2EE setup with Diffie-Hellman key exchange, PBKD2 derivation, | |
| //! and AES GCM SIV AEAD data encryption. | |
| #![deny(unsafe_code)] | |
| #![deny(clippy::all)] | |
| #![deny(clippy::pedantic)] | |
| use aes_gcm_siv::{ | |
| Aes256GcmSiv, Nonce, | |
| aead::{Aead, KeyInit, OsRng}, | |
| }; | |
| use pbkdf2::pbkdf2_hmac_array; | |
| use sha2::Sha256; | |
| use x25519_dalek::{EphemeralSecret, PublicKey}; | |
| const PBKDF2_ROUNDS: u32 = 1_000; // minimum 600_000 for proper generation | |
| const TEST_MESSAGE: &str = "This is a super secret bit of information."; | |
| fn main() { | |
| println!("Generating initial secrets"); | |
| let alice_secret = EphemeralSecret::random(); | |
| let bob_secret = EphemeralSecret::random(); | |
| let bob_public = PublicKey::from(&bob_secret); | |
| println!("Performing key exchange"); | |
| let shared_secret = alice_secret.diffie_hellman(&bob_public); | |
| println!("Deriving key from shared secret"); | |
| let aes_key = pbkdf2_hmac_array::<Sha256, 32>(shared_secret.as_bytes(), b"", PBKDF2_ROUNDS); | |
| println!("Setting up AES"); | |
| let cipher = Aes256GcmSiv::new_from_slice(&aes_key).unwrap(); | |
| let nonce = Nonce::from_slice(b"unique nonce"); | |
| println!("Encrypting test message"); | |
| let ciphertext = cipher.encrypt(nonce, TEST_MESSAGE.as_bytes()).unwrap(); | |
| let plaintext = cipher.decrypt(nonce, ciphertext.as_ref()).unwrap(); | |
| assert_eq!(std::str::from_utf8(&plaintext).unwrap(), TEST_MESSAGE); | |
| println!("Pre-encrypted and post-decrypted strings are equal"); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment