blake2-rfc-0.2.18/.gitignore01006640001750000175000000000022130417003010013704 0ustar0000000000000000target Cargo.lock blake2-rfc-0.2.18/.travis.yml01006640001750000175000000002021132057673450014055 0ustar0000000000000000language: rust matrix: include: - rust: stable env: FEATURES= - rust: stable env: FEATURES=--no-default-features - rust: beta env: FEATURES= - rust: beta env: FEATURES=--no-default-features - rust: nightly env: FEATURES=--features=bench - rust: nightly env: FEATURES=--features=simd,bench - rust: nightly env: FEATURES=--features=simd_opt,bench - rust: nightly env: FEATURES=--features=simd_asm,bench - rust: nightly env: 'FEATURES="--no-default-features --features=bench"' - rust: nightly env: 'FEATURES="--no-default-features --features=simd,bench"' - rust: nightly env: 'FEATURES="--no-default-features --features=simd_opt,bench"' - rust: nightly env: 'FEATURES="--no-default-features --features=simd_asm,bench"' script: - cargo build --verbose $FEATURES - cargo test --verbose $FEATURES - cargo build --verbose --release $FEATURES - cargo test --verbose --release $FEATURES - '[ "$TRAVIS_RUST_VERSION" != "nightly" ] || cargo bench --verbose $FEATURES' blake2-rfc-0.2.18/Cargo.toml.orig01006640001750000175000000001417132061250470014627 0ustar0000000000000000[package] name = "blake2-rfc" version = "0.2.18" authors = ["Cesar Eduardo Barros "] description = "A pure Rust implementation of BLAKE2 based on RFC 7693." documentation = "https://docs.rs/blake2-rfc" repository = "https://github.com/cesarb/blake2-rfc" readme = "README.md" keywords = ["blake2", "blake2b", "blake2s", "hash", "crypto"] categories = ["cryptography", "no-std"] license = "MIT OR Apache-2.0" [badges] travis-ci = { repository = "cesarb/blake2-rfc" } [features] default = ["std"] bench = [] simd = [] simd_opt = ["simd"] simd_asm = ["simd_opt"] std = [] [dependencies] arrayvec = {version = "0.4.6", default-features = false} constant_time_eq = "0.1.0" clippy = {version = "0.0.41", optional = true} [dev-dependencies] data-encoding = "2.0.0" blake2-rfc-0.2.18/Cargo.toml0000644000000024700010054 0ustar00# 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 believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "blake2-rfc" version = "0.2.18" authors = ["Cesar Eduardo Barros "] description = "A pure Rust implementation of BLAKE2 based on RFC 7693." documentation = "https://docs.rs/blake2-rfc" readme = "README.md" keywords = ["blake2", "blake2b", "blake2s", "hash", "crypto"] categories = ["cryptography", "no-std"] license = "MIT OR Apache-2.0" repository = "https://github.com/cesarb/blake2-rfc" [dependencies.arrayvec] version = "0.4.6" default-features = false [dependencies.clippy] version = "0.0.41" optional = true [dependencies.constant_time_eq] version = "0.1.0" [dev-dependencies.data-encoding] version = "2.0.0" [features] bench = [] default = ["std"] simd = [] simd_asm = ["simd_opt"] simd_opt = ["simd"] std = [] [badges.travis-ci] repository = "cesarb/blake2-rfc" blake2-rfc-0.2.18/Cargo.toml.orig0000644000000024700011013 0ustar00# 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 believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "blake2-rfc" version = "0.2.18" authors = ["Cesar Eduardo Barros "] description = "A pure Rust implementation of BLAKE2 based on RFC 7693." documentation = "https://docs.rs/blake2-rfc" readme = "README.md" keywords = ["blake2", "blake2b", "blake2s", "hash", "crypto"] categories = ["cryptography", "no-std"] license = "MIT OR Apache-2.0" repository = "https://github.com/cesarb/blake2-rfc" [dependencies.clippy] version = "0.0.41" optional = true [dependencies.arrayvec] version = "0.4.6" default-features = false [dependencies.constant_time_eq] version = "0.1.0" [dev-dependencies.data-encoding] version = "2.0.0" [features] default = ["std"] simd_opt = ["simd"] simd = [] simd_asm = ["simd_opt"] bench = [] std = [] [badges.travis-ci] repository = "cesarb/blake2-rfc" blake2-rfc-0.2.18/LICENSE-APACHE01006640001750000175000000026136130417003010013656 0ustar0000000000000000 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. blake2-rfc-0.2.18/LICENSE-MIT01006640001750000175000000002114132053742500013370 0ustar0000000000000000Copyright (c) 2015 The blake2-rfc Developers Copyright (c) 2017 Google Inc. 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. blake2-rfc-0.2.18/README.md01006640001750000175000000010177132053764630013233 0ustar0000000000000000# blake2-rfc This is a pure Rust implementation of BLAKE2 based on [RFC 7693]. [RFC 7693]: https://tools.ietf.org/html/rfc7693 ## Design This crate follow the common API design for streaming hash functions, which has one state/context struct and three associated functions: one to initialize the struct, one which is called repeatedly to process the incoming data, and one to do the final processing and return the hash. For the case where the full data is already in memory, there is a convenience function which does these three steps in a single call. This basic design was slightly adapted to make a better use of Rust's characteristics: the finalization function consumes the struct, doing a move instead of a borrow, so the struct cannot be accidentally used after its internal state has been overwritten by the finalization. To prevent timing attacks, it's important that the comparison of hash values takes constant time. To make it easier to do the right thing, the finalization function returns the result wrapped in a struct which does a constant-time comparison by default. If a constant-time comparison is not necessary, the hash result can easily be extracted from this struct. ## Limitations A single BLAKE2b hash is limited to 16 exabytes, lower than its theorical limit (but identical to the BLAKE2s theorical limit), due to the use of a `u64` as the byte counter. This limit can be increased, if necessary, after either the `extprim` crate (with its `u128` type) or the `OverflowingOps` trait become usable with the "stable" Rust release. This crate does not attempt to clear potentially sensitive data from its work memory (which includes the state context, the stack, and processor registers). To do so correctly without a heavy performance penalty would require help from the compiler. It's better to not attempt to do so than to present a false assurance. ## Non-RFC uses This crate is limited to the features described in the RFC: only the "digest length" and "key length" parameters can be used. If you need to use other advanced BLAKE2 features, this crate has an undocumented function to create a hashing context with an arbitrary parameter block, and an undocumented function to finalize the last node in tree hashing mode. You are responsible for creating a valid parameter block, for hashing the padded key block if using keyed hashing, and for calling the correct finalization function. The parameter block is not validated by these functions. ## SIMD optimization This crate has experimental support for explicit SIMD optimizations. It requires nightly Rust due to the use of unstable features. The following cargo features enable the explicit SIMD optimization: * `simd` enables the explicit use of SIMD vectors instead of a plain struct * `simd_opt` additionally enables the use of SIMD shuffles to implement some of the rotates * `simd_asm` additionally enables the use of inline asm to implement some of the SIMD shuffles While one might expect that each of these is faster than the previous one, and that they are all faster than not enabling explicit SIMD vectors, that's not always the case. It can vary depending on target architecture and compiler options. If you need the extra speed from these optimizations, benchmark each one (the `bench` feature enables `cargo bench` in this crate, so you can use for instance `cargo bench --features="bench simd_asm"`). They have currently been tuned for SSE2 (x86 and x86-64) and NEON (arm). ## `no_std` support This crate links against the Rust standard library by default, to provide implementations of `std::io::Write`. To build `no_std`, use [`default-features = false`](http://doc.crates.io/manifest.html#rules). ## License Licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or 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. blake2-rfc-0.2.18/src/as_bytes.rs01006640001750000175000000002260132053764630014714 0ustar0000000000000000// Copyright 2016 blake2-rfc Developers // // Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be // copied, modified, or distributed except according to those terms. use core::mem; use core::slice; pub unsafe trait Safe {} pub trait AsBytes { fn as_bytes(&self) -> &[u8]; fn as_mut_bytes(&mut self) -> &mut [u8]; } impl AsBytes for [T] { #[inline] fn as_bytes(&self) -> &[u8] { unsafe { slice::from_raw_parts(self.as_ptr() as *const u8, self.len() * mem::size_of::()) } } #[inline] fn as_mut_bytes(&mut self) -> &mut [u8] { unsafe { slice::from_raw_parts_mut(self.as_mut_ptr() as *mut u8, self.len() * mem::size_of::()) } } } unsafe impl Safe for u8 {} unsafe impl Safe for u16 {} unsafe impl Safe for u32 {} unsafe impl Safe for u64 {} unsafe impl Safe for i8 {} unsafe impl Safe for i16 {} unsafe impl Safe for i32 {} unsafe impl Safe for i64 {} blake2-rfc-0.2.18/src/blake2.rs01006640001750000175000000032274132057724010014243 0ustar0000000000000000// Copyright 2015 blake2-rfc Developers // // Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be // copied, modified, or distributed except according to those terms. use arrayvec::ArrayVec; pub const SIGMA: [[usize; 16]; 10] = [ [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3], [11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4], [ 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8], [ 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13], [ 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9], [12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11], [13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10], [ 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5], [10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0], ]; macro_rules! blake2_impl { ($state:ident, $result:ident, $func:ident, $word:ident, $vec:ident, $bytes:expr, $R1:expr, $R2:expr, $R3:expr, $R4:expr, $IV:expr) => { use core::cmp; #[cfg(feature = "std")] use std::io; use $crate::as_bytes::AsBytes; use $crate::bytes::BytesExt; use $crate::constant_time_eq::constant_time_eq; use $crate::simd::{Vector4, $vec}; /// Container for a hash result. /// /// This container uses a constant-time comparison for equality. /// If a constant-time comparison is not necessary, the hash /// result can be extracted with the `as_bytes` method. #[derive(Clone, Copy, Debug)] pub struct $result { h: [$vec; 2], nn: usize, } #[cfg_attr(feature = "clippy", allow(len_without_is_empty))] impl $result { /// Returns the contained hash result as a byte string. #[inline] pub fn as_bytes(&self) -> &[u8] { &self.h.as_bytes()[..self.nn] } /// Returns the length of the hash result. /// /// This is the same value that was used to create the hash /// context. #[inline] pub fn len(&self) -> usize { self.nn } } impl AsRef<[u8]> for $result { #[inline] fn as_ref(&self) -> &[u8] { self.as_bytes() } } impl Eq for $result { } impl PartialEq for $result { #[inline] fn eq(&self, other: &Self) -> bool { constant_time_eq(self.as_bytes(), other.as_bytes()) } } impl PartialEq<[u8]> for $result { #[inline] fn eq(&self, other: &[u8]) -> bool { constant_time_eq(self.as_bytes(), other) } } /// State context. #[derive(Clone, Debug)] pub struct $state { m: [$word; 16], h: [$vec; 2], t: u64, nn: usize, } const IV: [$word; 8] = $IV; #[inline(always)] fn iv0() -> $vec { $vec::new(IV[0], IV[1], IV[2], IV[3]) } #[inline(always)] fn iv1() -> $vec { $vec::new(IV[4], IV[5], IV[6], IV[7]) } /// Convenience function for all-in-one computation. pub fn $func(nn: usize, k: &[u8], data: &[u8]) -> $result { let mut state = $state::with_key(nn, k); state.update(data); state.finalize() } impl $state { /// Creates a new hashing context without a key. pub fn new(nn: usize) -> Self { Self::with_key(nn, &[]) } /// Creates a new hashing context with a key. #[cfg_attr(feature = "clippy", allow(cast_possible_truncation))] pub fn with_key(nn: usize, k: &[u8]) -> Self { let kk = k.len(); assert!(nn >= 1 && nn <= $bytes && kk <= $bytes); let p0 = 0x01010000 ^ ((kk as $word) << 8) ^ (nn as $word); let mut state = $state { m: [0; 16], h: [iv0() ^ $vec::new(p0, 0, 0, 0), iv1()], t: 0, nn: nn, }; if kk > 0 { state.m.as_mut_bytes().copy_bytes_from(k); state.t = $bytes * 2; } state } #[doc(hidden)] #[cfg_attr(feature = "clippy", allow(cast_possible_truncation))] pub fn with_parameter_block(p: &[$word; 8]) -> Self { let nn = p[0] as u8 as usize; let kk = (p[0] >> 8) as u8 as usize; assert!(nn >= 1 && nn <= $bytes && kk <= $bytes); $state { m: [0; 16], h: [iv0() ^ $vec::new(p[0], p[1], p[2], p[3]), iv1() ^ $vec::new(p[4], p[5], p[6], p[7])], t: 0, nn: nn, } } /// Updates the hashing context with more data. #[cfg_attr(feature = "clippy", allow(cast_possible_truncation))] pub fn update(&mut self, data: &[u8]) { let mut rest = data; let off = (self.t % ($bytes * 2)) as usize; if off != 0 || self.t == 0 { let len = cmp::min(($bytes * 2) - off, rest.len()); let part = &rest[..len]; rest = &rest[part.len()..]; self.m.as_mut_bytes()[off..].copy_bytes_from(part); self.t = self.t.checked_add(part.len() as u64) .expect("hash data length overflow"); } while rest.len() >= $bytes * 2 { self.compress(0, 0); let part = &rest[..($bytes * 2)]; rest = &rest[part.len()..]; self.m.as_mut_bytes().copy_bytes_from(part); self.t = self.t.checked_add(part.len() as u64) .expect("hash data length overflow"); } if rest.len() > 0 { self.compress(0, 0); self.m.as_mut_bytes().copy_bytes_from(rest); self.t = self.t.checked_add(rest.len() as u64) .expect("hash data length overflow"); } } /// Consumes the hashing context and returns the resulting hash. pub fn finalize(self) -> $result { self.finalize_with_flag(0) } #[doc(hidden)] pub fn finalize_last_node(self) -> $result { self.finalize_with_flag(!0) } #[cfg_attr(feature = "clippy", allow(cast_possible_truncation))] fn finalize_with_flag(mut self, f1: $word) -> $result { let off = (self.t % ($bytes * 2)) as usize; if off != 0 { self.m.as_mut_bytes()[off..].set_bytes(0); } self.compress(!0, f1); $result { h: [self.h[0].to_le(), self.h[1].to_le()], nn: self.nn, } } #[inline(always)] fn quarter_round(v: &mut [$vec; 4], rd: u32, rb: u32, m: $vec) { v[0] = v[0].wrapping_add(v[1]).wrapping_add(m.from_le()); v[3] = (v[3] ^ v[0]).rotate_right_const(rd); v[2] = v[2].wrapping_add(v[3]); v[1] = (v[1] ^ v[2]).rotate_right_const(rb); } #[inline(always)] fn shuffle(v: &mut [$vec; 4]) { v[1] = v[1].shuffle_left_1(); v[2] = v[2].shuffle_left_2(); v[3] = v[3].shuffle_left_3(); } #[inline(always)] fn unshuffle(v: &mut [$vec; 4]) { v[1] = v[1].shuffle_right_1(); v[2] = v[2].shuffle_right_2(); v[3] = v[3].shuffle_right_3(); } #[inline(always)] fn round(v: &mut [$vec; 4], m: &[$word; 16], s: &[usize; 16]) { $state::quarter_round(v, $R1, $R2, $vec::gather(m, s[ 0], s[ 2], s[ 4], s[ 6])); $state::quarter_round(v, $R3, $R4, $vec::gather(m, s[ 1], s[ 3], s[ 5], s[ 7])); $state::shuffle(v); $state::quarter_round(v, $R1, $R2, $vec::gather(m, s[ 8], s[10], s[12], s[14])); $state::quarter_round(v, $R3, $R4, $vec::gather(m, s[ 9], s[11], s[13], s[15])); $state::unshuffle(v); } #[cfg_attr(feature = "clippy", allow(cast_possible_truncation, eq_op))] fn compress(&mut self, f0: $word, f1: $word) { use $crate::blake2::SIGMA; let m = &self.m; let h = &mut self.h; let t0 = self.t as $word; let t1 = match $bytes { 64 => 0, 32 => (self.t >> 32) as $word, _ => unreachable!(), }; let mut v = [ h[0], h[1], iv0(), iv1() ^ $vec::new(t0, t1, f0, f1), ]; $state::round(&mut v, m, &SIGMA[0]); $state::round(&mut v, m, &SIGMA[1]); $state::round(&mut v, m, &SIGMA[2]); $state::round(&mut v, m, &SIGMA[3]); $state::round(&mut v, m, &SIGMA[4]); $state::round(&mut v, m, &SIGMA[5]); $state::round(&mut v, m, &SIGMA[6]); $state::round(&mut v, m, &SIGMA[7]); $state::round(&mut v, m, &SIGMA[8]); $state::round(&mut v, m, &SIGMA[9]); if $bytes > 32 { $state::round(&mut v, m, &SIGMA[0]); $state::round(&mut v, m, &SIGMA[1]); } h[0] = h[0] ^ (v[0] ^ v[2]); h[1] = h[1] ^ (v[1] ^ v[3]); } } #[cfg(feature = "std")] impl io::Write for $state { fn write(&mut self, buf: &[u8]) -> io::Result { if self.t.checked_add(buf.len() as u64).is_none() { return Err(io::Error::new(io::ErrorKind::WriteZero, "counter overflow")); } self.update(buf); Ok(buf.len()) } #[inline] fn flush(&mut self) -> io::Result<()> { Ok(()) } } } } #[cfg_attr(feature = "clippy", allow(cast_possible_truncation))] #[cold] pub fn selftest_seq(len: usize) -> ArrayVec<[u8; 1024]> { use core::num::Wrapping; let seed = Wrapping(len as u32); let mut out = ArrayVec::new(); let mut a = Wrapping(0xDEAD4BAD) * seed; let mut b = Wrapping(1); for _ in 0..len { let t = a + b; a = b; b = t; out.push((t >> 24).0 as u8); } out } macro_rules! blake2_selftest_impl { ($state:ident, $func:ident, $res:expr, $md_len:expr, $in_len:expr) => { /// Runs the self-test for this hash function. #[cold] pub fn selftest() { use $crate::blake2::selftest_seq; const BLAKE2_RES: [u8; 32] = $res; const B2_MD_LEN: [usize; 4] = $md_len; const B2_IN_LEN: [usize; 6] = $in_len; let mut state = $state::new(32); for &outlen in &B2_MD_LEN { for &inlen in &B2_IN_LEN { let data = selftest_seq(inlen); let md = $func(outlen, &[], &data); state.update(md.as_bytes()); let key = selftest_seq(outlen); let md = $func(outlen, &key, &data); state.update(md.as_bytes()); } } assert_eq!(&state.finalize(), &BLAKE2_RES[..]); } } } macro_rules! blake2_bench_impl { ($state:ident, $bytes:expr) => { #[cfg(all(feature = "bench", test))] mod bench { use std::iter::repeat; use std::vec::Vec; use test::Bencher; use blake2::selftest_seq; use super::$state; fn bench_blake2(bytes: usize, b: &mut Bencher) { let data: Vec = repeat(selftest_seq(1024)) .flat_map(|v| v) .take(bytes) .collect(); b.bytes = bytes as u64; b.iter(|| { let mut state = $state::new($bytes); state.update(&data[..]); state.finalize() }) } #[bench] fn bench_16(b: &mut Bencher) { bench_blake2(16, b) } #[bench] fn bench_4k(b: &mut Bencher) { bench_blake2(4096, b) } #[bench] fn bench_64k(b: &mut Bencher) { bench_blake2(65536, b) } } } } blake2-rfc-0.2.18/src/blake2b.rs01006640001750000175000000007060132053764630014410 0ustar0000000000000000// Copyright 2015 blake2-rfc Developers // Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be // copied, modified, or distributed except according to those terms. //! The BLAKE2b hash function. //! //! # Examples //! //! ``` //! use blake2_rfc::blake2b::{Blake2b, blake2b}; //! //! // Using the convenience function. //! let hash = blake2b(64, &[], b"The quick brown fox jumps over the lazy dog"); //! //! // Using the state context. //! let mut context = Blake2b::new(64); //! context.update(b"The quick brown fox jumps over the lazy dog"); //! let hash = context.finalize(); //! //! // Using the convenience function, with a key. //! let hash = blake2b(64, b"key", b"The quick brown fox jumps over the lazy dog"); //! //! // Using the state context, with a key. //! let mut context = Blake2b::with_key(64, b"key"); //! context.update(b"The quick brown fox jumps over the lazy dog"); //! let hash = context.finalize(); //! ``` //! //! The returned hash is a `Blake2bResult`, which can be compared with //! a byte string (the comparison will take constant time), or converted //! into a byte string. blake2_impl!(Blake2b, Blake2bResult, blake2b, u64, u64x4, 64, 32, 24, 16, 63, [ 0x6A09E667F3BCC908, 0xBB67AE8584CAA73B, 0x3C6EF372FE94F82B, 0xA54FF53A5F1D36F1, 0x510E527FADE682D1, 0x9B05688C2B3E6C1F, 0x1F83D9ABFB41BD6B, 0x5BE0CD19137E2179, ]); blake2_selftest_impl!(Blake2b, blake2b, [ 0xC2, 0x3A, 0x78, 0x00, 0xD9, 0x81, 0x23, 0xBD, 0x10, 0xF5, 0x06, 0xC6, 0x1E, 0x29, 0xDA, 0x56, 0x03, 0xD7, 0x63, 0xB8, 0xBB, 0xAD, 0x2E, 0x73, 0x7F, 0x5E, 0x76, 0x5A, 0x7B, 0xCC, 0xD4, 0x75, ], [ 20, 32, 48, 64 ], [ 0, 3, 128, 129, 255, 1024 ]); blake2_bench_impl!(Blake2b, 64); #[cfg(test)] mod tests { #![cfg_attr(feature = "clippy", allow(result_unwrap_used))] extern crate data_encoding; use self::data_encoding::HEXUPPER; use blake2::selftest_seq; use super::{Blake2b, blake2b}; #[test] fn test_empty() { assert_eq!(&blake2b(64, &[], b""), &HEXUPPER.decode( b"786A02F742015903C6C6FD852552D272912F4740E15847618A86E217F71F5419D25E1031AFEE585313896444934EB04B903A685B1448B755D56F701AFE9BE2CE") .unwrap()[..]); } #[test] fn selftest() { super::selftest(); } #[test] fn test_split() { let data = selftest_seq(512); let mut ctx = Blake2b::new(64); ctx.update(&data[..32]); ctx.update(&data[32..64]); ctx.update(&data[64..448]); ctx.update(&data[448..]); assert_eq!(&ctx.finalize(), &blake2b(64, &[], &data)); } #[cfg(feature = "std")] #[test] fn test_write() { use std::io::prelude::*; let data = selftest_seq(1024); let mut ctx = Blake2b::new(64); ctx.update(&data[..]); let mut writer = Blake2b::new(64); writer.write_all(&data[..]).unwrap(); assert_eq!(&writer.finalize(), &ctx.finalize()); } #[cfg_attr(debug_assertions, ignore)] #[test] fn test_4g() { const ZEROS: [u8; 4096] = [0; 4096]; let mut state = Blake2b::new(64); for _ in 0..1048576 { state.update(&ZEROS); } assert_eq!(&state.finalize(), &HEXUPPER.decode( b"645572CA5756F9104329ED543735FC11904F0C18C4DF8ADF930F22D07F3094919A519FF34FD240AE3F5D5B4C8042225C109FB951036FDC99E7D2CD0C1D36B267") .unwrap()[..]); } } blake2-rfc-0.2.18/src/blake2s.rs01006640001750000175000000006546132053764630014441 0ustar0000000000000000// Copyright 2015 blake2-rfc Developers // Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be // copied, modified, or distributed except according to those terms. //! The BLAKE2s hash function. //! //! # Examples //! //! ``` //! use blake2_rfc::blake2s::{Blake2s, blake2s}; //! //! // Using the convenience function. //! let hash = blake2s(32, &[], b"The quick brown fox jumps over the lazy dog"); //! //! // Using the state context. //! let mut context = Blake2s::new(32); //! context.update(b"The quick brown fox jumps over the lazy dog"); //! let hash = context.finalize(); //! //! // Using the convenience function, with a key. //! let hash = blake2s(32, b"key", b"The quick brown fox jumps over the lazy dog"); //! //! // Using the state context, with a key. //! let mut context = Blake2s::with_key(32, b"key"); //! context.update(b"The quick brown fox jumps over the lazy dog"); //! let hash = context.finalize(); //! ``` //! //! The returned hash is a `Blake2sResult`, which can be compared with //! a byte string (the comparison will take constant time), or converted //! into a byte string. blake2_impl!(Blake2s, Blake2sResult, blake2s, u32, u32x4, 32, 16, 12, 8, 7, [ 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19, ]); blake2_selftest_impl!(Blake2s, blake2s, [ 0x6A, 0x41, 0x1F, 0x08, 0xCE, 0x25, 0xAD, 0xCD, 0xFB, 0x02, 0xAB, 0xA6, 0x41, 0x45, 0x1C, 0xEC, 0x53, 0xC5, 0x98, 0xB2, 0x4F, 0x4F, 0xC7, 0x87, 0xFB, 0xDC, 0x88, 0x79, 0x7F, 0x4C, 0x1D, 0xFE, ], [ 16, 20, 28, 32 ], [ 0, 3, 64, 65, 255, 1024 ]); blake2_bench_impl!(Blake2s, 32); #[cfg(test)] mod tests { #![cfg_attr(feature = "clippy", allow(result_unwrap_used))] extern crate data_encoding; use self::data_encoding::HEXUPPER; use blake2::selftest_seq; use super::{Blake2s, blake2s}; #[test] fn test_empty() { assert_eq!(&blake2s(32, &[], b""), &HEXUPPER.decode( b"69217A3079908094E11121D042354A7C1F55B6482CA1A51E1B250DFD1ED0EEF9") .unwrap()[..]); } #[test] fn selftest() { super::selftest(); } #[test] fn test_split() { let data = selftest_seq(256); let mut ctx = Blake2s::new(32); ctx.update(&data[..16]); ctx.update(&data[16..32]); ctx.update(&data[32..224]); ctx.update(&data[224..]); assert_eq!(&ctx.finalize(), &blake2s(32, &[], &data)); } #[cfg(feature = "std")] #[test] fn test_write() { use std::io::prelude::*; let data = selftest_seq(1024); let mut ctx = Blake2s::new(32); ctx.update(&data[..]); let mut writer = Blake2s::new(32); writer.write_all(&data[..]).unwrap(); assert_eq!(&writer.finalize(), &ctx.finalize()); } #[cfg_attr(debug_assertions, ignore)] #[test] fn test_4g() { const ZEROS: [u8; 4096] = [0; 4096]; let mut state = Blake2s::new(32); for _ in 0..1048576 { state.update(&ZEROS); } assert_eq!(&state.finalize(), &HEXUPPER.decode( b"2A8E26830310DA3EF7F7032B7B1AF11B989ABA44A3713A22F539F69BD2CE4A87") .unwrap()[..]); } } blake2-rfc-0.2.18/src/bytes.rs01006640001750000175000000002172132053764630014233 0ustar0000000000000000// Copyright 2015 blake2-rfc Developers // // Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be // copied, modified, or distributed except according to those terms. //! Operations on byte slices. use core::ptr; /// Operations on byte slices. pub trait BytesExt { /// Set all bytes of this slice to the same value. /// /// Equivalent to C's memset(). fn set_bytes(&mut self, value: u8); /// Copy all bytes from a source slice to the start of this slice. /// /// Equivalent to C's memcpy(). fn copy_bytes_from(&mut self, src: &[u8]); } impl BytesExt for [u8] { #[inline] fn set_bytes(&mut self, value: u8) { unsafe { ptr::write_bytes(self.as_mut_ptr(), value, self.len()); } } #[inline] fn copy_bytes_from(&mut self, src: &[u8]) { assert!(src.len() <= self.len()); unsafe { ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), src.len()); } } } blake2-rfc-0.2.18/src/lib.rs01006640001750000175000000002450132057705030013643 0ustar0000000000000000// Copyright 2015 blake2-rfc Developers // // Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be // copied, modified, or distributed except according to those terms. //! A pure Rust implementation of BLAKE2 based on RFC 7693. #![no_std] #![warn(missing_docs)] #![cfg_attr(feature = "clippy", feature(plugin))] #![cfg_attr(feature = "clippy", plugin(clippy))] #![cfg_attr(feature = "clippy", warn(clippy_pedantic))] #![cfg_attr(all(feature = "bench", test), feature(test))] #![cfg_attr(feature = "simd", feature(platform_intrinsics, repr_simd))] #![cfg_attr(feature = "simd_opt", feature(cfg_target_feature))] #![cfg_attr(feature = "simd_asm", feature(asm))] #[cfg(any(feature = "std", all(feature = "bench", test)))] #[macro_use] extern crate std; #[cfg(all(feature = "bench", test))] extern crate test; extern crate arrayvec; extern crate constant_time_eq; mod as_bytes; mod bytes; mod simdty; mod simdint; mod simdop; mod simd_opt; mod simd; #[macro_use] mod blake2; pub mod blake2b; pub mod blake2s; /// Runs the self-test for both BLAKE2b and BLAKE2s. #[cold] pub fn selftest() { blake2b::selftest(); blake2s::selftest(); } blake2-rfc-0.2.18/src/simd.rs01006640001750000175000000007475130417003010014030 0ustar0000000000000000// Copyright 2015 blake2-rfc Developers // // Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be // copied, modified, or distributed except according to those terms. #![cfg_attr(feature = "clippy", allow(inline_always))] use simd_opt; pub use simdty::{u32x4, u64x4}; pub trait Vector4: Copy { fn gather(src: &[T], i0: usize, i1: usize, i2: usize, i3: usize) -> Self; fn from_le(self) -> Self; fn to_le(self) -> Self; fn wrapping_add(self, rhs: Self) -> Self; fn rotate_right_const(self, n: u32) -> Self; fn shuffle_left_1(self) -> Self; fn shuffle_left_2(self) -> Self; fn shuffle_left_3(self) -> Self; #[inline(always)] fn shuffle_right_1(self) -> Self { self.shuffle_left_3() } #[inline(always)] fn shuffle_right_2(self) -> Self { self.shuffle_left_2() } #[inline(always)] fn shuffle_right_3(self) -> Self { self.shuffle_left_1() } } macro_rules! impl_vector4 { ($vec:ident, $word:ident) => { impl Vector4<$word> for $vec { #[inline(always)] fn gather(src: &[$word], i0: usize, i1: usize, i2: usize, i3: usize) -> Self { $vec::new(src[i0], src[i1], src[i2], src[i3]) } #[cfg(target_endian = "little")] #[inline(always)] fn from_le(self) -> Self { self } #[cfg(not(target_endian = "little"))] #[inline(always)] fn from_le(self) -> Self { $vec::new($word::from_le(self.0), $word::from_le(self.1), $word::from_le(self.2), $word::from_le(self.3)) } #[cfg(target_endian = "little")] #[inline(always)] fn to_le(self) -> Self { self } #[cfg(not(target_endian = "little"))] #[inline(always)] fn to_le(self) -> Self { $vec::new(self.0.to_le(), self.1.to_le(), self.2.to_le(), self.3.to_le()) } #[inline(always)] fn wrapping_add(self, rhs: Self) -> Self { self + rhs } #[inline(always)] fn rotate_right_const(self, n: u32) -> Self { simd_opt::$vec::rotate_right_const(self, n) } #[cfg(feature = "simd")] #[inline(always)] fn shuffle_left_1(self) -> Self { use simdint::simd_shuffle4; unsafe { simd_shuffle4(self, self, [1, 2, 3, 0]) } } #[cfg(not(feature = "simd"))] #[inline(always)] fn shuffle_left_1(self) -> Self { $vec::new(self.1, self.2, self.3, self.0) } #[cfg(feature = "simd")] #[inline(always)] fn shuffle_left_2(self) -> Self { use simdint::simd_shuffle4; unsafe { simd_shuffle4(self, self, [2, 3, 0, 1]) } } #[cfg(not(feature = "simd"))] #[inline(always)] fn shuffle_left_2(self) -> Self { $vec::new(self.2, self.3, self.0, self.1) } #[cfg(feature = "simd")] #[inline(always)] fn shuffle_left_3(self) -> Self { use simdint::simd_shuffle4; unsafe { simd_shuffle4(self, self, [3, 0, 1, 2]) } } #[cfg(not(feature = "simd"))] #[inline(always)] fn shuffle_left_3(self) -> Self { $vec::new(self.3, self.0, self.1, self.2) } } } } impl_vector4!(u32x4, u32); impl_vector4!(u64x4, u64); blake2-rfc-0.2.18/src/simd_opt/mod.rs01006640001750000175000000002615132061217600015471 0ustar0000000000000000// Copyright 2015 blake2-rfc Developers // // Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be // copied, modified, or distributed except according to those terms. #![cfg_attr(feature = "clippy", allow(inline_always))] #[cfg(feature = "simd")] macro_rules! transmute_shuffle { ($tmp:ident, $shuffle:ident, $vec:expr, $idx:expr) => { unsafe { use simdty::$tmp; use simdint::$shuffle; use core::mem::transmute; let tmp_i: $tmp = transmute($vec); let tmp_o: $tmp = $shuffle(tmp_i, tmp_i, $idx); transmute(tmp_o) } } } #[cfg(feature = "simd")] pub mod u32x4; #[cfg(feature = "simd")] pub mod u64x4; #[cfg(not(feature = "simd"))] macro_rules! simd_opt { ($vec:ident) => { pub mod $vec { use simdty::$vec; #[inline(always)] pub fn rotate_right_const(vec: $vec, n: u32) -> $vec { $vec::new(vec.0.rotate_right(n), vec.1.rotate_right(n), vec.2.rotate_right(n), vec.3.rotate_right(n)) } } } } #[cfg(not(feature = "simd"))] simd_opt!(u32x4); #[cfg(not(feature = "simd"))] simd_opt!(u64x4); blake2-rfc-0.2.18/src/simd_opt/u32x4.rs01006640001750000175000000004242130417003010015564 0ustar0000000000000000// Copyright 2015 blake2-rfc Developers // // Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be // copied, modified, or distributed except according to those terms. #![cfg_attr(feature = "clippy", allow(inline_always))] use simdty::u32x4; #[cfg(feature = "simd_opt")] #[inline(always)] pub fn rotate_right_const(vec: u32x4, n: u32) -> u32x4 { match n { 16 => rotate_right_16(vec), 8 => rotate_right_8(vec), _ => rotate_right_any(vec, n), } } #[cfg(not(feature = "simd_opt"))] #[inline(always)] pub fn rotate_right_const(vec: u32x4, n: u32) -> u32x4 { rotate_right_any(vec, n) } #[inline(always)] fn rotate_right_any(vec: u32x4, n: u32) -> u32x4 { let r = n as u32; let l = 32 - r; (vec >> u32x4::new(r, r, r, r)) ^ (vec << u32x4::new(l, l, l, l)) } #[cfg(feature = "simd_opt")] #[inline(always)] fn rotate_right_16(vec: u32x4) -> u32x4 { if cfg!(target_feature = "ssse3") { // pshufb (SSSE3) / vpshufb (AVX2) transmute_shuffle!(u8x16, simd_shuffle16, vec, [ 2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9, 14, 15, 12, 13]) } else if cfg!(any(target_feature = "sse2", target_feature = "neon")) { // pshuflw+pshufhw (SSE2) / vrev (NEON) transmute_shuffle!(u16x8, simd_shuffle8, vec, [1, 0, 3, 2, 5, 4, 7, 6]) } else { rotate_right_any(vec, 16) } } #[cfg(feature = "simd_opt")] #[inline(always)] fn rotate_right_8(vec: u32x4) -> u32x4 { if cfg!(target_feature = "ssse3") { // pshufb (SSSE3) / vpshufb (AVX2) transmute_shuffle!(u8x16, simd_shuffle16, vec, [ 1, 2, 3, 0, 5, 6, 7, 4, 9, 10, 11, 8, 13, 14, 15, 12]) } else { rotate_right_any(vec, 8) } } blake2-rfc-0.2.18/src/simd_opt/u64x4.rs01006640001750000175000000010503132061217650015604 0ustar0000000000000000// Copyright 2015 blake2-rfc Developers // // Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be // copied, modified, or distributed except according to those terms. #![cfg_attr(feature = "clippy", allow(inline_always))] use simdty::u64x4; #[cfg(feature = "simd_opt")] #[inline(always)] pub fn rotate_right_const(vec: u64x4, n: u32) -> u64x4 { match n { 32 => rotate_right_32(vec), 24 => rotate_right_24(vec), 16 => rotate_right_16(vec), _ => rotate_right_any(vec, n), } } #[cfg(not(feature = "simd_opt"))] #[inline(always)] pub fn rotate_right_const(vec: u64x4, n: u32) -> u64x4 { rotate_right_any(vec, n) } #[inline(always)] fn rotate_right_any(vec: u64x4, n: u32) -> u64x4 { let r = n as u64; let l = 64 - r; (vec >> u64x4::new(r, r, r, r)) ^ (vec << u64x4::new(l, l, l, l)) } #[cfg(feature = "simd_opt")] #[inline(always)] fn rotate_right_32(vec: u64x4) -> u64x4 { if cfg!(any(target_feature = "sse2", target_feature = "neon")) { // 2 x pshufd (SSE2) / vpshufd (AVX2) / 2 x vrev (NEON) transmute_shuffle!(u32x8, simd_shuffle8, vec, [1, 0, 3, 2, 5, 4, 7, 6]) } else { rotate_right_any(vec, 32) } } #[cfg(feature = "simd_opt")] #[inline(always)] fn rotate_right_24(vec: u64x4) -> u64x4 { if cfg!(all(feature = "simd_asm", target_feature = "neon", target_arch = "arm")) { // 4 x vext (NEON) rotate_right_vext(vec, 3) } else if cfg!(target_feature = "ssse3") { // 2 x pshufb (SSSE3) / vpshufb (AVX2) transmute_shuffle!(u8x32, simd_shuffle32, vec, [ 3, 4, 5, 6, 7, 0, 1, 2, 11, 12, 13, 14, 15, 8, 9, 10, 19, 20, 21, 22, 23, 16, 17, 18, 27, 28, 29, 30, 31, 24, 25, 26]) } else { rotate_right_any(vec, 24) } } #[cfg(feature = "simd_opt")] #[inline(always)] fn rotate_right_16(vec: u64x4) -> u64x4 { if cfg!(all(feature = "simd_asm", target_feature = "neon", target_arch = "arm")) { // 4 x vext (NEON) rotate_right_vext(vec, 2) } else if cfg!(target_feature = "ssse3") { // 2 x pshufb (SSSE3) / vpshufb (AVX2) transmute_shuffle!(u8x32, simd_shuffle32, vec, [ 2, 3, 4, 5, 6, 7, 0, 1, 10, 11, 12, 13, 14, 15, 8, 9, 18, 19, 20, 21, 22, 23, 16, 17, 26, 27, 28, 29, 30, 31, 24, 25]) } else if cfg!(target_feature = "sse2") { // 2 x pshuflw+pshufhw (SSE2) transmute_shuffle!(u16x16, simd_shuffle16, vec, [ 1, 2, 3, 0, 5, 6, 7, 4, 9, 10, 11, 8, 13, 14, 15, 12]) } else { rotate_right_any(vec, 16) } } #[cfg(all(feature = "simd_asm", target_feature = "neon", target_arch = "arm"))] mod simd_asm_neon_arm { use simdty::{u64x2, u64x4}; #[inline(always)] fn vext_u64(vec: u64x2, b: u8) -> u64x2 { unsafe { let result: u64x2; asm!("vext.8 ${0:e}, ${1:e}, ${1:e}, $2\nvext.8 ${0:f}, ${1:f}, ${1:f}, $2" : "=w" (result) : "w" (vec), "n" (b)); result } } #[inline(always)] pub fn rotate_right_vext(vec: u64x4, b: u8) -> u64x4 { use simdint::{simd_shuffle2, simd_shuffle4}; unsafe { let tmp0 = vext_u64(simd_shuffle2(vec, vec, [0, 1]), b); let tmp1 = vext_u64(simd_shuffle2(vec, vec, [2, 3]), b); simd_shuffle4(tmp0, tmp1, [0, 1, 2, 3]) } } } #[cfg(all(feature = "simd_asm", target_feature = "neon", target_arch = "arm"))] use self::simd_asm_neon_arm::rotate_right_vext; #[cfg(feature = "simd_opt")] #[cfg(not(all(feature = "simd_asm", target_feature = "neon", target_arch = "arm")))] fn rotate_right_vext(_vec: u64x4, _n: u8) -> u64x4 { unreachable!() } blake2-rfc-0.2.18/src/simdint.rs01006640001750000175000000001612130417003010014526 0ustar0000000000000000// Copyright 2015 blake2-rfc Developers // // Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be // copied, modified, or distributed except according to those terms. #![allow(dead_code)] #[cfg(feature = "simd")] extern "platform-intrinsic" { pub fn simd_add(x: T, y: T) -> T; pub fn simd_shl(x: T, y: T) -> T; pub fn simd_shr(x: T, y: T) -> T; pub fn simd_xor(x: T, y: T) -> T; pub fn simd_shuffle2(v: T, w: T, idx: [u32; 2]) -> U; pub fn simd_shuffle4(v: T, w: T, idx: [u32; 4]) -> U; pub fn simd_shuffle8(v: T, w: T, idx: [u32; 8]) -> U; pub fn simd_shuffle16(v: T, w: T, idx: [u32; 16]) -> U; pub fn simd_shuffle32(v: T, w: T, idx: [u32; 32]) -> U; } blake2-rfc-0.2.18/src/simdop.rs01006640001750000175000000005525132053764630014405 0ustar0000000000000000// Copyright 2015 blake2-rfc Developers // // Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be // copied, modified, or distributed except according to those terms. use simdty::{u32x4, u64x4}; #[cfg(feature = "simd")] use simdint; use core::ops::{Add, BitXor, Shl, Shr}; macro_rules! impl_ops { ($vec:ident) => { impl Add for $vec { type Output = Self; #[cfg(feature = "simd")] #[inline(always)] fn add(self, rhs: Self) -> Self::Output { unsafe { simdint::simd_add(self, rhs) } } #[cfg(not(feature = "simd"))] #[inline(always)] fn add(self, rhs: Self) -> Self::Output { $vec::new(self.0.wrapping_add(rhs.0), self.1.wrapping_add(rhs.1), self.2.wrapping_add(rhs.2), self.3.wrapping_add(rhs.3)) } } impl BitXor for $vec { type Output = Self; #[cfg(feature = "simd")] #[inline(always)] fn bitxor(self, rhs: Self) -> Self::Output { unsafe { simdint::simd_xor(self, rhs) } } #[cfg(not(feature = "simd"))] #[inline(always)] fn bitxor(self, rhs: Self) -> Self::Output { $vec::new(self.0 ^ rhs.0, self.1 ^ rhs.1, self.2 ^ rhs.2, self.3 ^ rhs.3) } } impl Shl<$vec> for $vec { type Output = Self; #[cfg(feature = "simd")] #[inline(always)] fn shl(self, rhs: Self) -> Self::Output { unsafe { simdint::simd_shl(self, rhs) } } #[cfg(not(feature = "simd"))] #[inline(always)] fn shl(self, rhs: Self) -> Self::Output { $vec::new(self.0 << rhs.0, self.1 << rhs.1, self.2 << rhs.2, self.3 << rhs.3) } } impl Shr<$vec> for $vec { type Output = Self; #[cfg(feature = "simd")] #[inline(always)] fn shr(self, rhs: Self) -> Self::Output { unsafe { simdint::simd_shr(self, rhs) } } #[cfg(not(feature = "simd"))] #[inline(always)] fn shr(self, rhs: Self) -> Self::Output { $vec::new(self.0 >> rhs.0, self.1 >> rhs.1, self.2 >> rhs.2, self.3 >> rhs.3) } } } } impl_ops!(u32x4); impl_ops!(u64x4); blake2-rfc-0.2.18/src/simdty.rs01006640001750000175000000004366130417003010014401 0ustar0000000000000000// Copyright 2016 blake2-rfc Developers // // Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be // copied, modified, or distributed except according to those terms. #![allow(dead_code)] #![allow(non_camel_case_types)] use as_bytes::Safe; #[cfg(feature = "simd")] macro_rules! decl_simd { ($($decl:item)*) => { $( #[derive(Clone, Copy, Debug)] #[repr(simd)] $decl )* } } #[cfg(not(feature = "simd"))] macro_rules! decl_simd { ($($decl:item)*) => { $( #[derive(Clone, Copy, Debug)] #[repr(C)] $decl )* } } decl_simd! { pub struct Simd2(pub T, pub T); pub struct Simd4(pub T, pub T, pub T, pub T); pub struct Simd8(pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T); pub struct Simd16(pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T); pub struct Simd32(pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T, pub T); } pub type u64x2 = Simd2; pub type u32x4 = Simd4; pub type u64x4 = Simd4; pub type u16x8 = Simd8; pub type u32x8 = Simd8; pub type u8x16 = Simd16; pub type u16x16 = Simd16; pub type u8x32 = Simd32; #[cfg_attr(feature = "clippy", allow(inline_always))] impl Simd4 { #[inline(always)] pub fn new(e0: T, e1: T, e2: T, e3: T) -> Simd4 { Simd4(e0, e1, e2, e3) } } unsafe impl Safe for Simd2 {} unsafe impl Safe for Simd4 {} unsafe impl Safe for Simd8 {} unsafe impl Safe for Simd16 {} unsafe impl Safe for Simd32 {}