|
| 1 | +use crate::crypto::chacha20poly1305::ChaCha20Poly1305; |
| 2 | +use crate::types::{EncryptionMetadata, PlaintextBlob, Storable}; |
| 3 | +use ::prost::Message; |
| 4 | +use bytes::Bytes; |
| 5 | +use rand::rngs::ThreadRng; |
| 6 | +use rand::RngCore; |
| 7 | +use std::borrow::Borrow; |
| 8 | +use std::io; |
| 9 | +use std::io::{Error, ErrorKind}; |
| 10 | + |
| 11 | +pub struct StorableBuilder { |
| 12 | + data_encryption_key: Bytes, |
| 13 | +} |
| 14 | + |
| 15 | +const CHACHA20_CIPHER_NAME: &'static str = "ChaCha20Poly1305"; |
| 16 | + |
| 17 | +impl StorableBuilder { |
| 18 | + pub fn build(&mut self, input: Vec<u8>, version: i64) -> Storable { |
| 19 | + let mut rng = ThreadRng::default(); |
| 20 | + let mut nonce = [0u8; 96]; |
| 21 | + rng.fill_bytes(&mut nonce); |
| 22 | + |
| 23 | + let mut data_blob = PlaintextBlob { value: input, version }.encode_to_vec(); |
| 24 | + |
| 25 | + let mut cipher = ChaCha20Poly1305::new(&self.data_encryption_key, &nonce, &vec![]); |
| 26 | + let mut tag = [0u8; 16]; |
| 27 | + cipher.encrypt_inplace(&mut data_blob, &mut tag); |
| 28 | + Storable { |
| 29 | + data: data_blob, |
| 30 | + encryption_metadata: Option::from(EncryptionMetadata { |
| 31 | + nonce: nonce.to_vec(), |
| 32 | + tag: tag.to_vec(), |
| 33 | + cipher_format: CHACHA20_CIPHER_NAME.to_string(), |
| 34 | + }), |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + pub fn deconstruct(&mut self, mut storable: Storable) -> io::Result<(Vec<u8>, i64)> { |
| 39 | + let encryption_metadata = storable.encryption_metadata.unwrap(); |
| 40 | + let mut cipher = ChaCha20Poly1305::new(&self.data_encryption_key, &encryption_metadata.nonce, &vec![]); |
| 41 | + let input_output = &mut storable.data; |
| 42 | + |
| 43 | + if cipher.decrypt_inplace(input_output, encryption_metadata.tag.borrow()) { |
| 44 | + let data_blob = |
| 45 | + PlaintextBlob::decode(&**input_output).map_err(|e| Error::new(ErrorKind::InvalidData, e))?; |
| 46 | + Ok((data_blob.value, data_blob.version)) |
| 47 | + } else { |
| 48 | + Err(Error::new(ErrorKind::InvalidData, "Invalid Tag")) |
| 49 | + } |
| 50 | + } |
| 51 | +} |
0 commit comments