如何在 Rust 的 `aes` crate 中设置初始化向量 (IV)? (AES-128 CBC)

问题描述

正如标题所暗示的那样。我可以创建一个新的 Aes128 密码,但我已经检查了文档并没有发现任何可以让我提供 IV 的内容。我是否遗漏了一些明显的东西?

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

解决方法

您可以使用板条箱 aesblock_modes

像这样,但是这个测试会恐慌,因为我使用了 unwrap() 并且没有设置有效的 'key','iv' 和 '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();
}