rust/confidential: Add From and Into for confidential byes arrays/vectors

Implement `TryFrom<Confidential<Vec<u8>> for Confidential<[u8; N]>` and
`From<Confidential<[u8; N]> for Confidential<Vec<u8>>`.
Reviewed-by: Steffen Eiden <seiden@linux.ibm.com>
Signed-off-by: Marc Hartmayer <mhartmay@linux.ibm.com>
Signed-off-by: Steffen Eiden <seiden@linux.ibm.com>
This commit is contained in:
Marc Hartmayer
2024-10-14 19:18:22 +00:00
committed by Steffen Eiden
parent e480c4738d
commit 7608cf2de4
2 changed files with 50 additions and 0 deletions

View File

@@ -4,6 +4,8 @@
use std::fmt::Debug;
use crate::Error;
/// Trait for securely zeroizing memory.
///
/// To be used with [`Confidential`]
@@ -170,6 +172,27 @@ impl<C: Zeroize> Drop for Confidential<C> {
}
}
impl<const N: usize> TryFrom<Confidential<Vec<u8>>> for Confidential<[u8; N]> {
type Error = Error;
fn try_from(value: Confidential<Vec<u8>>) -> Result<Self, Self::Error> {
let len = value.0.len();
if len == N {
Ok(Self::new(
TryInto::<[u8; N]>::try_into(value.0.clone()).unwrap(),
))
} else {
Err(Error::LengthMismatch(len, N))
}
}
}
impl<const N: usize> From<Confidential<[u8; N]>> for Confidential<Vec<u8>> {
fn from(value: Confidential<[u8; N]>) -> Self {
Self::new(value.0.to_vec())
}
}
#[cfg(test)]
mod test {
use super::*;
@@ -221,4 +244,28 @@ mod test {
conf.zeroize();
assert_eq!(&[0; 4], conf.value().as_bytes());
}
#[test]
fn try_from_conf_vec_into_conf_array() {
let _: Confidential<[u8; 0]> = Confidential::new(vec![])
.try_into()
.expect("should not fail");
let data = vec![0x12u8; 100];
let arr: Confidential<[u8; 100]> = Confidential::new(data.clone())
.try_into()
.expect("should not fail");
assert_eq!(arr.value(), data.as_slice());
let result: Result<Confidential<[u8; 101]>, Error> =
Confidential::new(data.clone()).try_into();
assert!(matches!(result, Err(Error::LengthMismatch(100, 101))));
}
#[test]
fn try_from_conf_array_into_conf_vec() {
let _: Confidential<Vec<u8>> = Confidential::new([]).into();
let data = [0x12u8; 100];
let vec: Confidential<Vec<u8>> = Confidential::new(data).into();
assert_eq!(vec.value(), data.as_slice());
}
}

View File

@@ -74,6 +74,9 @@ pub enum Error {
#[error("Cannot decode hex string")]
InvHexStringChar { source: std::num::ParseIntError },
#[error("Expected size {0}, found {1}")]
LengthMismatch(usize, usize),
}
/// Error cases for I/O operations