diff options
author | Daniel Baumann <daniel@debian.org> | 2024-11-20 08:24:11 +0100 |
---|---|---|
committer | Daniel Baumann <daniel@debian.org> | 2024-11-20 08:24:11 +0100 |
commit | 0274dd146262558980189e6727ce12d98f808c56 (patch) | |
tree | deea19e00a89125dbafabd34da4efa2705b133f9 | |
parent | Initial commit. (diff) | |
download | rust-sha256-0274dd146262558980189e6727ce12d98f808c56.tar.xz rust-sha256-0274dd146262558980189e6727ce12d98f808c56.zip |
Adding upstream version 1.5.0.upstream/1.5.0upstream
Signed-off-by: Daniel Baumann <daniel@debian.org>
-rw-r--r-- | .cargo_vcs_info.json | 6 | ||||
-rw-r--r-- | .github/dependabot.yml | 11 | ||||
-rw-r--r-- | .github/workflows/check.yml | 79 | ||||
-rw-r--r-- | .github/workflows/publish.yml | 24 | ||||
-rw-r--r-- | .gitignore | 3 | ||||
-rw-r--r-- | Cargo.toml | 64 | ||||
-rw-r--r-- | Cargo.toml.orig | 30 | ||||
-rw-r--r-- | LICENSE-APACHE | 201 | ||||
-rw-r--r-- | LICENSE-MIT | 20 | ||||
-rw-r--r-- | README.md | 57 | ||||
-rw-r--r-- | foo.file | 1 | ||||
-rw-r--r-- | src/lib.rs | 513 |
12 files changed, 1009 insertions, 0 deletions
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json new file mode 100644 index 0000000..865a291 --- /dev/null +++ b/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "4184f8ef58a6f148f1dda5c83dcf2a98962f541e" + }, + "path_in_vcs": "" +}
\ No newline at end of file diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..e8d486a --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,11 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "cargo" # See documentation for possible values + directory: "/" # Location of package manifests + schedule: + interval: "weekly" diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml new file mode 100644 index 0000000..62c0014 --- /dev/null +++ b/.github/workflows/check.yml @@ -0,0 +1,79 @@ +name: check +on: + push: + branches: + - "*" + tags: + - "*" + pull_request: + branches: + - "*" + +jobs: + build: + strategy: + matrix: + os: + - ubuntu-latest + - macos-latest + runs-on: ${{ matrix.os }} + steps: + - name: Checkout + uses: actions/checkout@v2 + with: + submodules: true + - uses: actions-rs/toolchain@v1 + with: + toolchain: stable + override: true + components: clippy, rustfmt + - name: Check format + run: cargo fmt --all -- --check + - name: Check fix + run: cargo fix && cargo fix + - name: Check with clippy + run: cargo clippy --all -- -D warnings + - name: Build Release + run: cargo build --release --all-features + - name: Run tests + run: cargo test --all-features --all + + # build on nightly + - uses: actions-rs/toolchain@v1 + with: + toolchain: nightly + override: true + - name: Build on nightly + run: cargo build --release --all-features + windows-vcpkg: + name: windows-vcpkg + runs-on: windows-latest + steps: + - uses: actions/checkout@v3 + - uses: sfackler/actions/rustup@master + - run: echo "version=$(rustc --version)" >> $GITHUB_OUTPUT + id: rust-version + - run: echo "VCPKG_ROOT=$env:VCPKG_INSTALLATION_ROOT" | Out-File -FilePath $env:GITHUB_ENV -Append + - run: vcpkg install openssl:x64-windows-static-md + - uses: actions-rs/toolchain@v1 + with: + toolchain: stable + override: true + components: clippy, rustfmt + - name: Check format + run: cargo fmt --all -- --check + - name: Check fix + run: cargo fix && cargo fix + - name: Check with clippy + run: cargo clippy --all -- -D warnings + - name: Build Release + run: cargo build --release + - name: Run tests + run: cargo test --all-features --all + - uses: actions-rs/toolchain@v1 + with: + toolchain: nightly + override: true + - name: Build on nightly + run: cargo build --release + diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..b9e3741 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,24 @@ +name: Deploy +on: + push: + tags: + - "*" + +jobs: + # Publish starship to Crates.io + cargo_publish: + name: Publish Cargo Package + runs-on: ubuntu-latest + steps: + - name: Setup | Checkout + uses: actions/checkout@v2 + + - name: Setup | Rust + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + profile: minimal + override: true + + - name: Build | Publish + run: cargo publish --token ${{ secrets.CRATES_GITHUB_TOKEN }}
\ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..617f798 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +target/ +.idea/ +Cargo.lock
\ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..e6f1ea4 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,64 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +name = "sha256" +version = "1.5.0" +authors = ["baoyachi <liaoymxsdl@gmail.com>"] +description = "sha256 crypto digest" +readme = "README.md" +keywords = [ + "sha256", + "hash", + "digest", +] +categories = ["cryptography"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/baoyachi/sha256-rs" + +[dependencies.async-trait] +version = "0.1.68" + +[dependencies.bytes] +version = "1.4.0" + +[dependencies.hex] +version = "0.4.2" + +[dependencies.openssl] +version = "0.10.54" +optional = true +default-features = false + +[dependencies.sha2] +version = "0.10.6" +default-features = false + +[dependencies.tokio] +version = "1.28.2" +features = [ + "io-util", + "fs", +] +optional = true + +[dev-dependencies.tokio] +version = "1.28.2" +features = ["full"] + +[dev-dependencies.tokio-test] +version = "0.4.2" + +[features] +async = ["tokio"] +default = ["async"] +native_openssl = ["openssl"] diff --git a/Cargo.toml.orig b/Cargo.toml.orig new file mode 100644 index 0000000..d8f4b9a --- /dev/null +++ b/Cargo.toml.orig @@ -0,0 +1,30 @@ +[package] +name = "sha256" +version = "1.5.0" +authors = ["baoyachi <liaoymxsdl@gmail.com>"] +edition = "2018" +description = "sha256 crypto digest" +keywords = ["sha256", "hash", "digest"] +readme = "README.md" +categories = ["cryptography"] +repository = "https://github.com/baoyachi/sha256-rs" +license = "MIT OR Apache-2.0" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +hex = "0.4.2" +sha2 = { version = "0.10.6", default-features = false } +openssl = { version = "0.10.54", optional = true, default-features = false } +async-trait = "0.1.68" +tokio = { version = "1.28.2", optional = true, features = ["io-util", "fs"] } +bytes = "1.4.0" + +[features] +default = ["async"] +native_openssl = ["openssl"] +async = ["tokio"] + +[dev-dependencies] +tokio = { version = "1.28.2", features = ["full"] } +tokio-test = "0.4.2" diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..db1a289 --- /dev/null +++ b/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 [2022] [baoyachi of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..4ff994c --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,20 @@ +Copyright (c) 2021-present baoyachi and others + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..e338789 --- /dev/null +++ b/README.md @@ -0,0 +1,57 @@ +# sha256 crypto digest + +[docsrs]: https://docs.rs/sha256 + +[![GitHub Actions](https://github.com/baoyachi/sha256-rs/workflows/check/badge.svg)](https://github.com/baoyachi/sha256-rs/actions?query=workflow%3Abuild) +[![Crates.io](https://img.shields.io/crates/v/sha256.svg)](https://crates.io/crates/sha256) +[![Docs.rs](https://docs.rs/sha256/badge.svg)](https://docs.rs/sha256) +[![Download](https://img.shields.io/crates/d/sha256)](https://crates.io/crates/sha256) + + +## Examples + +#### sha256 digest function + +```rust +use sha256::digest; + +fn main() { + let input = String::from("hello"); + let val = digest(input); + assert_eq!(val,"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"); + + //sha256 digest &str + let input = "hello"; + let val = digest(input); + assert_eq!(val,"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"); + + //sha256 digest &mut &str + let mut input = "hello"; + let val = digest(&mut input); + assert_eq!(val,"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"); + + //sha256 digest char + let mut input = "π"; + let val = digest(input); + assert_eq!(val,"2617fcb92baa83a96341de050f07a3186657090881eae6b833f66a035600f35a"); + + + let input = b"hello"; + let val = digest(input); + assert_eq!(val, "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"); +} +``` + +#### sha256 try_digest function + +```rust +use sha256::try_digest; +use std::path::Path; + +fn main() { + let input = Path::new("./foo.file"); + let val = try_digest(input).unwrap(); + assert_eq!(val,"433855b7d2b96c23a6f60e70c655eb4305e8806b682a9596a200642f947259b1"); +} +``` + diff --git a/foo.file b/foo.file new file mode 100644 index 0000000..53bab1d --- /dev/null +++ b/foo.file @@ -0,0 +1 @@ +hello sha256
\ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..94ec155 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,513 @@ +//! sha256 crypto digest util +//! +//! ```rust +//! +//! use sha256::{digest, try_digest}; +//! +//! //sha256 digest String +//! let input = String::from("hello"); +//! let val = digest(input); +//! assert_eq!(val,"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"); +//! +//! //sha256 digest &str +//! let input = "hello"; +//! let val = digest(input); +//! assert_eq!(val,"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"); +//! +//! //sha256 digest &mut &str +//! let mut input = "hello"; +//! let val = digest(&mut input); +//! assert_eq!(val,"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"); +//! +//! //sha256 digest char +//! let mut input = "π"; +//! let val = digest(input); +//! assert_eq!(val,"2617fcb92baa83a96341de050f07a3186657090881eae6b833f66a035600f35a"); +//! +//! //sha256 digest bytes +//! let input = b"hello"; +//! let val = digest(input); +//! assert_eq!(val,"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"); +//! +//! //sha256 digest file +//! use std::path::Path; +//! let input = Path::new("./foo.file"); +//! let val = try_digest(input).unwrap(); +//! assert_eq!(val,"433855b7d2b96c23a6f60e70c655eb4305e8806b682a9596a200642f947259b1"); +//! +//! ``` + +#[cfg(feature = "native_openssl")] +use crate::openssl_sha256::OpenSslSha256; + +#[cfg(feature = "async")] +pub use async_digest::*; +use sha2::digest::Output; +use sha2::{Digest, Sha256}; +use std::fmt::Debug; +use std::fs; +use std::io; +use std::io::{BufReader, Read}; +use std::path::Path; + +/// sha256 digest string +/// +/// # Examples +/// +/// ```rust +/// use sha256::digest; +/// let input = "hello"; +/// let val = digest(input); +/// assert_eq!(val,"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824") +/// ``` +/// +pub fn digest<D: Sha256Digest>(input: D) -> String { + input.digest() +} + +/// sha256 digest file +/// +/// # Examples +/// +/// ```rust +/// use sha256::try_digest; +/// use std::path::Path; +/// let input = Path::new("./foo.file"); +/// let val = try_digest(input).unwrap(); +/// assert_eq!(val,"433855b7d2b96c23a6f60e70c655eb4305e8806b682a9596a200642f947259b1") +/// ``` +pub fn try_digest<D: TrySha256Digest>(input: D) -> Result<String, D::Error> { + input.digest() +} + +/// sha256 digest bytes +/// +/// # Examples +/// +/// ```rust +/// use sha256::digest_bytes; +/// let input = b"hello"; +/// let val = digest_bytes(input); +/// assert_eq!(val,"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824") +/// ``` +/// +#[deprecated(since = "1.1.0", note = "Use new function `digest()` instead")] +pub fn digest_bytes(input: &[u8]) -> String { + __digest__(input) +} + +/// sha256 digest file +/// +/// # Examples +/// +/// ```rust +/// use sha256::digest_file; +/// use std::path::Path; +/// let input = Path::new("./foo.file"); +/// let val = digest_file(input).unwrap(); +/// assert_eq!(val,"433855b7d2b96c23a6f60e70c655eb4305e8806b682a9596a200642f947259b1") +/// ``` +#[deprecated(since = "1.1.0", note = "Use new function `try_digest()` instead")] +pub fn digest_file<P: AsRef<Path>>(path: P) -> Result<String, io::Error> { + let bytes = fs::read(path)?; + Ok(__digest__(&bytes)) +} + +pub trait Sha256Digest { + fn digest(self) -> String; +} + +#[async_trait::async_trait] +pub trait TrySha256Digest { + type Error: Debug; + + fn digest(self) -> Result<String, Self::Error>; + + #[cfg(feature = "async")] + async fn async_digest(self) -> Result<String, Self::Error>; + + #[cfg(feature = "native_openssl")] + async fn async_openssl_digest(self) -> Result<String, Self::Error>; +} + +impl<const N: usize> Sha256Digest for &[u8; N] { + fn digest(self) -> String { + __digest__(self) + } +} + +impl Sha256Digest for &[u8] { + fn digest(self) -> String { + __digest__(self) + } +} + +impl Sha256Digest for &Vec<u8> { + fn digest(self) -> String { + __digest__(self) + } +} + +impl Sha256Digest for Vec<u8> { + fn digest(self) -> String { + __digest__(&self) + } +} + +impl Sha256Digest for String { + fn digest(self) -> String { + __digest__(self.as_bytes()) + } +} + +impl Sha256Digest for &str { + fn digest(self) -> String { + __digest__(self.as_bytes()) + } +} + +impl Sha256Digest for char { + fn digest(self) -> String { + __digest__(self.encode_utf8(&mut [0; 4]).as_bytes()) + } +} + +impl Sha256Digest for &mut &str { + fn digest(self) -> String { + __digest__(self.as_bytes()) + } +} + +impl Sha256Digest for &String { + fn digest(self) -> String { + __digest__(self.as_bytes()) + } +} + +#[async_trait::async_trait] +impl<P> TrySha256Digest for P +where + P: AsRef<Path> + Send, +{ + type Error = io::Error; + + fn digest(self) -> Result<String, Self::Error> { + let f = fs::File::open(self)?; + let reader = BufReader::new(f); + let sha = Sha256::new(); + calc(reader, sha) + } + + #[cfg(feature = "async")] + async fn async_digest(self) -> Result<String, Self::Error> { + let f = tokio::fs::File::open(self).await?; + let reader = tokio::io::BufReader::new(f); + let sha = Sha256::new(); + async_calc(reader, sha).await + } + + #[cfg(all(feature = "async", feature = "native_openssl"))] + async fn async_openssl_digest(self) -> Result<String, Self::Error> { + let f = tokio::fs::File::open(self).await?; + let reader = tokio::io::BufReader::new(f); + let sha = OpenSslSha256::new(); + async_calc(reader, sha).await + } +} + +fn __digest__(data: &[u8]) -> String { + hex::encode(Sha256::digest(data)) +} + +trait CalculatorInput { + fn read_inner(&mut self, buf: &mut [u8]) -> std::io::Result<usize>; +} + +impl<T> CalculatorInput for T +where + T: Read, +{ + fn read_inner(&mut self, buf: &mut [u8]) -> io::Result<usize> { + self.read(buf) + } +} + +pub trait CalculatorSelector { + type FinishType: AsRef<[u8]>; + fn update_inner(&mut self, data: &[u8]); + fn finish_inner(self) -> Self::FinishType; +} + +impl CalculatorSelector for Sha256 { + type FinishType = Output<Sha256>; + + fn update_inner(&mut self, data: &[u8]) { + self.update(data) + } + + fn finish_inner(self) -> Self::FinishType { + self.finalize() + } +} + +fn calc<I, S>(mut input: I, mut selector: S) -> io::Result<String> +where + I: CalculatorInput, + S: CalculatorSelector, +{ + let mut buf = [0u8; 1024]; + loop { + let len = input.read_inner(&mut buf)?; + if len == 0 { + break; + } + selector.update_inner(&buf[0..len]); + } + let hash = selector.finish_inner(); + Ok(hex::encode(hash)) +} + +#[cfg(feature = "async")] +pub mod async_digest { + use crate::{CalculatorSelector, TrySha256Digest}; + use bytes::BytesMut; + use std::io; + + /// sha256 digest file + /// + /// # Examples + /// + /// ```rust + /// use sha256::{try_async_digest}; + /// use std::path::Path; + /// let input = Path::new("./foo.file"); + /// tokio_test::block_on(async{ + /// let val = try_async_digest(input).await.unwrap(); + /// assert_eq!(val,"433855b7d2b96c23a6f60e70c655eb4305e8806b682a9596a200642f947259b1") + /// }); + /// + /// ``` + pub async fn try_async_digest<D: TrySha256Digest>(input: D) -> Result<String, D::Error> { + input.async_digest().await + } + + /// sha256 digest file + /// + /// # Examples + /// + /// ```rust + /// use sha256::{try_async_openssl_digest}; + /// use std::path::Path; + /// let input = Path::new("./foo.file"); + /// tokio_test::block_on(async{ + /// let val = try_async_openssl_digest(input).await.unwrap(); + /// assert_eq!(val,"433855b7d2b96c23a6f60e70c655eb4305e8806b682a9596a200642f947259b1") + /// }); + /// ``` + #[cfg(feature = "native_openssl")] + pub async fn try_async_openssl_digest<D: TrySha256Digest>( + input: D, + ) -> Result<String, D::Error> { + input.async_openssl_digest().await + } + + #[async_trait::async_trait] + pub trait AsyncCalculatorInput { + async fn read_inner(&mut self, buf: &mut BytesMut) -> io::Result<usize>; + } + + pub async fn async_calc<I, S>(mut input: I, mut selector: S) -> io::Result<String> + where + I: AsyncCalculatorInput, + S: CalculatorSelector, + { + let mut buf = BytesMut::with_capacity(1024); + loop { + buf.clear(); + let len = input.read_inner(&mut buf).await?; + if len == 0 { + break; + } + selector.update_inner(&buf[0..len]); + } + let hash = selector.finish_inner(); + Ok(hex::encode(hash)) + } + + #[async_trait::async_trait] + impl<R> AsyncCalculatorInput for tokio::io::BufReader<R> + where + R: tokio::io::AsyncRead + Unpin + Send, + { + async fn read_inner(&mut self, buf: &mut BytesMut) -> io::Result<usize> { + use tokio::io::AsyncReadExt; + + self.read_buf(buf).await + } + } +} + +#[cfg(feature = "native_openssl")] +mod openssl_sha256 { + use crate::CalculatorSelector; + + pub type OpenSslSha256 = openssl::sha::Sha256; + + impl CalculatorSelector for OpenSslSha256 { + type FinishType = [u8; 32]; + + fn update_inner(&mut self, data: &[u8]) { + self.update(data) + } + + fn finish_inner(self) -> Self::FinishType { + self.finish() + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[cfg(feature = "native_openssl")] + #[test] + fn test_openssl() { + let input = Path::new("./foo.file"); + let f = fs::File::open(input).unwrap(); + let reader = BufReader::new(f); + let sha = openssl::sha::Sha256::new(); + assert_eq!( + "433855b7d2b96c23a6f60e70c655eb4305e8806b682a9596a200642f947259b1", + calc(reader, sha).unwrap() + ); + } + + #[test] + fn test_sha256() { + let input = Path::new("./foo.file"); + let f = fs::File::open(input).unwrap(); + let reader = BufReader::new(f); + let sha = Sha256::new(); + assert_eq!( + "433855b7d2b96c23a6f60e70c655eb4305e8806b682a9596a200642f947259b1", + calc(reader, sha).unwrap() + ); + } + + #[cfg(all(feature = "async", feature = "native_openssl"))] + #[tokio::test] + async fn test_async_openssl() { + let input = Path::new("./foo.file"); + let f = tokio::fs::File::open(input).await.unwrap(); + let reader = tokio::io::BufReader::new(f); + let sha = openssl::sha::Sha256::new(); + assert_eq!( + "433855b7d2b96c23a6f60e70c655eb4305e8806b682a9596a200642f947259b1", + async_calc(reader, sha).await.unwrap() + ); + } + + #[cfg(feature = "async")] + #[tokio::test] + async fn test_async() { + let input = Path::new("./foo.file"); + let f = tokio::fs::File::open(input).await.unwrap(); + let reader = tokio::io::BufReader::new(f); + let sha = Sha256::new(); + assert_eq!( + "433855b7d2b96c23a6f60e70c655eb4305e8806b682a9596a200642f947259b1", + async_calc(reader, sha).await.unwrap() + ); + } + + #[cfg(all(feature = "async", feature = "native_openssl"))] + #[tokio::test] + async fn test_try_async_openssl_digest() { + let hash = try_async_openssl_digest("./foo.file").await.unwrap(); + assert_eq!( + "433855b7d2b96c23a6f60e70c655eb4305e8806b682a9596a200642f947259b1", + hash + ); + } + + #[cfg(feature = "async")] + #[tokio::test] + async fn test_try_async_digest() { + let hash = try_async_digest("./foo.file").await.unwrap(); + assert_eq!( + "433855b7d2b96c23a6f60e70c655eb4305e8806b682a9596a200642f947259b1", + hash + ); + } + + #[cfg(feature = "async")] + #[tokio::test] + async fn test_async_parity() { + let bytes = (0..0x1000).map(|v| (v % 256) as u8).collect::<Vec<_>>(); + let val = digest(&bytes); + + let async_res = { + let bytes = &bytes; + // We want to force Poll::Pending on reads during async_calc, which may break parity + // between sync and async hashing. + let (client, mut server) = tokio::io::duplex(64); + let reader = tokio::io::BufReader::new(client); + let sha = Sha256::new(); + + use tokio::io::AsyncWriteExt; + tokio::join! { + async_calc(reader, sha), + async move { + server.write_all(&bytes[..]).await.unwrap(); + core::mem::drop(server); + } + } + .0 + .unwrap() + }; + + let sync_res = { + let reader = BufReader::new(&*bytes); + let sha = Sha256::new(); + calc(reader, sha).unwrap() + }; + assert_eq!(val, async_res); + assert_eq!(async_res, sync_res); + } + + #[cfg(all(feature = "async", feature = "native_openssl"))] + #[tokio::test] + async fn test_async_parity_openssl() { + let bytes = (0..0x1000).map(|v| (v % 256) as u8).collect::<Vec<_>>(); + let val = digest(&bytes); + + let async_res = { + let bytes = &bytes; + // We want to force Poll::Pending on reads during async_calc, which may break parity + // between sync and async hashing. + let (client, mut server) = tokio::io::duplex(64); + let reader = tokio::io::BufReader::new(client); + let sha = OpenSslSha256::new(); + + use tokio::io::AsyncWriteExt; + tokio::join! { + async_calc(reader, sha), + async move { + server.write_all(&bytes[..]).await.unwrap(); + core::mem::drop(server); + } + } + .0 + .unwrap() + }; + + let sync_res = { + let reader = BufReader::new(&*bytes); + let sha = OpenSslSha256::new(); + calc(reader, sha).unwrap() + }; + assert_eq!(val, async_res); + assert_eq!(async_res, sync_res); + } +} |