aboutsummaryrefslogtreecommitdiff
path: root/src/cryptoblob.rs
diff options
context:
space:
mode:
authorAlex Auvolat <alex@adnab.me>2022-05-18 12:24:37 +0200
committerAlex Auvolat <alex@adnab.me>2022-05-18 12:26:50 +0200
commit7a3ce9f81963cc374271272bfe4e0e204e9b7012 (patch)
tree369a1c390d5aeb5f3ce2515b677affca366cc328 /src/cryptoblob.rs
downloadaerogramme-7a3ce9f81963cc374271272bfe4e0e204e9b7012.tar.gz
aerogramme-7a3ce9f81963cc374271272bfe4e0e204e9b7012.zip
Skeleton for some stuff
Diffstat (limited to 'src/cryptoblob.rs')
-rw-r--r--src/cryptoblob.rs58
1 files changed, 58 insertions, 0 deletions
diff --git a/src/cryptoblob.rs b/src/cryptoblob.rs
new file mode 100644
index 0000000..6e51dbb
--- /dev/null
+++ b/src/cryptoblob.rs
@@ -0,0 +1,58 @@
+//! Helper functions for secret-key encrypted blobs
+//! that contain Zstd encrypted data
+
+use anyhow::{anyhow, Result};
+use serde::{Deserialize, Serialize};
+use zstd::stream::{decode_all as zstd_decode, encode_all as zstd_encode};
+
+use sodiumoxide::crypto::secretbox::xsalsa20poly1305::{self, gen_nonce, Nonce, NONCEBYTES};
+pub use sodiumoxide::crypto::secretbox::xsalsa20poly1305::{gen_key, Key, KEYBYTES};
+
+pub fn open(cryptoblob: &[u8], key: &Key) -> Result<Vec<u8>> {
+ if cryptoblob.len() < NONCEBYTES {
+ return Err(anyhow!("Cyphertext too short"));
+ }
+
+ // Decrypt -> get Zstd data
+ let nonce = Nonce::from_slice(&cryptoblob[..NONCEBYTES]).unwrap();
+ let zstdblob = xsalsa20poly1305::open(&cryptoblob[NONCEBYTES..], &nonce, key)
+ .map_err(|_| anyhow!("Could not decrypt blob"))?;
+
+ // Decompress zstd data
+ let mut reader = &zstdblob[..];
+ let data = zstd_decode(&mut reader)?;
+
+ Ok(data)
+}
+
+pub fn seal(plainblob: &[u8], key: &Key) -> Result<Vec<u8>> {
+ // Compress data using zstd
+ let mut reader = &plainblob[..];
+ let zstdblob = zstd_encode(&mut reader, 0)?;
+
+ // Encrypt
+ let nonce = gen_nonce();
+ let cryptoblob = xsalsa20poly1305::seal(&zstdblob, &nonce, key);
+
+ let mut res = Vec::with_capacity(NONCEBYTES + cryptoblob.len());
+ res.extend(nonce.as_ref());
+ res.extend(cryptoblob);
+
+ Ok(res)
+}
+
+pub fn open_deserialize<T: for<'de> Deserialize<'de>>(cryptoblob: &[u8], key: &Key) -> Result<T> {
+ let blob = open(cryptoblob, key)?;
+
+ Ok(rmp_serde::decode::from_read_ref::<_, T>(&blob)?)
+}
+
+pub fn seal_serialize<T: Serialize>(obj: T, key: &Key) -> Result<Vec<u8>> {
+ let mut wr = Vec::with_capacity(128);
+ let mut se = rmp_serde::Serializer::new(&mut wr)
+ .with_struct_map()
+ .with_string_variants();
+ obj.serialize(&mut se)?;
+
+ Ok(seal(&wr, key)?)
+}