extern crate generic_array;
extern crate rand;
use aes_gcm::Aes256Gcm;
use aes_gcm::aead::{Aead, generic_array::GenericArray};
use rand::Rng;
use generic_array::typenum::{U12, U32};
// 生成随机的256位密钥
fn generate_aes_key() -> GenericArray {
let mut key = [0u8; 32];
rand::thread_rng().fill(&mut key);
GenericArray::clone_from_slice(&key)
}
// 生成随机的96位 nonce
fn generate_nonce() -> GenericArray {
let mut nonce = [0u8; 12];
rand::thread_rng().fill(&mut nonce);
GenericArray::clone_from_slice(&nonce)
}
// AES GCM加密函数
fn aes_gcm_encrypt(key: GenericArray, nonce: GenericArray, plaintext: &[u8]) -> Vec {
let cipher = Aes256Gcm::from(&key);
let ciphertext = cipher
.encrypt(&nonce, plaintext.into())
.expect("Encryption failure!");
ciphertext
}
// AES GCM解密函数
fn aes_gcm_decrypt(
key: GenericArray,
nonce: GenericArray,
ciphertext: &[u8],
) -> Option {
let cipher = Aes256Gcm::from(&key);
let decrypted_data = cipher.decrypt(&nonce, ciphertext.into()).ok()?;
Some(decrypted_data)
}
fn main() {
let key = generate_aes_key();
let nonce = generate_nonce();
let plaintext = b"Hello, AES GCM encryption and decryption!";
let ciphertext = aes_gcm_encrypt(key.clone(), nonce.clone(), plaintext);
println!("Ciphertext: {:?}", ciphertext);
let decrypted_data = aes_gcm_decrypt(key, nonce, &ciphertext);
match decrypted_data {
Some(data) => {
let decrypted_text = String::from_utf8_lossy(&data);
println!("Decrypted Text: {}", decrypted_text);
}
None => {
println!("Decryption failed.");
}
}
}[/ol]复制代码
给出的代码:来回循环否定自己的代码。比如:一会说A对了,B错了。当我贴出报错代码后,它又说B对了,A错误了,然后我继续贴出报错代码,它又说对不起,A对了,B错误了。来回循环往复。使用gpt4和gpt3.5都是这样。