nutek_cipher_lib/lib.rs
1pub mod aes_gcm_siv {
2 extern crate aes_gcm_siv;
3 use aes_gcm_siv::{
4 aead::{Aead, KeyInit},
5 Aes256GcmSiv, Nonce, Key // Or `Aes128GcmSiv`
6 };
7 use aes_gcm_siv::aead::consts::U12;
8 use aes_gcm_siv::aead::generic_array::GenericArray;
9
10 /// Decrypts the given ciphertext with the given key and nonce.
11 /// The key must be 32 bytes long and the nonce must be 12 bytes long.
12 /// The plaintext is returned as an option vector of bytes.
13 ///
14 /// # Examples
15 ///
16 /// ```
17 /// use nutek_cipher_lib::aes_gcm_siv::decrypt;
18 /// use nutek_cipher_lib::aes_gcm_siv::encrypt;
19 ///
20 /// fn main() {
21 /// let ciphertext = encrypt(b"hello world", b"123456123456", b"12345678123456781234567812345678");
22 /// let plaintext = decrypt( b"12345678123456781234567812345678", b"123456123456", ciphertext).unwrap();
23 /// assert_eq!(plaintext, b"hello world");
24 /// }
25 /// ```
26 ///
27 pub fn decrypt(key_slice: &[u8], nonce_slice: &[u8], ciphertext: Vec<u8>) -> Option<Vec<u8>> {
28 let key = Key::<Aes256GcmSiv>::from_slice(key_slice);
29 let cipher = Aes256GcmSiv::new(&key);
30 let nonce: &GenericArray<u8, U12> = Nonce::from_slice(nonce_slice);
31 let plaintext = cipher.decrypt(nonce, ciphertext.as_ref()).ok()?;
32 Some(plaintext)
33 }
34
35 /// Encrypts the given plaintext with the given key and nonce.
36 /// The key must be 32 bytes long and the nonce must be 12 bytes long.
37 /// The ciphertext is returned as a vector of bytes.
38 ///
39 /// # Examples
40 ///
41 /// ```
42 /// use nutek_cipher_lib::aes_gcm_siv::encrypt;
43 ///
44 /// fn main() {
45 /// encrypt(b"hello world", b"123456123456", b"12345678123456781234567812345678");
46 /// }
47 /// ```
48 ///
49 pub fn encrypt(plaintext: &[u8], nonce_slice: &[u8], key_slice: &[u8]) -> Vec<u8> {
50 let key = Key::<Aes256GcmSiv>::from_slice(key_slice);
51 let cipher = Aes256GcmSiv::new(&key);
52 let nonce: &GenericArray<u8, U12> = Nonce::from_slice(nonce_slice);
53 let ciphertext = cipher.encrypt(nonce, plaintext.as_ref()).unwrap();
54 if ciphertext.len() == 0 {
55 panic!("❌ Ciphertext is empty");
56 } else if ciphertext.len() > aes_gcm_siv::C_MAX.try_into().unwrap() {
57 println!("❌ Ciphertext is too long");
58 }
59 ciphertext
60 }
61}
62
63#[cfg(test)]
64mod tests {
65 use super::*;
66
67 #[test]
68 fn test_encrypt_decrypt() {
69 let key = b"12345678123456781234567812345678";
70 let nonce = b"123456123456";
71 let plaintext = b"hello world";
72
73 // let ciphertext = encrypt(key, nonce, plaintext);
74 let ciphertext = aes_gcm_siv::encrypt(plaintext, nonce, key);
75 let decrypted_content = aes_gcm_siv::decrypt(key, nonce, ciphertext).unwrap();
76
77 assert_eq!(plaintext, &decrypted_content[..]);
78 }
79}