diff --git a/.github/workflows/belt-hash.yml b/.github/workflows/belt-hash.yml new file mode 100644 index 000000000..11c42ccce --- /dev/null +++ b/.github/workflows/belt-hash.yml @@ -0,0 +1,65 @@ +name: belt-hash + +on: + pull_request: + paths: + - ".github/workflows/belt-hash.yml" + - "belt-hash/**" + - "Cargo.*" + push: + branches: master + +defaults: + run: + working-directory: belt-hash + +env: + CARGO_INCREMENTAL: 0 + RUSTFLAGS: "-Dwarnings" + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + rust: + - 1.57.0 # MSRV + - stable + target: + - thumbv7em-none-eabi + - wasm32-unknown-unknown + steps: + - uses: actions/checkout@v3 + - uses: RustCrypto/actions/cargo-cache@master + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: ${{ matrix.rust }} + target: ${{ matrix.target }} + override: true + - run: cargo build --no-default-features --target ${{ matrix.target }} + + minimal-versions: + uses: RustCrypto/actions/.github/workflows/minimal-versions.yml@master + with: + working-directory: ${{ github.workflow }} + + test: + runs-on: ubuntu-latest + strategy: + matrix: + rust: + - 1.57.0 # MSRV + - stable + steps: + - uses: actions/checkout@v3 + - uses: RustCrypto/actions/cargo-cache@master + - uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: ${{ matrix.rust }} + override: true + - run: cargo check --all-features + - run: cargo test --no-default-features + - run: cargo test + - run: cargo test --all-features diff --git a/.gitignore b/.gitignore index 8c754c8f8..675d60f92 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ target/ */target/ */*/target/ +*/Cargo.lock diff --git a/Cargo.lock b/Cargo.lock index 9b1e65dba..59c7ce648 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,12 +2,26 @@ # It is not intended for manual editing. version = 3 +[[package]] +name = "belt-block" +version = "0.1.1" +source = "git+https://github.com/RustCrypto/block-ciphers?branch=belt_raw#c04896e96172e1b35bed85522119c9505fa659cd" + +[[package]] +name = "belt-hash" +version = "0.1.0" +dependencies = [ + "belt-block", + "digest", + "hex-literal 0.3.4", +] + [[package]] name = "blake2" version = "0.10.4" dependencies = [ "digest", - "hex-literal", + "hex-literal 0.2.2", ] [[package]] @@ -80,7 +94,7 @@ name = "fsb" version = "0.1.3" dependencies = [ "digest", - "hex-literal", + "hex-literal 0.2.2", "whirlpool", ] @@ -99,7 +113,7 @@ name = "gost94" version = "0.10.3" dependencies = [ "digest", - "hex-literal", + "hex-literal 0.2.2", ] [[package]] @@ -107,7 +121,7 @@ name = "groestl" version = "0.10.1" dependencies = [ "digest", - "hex-literal", + "hex-literal 0.2.2", ] [[package]] @@ -120,6 +134,12 @@ dependencies = [ "proc-macro-hack", ] +[[package]] +name = "hex-literal" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ebdb29d2ea9ed0083cd8cece49bbd968021bd99b0849edb4a9a7ee0fdf6a4e0" + [[package]] name = "hex-literal-impl" version = "0.2.3" @@ -134,7 +154,7 @@ name = "k12" version = "0.2.1" dependencies = [ "digest", - "hex-literal", + "hex-literal 0.2.2", ] [[package]] @@ -154,7 +174,7 @@ name = "md-5" version = "0.10.5" dependencies = [ "digest", - "hex-literal", + "hex-literal 0.2.2", "md5-asm", ] @@ -163,7 +183,7 @@ name = "md2" version = "0.10.1" dependencies = [ "digest", - "hex-literal", + "hex-literal 0.2.2", ] [[package]] @@ -171,7 +191,7 @@ name = "md4" version = "0.10.1" dependencies = [ "digest", - "hex-literal", + "hex-literal 0.2.2", ] [[package]] @@ -194,7 +214,7 @@ name = "ripemd" version = "0.1.3" dependencies = [ "digest", - "hex-literal", + "hex-literal 0.2.2", ] [[package]] @@ -204,7 +224,7 @@ dependencies = [ "cfg-if", "cpufeatures", "digest", - "hex-literal", + "hex-literal 0.2.2", "sha1-asm", ] @@ -224,7 +244,7 @@ dependencies = [ "cfg-if", "cpufeatures", "digest", - "hex-literal", + "hex-literal 0.2.2", "sha2-asm", ] @@ -242,7 +262,7 @@ name = "sha3" version = "0.10.5" dependencies = [ "digest", - "hex-literal", + "hex-literal 0.2.2", "keccak", ] @@ -251,7 +271,7 @@ name = "shabal" version = "0.4.1" dependencies = [ "digest", - "hex-literal", + "hex-literal 0.2.2", ] [[package]] @@ -259,7 +279,7 @@ name = "sm3" version = "0.4.1" dependencies = [ "digest", - "hex-literal", + "hex-literal 0.2.2", ] [[package]] @@ -267,7 +287,7 @@ name = "streebog" version = "0.10.2" dependencies = [ "digest", - "hex-literal", + "hex-literal 0.2.2", ] [[package]] @@ -281,7 +301,7 @@ name = "tiger" version = "0.2.1" dependencies = [ "digest", - "hex-literal", + "hex-literal 0.2.2", ] [[package]] @@ -301,7 +321,7 @@ name = "whirlpool" version = "0.10.4" dependencies = [ "digest", - "hex-literal", + "hex-literal 0.2.2", "whirlpool-asm", ] diff --git a/Cargo.toml b/Cargo.toml index 675ac3604..beee3a843 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,6 +21,7 @@ members = [ "tiger", "whirlpool", ] +exclude = ["belt-hash"] [profile.dev] opt-level = 2 diff --git a/README.md b/README.md index 4314fb738..63f0807ae 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ Additionally all crates do not require the standard library (i.e. `no_std` capab | Algorithm | Crate | Crates.io | Documentation | MSRV | [Security] | |-----------|-------|:---------:|:-------------:|:----:|:----------:| +| [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) | ![MSRV 1.57][msrv-1.57] | :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) | ![MSRV 1.41][msrv-1.41] | :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) | ![MSRV 1.41][msrv-1.41] | :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) | ![MSRV 1.41][msrv-1.41] | :yellow_heart: | @@ -230,9 +231,11 @@ Unless you explicitly state otherwise, any contribution intentionally submitted [deps-image]: https://deps.rs/repo/github/RustCrypto/hashes/status.svg [deps-link]: https://deps.rs/repo/github/RustCrypto/hashes [msrv-1.41]: https://img.shields.io/badge/rustc-1.41.0+-blue.svg +[msrv-1.57]: https://img.shields.io/badge/rustc-1.57.0+-blue.svg [//]: # (crates) +[`belt-hash`]: ./belt-hash [`blake2`]: ./blake2 [`fsb`]: ./fsb [`gost94`]: ./gost94 @@ -270,6 +273,7 @@ Unless you explicitly state otherwise, any contribution intentionally submitted [//]: # (algorithms) +[BelT]: https://ru.wikipedia.org/wiki/BelT [BLAKE2]: https://en.wikipedia.org/wiki/BLAKE_(hash_function)#BLAKE2 [FSB]: https://en.wikipedia.org/wiki/Fast_syndrome-based_hash [GOST94]: https://en.wikipedia.org/wiki/GOST_(hash_function) diff --git a/belt-hash/CHANGELOG.md b/belt-hash/CHANGELOG.md new file mode 100644 index 000000000..9e82e1692 --- /dev/null +++ b/belt-hash/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 (2022-09-23) +- Initial release ([#416]) + +[#416]: https://github.com/RustCrypto/hashes/pull/416 diff --git a/belt-hash/Cargo.toml b/belt-hash/Cargo.toml new file mode 100644 index 000000000..14891c809 --- /dev/null +++ b/belt-hash/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "belt-hash" +version = "0.1.0" +description = "BelT hash function (STB 34.101.31-2020)" +authors = ["RustCrypto Developers"] +license = "MIT OR Apache-2.0" +readme = "README.md" +edition = "2021" +rust-version = "1.57" +documentation = "https://docs.rs/belt-hash" +repository = "https://github.com/RustCrypto/hashes" +keywords = ["crypto", "belt", "stb", "hash", "digest"] +categories = ["cryptography", "no-std"] + +[dependencies] +digest = "0.10.4" +belt-block = { version = "0.1.1", default-features = false } + +[dev-dependencies] +digest = { version = "0.10.4", features = ["dev"] } +hex-literal = "0.3.3" + +[features] +default = ["std"] +std = ["digest/std"] +oid = ["digest/oid"] + +# TODO: remove when crate will be part of the root workspace +[profile.dev] +opt-level = 2 diff --git a/belt-hash/LICENSE-APACHE b/belt-hash/LICENSE-APACHE new file mode 100644 index 000000000..78173fa2e --- /dev/null +++ b/belt-hash/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/belt-hash/LICENSE-MIT b/belt-hash/LICENSE-MIT new file mode 100644 index 000000000..bebabe744 --- /dev/null +++ b/belt-hash/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2022 Artyom Pavlov + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/belt-hash/README.md b/belt-hash/README.md new file mode 100644 index 000000000..b9b03a24a --- /dev/null +++ b/belt-hash/README.md @@ -0,0 +1,57 @@ +# RustCrypto: BelT hash + +[![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 [BelT] hash function specified in [STB 34.101.31-2020]. + +[Documentation][docs-link] + +## Minimum Supported Rust Version + +Rust **1.57** or higher. + +Minimum supported Rust version can be changed in the future, but it will be +done with a minor version bump. + +## SemVer Policy + +- All on-by-default features of this library are covered by SemVer +- MSRV is considered exempt from SemVer as noted above + +## License + +Licensed under either of: + + * [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) + * [MIT license](http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. + +[//]: # (badges) + +[crate-image]: https://img.shields.io/crates/v/belt-hash.svg +[crate-link]: https://crates.io/crates/belt-hash +[docs-image]: https://docs.rs/belt-hash/badge.svg +[docs-link]: https://docs.rs/belt-hash +[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg +[rustc-image]: https://img.shields.io/badge/rustc-1.57+-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/belt-hash/badge.svg?branch=master +[build-link]: https://github.com/RustCrypto/hashes/actions?query=workflow%3Abelt-hash + +[//]: # (general links) + +[BelT]: https://ru.wikipedia.org/wiki/BelT +[STB 34.101.31-2020]: http://apmi.bsu.by/assets/files/std/belt-spec371.pdf diff --git a/belt-hash/benches/mod.rs b/belt-hash/benches/mod.rs new file mode 100644 index 000000000..12635130f --- /dev/null +++ b/belt-hash/benches/mod.rs @@ -0,0 +1,14 @@ +#![feature(test)] +extern crate test; + +use belt_hash::BeltHash; +use digest::bench_update; +use test::Bencher; + +bench_update!( + BeltHash::default(); + belt_hash_10 10; + belt_hash_100 100; + belt_hash_1000 1000; + belt_hash_10000 10000; +); diff --git a/belt-hash/src/lib.rs b/belt-hash/src/lib.rs new file mode 100644 index 000000000..925ca6094 --- /dev/null +++ b/belt-hash/src/lib.rs @@ -0,0 +1,245 @@ +//! Pure Rust implementation of the [BelT] hash function specified in +//! [STB 34.101.31-2020]. +//! +//! # Usage +//! +//! ```rust +//! use belt_hash::{BeltHash, Digest}; +//! use hex_literal::hex; +//! +//! // create a BelT hasher instance +//! let mut hasher = BeltHash::new(); +//! +//! // process input message +//! hasher.update(b"hello world"); +//! +//! // acquire hash digest in the form of GenericArray, +//! // which in this case is equivalent to [u8; 32] +//! let result = hasher.finalize(); +//! let expected = hex!( +//! "afb175816416fbadad4629ecbd78e1887789881f2d2e5b80c22a746b7ac7ba88" +//! ); +//! assert_eq!(result[..], expected[..]); +//! ``` +//! +//! Also see [examples] in the RustCrypto/hashes readme. +//! +//! [BelT]: https://ru.wikipedia.org/wiki/BelT +//! [STB 34.101.31-2020]: http://apmi.bsu.by/assets/files/std/belt-spec371.pdf +//! [examples]: https://github.com/RustCrypto/hashes#usage +#![no_std] +#![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" +)] +#![warn(missing_docs, rust_2018_idioms)] +#![forbid(unsafe_code)] + +pub use digest::{self, Digest}; + +use belt_block::belt_block_raw; +use core::fmt; +#[cfg(feature = "oid")] +use digest::const_oid::{AssociatedOid, ObjectIdentifier}; +use digest::{ + block_buffer::Eager, + core_api::{ + AlgorithmName, Block, BlockSizeUser, Buffer, BufferKindUser, CoreWrapper, FixedOutputCore, + OutputSizeUser, Reset, UpdateCore, + }, + typenum::{Unsigned, U32}, + HashMarker, Output, +}; + +const U32_MASK: u128 = (1 << 32) - 1; + +/// Core BelT hasher state. +#[derive(Clone)] +pub struct BeltHashCore { + r: u128, + s: [u32; 4], + h: [u32; 8], +} + +impl BeltHashCore { + fn compress_block(&mut self, block: &Block) { + let x1 = [ + get_u32(block, 0), + get_u32(block, 1), + get_u32(block, 2), + get_u32(block, 3), + ]; + let x2 = [ + get_u32(block, 4), + get_u32(block, 5), + get_u32(block, 6), + get_u32(block, 7), + ]; + let (t, h) = belt_compress(x1, x2, self.h); + self.h = h; + self.s.iter_mut().zip(t).for_each(|(s, t)| *s ^= t); + } +} + +impl HashMarker for BeltHashCore {} + +impl BlockSizeUser for BeltHashCore { + type BlockSize = U32; +} + +impl BufferKindUser for BeltHashCore { + type BufferKind = Eager; +} + +impl OutputSizeUser for BeltHashCore { + type OutputSize = U32; +} + +impl UpdateCore for BeltHashCore { + #[inline] + fn update_blocks(&mut self, blocks: &[Block]) { + self.r = self.r.wrapping_add(blocks.len() as u128); + for block in blocks { + self.compress_block(block); + } + } +} + +impl FixedOutputCore for BeltHashCore { + #[inline] + fn finalize_fixed_core(&mut self, buffer: &mut Buffer, out: &mut Output) { + let pos = buffer.get_pos(); + if pos != 0 { + let block = buffer.pad_with_zeros(); + self.compress_block(block); + } + let bs = Self::BlockSize::USIZE as u128; + let r = encode_r(8 * ((bs * self.r) + pos as u128)); + let (_, y) = belt_compress(r, self.s, self.h); + for (chunk, val) in out.chunks_exact_mut(4).zip(y) { + chunk.copy_from_slice(&val.to_le_bytes()); + } + } +} + +impl Default for BeltHashCore { + #[inline] + fn default() -> Self { + Self { + r: 0, + s: [0; 4], + #[rustfmt::skip] + h: [ + 0xC8BA94B1, 0x3BF5080A, 0x8E006D36, 0xE45D4A58, + 0x9DFA0485, 0xACC7B61B, 0xC2722E25, 0x0DCEFD02, + ], + } + } +} + +impl Reset for BeltHashCore { + #[inline] + fn reset(&mut self) { + *self = Default::default(); + } +} + +impl AlgorithmName for BeltHashCore { + fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("BeltHash") + } +} + +impl fmt::Debug for BeltHashCore { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("BeltHashCore { ... }") + } +} + +#[cfg(feature = "oid")] +#[cfg_attr(docsrs, doc(cfg(feature = "oid")))] +impl AssociatedOid for BeltHashCore { + const OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.112.0.2.0.34.101.31.81"); +} + +/// BelT hasher state. +pub type BeltHash = CoreWrapper; + +/// Compression function described in the section 6.3.2 +#[inline(always)] +fn belt_compress(x1: [u32; 4], x2: [u32; 4], x34: [u32; 8]) -> ([u32; 4], [u32; 8]) { + let x3 = [x34[0], x34[1], x34[2], x34[3]]; + let x4 = [x34[4], x34[5], x34[6], x34[7]]; + + // Step 2 + let t1 = belt_block_raw(xor(x3, x4), &concat(x1, x2)); + let s = xor(xor(t1, x3), x4); + // Step 3 + let t2 = belt_block_raw(x1, &concat(s, x4)); + let y1 = xor(t2, x1); + // Step 4 + let t3 = belt_block_raw(x2, &concat(s.map(|v| !v), x3)); + let y2 = xor(t3, x2); + // Step 5 + (s, concat(y1, y2)) +} + +#[inline(always)] +fn xor(a: [u32; 4], b: [u32; 4]) -> [u32; 4] { + // TODO: use array zip on stabilization and MSRV bump + [a[0] ^ b[0], a[1] ^ b[1], a[2] ^ b[2], a[3] ^ b[3]] +} + +#[inline(always)] +fn concat(a: [u32; 4], b: [u32; 4]) -> [u32; 8] { + [a[0], a[1], a[2], a[3], b[0], b[1], b[2], b[3]] +} + +#[inline(always)] +fn get_u32(block: &[u8], i: usize) -> u32 { + u32::from_le_bytes(block[4 * i..][..4].try_into().unwrap()) +} + +#[inline(always)] +fn encode_r(r: u128) -> [u32; 4] { + [ + (r & U32_MASK) as u32, + ((r >> 32) & U32_MASK) as u32, + ((r >> 64) & U32_MASK) as u32, + ((r >> 96) & U32_MASK) as u32, + ] +} + +#[cfg(test)] +mod tests { + use super::{belt_compress, get_u32}; + use hex_literal::hex; + + const ENUM4: [usize; 4] = [0, 1, 2, 3]; + const ENUM8: [usize; 8] = [0, 1, 2, 3, 4, 5, 6, 7]; + + /// Test vectors for the `belt-compress` functions from the + /// specification (Table A.8). + #[test] + fn compress() { + let x = &hex!( + "B194BAC8 0A08F53B 366D008E 584A5DE4" + "8504FA9D 1BB6C7AC 252E72C2 02FDCE0D" + "5BE3D612 17B96181 FE6786AD 716B890B" + "5CB0C0FF 33C356B8 35C405AE D8E07F99" + ); + let expected_s = &hex!("46FE7425 C9B181EB 41DFEE3E 72163D5A"); + let expected_y = &hex!( + "ED2F5481 D593F40D 87FCE37D 6BC1A2E1" + "B7D1A2CC 975C82D3 C0497488 C90D99D8" + ); + let x1 = ENUM4.map(|i| get_u32(x, i)); + let x2 = ENUM4.map(|i| get_u32(x, 4 + i)); + let x34 = ENUM8.map(|i| get_u32(x, 8 + i)); + + let (s, y) = belt_compress(x1, x2, x34); + + assert_eq!(s, ENUM4.map(|i| get_u32(expected_s, i))); + assert_eq!(y, ENUM8.map(|i| get_u32(expected_y, i))); + } +} diff --git a/belt-hash/tests/data/stb.blb b/belt-hash/tests/data/stb.blb new file mode 100644 index 000000000..6e6307945 Binary files /dev/null and b/belt-hash/tests/data/stb.blb differ diff --git a/belt-hash/tests/mod.rs b/belt-hash/tests/mod.rs new file mode 100644 index 000000000..d8259a128 --- /dev/null +++ b/belt-hash/tests/mod.rs @@ -0,0 +1,20 @@ +use belt_hash::{BeltHash, Digest}; +use digest::dev::{feed_rand_16mib, fixed_reset_test}; +use hex_literal::hex; + +// Test vectors from STB 34.101.31-2020 (Section A.11, Table A.23): +// http://apmi.bsu.by/assets/files/std/belt-spec371.pdf +digest::new_test!(belt_stb, "stb", BeltHash, fixed_reset_test); + +#[test] +fn belt_rand() { + let mut h = BeltHash::new(); + feed_rand_16mib(&mut h); + assert_eq!( + h.finalize()[..], + hex!( + "a45053f80827d530008198c8185aa507" + "403b4a21f591579f07c34358e5991754" + )[..] + ); +}