Skip to content

Commit

Permalink
fixup! Add wrapper for Key that implements zeroize
Browse files Browse the repository at this point in the history
  • Loading branch information
threema-donat committed Feb 6, 2024
1 parent 7b1ae3b commit 95d372b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
14 changes: 13 additions & 1 deletion src/crypto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use crypto_secretbox::{
};
use data_encoding::{HEXLOWER, HEXLOWER_PERMISSIVE};
use rand::Rng;
use serde::{Serialize, Serializer};
use serde_json as json;
use zeroize::{Zeroize, ZeroizeOnDrop};

Expand All @@ -23,6 +24,7 @@ use crate::{
pub const NONCE_SIZE: usize = 24;
const KEY_SIZE: usize = 32;

/// Key type used for nacl secretbox cryptography
#[derive(PartialEq, Zeroize, ZeroizeOnDrop)]
pub struct Key(SecretboxKey);

Expand Down Expand Up @@ -56,13 +58,23 @@ impl TryFrom<Vec<u8>> for Key {
fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
<[u8; KEY_SIZE]>::try_from(value)
.map_err(|original| {
CryptoError::BadKey(format!("Key has wrong size: {}", original.len()))
CryptoError::BadKey(format!(
"Key has wrong size: {} instead of {}",
original.len(),
KEY_SIZE
))
})
.map(SecretboxKey::from)
.map(Self::from)
}
}

impl Serialize for Key {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&HEXLOWER.encode(&self.0))
}
}

fn get_file_nonce() -> &'static Nonce {
static FILE_NONCE: OnceLock<Nonce> = OnceLock::new();
FILE_NONCE.get_or_init(|| {
Expand Down
5 changes: 0 additions & 5 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@ pub struct FileMessage {
thumbnail_media_type: Option<String>,

#[serde(rename = "k")]
#[serde(serialize_with = "key_to_hex")]
blob_encryption_key: Key,

#[serde(rename = "n")]
Expand Down Expand Up @@ -392,10 +391,6 @@ impl Serialize for BlobId {
}
}

fn key_to_hex<S: Serializer>(val: &Key, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&HEXLOWER.encode(&val.as_ref()[..]))
}

#[cfg(test)]
mod test {
use std::collections::HashMap;
Expand Down

0 comments on commit 95d372b

Please sign in to comment.