Skip to content

Commit

Permalink
crypto-common: leverage TryFrom impl on hybrid_array::Array
Browse files Browse the repository at this point in the history
  • Loading branch information
tarcieri committed May 31, 2023
1 parent 931db86 commit 00544a8
Showing 1 changed file with 8 additions and 20 deletions.
28 changes: 8 additions & 20 deletions crypto-common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,11 +151,9 @@ pub trait KeyInit: KeySizeUser + Sized {
/// Create new value from variable size key.
#[inline]
fn new_from_slice(key: &[u8]) -> Result<Self, InvalidLength> {
if key.len() != Self::KeySize::to_usize() {
Err(InvalidLength)
} else {
Ok(Self::new(Key::<Self>::ref_from_slice(key)))
}
<&Key<Self>>::try_from(key)
.map(Self::new)
.map_err(|_| InvalidLength)
}

/// Generate random key using the provided [`CryptoRng`].
Expand All @@ -177,16 +175,9 @@ pub trait KeyIvInit: KeySizeUser + IvSizeUser + Sized {
/// Create new value from variable length key and nonce.
#[inline]
fn new_from_slices(key: &[u8], iv: &[u8]) -> Result<Self, InvalidLength> {
let key_len = Self::KeySize::USIZE;
let iv_len = Self::IvSize::USIZE;
if key.len() != key_len || iv.len() != iv_len {
Err(InvalidLength)
} else {
Ok(Self::new(
Key::<Self>::ref_from_slice(key),
Iv::<Self>::ref_from_slice(iv),
))
}
let key = <&Key<Self>>::try_from(key).map_err(|_| InvalidLength)?;
let iv = <&Iv<Self>>::try_from(iv).map_err(|_| InvalidLength)?;
Ok(Self::new(key, iv))
}

/// Generate random key using the provided [`CryptoRng`].
Expand Down Expand Up @@ -237,11 +228,8 @@ pub trait InnerIvInit: InnerUser + IvSizeUser + Sized {
/// Initialize value using `inner` and `iv` slice.
#[inline]
fn inner_iv_slice_init(inner: Self::Inner, iv: &[u8]) -> Result<Self, InvalidLength> {
if iv.len() != Self::IvSize::to_usize() {
Err(InvalidLength)
} else {
Ok(Self::inner_iv_init(inner, Iv::<Self>::ref_from_slice(iv)))
}
let iv = <&Iv<Self>>::try_from(iv).map_err(|_| InvalidLength)?;
Ok(Self::inner_iv_init(inner, iv))
}

/// Generate random IV using the provided [`CryptoRng`].
Expand Down

0 comments on commit 00544a8

Please sign in to comment.