feat: v0.2.1, add aes_256_gcm_decrypt and aes_256_gcm_encrypt

This commit is contained in:
2023-10-14 10:36:30 +08:00
parent 6537b7c473
commit a8ca61dba4
2 changed files with 54 additions and 1 deletions

View File

@@ -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"

View File

@@ -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<Vec<u8>, 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<Vec<u8>, 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);
}