From 6b286b6b26f7d727f82a3ad2e56571b80750b45b Mon Sep 17 00:00:00 2001 From: dignifiedquire Date: Mon, 4 Mar 2024 18:03:51 +0100 Subject: [PATCH] refactor: move to its own crate --- .github/workflows/sha1-checked.yml | 155 ++++++++++++++ Cargo.lock | 9 + Cargo.toml | 1 + sha1-checked/CHANGELOG.md | 8 + sha1-checked/Cargo.toml | 32 +++ sha1-checked/LICENSE-APACHE | 201 ++++++++++++++++++ sha1-checked/LICENSE-MIT | 25 +++ sha1-checked/README.md | 96 +++++++++ sha1-checked/benches/mod.rs | 41 ++++ .../checked => sha1-checked/src}/compress.rs | 6 +- .../src/checked.rs => sha1-checked/src/lib.rs | 64 ++---- .../checked => sha1-checked/src}/ubc_check.rs | 0 .../tests/data/sha-mbles-1.bin | Bin .../tests/data/sha-mbles-2.bin | Bin sha1-checked/tests/data/sha1.blb | Bin 0 -> 234 bytes .../tests/data/sha1_reducedsha_coll.bin | 1 + .../tests/data/shattered-1.pdf | Bin .../tests/data/shattered-2.pdf | Bin sha1-checked/tests/mod.rs | 111 ++++++++++ sha1/src/lib.rs | 3 - sha1/tests/mod.rs | 96 --------- 21 files changed, 706 insertions(+), 143 deletions(-) create mode 100644 .github/workflows/sha1-checked.yml create mode 100644 sha1-checked/CHANGELOG.md create mode 100644 sha1-checked/Cargo.toml create mode 100644 sha1-checked/LICENSE-APACHE create mode 100644 sha1-checked/LICENSE-MIT create mode 100644 sha1-checked/README.md create mode 100644 sha1-checked/benches/mod.rs rename {sha1/src/checked => sha1-checked/src}/compress.rs (99%) rename sha1/src/checked.rs => sha1-checked/src/lib.rs (82%) rename {sha1/src/checked => sha1-checked/src}/ubc_check.rs (100%) rename {sha1 => sha1-checked}/tests/data/sha-mbles-1.bin (100%) rename {sha1 => sha1-checked}/tests/data/sha-mbles-2.bin (100%) create mode 100644 sha1-checked/tests/data/sha1.blb create mode 100644 sha1-checked/tests/data/sha1_reducedsha_coll.bin rename {sha1 => sha1-checked}/tests/data/shattered-1.pdf (100%) rename {sha1 => sha1-checked}/tests/data/shattered-2.pdf (100%) create mode 100644 sha1-checked/tests/mod.rs diff --git a/.github/workflows/sha1-checked.yml b/.github/workflows/sha1-checked.yml new file mode 100644 index 000000000..bf1d6f2ad --- /dev/null +++ b/.github/workflows/sha1-checked.yml @@ -0,0 +1,155 @@ +name: sha1 + +on: + pull_request: + paths: + - ".github/workflows/sha1-checked.yml" + - "sha1-checked/**" + - "Cargo.*" + push: + branches: master + +defaults: + run: + working-directory: sha1-checked + +env: + RUSTFLAGS: "-Dwarnings" + CARGO_INCREMENTAL: 0 + +jobs: + set-msrv: + uses: RustCrypto/actions/.github/workflows/set-msrv.yml@master + with: + msrv: 1.72.0 + + # Builds for no_std platforms + build: + needs: set-msrv + runs-on: ubuntu-latest + strategy: + matrix: + rust: + - ${{needs.set-msrv.outputs.msrv}} + - stable + target: + - thumbv7em-none-eabi + - wasm32-unknown-unknown + - loongarch64-unknown-linux-gnu + steps: + - uses: actions/checkout@v4 + - 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 --exclude-features default,std + + minimal-versions: + uses: RustCrypto/actions/.github/workflows/minimal-versions.yml@master + with: + working-directory: ${{ github.workflow }} + + # Linux tests + linux: + needs: set-msrv + strategy: + matrix: + include: + # 32-bit Linux/x86 + #- target: i686-unknown-linux-gnu + # rust: ${{needs.set-msrv.outputs.msrv}} + # deps: sudo apt update && sudo apt install gcc-multilib + #- target: i686-unknown-linux-gnu + # rust: stable + # deps: sudo apt update && sudo apt install gcc-multilib + + # 64-bit Linux/x86_64 + - target: x86_64-unknown-linux-gnu + rust: ${{needs.set-msrv.outputs.msrv}} + - target: x86_64-unknown-linux-gnu + rust: stable + + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - 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: ${{ matrix.deps }} + - run: cargo hack test --feature-powerset + + # macOS tests + macos: + needs: set-msrv + strategy: + matrix: + rust: + - ${{needs.set-msrv.outputs.msrv}} + - stable + + runs-on: macos-latest + steps: + - uses: actions/checkout@v4 + - uses: RustCrypto/actions/cargo-cache@master + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ matrix.rust }} + targets: x86_64-apple-darwin + - run: cargo test --no-default-features + - run: cargo test + - run: cargo test --all-features + + # Windows tests + windows: + needs: set-msrv + strategy: + matrix: + include: + # 64-bit Windows (GNU) + - target: x86_64-pc-windows-gnu + toolchain: ${{needs.set-msrv.outputs.msrv}} + - target: x86_64-pc-windows-gnu + toolchain: stable + + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + - uses: RustCrypto/actions/cargo-cache@master + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ matrix.toolchain }} + targets: ${{ matrix.target }} + - uses: msys2/setup-msys2@v2 + - run: cargo test --target ${{ matrix.target }} + + # Cross-compiled tests + cross: + strategy: + matrix: + rust: + - 1.72.0 + - stable + target: + - aarch64-unknown-linux-gnu + - powerpc-unknown-linux-gnu + features: + - default + + runs-on: ubuntu-latest + defaults: + run: + # Cross mounts only current package, i.e. by default it ignores workspace's Cargo.toml + working-directory: . + steps: + - uses: actions/checkout@v4 + - uses: ./.github/actions/cross-tests + with: + rust: ${{ matrix.rust }} + package: ${{ github.workflow }} + target: ${{ matrix.target }} + features: ${{ matrix.features }} diff --git a/Cargo.lock b/Cargo.lock index 6d42be8f4..1e2d3b9f4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -255,6 +255,15 @@ dependencies = [ "hex-literal", ] +[[package]] +name = "sha1-checked" +version = "0.11.0-pre.3" +dependencies = [ + "digest", + "hex-literal", + "sha1", +] + [[package]] name = "sha2" version = "0.11.0-pre.3" diff --git a/Cargo.toml b/Cargo.toml index 26637761e..54e8d97aa 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,7 @@ members = [ "md5", "ripemd", "sha1", + "sha1-checked", "sha2", "sha3", "shabal", diff --git a/sha1-checked/CHANGELOG.md b/sha1-checked/CHANGELOG.md new file mode 100644 index 000000000..dadf78569 --- /dev/null +++ b/sha1-checked/CHANGELOG.md @@ -0,0 +1,8 @@ +# 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). + +## UNRELEASED diff --git a/sha1-checked/Cargo.toml b/sha1-checked/Cargo.toml new file mode 100644 index 000000000..b6e69623b --- /dev/null +++ b/sha1-checked/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "sha1-checked" +version = "0.11.0-pre.3" +description = "SHA-1 hash function with collision detection" +authors = ["RustCrypto Developers"] +license = "MIT OR Apache-2.0" +readme = "README.md" +edition = "2021" +documentation = "https://docs.rs/sha1-checked" +repository = "https://github.com/RustCrypto/hashes" +keywords = ["crypto", "sha1", "hash", "digest"] +categories = ["cryptography", "no-std"] +rust-version = "1.72" + +[dependencies] +digest = "=0.11.0-pre.8" +sha1 = { version = "=0.11.0-pre.3", features = [], path = "../sha1" } + +[dev-dependencies] +digest = { version = "=0.11.0-pre.8", features = ["dev"] } +hex-literal = "0.4" + +[features] +default = ["oid", "std"] +std = ["digest/std", "sha1/std"] +oid = ["digest/oid", "sha1/oid"] # Enable OID support +zeroize = ["digest/zeroize", "sha1/zeroize"] + + +[package.metadata.docs.rs] +all-features = true +rustdoc-args = ["--cfg", "docsrs"] diff --git a/sha1-checked/LICENSE-APACHE b/sha1-checked/LICENSE-APACHE new file mode 100644 index 000000000..78173fa2e --- /dev/null +++ b/sha1-checked/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/sha1-checked/LICENSE-MIT b/sha1-checked/LICENSE-MIT new file mode 100644 index 000000000..455de7c85 --- /dev/null +++ b/sha1-checked/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2024 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/sha1-checked/README.md b/sha1-checked/README.md new file mode 100644 index 000000000..4cfdf25e0 --- /dev/null +++ b/sha1-checked/README.md @@ -0,0 +1,96 @@ +# RustCrypto: SHA-1 Checked + +[![crate][crate-image]][crate-link] +[![Docs][docs-image]][docs-link] +![Apache2/MIT licensed][license-image] +![Rust Version][rustc-image] +[![Project Chat][chat-image]][chat-link] +[![Build Status][build-image]][build-link] + +Pure Rust implementation of the [SHA-1] cryptographic hash algorithm with collision detection. + +## 🚨 Warning: Cryptographically Broken! 🚨 + +The SHA-1 hash function should be considered cryptographically broken and +unsuitable for further use in any security critical capacity, as it is +[practically vulnerable to chosen-prefix collisions][1]. + +But, this crate provides the detection [algorithm] pioneered by git, to detect hash collisions when they +occur and prevent them. The [paper] has more details on how this works. + +This implementation will be slower to use than the pure SHA-1 implementation, as more work as to be done. + +## Examples + +### One-shot API + +```rust +use hex_literal::hex; +use sha1_checked::{Sha1, Digest}; + +let result = Sha1::digest(b"hello world"); +assert_eq!(result, hex!("2aae6c35c94fcfb415dbe95f408b9ce91ee846ed")); +``` + +### Incremental API + +```rust +use hex_literal::hex; +use sha1_checked::{Sha1, Digest}; + +let mut hasher = Sha1::new(); +hasher.update(b"hello world"); +let hash = hasher.finalize(); + +assert_eq!(hash, hex!("2aae6c35c94fcfb415dbe95f408b9ce91ee846ed")); +``` + +Also, see the [examples section] in the RustCrypto/hashes readme. + +## Minimum Supported Rust Version + +Rust **1.72** 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 + +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/sha1-checked.svg +[crate-link]: https://crates.io/crates/sha1-checked +[docs-image]: https://docs.rs/sha1-checked/badge.svg +[docs-link]: https://docs.rs/sha1-checked/ +[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg +[rustc-image]: https://img.shields.io/badge/rustc-1.72+-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/workflows/sha1-checked/badge.svg?branch=master +[build-link]: https://github.com/RustCrypto/hashes/actions?query=workflow%3Asha1-checked + +[//]: # (general links) + +[SHA-1]: https://en.wikipedia.org/wiki/SHA-1 +[1]: https://sha-mbles.github.io/ +[examples section]: https://github.com/RustCrypto/hashes#Examples +[algorithm]: https://github.com/cr-marcstevens/sha1collisiondetection +[paper]: https://marc-stevens.nl/research/papers/C13-S.pdf diff --git a/sha1-checked/benches/mod.rs b/sha1-checked/benches/mod.rs new file mode 100644 index 000000000..e5d64170e --- /dev/null +++ b/sha1-checked/benches/mod.rs @@ -0,0 +1,41 @@ +#![feature(test)] +extern crate test; + +use digest::bench_update; +use sha1::Sha1; +use test::Bencher; + +bench_update!( + Sha1::default(); + sha1_10 10; + sha1_100 100; + sha1_1000 1000; + sha1_10000 10000; +); + +#[cfg(feature = "collision")] +bench_update!( + sha1::checked::Sha1::default(); + sha1_collision_10 10; + sha1_collision_100 100; + sha1_collision_1000 1000; + sha1_collision_10000 10000; +); + +#[cfg(feature = "collision")] +bench_update!( + sha1::checked::Sha1::builder().detect_collision(false).build(); + sha1_collision_no_check_10 10; + sha1_collision_no_check_100 100; + sha1_collision_no_check_1000 1000; + sha1_collision_no_check_10000 10000; +); + +#[cfg(feature = "collision")] +bench_update!( + sha1::checked::Sha1::builder().use_ubc(false).build(); + sha1_collision_no_ubc_10 10; + sha1_collision_no_ubc_100 100; + sha1_collision_no_ubc_1000 1000; + sha1_collision_no_ubc_10000 10000; +); diff --git a/sha1/src/checked/compress.rs b/sha1-checked/src/compress.rs similarity index 99% rename from sha1/src/checked/compress.rs rename to sha1-checked/src/compress.rs index 0a548a71c..92a02cf3d 100644 --- a/sha1/src/checked/compress.rs +++ b/sha1-checked/src/compress.rs @@ -6,8 +6,8 @@ #![allow(clippy::many_single_char_names, clippy::too_many_arguments)] use crate::{ - checked::{ubc_check::Testt, DetectionState}, BLOCK_SIZE, + {ubc_check::Testt, DetectionState}, }; const K: [u32; 4] = [0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6]; @@ -692,14 +692,14 @@ pub(super) fn compress( compression_states(&mut state_cpy, &block_u32, m1, state_58, state_65); let ubc_mask = if ctx.ubc_check { - crate::checked::ubc_check::ubc_check(&ctx.m1) + crate::ubc_check::ubc_check(&ctx.m1) } else { 0xFFFFFFFF }; if ubc_mask != 0 { let mut ihvtmp = [0u32; 5]; - for dv_type in &crate::checked::ubc_check::SHA1_DVS { + for dv_type in &crate::ubc_check::SHA1_DVS { if ubc_mask & (1 << dv_type.maskb) != 0 { for ((m2, m1), dm) in ctx.m2.iter_mut().zip(ctx.m1.iter()).zip(dv_type.dm.iter()) diff --git a/sha1/src/checked.rs b/sha1-checked/src/lib.rs similarity index 82% rename from sha1/src/checked.rs rename to sha1-checked/src/lib.rs index 6bd03e2d0..caab89485 100644 --- a/sha1/src/checked.rs +++ b/sha1-checked/src/lib.rs @@ -1,48 +1,31 @@ +#![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_auto_cfg))] +#![warn(missing_docs, rust_2018_idioms)] + //! Collision checked Sha1. //! //! General techniques and implementation are based on the research and implementation done in [1], [2] by //! Marc Stevens. //! //! -//! Original license from [3]. -//! -//! > MIT License -//! > -//! > Copyright (c) 2017: -//! > Marc Stevens -//! > Cryptology Group -//! > Centrum Wiskunde & Informatica -//! > P.O. Box 94079, 1090 GB Amsterdam, Netherlands -//! > marc@marc-stevens.nl -//! > -//! > Dan Shumow -//! > Microsoft Research -//! > danshu@microsoft.com -//! > -//! > 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. +//! Original license can be found in [3]. //! //! [1]: https://github.com/cr-marcstevens/sha1collisiondetection //! [2]: https://marc-stevens.nl/research/papers/C13-S.pdf //! [3]: https://github.com/cr-marcstevens/sha1collisiondetection/blob/master/LICENSE.txt +pub use digest::{self, Digest}; + use core::slice::from_ref; +#[cfg(feature = "std")] +extern crate std; + #[cfg(feature = "zeroize")] use digest::zeroize::{Zeroize, ZeroizeOnDrop}; use digest::{ @@ -50,10 +33,12 @@ use digest::{ block_buffer::{BlockBuffer, Eager}, core_api::{BlockSizeUser, BufferKindUser}, typenum::{Unsigned, U20, U64}, - FixedOutput, FixedOutputReset, HashMarker, MacMarker, Output, OutputSizeUser, Reset, Update, + FixedOutput, FixedOutputReset, HashMarker, Output, OutputSizeUser, Reset, Update, }; -use crate::{INITIAL_H, STATE_LEN}; +const BLOCK_SIZE: usize = ::BlockSize::USIZE; +const STATE_LEN: usize = 5; +const INITIAL_H: [u32; 5] = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]; mod compress; mod ubc_check; @@ -69,9 +54,6 @@ pub struct Sha1 { impl HashMarker for Sha1 {} -impl MacMarker for Sha1 {} - -// this blanket impl is needed for HMAC impl BlockSizeUser for Sha1 { type BlockSize = U64; } @@ -123,7 +105,7 @@ impl Sha1 { compress::finalize(h, bs * self.block_len, last_block, ctx); } else { let bit_len = 8 * (buffer.get_pos() as u64 + bs * self.block_len); - buffer.len64_padding_be(bit_len, |b| crate::compress::compress(h, from_ref(&b.0))); + buffer.len64_padding_be(bit_len, |b| sha1::compress(h, from_ref(&b.0))); } for (chunk, v) in out.chunks_exact_mut(4).zip(h.iter()) { @@ -194,7 +176,7 @@ impl Update for Sha1 { if let Some(ref mut ctx) = detection { compress::compress(h, ctx, blocks); } else { - crate::compress::compress(h, blocks); + sha1::compress(h, blocks); } }); } @@ -215,7 +197,7 @@ impl FixedOutputReset for Sha1 { #[inline] fn finalize_into_reset(&mut self, out: &mut Output) { self.finalize_inner(out); - self.reset(); + Reset::reset(self); } } @@ -253,7 +235,7 @@ impl ZeroizeOnDrop for DetectionState {} #[cfg(feature = "oid")] #[cfg_attr(docsrs, doc(cfg(feature = "oid")))] impl digest::const_oid::AssociatedOid for Sha1 { - const OID: digest::const_oid::ObjectIdentifier = crate::Sha1Core::OID; + const OID: digest::const_oid::ObjectIdentifier = sha1::Sha1Core::OID; } #[cfg(feature = "std")] diff --git a/sha1/src/checked/ubc_check.rs b/sha1-checked/src/ubc_check.rs similarity index 100% rename from sha1/src/checked/ubc_check.rs rename to sha1-checked/src/ubc_check.rs diff --git a/sha1/tests/data/sha-mbles-1.bin b/sha1-checked/tests/data/sha-mbles-1.bin similarity index 100% rename from sha1/tests/data/sha-mbles-1.bin rename to sha1-checked/tests/data/sha-mbles-1.bin diff --git a/sha1/tests/data/sha-mbles-2.bin b/sha1-checked/tests/data/sha-mbles-2.bin similarity index 100% rename from sha1/tests/data/sha-mbles-2.bin rename to sha1-checked/tests/data/sha-mbles-2.bin diff --git a/sha1-checked/tests/data/sha1.blb b/sha1-checked/tests/data/sha1.blb new file mode 100644 index 0000000000000000000000000000000000000000..e8dc49163c0c33f4048bfebb2b28b82707e28483 GIT binary patch literal 234 zcmZQzOH4}ESUJ;&0Z}#( zq~jN)_E=b8L0X6sawIvu#k*Yg~HOzNM]{$,+0ThEC !R6+f^j@,9|<r \ No newline at end of file diff --git a/sha1/tests/data/shattered-1.pdf b/sha1-checked/tests/data/shattered-1.pdf similarity index 100% rename from sha1/tests/data/shattered-1.pdf rename to sha1-checked/tests/data/shattered-1.pdf diff --git a/sha1/tests/data/shattered-2.pdf b/sha1-checked/tests/data/shattered-2.pdf similarity index 100% rename from sha1/tests/data/shattered-2.pdf rename to sha1-checked/tests/data/shattered-2.pdf diff --git a/sha1-checked/tests/mod.rs b/sha1-checked/tests/mod.rs new file mode 100644 index 000000000..8b5faffa4 --- /dev/null +++ b/sha1-checked/tests/mod.rs @@ -0,0 +1,111 @@ +use digest::dev::{feed_rand_16mib, fixed_reset_test}; +use hex_literal::hex; +use sha1::{Digest, Sha1}; + +digest::new_test!(sha1_main, "sha1", Sha1, fixed_reset_test); + +#[test] +fn sha1_rand() { + let mut h = Sha1::new(); + feed_rand_16mib(&mut h); + assert_eq!( + h.finalize(), + hex!("7e565a25a8b123e9881addbcedcd927b23377a78"), + ); +} + +#[cfg(feature = "collision")] +digest::new_test!( + sha1_collision_main, + "sha1", + sha1::checked::Sha1, + fixed_reset_test +); + +#[cfg(feature = "collision")] +#[test] +fn sha1_collision_rand() { + let mut h = sha1::checked::Sha1::new(); + feed_rand_16mib(&mut h); + assert_eq!( + h.finalize(), + hex!("7e565a25a8b123e9881addbcedcd927b23377a78"), + ); +} + +#[cfg(feature = "collision")] +#[test] +fn shambles_1() { + collision_test( + &include_bytes!("./data/sha-mbles-1.bin")[..], + hex!("8ac60ba76f1999a1ab70223f225aefdc78d4ddc0"), + hex!("4f3d9be4a472c4dae83c6314aa6c36a064c1fd14"), + ) +} + +#[cfg(feature = "collision")] +#[test] +fn shambles_2() { + collision_test( + &include_bytes!("./data/sha-mbles-2.bin")[..], + hex!("8ac60ba76f1999a1ab70223f225aefdc78d4ddc0"), + hex!("9ed5d77a4f48be1dbf3e9e15650733eb850897f2"), + ) +} + +#[cfg(feature = "collision")] +#[test] +fn shattered_1() { + collision_test( + &include_bytes!("./data/shattered-1.pdf")[..], + hex!("38762cf7f55934b34d179ae6a4c80cadccbb7f0a"), + hex!("16e96b70000dd1e7c85b8368ee197754400e58ec"), + ) +} + +#[cfg(feature = "collision")] +#[test] +fn shattered_2() { + collision_test( + &include_bytes!("./data/shattered-2.pdf")[..], + hex!("38762cf7f55934b34d179ae6a4c80cadccbb7f0a"), + hex!("e1761773e6a35916d99f891b77663e6405313587"), + ) +} + +#[cfg(feature = "collision")] +fn collision_test(input: &[u8], hash: [u8; 20], mitigated_hash: [u8; 20]) { + use sha1::checked; + + // No detection. + let mut ctx = checked::Sha1::builder().detect_collision(false).build(); + ctx.update(input); + let d = ctx.try_finalize(); + assert!(!d.has_collision()); + assert_eq!(&d.hash()[..], hash,); + + // No mitigation. + let mut ctx = checked::Sha1::builder().safe_hash(false).build(); + ctx.update(input); + + let d = ctx.try_finalize(); + assert!(d.has_collision()); + assert_eq!(&d.hash()[..], hash); + + // No mitigation, no optimization. + let mut ctx = checked::Sha1::builder() + .safe_hash(false) + .use_ubc(false) + .build(); + ctx.update(input); + let d = ctx.try_finalize(); + assert!(d.has_collision()); + assert_eq!(&d.hash()[..], hash); + + // With mitigation. + let mut ctx = checked::Sha1::new(); + ctx.update(input); + let d = ctx.try_finalize(); + assert!(d.has_collision()); + assert_eq!(&d.hash()[..], mitigated_hash); +} diff --git a/sha1/src/lib.rs b/sha1/src/lib.rs index 2bd64faf6..4cd381243 100644 --- a/sha1/src/lib.rs +++ b/sha1/src/lib.rs @@ -30,9 +30,6 @@ use digest::zeroize::{Zeroize, ZeroizeOnDrop}; #[cfg(feature = "std")] extern crate std; -#[cfg(feature = "collision")] -pub mod checked; - mod compress; pub use compress::compress; diff --git a/sha1/tests/mod.rs b/sha1/tests/mod.rs index 8b5faffa4..6f26dabc3 100644 --- a/sha1/tests/mod.rs +++ b/sha1/tests/mod.rs @@ -13,99 +13,3 @@ fn sha1_rand() { hex!("7e565a25a8b123e9881addbcedcd927b23377a78"), ); } - -#[cfg(feature = "collision")] -digest::new_test!( - sha1_collision_main, - "sha1", - sha1::checked::Sha1, - fixed_reset_test -); - -#[cfg(feature = "collision")] -#[test] -fn sha1_collision_rand() { - let mut h = sha1::checked::Sha1::new(); - feed_rand_16mib(&mut h); - assert_eq!( - h.finalize(), - hex!("7e565a25a8b123e9881addbcedcd927b23377a78"), - ); -} - -#[cfg(feature = "collision")] -#[test] -fn shambles_1() { - collision_test( - &include_bytes!("./data/sha-mbles-1.bin")[..], - hex!("8ac60ba76f1999a1ab70223f225aefdc78d4ddc0"), - hex!("4f3d9be4a472c4dae83c6314aa6c36a064c1fd14"), - ) -} - -#[cfg(feature = "collision")] -#[test] -fn shambles_2() { - collision_test( - &include_bytes!("./data/sha-mbles-2.bin")[..], - hex!("8ac60ba76f1999a1ab70223f225aefdc78d4ddc0"), - hex!("9ed5d77a4f48be1dbf3e9e15650733eb850897f2"), - ) -} - -#[cfg(feature = "collision")] -#[test] -fn shattered_1() { - collision_test( - &include_bytes!("./data/shattered-1.pdf")[..], - hex!("38762cf7f55934b34d179ae6a4c80cadccbb7f0a"), - hex!("16e96b70000dd1e7c85b8368ee197754400e58ec"), - ) -} - -#[cfg(feature = "collision")] -#[test] -fn shattered_2() { - collision_test( - &include_bytes!("./data/shattered-2.pdf")[..], - hex!("38762cf7f55934b34d179ae6a4c80cadccbb7f0a"), - hex!("e1761773e6a35916d99f891b77663e6405313587"), - ) -} - -#[cfg(feature = "collision")] -fn collision_test(input: &[u8], hash: [u8; 20], mitigated_hash: [u8; 20]) { - use sha1::checked; - - // No detection. - let mut ctx = checked::Sha1::builder().detect_collision(false).build(); - ctx.update(input); - let d = ctx.try_finalize(); - assert!(!d.has_collision()); - assert_eq!(&d.hash()[..], hash,); - - // No mitigation. - let mut ctx = checked::Sha1::builder().safe_hash(false).build(); - ctx.update(input); - - let d = ctx.try_finalize(); - assert!(d.has_collision()); - assert_eq!(&d.hash()[..], hash); - - // No mitigation, no optimization. - let mut ctx = checked::Sha1::builder() - .safe_hash(false) - .use_ubc(false) - .build(); - ctx.update(input); - let d = ctx.try_finalize(); - assert!(d.has_collision()); - assert_eq!(&d.hash()[..], hash); - - // With mitigation. - let mut ctx = checked::Sha1::new(); - ctx.update(input); - let d = ctx.try_finalize(); - assert!(d.has_collision()); - assert_eq!(&d.hash()[..], mitigated_hash); -}