Skip to content

Commit b68759d

Browse files
committed
Add storable_builder helper
1 parent b1a0ecc commit b68759d

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,5 +19,8 @@ pub mod error;
1919
/// Contains request/response types generated from the API definition of VSS.
2020
pub mod types;
2121

22+
/// Contains helper utils for encryption, requests-retries etc.
23+
pub mod util;
24+
2225
// Encryption-Decryption related crate-only helpers.
2326
pub(crate) mod crypto;

src/util/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pub mod storable_builder;

src/util/storable_builder.rs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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

Comments
 (0)