Skip to content

Instantly share code, notes, and snippets.

@TheBestTvarynka
Last active February 29, 2024 19:09
Show Gist options
  • Save TheBestTvarynka/12ed5b2b119a89789b1a65766d464f2c to your computer and use it in GitHub Desktop.
Save TheBestTvarynka/12ed5b2b119a89789b1a65766d464f2c to your computer and use it in GitHub Desktop.
aes256 cbc example
[package]
name = "aes-cbc-example"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
aes = "0.8.2"
cbc = "0.1.2"
use aes::cipher::block_padding::Pkcs7;
use aes::cipher::{BlockEncryptMut, KeyIvInit, BlockDecryptMut};
use aes::Aes256;
use cbc::{Encryptor, Decryptor};
type Aes256CbcEncryptor = Encryptor<Aes256>;
type Aes256CbcDecryptor = Decryptor<Aes256>;
const AES_BLOCK_SIZE: usize = 16;
fn main() {
//= cipher key and initialization vector =//
// 32-byte key for aes256
let key = [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5];
// initialization vector
let iv = vec![0; AES_BLOCK_SIZE];
//= encrypt =//
let plaintext = b"TheBestTvarynka";
let plaintext_len = plaintext.len();
// encryption performs inplace
let mut payload = plaintext.to_vec();
// input buffer must be big enough for padded plaintext
payload.extend_from_slice(&vec![0; AES_BLOCK_SIZE - plaintext_len % AES_BLOCK_SIZE]);
let encryptor = Aes256CbcEncryptor::new(key.as_slice().into(), iv.as_slice().into());
let encrypted = encryptor.encrypt_padded_mut::<Pkcs7>(&mut payload, plaintext_len).unwrap();
println!("{:?}", encrypted);
//= decrypt =//
let mut cipher = encrypted.to_vec();
let decryptor = Aes256CbcDecryptor::new(key.as_slice().into(), iv.as_slice().into());
let decrypted = decryptor.decrypt_padded_mut::<Pkcs7>(&mut cipher).unwrap();
println!("{:?}, {}", decrypted, String::from_utf8(decrypted.to_vec()).unwrap());
//= make sure that the data before and after are the same =//
assert_eq!(plaintext, decrypted);
}
@LostMyCode
Copy link

LostMyCode commented Feb 29, 2024

line27

    payload.extend_from_slice(&vec![0; plaintext_len % AES_BLOCK_SIZE]);

plaintext_len % AES_BLOCK_SIZE creates invalid size blocks.
it causes error in some cases like plaintext length is less than 8 or 16, etc...

so it should be AES_BLOCK_SIZE - plaintext_len % AES_BLOCK_SIZE

@TheBestTvarynka
Copy link
Author

@LostMyCode yes, you are right. thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment