Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 19 additions & 12 deletions aes-kw/src/kw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use aes::cipher::{
Array, Block, BlockCipherDecrypt, BlockCipherEncrypt,
array::ArraySize,
common::{InnerInit, InnerUser},
typenum::{Mod, NonZero, Sum, U16, Zero},
typenum::{GrEq, IsGreaterOrEqual, Mod, NonZero, Sum, U16, Zero},
};

/// Default Initial Value for AES-KW as defined in RFC3394 § 2.2.3.1.
Expand Down Expand Up @@ -76,12 +76,12 @@ impl<C: BlockCipherEncrypt<BlockSize = U16>> AesKw<C> {
///
/// Returns slice which points to `buf` and contains wrapped data.
///
/// Length of `data` must be multiple of [`IV_LEN`] and bigger than zero.
/// Length of `buf` must be bigger or equal to `data.len() + IV_LEN`.
/// Length of `key` must be a multiple of [`IV_LEN`] and at least 16 bytes.
/// Length of `buf` must be at least `key.len() + IV_LEN`.
#[inline]
pub fn wrap_key<'a>(&self, key: &[u8], buf: &'a mut [u8]) -> Result<&'a [u8], Error> {
let blocks_rem = key.len() % IV_LEN;
if blocks_rem != 0 {
if blocks_rem != 0 || key.len() < 2 * IV_LEN {
return Err(Error::InvalidDataSize);
}

Expand All @@ -97,10 +97,12 @@ impl<C: BlockCipherEncrypt<BlockSize = U16>> AesKw<C> {

/// Wrap fixed-size key `key` and return wrapped key.
///
/// The key must be a multiple of 8 bytes and at least 16 bytes long.
///
/// This method is roughly equivalent to:
/// ```ignore
/// const fn check_key_size(n: usize) -> usize {
/// assert!(n != 0 && n % IV_LEN == 0);
/// assert!(n >= 16 && n % IV_LEN == 0);
/// 0
/// }
///
Expand All @@ -117,9 +119,10 @@ impl<C: BlockCipherEncrypt<BlockSize = U16>> AesKw<C> {
#[inline]
pub fn wrap_fixed_key<N>(&self, key: &Array<u8, N>) -> KwWrappedKey<N>
where
N: ArraySize + NonZero + Add<IvLen> + Rem<IvLen>,
N: ArraySize + NonZero + Add<IvLen> + Rem<IvLen> + IsGreaterOrEqual<U16>,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, the bounds change is technically breaking. It may not actually matter in practice, though.

We could also just bump the minor version to v0.4.

Sum<N, IvLen>: ArraySize,
Mod<N, IvLen>: Zero,
GrEq<N, U16>: NonZero,
{
let mut buf = KwWrappedKey::<N>::default();
self.wrap_key_trusted(key, &mut buf);
Expand Down Expand Up @@ -168,13 +171,14 @@ impl<C: BlockCipherDecrypt<BlockSize = U16>> AesKw<C> {
///
/// Returns slice which points to `buf` and contains unwrapped data.
///
/// Length of `data` must be multiple of [`IV_LEN`] and bigger than zero.
/// Length of `buf` must be bigger or equal to `data.len()`.
/// Length of `wkey` must be a multiple of [`IV_LEN`] and at least 24 bytes.
/// Length of `buf` must be at least `wkey.len() - IV_LEN`.
#[inline]
pub fn unwrap_key<'a>(&self, wkey: &[u8], buf: &'a mut [u8]) -> Result<&'a [u8], Error> {
let blocks_len = wkey.len() / IV_LEN;
let blocks_rem = wkey.len() % IV_LEN;
if blocks_rem != 0 || blocks_len < 1 {
// The IV plus at least two semiblocks of key data.
if blocks_rem != 0 || blocks_len < 3 {
return Err(Error::InvalidDataSize);
}

Expand All @@ -190,12 +194,14 @@ impl<C: BlockCipherDecrypt<BlockSize = U16>> AesKw<C> {
Ok(buf)
}

/// Unwrap key in `data` and return unwrapped key.
/// Unwrap key in `wkey` and return unwrapped key.
///
/// The wrapped key must be at least 24 bytes long.
///
/// This method is roughly equivalent to:
/// ```ignore
/// const fn check_key_size(n: usize) -> usize {
/// assert!(n != 0 && n % IV_LEN == 0);
/// assert!(n >= 16 && n % IV_LEN == 0);
/// 0
/// }
///
Expand All @@ -215,9 +221,10 @@ impl<C: BlockCipherDecrypt<BlockSize = U16>> AesKw<C> {
wkey: &KwWrappedKey<N>,
) -> Result<Array<u8, N>, IntegrityCheckFailed>
where
N: ArraySize + NonZero + Add<IvLen> + Rem<IvLen>,
N: ArraySize + NonZero + Add<IvLen> + Rem<IvLen> + IsGreaterOrEqual<U16>,
Sum<N, IvLen>: ArraySize,
Mod<N, IvLen>: Zero,
GrEq<N, U16>: NonZero,
{
let mut buf = Array::<u8, N>::default();
self.unwrap_key_trusted(wkey, &mut buf)?;
Expand Down
27 changes: 23 additions & 4 deletions aes-kw/src/kwp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ impl<C: BlockCipherEncrypt<BlockSize = U16>> AesKwp<C> {
/// bytes (i.e. 8 bytes) longer than the length of `data`.
#[inline]
pub fn wrap_key<'a>(&self, key: &[u8], buf: &'a mut [u8]) -> Result<&'a [u8], Error> {
if key.len() > KWP_MAX_LEN {
if key.is_empty() || key.len() > KWP_MAX_LEN {
return Err(Error::InvalidDataSize);
}

Expand All @@ -119,20 +119,29 @@ impl<C: BlockCipherEncrypt<BlockSize = U16>> AesKwp<C> {

/// Wrap fixed-size key `key` and return wrapped key.
///
/// The key must be non-empty; keys of 1 to 8 bytes use the single-block path.
///
/// This method is roughly equivalent to:
/// ```ignore
/// const fn check_key_size(n: usize) -> usize {
/// assert!(n != 0);
/// 0
/// }
///
/// pub fn wrap_fixed_key<const N: usize>(
/// &self,
/// key: &[u8; N],
/// ) -> [u8; IV_LEN * (N.div_ceil(IV_LEN) + 1)]
/// where
/// [(); check_key_size(N)]: Sized,
/// { ... }
/// ```
/// but uses [`hybrid_array::Array`][Array] instead of built-in arrays
/// to work around current limitations of the const generics system.
#[inline]
pub fn wrap_fixed_key<N>(&self, key: &Array<u8, N>) -> KwpWrappedKey<N>
where
N: ArraySize + Add<IvLenM1> + IsLess<KwpMaxLen>,
N: ArraySize + NonZero + Add<IvLenM1> + IsLess<KwpMaxLen>,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here re: bounds changes, though I'm not sure it matters if the thing it breaks is buggy anyway.

Le<N, KwpMaxLen>: NonZero,
Sum<N, IvLenM1>: Div<IvLen>,
Quot<Sum<N, IvLenM1>, IvLen>: Add<B1>,
Expand Down Expand Up @@ -229,7 +238,8 @@ impl<C: BlockCipherDecrypt<BlockSize = U16>> AesKwp<C> {
pub fn unwrap_key<'a>(&self, data: &[u8], buf: &'a mut [u8]) -> Result<&'a [u8], Error> {
let blocks_len = data.len() / IV_LEN;
let blocks_rem = data.len() % IV_LEN;
if blocks_rem != 0 || blocks_len < 1 || data.len() > KWP_MAX_LEN {
// The AIV plus at least one semiblock of padded key data.
if blocks_rem != 0 || blocks_len < 2 || data.len() > KWP_MAX_LEN {
return Err(Error::InvalidDataSize);
}

Expand All @@ -245,12 +255,21 @@ impl<C: BlockCipherDecrypt<BlockSize = U16>> AesKwp<C> {

/// Unwrap fixed-size wrapped key `wkey` and return resulting key.
///
/// The resulting key must be non-empty.
///
/// This method is roughly equivalent to:
/// ```ignore
/// const fn check_key_size(n: usize) -> usize {
/// assert!(n != 0);
/// 0
/// }
///
/// pub fn unwrap_fixed_key<const N: usize>(
/// &self,
/// wkey: &[u8; IV_LEN * (N.div_ceil(IV_LEN) + 1)],
/// ) -> [u8; N]
/// where
/// [(); check_key_size(N)]: Sized,
/// { ... }
/// ```
/// but uses [`hybrid_array::Array`][Array] instead of built-in arrays
Expand All @@ -261,7 +280,7 @@ impl<C: BlockCipherDecrypt<BlockSize = U16>> AesKwp<C> {
wkey: &KwpWrappedKey<N>,
) -> Result<Array<u8, N>, IntegrityCheckFailed>
where
N: ArraySize + Add<IvLenM1> + IsLess<KwpMaxLen>,
N: ArraySize + NonZero + Add<IvLenM1> + IsLess<KwpMaxLen>,
Le<N, KwpMaxLen>: NonZero,
Sum<N, IvLenM1>: Div<IvLen>,
Quot<Sum<N, IvLenM1>, IvLen>: Add<B1> + Mul<IvLen>,
Expand Down
13 changes: 13 additions & 0 deletions aes-kw/tests/kw_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,19 @@ fn error_invalid_data_size() {
let res = kek.unwrap_key(&output, &mut buf);
assert_eq!(res, Err(Error::InvalidDataSize));

// KW requires two semiblocks of key data and one semiblock for the IV.
let res = kek.wrap_key(&[], &mut buf);
assert_eq!(res, Err(Error::InvalidDataSize));

let res = kek.wrap_key(&[0u8; 8], &mut buf);
assert_eq!(res, Err(Error::InvalidDataSize));

let res = kek.unwrap_key(&[0u8; 8], &mut buf);
assert_eq!(res, Err(Error::InvalidDataSize));

let res = kek.unwrap_key(&[0u8; 16], &mut buf);
assert_eq!(res, Err(Error::InvalidDataSize));

let res = kek.unwrap_key(&[], &mut buf);
assert_eq!(res, Err(Error::InvalidDataSize));
}
Expand Down
26 changes: 26 additions & 0 deletions aes-kw/tests/kwp_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,26 @@ test_aes_kwp!(
hex!("afbeb0f07dfbf5419200f2ccb50bb24f")
);

#[test]
fn wrap_unwrap_one_byte_key() {
let key = hex!("000102030405060708090A0B0C0D0E0F");
let kwp = KwpAes128::new(&key.into());
let input = [0x42];
let mut wrapped_buf = [0u8; 16];
let wrapped = kwp.wrap_key(&input, &mut wrapped_buf).unwrap();
let mut unwrapped_buf = [0u8; 8];
assert_eq!(kwp.unwrap_key(wrapped, &mut unwrapped_buf).unwrap(), input);

let wrapped_fixed = kwp.wrap_fixed_key::<consts::U1>((&input).into());
assert_eq!(wrapped_fixed.as_slice(), wrapped);
assert_eq!(
kwp.unwrap_fixed_key::<consts::U1>(&wrapped_fixed)
.unwrap()
.as_slice(),
input
);
}

// These test vectors were obtained using NIST's CAVP system

test_aes_kwp!(
Expand Down Expand Up @@ -168,6 +188,12 @@ fn error_invalid_data_size() {
assert_eq!(res, Err(Error::InvalidDataSize));
let res = kwp.unwrap_key(&[], &mut buf);
assert_eq!(res, Err(Error::InvalidDataSize));

// Empty plaintext is invalid, and a single ciphertext semiblock is too short.
let res = kwp.wrap_key(&[], &mut buf);
assert_eq!(res, Err(Error::InvalidDataSize));
let res = kwp.unwrap_key(&[0u8; 8], &mut buf);
assert_eq!(res, Err(Error::InvalidDataSize));
}

#[test]
Expand Down
Loading