Rust实现AES加解密详解
作者:Zhou T.x.
这篇文章主要为大家详细介绍了如何利用Rust语言实现AES加解密算法,文中的示例代码讲解详细,具有一定的借鉴价值,需要的可以了解一下
一、选择使用 rust-crypto
rust-crypto 官方相关站点
crates.io
https://crates.io/crates/rust-crypto
repository
https://github.com/DaGenix/rust-crypto
documentation (以0.2.36为例)
https://docs.rs/rust-crypto/0.2.36
二、Cargo.toml 文件
[dependencies] rust-crypto = "0.2.36"
三、工具类
说明:这里使用的是AES256/CBC/Pkcs加解密格式。
因此,key的长度为 256bits (32Bytes) iv的长度为128bits (16Bytes)
1、加密
/// Encrypt a buffer with the given key and iv using AES256/CBC/Pkcs encryption. fn aes256_cbc_encrypt( data: &[u8], key: &[u8; 32], iv: &[u8; 16], ) -> Result<Vec<u8>, SymmetricCipherError> { let mut encryptor = aes::cbc_encryptor( KeySize256, key, iv, PkcsPadding, ); let mut buffer = [0; 4096]; let mut write_buffer = RefWriteBuffer::new(&mut buffer); let mut read_buffer = RefReadBuffer::new(data); let mut final_result = Vec::new(); loop { let result = encryptor.encrypt(&mut read_buffer, &mut write_buffer, true)?; final_result.extend(write_buffer.take_read_buffer().take_remaining().iter().map(|&i| i)); match result { BufferUnderflow => break, _ => continue, } } Ok(final_result) }
2、解密
/// Decrypt a buffer with the given key and iv using AES256/CBC/Pkcs encryption. fn aes256_cbc_decrypt( data: &[u8], key: &[u8; 32], iv: &[u8; 16], ) -> Result<Vec<u8>, SymmetricCipherError> { let mut decryptor = aes::cbc_decryptor( KeySize256, key, iv, PkcsPadding, ); let mut buffer = [0; 4096]; let mut write_buffer = RefWriteBuffer::new(&mut buffer); let mut read_buffer = RefReadBuffer::new(data); let mut final_result = Vec::new(); loop { let result = decryptor.decrypt(&mut read_buffer, &mut write_buffer, true)?; final_result.extend(write_buffer.take_read_buffer().take_remaining().iter().map(|&i| i)); match result { BufferUnderflow => break, _ => continue, } } Ok(final_result) }
3、测试样例
3.1、生成随机key和iv
因为仅用作测试,所以才使用随机key和iv,应用场景注意使用固定值!
这里我们使用的crate是rand。
首先在Cargo.toml中引入:
[dependencies] rand = "0.8.4"
3.2、编写测试用例
#[test] fn test_aes256_cbc() { use rand::{RngCore, rngs::OsRng}; let mut rng = OsRng::default(); let mut key = [0; 32]; let mut iv = [0; 16]; rng.fill_bytes(&mut key); rng.fill_bytes(&mut iv); let data = "Hello, world!"; let encrypted_data = aes256_cbc_encrypt(data.as_bytes(), &key, &iv).unwrap(); let decrypted_data = aes256_cbc_decrypt(encrypted_data.as_slice(), &key, &iv).unwrap(); let result = str::from_utf8(decrypted_data.as_slice()).unwrap(); assert_eq!(data, result); println!("{}", result); }
最后,执行测试用例,测试成功!
到此这篇关于Rust实现AES加解密详解的文章就介绍到这了,更多相关Rust AES加解密内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!