hkdf-0.10.0/benches/hkdf.rs010064400007650000024000000013301366573117600136300ustar0000000000000000#[macro_use] extern crate bencher; use bencher::Bencher; use hkdf::Hkdf; use sha2::Sha256; fn sha256_10(b: &mut Bencher) { let mut okm = vec![0u8; 10]; b.iter(|| Hkdf::::new(Some(&[]), &[]).expand(&[], &mut okm)); b.bytes = 10u64; } fn sha256_1k(b: &mut Bencher) { let mut okm = vec![0u8; 1024]; b.iter(|| Hkdf::::new(Some(&[]), &[]).expand(&[], &mut okm)); b.bytes = 1024u64; } fn sha256_8k(b: &mut Bencher) { let mut okm = vec![0u8; 8000]; b.iter(|| Hkdf::::new(Some(&[]), &[]).expand(&[], &mut okm)); b.bytes = 8000u64; } // note: SHA-256 output limit is 255*32=8160 bytes benchmark_group!(benches, sha256_10, sha256_1k, sha256_8k); benchmark_main!(benches); hkdf-0.10.0/Cargo.toml.orig010064400007650000024000000011571374561006000136200ustar0000000000000000[package] name = "hkdf" version = "0.10.0" authors = ["vladikoff", "warner", "RustCrypto Developers"] license = "MIT/Apache-2.0" homepage = "https://github.com/RustCrypto/KDFs/" repository = "https://github.com/RustCrypto/KDFs/" description = "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)" keywords = [ "HKDF", "Crypto" ] readme = "README.md" edition = "2018" [features] std = [] [lib] name = "hkdf" path = "src/hkdf.rs" [dependencies] digest = "0.9" hmac = "0.10" [dev-dependencies] crypto-tests = "0.5.*" hex = "0.4" sha-1 = "0.9" sha2 = "0.9" bencher = "0.1" [[bench]] name = "hkdf" harness = false hkdf-0.10.0/Cargo.toml0000644000000024201374561045100101260ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "hkdf" version = "0.10.0" authors = ["vladikoff", "warner", "RustCrypto Developers"] description = "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)" homepage = "https://github.com/RustCrypto/KDFs/" readme = "README.md" keywords = ["HKDF", "Crypto"] license = "MIT/Apache-2.0" repository = "https://github.com/RustCrypto/KDFs/" [lib] name = "hkdf" path = "src/hkdf.rs" [[bench]] name = "hkdf" harness = false [dependencies.digest] version = "0.9" [dependencies.hmac] version = "0.10" [dev-dependencies.bencher] version = "0.1" [dev-dependencies.crypto-tests] version = "0.5.*" [dev-dependencies.hex] version = "0.4" [dev-dependencies.sha-1] version = "0.9" [dev-dependencies.sha2] version = "0.9" [features] std = [] hkdf-0.10.0/examples/extract.rs010064400007650000024000000017111366573117600146000ustar0000000000000000use hkdf::Hkdf; use sha2::Sha256; // Normally the PRK (Pseudo-Random Key) remains hidden within the HKDF // object, but if you need to access it, use `Hkdf::extract` instead of // `Hkdf::new` fn main() { let ikm = hex::decode("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b").unwrap(); let salt = hex::decode("000102030405060708090a0b0c").unwrap(); let info = hex::decode("f0f1f2f3f4f5f6f7f8f9").unwrap(); let (prk, hk) = Hkdf::::extract(Some(&salt[..]), &ikm); let mut okm = [0u8; 42]; hk.expand(&info, &mut okm) .expect("42 is a valid length for Sha256 to output"); println!("Vector 1 PRK is {}", hex::encode(prk)); println!("Vector 1 OKM is {}", hex::encode(&okm[..])); println!("Matched with https://tools.ietf.org/html/rfc5869#appendix-A.1"); let expected = "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"; assert_eq!(hex::encode(&okm[..]), expected); } hkdf-0.10.0/examples/from_prk.rs010064400007650000024000000020651366573117600147500ustar0000000000000000use hkdf::Hkdf; use sha2::Sha256; // If you already have a strong key to work from (uniformly-distributed and // long enough), you can save a tiny amount of time by skipping the extract // step. In this case, you pass a Pseudo-Random Key (PRK) into the `from_prk` // constructor, then use the resulting `Hkdf` object as usual. fn main() { // data from RFC 5869, section A.1, Test Case 1 let prk = hex::decode("077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5").unwrap(); let info = hex::decode("f0f1f2f3f4f5f6f7f8f9").unwrap(); let hk = Hkdf::::from_prk(&prk).expect("PRK should be large enough"); let mut okm = [0u8; 42]; hk.expand(&info, &mut okm) .expect("42 is a valid length for Sha256 to output"); println!("Vector 1 OKM is {}", hex::encode(&okm[..])); println!("Matched with https://tools.ietf.org/html/rfc5869#appendix-A.1"); let expected = "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"; assert_eq!(hex::encode(&okm[..]), expected); } hkdf-0.10.0/examples/main.rs010064400007650000024000000017041366573117600140540ustar0000000000000000use hkdf::Hkdf; use sha2::Sha256; // this is the most common way to use HKDF: you provide the Initial Key // Material and an optional salt, then you expand it (perhaps multiple times) // into some Output Key Material bound to an "info" context string. fn main() { let ikm = hex::decode("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b").unwrap(); let salt = hex::decode("000102030405060708090a0b0c").unwrap(); let info = hex::decode("f0f1f2f3f4f5f6f7f8f9").unwrap(); let hk = Hkdf::::new(Some(&salt[..]), &ikm); let mut okm = [0u8; 42]; hk.expand(&info, &mut okm) .expect("42 is a valid length for Sha256 to output"); println!("Vector 1 OKM is {}", hex::encode(&okm[..])); println!("Matched with https://tools.ietf.org/html/rfc5869#appendix-A.1"); let expected = "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"; assert_eq!(hex::encode(&okm[..]), expected); } hkdf-0.10.0/LICENSE-APACHE010064400007650000024000000251401366524563000126630ustar0000000000000000 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.hkdf-0.10.0/LICENSE-MIT010064400007650000024000000021171366524563000123720ustar0000000000000000Copyright (c) 2015-2018 Vlad Filippov Copyright (c) 2018 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. hkdf-0.10.0/README.md010064400007650000024000000042401374355501100122060ustar0000000000000000# RustCrypto: HKDF [![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] [HMAC-based Extract-and-Expand Key Derivation Function (HKDF)](https://tools.ietf.org/html/rfc5869) for [Rust](http://www.rust-lang.org/). Uses the Digest trait which specifies an interface common to digest functions, such as SHA-1, SHA-256, etc. ## Installation From crates.io: ```toml [dependencies] hkdf = "0.7" ``` ## Usage See the example [examples/main.rs](examples/main.rs) or run it with `cargo run --example main` ## Changelog - 0.8.0 - new API, add `Hkdf::from_prk()`, `Hkdf::extract()` - 0.7.0 - Update digest to 0.8, refactor for API changes, remove redundant `generic-array` crate. - 0.6.0 - remove std requirement. The `expand` signature has changed. - 0.5.0 - removed deprecated interface, fixed omitting HKDF salt. - 0.4.0 - RFC-inspired interface, Reduce heap allocation, remove unnecessary mut, derive Clone. deps: hex-0.3, benchmarks. - 0.3.0 - update dependencies: digest-0.7, hmac-0.5 - 0.2.0 - support for rustc 1.20.0 - 0.1.1 - fixes to support rustc 1.5.0 - 0.1.0 - initial release ## Authors [![Vlad Filippov](https://avatars3.githubusercontent.com/u/128755?s=70)](http://vf.io/) | [![Brian Warner](https://avatars3.githubusercontent.com/u/27146?v=4&s=70)](http://www.lothar.com/blog/) ---|--- [Vlad Filippov](http://vf.io/) | [Brian Warner](http://www.lothar.com/blog/) [//]: # (badges) [crate-image]: https://img.shields.io/crates/v/hkdf.svg [crate-link]: https://crates.io/crates/hkdf [docs-image]: https://docs.rs/hkdf/badge.svg [docs-link]: https://docs.rs/hkdf/ [license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg [rustc-image]: https://img.shields.io/badge/rustc-1.41+-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/hkdf/badge.svg?branch=master&event=push [build-link]: https://github.com/RustCrypto/KDFs/actions?query=workflow:hkdf hkdf-0.10.0/src/hkdf.rs010064400007650000024000000153151374335766300130220ustar0000000000000000//! An implementation of HKDF, the [HMAC-based Extract-and-Expand Key Derivation Function][1]. //! //! # Usage //! //! ```rust //! # extern crate hex; //! # extern crate hkdf; //! # extern crate sha2; //! # use sha2::Sha256; //! # use hkdf::Hkdf; //! let ikm = hex::decode("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b").unwrap(); //! let salt = hex::decode("000102030405060708090a0b0c").unwrap(); //! let info = hex::decode("f0f1f2f3f4f5f6f7f8f9").unwrap(); //! //! let h = Hkdf::::new(Some(&salt[..]), &ikm); //! let mut okm = [0u8; 42]; //! h.expand(&info, &mut okm).unwrap(); //! println!("OKM is {}", hex::encode(&okm[..])); //! ``` //! //! [1]: https://tools.ietf.org/html/rfc5869 #![no_std] #![warn(rust_2018_idioms)] #[cfg(feature = "std")] extern crate std; use core::fmt; use digest::generic_array::{self, ArrayLength, GenericArray}; use digest::{BlockInput, FixedOutput, Reset, Update}; use hmac::{Hmac, Mac, NewMac}; /// Error that is returned when supplied pseudorandom key (PRK) is not long enough. #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub struct InvalidPrkLength; /// Structure for InvalidLength, used for output error handling. #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub struct InvalidLength; /// Structure representing the streaming context of an HKDF-Extract operation /// ```rust /// # use hkdf::{Hkdf, HkdfExtract}; /// # use sha2::Sha256; /// let mut extract_ctx = HkdfExtract::::new(Some(b"mysalt")); /// extract_ctx.input_ikm(b"hello"); /// extract_ctx.input_ikm(b" world"); /// let (streamed_res, _) = extract_ctx.finalize(); /// /// let (oneshot_res, _) = Hkdf::::extract(Some(b"mysalt"), b"hello world"); /// assert_eq!(streamed_res, oneshot_res); /// ``` #[derive(Clone)] pub struct HkdfExtract where D: Update + BlockInput + FixedOutput + Reset + Default + Clone, D::BlockSize: ArrayLength, D::OutputSize: ArrayLength, { hmac: Hmac, } impl HkdfExtract where D: Update + BlockInput + FixedOutput + Reset + Default + Clone, D::BlockSize: ArrayLength, D::OutputSize: ArrayLength, { /// Initiates the HKDF-Extract context with the given optional salt pub fn new(salt: Option<&[u8]>) -> HkdfExtract { let hmac = match salt { Some(s) => Hmac::::new_varkey(s).expect("HMAC can take a key of any size"), None => Hmac::::new(&Default::default()), }; HkdfExtract { hmac } } /// Feeds in additional input key material to the HKDF-Extract context pub fn input_ikm(&mut self, ikm: &[u8]) { self.hmac.update(ikm); } /// Completes the HKDF-Extract operation, returning both the generated pseudorandom key and /// `Hkdf` struct for expanding. pub fn finalize(self) -> (GenericArray, Hkdf) { let prk = self.hmac.finalize().into_bytes(); let hkdf = Hkdf::from_prk(&prk).expect("PRK size is correct"); (prk, hkdf) } } /// Structure representing the HKDF, capable of HKDF-Expand and HKDF-Extract operations. #[derive(Clone)] pub struct Hkdf where D: Update + BlockInput + FixedOutput + Reset + Default + Clone, D::BlockSize: ArrayLength, D::OutputSize: ArrayLength, { hmac: Hmac, } impl Hkdf where D: Update + BlockInput + FixedOutput + Reset + Default + Clone, D::BlockSize: ArrayLength, D::OutputSize: ArrayLength, { /// Convenience method for [`extract`][Hkdf::extract] when the generated /// pseudorandom key can be ignored and only HKDF-Expand operation is needed. This is the most /// common constructor. pub fn new(salt: Option<&[u8]>, ikm: &[u8]) -> Hkdf { let (_, hkdf) = Hkdf::extract(salt, ikm); hkdf } /// Create `Hkdf` from an already cryptographically strong pseudorandom key /// as per section 3.3 from RFC5869. pub fn from_prk(prk: &[u8]) -> Result, InvalidPrkLength> { use crate::generic_array::typenum::Unsigned; // section 2.3 specifies that prk must be "at least HashLen octets" if prk.len() < D::OutputSize::to_usize() { return Err(InvalidPrkLength); } Ok(Hkdf { hmac: Hmac::new_varkey(prk).expect("HMAC can take a key of any size"), }) } /// The RFC5869 HKDF-Extract operation returning both the generated /// pseudorandom key and `Hkdf` struct for expanding. pub fn extract(salt: Option<&[u8]>, ikm: &[u8]) -> (GenericArray, Hkdf) { let mut extract_ctx = HkdfExtract::new(salt); extract_ctx.input_ikm(ikm); extract_ctx.finalize() } /// The RFC5869 HKDF-Expand operation. This is equivalent to calling /// [`expand`][Hkdf::extract] with the `info` argument set equal to the /// concatenation of all the elements of `info_components`. pub fn expand_multi_info( &self, info_components: &[&[u8]], okm: &mut [u8], ) -> Result<(), InvalidLength> { use crate::generic_array::typenum::Unsigned; let mut prev: Option::OutputSize>> = None; let hmac_output_bytes = D::OutputSize::to_usize(); if okm.len() > hmac_output_bytes * 255 { return Err(InvalidLength); } let mut hmac = self.hmac.clone(); for (blocknum, okm_block) in okm.chunks_mut(hmac_output_bytes).enumerate() { let block_len = okm_block.len(); if let Some(ref prev) = prev { hmac.update(prev) }; // Feed in the info components in sequence. This is equivalent to feeding in the // concatenation of all the info components for info in info_components { hmac.update(info); } hmac.update(&[blocknum as u8 + 1]); let output = hmac.finalize_reset().into_bytes(); okm_block.copy_from_slice(&output[..block_len]); prev = Some(output); } Ok(()) } /// The RFC5869 HKDF-Expand operation /// /// If you don't have any `info` to pass, use an empty slice. pub fn expand(&self, info: &[u8], okm: &mut [u8]) -> Result<(), InvalidLength> { self.expand_multi_info(&[info], okm) } } impl fmt::Display for InvalidPrkLength { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { f.write_str("invalid pseudorandom key length, too short") } } #[cfg(feature = "std")] impl ::std::error::Error for InvalidPrkLength {} impl fmt::Display for InvalidLength { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { f.write_str("invalid number of blocks, too large output") } } #[cfg(feature = "std")] impl ::std::error::Error for InvalidLength {} hkdf-0.10.0/tests/tests.rs010064400007650000024000000264731374240315400136140ustar0000000000000000use core::iter; use hex; use hkdf::{Hkdf, HkdfExtract}; use sha1::Sha1; use sha2::Sha256; struct Test<'a> { ikm: &'a str, salt: &'a str, info: &'a str, length: usize, prk: &'a str, okm: &'a str, } // Test Vectors from https://tools.ietf.org/html/rfc5869. fn tests_sha256<'a>() -> Vec> { vec![ Test { // Test Case 1 ikm: "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", salt: "000102030405060708090a0b0c", info: "f0f1f2f3f4f5f6f7f8f9", length: 42, prk: "077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5", okm: "3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b8\ 87185865", }, Test { // Test Case 2 ikm: "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425\ 262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b\ 4c4d4e4f", salt: "606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f80818283848\ 5868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aa\ abacadaeaf", info: "b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d\ 5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fa\ fbfcfdfeff", length: 82, prk: "06a6b88c5853361a06104c9ceb35b45cef760014904671014a193f40c15fc244", okm: "b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c59045a99cac7\ 827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71cc30c58179ec3e87c14c01d5\ c1f3434f1d87", }, Test { // Test Case 3 ikm: "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", salt: "", info: "", length: 42, prk: "19ef24a32c717b167f33a91d6f648bdf96596776afdb6377ac434c1c293ccb04", okm: "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4\ b61a96c8", }, ] } #[test] fn test_derive_sha256() { let tests = tests_sha256(); for t in tests.iter() { let ikm = hex::decode(&t.ikm).unwrap(); let salt = hex::decode(&t.salt).unwrap(); let info = hex::decode(&t.info).unwrap(); let (prk, hkdf) = Hkdf::::extract(Option::from(&salt[..]), &ikm[..]); let mut okm = vec![0u8; t.length]; assert!(hkdf.expand(&info[..], &mut okm).is_ok()); assert_eq!(hex::encode(prk), t.prk); assert_eq!(hex::encode(&okm), t.okm); let prk = &hex::decode(&t.prk).unwrap(); let hkdf = Hkdf::::from_prk(prk).unwrap(); assert!(hkdf.expand(&info[..], &mut okm).is_ok()); assert_eq!(hex::encode(&okm), t.okm); } } const MAX_SHA256_LENGTH: usize = 255 * (256 / 8); // =8160 #[test] fn test_lengths() { let hkdf = Hkdf::::new(None, &[]); let mut longest = vec![0u8; MAX_SHA256_LENGTH]; assert!(hkdf.expand(&[], &mut longest).is_ok()); // Runtime is O(length), so exhaustively testing all legal lengths // would take too long (at least without --release). Only test a // subset: the first 500, the last 10, and every 100th in between. let lengths = (0..MAX_SHA256_LENGTH + 1) .filter(|&len| len < 500 || len > MAX_SHA256_LENGTH - 10 || len % 100 == 0); for length in lengths { let mut okm = vec![0u8; length]; assert!(hkdf.expand(&[], &mut okm).is_ok()); assert_eq!(okm.len(), length); assert_eq!(hex::encode(okm), hex::encode(longest[..length].iter())); } } #[test] fn test_max_length() { let hkdf = Hkdf::::new(Some(&[]), &[]); let mut okm = vec![0u8; MAX_SHA256_LENGTH]; assert!(hkdf.expand(&[], &mut okm).is_ok()); } #[test] fn test_max_length_exceeded() { let hkdf = Hkdf::::new(Some(&[]), &[]); let mut okm = vec![0u8; MAX_SHA256_LENGTH + 1]; assert!(hkdf.expand(&[], &mut okm).is_err()); } #[test] fn test_unsupported_length() { let hkdf = Hkdf::::new(Some(&[]), &[]); let mut okm = vec![0u8; 90000]; assert!(hkdf.expand(&[], &mut okm).is_err()); } #[test] fn test_prk_too_short() { use sha2::digest::generic_array::typenum::Unsigned; use sha2::digest::Digest; let output_len = ::OutputSize::to_usize(); let prk = vec![0; output_len - 1]; assert!(Hkdf::::from_prk(&prk).is_err()); } // Test Vectors from https://tools.ietf.org/html/rfc5869. fn tests_sha1<'a>() -> Vec> { vec![ Test { // Test Case 4 ikm: "0b0b0b0b0b0b0b0b0b0b0b", salt: "000102030405060708090a0b0c", info: "f0f1f2f3f4f5f6f7f8f9", length: 42, prk: "9b6c18c432a7bf8f0e71c8eb88f4b30baa2ba243", okm: "085a01ea1b10f36933068b56efa5ad81\ a4f14b822f5b091568a9cdd4f155fda2\ c22e422478d305f3f896", }, Test { // Test Case 5 ikm: "000102030405060708090a0b0c0d0e0f\ 101112131415161718191a1b1c1d1e1f\ 202122232425262728292a2b2c2d2e2f\ 303132333435363738393a3b3c3d3e3f\ 404142434445464748494a4b4c4d4e4f", salt: "606162636465666768696a6b6c6d6e6f\ 707172737475767778797a7b7c7d7e7f\ 808182838485868788898a8b8c8d8e8f\ 909192939495969798999a9b9c9d9e9f\ a0a1a2a3a4a5a6a7a8a9aaabacadaeaf", info: "b0b1b2b3b4b5b6b7b8b9babbbcbdbebf\ c0c1c2c3c4c5c6c7c8c9cacbcccdcecf\ d0d1d2d3d4d5d6d7d8d9dadbdcdddedf\ e0e1e2e3e4e5e6e7e8e9eaebecedeeef\ f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff", length: 82, prk: "8adae09a2a307059478d309b26c4115a224cfaf6", okm: "0bd770a74d1160f7c9f12cd5912a06eb\ ff6adcae899d92191fe4305673ba2ffe\ 8fa3f1a4e5ad79f3f334b3b202b2173c\ 486ea37ce3d397ed034c7f9dfeb15c5e\ 927336d0441f4c4300e2cff0d0900b52\ d3b4", }, Test { // Test Case 6 ikm: "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", salt: "", info: "", length: 42, prk: "da8c8a73c7fa77288ec6f5e7c297786aa0d32d01", okm: "0ac1af7002b3d761d1e55298da9d0506\ b9ae52057220a306e07b6b87e8df21d0\ ea00033de03984d34918", }, Test { // Test Case 7 ikm: "0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c", salt: "", // "Not Provided" info: "", length: 42, prk: "2adccada18779e7c2077ad2eb19d3f3e731385dd", okm: "2c91117204d745f3500d636a62f64f0a\ b3bae548aa53d423b0d1f27ebba6f5e5\ 673a081d70cce7acfc48", }, ] } #[test] fn test_derive_sha1() { let tests = tests_sha1(); for t in tests.iter() { let ikm = hex::decode(&t.ikm).unwrap(); let salt = hex::decode(&t.salt).unwrap(); let info = hex::decode(&t.info).unwrap(); let (prk, hkdf) = Hkdf::::extract(Some(&salt[..]), &ikm[..]); let mut okm = vec![0u8; t.length]; assert!(hkdf.expand(&info[..], &mut okm).is_ok()); assert_eq!(hex::encode(prk), t.prk); assert_eq!(hex::encode(&okm), t.okm); let prk = &hex::decode(&t.prk).unwrap(); let hkdf = Hkdf::::from_prk(&prk).unwrap(); assert!(hkdf.expand(&info[..], &mut okm).is_ok()); assert_eq!(hex::encode(&okm), t.okm); } } #[test] fn test_derive_sha1_with_none() { let ikm = hex::decode("0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c").unwrap(); let salt = None; let info = hex::decode("").unwrap(); let (prk, hkdf) = Hkdf::::extract(salt, &ikm[..]); let mut okm = vec![0u8; 42]; assert!(hkdf.expand(&info[..], &mut okm).is_ok()); assert_eq!(hex::encode(prk), "2adccada18779e7c2077ad2eb19d3f3e731385dd"); assert_eq!( hex::encode(&okm), "2c91117204d745f3500d636a62f64f0a\ b3bae548aa53d423b0d1f27ebba6f5e5\ 673a081d70cce7acfc48" ); } #[test] fn test_expand_multi_info() { let info_components = &[ &b"09090909090909090909090909090909090909090909"[..], &b"8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a"[..], &b"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0"[..], &b"4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4"[..], &b"1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d"[..], ]; let (_, hkdf_ctx) = Hkdf::::extract(None, b"some ikm here"); // Compute HKDF-Expand on the concatenation of all the info components let mut oneshot_res = [0u8; 16]; hkdf_ctx .expand(&info_components.concat(), &mut oneshot_res) .unwrap(); // Now iteratively join the components of info_components until it's all 1 component. The value // of HKDF-Expand should be the same throughout let mut num_concatted = 0; let mut info_head = Vec::new(); while num_concatted < info_components.len() { info_head.extend(info_components[num_concatted]); // Build the new input to be the info head followed by the remaining components let input: Vec<&[u8]> = iter::once(info_head.as_slice()) .chain(info_components.iter().cloned().skip(num_concatted + 1)) .collect(); // Compute and compare to the one-shot answer let mut multipart_res = [0u8; 16]; hkdf_ctx .expand_multi_info(&input, &mut multipart_res) .unwrap(); assert_eq!(multipart_res, oneshot_res); num_concatted += 1; } } #[test] fn test_extract_streaming() { let ikm_components = &[ &b"09090909090909090909090909090909090909090909"[..], &b"8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a"[..], &b"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0"[..], &b"4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4"[..], &b"1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d"[..], ]; let salt = b"mysalt"; // Compute HKDF-Extract on the concatenation of all the IKM components let (oneshot_res, _) = Hkdf::::extract(Some(&salt[..]), &ikm_components.concat()); // Now iteratively join the components of ikm_components until it's all 1 component. The value // of HKDF-Extract should be the same throughout let mut num_concatted = 0; let mut ikm_head = Vec::new(); while num_concatted < ikm_components.len() { ikm_head.extend(ikm_components[num_concatted]); // Make a new extraction context and build the new input to be the IKM head followed by the // remaining components let mut extract_ctx = HkdfExtract::::new(Some(&salt[..])); let input = iter::once(ikm_head.as_slice()) .chain(ikm_components.iter().cloned().skip(num_concatted + 1)); // Stream in the IKM input in the chunks specified for ikm in input { extract_ctx.input_ikm(ikm); } // Finalize and compare to the one-shot answer let (multipart_res, _) = extract_ctx.finalize(); assert_eq!(multipart_res, oneshot_res); num_concatted += 1; } } hkdf-0.10.0/.cargo_vcs_info.json0000644000000001121374561045100121240ustar00{ "git": { "sha1": "2462ad3326f9f320a5239a3f327f5eb7d4b525da" } } hkdf-0.10.0/Cargo.lock0000644000000121541374561045100101100ustar00# This file is automatically @generated by Cargo. # It is not intended for manual editing. [[package]] name = "bencher" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7dfdb4953a096c551ce9ace855a604d702e6e62d77fac690575ae347571717f5" [[package]] name = "block-buffer" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" dependencies = [ "generic-array 0.14.4", ] [[package]] name = "block-cipher-trait" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d85cf11f176fc683b9d290b231200f501a938f36dd0b9516a5ae6278377a1583" dependencies = [ "generic-array 0.8.3", ] [[package]] name = "cfg-if" version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" [[package]] name = "constant_time_eq" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc" [[package]] name = "cpuid-bool" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8aebca1129a03dc6dc2b127edd729435bbc4a37e1d5f4d7513165089ceb02634" [[package]] name = "crypto-mac" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "779015233ac67d65098614aec748ac1c756ab6677fa2e14cf8b37c08dfed1198" dependencies = [ "constant_time_eq", "generic-array 0.8.3", ] [[package]] name = "crypto-mac" version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4857fd85a0c34b3c3297875b747c1e02e06b6a0ea32dd892d8192b9ce0813ea6" dependencies = [ "generic-array 0.14.4", "subtle", ] [[package]] name = "crypto-tests" version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b8c30525659210fcced70ae9be2d0269ae4a417efc77b939884d2a40081d923" dependencies = [ "block-cipher-trait", "crypto-mac 0.4.0", "digest 0.6.2", "generic-array 0.8.3", ] [[package]] name = "digest" version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e5b29bf156f3f4b3c4f610a25ff69370616ae6e0657d416de22645483e72af0a" dependencies = [ "generic-array 0.8.3", ] [[package]] name = "digest" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" dependencies = [ "generic-array 0.14.4", ] [[package]] name = "generic-array" version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fceb69994e330afed50c93524be68c42fa898c2d9fd4ee8da03bd7363acd26f2" dependencies = [ "nodrop", "typenum", ] [[package]] name = "generic-array" version = "0.14.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "501466ecc8a30d1d3b7fc9229b122b2ce8ed6e9d9223f1138d4babb253e51817" dependencies = [ "typenum", "version_check", ] [[package]] name = "hex" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "644f9158b2f133fd50f5fb3242878846d9eb792e445c893805ff0e3824006e35" [[package]] name = "hkdf" version = "0.10.0" dependencies = [ "bencher", "crypto-tests", "digest 0.9.0", "hex", "hmac", "sha-1", "sha2", ] [[package]] name = "hmac" version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1441c6b1e930e2817404b5046f1f989899143a12bf92de603b69f4e0aee1e15" dependencies = [ "crypto-mac 0.10.0", "digest 0.9.0", ] [[package]] name = "nodrop" version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb" [[package]] name = "opaque-debug" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" [[package]] name = "sha-1" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "170a36ea86c864a3f16dd2687712dd6646f7019f301e57537c7f4dc9f5916770" dependencies = [ "block-buffer", "cfg-if", "cpuid-bool", "digest 0.9.0", "opaque-debug", ] [[package]] name = "sha2" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2933378ddfeda7ea26f48c555bdad8bb446bf8a3d17832dc83e380d444cfb8c1" dependencies = [ "block-buffer", "cfg-if", "cpuid-bool", "digest 0.9.0", "opaque-debug", ] [[package]] name = "subtle" version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "343f3f510c2915908f155e94f17220b19ccfacf2a64a2a5d8004f2c3e311e7fd" [[package]] name = "typenum" version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "373c8a200f9e67a0c95e62a4f52fbf80c23b4381c05a17845531982fa99e6b33" [[package]] name = "version_check" version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5a972e5669d67ba988ce3dc826706fb0a8b01471c088cb0b6110b805cc36aed"