Using rust_crypto AesSafe256Encryptor

Hi

I am encountering a runtime error when I tried to encrypt some buffer but not sure what is the problem.

    let mut file_to_encrypt = std::fs::File::open("tempfile").unwrap();
	let mut plain_bytes = vec![];
	file_to_encrypt.read_to_end(&mut plain_bytes).unwrap();

	let mut symmetric_key = [0u8; 32];
	rand::rngs::OsRng.fill(&mut symmetric_key);

	let aes_encryptor = crypto::aessafe::AesSafe256Encryptor::new(&symmetric_key);
	let mut encrypted_buffer = [0u8; 4096];

	aes_encryptor.encrypt_block(&plain_bytes, &mut encrypted_buffer);

The error I saw was

thread 'main' panicked at 'assertion failed: dst.len() * 4 == input.len()'

It sounds like it wants encrypted_buffer to be exactly 4 times as large as plain_bytes, but I may be wrong as you didn't post which line failed.

Do not use rust-crypto:

I recommend to take a look at RustCrypto crates (disclaimer: I am a maintainer of this org). AES is implemented in the aes crate.

Block ciphers work on blocks (16 bytes for AES), so to encrypt/decrypt messages longer than that you have to choose mode of operation. Unless you have to be compatible with other software, CTR mode mode will be a good choice (but do pay attention to the "hazmat" notice), since it transforms block cipher into stream cipher, so you don't have to bother with message padding.

2 Likes