AES 加密算法
AES(Advanced Encryption Standard),全称:高级加密标准,是一种最常见的对称加密算法
配置 Rust Toml 文件
1
2
|
[dependencies]
openssl = { version = "0.10", features = ["vendored"] }
|
示例代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
use openssl::symm::{Cipher, Crypter, Mode};
fn main() {
let key = "061cecfd897548208c76c04b6e7fb".as_bytes();
let crypto_word: &mut Vec<u8> = &mut "keyword".as_bytes().to_vec();
let block_size = Cipher::aes_128_cbc().block_size();
// 添加填充
pkcs7_padding(crypto_word, block_size);
let mut output = vec![0; 1024];
// 取16位密钥
let mut encrypter = Crypter::new(Cipher::aes_128_ecb(), Mode::Encrypt, &key[..16], None).unwrap();
match encrypter.update(&f, &mut output) {
Ok(size) => {
eprintln!("size is: {size}");
println!("{:?}", &output[..size]);
println!("{:02x?}", &output[..size]); // 转换为16进制
}
Err(_) => {}
};
}
fn pkcs7_padding(data: &mut Vec<u8>, block_size: usize) {
let padding_num = block_size - data.len() % block_size;
let padding = padding_num as u8;
data.append(&mut [padding].repeat(padding_num));
}
|
参考链接: