-
Notifications
You must be signed in to change notification settings - Fork 143
Closed
RustCrypto/traits
#849Description
describe & question
BlockCipher.encrypt work in-place, and no allocate. So I need to calculate the buffer size manually.
my question :
- Is there any way to get block-size easily? not the wordy one.
- can we add
block_sizemethod toBlockCipher?
my code
use std::error;
use aes::block_cipher::{generic_array::typenum::Unsigned, BlockCipher};
use aes::Aes128;
use block_modes::{block_padding::Pkcs7, BlockMode, Cbc};
type Aes128Cbc = Cbc<Aes128, Pkcs7>;
type Byte = u8;
fn aes128_cbc_encrypt(
plaintext: &[Byte],
key: &[Byte],
iv: &[Byte],
) -> Result<Vec<Byte>, Box<dyn error::Error>> {
// pading只是做对齐, 但是这个对齐是in-place, 这个buf还是需要自己申请大小以满足条件
// pading just fill, no allocate
// =======================================
let block_size = <Aes128 as BlockCipher>::BlockSize::to_usize();
let padding_length = block_size - plaintext.len() % block_size;
// =======================================
let cipher = Aes128Cbc::new_var(&key, &iv)?;
let mut buffer = Vec::with_capacity(padding_length + plaintext.len());
buffer.resize(padding_length + plaintext.len(), 0u8);
// unsafe { buffer.set_len(padding_length+plaintext.len()); }
buffer[..plaintext.len()].copy_from_slice(plaintext);
//let ciphertext = cipher.encrypt(&mut buffer, plaintext.len())?;
cipher.encrypt(&mut buffer, plaintext.len())?;
Ok(buffer)
}Cargo.toml
[dependencies]
block-modes="0.4.0"
aes="0.4.0Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels