45 lines
1.2 KiB
Rust
45 lines
1.2 KiB
Rust
use crypto::Error;
|
|
use crypto::ciphers::{
|
|
aes_gcm::Aes256Gcm,
|
|
traits::Aead,
|
|
};
|
|
use crypto::utils::rand;
|
|
|
|
const NONCE: [u8; 12] = [0xd0, 0xc3, 0x75, 0x56, 0x58, 0xc1, 0x7e, 0x5f, 0xd6, 0xcc, 0xb6, 0x76];
|
|
|
|
pub fn encrypt(key: &[u8; 32], plaintext: &[u8]) -> Vec<u8> {
|
|
let mut result = vec![0; plaintext.len() + 16];
|
|
let (cyphertext, tag) = result.split_at_mut(plaintext.len());
|
|
Aes256Gcm::try_encrypt(
|
|
key,
|
|
&NONCE,
|
|
&[],
|
|
plaintext,
|
|
cyphertext,
|
|
tag).expect("Unexpected cryptography error");
|
|
result
|
|
}
|
|
|
|
pub fn decrypt<'p>(key: &[u8; 32], encrypted: &[u8], plaintext_dest: &'p mut Vec<u8>) -> Option<&'p mut Vec<u8>> {
|
|
let (cyphertext, tag) = encrypted.split_at(encrypted.len() - 16);
|
|
plaintext_dest.resize(cyphertext.len(), 0);
|
|
let e = Aes256Gcm::try_decrypt(
|
|
key,
|
|
&NONCE,
|
|
&[],
|
|
plaintext_dest,
|
|
cyphertext,
|
|
tag);
|
|
match e {
|
|
Ok(_) => Some(plaintext_dest),
|
|
Err(Error::CipherError { alg: "AES-256-GCM" }) => None, // Invalid key or tag
|
|
Err(e) => panic!("Unexpected decryption return value: {e:?}"),
|
|
}
|
|
}
|
|
|
|
pub fn make_key() -> [u8; 32] {
|
|
let mut result = [0; 32];
|
|
rand::fill(&mut result).expect("Unexpected error generating random data");
|
|
result
|
|
}
|