diff --git a/Cargo.toml b/Cargo.toml index 96108a9..fb75112 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "aes-gcm-stream" -version = "0.2.0" +version = "0.2.1" edition = "2021" authors = ["Hatter Jiang"] repository = "https://git.hatter.ink/hatter/aes-gcm-stream" diff --git a/src/lib.rs b/src/lib.rs index e19c641..1067d73 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,5 @@ +use zeroize::Zeroize; + /// This library is created for AES/GCM stream encrypt or decrypt /// /// Structs for encryption: @@ -22,6 +24,33 @@ mod util; mod encryptor; mod decryptor; +pub fn aes_256_gcm_decrypt(key: &[u8], nonce: &[u8], message: &[u8]) -> Result, String> { + let mut key: [u8; 32] = match key.try_into() { + Err(_) => return Err(format!("Bad key length")), + Ok(key) => key, + }; + let mut aes256_gcm = Aes256GcmStreamDecryptor::new(key, nonce); + let mut first_block = aes256_gcm.update(message); + let final_block = aes256_gcm.finalize()?; + first_block.extend_from_slice(&final_block); + key.zeroize(); + Ok(first_block) +} + +pub fn aes_256_gcm_encrypt(key: &[u8], nonce: &[u8], message: &[u8]) -> Result, String> { + let mut key: [u8; 32] = match key.try_into() { + Err(_) => return Err(format!("Bad key length")), + Ok(key) => key, + }; + let mut aes256_gcm = Aes256GcmStreamEncryptor::new(key, nonce); + let mut first_block = aes256_gcm.update(message); + let (last_block, tag) = aes256_gcm.finalize(); + first_block.extend_from_slice(&last_block); + first_block.extend_from_slice(&tag); + key.zeroize(); + Ok(first_block) +} + #[test] fn test128() { use aes_gcm::{aead::{Aead, Nonce, Payload}, Aes128Gcm, KeyInit}; @@ -279,3 +308,27 @@ fn test256_stream() { let decrypted_plaintext = cipher.decrypt(&decrypt_nonce, ciphertext.as_slice()).expect("decrypt1"); assert_eq!(plaintext, decrypted_plaintext.as_slice()); } + +#[test] +fn test256_stream_and_array() { + let key = [0u8; 32]; + let nonce = [0; 12]; + + let mut plaintext = vec![]; + // encrypt + let mut ciphertext = vec![]; + let mut encryptor = Aes256GcmStreamEncryptor::new(key.clone(), &nonce); + for i in 0..1025 { + plaintext.extend_from_slice(&[(i % 128) as u8]); + ciphertext.extend_from_slice(&encryptor.update(&[(i % 128) as u8])); + } + let (last_block, tag) = encryptor.finalize(); + ciphertext.extend_from_slice(&last_block); + ciphertext.extend_from_slice(&tag); + + let encrypted = aes_256_gcm_encrypt(&key, &nonce, &plaintext).unwrap(); + let decrypted = aes_256_gcm_decrypt(&key, &nonce, &ciphertext).unwrap(); + + assert_eq!(ciphertext, encrypted); + assert_eq!(plaintext, decrypted); +}