Use a custom result type

This commit is contained in:
Rodolphe Bréard 2024-02-17 20:47:07 +01:00
parent 4ddc0413ec
commit 9df9fa6bf5
3 changed files with 19 additions and 17 deletions

View file

@ -1,10 +1,11 @@
use crate::canonicalization::{canonicalize, join_canonicalized_str}; use crate::canonicalization::{canonicalize, join_canonicalized_str};
use crate::error::Result;
use crate::kdf::derive_key; use crate::kdf::derive_key;
use crate::{storage, Error, InputKeyMaterialList}; use crate::{storage, InputKeyMaterialList};
use chacha20poly1305::aead::{Aead, KeyInit, Payload}; use chacha20poly1305::aead::{Aead, KeyInit, Payload};
use chacha20poly1305::{Key, XChaCha20Poly1305, XNonce}; use chacha20poly1305::{Key, XChaCha20Poly1305, XNonce};
pub(crate) type EncryptionFunction = dyn Fn(&[u8], &[u8], &str) -> Result<EncryptedData, Error>; pub(crate) type EncryptionFunction = dyn Fn(&[u8], &[u8], &str) -> Result<EncryptedData>;
pub(crate) struct EncryptedData { pub(crate) struct EncryptedData {
pub(crate) nonce: Vec<u8>, pub(crate) nonce: Vec<u8>,
@ -16,7 +17,7 @@ pub fn encrypt(
key_context: &[&str], key_context: &[&str],
data: impl AsRef<[u8]>, data: impl AsRef<[u8]>,
data_context: &[impl AsRef<[u8]>], data_context: &[impl AsRef<[u8]>],
) -> Result<String, Error> { ) -> Result<String> {
// Derive the key // Derive the key
let ikm = ikml.get_latest_ikm()?; let ikm = ikml.get_latest_ikm()?;
let key = derive_key(ikm, key_context); let key = derive_key(ikm, key_context);
@ -38,7 +39,7 @@ pub(crate) fn xchacha20poly1305_encrypt(
key: &[u8], key: &[u8],
data: &[u8], data: &[u8],
aad: &str, aad: &str,
) -> Result<EncryptedData, Error> { ) -> Result<EncryptedData> {
// Adapt the key // Adapt the key
let key = Key::from_slice(key); let key = Key::from_slice(key);
@ -69,7 +70,7 @@ pub fn decrypt(
key_context: &[&str], key_context: &[&str],
data: impl AsRef<[u8]>, data: impl AsRef<[u8]>,
data_context: &[impl AsRef<[u8]>], data_context: &[impl AsRef<[u8]>],
) -> Result<Vec<u8>, Error> { ) -> Result<Vec<u8>> {
unimplemented!("decrypt"); unimplemented!("decrypt");
} }

View file

@ -1,6 +1,6 @@
use thiserror::Error; pub(crate) type Result<T, E = Error> = core::result::Result<T, E>;
#[derive(Error, Debug)] #[derive(thiserror::Error, Debug)]
pub enum Error { pub enum Error {
#[error("cipher error: {0}")] #[error("cipher error: {0}")]
ChaCha20Poly1305Error(chacha20poly1305::Error), ChaCha20Poly1305Error(chacha20poly1305::Error),

View file

@ -1,4 +1,5 @@
use crate::{Error, Scheme}; use crate::error::{Error, Result};
use crate::Scheme;
use base64ct::{Base64UrlUnpadded, Encoding}; use base64ct::{Base64UrlUnpadded, Encoding};
use std::time::{Duration, SystemTime}; use std::time::{Duration, SystemTime};
@ -17,7 +18,7 @@ pub(crate) struct InputKeyMaterial {
impl InputKeyMaterial { impl InputKeyMaterial {
#[cfg(feature = "ikm-management")] #[cfg(feature = "ikm-management")]
fn as_bytes(&self) -> Result<[u8; IKM_STRUCT_SIZE], Error> { fn as_bytes(&self) -> Result<[u8; IKM_STRUCT_SIZE]> {
let mut res = Vec::with_capacity(IKM_STRUCT_SIZE); let mut res = Vec::with_capacity(IKM_STRUCT_SIZE);
res.extend_from_slice(&self.id.to_le_bytes()); res.extend_from_slice(&self.id.to_le_bytes());
res.extend_from_slice(&(self.scheme as u32).to_le_bytes()); res.extend_from_slice(&(self.scheme as u32).to_le_bytes());
@ -40,7 +41,7 @@ impl InputKeyMaterial {
Ok(res.try_into().unwrap()) Ok(res.try_into().unwrap())
} }
pub(crate) fn from_bytes(b: [u8; IKM_STRUCT_SIZE]) -> Result<Self, Error> { pub(crate) fn from_bytes(b: [u8; IKM_STRUCT_SIZE]) -> Result<Self> {
Ok(Self { Ok(Self {
id: u32::from_le_bytes(b[0..4].try_into().unwrap()), id: u32::from_le_bytes(b[0..4].try_into().unwrap()),
scheme: u32::from_le_bytes(b[4..8].try_into().unwrap()).try_into()?, scheme: u32::from_le_bytes(b[4..8].try_into().unwrap()).try_into()?,
@ -51,7 +52,7 @@ impl InputKeyMaterial {
}) })
} }
fn bytes_to_system_time(ts_slice: &[u8]) -> Result<SystemTime, Error> { fn bytes_to_system_time(ts_slice: &[u8]) -> Result<SystemTime> {
let ts_array: [u8; 8] = ts_slice.try_into().unwrap(); let ts_array: [u8; 8] = ts_slice.try_into().unwrap();
let ts = u64::from_le_bytes(ts_array); let ts = u64::from_le_bytes(ts_array);
SystemTime::UNIX_EPOCH SystemTime::UNIX_EPOCH
@ -73,12 +74,12 @@ impl InputKeyMaterialList {
} }
#[cfg(feature = "ikm-management")] #[cfg(feature = "ikm-management")]
pub fn add_ikm(&mut self) -> Result<(), Error> { pub fn add_ikm(&mut self) -> Result<()> {
self.add_ikm_with_duration(Duration::from_secs(crate::DEFAULT_IKM_DURATION)) self.add_ikm_with_duration(Duration::from_secs(crate::DEFAULT_IKM_DURATION))
} }
#[cfg(feature = "ikm-management")] #[cfg(feature = "ikm-management")]
pub fn add_ikm_with_duration(&mut self, duration: Duration) -> Result<(), Error> { pub fn add_ikm_with_duration(&mut self, duration: Duration) -> Result<()> {
let mut content: [u8; 32] = [0; 32]; let mut content: [u8; 32] = [0; 32];
getrandom::getrandom(&mut content)?; getrandom::getrandom(&mut content)?;
let created_at = SystemTime::now(); let created_at = SystemTime::now();
@ -95,7 +96,7 @@ impl InputKeyMaterialList {
} }
#[cfg(feature = "ikm-management")] #[cfg(feature = "ikm-management")]
pub fn export(&self) -> Result<String, Error> { pub fn export(&self) -> Result<String> {
let data_size = (self.ikm_lst.len() * IKM_STRUCT_SIZE) + 4; let data_size = (self.ikm_lst.len() * IKM_STRUCT_SIZE) + 4;
let mut data = Vec::with_capacity(data_size); let mut data = Vec::with_capacity(data_size);
data.extend_from_slice(&self.id_counter.to_le_bytes()); data.extend_from_slice(&self.id_counter.to_le_bytes());
@ -105,7 +106,7 @@ impl InputKeyMaterialList {
Ok(Base64UrlUnpadded::encode_string(&data)) Ok(Base64UrlUnpadded::encode_string(&data))
} }
pub fn import(s: &str) -> Result<Self, Error> { pub fn import(s: &str) -> Result<Self> {
let data = Base64UrlUnpadded::decode_vec(s)?; let data = Base64UrlUnpadded::decode_vec(s)?;
if data.len() % IKM_STRUCT_SIZE != 4 { if data.len() % IKM_STRUCT_SIZE != 4 {
return Err(Error::ParsingInvalidLength(data.len())); return Err(Error::ParsingInvalidLength(data.len()));
@ -121,7 +122,7 @@ impl InputKeyMaterialList {
} }
#[cfg(feature = "encryption")] #[cfg(feature = "encryption")]
pub(crate) fn get_latest_ikm(&self) -> Result<&InputKeyMaterial, Error> { pub(crate) fn get_latest_ikm(&self) -> Result<&InputKeyMaterial> {
self.ikm_lst self.ikm_lst
.iter() .iter()
.rev() .rev()
@ -130,7 +131,7 @@ impl InputKeyMaterialList {
} }
#[cfg(feature = "encryption")] #[cfg(feature = "encryption")]
pub(crate) fn get_ikm_by_id(&self, id: u32) -> Result<&InputKeyMaterial, Error> { pub(crate) fn get_ikm_by_id(&self, id: u32) -> Result<&InputKeyMaterial> {
self.ikm_lst self.ikm_lst
.iter() .iter()
.find(|&ikm| ikm.id == id) .find(|&ikm| ikm.id == id)