How do I set the Initialization Vector (IV) in Rust's `aes` crate? (AES-128 CBC)

2.5k Views Asked by At

As the title suggests. I can create a new Aes128 cipher, but I've checked the documentation and found nothing that might allow me to provide an IV. Am I missing something obvious?

let cipher = Aes128::new(key);
let mut block = file_blocks[0].clone();
cipher.decrypt_block(&mut block);
1

There are 1 best solutions below

3
Universe Chen On

You can use crate aes and block_modes.

Like this, but this test will panic because I used unwrap() and didn't set effective 'key', 'iv' and 'encrypted_data';

Cargo.toml

base64 = "0.13.0"
aes = "0.7.4"
block-modes = "0.8.1"

lib.rs

use aes::Aes128;
use block_modes::block_padding::Pkcs7;
use block_modes::{BlockMode, Cbc};

// create an alias for convenience
type Aes128Cbc = Cbc<Aes128, Pkcs7>;

/// Use [key](https://en.wikipedia.org/wiki/Key_(cryptography)) and [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector) to decrypt data encrypt by [aes128](https://en.wikipedia.org/wiki/Advanced_Encryption_Standard); <br />
/// 使用密钥([百度百科](https://baike.baidu.com/item/%E5%AF%86%E9%92%A5) | [维基百科](https://zh.wikipedia.org/wiki/%E5%AF%86%E9%92%A5))和初始化向量([百度百科](https://baike.baidu.com/item/%E5%88%9D%E5%A7%8B%E5%8C%96%E5%90%91%E9%87%8F) | [维基百科](https://zh.wikipedia.org/wiki/%E5%88%9D%E5%A7%8B%E5%90%91%E9%87%8F))来解密根据 aes128([百度百科](https://baike.baidu.com/item/AES%E5%8A%A0%E5%AF%86%E6%A0%87%E5%87%86) | [维基百科](https://zh.wikipedia.org/wiki/%E9%AB%98%E7%BA%A7%E5%8A%A0%E5%AF%86%E6%A0%87%E5%87%86)) 进行加密的数据;
pub fn decrypt_aes128(key: &[u8], iv: &[u8], data: &[u8]) -> Vec<u8> {
    let mut encrypted_data = data.clone().to_owned();
    let cipher = Aes128Cbc::new_from_slices(&key, &iv).unwrap();
    cipher.decrypt(&mut encrypted_data).unwrap().to_vec()
}

#[test]
fn test_demo_decrypt() {
    let key = "something";
    let iv = "something";
    let data = "something";

    let key = base64::decode(key).unwrap();
    let iv = base64::decode(iv).unwrap();
    let data = base64::decode(data).unwrap();

    let result = decrypt_aes128(&key, &iv, &data);
    let _result = std::str::from_utf8(&result).unwrap().to_string();
}