这是一个创建于 100 天前的主题,其中的信息可能已经有所发展或是发生改变。
```rust
use aes_gcm::{aead::{Aead, AeadCore, KeyInit, OsRng}, Aes256Gcm, AesGcm};
use aes_gcm::aead::consts::U12;
use aes_gcm::aead::Nonce;
use aes_gcm::aes::Aes256;
// aes-gcm = "0.10.3"
#[test]
fn test_3_aes256_cbc() {
// 生成一个随机的 AES256-GCM 加密密钥 key 。
// The encryption key can be generated randomly:
let key = Aes256Gcm::generate_key(OsRng);
// 使用生成的密钥 key 创建 AES256-GCM 加密器 cipher ,然后生成一个 96 位长度的随机 nonce nonce 。
// 使用 cipher 对 "plaintext message" 进行加密得到 ciphertext ,然后再对 ciphertext 进行解密得到 plaintext 。
// 最后使用 assert_eq! 宏来验证解密后的 plaintext 是否与原始消息相同。
let cipher: AesGcm<Aes256, U12> = Aes256Gcm::new(&key);
// 生成随机 nonce ( 96 bits )
// let nonce = GenericArray::from_slice(&Aes256Gcm::generate_nonce(&mut OsRng));
// let nonce: &GenericArray<u8, <Aes256Gcm as Aead>::NonceSize> = GenericArray::from_slice(&Aes256Gcm::generate_nonce(&mut OsRng));
// let nonce: GenericArray<u8, <Aes256Gcm as Aead>::NonceSize> = ...;
let nonce: Nonce<Aes256Gcm> = Aes256Gcm::generate_nonce(&mut OsRng); // 96-bits; unique per message
// 将明文消息作为字节数组传递给 encrypt 函数。
let plaintext: &[u8] = b"plaintext message";
let ciphertext = cipher.encrypt(&nonce, plaintext).unwrap();
let plaintext = cipher.decrypt(&nonce, ciphertext.as_ref()).unwrap();
assert_eq!(&plaintext, b"plaintext message");
}
```
let plaintext: &[u8] = b"plaintext message";
这一行代码,要自己将手动推导的 &[u8;17] 固定长度数组,,修改为可变数组。。
以及一些其他的,,整个代码才可以运行
5 条回复 • 2024-07-30 11:43:45 +08:00
|
|
1
chainal7777 100 天前
1 ,用点 use as 2 ,用点 type A=a 3 ,只写关键注释
|
|
|
3
cppc 100 天前 via iPhone
为了安全是这样啦,我还见过编译时 SQL 检查呢,SQL 写错代码都不能编译
|
|
|
4
PTLin 99 天前
不是 rust 复杂,这个是库复杂,用了太多泛型了
|
|
|
5
whoami9894 80 天前
有没有可能,不用写那么多类型标注
另外,函数当然不可能接收 [u8; const N] 参数,难道你能在编译期知道数据长度?
``` let key = Aes256Gcm::generate_key(OsRng); let cipher = Aes256Gcm::new(&key); let nonce = Aes256Gcm::generate_nonce(OsRng);
let plaintext = b"plaintext message"; let ciphertext = cipher.encrypt(&nonce, plaintext.as_slice()).unwrap(); let plaintext = cipher.decrypt(&nonce, ciphertext.as_slice()).unwrap();
assert_eq!(&plaintext, b"plaintext message"); ```
|