ruck/src/crypto.rs

46 lines
1.4 KiB
Rust
Raw Normal View History

2022-08-30 03:33:50 +01:00
use crate::conf::NONCE_SIZE_IN_BYTES;
2022-02-12 17:18:24 +00:00
use aes_gcm::aead::{Aead, NewAead};
use aes_gcm::{Aes256Gcm, Key, Nonce}; // Or `Aes128Gcm`
2022-02-10 19:52:28 +00:00
use anyhow::{anyhow, Result};
2022-08-30 14:53:16 +01:00
use bytes::{Bytes, BytesMut};
2022-08-30 02:21:48 +01:00
2022-02-12 17:18:24 +00:00
use rand::{thread_rng, Rng};
2022-02-10 19:52:28 +00:00
2022-08-30 03:33:50 +01:00
pub struct Crypt {
cipher: Aes256Gcm,
2022-02-12 17:18:24 +00:00
}
2022-08-30 03:33:50 +01:00
impl Crypt {
pub fn new(key: &Vec<u8>) -> Crypt {
let key = Key::from_slice(&key[..]);
Crypt {
cipher: Aes256Gcm::new(key),
}
}
2022-08-30 14:53:16 +01:00
pub fn encrypt(&self, plaintext: Bytes) -> Result<Bytes> {
2022-08-30 03:33:50 +01:00
let mut arr = [0u8; NONCE_SIZE_IN_BYTES];
thread_rng().try_fill(&mut arr[..])?;
let nonce = Nonce::from_slice(&arr);
2022-08-30 14:53:16 +01:00
match self.cipher.encrypt(nonce, plaintext.as_ref()) {
Ok(body) => {
let mut buffer = BytesMut::with_capacity(NONCE_SIZE_IN_BYTES + body.len());
buffer.extend_from_slice(nonce);
buffer.extend_from_slice(&body);
Ok(buffer.freeze())
}
Err(e) => Err(anyhow!(e.to_string())),
2022-08-30 03:33:50 +01:00
}
2022-02-12 17:18:24 +00:00
}
2022-08-30 14:53:16 +01:00
pub fn decrypt(&self, body: Bytes) -> Result<Bytes> {
let mut body = body;
let nonce_bytes = body.split_to(NONCE_SIZE_IN_BYTES);
let nonce = Nonce::from_slice(&nonce_bytes);
match self.cipher.decrypt(nonce, body.as_ref()) {
2022-08-30 03:33:50 +01:00
Ok(payload) => Ok(Bytes::from(payload)),
2022-08-30 14:53:16 +01:00
Err(e) => Err(anyhow!(e.to_string())),
2022-08-30 03:33:50 +01:00
}
2022-02-12 17:18:24 +00:00
}
}