ruck/src/crypto.rs

44 lines
1.3 KiB
Rust
Raw Normal View History

2022-08-30 03:33:50 +01:00
use crate::conf::NONCE_SIZE_IN_BYTES;
2022-08-29 19:01:56 +01:00
use crate::message::EncryptedPayload;
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 02:21:48 +01:00
use bytes::Bytes;
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),
}
}
pub fn encrypt(&self, body: &Vec<u8>) -> Result<EncryptedPayload> {
let mut arr = [0u8; NONCE_SIZE_IN_BYTES];
thread_rng().try_fill(&mut arr[..])?;
let nonce = Nonce::from_slice(&arr);
let plaintext = body.as_ref();
match self.cipher.encrypt(nonce, plaintext) {
Ok(body) => Ok(EncryptedPayload {
nonce: arr.to_vec(),
body,
}),
Err(_) => Err(anyhow!("Encryption error")),
}
2022-02-12 17:18:24 +00:00
}
2022-08-30 03:33:50 +01:00
pub fn decrypt(&self, payload: &EncryptedPayload) -> Result<Bytes> {
let nonce = Nonce::from_slice(payload.nonce.as_ref());
match self.cipher.decrypt(nonce, payload.body.as_ref()) {
Ok(payload) => Ok(Bytes::from(payload)),
Err(_) => Err(anyhow!("Decryption error")),
}
2022-02-12 17:18:24 +00:00
}
}