Last active
February 29, 2024 19:09
-
-
Save TheBestTvarynka/12ed5b2b119a89789b1a65766d464f2c to your computer and use it in GitHub Desktop.
aes256 cbc example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| [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" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
line27
plaintext_len % AES_BLOCK_SIZEcreates invalid size blocks.it causes error in some cases like
plaintextlength is less than 8 or 16, etc...so it should be
AES_BLOCK_SIZE - plaintext_len % AES_BLOCK_SIZE