pub async fn gcm_aes_encrypt_async<R, W>(
key: &[u8],
iv: &[u8],
reader: R,
writer: W,
aad: &[u8],
mul_fn: &GcmBlockMulFn,
) -> Result<[u8; 16], AesGcmAsyncError>Expand description
Async version of gcm_aes_encrypt that reads from an AsyncRead source and writes to an AsyncWrite destination.
This function provides authenticated encryption using AES-GCM mode with optimized performance for large data streams. It includes comprehensive error handling and input validation.
§Parameters
key- AES cipher key (16, 24, or 32 bytes for AES-128, AES-192, or AES-256)iv- Initialization Vector (at least 1 byte, longer IVs are hashed to 12 bytes)reader- AsyncRead source for plain text to encrypt and authenticatewriter- AsyncWrite destination for cipher textaad- Additional authenticated data (can be empty)mul_fn- Block multiplication function fromGcmBlockMulEnhancement::to_mul_fn()
§Returns
Result<[u8; 16], AesGcmAsyncError>- Authentication tag on success, error on failure
§Errors
InvalidKeySize- Key size is not 16, 24, or 32 bytesInvalidIvSize- IV size is 0 bytesIoError- I/O error during reading or writingCryptoError- Internal cryptographic error
§Examples
§Basic encryption
use crypto_async_rs::aes_gcm::{GcmBlockMulEnhancement};
use crypto_async_rs::aes_gcm_async::{gcm_aes_encrypt_async, AesGcmAsyncError};
use futures::io::Cursor;
async fn example() -> Result<(), AesGcmAsyncError> {
let cipher_key = [0xfe, 0xff, 0xe9, 0x92, 0x86, 0x65, 0x73, 0x1c, 0x6d, 0x6a, 0x8f, 0x94, 0x67, 0x30, 0x83, 0x08];
let iv = [0xca, 0xfe, 0xba, 0xbe, 0xfa, 0xce, 0xdb, 0xad];
let plain_text = [0xd9, 0x31, 0x32, 0x25, 0xf8, 0x84, 0x06, 0xe5, 0xa5, 0x59];
let aad = [0xfe, 0xed, 0xfa, 0xce, 0xde, 0xad, 0xbe];
let mul_fn = GcmBlockMulEnhancement::None.to_mul_fn(&cipher_key);
let reader = Cursor::new(&plain_text);
let mut writer = Cursor::new(Vec::new());
let tag = gcm_aes_encrypt_async(&cipher_key, &iv, reader, &mut writer, &aad, &mul_fn).await?;
println!("Authentication tag: {:?}", tag);
Ok(())
}§Error handling
use crypto_async_rs::aes_gcm_async::{gcm_aes_encrypt_async, AesGcmAsyncError};
use crypto_async_rs::aes_gcm::GcmBlockMulEnhancement;
use futures::io::Cursor;
async fn error_example() {
let invalid_key = [0u8; 8]; // Too short
let iv = [0xca, 0xfe, 0xba, 0xbe];
let reader = Cursor::new(b"test");
let mut writer = Cursor::new(Vec::new());
let mul_fn = GcmBlockMulEnhancement::None.to_mul_fn(&[0u8; 16]);
match gcm_aes_encrypt_async(&invalid_key, &iv, reader, &mut writer, &[], &mul_fn).await {
Err(AesGcmAsyncError::InvalidKeySize(size)) => {
println!("Invalid key size: {} bytes", size);
}
_ => unreachable!(),
}
}