diff --git a/.github/workflows/sp800-108.yml b/.github/workflows/sp800-108.yml new file mode 100644 index 0000000..f79545d --- /dev/null +++ b/.github/workflows/sp800-108.yml @@ -0,0 +1,60 @@ +name: sp800-108 + +on: + pull_request: + paths: + - ".github/workflows/sp800-108.yml" + - "sp800-108/**" + - "Cargo.*" + push: + branches: master + +defaults: + run: + working-directory: sp800-108 + +env: + CARGO_INCREMENTAL: 0 + RUSTFLAGS: "-Dwarnings" + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + rust: + - 1.85.0 # MSRV + - stable + target: + - thumbv7em-none-eabi + - wasm32-unknown-unknown + steps: + - uses: actions/checkout@v6 + - uses: RustCrypto/actions/cargo-cache@master + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ matrix.rust }} + targets: ${{ matrix.target }} + - run: cargo build --no-default-features --target ${{ matrix.target }} + + minimal-versions: + uses: RustCrypto/actions/.github/workflows/minimal-versions.yml@master + with: + working-directory: ${{ github.workflow }} + + test: + runs-on: ubuntu-latest + strategy: + matrix: + rust: + - 1.85.0 # MSRV + - stable + steps: + - uses: actions/checkout@v6 + - uses: RustCrypto/actions/cargo-cache@master + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ matrix.rust }} + - uses: RustCrypto/actions/cargo-hack-install@master + - run: cargo hack test --feature-powerset + - run: cargo test --release --all-features diff --git a/Cargo.lock b/Cargo.lock index 0006456..a34c2a3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -59,6 +59,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cdd35008169921d80bc60d3d0ab416eecb028c4cd653352907921d95084790be" dependencies = [ "hybrid-array", + "zeroize", ] [[package]] @@ -145,6 +146,18 @@ dependencies = [ "block-buffer", "crypto-common", "ctutils", + "zeroize", +] + +[[package]] +name = "generic-array" +version = "1.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaf57c49a95fd1fe24b90b3033bee6dc7e8f1288d51494cb44e627c295e38542" +dependencies = [ + "rustversion", + "typenum", + "zeroize", ] [[package]] @@ -233,6 +246,12 @@ dependencies = [ "sha2", ] +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + [[package]] name = "sha1" version = "0.11.0" @@ -255,8 +274,31 @@ dependencies = [ "digest", ] +[[package]] +name = "sp800-108" +version = "0.1.0" +dependencies = [ + "aes", + "blobby", + "cmac", + "digest", + "generic-array", + "hex", + "hex-literal", + "hmac", + "kdf", + "sha1", + "sha2", +] + [[package]] name = "typenum" version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" + +[[package]] +name = "zeroize" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" diff --git a/Cargo.toml b/Cargo.toml index 4222bd0..b948084 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,8 @@ members = [ "bake-kdf", "hkdf", "kbkdf", - "one-step-kdf" + "one-step-kdf", + "sp800-108" ] [profile.dev] diff --git a/sp800-108/Cargo.toml b/sp800-108/Cargo.toml new file mode 100644 index 0000000..ec01a69 --- /dev/null +++ b/sp800-108/Cargo.toml @@ -0,0 +1,40 @@ +[package] +name = "sp800-108" +version = "0.1.0" +authors = ["RustCrypto Developers"] +license = "MIT OR Apache-2.0" +homepage = "https://github.com/RustCrypto/KDFs/" +repository = "https://github.com/RustCrypto/KDFs/" +description = "NIST SP 800-108 Key Derivation Functions (KDFs)" +keywords = ["crypto", "NIST SP 800-108", "KDF"] +categories = ["cryptography", "no-std"] +readme = "README.md" +edition = "2024" +rust-version = "1.85" + +[dependencies] +digest = { version = "0.11.2", default-features = false, features = [ "mac" ]} +generic-array = { version = "1.3.5", default-features = false} + +# optional dependencies +kdf = { version = "0.1"} + +[dev-dependencies] +blobby = "0.4" +hex-literal = "1" +hex = "0.4" +hmac = { version = "0.13.0", default-features = false} +sha1 = { version = "0.11", default-features = false } +sha2 = { version = "0.11", default-features = false } +cmac = { version = "0.8.0", default-features = false} +aes = { version = "0.9.0", default-features = false} + +[features] +default = ["zeroize"] +zeroize = ["generic-array/zeroize", "digest/zeroize"] + +[lints] +workspace = true + +[package.metadata.docs.rs] +all-features = true diff --git a/sp800-108/LICENSE-APACHE b/sp800-108/LICENSE-APACHE new file mode 100644 index 0000000..53b7ccd --- /dev/null +++ b/sp800-108/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/sp800-108/LICENSE-MIT b/sp800-108/LICENSE-MIT new file mode 100644 index 0000000..c0d0781 --- /dev/null +++ b/sp800-108/LICENSE-MIT @@ -0,0 +1,26 @@ +Copyright (c) 2015-2018 Vlad Filippov +Copyright (c) 2018-2021 RustCrypto Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/sp800-108/README.md b/sp800-108/README.md new file mode 100644 index 0000000..08c008f --- /dev/null +++ b/sp800-108/README.md @@ -0,0 +1,170 @@ +# [RustCrypto]: SP 800-108 + +[![crate][crate-image]][crate-link] +[![Docs][docs-image]][docs-link] +![Apache2/MIT licensed][license-image] +![Rust Version][rustc-image] +[![Project Chat][chat-image]][chat-link] +[![Build Status][build-image]][build-link] + +Pure Rust implementation of the [NIST SP 800-108] KDFs generic over PRFs. + +This crate currently supports Counter and Feedback KDFs and does not implement either the Double-Pipeline or KMAC-based KDFs. + +# Usage + +[NIST SP 800-108] describes multiple families of KDFs and ways to construct them. +This means that, unlike HKDF, there is not a specific "NIST SP 800-108 Counter KDF." +Instead, each user of this crate will need to define the specific KDF construction that meets their requirements. + +**WARNING!** Properly defining the context is a *security-critical* decision. It is very easy to define an insecure KDF with an improper context. Generally, people should not be using this crate unless specifically required by compliance, standards, or protocols. + +All SP 800-108 KDFs generate one block of output at a time using an underlying keyed PRF (pseudo-random function) such as HMAC or CMAC. +As input to the PRF is various context which may include constant labels, derivation specific non-secret values, and other values. +In order to generate outputs longer than the output length of the PRF, the KDF generates one block of data at a time from the PRF +and modifies the input to it so that each block is different. +This means that the context must contain some values which change from block to block. +The two ways of doing this are with a counter or feedback. +They can also be combined. + +## Counter KDF + +When used with a counter, one of the item in the context is a big-endian counter, starting at 1 and counting each block generated. +That way each block has a different input to the PRF and thus output. +You do this with [`ContextComponent::BeCounter`]. + +```rust +use sha2::Sha256; +use hmac::Hmac; +use aes::Aes128; +use cmac::Cmac; +use sp800_108::{ContextComponent, Kdf, KeyInit, NistSp800_108KDF}; +use hex_literal::hex; + +let ikm = hex!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); + +// For this example, we will have the additional data *before* the 32-bit counter. +// However, simply by reordering the elements, it could be placed after. +let context = [ + ContextComponent::NonSecret, + ContextComponent::BeCounter(32)]; +let kdf = NistSp800_108KDF::>::new(&context).expect("KDF creation failed"); + +let mut key1 = [0u8; 16]; +kdf.derive_key(&ikm, b"non-secret data 1", &mut key1).expect("Derivation failed"); +println!("Derived key 1: {:?}", key1); + +let mut key2 = [0u8; 32]; +kdf.derive_key(&ikm, b"non-secret data 2", &mut key2).expect("Derivation failed"); +println!("Derived key 2: {:?}", key2); + +// Alternatively, the data can be encoded as fixed data directly in the context +let context = [ + ContextComponent::ConstantString("non-secret data 1"), + ContextComponent::BeCounter(32)]; +let kdf = NistSp800_108KDF::>::new(&context).expect("KDF creation failed"); + +let mut key1_again = [0u8; 16]; +kdf.derive_key(&ikm, &[] /* no input this time */, &mut key1_again).expect("Derivation failed"); +assert_eq!(key1, key1_again); + +// Some constructions require fixed data before and after the counter. +// Since kdf.derive_key() only takes in a single non-secret input, we must use a constant for one or both of them. +// This one is taken from a NIST test vector for use with CMAC-AES-128 +let ikm = hex!("b6e04abd1651f8794d4326f4c684e631"); +let context = [ + ContextComponent::ConstantBytes(&hex!( + "93612f7256c46a3d856d3e951e32dbf15fe11159d0b389ad38d603850fee6d18d22031435ed36ee20da76745fbea4b10fe1e")), + ContextComponent::BeCounter(8), + ContextComponent::ConstantBytes(&hex!("99322aae605a5f01e32b"))]; +let mut key3 = [0u8; 16]; +let kdf = NistSp800_108KDF::>::new(&context).expect("KDF creation failed"); +kdf.derive_key(&ikm, &[], &mut key3).expect("Derivation failed"); +assert_eq!(key3, hex!("dcb1db87a68762c6b3354779fa590bef")); +``` + +## Feedback KDF + +Another way of modifying the input to the PRF for each block is to feedback the value of the prior block into the input for the next block. +You do this with You do this with [`ContextComponent::Feedback`] which takes in an `iv` (which may be empty). +The `iv` is provided as input to the first block. + +```rust +use sha2::Sha256; +use hmac::Hmac; +use aes::Aes128; +use cmac::Cmac; +use sp800_108::{ContextComponent, Kdf, KeyInit, NistSp800_108KDF}; +use hex_literal::hex; + +let ikm = hex!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"); + +let context = [ + ContextComponent::ConstantString("non-secret data"), + ContextComponent::Feedback(&[]),// empty IV +]; +let kdf = NistSp800_108KDF::>::new(&context).expect("KDF creation failed"); + +let mut key1 = [64]; +kdf.derive_key(&ikm, &[], &mut key1).expect("Derivation failed"); +println!("Derived key 1: {:?}", key1); + +// With an IV we'll get a different output +let context = [ + ContextComponent::ConstantString("non-secret data 1"), + ContextComponent::Feedback(b"YellowSubmarine"), // Non-empty IV +]; +let kdf = NistSp800_108KDF::>::new(&context).expect("KDF creation failed"); + +let mut key2 = [64]; +kdf.derive_key(&ikm, &[], &mut key2).expect("Derivation failed"); +println!("Derived key 2: {:?}", key2); +assert_ne!(key1, key2); + +// Finally, some constructions have both counters and feedback +let context = [ + ContextComponent::ConstantString("non-secret data"), + ContextComponent::BeCounter(16), + ContextComponent::NonSecret, + ContextComponent::Feedback(&[]),// empty IV +]; + +let kdf = NistSp800_108KDF::>::new(&context).expect("KDF creation failed"); + +let mut key3 = [64]; +kdf.derive_key(&ikm, &[], &mut key3).expect("Derivation failed"); +println!("Derived key 3: {:?}", key3); +``` + +## License + +Licensed under either of: + +* [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) +* [MIT license](http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. + +[//]: # (badges) + +[crate-image]: https://img.shields.io/crates/v/sp800-108.svg +[crate-link]: https://crates.io/crates/sp800-108 +[docs-image]: https://docs.rs/sp800-108/badge.svg +[docs-link]: https://docs.rs/sp800-108/ +[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg +[rustc-image]: https://img.shields.io/badge/rustc-1.85+-blue.svg +[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg +[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260043-KDFs +[build-image]: https://github.com/RustCrypto/KDFs/workflows/sp800-108/badge.svg?branch=master&event=push +[build-link]: https://github.com/RustCrypto/KDFs/actions?query=workflow:sp800-108 + +[//]: # (links) + +[RustCrypto]: https://github.com/RustCrypto +[NIST SP 800-108]: https://csrc.nist.gov/pubs/sp/800/108/r1/upd1/final \ No newline at end of file diff --git a/sp800-108/src/lib.rs b/sp800-108/src/lib.rs new file mode 100644 index 0000000..2a8e993 --- /dev/null +++ b/sp800-108/src/lib.rs @@ -0,0 +1,243 @@ +#![no_std] +#![doc = include_str!("../README.md")] +#![doc( + html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg", + html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg" +)] +#![cfg_attr(docsrs, feature(doc_cfg))] + +use core::marker::PhantomData; + +pub use digest::{FixedOutput, KeyInit, Update}; +pub use kdf::Kdf; + +/// The maximum number of [`ContextComponent`]s that can be passed to [`NistSp800_108KDF::new()`]. +pub const MAX_CONTEXT_COMPONENTS: usize = 16; + +/// Specifies a specific input to the PRF when deriving a key. +/// +/// The NIST SP 800-108 KDFs generate their output one block at a time +/// where a block is a single output of the underlying PRF. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ContextComponent<'a> { + /// No input. If used, must be after any others. + /// + /// Generally, there is no need for developers to use this value. + Null, + /// Big-endian block counter with a specified bit-length. + /// The bit-length must be a positive multiple of 8 and no greater than 64. + BeCounter(u32), + /// The `non-secret` input to [`Kdf::derive_key()`]. + NonSecret, + /// The prior-block or the supplied `iv` value (may be empty). + Feedback(&'a [u8]), + /// The block generated when both the counter and `K0` are omitted. + /// See section 4.1 of the [specification](https://csrc.nist.gov/pubs/sp/800/108/r1/upd1/final) + /// for more information. + K0, + /// The bytes corresponding to the provided string. + ConstantString(&'a str), + /// The provided bytes. + ConstantBytes(&'a [u8]), + /// The length in bytes of the requested derived key. + /// It is encoded as a big-endian number with the specified number of bits. + /// The the specified bit-length must be a positive multiple of 8 and no greater than 64. + BeLength(usize), +} + +/// Structure representing the KDF, generic over a PRF `P`. +/// Depending on configuration, it can represent a counter KDF, +/// a feedback KDF, or a combination of the two. +/// +/// The PRF `P` should generally be either an implementation of +/// [`Hmac`](https://docs.rs/hmac/0.13.0/hmac/struct.Hmac.html) +/// or of [`Cmac`](https://docs.rs/cmac/latest/cmac/struct.Cmac.html). +#[derive(Debug)] +pub struct NistSp800_108KDF<'a, P> +where + P: FixedOutput + KeyInit + Clone, +{ + context: [ContextComponent<'a>; MAX_CONTEXT_COMPONENTS], + summary: ContextSummary, + phantom: PhantomData

, +} + +impl<'a, P> NistSp800_108KDF<'a, P> +where + P: FixedOutput + KeyInit + Clone, +{ + /// Construct a new KDF instance where the input to the PRF is defined by `context`. + /// + /// `context` must be no longer than [`MAX_CONTEXT_COMPONENTS`]. + /// `context` should not contain any instances of [`ContextComponent::Null`], + /// but if it does, they must be after all non-null values. + /// + /// # Errors + /// + /// Will return `Err` in any of the following cases: + /// + /// - `context` is longer than [`MAX_CONTEXT_COMPONENTS`]. + /// - `context` has any `ContextComponent::Null` values before non-null values. + /// - `context` does not have any non-null values. + pub fn new(context: &[ContextComponent<'a>]) -> kdf::Result { + if context.len() > MAX_CONTEXT_COMPONENTS { + return Err(kdf::Error); + } + let summary = Self::summarize_context(context); + if summary.last_non_null_idx.is_none() { + return Err(kdf::Error); + } + if let Some(min_null) = summary.first_null_idx { + if let Some(max_non_null) = summary.last_non_null_idx { + if min_null < max_non_null { + // There are components after the first null component + return Err(kdf::Error); + } + } + } + let mut result = Self { + context: [ContextComponent::Null; MAX_CONTEXT_COMPONENTS], + summary, + phantom: PhantomData, + }; + result.context[0..context.len()].copy_from_slice(context); + Ok(result) + } + + fn summarize_context(context: &[ContextComponent]) -> ContextSummary { + context + .iter() + .enumerate() + .fold(ContextSummary::default(), |mut acc, v| -> ContextSummary { + match v.1 { + ContextComponent::BeCounter(length) => { + acc.min_ctr = acc + .min_ctr + .map_or(Some(*length), |old_length| Some(old_length.min(*length))); + } + ContextComponent::NonSecret => acc.has_non_secret = true, + ContextComponent::K0 => acc.has_k0 = true, + _ => (), // NOP, + } + if v.1 == &ContextComponent::Null { + if acc.first_null_idx.is_none() { + acc.first_null_idx = Some(v.0); + } + } else { + acc.last_non_null_idx = Some(v.0); + } + acc + }) + } + + fn calculate_block( + &self, + mut prf: P, + non_secret: &[u8], + counter: u64, + feedback: &Option>, + k0: &Option>, + output_len: usize, + ) -> kdf::Result> { + for c in self.context { + match c { + ContextComponent::Null => (), + ContextComponent::BeCounter(length) => { + if counter > 0 { + Self::update_be_ctr(&mut prf, counter, length as usize)?; + } + } + ContextComponent::NonSecret => Update::update(&mut prf, non_secret), + ContextComponent::Feedback(iv) => Self::update_option(&mut prf, feedback, iv), + ContextComponent::K0 => Self::update_option(&mut prf, k0, &[]), + ContextComponent::ConstantString(value) => { + Update::update(&mut prf, value.as_bytes()); + } + ContextComponent::ConstantBytes(value) => Update::update(&mut prf, value), + ContextComponent::BeLength(length) => { + Self::update_be_ctr(&mut prf, output_len as u64, length)?; + } + } + } + + Ok(prf.finalize_fixed()) + } + + fn update_be_ctr(prf: &mut P, counter: u64, length: usize) -> kdf::Result<()> { + if counter >> length != 0 { + // Counter overflow + return Err(kdf::Error); + } + let bytes = counter.to_be_bytes(); + Update::update(prf, &bytes[bytes.len() - (length / 8)..bytes.len()]); + Ok(()) + } + + fn update_option(prf: &mut P, value: &Option>, default: &[u8]) { + if let Some(data) = value { + Update::update(prf, data); + } else { + Update::update(prf, default); + } + } +} + +impl<'a, P> Kdf for NistSp800_108KDF<'a, P> +where + P: FixedOutput + KeyInit + Clone, +{ + /// Writes uniformly random data suitable as key material into the entire length of out + /// as described by [`Kdf::derive_key()`]. + /// + /// # Errors + /// + /// Will return `Err` in any of the following cases: + /// + /// - `out` is long enough that a counter in the context would overflow + /// - `non_secret` contains data but there is no corresponding [`ContextComponent::NonSecret`] to emit it. + fn derive_key(&self, secret: &[u8], non_secret: &[u8], out: &mut [u8]) -> kdf::Result<()> { + let prf = P::new_from_slice(secret).map_err(|_| kdf::Error)?; + if !non_secret.is_empty() && !self.summary.has_non_secret { + // Additional input was provided but isn't used by the context. + // This is an error + return Err(kdf::Error); + } + if let Some(min_ctr_bits) = self.summary.min_ctr { + let needed_blocks: usize = out.len().div_ceil(P::output_size()); + let needed_ctr_bits = usize::BITS - needed_blocks.leading_zeros(); + if needed_ctr_bits > min_ctr_bits { + // We cannot encode the counter in the bits we're given + return Err(kdf::Error); + } + } + let k0 = if self.summary.has_k0 { + Some(self.calculate_block(prf.clone(), non_secret, 0, &None, &None, out.len())?) + } else { + None + }; + + let mut feedback = None; + let mut counter = 1; + let mut data_written = 0; + while data_written < out.len() { + let block = + self.calculate_block(prf.clone(), non_secret, counter, &feedback, &k0, out.len())?; + let data_to_write = block.len().min(out.len() - data_written); + out[data_written..data_written + data_to_write] + .copy_from_slice(&block[..data_to_write]); + data_written += data_to_write; + feedback = Some(block); + counter += 1; + } + Ok(()) + } +} + +#[derive(Debug, Copy, Clone, Default)] +struct ContextSummary { + min_ctr: Option, + has_k0: bool, + has_non_secret: bool, + first_null_idx: Option, + last_non_null_idx: Option, +} diff --git a/sp800-108/tests/cavp_tests.rs b/sp800-108/tests/cavp_tests.rs new file mode 100644 index 0000000..e339ebc --- /dev/null +++ b/sp800-108/tests/cavp_tests.rs @@ -0,0 +1,300 @@ +//! CAVP test vectors. + +use core::fmt::Debug; + +use aes::{Aes128, Aes192, Aes256}; +use cmac::Cmac; +use digest::{FixedOutput, KeyInit}; +use hmac::Hmac; +use kdf::Kdf; +use sha1::Sha1; +use sha2::{Sha224, Sha256, Sha384, Sha512}; +use sp800_108::{ContextComponent, NistSp800_108KDF}; + +#[derive(Copy, Clone)] +struct TestVector { + ctr_location: &'static [u8], + rlen: &'static [u8], + key: &'static [u8], + iv: &'static [u8], + fixed_input_data: &'static [u8], + data_before_ctr: &'static [u8], + data_after_ctr: &'static [u8], + okm: &'static [u8], +} + +impl Debug for TestVector { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + writeln!(f, "TestVector {{")?; + writeln!( + f, + " ctr_location: \"{}\"", + String::from_utf8_lossy(self.ctr_location).to_string() + )?; + writeln!( + f, + " rlen: \"{}\"", + String::from_utf8_lossy(self.rlen).to_string() + )?; + writeln!(f, " key: {}", hex::encode(self.key))?; + writeln!(f, " iv: {}", hex::encode(self.iv))?; + writeln!( + f, + " fixed_input_data: {}", + hex::encode(self.fixed_input_data) + )?; + writeln!( + f, + " data_before_ctr: {}", + hex::encode(self.data_before_ctr) + )?; + writeln!( + f, + " data_after_ctr: {}", + hex::encode(self.data_after_ctr) + )?; + writeln!(f, " okm: {}", hex::encode(self.okm))?; + writeln!(f, "}}") + } +} + +fn test_cases

(cases: &[(Vec, &[u8])], i: usize, tv: &TestVector) +where + P: FixedOutput + KeyInit + Clone, +{ + let mut okm_dst = vec![0u8; tv.okm.len()]; + for c in cases { + let context = &c.0; + let input = c.1; + okm_dst.fill(0); + let kdf = NistSp800_108KDF::

::new(&c.0); + assert!( + kdf.is_ok(), + "Failed test #{i}: {context:?} Creating KDF\nTest vector:\t{tv:#?}" + ); + let kdf = kdf.expect("Already verified this is ok"); + + assert!( + kdf.derive_key(tv.key, input, &mut okm_dst).is_ok(), + "Failed test #{i}: {context:?} derive_key\nTest vector:\t{tv:#?}" + ); + assert_eq!( + &okm_dst, tv.okm, + "Failed test #{i}: {context:?} mismatch in okm\nTest vector:\t{tv:#?}" + ); + } +} + +fn parse_rlen(rlen: &[u8]) -> u32 { + String::from_utf8_lossy(rlen) + .split('_') + .next() + .expect("CAVP data incorrectly formatted") + .trim() + .parse::() + .expect("CAVP data incorrectly formatted") +} + +fn test_ctr

(test_vectors: &[TestVector]) +where + P: FixedOutput + KeyInit + Clone, +{ + for (i, tv) in test_vectors.iter().enumerate() { + // rlen takes the form of _BITS. Example: "8_BITS" + let rlen = parse_rlen(tv.rlen); + let ctr_location = String::from_utf8_lossy(tv.ctr_location).to_string(); + match ctr_location.as_str() { + "MIDDLE_FIXED" => { + test_cases::

( + &[ + ( + vec![ + ContextComponent::ConstantBytes(tv.data_before_ctr), + ContextComponent::BeCounter(rlen), + ContextComponent::ConstantBytes(tv.data_after_ctr), + ], + &[], + ), + ( + vec![ + ContextComponent::NonSecret, + ContextComponent::BeCounter(rlen), + ContextComponent::ConstantBytes(tv.data_after_ctr), + ], + tv.data_before_ctr, + ), + ( + vec![ + ContextComponent::ConstantBytes(tv.data_before_ctr), + ContextComponent::BeCounter(rlen), + ContextComponent::NonSecret, + ], + tv.data_after_ctr, + ), + ], + i, + tv, + ); + } + "BEFORE_FIXED" => { + test_cases::

( + &[ + ( + vec![ + ContextComponent::BeCounter(rlen), + ContextComponent::ConstantBytes(tv.fixed_input_data), + ], + &[], + ), + ( + vec![ + ContextComponent::BeCounter(rlen), + ContextComponent::NonSecret, + ], + tv.fixed_input_data, + ), + ], + i, + tv, + ); + } + "AFTER_FIXED" => { + test_cases::

( + &[ + ( + vec![ + ContextComponent::ConstantBytes(tv.fixed_input_data), + ContextComponent::BeCounter(rlen), + ], + &[], + ), + ( + vec![ + ContextComponent::NonSecret, + ContextComponent::BeCounter(rlen), + ], + tv.fixed_input_data, + ), + ], + i, + tv, + ); + } + _ => panic!("Unsupported counter location: {}", ctr_location), + }; + } +} + +fn test_feedback

(test_vectors: &[TestVector]) +where + P: FixedOutput + KeyInit + Clone, +{ + for (i, tv) in test_vectors.iter().enumerate() { + test_cases::

( + &[ + ( + vec![ + ContextComponent::Feedback(tv.iv), + ContextComponent::ConstantBytes(tv.fixed_input_data), + ], + &[], + ), + ( + vec![ + ContextComponent::Feedback(tv.iv), + ContextComponent::NonSecret, + ], + tv.fixed_input_data, + ), + ], + i, + tv, + ); + } +} + +fn test_feedback_ctr

(test_vectors: &[TestVector]) +where + P: FixedOutput + KeyInit + Clone, +{ + for (i, tv) in test_vectors.iter().enumerate() { + // rlen takes the form of _BITS. Example: "8_BITS" + let rlen = parse_rlen(tv.rlen); + let ctr_location = String::from_utf8_lossy(tv.ctr_location).to_string(); + let cases: &mut [(Vec, &[u8])] = &mut [ + ( + vec![ + ContextComponent::Feedback(tv.iv), + ContextComponent::ConstantBytes(tv.fixed_input_data), + ], + &[], + ), + ( + vec![ + ContextComponent::Feedback(tv.iv), + ContextComponent::NonSecret, + ], + tv.fixed_input_data, + ), + ]; + let ctr_idx = match ctr_location.as_str() { + "BEFORE_ITER" => 0, + "AFTER_ITER" => 1, + "AFTER_FIXED" => 2, + _ => panic!("Unsupported counter location: {}", ctr_location), + }; + for c in cases.iter_mut() { + c.0.insert(ctr_idx, ContextComponent::BeCounter(rlen)); + } + test_cases::

(cases, i, tv); + } +} + +macro_rules! new_test { + ($name:ident, $prf:ty, $test:ident) => { + #[test] + fn $name() { + blobby::parse_into_structs!( + include_bytes!(concat!("data/", stringify!($name), ".blb")); + static TEST_VECTORS: &[TestVector { ctr_location, rlen, key, iv, fixed_input_data, data_before_ctr, data_after_ctr, okm }]; + ); + + $test::<$prf>(TEST_VECTORS); + } + }; +} + +// All tests from https://csrc.nist.gov/Projects/Cryptographic-Algorithm-Validation-Program/Key-Derivation + +// KDF in Counter Mode Test Vectors +new_test!(ctr_hmac_sha1, Hmac, test_ctr); +new_test!(ctr_hmac_sha224, Hmac, test_ctr); +new_test!(ctr_hmac_sha256, Hmac, test_ctr); +new_test!(ctr_hmac_sha384, Hmac, test_ctr); +new_test!(ctr_hmac_sha512, Hmac, test_ctr); + +new_test!(ctr_cmac_aes128, Cmac, test_ctr); +new_test!(ctr_cmac_aes192, Cmac, test_ctr); +new_test!(ctr_cmac_aes256, Cmac, test_ctr); + +// KDF in Feedback Mode Test Vectors where no counter is used +new_test!(feedback_hmac_sha1, Hmac, test_feedback); +new_test!(feedback_hmac_sha224, Hmac, test_feedback); +new_test!(feedback_hmac_sha256, Hmac, test_feedback); +new_test!(feedback_hmac_sha384, Hmac, test_feedback); +new_test!(feedback_hmac_sha512, Hmac, test_feedback); + +new_test!(feedback_cmac_aes128, Cmac, test_feedback); +new_test!(feedback_cmac_aes192, Cmac, test_feedback); +new_test!(feedback_cmac_aes256, Cmac, test_feedback); + +// KDF in Feedback Mode Test Vectors where zero length IV is allowed +new_test!(feedback_ctr_hmac_sha1, Hmac, test_feedback_ctr); +new_test!(feedback_ctr_hmac_sha224, Hmac, test_feedback_ctr); +new_test!(feedback_ctr_hmac_sha256, Hmac, test_feedback_ctr); +new_test!(feedback_ctr_hmac_sha384, Hmac, test_feedback_ctr); +new_test!(feedback_ctr_hmac_sha512, Hmac, test_feedback_ctr); + +new_test!(feedback_ctr_cmac_aes128, Cmac, test_feedback_ctr); +new_test!(feedback_ctr_cmac_aes192, Cmac, test_feedback_ctr); +new_test!(feedback_ctr_cmac_aes256, Cmac, test_feedback_ctr); diff --git a/sp800-108/tests/data/ctr_cmac_aes128.blb b/sp800-108/tests/data/ctr_cmac_aes128.blb new file mode 100644 index 0000000..5a2b2d5 Binary files /dev/null and b/sp800-108/tests/data/ctr_cmac_aes128.blb differ diff --git a/sp800-108/tests/data/ctr_cmac_aes192.blb b/sp800-108/tests/data/ctr_cmac_aes192.blb new file mode 100644 index 0000000..ab18ecc Binary files /dev/null and b/sp800-108/tests/data/ctr_cmac_aes192.blb differ diff --git a/sp800-108/tests/data/ctr_cmac_aes256.blb b/sp800-108/tests/data/ctr_cmac_aes256.blb new file mode 100644 index 0000000..054092e Binary files /dev/null and b/sp800-108/tests/data/ctr_cmac_aes256.blb differ diff --git a/sp800-108/tests/data/ctr_hmac_sha1.blb b/sp800-108/tests/data/ctr_hmac_sha1.blb new file mode 100644 index 0000000..04a5ea0 Binary files /dev/null and b/sp800-108/tests/data/ctr_hmac_sha1.blb differ diff --git a/sp800-108/tests/data/ctr_hmac_sha224.blb b/sp800-108/tests/data/ctr_hmac_sha224.blb new file mode 100644 index 0000000..d0788a1 Binary files /dev/null and b/sp800-108/tests/data/ctr_hmac_sha224.blb differ diff --git a/sp800-108/tests/data/ctr_hmac_sha256.blb b/sp800-108/tests/data/ctr_hmac_sha256.blb new file mode 100644 index 0000000..dc1470f Binary files /dev/null and b/sp800-108/tests/data/ctr_hmac_sha256.blb differ diff --git a/sp800-108/tests/data/ctr_hmac_sha384.blb b/sp800-108/tests/data/ctr_hmac_sha384.blb new file mode 100644 index 0000000..937886b Binary files /dev/null and b/sp800-108/tests/data/ctr_hmac_sha384.blb differ diff --git a/sp800-108/tests/data/ctr_hmac_sha512.blb b/sp800-108/tests/data/ctr_hmac_sha512.blb new file mode 100644 index 0000000..29ce9c3 Binary files /dev/null and b/sp800-108/tests/data/ctr_hmac_sha512.blb differ diff --git a/sp800-108/tests/data/feedback_cmac_aes128.blb b/sp800-108/tests/data/feedback_cmac_aes128.blb new file mode 100644 index 0000000..a06ab2b Binary files /dev/null and b/sp800-108/tests/data/feedback_cmac_aes128.blb differ diff --git a/sp800-108/tests/data/feedback_cmac_aes192.blb b/sp800-108/tests/data/feedback_cmac_aes192.blb new file mode 100644 index 0000000..2c0d4b5 Binary files /dev/null and b/sp800-108/tests/data/feedback_cmac_aes192.blb differ diff --git a/sp800-108/tests/data/feedback_cmac_aes256.blb b/sp800-108/tests/data/feedback_cmac_aes256.blb new file mode 100644 index 0000000..e959ae1 Binary files /dev/null and b/sp800-108/tests/data/feedback_cmac_aes256.blb differ diff --git a/sp800-108/tests/data/feedback_ctr_cmac_aes128.blb b/sp800-108/tests/data/feedback_ctr_cmac_aes128.blb new file mode 100644 index 0000000..9517015 Binary files /dev/null and b/sp800-108/tests/data/feedback_ctr_cmac_aes128.blb differ diff --git a/sp800-108/tests/data/feedback_ctr_cmac_aes192.blb b/sp800-108/tests/data/feedback_ctr_cmac_aes192.blb new file mode 100644 index 0000000..ed53bb1 Binary files /dev/null and b/sp800-108/tests/data/feedback_ctr_cmac_aes192.blb differ diff --git a/sp800-108/tests/data/feedback_ctr_cmac_aes256.blb b/sp800-108/tests/data/feedback_ctr_cmac_aes256.blb new file mode 100644 index 0000000..36029a0 Binary files /dev/null and b/sp800-108/tests/data/feedback_ctr_cmac_aes256.blb differ diff --git a/sp800-108/tests/data/feedback_ctr_hmac_sha1.blb b/sp800-108/tests/data/feedback_ctr_hmac_sha1.blb new file mode 100644 index 0000000..976dc9b Binary files /dev/null and b/sp800-108/tests/data/feedback_ctr_hmac_sha1.blb differ diff --git a/sp800-108/tests/data/feedback_ctr_hmac_sha224.blb b/sp800-108/tests/data/feedback_ctr_hmac_sha224.blb new file mode 100644 index 0000000..fc07847 Binary files /dev/null and b/sp800-108/tests/data/feedback_ctr_hmac_sha224.blb differ diff --git a/sp800-108/tests/data/feedback_ctr_hmac_sha256.blb b/sp800-108/tests/data/feedback_ctr_hmac_sha256.blb new file mode 100644 index 0000000..d3bb2fb Binary files /dev/null and b/sp800-108/tests/data/feedback_ctr_hmac_sha256.blb differ diff --git a/sp800-108/tests/data/feedback_ctr_hmac_sha384.blb b/sp800-108/tests/data/feedback_ctr_hmac_sha384.blb new file mode 100644 index 0000000..a005ec5 Binary files /dev/null and b/sp800-108/tests/data/feedback_ctr_hmac_sha384.blb differ diff --git a/sp800-108/tests/data/feedback_ctr_hmac_sha512.blb b/sp800-108/tests/data/feedback_ctr_hmac_sha512.blb new file mode 100644 index 0000000..607fd96 Binary files /dev/null and b/sp800-108/tests/data/feedback_ctr_hmac_sha512.blb differ diff --git a/sp800-108/tests/data/feedback_hmac_sha1.blb b/sp800-108/tests/data/feedback_hmac_sha1.blb new file mode 100644 index 0000000..f305224 Binary files /dev/null and b/sp800-108/tests/data/feedback_hmac_sha1.blb differ diff --git a/sp800-108/tests/data/feedback_hmac_sha224.blb b/sp800-108/tests/data/feedback_hmac_sha224.blb new file mode 100644 index 0000000..81f1bff Binary files /dev/null and b/sp800-108/tests/data/feedback_hmac_sha224.blb differ diff --git a/sp800-108/tests/data/feedback_hmac_sha256.blb b/sp800-108/tests/data/feedback_hmac_sha256.blb new file mode 100644 index 0000000..b483501 Binary files /dev/null and b/sp800-108/tests/data/feedback_hmac_sha256.blb differ diff --git a/sp800-108/tests/data/feedback_hmac_sha384.blb b/sp800-108/tests/data/feedback_hmac_sha384.blb new file mode 100644 index 0000000..452b639 Binary files /dev/null and b/sp800-108/tests/data/feedback_hmac_sha384.blb differ diff --git a/sp800-108/tests/data/feedback_hmac_sha512.blb b/sp800-108/tests/data/feedback_hmac_sha512.blb new file mode 100644 index 0000000..169e267 Binary files /dev/null and b/sp800-108/tests/data/feedback_hmac_sha512.blb differ diff --git a/sp800-108/tests/spot_tests.rs b/sp800-108/tests/spot_tests.rs new file mode 100644 index 0000000..524f6e1 --- /dev/null +++ b/sp800-108/tests/spot_tests.rs @@ -0,0 +1,178 @@ +//! Tests covering specific edge-cases not necessarily covered by the CAVP tests vectors + +use digest::{OutputSizeUser, Update}; +use hmac::{Hmac, KeyInit, Mac}; +use kdf::Kdf; +use sha1::Sha1; +use sha2::Sha256; +use sp800_108::{ContextComponent, NistSp800_108KDF}; + +/// Tests that we properly handle the `K0` and `ConstantString` components +/// See section 4.1. +#[test] +fn k0_test() { + let key = b"1234567890abcdef"; + let label = "Label"; + + let mut hmac = Hmac::::new_from_slice(key).expect("Could not construct hmac"); + // Counter is omitted + Update::update(&mut hmac, label.as_bytes()); + let k0 = hmac.finalize().as_bytes().to_vec(); + + let ctr_1 = [0u8, 0u8, 0u8, 1u8]; + + let mut hmac = Hmac::::new_from_slice(key).expect("Could not construct hmac"); + Update::update(&mut hmac, &ctr_1); + Update::update(&mut hmac, label.as_bytes()); + Update::update(&mut hmac, &k0); + let expected = hmac.finalize().as_bytes().to_vec(); + + // Use the KDF now + let context = [ + ContextComponent::BeCounter(32), + ContextComponent::ConstantString(label), + ContextComponent::K0, + ]; + let kdf = NistSp800_108KDF::>::new(&context).expect("Could not construct KDF"); + let mut actual = vec![0u8; expected.len()]; + kdf.derive_key(key, &[], &mut actual) + .expect("Could not derive key"); + assert_eq!(actual, expected); +} + +/// Tests that we reject outputs where the counter would roll over +#[test] +fn length_limit() { + let h_len = Sha1::output_size(); + let context = [ContextComponent::BeCounter(8)]; // 8 bits, max 255 + let kdf = NistSp800_108KDF::>::new(&context).expect("Could not create KDF"); + let key = b"1234567890abcdef"; + + // Largest possible output + let mut out = vec![0u8; h_len * 255]; + assert!( + kdf.derive_key(key, &[], &mut out).is_ok(), + "Unable to derive key of acceptable length" + ); + + // Too big + out.resize(out.len() + 1, 0); + assert!( + kdf.derive_key(key, &[], &mut out).is_err(), + "Did not reject overlength output" + ); +} + +/// Tests that we reject if you attempt to pass non-secret data as input but the context doesn't use it +#[test] +fn non_secret_input_used() { + let key = b"1234567890abcdef"; + let ignored_input = "Ignored input"; + + let context = [ContextComponent::BeCounter(32)]; + let kdf = NistSp800_108KDF::>::new(&context).expect("Could not construct KDF"); + + let mut out = [0u8; 16]; + assert!( + kdf.derive_key(key, ignored_input.as_bytes(), &mut out) + .is_err(), + "Did not reject ignored input" + ); +} + +/// Require at least one non-null element +#[test] +fn non_null_ctx() { + assert!( + NistSp800_108KDF::>::new(&[]).is_err(), + "Constructed KDF with empty context" + ); + + assert!( + NistSp800_108KDF::>::new(&[ContextComponent::Null]).is_err(), + "Constructed KDF with only null context" + ); +} + +/// Requires that all non-null `ContextComponent` values are before any `Null` ones. +#[test] +fn non_null_ctx_at_start() { + // Base case + let context = [ContextComponent::BeCounter(32)]; + assert!( + NistSp800_108KDF::>::new(&context).is_ok(), + "Could not construct KDF" + ); + + // Identical to base + let context = [ContextComponent::BeCounter(32), ContextComponent::Null]; + assert!( + NistSp800_108KDF::>::new(&context).is_ok(), + "Could not construct KDF" + ); + + // Only a single non-null + let context = [ContextComponent::Null, ContextComponent::BeCounter(32)]; + assert!( + NistSp800_108KDF::>::new(&context).is_err(), + "Did not reject" + ); + + // Null in between + let context = [ + ContextComponent::ConstantString("Some value"), + ContextComponent::Null, + ContextComponent::BeCounter(32), + ]; + assert!( + NistSp800_108KDF::>::new(&context).is_err(), + "Did not reject" + ); +} + +/// Test that BeLength is properly handled +#[test] +fn be_length() { + let key = b"1234567890abcdef"; + let label = "Label"; + let context = [ + ContextComponent::ConstantString(label), + ContextComponent::BeLength(8), + ]; + let kdf = NistSp800_108KDF::>::new(&context).expect("Could not create KDF"); + + // Length 16 + let length = [16u8]; + let mut hmac = Hmac::::new_from_slice(key).expect("Could not construct hmac"); + Update::update(&mut hmac, label.as_bytes()); + Update::update(&mut hmac, &length); + let mut expected = hmac.finalize().as_bytes().to_vec(); + expected.truncate(16); + let mut actual = [0u8; 16]; + assert!( + kdf.derive_key(key, &[], &mut actual).is_ok(), + "Could not derive key" + ); + assert_eq!( + &actual[..], + &expected, + "Derived keys are different for length 16" + ); + + // Length 32 + let length = [32u8]; + let mut hmac = Hmac::::new_from_slice(key).expect("Could not construct hmac"); + Update::update(&mut hmac, label.as_bytes()); + Update::update(&mut hmac, &length); + let expected = hmac.finalize().as_bytes().to_vec(); + let mut actual = [0u8; 32]; + assert!( + kdf.derive_key(key, &[], &mut actual).is_ok(), + "Could not derive key" + ); + assert_eq!( + &actual[..], + &expected, + "Derived keys are different for length 16" + ); +}