diff --git a/pubky-common/src/crypto.rs b/pubky-common/src/crypto.rs index a7adea5..6f09a33 100644 --- a/pubky-common/src/crypto.rs +++ b/pubky-common/src/crypto.rs @@ -30,7 +30,7 @@ pub fn random_bytes() -> [u8; N] { arr } -pub fn encrypt(plain_text: &[u8], encryption_key: &[u8; 32]) -> Result, Error> { +pub fn encrypt(plain_text: &[u8], encryption_key: &[u8; 32]) -> Result, EncryptError> { let cipher = XSalsa20Poly1305::new(encryption_key.into()); let nonce = XSalsa20Poly1305::generate_nonce(&mut OsRng); // unique per message let ciphertext = cipher.encrypt(&nonce, plain_text)?; @@ -42,18 +42,31 @@ pub fn encrypt(plain_text: &[u8], encryption_key: &[u8; 32]) -> Result, Ok(out) } -pub fn decrypt(bytes: &[u8], encryption_key: &[u8; 32]) -> Result, Error> { +pub fn decrypt(bytes: &[u8], encryption_key: &[u8; 32]) -> Result, DecryptError> { let cipher = XSalsa20Poly1305::new(encryption_key.into()); + if bytes.len() < 24 { + return Err(DecryptError::PayloadTooSmall(bytes.len())); + } + Ok(cipher.decrypt(bytes[..24].into(), &bytes[24..])?) } #[derive(thiserror::Error, Debug)] -pub enum Error { +pub enum EncryptError { #[error(transparent)] SecretBox(#[from] crypto_secretbox::Error), } +#[derive(thiserror::Error, Debug)] +pub enum DecryptError { + #[error(transparent)] + SecretBox(#[from] crypto_secretbox::Error), + + #[error("Encrypted message too small, expected at least 24 bytes nonce, receieved {0} bytes")] + PayloadTooSmall(usize), +} + #[cfg(test)] mod tests { use super::*; diff --git a/pubky-common/src/recovery_file.rs b/pubky-common/src/recovery_file.rs index 0a2f9b4..088dac9 100644 --- a/pubky-common/src/recovery_file.rs +++ b/pubky-common/src/recovery_file.rs @@ -82,7 +82,10 @@ pub enum Error { Argon(#[from] argon2::Error), #[error(transparent)] - Crypto(#[from] crate::crypto::Error), + DecryptError(#[from] crate::crypto::DecryptError), + + #[error(transparent)] + EncryptError(#[from] crate::crypto::EncryptError), } #[cfg(test)]