Import hmac 0.12.1 upstream upstream/0.12.1
authorDongHun Kwak <dh0128.kwak@samsung.com>
Mon, 3 Apr 2023 03:34:52 +0000 (12:34 +0900)
committerDongHun Kwak <dh0128.kwak@samsung.com>
Mon, 3 Apr 2023 03:34:52 +0000 (12:34 +0900)
22 files changed:
.cargo_vcs_info.json [new file with mode: 0644]
CHANGELOG.md [new file with mode: 0644]
Cargo.toml [new file with mode: 0644]
Cargo.toml.orig [new file with mode: 0644]
LICENSE-APACHE [new file with mode: 0644]
LICENSE-MIT [new file with mode: 0644]
README.md [new file with mode: 0644]
src/lib.rs [new file with mode: 0644]
src/optim.rs [new file with mode: 0644]
src/simple.rs [new file with mode: 0644]
tests/data/md5.blb [new file with mode: 0644]
tests/data/sha224.blb [new file with mode: 0644]
tests/data/sha256.blb [new file with mode: 0644]
tests/data/sha384.blb [new file with mode: 0644]
tests/data/sha512.blb [new file with mode: 0644]
tests/data/streebog256.blb [new file with mode: 0644]
tests/data/streebog512.blb [new file with mode: 0644]
tests/data/wycheproof-sha1.blb [new file with mode: 0644]
tests/data/wycheproof-sha256.blb [new file with mode: 0644]
tests/data/wycheproof-sha384.blb [new file with mode: 0644]
tests/data/wycheproof-sha512.blb [new file with mode: 0644]
tests/mod.rs [new file with mode: 0644]

diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json
new file mode 100644 (file)
index 0000000..36b6de6
--- /dev/null
@@ -0,0 +1,6 @@
+{
+  "git": {
+    "sha1": "46797e3b44973a30edb9d7f3a3ebb41810061d90"
+  },
+  "path_in_vcs": "hmac"
+}
\ No newline at end of file
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644 (file)
index 0000000..2569cc5
--- /dev/null
@@ -0,0 +1,97 @@
+# Changelog
+
+All notable changes to this project will be documented in this file.
+
+The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+
+## 0.12.1 (2022-02-17)
+### Fixed
+- Minimal versions build ([#108])
+
+[#108]: https://github.com/RustCrypto/MACs/pull/108
+
+## 0.12.0 (2021-12-07)
+### Changed
+- Bump `digest` crate dependency to v0.10 and remove `crypto-mac` ([#97])
+- Use a more efficient state representation by using block-level hash API ([#97])
+
+### Added
+- `SimpleHmac` as a less constrained alternative to `Hmac` ([#97])
+
+[#97]: https://github.com/RustCrypto/MACs/pull/97
+
+## 0.11.0 (2021-04-29)
+### Changed
+- Bump `crypto-mac` crate dependency to v0.11 ([#73])
+
+[#73]: https://github.com/RustCrypto/MACs/pull/73
+
+## 0.10.1 (2020-10-16)
+### Added
+- Zulip badge ([#64])
+
+[#64]: https://github.com/RustCrypto/MACs/pull/64
+
+## 0.10.0 (2020-10-16)
+### Changed
+- Bump `crypto-mac` dependency to v0.10 ([#62])
+
+[#62]: https://github.com/RustCrypto/MACs/pull/62
+
+## 0.9.0 (2020-08-12)
+### Changed
+- Bump `crypto-mac` dependency to v0.9 ([#57])
+
+### Added
+- Implement `io::Write` ([#55])
+
+[#55]: https://github.com/RustCrypto/MACs/pull/55
+[#57]: https://github.com/RustCrypto/MACs/pull/57
+
+## 0.8.1 (2020-06-24)
+### Fixed
+- Replace outdated `code` with `into_bytes` in documentation ([#50])
+
+[#50]: https://github.com/RustCrypto/MACs/pull/50
+
+## 0.8.0 (2020-06-09)
+### Changed
+- Upgrade to `digest` v0.9 crate release; MSRV 1.41 ([#45])
+- Upgrade `crypto-mac` to v0.8 ([#33])
+- Rename `*result*` to `finalize` ([#38])
+- Upgrade to Rust 2018 edition  ([#33])
+
+[#45]: https://github.com/RustCrypto/MACs/pull/45
+[#38]: https://github.com/RustCrypto/MACs/pull/38
+[#33]: https://github.com/RustCrypto/MACs/pull/33
+
+## 0.7.1 (2019-07-11)
+
+## 0.7.0 (2018-10-03)
+
+## 0.6.3 (2018-08-15)
+
+## 0.6.2 (2018-04-15)
+
+## 0.6.1 (2018-04-05)
+
+## 0.6.0 (2018-03-30)
+
+## 0.5.0 (2017-11-15)
+
+## 0.4.2 (2017-07-24)
+
+## 0.4.1 (2017-07-24)
+
+## 0.4.0 (2017-07-24)
+
+## 0.3.1 (2017-06-12)
+
+## 0.1.2 (2017-07-24)
+
+## 0.1.1 (2017-05-14)
+
+## 0.1.0 (2017-05-14)
+
+## 0.0.1 (2016-10-21)
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644 (file)
index 0000000..ca1c001
--- /dev/null
@@ -0,0 +1,55 @@
+# 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 are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2018"
+name = "hmac"
+version = "0.12.1"
+authors = ["RustCrypto Developers"]
+description = "Generic implementation of Hash-based Message Authentication Code (HMAC)"
+documentation = "https://docs.rs/hmac"
+readme = "README.md"
+keywords = ["crypto", "mac", "hmac", "digest"]
+categories = ["cryptography", "no-std"]
+license = "MIT OR Apache-2.0"
+repository = "https://github.com/RustCrypto/MACs"
+[package.metadata.docs.rs]
+all-features = true
+rustdoc-args = ["--cfg", "docsrs"]
+[dependencies.digest]
+version = "0.10.3"
+features = ["mac"]
+[dev-dependencies.digest]
+version = "0.10"
+features = ["dev"]
+
+[dev-dependencies.hex-literal]
+version = "0.2.2"
+
+[dev-dependencies.md-5]
+version = "0.10"
+default-features = false
+
+[dev-dependencies.sha-1]
+version = "0.10"
+default-features = false
+
+[dev-dependencies.sha2]
+version = "0.10"
+default-features = false
+
+[dev-dependencies.streebog]
+version = "0.10"
+default-features = false
+
+[features]
+reset = []
+std = ["digest/std"]
diff --git a/Cargo.toml.orig b/Cargo.toml.orig
new file mode 100644 (file)
index 0000000..d04c7cf
--- /dev/null
@@ -0,0 +1,35 @@
+[package]
+name = "hmac"
+version = "0.12.1" # Also update html_root_url in lib.rs when bumping this
+description = "Generic implementation of Hash-based Message Authentication Code (HMAC)"
+authors = ["RustCrypto Developers"]
+license = "MIT OR Apache-2.0"
+edition = "2018"
+readme = "README.md"
+documentation = "https://docs.rs/hmac"
+repository = "https://github.com/RustCrypto/MACs"
+keywords = ["crypto", "mac", "hmac", "digest"]
+categories = ["cryptography", "no-std"]
+
+# Hack to allow this crate to coexist with 2021 edition crates
+[workspace]
+members = ["."]
+
+[dependencies]
+digest = { version = "0.10.3", features = ["mac"] }
+
+[dev-dependencies]
+digest = { version = "0.10", features = ["dev"] }
+md-5 = { version = "0.10", default-features = false }
+sha-1 = { version = "0.10", default-features = false }
+sha2 = { version = "0.10", default-features = false }
+streebog = { version = "0.10", default-features = false }
+hex-literal = "0.2.2"
+
+[features]
+std = ["digest/std"]
+reset = [] # Enable ability to reset HMAC instances
+
+[package.metadata.docs.rs]
+all-features = true
+rustdoc-args = ["--cfg", "docsrs"]
diff --git a/LICENSE-APACHE b/LICENSE-APACHE
new file mode 100644 (file)
index 0000000..78173fa
--- /dev/null
@@ -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.
diff --git a/LICENSE-MIT b/LICENSE-MIT
new file mode 100644 (file)
index 0000000..8dcb85b
--- /dev/null
@@ -0,0 +1,25 @@
+Copyright (c) 2017 Artyom Pavlov
+
+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/README.md b/README.md
new file mode 100644 (file)
index 0000000..52d4ef9
--- /dev/null
+++ b/README.md
@@ -0,0 +1,53 @@
+# RustCrypto: HMAC
+
+[![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]
+
+Pure Rust implementation of the [Hash-based Message Authentication Code (HMAC)][1].
+
+[Documentation][docs-link]
+
+## Minimum Supported Rust Version
+
+Rust **1.41** or higher.
+
+Minimum supported Rust version can be changed in the future, but it will be
+done with a minor version bump.
+
+## SemVer Policy
+
+- All on-by-default features of this library are covered by SemVer
+- MSRV is considered exempt from SemVer as noted above
+
+## 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/hmac.svg
+[crate-link]: https://crates.io/crates/hmac
+[docs-image]: https://docs.rs/hmac/badge.svg
+[docs-link]: https://docs.rs/hmac/
+[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/260044-MACs
+
+[//]: # (general links)
+
+[1]: https://en.wikipedia.org/wiki/HMAC
diff --git a/src/lib.rs b/src/lib.rs
new file mode 100644 (file)
index 0000000..e79c068
--- /dev/null
@@ -0,0 +1,131 @@
+//! Generic implementation of Hash-based Message Authentication Code (HMAC).
+//!
+//! To use it you will need a cryptographic hash function implementation which
+//! implements the [`digest`] crate traits. You can find compatible crates
+//! (e.g. [`sha2`]) in the [`RustCrypto/hashes`] repository.
+//!
+//! This crate provides two HMAC implementation [`Hmac`] and [`SimpleHmac`].
+//! The first one is a buffered wrapper around block-level [`HmacCore`].
+//! Internally it uses efficient state representation, but works only with
+//! hash functions which expose block-level API and consume blocks eagerly
+//! (e.g. it will not work with the BLAKE2 family of  hash functions).
+//! On the other hand, [`SimpleHmac`] is a bit less efficient memory-wise,
+//! but works with all hash functions which implement the [`Digest`] trait.
+//!
+//! # Examples
+//! Let us demonstrate how to use HMAC using the SHA-256 hash function.
+//!
+//! In the following examples [`Hmac`] is interchangeable with [`SimpleHmac`].
+//!
+//! To get authentication code:
+//!
+//! ```rust
+//! use sha2::Sha256;
+//! use hmac::{Hmac, Mac};
+//! use hex_literal::hex;
+//!
+//! // Create alias for HMAC-SHA256
+//! type HmacSha256 = Hmac<Sha256>;
+//!
+//! let mut mac = HmacSha256::new_from_slice(b"my secret and secure key")
+//!     .expect("HMAC can take key of any size");
+//! mac.update(b"input message");
+//!
+//! // `result` has type `CtOutput` which is a thin wrapper around array of
+//! // bytes for providing constant time equality check
+//! let result = mac.finalize();
+//! // To get underlying array use `into_bytes`, but be careful, since
+//! // incorrect use of the code value may permit timing attacks which defeats
+//! // the security provided by the `CtOutput`
+//! let code_bytes = result.into_bytes();
+//! let expected = hex!("
+//!     97d2a569059bbcd8ead4444ff99071f4
+//!     c01d005bcefe0d3567e1be628e5fdcd9
+//! ");
+//! assert_eq!(code_bytes[..], expected[..]);
+//! ```
+//!
+//! To verify the message:
+//!
+//! ```rust
+//! # use sha2::Sha256;
+//! # use hmac::{Hmac, Mac};
+//! # use hex_literal::hex;
+//! # type HmacSha256 = Hmac<Sha256>;
+//! let mut mac = HmacSha256::new_from_slice(b"my secret and secure key")
+//!     .expect("HMAC can take key of any size");
+//!
+//! mac.update(b"input message");
+//!
+//! let code_bytes = hex!("
+//!     97d2a569059bbcd8ead4444ff99071f4
+//!     c01d005bcefe0d3567e1be628e5fdcd9
+//! ");
+//! // `verify_slice` will return `Ok(())` if code is correct, `Err(MacError)` otherwise
+//! mac.verify_slice(&code_bytes[..]).unwrap();
+//! ```
+//!
+//! # Block and input sizes
+//! Usually it is assumed that block size is larger than output size. Due to the
+//! generic nature of the implementation, this edge case must be handled as well
+//! to remove potential panic. This is done by truncating hash output to the hash
+//! block size if needed.
+//!
+//! [`digest`]: https://docs.rs/digest
+//! [`sha2`]: https://docs.rs/sha2
+//! [`RustCrypto/hashes`]: https://github.com/RustCrypto/hashes
+
+#![no_std]
+#![doc(
+    html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/26acc39f/logo.svg",
+    html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/26acc39f/logo.svg",
+    html_root_url = "https://docs.rs/hmac/0.12.1"
+)]
+#![forbid(unsafe_code)]
+#![cfg_attr(docsrs, feature(doc_cfg))]
+#![warn(missing_docs, rust_2018_idioms)]
+
+#[cfg(feature = "std")]
+extern crate std;
+
+pub use digest;
+pub use digest::Mac;
+
+use digest::{
+    core_api::{Block, BlockSizeUser},
+    Digest,
+};
+
+mod optim;
+mod simple;
+
+pub use optim::{Hmac, HmacCore};
+pub use simple::SimpleHmac;
+
+const IPAD: u8 = 0x36;
+const OPAD: u8 = 0x5C;
+
+fn get_der_key<D: Digest + BlockSizeUser>(key: &[u8]) -> Block<D> {
+    let mut der_key = Block::<D>::default();
+    // The key that HMAC processes must be the same as the block size of the
+    // underlying hash function. If the provided key is smaller than that,
+    // we just pad it with zeros. If its larger, we hash it and then pad it
+    // with zeros.
+    if key.len() <= der_key.len() {
+        der_key[..key.len()].copy_from_slice(key);
+    } else {
+        let hash = D::digest(key);
+        // All commonly used hash functions have block size bigger
+        // than output hash size, but to be extra rigorous we
+        // handle the potential uncommon cases as well.
+        // The condition is calcualted at compile time, so this
+        // branch gets removed from the final binary.
+        if hash.len() <= der_key.len() {
+            der_key[..hash.len()].copy_from_slice(&hash);
+        } else {
+            let n = der_key.len();
+            der_key.copy_from_slice(&hash[..n]);
+        }
+    }
+    der_key
+}
diff --git a/src/optim.rs b/src/optim.rs
new file mode 100644 (file)
index 0000000..32d6277
--- /dev/null
@@ -0,0 +1,280 @@
+use super::{get_der_key, IPAD, OPAD};
+use core::{fmt, slice};
+#[cfg(feature = "reset")]
+use digest::Reset;
+use digest::{
+    block_buffer::Eager,
+    core_api::{
+        AlgorithmName, Block, BlockSizeUser, Buffer, BufferKindUser, CoreProxy, CoreWrapper,
+        FixedOutputCore, OutputSizeUser, UpdateCore,
+    },
+    crypto_common::{Key, KeySizeUser},
+    generic_array::typenum::{IsLess, Le, NonZero, U256},
+    HashMarker, InvalidLength, KeyInit, MacMarker, Output,
+};
+
+/// Generic HMAC instance.
+pub type Hmac<D> = CoreWrapper<HmacCore<D>>;
+
+/// Generic core HMAC instance, which operates over blocks.
+pub struct HmacCore<D>
+where
+    D: CoreProxy,
+    D::Core: HashMarker
+        + UpdateCore
+        + FixedOutputCore
+        + BufferKindUser<BufferKind = Eager>
+        + Default
+        + Clone,
+    <D::Core as BlockSizeUser>::BlockSize: IsLess<U256>,
+    Le<<D::Core as BlockSizeUser>::BlockSize, U256>: NonZero,
+{
+    digest: D::Core,
+    opad_digest: D::Core,
+    #[cfg(feature = "reset")]
+    ipad_digest: D::Core,
+}
+
+impl<D> Clone for HmacCore<D>
+where
+    D: CoreProxy,
+    D::Core: HashMarker
+        + UpdateCore
+        + FixedOutputCore
+        + BufferKindUser<BufferKind = Eager>
+        + Default
+        + Clone,
+    <D::Core as BlockSizeUser>::BlockSize: IsLess<U256>,
+    Le<<D::Core as BlockSizeUser>::BlockSize, U256>: NonZero,
+{
+    fn clone(&self) -> Self {
+        Self {
+            digest: self.digest.clone(),
+            opad_digest: self.opad_digest.clone(),
+            #[cfg(feature = "reset")]
+            ipad_digest: self.ipad_digest.clone(),
+        }
+    }
+}
+
+impl<D> MacMarker for HmacCore<D>
+where
+    D: CoreProxy,
+    D::Core: HashMarker
+        + UpdateCore
+        + FixedOutputCore
+        + BufferKindUser<BufferKind = Eager>
+        + Default
+        + Clone,
+    <D::Core as BlockSizeUser>::BlockSize: IsLess<U256>,
+    Le<<D::Core as BlockSizeUser>::BlockSize, U256>: NonZero,
+{
+}
+
+impl<D> BufferKindUser for HmacCore<D>
+where
+    D: CoreProxy,
+    D::Core: HashMarker
+        + UpdateCore
+        + FixedOutputCore
+        + BufferKindUser<BufferKind = Eager>
+        + Default
+        + Clone,
+    <D::Core as BlockSizeUser>::BlockSize: IsLess<U256>,
+    Le<<D::Core as BlockSizeUser>::BlockSize, U256>: NonZero,
+{
+    type BufferKind = Eager;
+}
+
+impl<D> KeySizeUser for HmacCore<D>
+where
+    D: CoreProxy,
+    D::Core: HashMarker
+        + UpdateCore
+        + FixedOutputCore
+        + BufferKindUser<BufferKind = Eager>
+        + Default
+        + Clone,
+    <D::Core as BlockSizeUser>::BlockSize: IsLess<U256>,
+    Le<<D::Core as BlockSizeUser>::BlockSize, U256>: NonZero,
+{
+    type KeySize = <<D as CoreProxy>::Core as BlockSizeUser>::BlockSize;
+}
+
+impl<D> BlockSizeUser for HmacCore<D>
+where
+    D: CoreProxy,
+    D::Core: HashMarker
+        + UpdateCore
+        + FixedOutputCore
+        + BufferKindUser<BufferKind = Eager>
+        + Default
+        + Clone,
+    <D::Core as BlockSizeUser>::BlockSize: IsLess<U256>,
+    Le<<D::Core as BlockSizeUser>::BlockSize, U256>: NonZero,
+{
+    type BlockSize = <<D as CoreProxy>::Core as BlockSizeUser>::BlockSize;
+}
+
+impl<D> OutputSizeUser for HmacCore<D>
+where
+    D: CoreProxy,
+    D::Core: HashMarker
+        + UpdateCore
+        + FixedOutputCore
+        + BufferKindUser<BufferKind = Eager>
+        + Default
+        + Clone,
+    <D::Core as BlockSizeUser>::BlockSize: IsLess<U256>,
+    Le<<D::Core as BlockSizeUser>::BlockSize, U256>: NonZero,
+{
+    type OutputSize = <<D as CoreProxy>::Core as OutputSizeUser>::OutputSize;
+}
+
+impl<D> KeyInit for HmacCore<D>
+where
+    D: CoreProxy,
+    D::Core: HashMarker
+        + UpdateCore
+        + FixedOutputCore
+        + BufferKindUser<BufferKind = Eager>
+        + Default
+        + Clone,
+    <D::Core as BlockSizeUser>::BlockSize: IsLess<U256>,
+    Le<<D::Core as BlockSizeUser>::BlockSize, U256>: NonZero,
+{
+    #[inline(always)]
+    fn new(key: &Key<Self>) -> Self {
+        Self::new_from_slice(key.as_slice()).unwrap()
+    }
+
+    #[inline(always)]
+    fn new_from_slice(key: &[u8]) -> Result<Self, InvalidLength> {
+        let mut buf = get_der_key::<CoreWrapper<D::Core>>(key);
+        for b in buf.iter_mut() {
+            *b ^= IPAD;
+        }
+        let mut digest = D::Core::default();
+        digest.update_blocks(slice::from_ref(&buf));
+
+        for b in buf.iter_mut() {
+            *b ^= IPAD ^ OPAD;
+        }
+
+        let mut opad_digest = D::Core::default();
+        opad_digest.update_blocks(slice::from_ref(&buf));
+
+        Ok(Self {
+            #[cfg(feature = "reset")]
+            ipad_digest: digest.clone(),
+            opad_digest,
+            digest,
+        })
+    }
+}
+
+impl<D> UpdateCore for HmacCore<D>
+where
+    D: CoreProxy,
+    D::Core: HashMarker
+        + UpdateCore
+        + FixedOutputCore
+        + BufferKindUser<BufferKind = Eager>
+        + Default
+        + Clone,
+    <D::Core as BlockSizeUser>::BlockSize: IsLess<U256>,
+    Le<<D::Core as BlockSizeUser>::BlockSize, U256>: NonZero,
+{
+    #[inline(always)]
+    fn update_blocks(&mut self, blocks: &[Block<Self>]) {
+        self.digest.update_blocks(blocks);
+    }
+}
+
+impl<D> FixedOutputCore for HmacCore<D>
+where
+    D: CoreProxy,
+    D::Core: HashMarker
+        + UpdateCore
+        + FixedOutputCore
+        + BufferKindUser<BufferKind = Eager>
+        + Default
+        + Clone,
+    <D::Core as BlockSizeUser>::BlockSize: IsLess<U256>,
+    Le<<D::Core as BlockSizeUser>::BlockSize, U256>: NonZero,
+{
+    #[inline(always)]
+    fn finalize_fixed_core(&mut self, buffer: &mut Buffer<Self>, out: &mut Output<Self>) {
+        let mut hash = Output::<D::Core>::default();
+        self.digest.finalize_fixed_core(buffer, &mut hash);
+        // finalize_fixed_core should reset the buffer as well, but
+        // to be extra safe we reset it explicitly again.
+        buffer.reset();
+        #[cfg(not(feature = "reset"))]
+        let h = &mut self.opad_digest;
+        #[cfg(feature = "reset")]
+        let mut h = self.opad_digest.clone();
+        buffer.digest_blocks(&hash, |b| h.update_blocks(b));
+        h.finalize_fixed_core(buffer, out);
+    }
+}
+
+#[cfg(feature = "reset")]
+#[cfg_attr(docsrs, doc(cfg(feature = "reset")))]
+impl<D> Reset for HmacCore<D>
+where
+    D: CoreProxy,
+    D::Core: HashMarker
+        + UpdateCore
+        + FixedOutputCore
+        + BufferKindUser<BufferKind = Eager>
+        + Default
+        + Clone,
+    <D::Core as BlockSizeUser>::BlockSize: IsLess<U256>,
+    Le<<D::Core as BlockSizeUser>::BlockSize, U256>: NonZero,
+{
+    #[inline(always)]
+    fn reset(&mut self) {
+        self.digest = self.ipad_digest.clone();
+    }
+}
+
+impl<D> AlgorithmName for HmacCore<D>
+where
+    D: CoreProxy,
+    D::Core: HashMarker
+        + AlgorithmName
+        + UpdateCore
+        + FixedOutputCore
+        + BufferKindUser<BufferKind = Eager>
+        + Default
+        + Clone,
+    <D::Core as BlockSizeUser>::BlockSize: IsLess<U256>,
+    Le<<D::Core as BlockSizeUser>::BlockSize, U256>: NonZero,
+{
+    fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.write_str("Hmac<")?;
+        <D::Core as AlgorithmName>::write_alg_name(f)?;
+        f.write_str(">")
+    }
+}
+
+impl<D> fmt::Debug for HmacCore<D>
+where
+    D: CoreProxy,
+    D::Core: HashMarker
+        + AlgorithmName
+        + UpdateCore
+        + FixedOutputCore
+        + BufferKindUser<BufferKind = Eager>
+        + Default
+        + Clone,
+    <D::Core as BlockSizeUser>::BlockSize: IsLess<U256>,
+    Le<<D::Core as BlockSizeUser>::BlockSize, U256>: NonZero,
+{
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.write_str("HmacCore<")?;
+        <D::Core as AlgorithmName>::write_alg_name(f)?;
+        f.write_str("> { ... }")
+    }
+}
diff --git a/src/simple.rs b/src/simple.rs
new file mode 100644 (file)
index 0000000..e28c4c3
--- /dev/null
@@ -0,0 +1,106 @@
+use super::{get_der_key, IPAD, OPAD};
+use core::fmt;
+use digest::{
+    crypto_common::{Block, BlockSizeUser, InvalidLength, Key, KeySizeUser},
+    Digest, FixedOutput, KeyInit, MacMarker, Output, OutputSizeUser, Update,
+};
+#[cfg(feature = "reset")]
+use digest::{FixedOutputReset, Reset};
+
+/// Simplified HMAC instance able to operate over hash functions
+/// which do not expose block-level API and hash functions which
+/// process blocks lazily (e.g. BLAKE2).
+#[derive(Clone)]
+pub struct SimpleHmac<D: Digest + BlockSizeUser> {
+    digest: D,
+    opad_key: Block<D>,
+    #[cfg(feature = "reset")]
+    ipad_key: Block<D>,
+}
+
+impl<D: Digest + BlockSizeUser> KeySizeUser for SimpleHmac<D> {
+    type KeySize = D::BlockSize;
+}
+
+impl<D: Digest + BlockSizeUser> MacMarker for SimpleHmac<D> {}
+
+impl<D: Digest + BlockSizeUser> KeyInit for SimpleHmac<D> {
+    fn new(key: &Key<Self>) -> Self {
+        Self::new_from_slice(key.as_slice()).unwrap()
+    }
+
+    #[inline]
+    fn new_from_slice(key: &[u8]) -> Result<Self, InvalidLength> {
+        let der_key = get_der_key::<D>(key);
+        let mut ipad_key = der_key.clone();
+        for b in ipad_key.iter_mut() {
+            *b ^= IPAD;
+        }
+        let mut digest = D::new();
+        digest.update(&ipad_key);
+
+        let mut opad_key = der_key;
+        for b in opad_key.iter_mut() {
+            *b ^= OPAD;
+        }
+
+        Ok(Self {
+            digest,
+            opad_key,
+            #[cfg(feature = "reset")]
+            ipad_key,
+        })
+    }
+}
+
+impl<D: Digest + BlockSizeUser> Update for SimpleHmac<D> {
+    #[inline(always)]
+    fn update(&mut self, data: &[u8]) {
+        self.digest.update(data);
+    }
+}
+
+impl<D: Digest + BlockSizeUser> OutputSizeUser for SimpleHmac<D> {
+    type OutputSize = D::OutputSize;
+}
+
+impl<D: Digest + BlockSizeUser> FixedOutput for SimpleHmac<D> {
+    fn finalize_into(self, out: &mut Output<Self>) {
+        let mut h = D::new();
+        h.update(&self.opad_key);
+        h.update(&self.digest.finalize());
+        h.finalize_into(out);
+    }
+}
+
+impl<D: Digest + BlockSizeUser + fmt::Debug> fmt::Debug for SimpleHmac<D> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_struct("SimpleHmac")
+            .field("digest", &self.digest)
+            // TODO: replace with `finish_non_exhaustive` on MSRV
+            // bump to 1.53
+            .field("..", &"..")
+            .finish()
+    }
+}
+
+#[cfg(feature = "reset")]
+#[cfg_attr(docsrs, doc(cfg(feature = "reset")))]
+impl<D: Digest + BlockSizeUser + Reset> Reset for SimpleHmac<D> {
+    fn reset(&mut self) {
+        Reset::reset(&mut self.digest);
+        self.digest.update(&self.ipad_key);
+    }
+}
+
+#[cfg(feature = "reset")]
+#[cfg_attr(docsrs, doc(cfg(feature = "reset")))]
+impl<D: Digest + BlockSizeUser + FixedOutputReset> FixedOutputReset for SimpleHmac<D> {
+    fn finalize_into_reset(&mut self, out: &mut Output<Self>) {
+        let mut h = D::new();
+        Update::update(&mut h, &self.opad_key);
+        Update::update(&mut h, &self.digest.finalize_reset());
+        Update::update(&mut self.digest, &self.ipad_key);
+        Digest::finalize_into(h, out);
+    }
+}
diff --git a/tests/data/md5.blb b/tests/data/md5.blb
new file mode 100644 (file)
index 0000000..731a0ae
Binary files /dev/null and b/tests/data/md5.blb differ
diff --git a/tests/data/sha224.blb b/tests/data/sha224.blb
new file mode 100644 (file)
index 0000000..dabb20b
Binary files /dev/null and b/tests/data/sha224.blb differ
diff --git a/tests/data/sha256.blb b/tests/data/sha256.blb
new file mode 100644 (file)
index 0000000..6b5b288
Binary files /dev/null and b/tests/data/sha256.blb differ
diff --git a/tests/data/sha384.blb b/tests/data/sha384.blb
new file mode 100644 (file)
index 0000000..d5cddb3
Binary files /dev/null and b/tests/data/sha384.blb differ
diff --git a/tests/data/sha512.blb b/tests/data/sha512.blb
new file mode 100644 (file)
index 0000000..b79ae49
Binary files /dev/null and b/tests/data/sha512.blb differ
diff --git a/tests/data/streebog256.blb b/tests/data/streebog256.blb
new file mode 100644 (file)
index 0000000..99d9722
Binary files /dev/null and b/tests/data/streebog256.blb differ
diff --git a/tests/data/streebog512.blb b/tests/data/streebog512.blb
new file mode 100644 (file)
index 0000000..8f0f151
Binary files /dev/null and b/tests/data/streebog512.blb differ
diff --git a/tests/data/wycheproof-sha1.blb b/tests/data/wycheproof-sha1.blb
new file mode 100644 (file)
index 0000000..a4f8f43
Binary files /dev/null and b/tests/data/wycheproof-sha1.blb differ
diff --git a/tests/data/wycheproof-sha256.blb b/tests/data/wycheproof-sha256.blb
new file mode 100644 (file)
index 0000000..62f1d35
Binary files /dev/null and b/tests/data/wycheproof-sha256.blb differ
diff --git a/tests/data/wycheproof-sha384.blb b/tests/data/wycheproof-sha384.blb
new file mode 100644 (file)
index 0000000..69a7874
Binary files /dev/null and b/tests/data/wycheproof-sha384.blb differ
diff --git a/tests/data/wycheproof-sha512.blb b/tests/data/wycheproof-sha512.blb
new file mode 100644 (file)
index 0000000..e061fd5
Binary files /dev/null and b/tests/data/wycheproof-sha512.blb differ
diff --git a/tests/mod.rs b/tests/mod.rs
new file mode 100644 (file)
index 0000000..d1798c8
--- /dev/null
@@ -0,0 +1,88 @@
+#[cfg(not(feature = "reset"))]
+use digest::new_mac_test as test;
+#[cfg(feature = "reset")]
+use digest::new_resettable_mac_test as test;
+use hmac::{Hmac, SimpleHmac};
+use sha1::Sha1;
+use sha2::{Sha224, Sha256, Sha384, Sha512};
+use streebog::{Streebog256, Streebog512};
+
+// Test vectors from RFC 2104, plus wiki test
+test!(hmac_md5_rfc2104, "md5", Hmac<md5::Md5>);
+test!(hmac_md5_rfc2104_simple, "md5", SimpleHmac<md5::Md5>);
+
+// Test vectors from RFC 4231
+test!(hmac_sha224_rfc4231, "sha224", Hmac<Sha224>);
+test!(hmac_sha256_rfc4231, "sha256", Hmac<Sha256>);
+test!(hmac_sha384_rfc4231, "sha384", Hmac<Sha384>);
+test!(hmac_sha512_rfc4231, "sha512", Hmac<Sha512>);
+test!(hmac_sha224_rfc4231_simple, "sha224", SimpleHmac<Sha224>);
+test!(hmac_sha256_rfc4231_simple, "sha256", SimpleHmac<Sha256>);
+test!(hmac_sha384_rfc4231_simple, "sha384", SimpleHmac<Sha384>);
+test!(hmac_sha512_rfc4231_simple, "sha512", SimpleHmac<Sha512>);
+
+// Test vectors from R 50.1.113-2016:
+// https://tc26.ru/standard/rs/Р 50.1.113-2016.pdf
+test!(hmac_streebog256, "streebog256", Hmac<Streebog256>);
+test!(hmac_streebog512, "streebog512", Hmac<Streebog512>);
+test!(
+    hmac_streebog256_simple,
+    "streebog256",
+    SimpleHmac<Streebog256>
+);
+test!(
+    hmac_streebog512_simple,
+    "streebog512",
+    SimpleHmac<Streebog512>
+);
+
+// Tests from Project Wycheproof:
+// https://github.com/google/wycheproof
+test!(
+    hmac_sha1_wycheproof,
+    "wycheproof-sha1",
+    Hmac<Sha1>,
+    trunc_left,
+);
+test!(
+    hmac_sha256_wycheproof,
+    "wycheproof-sha256",
+    Hmac<Sha256>,
+    trunc_left,
+);
+test!(
+    hmac_sha384_wycheproof,
+    "wycheproof-sha384",
+    Hmac<Sha384>,
+    trunc_left,
+);
+test!(
+    hmac_sha512_wycheproof,
+    "wycheproof-sha512",
+    Hmac<Sha512>,
+    trunc_left,
+);
+test!(
+    hmac_sha1_wycheproof_simple,
+    "wycheproof-sha1",
+    SimpleHmac<Sha1>,
+    trunc_left,
+);
+test!(
+    hmac_sha256_wycheproof_simple,
+    "wycheproof-sha256",
+    SimpleHmac<Sha256>,
+    trunc_left,
+);
+test!(
+    hmac_sha384_wycheproof_simple,
+    "wycheproof-sha384",
+    SimpleHmac<Sha384>,
+    trunc_left,
+);
+test!(
+    hmac_sha512_wycheproof_simple,
+    "wycheproof-sha512",
+    SimpleHmac<Sha512>,
+    trunc_left,
+);