diff --git a/.github/workflows/cshake.yml b/.github/workflows/cshake.yml new file mode 100644 index 000000000..a98c1039a --- /dev/null +++ b/.github/workflows/cshake.yml @@ -0,0 +1,72 @@ +name: cshake + +on: + pull_request: + paths: + - ".github/workflows/cshake.yml" + - "cshake/**" + - "Cargo.*" + push: + branches: master + +defaults: + run: + working-directory: cshake + +env: + CARGO_INCREMENTAL: 0 + RUSTFLAGS: "-Dwarnings" + +# Cancels CI jobs when new commits are pushed to a PR branch +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + set-msrv: + uses: RustCrypto/actions/.github/workflows/set-msrv.yml@master + with: + msrv: 1.85.0 + + build: + needs: set-msrv + runs-on: ubuntu-latest + strategy: + matrix: + rust: + - ${{needs.set-msrv.outputs.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 }} + - uses: RustCrypto/actions/cargo-hack-install@master + - run: cargo hack build --target ${{ matrix.target }} --each-feature + + test: + needs: set-msrv + runs-on: ubuntu-latest + strategy: + matrix: + rust: + - ${{needs.set-msrv.outputs.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 + + minimal-versions: + uses: RustCrypto/actions/.github/workflows/minimal-versions.yml@master + with: + working-directory: ${{ github.workflow }} diff --git a/.github/workflows/turbo-shake.yml b/.github/workflows/turbo-shake.yml new file mode 100644 index 000000000..7080720cb --- /dev/null +++ b/.github/workflows/turbo-shake.yml @@ -0,0 +1,72 @@ +name: turbo-shake + +on: + pull_request: + paths: + - ".github/workflows/turbo-shake.yml" + - "turbo-shake/**" + - "Cargo.*" + push: + branches: master + +defaults: + run: + working-directory: turbo-shake + +env: + CARGO_INCREMENTAL: 0 + RUSTFLAGS: "-Dwarnings" + +# Cancels CI jobs when new commits are pushed to a PR branch +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + set-msrv: + uses: RustCrypto/actions/.github/workflows/set-msrv.yml@master + with: + msrv: 1.85.0 + + build: + needs: set-msrv + runs-on: ubuntu-latest + strategy: + matrix: + rust: + - ${{needs.set-msrv.outputs.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 }} + - uses: RustCrypto/actions/cargo-hack-install@master + - run: cargo hack build --target ${{ matrix.target }} --each-feature + + test: + needs: set-msrv + runs-on: ubuntu-latest + strategy: + matrix: + rust: + - ${{needs.set-msrv.outputs.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 + + minimal-versions: + uses: RustCrypto/actions/.github/workflows/minimal-versions.yml@master + with: + working-directory: ${{ github.workflow }} diff --git a/Cargo.lock b/Cargo.lock index 10d479676..ffff5c8f8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -112,6 +112,15 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "cshake" +version = "0.1.0" +dependencies = [ + "digest", + "hex-literal", + "keccak", +] + [[package]] name = "ctutils" version = "0.4.0" @@ -174,9 +183,9 @@ checksum = "e712f64ec3850b98572bffac52e2c6f282b29fe6c5fa6d42334b30be438d95c1" [[package]] name = "hybrid-array" -version = "0.4.8" +version = "0.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8655f91cd07f2b9d0c24137bd650fe69617773435ee5ec83022377777ce65ef1" +checksum = "3944cf8cf766b40e2a1a333ee5e9b563f854d5fa49d6a8ca2764e97c6eddb214" dependencies = [ "typenum", ] @@ -196,7 +205,7 @@ version = "0.4.0-rc.1" dependencies = [ "digest", "hex-literal", - "sha3", + "turbo-shake", ] [[package]] @@ -219,9 +228,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.183" +version = "0.2.184" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d" +checksum = "48f5d2a454e16a5ea0f4ced81bd44e4cfc7bd3a507b61887c99fd3538b28e4af" [[package]] name = "md-5" @@ -389,6 +398,15 @@ dependencies = [ "hex-literal", ] +[[package]] +name = "turbo-shake" +version = "0.1.0" +dependencies = [ + "digest", + "hex-literal", + "keccak", +] + [[package]] name = "typenum" version = "1.19.0" @@ -411,18 +429,18 @@ dependencies = [ [[package]] name = "zerocopy" -version = "0.8.47" +version = "0.8.48" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "efbb2a062be311f2ba113ce66f697a4dc589f85e78a4aea276200804cea0ed87" +checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.47" +version = "0.8.48" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0e8bc7269b54418e7aeeef514aa68f8690b8c0489a06b0136e5f57c4c5ccab89" +checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 2c7653ae8..355de2b6a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,7 @@ members = [ "bash-hash", "belt-hash", "blake2", + "cshake", "fsb", "gost94", "groestl", @@ -24,6 +25,7 @@ members = [ "sm3", "streebog", "tiger", + "turbo-shake", "whirlpool", ] @@ -32,5 +34,5 @@ opt-level = 2 [patch.crates-io] sha1 = { path = "sha1" } -sha3 = { path = "sha3" } +turbo-shake = { path = "turbo-shake" } whirlpool = { path = "whirlpool" } diff --git a/README.md b/README.md index 613199b44..b483b642a 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ easily used for bare-metal or WebAssembly programming by disabling default crate | [Bash] hash | [`bash‑hash`] | [![crates.io](https://img.shields.io/crates/v/bash-hash.svg)](https://crates.io/crates/bash-hash) | [![Documentation](https://docs.rs/bash-hash/badge.svg)](https://docs.rs/bash-hash) | 1.85 | :green_heart: | | [BelT] hash | [`belt‑hash`] | [![crates.io](https://img.shields.io/crates/v/belt-hash.svg)](https://crates.io/crates/belt-hash) | [![Documentation](https://docs.rs/belt-hash/badge.svg)](https://docs.rs/belt-hash) | 1.85 | :green_heart: | | [BLAKE2] | [`blake2`] | [![crates.io](https://img.shields.io/crates/v/blake2.svg)](https://crates.io/crates/blake2) | [![Documentation](https://docs.rs/blake2/badge.svg)](https://docs.rs/blake2) | 1.85 | :green_heart: | +| [cSHAKE] | [`cshake`] | [![crates.io](https://img.shields.io/crates/v/cshake.svg)](https://crates.io/crates/cshake) | [![Documentation](https://docs.rs/cshake/badge.svg)](https://docs.rs/cshake) | 1.85 | :green_heart: | | [FSB] | [`fsb`] | [![crates.io](https://img.shields.io/crates/v/fsb.svg)](https://crates.io/crates/fsb) | [![Documentation](https://docs.rs/fsb/badge.svg)](https://docs.rs/fsb) | 1.85 | :green_heart: | | [GOST R 34.11-94][GOST94] | [`gost94`] | [![crates.io](https://img.shields.io/crates/v/gost94.svg)](https://crates.io/crates/gost94) | [![Documentation](https://docs.rs/gost94/badge.svg)](https://docs.rs/gost94) | 1.85 | :yellow_heart: | | [Grøstl] (Groestl) | [`groestl`] | [![crates.io](https://img.shields.io/crates/v/groestl.svg)](https://crates.io/crates/groestl) | [![Documentation](https://docs.rs/groestl/badge.svg)](https://docs.rs/groestl) | 1.85 | :green_heart: | @@ -40,6 +41,7 @@ easily used for bare-metal or WebAssembly programming by disabling default crate | [SM3] (OSCCA GM/T 0004-2012) | [`sm3`] | [![crates.io](https://img.shields.io/crates/v/sm3.svg)](https://crates.io/crates/sm3) | [![Documentation](https://docs.rs/sm3/badge.svg)](https://docs.rs/sm3) | 1.85 | :green_heart: | | [Streebog] (GOST R 34.11-2012) | [`streebog`] | [![crates.io](https://img.shields.io/crates/v/streebog.svg)](https://crates.io/crates/streebog) | [![Documentation](https://docs.rs/streebog/badge.svg)](https://docs.rs/streebog) | 1.85 | :yellow_heart: | | [Tiger] | [`tiger`] | [![crates.io](https://img.shields.io/crates/v/tiger.svg)](https://crates.io/crates/tiger) | [![Documentation](https://docs.rs/tiger/badge.svg)](https://docs.rs/tiger) | 1.85 | :green_heart: | +| [TurboSHAKE] | [`turbo-shake`] | [![crates.io](https://img.shields.io/crates/v/turbo-shake.svg)](https://crates.io/crates/turbo-shake) | [![Documentation](https://docs.rs/turbo-shake/badge.svg)](https://docs.rs/turbo-shake) | 1.85 | :green_heart: | | [Whirlpool] | [`whirlpool`] | [![crates.io](https://img.shields.io/crates/v/whirlpool.svg)](https://crates.io/crates/whirlpool) | [![Documentation](https://docs.rs/whirlpool/badge.svg)](https://docs.rs/whirlpool) | 1.85 | :green_heart: | NOTE: the [`blake3`] crate implements the `digest` traits used by the rest of the hashes in this repository, but is maintained by the BLAKE3 team. @@ -94,6 +96,7 @@ Unless you explicitly state otherwise, any contribution intentionally submitted [`bash‑hash`]: ./bash-hash [`belt‑hash`]: ./belt-hash [`blake2`]: ./blake2 +[`cshake`]: ./cshake [`fsb`]: ./fsb [`gost94`]: ./gost94 [`groestl`]: ./groestl @@ -113,6 +116,7 @@ Unless you explicitly state otherwise, any contribution intentionally submitted [`sm3`]: ./sm3 [`streebog`]: ./streebog [`tiger`]: ./tiger +[`turbo-shake`]: ./turbo-shake [`whirlpool`]: ./whirlpool [//]: # (footnotes) @@ -138,6 +142,7 @@ Unless you explicitly state otherwise, any contribution intentionally submitted [Bash]: https://apmi.bsu.by/assets/files/std/bash-spec241.pdf [BelT]: https://ru.wikipedia.org/wiki/BelT [BLAKE2]: https://en.wikipedia.org/wiki/BLAKE_(hash_function)#BLAKE2 +[cSHAKE]: https://csrc.nist.gov/pubs/sp/800/185/final [FSB]: https://en.wikipedia.org/wiki/Fast_syndrome-based_hash [GOST94]: https://en.wikipedia.org/wiki/GOST_(hash_function) [Grøstl]: https://en.wikipedia.org/wiki/Grøstl @@ -158,3 +163,4 @@ Unless you explicitly state otherwise, any contribution intentionally submitted [Streebog]: https://en.wikipedia.org/wiki/Streebog [Whirlpool]: https://en.wikipedia.org/wiki/Whirlpool_(cryptography) [Tiger]: http://www.cs.technion.ac.il/~biham/Reports/Tiger/tiger/tiger.html +[TurboSHAKE]: https://keccak.team/turboshake.html diff --git a/cshake/CHANGELOG.md b/cshake/CHANGELOG.md new file mode 100644 index 000000000..ff7d452c0 --- /dev/null +++ b/cshake/CHANGELOG.md @@ -0,0 +1,11 @@ +# 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.1.0 (UNRELEASED) +- Initial release with implementation moved from the `sha3` crate ([#815]) + +[#815]: https://github.com/RustCrypto/hashes/pull/815 diff --git a/cshake/Cargo.toml b/cshake/Cargo.toml new file mode 100644 index 000000000..4f56ee853 --- /dev/null +++ b/cshake/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "cshake" +version = "0.1.0" +authors = ["RustCrypto Developers"] +edition = "2024" +rust-version = "1.85" +documentation = "https://docs.rs/sha3" +readme = "README.md" +repository = "https://github.com/RustCrypto/hashes" +license = "MIT OR Apache-2.0" +keywords = ["sha3", "keccak", "hash", "xof", "digest"] +categories = ["cryptography", "no-std"] +description = "Implementation of the cSHAKE family of extendable-output functions (XOFs)" + +[dependencies] +digest = "0.11" +keccak = "0.2" + +[dev-dependencies] +digest = { version = "0.11", features = ["dev"] } +hex-literal = "1" + +[features] +default = ["alloc", "oid"] +alloc = ["digest/alloc"] +oid = ["digest/oid"] # Enable OID support. +zeroize = ["digest/zeroize"] + +[package.metadata.docs.rs] +all-features = true diff --git a/cshake/LICENSE-APACHE b/cshake/LICENSE-APACHE new file mode 100644 index 000000000..78173fa2e --- /dev/null +++ b/cshake/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. diff --git a/cshake/LICENSE-MIT b/cshake/LICENSE-MIT new file mode 100644 index 000000000..4697b3e72 --- /dev/null +++ b/cshake/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2026 The RustCrypto Project 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/cshake/README.md b/cshake/README.md new file mode 100644 index 000000000..89eab0447 --- /dev/null +++ b/cshake/README.md @@ -0,0 +1,76 @@ +# RustCrypto: cSHAKE + +[![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] + +Implementation of the cSHAKE family of extendable-output functions (XOFs) +defined in the NIST [SHA-3 Derived Functions]. + +## Examples + +cSHAKE functions have an extendable output, so finalization methods return +XOF reader from which results of arbitrary length can be read. + +```rust +use cshake::CShake128; +use cshake::digest::{CustomizedInit, Update, ExtendableOutput, XofReader}; +use hex_literal::hex; + +let mut hasher = CShake128::default(); +hasher.update(b"abc"); +let mut reader = hasher.finalize_xof(); +let mut buf = [0u8; 10]; +reader.read(&mut buf); +assert_eq!(buf, hex!("5881092dd818bf5cf8a3")); +reader.read(&mut buf); +assert_eq!(buf, hex!("ddb793fbcba74097d5c5")); + +// With customization string +let mut hasher = CShake128::new_customized(b"my customization string"); +hasher.update(b"abc"); +let mut reader = hasher.finalize_xof(); +let mut buf = [0u8; 10]; +reader.read(&mut buf); +assert_eq!(buf, hex!("a296533c8d5753bf3421")); +reader.read(&mut buf); +assert_eq!(buf, hex!("124e8eb79262233170ce")); +``` + +See the [`digest`] crate docs for additional examples. + +## License + +The crate is 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/sha3.svg +[crate-link]: https://crates.io/crates/sha3 +[docs-image]: https://docs.rs/sha3/badge.svg +[docs-link]: https://docs.rs/sha3/ +[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/260041-hashes +[build-image]: https://github.com/RustCrypto/hashes/actions/workflows/sha3.yml/badge.svg?branch=master +[build-link]: https://github.com/RustCrypto/hashes/actions/workflows/sha3.yml?query=branch:master + +[//]: # (general links) + +[SHA-3 Derived Functions]: https://csrc.nist.gov/pubs/sp/800/185/final +[`digest`]: https://docs.rs/digest diff --git a/cshake/benches/mod.rs b/cshake/benches/mod.rs new file mode 100644 index 000000000..f44d613be --- /dev/null +++ b/cshake/benches/mod.rs @@ -0,0 +1,21 @@ +#![feature(test)] +extern crate test; + +use digest::bench_update; +use test::Bencher; + +bench_update!( + cshake::CShake128::default(); + cshake128_10 10; + cshake128_100 100; + cshake128_1000 1000; + cshake128_10000 10000; +); + +bench_update!( + cshake::CShake256::default(); + cshake256_10 10; + cshake256_100 100; + cshake256_1000 1000; + cshake256_10000 10000; +); diff --git a/cshake/src/lib.rs b/cshake/src/lib.rs new file mode 100644 index 000000000..58fc2bb4b --- /dev/null +++ b/cshake/src/lib.rs @@ -0,0 +1,317 @@ +#![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))] +#![forbid(unsafe_code)] +#![warn(missing_docs, missing_debug_implementations)] +#![warn(unreachable_pub)] + +pub use digest; + +use core::fmt; +use digest::{ + CollisionResistance, CustomizedInit, ExtendableOutput, ExtendableOutputReset, HashMarker, + Reset, Update, XofReader, + array::Array, + block_api::{AlgorithmName, BlockSizeUser}, + block_buffer::{BlockSizes, EagerBuffer, ReadBuffer}, + consts::{U16, U32, U136, U168}, +}; +use keccak::{Keccak, State1600}; + +/// cSHAKE128 hasher. +pub type CShake128 = CShake; +/// cSHAKE256 hasher. +pub type CShake256 = CShake; + +/// cSHAKE hasher generic over rate. +/// +/// Rate MUST be either [`U168`] or [`U136`] for cSHAKE128 and cSHAKE256 respectively. +#[derive(Clone)] +pub struct CShake { + state: State1600, + initial_state: State1600, + keccak: Keccak, + buffer: EagerBuffer, +} + +impl Default for CShake { + #[inline] + fn default() -> Self { + const { + assert!(Rate::USIZE == 168 || Rate::USIZE == 136, "unsupported rate"); + } + Self { + state: Default::default(), + initial_state: Default::default(), + keccak: Keccak::new(), + buffer: Default::default(), + } + } +} + +impl CShake { + /// Creates a new cSHAKE instance with the given function name and customization. + /// + /// Note that the function name is intended for use by NIST and should only be set to + /// values defined by NIST. You probably don't need to use this function. + pub fn new_with_function_name(function_name: &[u8], customization: &[u8]) -> Self { + let mut state = Self::default(); + + if function_name.is_empty() && customization.is_empty() { + return state; + } + + #[inline(always)] + fn left_encode(val: u64, b: &mut [u8; 9]) -> &[u8] { + b[1..].copy_from_slice(&val.to_be_bytes()); + let i = b[1..8].iter().take_while(|&&a| a == 0).count(); + b[i] = (8 - i) as u8; + &b[i..] + } + + state.keccak.with_f1600(|f1600| { + let mut buffer: EagerBuffer = Default::default(); + let state = &mut state.state; + let mut b = [0u8; 9]; + + buffer.digest_blocks(left_encode(Rate::U64, &mut b), |blocks| { + update_blocks(f1600, state, blocks) + }); + + let mut encode_str = |str: &[u8]| { + let str_bits_len = 8 * u64::try_from(str.len()) + .expect("in practice strings can not be longer than u64::MAX"); + let encoded_len = left_encode(str_bits_len, &mut b); + buffer.digest_blocks(encoded_len, |blocks| update_blocks(f1600, state, blocks)); + buffer.digest_blocks(str, |blocks| update_blocks(f1600, state, blocks)); + }; + + encode_str(function_name); + encode_str(customization); + + update_blocks(f1600, state, &[buffer.pad_with_zeros()]) + }); + + state.initial_state = state.state; + state + } +} + +impl CustomizedInit for CShake { + #[inline] + fn new_customized(customization: &[u8]) -> Self { + Self::new_with_function_name(&[], customization) + } +} + +impl HashMarker for CShake {} + +impl BlockSizeUser for CShake { + type BlockSize = Rate; +} + +impl Update for CShake { + fn update(&mut self, data: &[u8]) { + let Self { + state, + buffer, + keccak, + .. + } = self; + + keccak.with_f1600(|f1600| { + buffer.digest_blocks(data, |blocks| update_blocks(f1600, state, blocks)); + }); + } +} + +impl Reset for CShake { + #[inline] + fn reset(&mut self) { + self.state = self.initial_state; + self.buffer.reset(); + } +} + +impl CShake { + fn finalize_dirty(&mut self) { + let Self { + state, + keccak, + buffer, + initial_state, + } = self; + + const SHAKE_PAD: u8 = 0x1f; + const CSHAKE_PAD: u8 = 0x04; + + let pos = buffer.get_pos(); + let mut block = buffer.pad_with_zeros(); + let pad = if initial_state.iter().all(|&b| b == 0) { + SHAKE_PAD + } else { + CSHAKE_PAD + }; + block[pos] = pad; + let n = block.len(); + block[n - 1] |= 0x80; + + keccak.with_f1600(|f1600| { + xor_block(state, &block); + f1600(state); + }); + } +} + +impl ExtendableOutput for CShake { + type Reader = CShakeReader; + + #[inline] + fn finalize_xof(mut self) -> Self::Reader { + self.finalize_dirty(); + Self::Reader { + state: self.state, + keccak: self.keccak, + buffer: Default::default(), + } + } +} + +impl ExtendableOutputReset for CShake { + #[inline] + fn finalize_xof_reset(&mut self) -> Self::Reader { + self.finalize_dirty(); + let reader = Self::Reader { + state: self.state, + keccak: self.keccak, + buffer: Default::default(), + }; + self.reset(); + reader + } +} + +impl AlgorithmName for CShake { + fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result { + let alg_name = match Rate::USIZE { + 168 => "cSHAKE128", + 136 => "cSHAKE256", + _ => unreachable!(), + }; + f.write_str(alg_name) + } +} + +impl fmt::Debug for CShake { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let debug_str = match Rate::USIZE { + 168 => "CShake128 { ... }", + 136 => "CShake256 { ... }", + _ => unreachable!(), + }; + f.write_str(debug_str) + } +} + +impl Drop for CShake { + fn drop(&mut self) { + #[cfg(feature = "zeroize")] + { + use digest::zeroize::Zeroize; + self.state.zeroize(); + self.initial_state.zeroize(); + // self.buffer is zeroized by its `Drop` + } + } +} + +#[cfg(feature = "zeroize")] +impl digest::zeroize::ZeroizeOnDrop for CShake {} + +/// Generic cSHAKE XOF reader +#[derive(Clone)] +pub struct CShakeReader { + state: State1600, + keccak: Keccak, + buffer: ReadBuffer, +} + +impl XofReader for CShakeReader { + #[inline] + fn read(&mut self, buf: &mut [u8]) { + let Self { + state, + keccak, + buffer, + } = self; + + buffer.read(buf, |block| { + let mut chunks = block.chunks_exact_mut(8); + for (src, dst) in state.iter().zip(&mut chunks) { + dst.copy_from_slice(&src.to_le_bytes()); + } + assert!( + chunks.into_remainder().is_empty(), + "rate is either 136 or 168", + ); + keccak.with_f1600(|f1600| f1600(state)); + }); + } +} + +impl fmt::Debug for CShakeReader { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let debug_str = match Rate::USIZE { + 168 => "TurboShakeReader128 { ... }", + 136 => "TurboShakeReader256 { ... }", + _ => unreachable!(), + }; + f.write_str(debug_str) + } +} + +impl Drop for CShakeReader { + fn drop(&mut self) { + #[cfg(feature = "zeroize")] + { + use digest::zeroize::Zeroize; + self.state.zeroize(); + // self.buffer is zeroized by its `Drop` + } + } +} + +// https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf#[{"num":68,"gen":0},{"name":"XYZ"},108,440,null] +impl CollisionResistance for CShake128 { + type CollisionResistance = U16; +} +impl CollisionResistance for CShake256 { + type CollisionResistance = U32; +} + +fn xor_block(state: &mut State1600, block: &[u8]) { + assert!(size_of_val(block) < size_of_val(state)); + + let mut chunks = block.chunks_exact(8); + for (s, chunk) in state.iter_mut().zip(&mut chunks) { + *s ^= u64::from_le_bytes(chunk.try_into().unwrap()); + } + + let rem = chunks.remainder(); + assert!(rem.is_empty(), "block size is equal to 136 or 168"); +} + +fn update_blocks( + f1600: keccak::Fn1600, + state: &mut State1600, + blocks: &[Array], +) { + for block in blocks { + xor_block(state, block); + f1600(state); + } +} diff --git a/sha3/tests/cshake.rs b/cshake/tests/cshake.rs similarity index 90% rename from sha3/tests/cshake.rs rename to cshake/tests/cshake.rs index 0ca4fb48f..8671cf78c 100644 --- a/sha3/tests/cshake.rs +++ b/cshake/tests/cshake.rs @@ -62,11 +62,11 @@ where } macro_rules! new_cshake_test { - ($name:ident, $test_name:expr, $hasher:ty $(,)?) => { + ($name:ident, $hasher:ty $(,)?) => { #[test] fn $name() { digest::dev::blobby::parse_into_structs!( - include_bytes!(concat!("data/", $test_name, ".blb")); + include_bytes!(concat!("data/", stringify!($name), ".blb")); static TEST_VECTORS: &[TestVector { customization, input, output }]; ); @@ -86,5 +86,5 @@ macro_rules! new_cshake_test { }; } -new_cshake_test!(cshake128_reset, "cshake128", sha3::CShake128); -new_cshake_test!(cshake256_reset, "cshake256", sha3::CShake256); +new_cshake_test!(cshake128, cshake::CShake128); +new_cshake_test!(cshake256, cshake::CShake256); diff --git a/sha3/tests/data/cshake128.blb b/cshake/tests/data/cshake128.blb similarity index 100% rename from sha3/tests/data/cshake128.blb rename to cshake/tests/data/cshake128.blb diff --git a/sha3/tests/data/cshake256.blb b/cshake/tests/data/cshake256.blb similarity index 100% rename from sha3/tests/data/cshake256.blb rename to cshake/tests/data/cshake256.blb diff --git a/k12/Cargo.toml b/k12/Cargo.toml index edb485cd5..a20b9ed8f 100644 --- a/k12/Cargo.toml +++ b/k12/Cargo.toml @@ -14,7 +14,7 @@ description = "Pure Rust implementation of the KangarooTwelve hash function" [dependencies] digest = "0.11" -sha3 = { version = "0.11.0-rc.7", default-features = false } +turbo-shake = { version = "0.1.0", default-features = false } [dev-dependencies] digest = { version = "0.11", features = ["alloc", "dev"] } @@ -23,7 +23,7 @@ hex-literal = "1" [features] default = ["alloc"] alloc = ["digest/alloc"] -zeroize = ["digest/zeroize", "sha3/zeroize"] +zeroize = ["digest/zeroize", "turbo-shake/zeroize"] [package.metadata.docs.rs] all-features = true diff --git a/k12/src/block_api.rs b/k12/src/block_api.rs index a4d631d39..f211eaba7 100644 --- a/k12/src/block_api.rs +++ b/k12/src/block_api.rs @@ -7,7 +7,7 @@ use digest::{ }, consts::{U128, U136, U168}, }; -use sha3::{TurboShake128, TurboShake128Reader, TurboShake256, TurboShake256Reader}; +use turbo_shake::{TurboShake128, TurboShake128Reader, TurboShake256, TurboShake256Reader}; const CHUNK_SIZE: usize = 8192; const LENGTH_ENCODE_SIZE: usize = 255; diff --git a/sha3/Cargo.toml b/sha3/Cargo.toml index c4b745606..e99d2ba97 100644 --- a/sha3/Cargo.toml +++ b/sha3/Cargo.toml @@ -8,13 +8,9 @@ documentation = "https://docs.rs/sha3" readme = "README.md" repository = "https://github.com/RustCrypto/hashes" license = "MIT OR Apache-2.0" -keywords = ["sha3", "keccak", "hash", "digest"] +keywords = ["keccak", "hash", "xof", "digest"] categories = ["cryptography", "no-std"] -description = """ -Pure Rust implementation of SHA-3, a family of Keccak-based hash functions -including the SHAKE family of eXtendable-Output Functions (XOFs), as well as -the accelerated variant TurboSHAKE -""" +description = "Implementation of the SHA-3 family of cryptographic hash algorithms" [dependencies] digest = "0.11" diff --git a/sha3/README.md b/sha3/README.md index e64100ab6..85587d0bd 100644 --- a/sha3/README.md +++ b/sha3/README.md @@ -7,7 +7,7 @@ [![Project Chat][chat-image]][chat-link] [![Build Status][build-image]][build-link] -Pure Rust implementation of the [SHA-3] cryptographic hash algorithms. +Implementation of the [SHA-3] family of cryptographic hash algorithms. There are 6 standard algorithms specified in the SHA-3 standard: @@ -15,10 +15,8 @@ There are 6 standard algorithms specified in the SHA-3 standard: - `SHAKE128` and `SHAKE256` (an extendable output function (XOF)) Additionally, this crate supports: -- `cSHAKE128` and `cSHAKE256` the customizable XOFs as defined in the NIST [SHA-3 Derived Functions] -- `TurboSHAKE` XOF variant -- CryptoNight variant of SHA-3 -- `Keccak224`, `Keccak256`, `Keccak384`, `Keccak512` (NIST submission without padding changes) +- `KeccakFull`: CryptoNight variant of SHA-3 +- `Keccak224`, `Keccak256`, `Keccak384`, `Keccak512`: NIST submission without padding changes ## Examples @@ -51,6 +49,8 @@ let mut reader = hasher.finalize_xof(); let mut buf = [0u8; 10]; reader.read(&mut buf); assert_eq!(buf, hex!("5881092dd818bf5cf8a3")); +reader.read(&mut buf); +assert_eq!(buf, hex!("ddb793fbcba74097d5c5")); ``` See the [`digest`] crate docs for additional examples. @@ -86,5 +86,4 @@ dual licensed as above, without any additional terms or conditions. [//]: # (general links) [SHA-3]: https://en.wikipedia.org/wiki/SHA-3 -[SHA-3 Derived Functions]: https://csrc.nist.gov/pubs/sp/800/185/final [`digest`]: https://docs.rs/digest diff --git a/sha3/src/block_api.rs b/sha3/src/block_api.rs index 63da99f68..4118bf558 100644 --- a/sha3/src/block_api.rs +++ b/sha3/src/block_api.rs @@ -10,13 +10,11 @@ use digest::{ common::hazmat::{DeserializeStateError, SerializableState, SerializedState}, typenum::{IsLessOrEqual, True, U0, U200}, }; -use keccak::{F1600_ROUNDS, Keccak, State1600}; +use keccak::{Keccak, State1600}; -pub use crate::cshake::{CShake128Core, CShake256Core}; - -/// Core Sha3 fixed output hasher state. +/// Core SHA-3 hasher state. #[derive(Clone)] -pub struct Sha3HasherCore +pub struct Sha3HasherCore where Rate: BlockSizes + IsLessOrEqual, OutputSize: ArraySize + IsLessOrEqual, @@ -26,16 +24,14 @@ where _pd: PhantomData<(Rate, OutputSize)>, } -impl HashMarker - for Sha3HasherCore +impl HashMarker for Sha3HasherCore where Rate: BlockSizes + IsLessOrEqual, OutputSize: ArraySize + IsLessOrEqual, { } -impl BlockSizeUser - for Sha3HasherCore +impl BlockSizeUser for Sha3HasherCore where Rate: BlockSizes + IsLessOrEqual, OutputSize: ArraySize + IsLessOrEqual, @@ -43,8 +39,7 @@ where type BlockSize = Rate; } -impl BufferKindUser - for Sha3HasherCore +impl BufferKindUser for Sha3HasherCore where Rate: BlockSizes + IsLessOrEqual, OutputSize: ArraySize + IsLessOrEqual, @@ -52,8 +47,7 @@ where type BufferKind = Eager; } -impl OutputSizeUser - for Sha3HasherCore +impl OutputSizeUser for Sha3HasherCore where Rate: BlockSizes + IsLessOrEqual, OutputSize: ArraySize + IsLessOrEqual, @@ -61,25 +55,23 @@ where type OutputSize = OutputSize; } -impl UpdateCore - for Sha3HasherCore +impl UpdateCore for Sha3HasherCore where Rate: BlockSizes + IsLessOrEqual, OutputSize: ArraySize + IsLessOrEqual, { #[inline] fn update_blocks(&mut self, blocks: &[Block]) { - self.keccak.with_p1600::(|p1600| { + self.keccak.with_f1600(|f1600| { for block in blocks { xor_block(&mut self.state, block); - p1600(&mut self.state); + f1600(&mut self.state); } }); } } -impl FixedOutputCore - for Sha3HasherCore +impl FixedOutputCore for Sha3HasherCore where Rate: BlockSizes + IsLessOrEqual, OutputSize: ArraySize + IsLessOrEqual, @@ -92,9 +84,9 @@ where let n = block.len(); block[n - 1] |= 0x80; - self.keccak.with_p1600::(|p1600| { + self.keccak.with_f1600(|f1600| { xor_block(&mut self.state, &block); - p1600(&mut self.state); + f1600(&mut self.state); for (o, s) in out.chunks_mut(8).zip(self.state.as_mut().iter()) { o.copy_from_slice(&s.to_le_bytes()[..o.len()]); @@ -103,12 +95,11 @@ where } } -impl ExtendableOutputCore - for Sha3HasherCore +impl ExtendableOutputCore for Sha3HasherCore where Rate: BlockSizes + IsLessOrEqual, { - type ReaderCore = Sha3ReaderCore; + type ReaderCore = Sha3ReaderCore; #[inline] fn finalize_xof_core(&mut self, buffer: &mut Buffer) -> Self::ReaderCore { @@ -118,17 +109,16 @@ where let n = block.len(); block[n - 1] |= 0x80; - self.keccak.with_p1600::(|p1600| { + self.keccak.with_f1600(|f1600| { xor_block(&mut self.state, &block); - p1600(&mut self.state); + f1600(&mut self.state); }); Sha3ReaderCore::new(&self.state, self.keccak) } } -impl Default - for Sha3HasherCore +impl Default for Sha3HasherCore where Rate: BlockSizes + IsLessOrEqual, OutputSize: ArraySize + IsLessOrEqual, @@ -143,8 +133,7 @@ where } } -impl Reset - for Sha3HasherCore +impl Reset for Sha3HasherCore where Rate: BlockSizes + IsLessOrEqual, OutputSize: ArraySize + IsLessOrEqual, @@ -155,19 +144,18 @@ where } } -impl AlgorithmName - for Sha3HasherCore +impl AlgorithmName for Sha3HasherCore where Rate: BlockSizes + IsLessOrEqual, OutputSize: ArraySize + IsLessOrEqual, { fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str("Sha3") // TODO + // TODO: change algorithm name depending on the generic parameters + f.write_str("Sha3") } } -impl fmt::Debug - for Sha3HasherCore +impl fmt::Debug for Sha3HasherCore where Rate: BlockSizes + IsLessOrEqual, OutputSize: ArraySize + IsLessOrEqual, @@ -177,8 +165,7 @@ where } } -impl Drop - for Sha3HasherCore +impl Drop for Sha3HasherCore where Rate: BlockSizes + IsLessOrEqual, OutputSize: ArraySize + IsLessOrEqual, @@ -193,16 +180,15 @@ where } #[cfg(feature = "zeroize")] -impl digest::zeroize::ZeroizeOnDrop - for Sha3HasherCore +impl digest::zeroize::ZeroizeOnDrop + for Sha3HasherCore where Rate: BlockSizes + IsLessOrEqual, OutputSize: ArraySize + IsLessOrEqual, { } -impl SerializableState - for Sha3HasherCore +impl SerializableState for Sha3HasherCore where Rate: BlockSizes + IsLessOrEqual, OutputSize: ArraySize + IsLessOrEqual, @@ -236,9 +222,9 @@ where } } -/// Core Sha3 XOF reader. +/// Core SHA-3 XOF reader. #[derive(Clone)] -pub struct Sha3ReaderCore +pub struct Sha3ReaderCore where Rate: BlockSizes + IsLessOrEqual, { @@ -247,7 +233,7 @@ where _pd: PhantomData, } -impl Sha3ReaderCore +impl Sha3ReaderCore where Rate: BlockSizes + IsLessOrEqual, { @@ -257,14 +243,14 @@ where } } -impl BlockSizeUser for Sha3ReaderCore +impl BlockSizeUser for Sha3ReaderCore where Rate: BlockSizes + IsLessOrEqual, { type BlockSize = Rate; } -impl XofReaderCore for Sha3ReaderCore +impl XofReaderCore for Sha3ReaderCore where Rate: BlockSizes + IsLessOrEqual, { @@ -274,13 +260,12 @@ where for (src, dst) in self.state.iter().zip(block.chunks_mut(8)) { dst.copy_from_slice(&src.to_le_bytes()[..dst.len()]); } - self.keccak - .with_p1600::(|p1600| p1600(&mut self.state)); + self.keccak.with_f1600(|f1600| f1600(&mut self.state)); block } } -impl Drop for Sha3ReaderCore +impl Drop for Sha3ReaderCore where Rate: BlockSizes + IsLessOrEqual, { @@ -293,7 +278,7 @@ where } } -impl fmt::Debug for Sha3ReaderCore +impl fmt::Debug for Sha3ReaderCore where Rate: BlockSizes + IsLessOrEqual, { @@ -303,7 +288,7 @@ where } #[cfg(feature = "zeroize")] -impl digest::zeroize::ZeroizeOnDrop for Sha3ReaderCore where +impl digest::zeroize::ZeroizeOnDrop for Sha3ReaderCore where Rate: BlockSizes + IsLessOrEqual { } diff --git a/sha3/src/cshake.rs b/sha3/src/cshake.rs deleted file mode 100644 index ff54da37c..000000000 --- a/sha3/src/cshake.rs +++ /dev/null @@ -1,227 +0,0 @@ -use crate::{CSHAKE_PAD, SHAKE_PAD, Sha3ReaderCore, block_api::xor_block}; -use core::fmt; -use digest::{ - CollisionResistance, CustomizedInit, HashMarker, Reset, - block_api::{ - AlgorithmName, Block, BlockSizeUser, Buffer, BufferKindUser, Eager, ExtendableOutputCore, - UpdateCore, - }, - common::hazmat::{DeserializeStateError, SerializableState, SerializedState}, - consts::{U16, U32, U136, U168, U400}, - typenum::Unsigned, -}; -use keccak::{F1600_ROUNDS as ROUNDS, Keccak, State1600}; - -macro_rules! impl_cshake { - ( - $name:ident, $full_name:ident, $reader_name:ident, $rate:ident, $alg_name:expr - ) => { - #[doc = $alg_name] - #[doc = " core hasher."] - #[derive(Clone, Default)] - pub struct $name { - state: State1600, - initial_state: State1600, - keccak: Keccak, - } - - impl $name { - /// Creates a new CSHAKE instance with the given function name and customization. - /// - /// Note that the function name is intended for use by NIST and should only be set to - /// values defined by NIST. You probably don't need to use this function. - pub fn new_with_function_name(function_name: &[u8], customization: &[u8]) -> Self { - let mut state = Self::default(); - - if function_name.is_empty() && customization.is_empty() { - return state; - } - - #[inline(always)] - pub(crate) fn left_encode(val: u64, b: &mut [u8; 9]) -> &[u8] { - b[1..].copy_from_slice(&val.to_be_bytes()); - let i = b[1..8].iter().take_while(|&&a| a == 0).count(); - b[i] = (8 - i) as u8; - &b[i..] - } - - let mut buffer = Buffer::::default(); - let mut b = [0u8; 9]; - buffer.digest_blocks(left_encode($rate::to_u64(), &mut b), |blocks| { - state.update_blocks(blocks) - }); - buffer.digest_blocks( - left_encode(8 * (function_name.len() as u64), &mut b), - |blocks| state.update_blocks(blocks), - ); - buffer.digest_blocks(function_name, |blocks| state.update_blocks(blocks)); - buffer.digest_blocks( - left_encode(8 * (customization.len() as u64), &mut b), - |blocks| state.update_blocks(blocks), - ); - buffer.digest_blocks(customization, |blocks| state.update_blocks(blocks)); - state.update_blocks(&[buffer.pad_with_zeros()]); - state.initial_state = state.state; - state - } - } - - impl CustomizedInit for $name { - #[inline] - fn new_customized(customization: &[u8]) -> Self { - Self::new_with_function_name(&[], customization) - } - } - - impl BufferKindUser for $name { - type BufferKind = Eager; - } - - impl HashMarker for $name {} - - impl BlockSizeUser for $name { - type BlockSize = $rate; - } - - impl UpdateCore for $name { - #[inline] - fn update_blocks(&mut self, blocks: &[Block]) { - self.keccak.with_p1600::(|p1600| { - for block in blocks { - xor_block(&mut self.state, block); - p1600(&mut self.state); - } - }) - } - } - - impl ExtendableOutputCore for $name { - type ReaderCore = Sha3ReaderCore<$rate>; - - #[inline] - fn finalize_xof_core(&mut self, buffer: &mut Buffer) -> Self::ReaderCore { - let pos = buffer.get_pos(); - let mut block = buffer.pad_with_zeros(); - let pad = if self.initial_state == State1600::default() { - SHAKE_PAD - } else { - CSHAKE_PAD - }; - block[pos] = pad; - let n = block.len(); - block[n - 1] |= 0x80; - - self.keccak.with_p1600::(|p1600| { - xor_block(&mut self.state, &block); - p1600(&mut self.state); - }); - - Sha3ReaderCore::new(&self.state, self.keccak) - } - } - - impl Reset for $name { - #[inline] - fn reset(&mut self) { - self.state = self.initial_state; - } - } - - impl AlgorithmName for $name { - fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str($alg_name) - } - } - - impl fmt::Debug for $name { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(concat!(stringify!($name), " { ... }")) - } - } - - impl Drop for $name { - fn drop(&mut self) { - #[cfg(feature = "zeroize")] - { - use digest::zeroize::Zeroize; - self.state.zeroize(); - self.initial_state.zeroize(); - } - } - } - - #[cfg(feature = "zeroize")] - impl digest::zeroize::ZeroizeOnDrop for $name {} - - impl SerializableState for $name { - type SerializedStateSize = U400; - - fn serialize(&self) -> SerializedState { - let mut serialized_state = SerializedState::::default(); - let mut chunks = serialized_state.chunks_exact_mut(8); - - for (val, chunk) in self.state.iter().zip(&mut chunks) { - chunk.copy_from_slice(&val.to_le_bytes()); - } - for (val, chunk) in self.initial_state.iter().zip(&mut chunks) { - chunk.copy_from_slice(&val.to_le_bytes()); - } - - serialized_state - } - - fn deserialize( - serialized_state: &SerializedState, - ) -> Result { - let (state_src, initial_state_src) = serialized_state.split_at(200); - let state = core::array::from_fn(|i| { - let chunk = state_src[8 * i..][..8].try_into().unwrap(); - u64::from_le_bytes(chunk) - }); - let initial_state = core::array::from_fn(|i| { - let chunk = initial_state_src[8 * i..][..8].try_into().unwrap(); - u64::from_le_bytes(chunk) - }); - Ok(Self{ state, initial_state, keccak: Keccak::new() }) - } - } - - digest::buffer_xof!( - #[doc = $alg_name] - #[doc = " hasher."] - pub struct $full_name($name); - // TODO: Use `XofHasherTraits CustomizedInit` after serialization for buffers is fixed - impl: Debug AlgorithmName Clone Default BlockSizeUser CoreProxy HashMarker Update Reset ExtendableOutputReset CustomizedInit; - #[doc = $alg_name] - #[doc = " XOF reader."] - pub struct $reader_name(Sha3ReaderCore<$rate>); - impl: XofReaderTraits; - ); - - impl $full_name { - /// Creates a new cSHAKE instance with the given function name and customization. - /// - /// Note that the function name is intended for use by NIST and should only be set to - /// values defined by NIST. You probably don't need to use this function. - pub fn new_with_function_name(function_name: &[u8], customization: &[u8]) -> Self { - Self { - core: $name::new_with_function_name(function_name, customization), - buffer: Default::default(), - } - } - } - }; -} - -impl_cshake!(CShake128Core, CShake128, CShake128Reader, U168, "cSHAKE128"); -impl_cshake!(CShake256Core, CShake256, CShake256Reader, U136, "cSHAKE256"); - -impl CollisionResistance for CShake128 { - // https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf#[{"num":68,"gen":0},{"name":"XYZ"},108,440,null] - type CollisionResistance = U16; -} - -impl CollisionResistance for CShake256 { - // https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf#[{"num":68,"gen":0},{"name":"XYZ"},108,440,null] - type CollisionResistance = U32; -} diff --git a/sha3/src/lib.rs b/sha3/src/lib.rs index 1384e2c89..7384c435c 100644 --- a/sha3/src/lib.rs +++ b/sha3/src/lib.rs @@ -13,11 +13,6 @@ pub use digest::{self, CollisionResistance, CustomizedInit, Digest}; /// Block-level types pub mod block_api; -mod cshake; -mod turbo_shake; - -pub use cshake::{CShake128, CShake128Reader, CShake256, CShake256Reader}; -pub use turbo_shake::{TurboShake128, TurboShake128Reader, TurboShake256, TurboShake256Reader}; use block_api::{Sha3HasherCore, Sha3ReaderCore}; use digest::consts::{U0, U16, U28, U32, U48, U64, U72, U104, U136, U144, U168, U200}; @@ -26,7 +21,6 @@ use digest::consts::{U0, U16, U28, U32, U48, U64, U72, U104, U136, U144, U168, U const KECCAK_PAD: u8 = 0x01; const SHA3_PAD: u8 = 0x06; const SHAKE_PAD: u8 = 0x1f; -const CSHAKE_PAD: u8 = 0x04; digest::buffer_fixed!( /// SHA-3-224 hasher. diff --git a/sha3/src/turbo_shake.rs b/sha3/src/turbo_shake.rs deleted file mode 100644 index c6f05001e..000000000 --- a/sha3/src/turbo_shake.rs +++ /dev/null @@ -1,136 +0,0 @@ -use crate::{Sha3HasherCore, Sha3ReaderCore}; -use core::fmt; -use digest::{ - CollisionResistance, ExtendableOutput, ExtendableOutputReset, HashMarker, Update, XofReader, - block_api::{ - AlgorithmName, BlockSizeUser, ExtendableOutputCore, Reset, UpdateCore, XofReaderCore, - }, - block_buffer::{EagerBuffer, ReadBuffer}, - consts::{U0, U16, U32, U136, U168}, -}; - -const TURBO_SHAKE_ROUND_COUNT: usize = 12; - -macro_rules! impl_turbo_shake { - ( - $name:ident, $reader_name:ident, $rate:ty, $alg_name:expr - ) => { - #[doc = $alg_name] - #[doc = "hasher with domain separator."] - #[doc = ""] - #[doc = "Domain separator `DS` MUST be in the range `0x01..=0x7f`, the default value is `0x1F`."] - #[doc = "Using `DS` outside of the range will result in a panic during initialization."] - #[derive(Clone)] - pub struct $name { - core: Sha3HasherCore<$rate, U0, DS, TURBO_SHAKE_ROUND_COUNT>, - buffer: EagerBuffer<$rate>, - } - - impl Default for $name { - #[inline] - fn default() -> Self { - assert!((0x01..=0x7F).contains(&DS), "invalid domain separator"); - Self { - core: Default::default(), - buffer: Default::default(), - } - } - } - - impl HashMarker for $name {} - - impl BlockSizeUser for $name { - type BlockSize = $rate; - } - - impl Update for $name { - #[inline] - fn update(&mut self, data: &[u8]) { - let Self { core, buffer } = self; - buffer.digest_blocks(data, |blocks| core.update_blocks(blocks)); - } - } - - impl ExtendableOutput for $name { - type Reader = $reader_name; - - #[inline] - fn finalize_xof(mut self) -> Self::Reader { - let Self { core, buffer } = &mut self; - let core = core.finalize_xof_core(buffer); - let buffer = Default::default(); - Self::Reader { core, buffer } - } - } - - impl ExtendableOutputReset for $name { - #[inline] - fn finalize_xof_reset(&mut self) -> Self::Reader { - let Self { core, buffer } = self; - let core = core.finalize_xof_core(buffer); - self.reset(); - let buffer = Default::default(); - Self::Reader { core, buffer } - } - } - - impl Reset for $name { - #[inline] - fn reset(&mut self) { - *self = Default::default(); - } - } - - impl AlgorithmName for $name { - fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(stringify!($alg_name)) - } - } - - impl fmt::Debug for $name { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(concat!(stringify!($name), " { ... }")) - } - } - - #[cfg(feature = "zeroize")] - impl digest::zeroize::ZeroizeOnDrop for $name {} - - #[doc = $alg_name] - #[doc = " XOF reader."] - #[derive(Clone)] - pub struct $reader_name { - core: Sha3ReaderCore<$rate, TURBO_SHAKE_ROUND_COUNT>, - buffer: ReadBuffer<$rate>, - } - - impl XofReader for $reader_name { - #[inline] - fn read(&mut self, buf: &mut [u8]) { - let Self { core, buffer } = self; - buffer.read(buf, |block| { - *block = core.read_block(); - }); - } - } - - impl fmt::Debug for $reader_name { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(concat!(stringify!($reader_name), " { ... }")) - } - } - }; -} - -impl_turbo_shake!(TurboShake128, TurboShake128Reader, U168, "TurboSHAKE128"); -impl_turbo_shake!(TurboShake256, TurboShake256Reader, U136, "TurboSHAKE256"); - -impl CollisionResistance for TurboShake128 { - // https://www.ietf.org/archive/id/draft-irtf-cfrg-kangarootwelve-17.html#section-7-7 - type CollisionResistance = U16; -} - -impl CollisionResistance for TurboShake256 { - // https://www.ietf.org/archive/id/draft-irtf-cfrg-kangarootwelve-17.html#section-7-8 - type CollisionResistance = U32; -} diff --git a/turbo-shake/CHANGELOG.md b/turbo-shake/CHANGELOG.md new file mode 100644 index 000000000..ff7d452c0 --- /dev/null +++ b/turbo-shake/CHANGELOG.md @@ -0,0 +1,11 @@ +# 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.1.0 (UNRELEASED) +- Initial release with implementation moved from the `sha3` crate ([#815]) + +[#815]: https://github.com/RustCrypto/hashes/pull/815 diff --git a/turbo-shake/Cargo.toml b/turbo-shake/Cargo.toml new file mode 100644 index 000000000..0c69d8e86 --- /dev/null +++ b/turbo-shake/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "turbo-shake" +version = "0.1.0" +authors = ["RustCrypto Developers"] +edition = "2024" +rust-version = "1.85" +documentation = "https://docs.rs/turbo-shake" +readme = "README.md" +repository = "https://github.com/RustCrypto/hashes" +license = "MIT OR Apache-2.0" +keywords = ["keccak", "hash", "xof", "digest"] +categories = ["cryptography", "no-std"] +description = "Implementation of the TurboSHAKE family of extendable-output functions (XOFs)" + +[dependencies] +digest = "0.11" +keccak = "0.2" + +[dev-dependencies] +digest = { version = "0.11", features = ["dev"] } +hex-literal = "1" + +[features] +default = ["alloc"] +alloc = ["digest/alloc"] +zeroize = ["digest/zeroize"] + +[package.metadata.docs.rs] +all-features = true diff --git a/turbo-shake/LICENSE-APACHE b/turbo-shake/LICENSE-APACHE new file mode 100644 index 000000000..78173fa2e --- /dev/null +++ b/turbo-shake/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. diff --git a/turbo-shake/LICENSE-MIT b/turbo-shake/LICENSE-MIT new file mode 100644 index 000000000..4697b3e72 --- /dev/null +++ b/turbo-shake/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2026 The RustCrypto Project 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/turbo-shake/README.md b/turbo-shake/README.md new file mode 100644 index 000000000..289d0e1d9 --- /dev/null +++ b/turbo-shake/README.md @@ -0,0 +1,83 @@ +# RustCrypto: SHA-3 + +[![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] + +Implementation of the [TurboSHAKE] family of fast and secure extendable-output functions (XOFs). + +## Examples + +SHAKE functions have an extendable output, so finalization method returns +XOF reader from which results of arbitrary length can be read. Note that +these functions do not implement `Digest`, so lower-level traits have to +be imported: + +```rust +use turbo_shake::TurboShake128; +use turbo_shake::digest::{Update, ExtendableOutput, XofReader}; +use hex_literal::hex; + +// With the default domain separator. +// +// Note that we have to use `` because of +// the inadequate handling of defaults in Rust. +// Alternatively, you could use `let mut hasher: TurboShake128 = Default::default();` +// or `TurboShake128::::default()`. +let mut hasher = ::default(); +hasher.update(b"abc"); +let mut reader = hasher.finalize_xof(); +let mut buf = [0u8; 10]; +reader.read(&mut buf); +assert_eq!(buf, hex!("dcf1646dfe993a8eb6b7")); +reader.read(&mut buf); +assert_eq!(buf, hex!("82d1faaca6d82416a5dc")); + +// With a custom domain separator +let mut hasher = TurboShake128::<0x10>::default(); +hasher.update(b"abc"); +let mut reader = hasher.finalize_xof(); +let mut buf = [0u8; 10]; +reader.read(&mut buf); +assert_eq!(buf, hex!("6702f7b19ea87087ed0f")); +reader.read(&mut buf); +assert_eq!(buf, hex!("45a2fa692bc18c3526d3")); +``` + +See the [`digest`] crate docs for additional examples. + +## License + +The crate is 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/sha3.svg +[crate-link]: https://crates.io/crates/sha3 +[docs-image]: https://docs.rs/sha3/badge.svg +[docs-link]: https://docs.rs/sha3/ +[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/260041-hashes +[build-image]: https://github.com/RustCrypto/hashes/actions/workflows/sha3.yml/badge.svg?branch=master +[build-link]: https://github.com/RustCrypto/hashes/actions/workflows/sha3.yml?query=branch:master + +[//]: # (general links) + +[TurboSHAKE]: https://keccak.team/turboshake.html +[`digest`]: https://docs.rs/digest diff --git a/turbo-shake/benches/mod.rs b/turbo-shake/benches/mod.rs new file mode 100644 index 000000000..585735300 --- /dev/null +++ b/turbo-shake/benches/mod.rs @@ -0,0 +1,22 @@ +#![feature(test)] +extern crate test; + +use digest::bench_update; +use test::Bencher; +use turbo_shake::{TurboShake128, TurboShake256}; + +bench_update!( + ::default(); + turboshake128_10 10; + turboshake128_100 100; + turboshake128_1000 1000; + turboshake128_10000 10000; +); + +bench_update!( + ::default(); + turboshake256_10 10; + turboshake256_100 100; + turboshake256_1000 1000; + turboshake256_10000 10000; +); diff --git a/turbo-shake/src/lib.rs b/turbo-shake/src/lib.rs new file mode 100644 index 000000000..c5b93f19c --- /dev/null +++ b/turbo-shake/src/lib.rs @@ -0,0 +1,262 @@ +#![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))] +#![forbid(unsafe_code)] +#![warn(missing_docs, missing_debug_implementations)] +#![warn(unreachable_pub)] + +pub use digest; +use keccak::{Keccak, State1600}; + +use core::fmt; +use digest::{ + CollisionResistance, ExtendableOutput, ExtendableOutputReset, HashMarker, Update, XofReader, + block_api::{AlgorithmName, BlockSizeUser, Reset}, + block_buffer::{BlockSizes, EagerBuffer, ReadBuffer}, + consts::{U16, U32, U136, U168}, +}; + +/// Number of Keccak rounds used by TurboSHAKE. +const ROUNDS: usize = 12; + +/// Default domain separator value. +pub const DEFAULT_DS: u8 = 0x1F; + +/// TurboSHAKE hasher generic over rate and domain separator. +/// +/// Domain separator `DS` MUST be in the range `0x01..=0x7f`. +/// Use [`DEFAULT_DS`] if you want the default value. +/// +/// Rate MUST be either [`U168`] or [`U136`] for TurboSHAKE128 and TurboSHAKE256 respectively. +#[derive(Clone)] +pub struct TurboShake { + state: State1600, + keccak: Keccak, + buffer: EagerBuffer, +} + +impl Default for TurboShake { + #[inline] + fn default() -> Self { + const { + assert!(DS >= 0x01 && DS <= 0x7F, "invalid domain separator"); + assert!(Rate::USIZE == 168 || Rate::USIZE == 136, "unsupported rate"); + } + Self { + state: Default::default(), + keccak: Keccak::new(), + buffer: Default::default(), + } + } +} + +impl HashMarker for TurboShake {} + +impl BlockSizeUser for TurboShake { + type BlockSize = Rate; +} + +impl Update for TurboShake { + #[inline] + fn update(&mut self, data: &[u8]) { + let Self { + state, + keccak, + buffer, + } = self; + + keccak.with_p1600::(|p1600| { + buffer.digest_blocks(data, |blocks| { + for block in blocks { + xor_block(state, block); + p1600(state); + } + }); + }); + } +} + +impl TurboShake { + fn finalize_dirty(&mut self) { + let Self { + state, + keccak, + buffer, + } = self; + + let pos = buffer.get_pos(); + let mut block = buffer.pad_with_zeros(); + block[pos] = DS; + let n = block.len(); + block[n - 1] |= 0x80; + + keccak.with_p1600::(|p1600| { + xor_block(state, &block); + p1600(state); + }); + } +} + +impl ExtendableOutput for TurboShake { + type Reader = TurboShakeReader; + + #[inline] + fn finalize_xof(mut self) -> Self::Reader { + self.finalize_dirty(); + Self::Reader { + state: self.state, + keccak: self.keccak, + buffer: Default::default(), + } + } +} + +impl ExtendableOutputReset for TurboShake { + #[inline] + fn finalize_xof_reset(&mut self) -> Self::Reader { + self.finalize_dirty(); + let reader = Self::Reader { + state: self.state, + keccak: self.keccak, + buffer: Default::default(), + }; + self.reset(); + reader + } +} + +impl Reset for TurboShake { + #[inline] + fn reset(&mut self) { + self.state = Default::default(); + self.buffer.reset(); + } +} + +impl AlgorithmName for TurboShake { + fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result { + let alg_name = match Rate::USIZE { + 168 => "TurboSHAKE128", + 136 => "TurboSHAKE256", + _ => unreachable!(), + }; + f.write_str(alg_name) + } +} + +impl fmt::Debug for TurboShake { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let debug_str = match Rate::USIZE { + 168 => "TurboShake128 { ... }", + 136 => "TurboShake256 { ... }", + _ => unreachable!(), + }; + f.write_str(debug_str) + } +} + +impl Drop for TurboShake { + fn drop(&mut self) { + #[cfg(feature = "zeroize")] + { + use digest::zeroize::Zeroize; + self.state.zeroize(); + // self.buffer is zeroized by its `Drop` + } + } +} + +#[cfg(feature = "zeroize")] +impl digest::zeroize::ZeroizeOnDrop for TurboShake {} + +/// Generic TurboSHAKE XOF reader +#[derive(Clone)] +pub struct TurboShakeReader { + state: State1600, + keccak: Keccak, + buffer: ReadBuffer, +} + +impl XofReader for TurboShakeReader { + #[inline] + fn read(&mut self, buf: &mut [u8]) { + let Self { + state, + keccak, + buffer, + } = self; + + buffer.read(buf, |block| { + let mut chunks = block.chunks_exact_mut(8); + for (src, dst) in state.iter().zip(&mut chunks) { + dst.copy_from_slice(&src.to_le_bytes()); + } + assert!( + chunks.into_remainder().is_empty(), + "rate is either 136 or 168", + ); + keccak.with_p1600::(|p1600| p1600(state)); + }); + } +} + +impl fmt::Debug for TurboShakeReader { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let debug_str = match Rate::USIZE { + 168 => "TurboShakeReader128 { ... }", + 136 => "TurboShakeReader256 { ... }", + _ => unreachable!(), + }; + f.write_str(debug_str) + } +} + +impl Drop for TurboShakeReader { + fn drop(&mut self) { + #[cfg(feature = "zeroize")] + { + use digest::zeroize::Zeroize; + self.state.zeroize(); + // self.buffer is zeroized by its `Drop` + } + } +} + +#[cfg(feature = "zeroize")] +impl digest::zeroize::ZeroizeOnDrop for TurboShakeReader {} + +/// TurboSHAKE128 hasher with domain separator. +pub type TurboShake128 = TurboShake; +/// TurboSHAKE256 hasher with domain separator. +pub type TurboShake256 = TurboShake; + +/// TurboSHAKE128 XOF reader. +pub type TurboShake128Reader = TurboShakeReader; +/// TurboSHAKE256 XOF reader. +pub type TurboShake256Reader = TurboShakeReader; + +impl CollisionResistance for TurboShake128 { + // https://www.ietf.org/archive/id/draft-irtf-cfrg-kangarootwelve-17.html#section-7-7 + type CollisionResistance = U16; +} + +impl CollisionResistance for TurboShake256 { + // https://www.ietf.org/archive/id/draft-irtf-cfrg-kangarootwelve-17.html#section-7-8 + type CollisionResistance = U32; +} + +fn xor_block(state: &mut State1600, block: &[u8]) { + assert!(size_of_val(block) < size_of_val(state)); + + let mut chunks = block.chunks_exact(8); + for (s, chunk) in state.iter_mut().zip(&mut chunks) { + *s ^= u64::from_le_bytes(chunk.try_into().unwrap()); + } + + let rem = chunks.remainder(); + assert!(rem.is_empty(), "block size is equal to 136 or 168"); +} diff --git a/sha3/tests/data/turboshake128_6.blb b/turbo-shake/tests/data/turboshake128_6.blb similarity index 100% rename from sha3/tests/data/turboshake128_6.blb rename to turbo-shake/tests/data/turboshake128_6.blb diff --git a/sha3/tests/data/turboshake128_7.blb b/turbo-shake/tests/data/turboshake128_7.blb similarity index 100% rename from sha3/tests/data/turboshake128_7.blb rename to turbo-shake/tests/data/turboshake128_7.blb diff --git a/sha3/tests/data/turboshake256_6.blb b/turbo-shake/tests/data/turboshake256_6.blb similarity index 100% rename from sha3/tests/data/turboshake256_6.blb rename to turbo-shake/tests/data/turboshake256_6.blb diff --git a/sha3/tests/data/turboshake256_7.blb b/turbo-shake/tests/data/turboshake256_7.blb similarity index 100% rename from sha3/tests/data/turboshake256_7.blb rename to turbo-shake/tests/data/turboshake256_7.blb diff --git a/sha3/tests/turboshake.rs b/turbo-shake/tests/turboshake.rs similarity index 95% rename from sha3/tests/turboshake.rs rename to turbo-shake/tests/turboshake.rs index f350f3f92..9c4ad0014 100644 --- a/sha3/tests/turboshake.rs +++ b/turbo-shake/tests/turboshake.rs @@ -1,5 +1,6 @@ use core::fmt::Debug; use digest::ExtendableOutput; +use turbo_shake::{TurboShake128, TurboShake256}; #[derive(Debug, Clone, Copy)] pub struct TestVector { @@ -80,8 +81,6 @@ macro_rules! new_turbo_shake_test { ); }; - println!("before func: {:?}", truncate_output.len()); - if let Err(desc) = $test_func::<$hasher>( &input, output, @@ -105,25 +104,25 @@ macro_rules! new_turbo_shake_test { new_turbo_shake_test!( turboshake128_6, "turboshake128_6", - sha3::TurboShake128<6>, + TurboShake128<6>, turbo_shake_test, ); new_turbo_shake_test!( turboshake128_7, "turboshake128_7", - sha3::TurboShake128<7>, + TurboShake128<7>, turbo_shake_test, ); new_turbo_shake_test!( turboshake256_6, "turboshake256_6", - sha3::TurboShake256<6>, + TurboShake256<6>, turbo_shake_test, ); new_turbo_shake_test!( turboshake256_7, "turboshake256_7", - sha3::TurboShake256<7>, + TurboShake256<7>, turbo_shake_test, );