polyval-0.6.1/.cargo_vcs_info.json0000644000000001450000000000100125260ustar { "git": { "sha1": "11d38e870b6bf53d980947b9d6a6a6588a2f6947" }, "path_in_vcs": "polyval" }polyval-0.6.1/CHANGELOG.md000064400000000000000000000121160072674642500131600ustar 00000000000000# 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.6.1 (2023-06-16) ### Added - Support for `polyval_armv8` on Rust 1.61+ ([#179]) [#179]: https://github.com/RustCrypto/universal-hashes/pull/179 ## 0.6.0 (2022-07-31) ### Added - Impl `Reset` ([#157]) ### Changed - Remove `sse4.1` from CPU feature requirements for PCLMUL backend ([#143]) - Relax `zeroize` constraints ([#147]) - Upgrade to Rust 2021 edition ([#147]) - Use stable `aarch64_target_feature` ([#154]) - Replace `armv8`/`force-soft` features with `cfg` attributes ([#159]) - Bump `universal-hash` to v0.5 ([#155], [#162]) [#143]: https://github.com/RustCrypto/universal-hashes/pull/143 [#147]: https://github.com/RustCrypto/universal-hashes/pull/147 [#154]: https://github.com/RustCrypto/universal-hashes/pull/154 [#155]: https://github.com/RustCrypto/universal-hashes/pull/155 [#157]: https://github.com/RustCrypto/universal-hashes/pull/157 [#159]: https://github.com/RustCrypto/universal-hashes/pull/159 [#162]: https://github.com/RustCrypto/universal-hashes/pull/162 ## 0.5.3 (2021-08-27) ### Changed - Bump `cpufeatures` dependency to v0.2 ([#136], [#138]) - Remove use of ARMv8 `crypto` feature ([#137]) [#136]: https://github.com/RustCrypto/universal-hashes/pull/136 [#137]: https://github.com/RustCrypto/universal-hashes/pull/137 [#138]: https://github.com/RustCrypto/universal-hashes/pull/138 ## 0.5.2 (2021-07-20) ### Changed - Pin `zeroize` dependency to v1.3 ([#134]) [#134]: https://github.com/RustCrypto/universal-hashes/pull/134 ## 0.5.1 (2021-05-31) ### Added - Nightly-only ARMv8 intrinsics support gated under the `armv8` feature ([#126]) [#126]: https://github.com/RustCrypto/universal-hashes/pull/126 ## 0.5.0 (2021-04-29) ### Changed - Use `ManuallyDrop` unions; MSRV 1.49+ ([#113], [#114]) - Replace `cpuid-bool` with `cpufeatures` ([#116]) ### Removed - `mulx` feature: now always built-in ([#118]) [#113]: https://github.com/RustCrypto/universal-hashes/pull/113 [#114]: https://github.com/RustCrypto/universal-hashes/pull/114 [#116]: https://github.com/RustCrypto/universal-hashes/pull/116 [#118]: https://github.com/RustCrypto/universal-hashes/pull/118 ## 0.4.5 (2020-12-26) ### Changed - Use `u128` to impl `mulx` ([#111]) [#111]: https://github.com/RustCrypto/universal-hashes/pull/111 ## 0.4.4 (2020-12-26) ### Added - `Debug` impl using `opaque-debug` ([#105]) - `mulx` feature ([#107]) [#105]: https://github.com/RustCrypto/universal-hashes/pull/105 [#107]: https://github.com/RustCrypto/universal-hashes/pull/107 ## 0.4.3 (2020-12-08) ### Added - CLMUL detection ([#92]) [#92]: https://github.com/RustCrypto/universal-hashes/pull/92 ## 0.4.2 (2020-11-25) ### Added - `KEY_SIZE` constant ([#82]) ### Changed - Bump `cfg-if` from v0.1 to v1.0.0 ([#86]) [#86]: https://github.com/RustCrypto/universal-hashes/pull/86 [#82]: https://github.com/RustCrypto/universal-hashes/pull/82 ## 0.4.1 (2020-09-26) ### Changed - Performance improvements ([#75]) [#75]: https://github.com/RustCrypto/universal-hashes/pull/75 ## 0.4.0 (2020-06-06) ### Changed - Bump `universal-hash` dependency to v0.4; MSRV 1.41 ([#52], [#57]) - Rename `result` methods to to `finalize` ([#56]) [#57]: https://github.com/RustCrypto/universal-hashes/pull/57 [#56]: https://github.com/RustCrypto/universal-hashes/pull/56 [#52]: https://github.com/RustCrypto/universal-hashes/pull/52 ## 0.3.3 (2019-12-21) ### Changed - Match ideal assembly implementation on x86/x86_64 ([#43], [#44]) [#43]: https://github.com/RustCrypto/universal-hashes/pull/43 [#44]: https://github.com/RustCrypto/universal-hashes/pull/44 ## 0.3.2 (2019-12-05) ### Added - Constant-time 32-bit software implementation ([#39]) ### Changed - Use `cfg-if` crate to reduce duplication ([#40]) [#39]: https://github.com/RustCrypto/universal-hashes/pull/39 [#40]: https://github.com/RustCrypto/universal-hashes/pull/40 ## 0.3.1 (2019-11-14) ### Changed - Upgrade to `zeroize` 1.0 ([#33]) [#33]: https://github.com/RustCrypto/universal-hashes/pull/33 ## 0.3.0 (2019-10-05) ### Removed - Remove `pub` from `field` module ([#28]) [#28]: https://github.com/RustCrypto/universal-hashes/pull/28 ## 0.2.0 (2019-10-04) ### Changed - Upgrade to `universal-hash` crate v0.3 ([#22]) [#22]: https://github.com/RustCrypto/universal-hashes/pull/22 ## 0.1.1 (2019-10-01) ### Changed - Upgrade to `zeroize` v1.0.0-pre ([#19]) [#19]: https://github.com/RustCrypto/universal-hashes/pull/19 ## 0.1.0 (2019-09-19) ### Added - Constant time software implementation ([#7]) ### Changed - Update to Rust 2018 edition ([#3]) - Use `UniversalHash` trait ([#6]) - Removed generics/traits from `field::Element` API ([#12]) ### Removed - `insecure-soft` cargo feature ([#7]) [#3]: https://github.com/RustCrypto/universal-hashes/pull/3 [#6]: https://github.com/RustCrypto/universal-hashes/pull/6 [#7]: https://github.com/RustCrypto/universal-hashes/pull/7 [#12]: https://github.com/RustCrypto/universal-hashes/pull/12 ## 0.0.1 (2019-08-26) - Initial release polyval-0.6.1/Cargo.toml0000644000000030770000000000100105330ustar # 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 = "2021" rust-version = "1.56" name = "polyval" version = "0.6.1" authors = ["RustCrypto Developers"] description = """ POLYVAL is a GHASH-like universal hash over GF(2^128) useful for constructing a Message Authentication Code (MAC) """ documentation = "https://docs.rs/polyval" readme = "README.md" keywords = [ "aes-gcm", "aes-gcm-siv", "crypto", "ghash", "universal-hashing", ] categories = [ "cryptography", "no-std", ] license = "Apache-2.0 OR MIT" repository = "https://github.com/RustCrypto/universal-hashes" resolver = "2" [package.metadata.docs.rs] all-features = true rustdoc-args = [ "--cfg", "docsrs", ] [dependencies.cfg-if] version = "1" [dependencies.opaque-debug] version = "0.3" [dependencies.universal-hash] version = "0.5" default-features = false [dependencies.zeroize] version = "1" optional = true default-features = false [dev-dependencies.hex-literal] version = "0.3" [features] std = ["universal-hash/std"] [target."cfg(any(target_arch = \"aarch64\", target_arch = \"x86_64\", target_arch = \"x86\"))".dependencies.cpufeatures] version = "0.2" polyval-0.6.1/Cargo.toml.orig000064400000000000000000000017510072674642500142410ustar 00000000000000[package] name = "polyval" version = "0.6.1" authors = ["RustCrypto Developers"] license = "Apache-2.0 OR MIT" description = """ POLYVAL is a GHASH-like universal hash over GF(2^128) useful for constructing a Message Authentication Code (MAC) """ documentation = "https://docs.rs/polyval" repository = "https://github.com/RustCrypto/universal-hashes" readme = "README.md" keywords = ["aes-gcm", "aes-gcm-siv", "crypto", "ghash", "universal-hashing"] categories = ["cryptography", "no-std"] rust-version = "1.56" edition = "2021" [dependencies] cfg-if = "1" opaque-debug = "0.3" universal-hash = { version = "0.5", default-features = false } zeroize = { version = "1", optional = true, default-features = false } [target.'cfg(any(target_arch = "aarch64", target_arch = "x86_64", target_arch = "x86"))'.dependencies] cpufeatures = "0.2" [dev-dependencies] hex-literal = "0.3" [features] std = ["universal-hash/std"] [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg", "docsrs"] polyval-0.6.1/LICENSE-APACHE000064400000000000000000000251410072674642500132750ustar 00000000000000 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. polyval-0.6.1/LICENSE-MIT000064400000000000000000000020560072674642500130050ustar 00000000000000Copyright (c) 2019-2023 RustCrypto Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. polyval-0.6.1/README.md000064400000000000000000000054560072674642500126370ustar 00000000000000# RustCrypto: POLYVAL [![crate][crate-image]][crate-link] [![Docs][docs-image]][docs-link] [![Build Status][build-image]][build-link] ![Apache2/MIT licensed][license-image] ![Rust Version][rustc-image] [POLYVAL][1] ([RFC 8452][2]) is a [universal hash function][3] which operates over GF(2^128) and can be used for constructing a [Message Authentication Code (MAC)][4]. Its primary intended use is for implementing [AES-GCM-SIV][5], however it is closely related to [GHASH][6] and therefore can also be used to implement [AES-GCM][7] at no cost to performance on little endian architectures. [Documentation][docs-link] ## Security Notes This crate has received one [security audit by NCC Group][8], with no significant findings. We would like to thank [MobileCoin][9] for funding the audit. All implementations contained in the crate are designed to execute in constant time, either by relying on hardware intrinsics (i.e. AVX2 on x86/x86_64), or using a portable implementation which is only constant time on processors which implement constant-time multiplication. It is not suitable for use on processors with a variable-time multiplication operation (e.g. short circuit on multiply-by-zero / multiply-by-one, such as certain 32-bit PowerPC CPUs and some non-ARM microcontrollers). ## 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://buildstats.info/crate/polyval [crate-link]: https://crates.io/crates/polyval [docs-image]: https://docs.rs/polyval/badge.svg [docs-link]: https://docs.rs/polyval/ [build-image]: https://github.com/RustCrypto/universal-hashes/workflows/polyval/badge.svg?branch=master&event=push [build-link]: https://github.com/RustCrypto/universal-hashes/actions?query=workflow%3Apolyval [license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg [rustc-image]: https://img.shields.io/badge/rustc-1.56+-blue.svg [//]: # (footnotes) [1]: https://en.wikipedia.org/wiki/AES-GCM-SIV#Operation [2]: https://tools.ietf.org/html/rfc8452#section-3 [3]: https://en.wikipedia.org/wiki/Universal_hashing [4]: https://en.wikipedia.org/wiki/Message_authentication_code [5]: https://en.wikipedia.org/wiki/AES-GCM-SIV [6]: https://en.wikipedia.org/wiki/Galois/Counter_Mode#Mathematical_basis [7]: https://en.wikipedia.org/wiki/Galois/Counter_Mode [8]: https://research.nccgroup.com/2020/02/26/public-report-rustcrypto-aes-gcm-and-chacha20poly1305-implementation-review/ [9]: https://www.mobilecoin.com/ polyval-0.6.1/benches/polyval.rs000064400000000000000000000012200072674642500150040ustar 00000000000000#![feature(test)] extern crate test; use polyval::{ universal_hash::{KeyInit, UniversalHash}, Polyval, }; use test::Bencher; // TODO(tarcieri): move this into the `universal-hash` crate macro_rules! bench { ($name:ident, $bs:expr) => { #[bench] fn $name(b: &mut Bencher) { let key = Default::default(); let mut m = Polyval::new(&key); let data = [0; $bs]; b.iter(|| { m.update_padded(&data); }); b.bytes = $bs; } }; } bench!(bench1_10, 10); bench!(bench2_100, 100); bench!(bench3_1000, 1000); bench!(bench3_10000, 10000); polyval-0.6.1/src/backend/autodetect.rs000064400000000000000000000055740072674642500162460ustar 00000000000000//! Autodetection for CPU intrinsics, with fallback to the "soft" backend when //! they are unavailable. use crate::{backend::soft, Key, Tag}; use core::mem::ManuallyDrop; use universal_hash::{ consts::U16, crypto_common::{BlockSizeUser, KeySizeUser}, KeyInit, Reset, UniversalHash, }; #[cfg(all(target_arch = "aarch64", polyval_armv8))] use super::pmull as intrinsics; #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] use super::clmul as intrinsics; #[cfg(all(target_arch = "aarch64", polyval_armv8))] cpufeatures::new!(mul_intrinsics, "aes"); // `aes` implies PMULL #[cfg(any(target_arch = "x86_64", target_arch = "x86"))] cpufeatures::new!(mul_intrinsics, "pclmulqdq"); /// **POLYVAL**: GHASH-like universal hash over GF(2^128). pub struct Polyval { inner: Inner, token: mul_intrinsics::InitToken, } union Inner { intrinsics: ManuallyDrop, soft: ManuallyDrop, } impl KeySizeUser for Polyval { type KeySize = U16; } impl KeyInit for Polyval { /// Initialize POLYVAL with the given `H` field element fn new(h: &Key) -> Self { let (token, has_intrinsics) = mul_intrinsics::init_get(); let inner = if has_intrinsics { Inner { intrinsics: ManuallyDrop::new(intrinsics::Polyval::new(h)), } } else { Inner { soft: ManuallyDrop::new(soft::Polyval::new(h)), } }; Self { inner, token } } } impl BlockSizeUser for Polyval { type BlockSize = U16; } impl UniversalHash for Polyval { fn update_with_backend( &mut self, f: impl universal_hash::UhfClosure, ) { unsafe { if self.token.get() { f.call(&mut *self.inner.intrinsics) } else { f.call(&mut *self.inner.soft) } } } /// Get POLYVAL result (i.e. computed `S` field element) fn finalize(self) -> Tag { unsafe { if self.token.get() { ManuallyDrop::into_inner(self.inner.intrinsics).finalize() } else { ManuallyDrop::into_inner(self.inner.soft).finalize() } } } } impl Clone for Polyval { fn clone(&self) -> Self { let inner = if self.token.get() { Inner { intrinsics: ManuallyDrop::new(unsafe { (*self.inner.intrinsics).clone() }), } } else { Inner { soft: ManuallyDrop::new(unsafe { (*self.inner.soft).clone() }), } }; Self { inner, token: self.token, } } } impl Reset for Polyval { fn reset(&mut self) { if self.token.get() { unsafe { (*self.inner.intrinsics).reset() } } else { unsafe { (*self.inner.soft).reset() } } } } polyval-0.6.1/src/backend/clmul.rs000064400000000000000000000074270072674642500152200ustar 00000000000000//! Intel `CLMUL`-accelerated implementation for modern x86/x86_64 CPUs //! (i.e. Intel Sandy Bridge-compatible or newer) use crate::{Block, Key, Tag}; use universal_hash::{ consts::{U1, U16}, crypto_common::{BlockSizeUser, KeySizeUser, ParBlocksSizeUser}, KeyInit, Reset, UhfBackend, }; #[cfg(target_arch = "x86")] use core::arch::x86::*; #[cfg(target_arch = "x86_64")] use core::arch::x86_64::*; /// **POLYVAL**: GHASH-like universal hash over GF(2^128). #[derive(Clone)] pub struct Polyval { h: __m128i, y: __m128i, } impl KeySizeUser for Polyval { type KeySize = U16; } impl KeyInit for Polyval { /// Initialize POLYVAL with the given `H` field element fn new(h: &Key) -> Self { unsafe { // `_mm_loadu_si128` performs an unaligned load #[allow(clippy::cast_ptr_alignment)] Self { h: _mm_loadu_si128(h.as_ptr() as *const __m128i), y: _mm_setzero_si128(), } } } } impl BlockSizeUser for Polyval { type BlockSize = U16; } impl ParBlocksSizeUser for Polyval { type ParBlocksSize = U1; } impl UhfBackend for Polyval { fn proc_block(&mut self, x: &Block) { unsafe { self.mul(x); } } } impl Polyval { /// Get GHASH output pub(crate) fn finalize(self) -> Tag { unsafe { core::mem::transmute(self.y) } } } impl Polyval { #[inline] #[target_feature(enable = "pclmulqdq")] unsafe fn mul(&mut self, x: &Block) { let h = self.h; // `_mm_loadu_si128` performs an unaligned load #[allow(clippy::cast_ptr_alignment)] let x = _mm_loadu_si128(x.as_ptr() as *const __m128i); let y = _mm_xor_si128(self.y, x); let h0 = h; let h1 = _mm_shuffle_epi32(h, 0x0E); let h2 = _mm_xor_si128(h0, h1); let y0 = y; // Multiply values partitioned to 64-bit parts let y1 = _mm_shuffle_epi32(y, 0x0E); let y2 = _mm_xor_si128(y0, y1); let t0 = _mm_clmulepi64_si128(y0, h0, 0x00); let t1 = _mm_clmulepi64_si128(y, h, 0x11); let t2 = _mm_clmulepi64_si128(y2, h2, 0x00); let t2 = _mm_xor_si128(t2, _mm_xor_si128(t0, t1)); let v0 = t0; let v1 = _mm_xor_si128(_mm_shuffle_epi32(t0, 0x0E), t2); let v2 = _mm_xor_si128(t1, _mm_shuffle_epi32(t2, 0x0E)); let v3 = _mm_shuffle_epi32(t1, 0x0E); // Polynomial reduction let v2 = xor5( v2, v0, _mm_srli_epi64(v0, 1), _mm_srli_epi64(v0, 2), _mm_srli_epi64(v0, 7), ); let v1 = xor4( v1, _mm_slli_epi64(v0, 63), _mm_slli_epi64(v0, 62), _mm_slli_epi64(v0, 57), ); let v3 = xor5( v3, v1, _mm_srli_epi64(v1, 1), _mm_srli_epi64(v1, 2), _mm_srli_epi64(v1, 7), ); let v2 = xor4( v2, _mm_slli_epi64(v1, 63), _mm_slli_epi64(v1, 62), _mm_slli_epi64(v1, 57), ); self.y = _mm_unpacklo_epi64(v2, v3); } } impl Reset for Polyval { fn reset(&mut self) { unsafe { self.y = _mm_setzero_si128(); } } } #[cfg(feature = "zeroize")] impl Drop for Polyval { fn drop(&mut self) { use zeroize::Zeroize; self.h.zeroize(); self.y.zeroize(); } } #[inline(always)] unsafe fn xor4(e1: __m128i, e2: __m128i, e3: __m128i, e4: __m128i) -> __m128i { _mm_xor_si128(_mm_xor_si128(e1, e2), _mm_xor_si128(e3, e4)) } #[inline(always)] unsafe fn xor5(e1: __m128i, e2: __m128i, e3: __m128i, e4: __m128i, e5: __m128i) -> __m128i { _mm_xor_si128( e1, _mm_xor_si128(_mm_xor_si128(e2, e3), _mm_xor_si128(e4, e5)), ) } polyval-0.6.1/src/backend/pmull.rs000064400000000000000000000067100072674642500152270ustar 00000000000000//! ARMv8 `PMULL`-accelerated implementation of POLYVAL. //! //! Based on this C intrinsics implementation: //! //! //! Original C written and placed in public domain by Jeffrey Walton. //! Based on code from ARM, and by Johannes Schneiders, Skip Hovsmith and //! Barry O'Rourke for the mbedTLS project. //! //! For more information about PMULL, see: //! - //! - use crate::{Block, Key, Tag}; use core::{arch::aarch64::*, mem}; use universal_hash::{ consts::{U1, U16}, crypto_common::{BlockSizeUser, KeySizeUser, ParBlocksSizeUser}, KeyInit, Reset, UhfBackend, }; /// **POLYVAL**: GHASH-like universal hash over GF(2^128). #[derive(Clone)] pub struct Polyval { h: uint8x16_t, y: uint8x16_t, } impl KeySizeUser for Polyval { type KeySize = U16; } impl KeyInit for Polyval { /// Initialize POLYVAL with the given `H` field element fn new(h: &Key) -> Self { unsafe { Self { h: vld1q_u8(h.as_ptr()), y: vdupq_n_u8(0), // all zeroes } } } } impl BlockSizeUser for Polyval { type BlockSize = U16; } impl ParBlocksSizeUser for Polyval { type ParBlocksSize = U1; } impl UhfBackend for Polyval { fn proc_block(&mut self, x: &Block) { unsafe { self.mul(x); } } } impl Reset for Polyval { fn reset(&mut self) { unsafe { self.y = vdupq_n_u8(0); } } } impl Polyval { /// Mask value used when performing reduction. /// This corresponds to POLYVAL's polynomial with the highest bit unset. const MASK: u128 = 1 << 127 | 1 << 126 | 1 << 121 | 1; /// Get POLYVAL output. pub(crate) fn finalize(self) -> Tag { unsafe { mem::transmute(self.y) } } /// POLYVAL carryless multiplication. // TODO(tarcieri): investigate ordering optimizations and fusions e.g.`fuse-crypto-eor` #[inline] #[target_feature(enable = "neon")] unsafe fn mul(&mut self, x: &Block) { let h = self.h; let y = veorq_u8(self.y, vld1q_u8(x.as_ptr())); // polynomial multiply let z = vdupq_n_u8(0); let r0 = pmull::<0, 0>(h, y); let r1 = pmull::<1, 1>(h, y); let t0 = pmull::<0, 1>(h, y); let t1 = pmull::<1, 0>(h, y); let t0 = veorq_u8(t0, t1); let t1 = vextq_u8(z, t0, 8); let r0 = veorq_u8(r0, t1); let t1 = vextq_u8(t0, z, 8); let r1 = veorq_u8(r1, t1); // polynomial reduction let p = mem::transmute(Self::MASK); let t0 = pmull::<0, 1>(r0, p); let t1 = vextq_u8(t0, t0, 8); let r0 = veorq_u8(r0, t1); let t1 = pmull::<1, 1>(r0, p); let r0 = veorq_u8(r0, t1); self.y = veorq_u8(r0, r1); } } /// Wrapper for the ARM64 `PMULL` instruction. #[inline(always)] unsafe fn pmull(a: uint8x16_t, b: uint8x16_t) -> uint8x16_t { mem::transmute(vmull_p64( vgetq_lane_u64(vreinterpretq_u64_u8(a), A_LANE), vgetq_lane_u64(vreinterpretq_u64_u8(b), B_LANE), )) } // TODO(tarcieri): zeroize support // #[cfg(feature = "zeroize")] // impl Drop for Polyval { // fn drop(&mut self) { // use zeroize::Zeroize; // self.h.zeroize(); // self.y.zeroize(); // } // } polyval-0.6.1/src/backend/soft32.rs000064400000000000000000000212710072674642500152150ustar 00000000000000//! Constant-time software implementation of POLYVAL for 32-bit architectures //! Adapted from BearSSL's `ghash_ctmul32.c`: //! //! //! //! Copyright (c) 2016 Thomas Pornin //! //! This implementation uses 32-bit multiplications, and only the low //! 32 bits for each multiplication result. This is meant primarily for //! the ARM Cortex M0 and M0+, whose multiplication opcode does not yield //! the upper 32 bits; but it might also be useful on architectures where //! access to the upper 32 bits requires use of specific registers that //! create contention (e.g. on i386, "mul" necessarily outputs the result //! in edx:eax, while "imul" can use any registers but is limited to the //! low 32 bits). //! //! The implementation trick that is used here is bit-reversing (bit 0 //! is swapped with bit 31, bit 1 with bit 30, and so on). In GF(2)[X], //! for all values x and y, we have: //! //! ```text //! rev32(x) * rev32(y) = rev64(x * y) //! ``` //! //! In other words, if we bit-reverse (over 32 bits) the operands, then we //! bit-reverse (over 64 bits) the result. use crate::{Block, Key, Tag}; use core::{ num::Wrapping, ops::{Add, Mul}, }; use universal_hash::{ consts::{U1, U16}, crypto_common::{BlockSizeUser, KeySizeUser, ParBlocksSizeUser}, KeyInit, Reset, UhfBackend, UniversalHash, }; #[cfg(feature = "zeroize")] use zeroize::Zeroize; /// **POLYVAL**: GHASH-like universal hash over GF(2^128). #[derive(Clone)] pub struct Polyval { /// GF(2^128) field element input blocks are multiplied by h: U32x4, /// Field element representing the computed universal hash s: U32x4, } impl KeySizeUser for Polyval { type KeySize = U16; } impl KeyInit for Polyval { /// Initialize POLYVAL with the given `H` field element fn new(h: &Key) -> Self { Self { h: h.into(), s: U32x4::default(), } } } impl BlockSizeUser for Polyval { type BlockSize = U16; } impl ParBlocksSizeUser for Polyval { type ParBlocksSize = U1; } impl UhfBackend for Polyval { fn proc_block(&mut self, x: &Block) { let x = U32x4::from(x); self.s = (self.s + x) * self.h; } } impl UniversalHash for Polyval { fn update_with_backend( &mut self, f: impl universal_hash::UhfClosure, ) { f.call(self); } /// Get POLYVAL result (i.e. computed `S` field element) fn finalize(self) -> Tag { let mut block = Block::default(); for (chunk, i) in block .chunks_mut(4) .zip(&[self.s.0, self.s.1, self.s.2, self.s.3]) { chunk.copy_from_slice(&i.to_le_bytes()); } block } } impl Reset for Polyval { fn reset(&mut self) { self.s = U32x4::default(); } } #[cfg(feature = "zeroize")] impl Drop for Polyval { fn drop(&mut self) { self.h.zeroize(); self.s.zeroize(); } } /// 4 x `u32` values #[derive(Copy, Clone, Debug, Default, Eq, PartialEq)] struct U32x4(u32, u32, u32, u32); impl From<&Block> for U32x4 { fn from(bytes: &Block) -> U32x4 { U32x4( u32::from_le_bytes(bytes[..4].try_into().unwrap()), u32::from_le_bytes(bytes[4..8].try_into().unwrap()), u32::from_le_bytes(bytes[8..12].try_into().unwrap()), u32::from_le_bytes(bytes[12..].try_into().unwrap()), ) } } #[allow(clippy::suspicious_arithmetic_impl)] impl Add for U32x4 { type Output = Self; /// Adds two POLYVAL field elements. fn add(self, rhs: Self) -> Self::Output { U32x4( self.0 ^ rhs.0, self.1 ^ rhs.1, self.2 ^ rhs.2, self.3 ^ rhs.3, ) } } #[allow(clippy::suspicious_arithmetic_impl)] impl Mul for U32x4 { type Output = Self; /// Computes carryless POLYVAL multiplication over GF(2^128) in constant time. /// /// Method described at: /// /// /// POLYVAL multiplication is effectively the little endian equivalent of /// GHASH multiplication, aside from one small detail described here: /// /// /// /// > The product of two bit-reversed 128-bit polynomials yields the /// > bit-reversed result over 255 bits, not 256. The BearSSL code ends up /// > with a 256-bit result in zw[], and that value is shifted by one bit, /// > because of that reversed convention issue. Thus, the code must /// > include a shifting step to put it back where it should /// /// This shift is unnecessary for POLYVAL and has been removed. fn mul(self, rhs: Self) -> Self { let hw = [self.0, self.1, self.2, self.3]; let yw = [rhs.0, rhs.1, rhs.2, rhs.3]; let hwr = [rev32(hw[0]), rev32(hw[1]), rev32(hw[2]), rev32(hw[3])]; // We are using Karatsuba: the 128x128 multiplication is // reduced to three 64x64 multiplications, hence nine // 32x32 multiplications. With the bit-reversal trick, // we have to perform 18 32x32 multiplications. let mut a = [0u32; 18]; a[0] = yw[0]; a[1] = yw[1]; a[2] = yw[2]; a[3] = yw[3]; a[4] = a[0] ^ a[1]; a[5] = a[2] ^ a[3]; a[6] = a[0] ^ a[2]; a[7] = a[1] ^ a[3]; a[8] = a[6] ^ a[7]; a[9] = rev32(yw[0]); a[10] = rev32(yw[1]); a[11] = rev32(yw[2]); a[12] = rev32(yw[3]); a[13] = a[9] ^ a[10]; a[14] = a[11] ^ a[12]; a[15] = a[9] ^ a[11]; a[16] = a[10] ^ a[12]; a[17] = a[15] ^ a[16]; let mut b = [0u32; 18]; b[0] = hw[0]; b[1] = hw[1]; b[2] = hw[2]; b[3] = hw[3]; b[4] = b[0] ^ b[1]; b[5] = b[2] ^ b[3]; b[6] = b[0] ^ b[2]; b[7] = b[1] ^ b[3]; b[8] = b[6] ^ b[7]; b[9] = hwr[0]; b[10] = hwr[1]; b[11] = hwr[2]; b[12] = hwr[3]; b[13] = b[9] ^ b[10]; b[14] = b[11] ^ b[12]; b[15] = b[9] ^ b[11]; b[16] = b[10] ^ b[12]; b[17] = b[15] ^ b[16]; let mut c = [0u32; 18]; for i in 0..18 { c[i] = bmul32(a[i], b[i]); } c[4] ^= c[0] ^ c[1]; c[5] ^= c[2] ^ c[3]; c[8] ^= c[6] ^ c[7]; c[13] ^= c[9] ^ c[10]; c[14] ^= c[11] ^ c[12]; c[17] ^= c[15] ^ c[16]; let mut zw = [0u32; 8]; zw[0] = c[0]; zw[1] = c[4] ^ rev32(c[9]) >> 1; zw[2] = c[1] ^ c[0] ^ c[2] ^ c[6] ^ rev32(c[13]) >> 1; zw[3] = c[4] ^ c[5] ^ c[8] ^ rev32(c[10] ^ c[9] ^ c[11] ^ c[15]) >> 1; zw[4] = c[2] ^ c[1] ^ c[3] ^ c[7] ^ rev32(c[13] ^ c[14] ^ c[17]) >> 1; zw[5] = c[5] ^ rev32(c[11] ^ c[10] ^ c[12] ^ c[16]) >> 1; zw[6] = c[3] ^ rev32(c[14]) >> 1; zw[7] = rev32(c[12]) >> 1; for i in 0..4 { let lw = zw[i]; zw[i + 4] ^= lw ^ (lw >> 1) ^ (lw >> 2) ^ (lw >> 7); zw[i + 3] ^= (lw << 31) ^ (lw << 30) ^ (lw << 25); } U32x4(zw[4], zw[5], zw[6], zw[7]) } } #[cfg(feature = "zeroize")] impl Zeroize for U32x4 { fn zeroize(&mut self) { self.0.zeroize(); self.1.zeroize(); self.2.zeroize(); self.3.zeroize(); } } /// Multiplication in GF(2)[X], truncated to the low 32-bits, with “holes” /// (sequences of zeroes) to avoid carry spilling. /// /// When carries do occur, they wind up in a "hole" and are subsequently masked /// out of the result. fn bmul32(x: u32, y: u32) -> u32 { let x0 = Wrapping(x & 0x1111_1111); let x1 = Wrapping(x & 0x2222_2222); let x2 = Wrapping(x & 0x4444_4444); let x3 = Wrapping(x & 0x8888_8888); let y0 = Wrapping(y & 0x1111_1111); let y1 = Wrapping(y & 0x2222_2222); let y2 = Wrapping(y & 0x4444_4444); let y3 = Wrapping(y & 0x8888_8888); let mut z0 = ((x0 * y0) ^ (x1 * y3) ^ (x2 * y2) ^ (x3 * y1)).0; let mut z1 = ((x0 * y1) ^ (x1 * y0) ^ (x2 * y3) ^ (x3 * y2)).0; let mut z2 = ((x0 * y2) ^ (x1 * y1) ^ (x2 * y0) ^ (x3 * y3)).0; let mut z3 = ((x0 * y3) ^ (x1 * y2) ^ (x2 * y1) ^ (x3 * y0)).0; z0 &= 0x1111_1111; z1 &= 0x2222_2222; z2 &= 0x4444_4444; z3 &= 0x8888_8888; z0 | z1 | z2 | z3 } /// Bit-reverse a 32-bit word in constant time. fn rev32(mut x: u32) -> u32 { x = ((x & 0x5555_5555) << 1) | (x >> 1 & 0x5555_5555); x = ((x & 0x3333_3333) << 2) | (x >> 2 & 0x3333_3333); x = ((x & 0x0f0f_0f0f) << 4) | (x >> 4 & 0x0f0f_0f0f); x = ((x & 0x00ff_00ff) << 8) | (x >> 8 & 0x00ff_00ff); (x << 16) | (x >> 16) } polyval-0.6.1/src/backend/soft64.rs000064400000000000000000000145570072674642500152330ustar 00000000000000//! Constant-time software implementation of POLYVAL for 64-bit architectures. //! Adapted from BearSSL's `ghash_ctmul64.c`: //! //! //! //! Copyright (c) 2016 Thomas Pornin use crate::{Block, Key, Tag}; use core::{ num::Wrapping, ops::{Add, Mul}, }; use universal_hash::{ consts::{U1, U16}, crypto_common::{BlockSizeUser, KeySizeUser, ParBlocksSizeUser}, KeyInit, Reset, UhfBackend, UniversalHash, }; #[cfg(feature = "zeroize")] use zeroize::Zeroize; /// **POLYVAL**: GHASH-like universal hash over GF(2^128). #[derive(Clone)] pub struct Polyval { /// GF(2^128) field element input blocks are multiplied by h: U64x2, /// Field element representing the computed universal hash s: U64x2, } impl KeySizeUser for Polyval { type KeySize = U16; } impl KeyInit for Polyval { /// Initialize POLYVAL with the given `H` field element fn new(h: &Key) -> Self { Self { h: h.into(), s: U64x2::default(), } } } impl BlockSizeUser for Polyval { type BlockSize = U16; } impl ParBlocksSizeUser for Polyval { type ParBlocksSize = U1; } impl UhfBackend for Polyval { fn proc_block(&mut self, x: &Block) { let x = U64x2::from(x); self.s = (self.s + x) * self.h; } } impl UniversalHash for Polyval { fn update_with_backend( &mut self, f: impl universal_hash::UhfClosure, ) { f.call(self); } /// Get POLYVAL result (i.e. computed `S` field element) fn finalize(self) -> Tag { let mut block = Block::default(); for (chunk, i) in block.chunks_mut(8).zip(&[self.s.0, self.s.1]) { chunk.copy_from_slice(&i.to_le_bytes()); } block } } impl Reset for Polyval { fn reset(&mut self) { self.s = U64x2::default(); } } #[cfg(feature = "zeroize")] impl Drop for Polyval { fn drop(&mut self) { self.h.zeroize(); self.s.zeroize(); } } /// 2 x `u64` values #[derive(Copy, Clone, Debug, Default, Eq, PartialEq)] struct U64x2(u64, u64); impl From<&Block> for U64x2 { fn from(bytes: &Block) -> U64x2 { U64x2( u64::from_le_bytes(bytes[..8].try_into().unwrap()), u64::from_le_bytes(bytes[8..].try_into().unwrap()), ) } } #[allow(clippy::suspicious_arithmetic_impl)] impl Add for U64x2 { type Output = Self; /// Adds two POLYVAL field elements. fn add(self, rhs: Self) -> Self::Output { U64x2(self.0 ^ rhs.0, self.1 ^ rhs.1) } } #[allow(clippy::suspicious_arithmetic_impl)] impl Mul for U64x2 { type Output = Self; /// Computes carryless POLYVAL multiplication over GF(2^128) in constant time. /// /// Method described at: /// /// /// POLYVAL multiplication is effectively the little endian equivalent of /// GHASH multiplication, aside from one small detail described here: /// /// /// /// > The product of two bit-reversed 128-bit polynomials yields the /// > bit-reversed result over 255 bits, not 256. The BearSSL code ends up /// > with a 256-bit result in zw[], and that value is shifted by one bit, /// > because of that reversed convention issue. Thus, the code must /// > include a shifting step to put it back where it should /// /// This shift is unnecessary for POLYVAL and has been removed. fn mul(self, rhs: Self) -> Self { let h0 = self.0; let h1 = self.1; let h0r = rev64(h0); let h1r = rev64(h1); let h2 = h0 ^ h1; let h2r = h0r ^ h1r; let y0 = rhs.0; let y1 = rhs.1; let y0r = rev64(y0); let y1r = rev64(y1); let y2 = y0 ^ y1; let y2r = y0r ^ y1r; let z0 = bmul64(y0, h0); let z1 = bmul64(y1, h1); let mut z2 = bmul64(y2, h2); let mut z0h = bmul64(y0r, h0r); let mut z1h = bmul64(y1r, h1r); let mut z2h = bmul64(y2r, h2r); z2 ^= z0 ^ z1; z2h ^= z0h ^ z1h; z0h = rev64(z0h) >> 1; z1h = rev64(z1h) >> 1; z2h = rev64(z2h) >> 1; let v0 = z0; let mut v1 = z0h ^ z2; let mut v2 = z1 ^ z2h; let mut v3 = z1h; v2 ^= v0 ^ (v0 >> 1) ^ (v0 >> 2) ^ (v0 >> 7); v1 ^= (v0 << 63) ^ (v0 << 62) ^ (v0 << 57); v3 ^= v1 ^ (v1 >> 1) ^ (v1 >> 2) ^ (v1 >> 7); v2 ^= (v1 << 63) ^ (v1 << 62) ^ (v1 << 57); U64x2(v2, v3) } } #[cfg(feature = "zeroize")] impl Zeroize for U64x2 { fn zeroize(&mut self) { self.0.zeroize(); self.1.zeroize(); } } /// Multiplication in GF(2)[X], truncated to the low 64-bits, with “holes” /// (sequences of zeroes) to avoid carry spilling. /// /// When carries do occur, they wind up in a "hole" and are subsequently masked /// out of the result. fn bmul64(x: u64, y: u64) -> u64 { let x0 = Wrapping(x & 0x1111_1111_1111_1111); let x1 = Wrapping(x & 0x2222_2222_2222_2222); let x2 = Wrapping(x & 0x4444_4444_4444_4444); let x3 = Wrapping(x & 0x8888_8888_8888_8888); let y0 = Wrapping(y & 0x1111_1111_1111_1111); let y1 = Wrapping(y & 0x2222_2222_2222_2222); let y2 = Wrapping(y & 0x4444_4444_4444_4444); let y3 = Wrapping(y & 0x8888_8888_8888_8888); let mut z0 = ((x0 * y0) ^ (x1 * y3) ^ (x2 * y2) ^ (x3 * y1)).0; let mut z1 = ((x0 * y1) ^ (x1 * y0) ^ (x2 * y3) ^ (x3 * y2)).0; let mut z2 = ((x0 * y2) ^ (x1 * y1) ^ (x2 * y0) ^ (x3 * y3)).0; let mut z3 = ((x0 * y3) ^ (x1 * y2) ^ (x2 * y1) ^ (x3 * y0)).0; z0 &= 0x1111_1111_1111_1111; z1 &= 0x2222_2222_2222_2222; z2 &= 0x4444_4444_4444_4444; z3 &= 0x8888_8888_8888_8888; z0 | z1 | z2 | z3 } /// Bit-reverse a `u64` in constant time fn rev64(mut x: u64) -> u64 { x = ((x & 0x5555_5555_5555_5555) << 1) | ((x >> 1) & 0x5555_5555_5555_5555); x = ((x & 0x3333_3333_3333_3333) << 2) | ((x >> 2) & 0x3333_3333_3333_3333); x = ((x & 0x0f0f_0f0f_0f0f_0f0f) << 4) | ((x >> 4) & 0x0f0f_0f0f_0f0f_0f0f); x = ((x & 0x00ff_00ff_00ff_00ff) << 8) | ((x >> 8) & 0x00ff_00ff_00ff_00ff); x = ((x & 0xffff_0000_ffff) << 16) | ((x >> 16) & 0xffff_0000_ffff); (x << 32) | (x >> 32) } polyval-0.6.1/src/backend.rs000064400000000000000000000012460072674642500140750ustar 00000000000000//! POLYVAL backends #[cfg_attr(not(target_pointer_width = "64"), path = "backend/soft32.rs")] #[cfg_attr(target_pointer_width = "64", path = "backend/soft64.rs")] mod soft; use cfg_if::cfg_if; cfg_if! { if #[cfg(all(target_arch = "aarch64", polyval_armv8, not(polyval_force_soft)))] { mod autodetect; mod pmull; pub use crate::backend::autodetect::Polyval; } else if #[cfg(all( any(target_arch = "x86_64", target_arch = "x86"), not(polyval_force_soft) ))] { mod autodetect; mod clmul; pub use crate::backend::autodetect::Polyval; } else { pub use crate::backend::soft::Polyval; } } polyval-0.6.1/src/lib.rs000064400000000000000000000101210072674642500132440ustar 00000000000000//! **POLYVAL** is a GHASH-like universal hash over GF(2^128) useful for //! implementing [AES-GCM-SIV] or [AES-GCM/GMAC]. //! //! From [RFC 8452 Section 3] which defines POLYVAL for use in AES-GCM-SIV: //! //! > "POLYVAL, like GHASH (the authenticator in AES-GCM; ...), operates in a //! > binary field of size 2^128. The field is defined by the irreducible //! > polynomial x^128 + x^127 + x^126 + x^121 + 1." //! //! By multiplying (in the finite field sense) a sequence of 128-bit blocks of //! input data data by a field element `H`, POLYVAL can be used to authenticate //! the message sequence as powers (in the finite field sense) of `H`. //! //! # Minimum Supported Rust Version //! Rust **1.56** or higher. //! //! In the future the minimum supported Rust version may be changed, but it //! be will be accompanied with a minor version bump. //! //! # Supported backends //! This crate provides multiple backends including a portable pure Rust //! backend as well as ones based on CPU intrinsics. //! //! ## "soft" portable backend //! As a baseline implementation, this crate provides a constant-time pure Rust //! implementation based on [BearSSL], which is a straightforward and //! compact implementation which uses a clever but simple technique to avoid //! carry-spilling. //! //! ## ARMv8 intrinsics (`PMULL`, MSRV 1.61+) //! On `aarch64` targets including `aarch64-apple-darwin` (Apple M1) and Linux //! targets such as `aarch64-unknown-linux-gnu` and `aarch64-unknown-linux-musl`, //! support for using the `PMULL` instructions in ARMv8's Cryptography Extensions //! with the following `RUSTFLAGS`: //! //! ```text //! --cfg polyval_armv8 //! ``` //! //! On Linux and macOS when the ARMv8 features are enabled, support for `PMULL` //! intrinsics is autodetected at runtime. On other platforms the `crypto` //! target feature must be enabled via RUSTFLAGS. //! //! ## `x86`/`x86_64` intrinsics (`CMLMUL`) //! By default this crate uses runtime detection on `i686`/`x86_64` targets //! in order to determine if `CLMUL` is available, and if it is not, it will //! fallback to using a constant-time software implementation. //! //! For optimal performance, set `target-cpu` in `RUSTFLAGS` to `sandybridge` //! or newer: //! //! Example: //! //! ```text //! $ RUSTFLAGS="-Ctarget-cpu=sandybridge" cargo bench //! ``` //! //! # Relationship to GHASH //! POLYVAL can be thought of as the little endian equivalent of GHASH, which //! affords it a small performance advantage over GHASH when used on little //! endian architectures. //! //! It has also been designed so it can also be used to compute GHASH and with //! it GMAC, the Message Authentication Code (MAC) used by AES-GCM. //! //! From [RFC 8452 Appendix A]: //! //! > "GHASH and POLYVAL both operate in GF(2^128), although with different //! > irreducible polynomials: POLYVAL works modulo x^128 + x^127 + x^126 + //! > x^121 + 1 and GHASH works modulo x^128 + x^7 + x^2 + x + 1. Note //! > that these irreducible polynomials are the 'reverse' of each other." //! //! [AES-GCM-SIV]: https://en.wikipedia.org/wiki/AES-GCM-SIV //! [AES-GCM/GMAC]: https://en.wikipedia.org/wiki/Galois/Counter_Mode //! [BearSSL]: https://www.bearssl.org/constanttime.html#ghash-for-gcm //! [RFC 8452 Section 3]: https://tools.ietf.org/html/rfc8452#section-3 //! [RFC 8452 Appendix A]: https://tools.ietf.org/html/rfc8452#appendix-A #![no_std] #![cfg_attr(docsrs, feature(doc_cfg))] #![doc( html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg", html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg" )] #![warn(missing_docs, rust_2018_idioms)] mod backend; mod mulx; pub use crate::{backend::Polyval, mulx::mulx}; pub use universal_hash; opaque_debug::implement!(Polyval); /// Size of a POLYVAL block in bytes pub const BLOCK_SIZE: usize = 16; /// Size of a POLYVAL key in bytes pub const KEY_SIZE: usize = 16; /// POLYVAL keys (16-bytes) pub type Key = universal_hash::Key; /// POLYVAL blocks (16-bytes) pub type Block = universal_hash::Block; /// POLYVAL tags (16-bytes) pub type Tag = universal_hash::Block; polyval-0.6.1/src/mulx.rs000064400000000000000000000201730072674642500134730ustar 00000000000000//! The `mulX_POLYVAL()` function. use crate::Block; /// The `mulX_POLYVAL()` function as defined in [RFC 8452 Appendix A][1]. /// /// Performs a doubling (a.k.a. "multiply by x") over GF(2^128). /// This is useful for implementing GHASH in terms of POLYVAL. /// /// [1]: https://tools.ietf.org/html/rfc8452#appendix-A pub fn mulx(block: &Block) -> Block { let mut v = u128::from_le_bytes((*block).into()); let v_hi = v >> 127; v <<= 1; v ^= v_hi ^ (v_hi << 127) ^ (v_hi << 126) ^ (v_hi << 121); v.to_le_bytes().into() } #[cfg(test)] mod tests { use super::{mulx, Block}; use hex_literal::hex; /// Test vector given in RFC 8452 Appendix A. /// /// NOTE: the vector in the RFC actually contains a typo which has been /// reported (and accepted) as RFC errata, so we use the vector from the /// errata instead: /// /// #[test] fn rfc8452_vector() { let input = Block::from(hex!("9c98c04df9387ded828175a92ba652d8")); let expected_output = Block::from(hex!("3931819bf271fada0503eb52574ca572")); let actual_output = mulx(&input); assert_eq!(expected_output, actual_output); } /// Test against the `MULX_TEST_VECTORS` given below, which cover the full /// size of a POLYVAL field element. #[test] fn mulx_vectors() { // One let mut r = Block::from(hex!("01000000000000000000000000000000")); for vector in MULX_TEST_VECTORS { r = mulx(&r); assert_eq!(&r, Block::from_slice(vector)); } } /// `mulX_POLYVAL()` test vectors. /// /// These were generated by this crate when in a known-correct state, /// verified by a GHASH implementation based on a POLYVAL core successfully /// passing the NIST test vectors. const MULX_TEST_VECTORS: &[[u8; 16]] = &[ hex!("02000000000000000000000000000000"), hex!("04000000000000000000000000000000"), hex!("08000000000000000000000000000000"), hex!("10000000000000000000000000000000"), hex!("20000000000000000000000000000000"), hex!("40000000000000000000000000000000"), hex!("80000000000000000000000000000000"), hex!("00010000000000000000000000000000"), hex!("00020000000000000000000000000000"), hex!("00040000000000000000000000000000"), hex!("00080000000000000000000000000000"), hex!("00100000000000000000000000000000"), hex!("00200000000000000000000000000000"), hex!("00400000000000000000000000000000"), hex!("00800000000000000000000000000000"), hex!("00000100000000000000000000000000"), hex!("00000200000000000000000000000000"), hex!("00000400000000000000000000000000"), hex!("00000800000000000000000000000000"), hex!("00001000000000000000000000000000"), hex!("00002000000000000000000000000000"), hex!("00004000000000000000000000000000"), hex!("00008000000000000000000000000000"), hex!("00000001000000000000000000000000"), hex!("00000002000000000000000000000000"), hex!("00000004000000000000000000000000"), hex!("00000008000000000000000000000000"), hex!("00000010000000000000000000000000"), hex!("00000020000000000000000000000000"), hex!("00000040000000000000000000000000"), hex!("00000080000000000000000000000000"), hex!("00000000010000000000000000000000"), hex!("00000000020000000000000000000000"), hex!("00000000040000000000000000000000"), hex!("00000000080000000000000000000000"), hex!("00000000100000000000000000000000"), hex!("00000000200000000000000000000000"), hex!("00000000400000000000000000000000"), hex!("00000000800000000000000000000000"), hex!("00000000000100000000000000000000"), hex!("00000000000200000000000000000000"), hex!("00000000000400000000000000000000"), hex!("00000000000800000000000000000000"), hex!("00000000001000000000000000000000"), hex!("00000000002000000000000000000000"), hex!("00000000004000000000000000000000"), hex!("00000000008000000000000000000000"), hex!("00000000000001000000000000000000"), hex!("00000000000002000000000000000000"), hex!("00000000000004000000000000000000"), hex!("00000000000008000000000000000000"), hex!("00000000000010000000000000000000"), hex!("00000000000020000000000000000000"), hex!("00000000000040000000000000000000"), hex!("00000000000080000000000000000000"), hex!("00000000000000010000000000000000"), hex!("00000000000000020000000000000000"), hex!("00000000000000040000000000000000"), hex!("00000000000000080000000000000000"), hex!("00000000000000100000000000000000"), hex!("00000000000000200000000000000000"), hex!("00000000000000400000000000000000"), hex!("00000000000000800000000000000000"), hex!("00000000000000000100000000000000"), hex!("00000000000000000200000000000000"), hex!("00000000000000000400000000000000"), hex!("00000000000000000800000000000000"), hex!("00000000000000001000000000000000"), hex!("00000000000000002000000000000000"), hex!("00000000000000004000000000000000"), hex!("00000000000000008000000000000000"), hex!("00000000000000000001000000000000"), hex!("00000000000000000002000000000000"), hex!("00000000000000000004000000000000"), hex!("00000000000000000008000000000000"), hex!("00000000000000000010000000000000"), hex!("00000000000000000020000000000000"), hex!("00000000000000000040000000000000"), hex!("00000000000000000080000000000000"), hex!("00000000000000000000010000000000"), hex!("00000000000000000000020000000000"), hex!("00000000000000000000040000000000"), hex!("00000000000000000000080000000000"), hex!("00000000000000000000100000000000"), hex!("00000000000000000000200000000000"), hex!("00000000000000000000400000000000"), hex!("00000000000000000000800000000000"), hex!("00000000000000000000000100000000"), hex!("00000000000000000000000200000000"), hex!("00000000000000000000000400000000"), hex!("00000000000000000000000800000000"), hex!("00000000000000000000001000000000"), hex!("00000000000000000000002000000000"), hex!("00000000000000000000004000000000"), hex!("00000000000000000000008000000000"), hex!("00000000000000000000000001000000"), hex!("00000000000000000000000002000000"), hex!("00000000000000000000000004000000"), hex!("00000000000000000000000008000000"), hex!("00000000000000000000000010000000"), hex!("00000000000000000000000020000000"), hex!("00000000000000000000000040000000"), hex!("00000000000000000000000080000000"), hex!("00000000000000000000000000010000"), hex!("00000000000000000000000000020000"), hex!("00000000000000000000000000040000"), hex!("00000000000000000000000000080000"), hex!("00000000000000000000000000100000"), hex!("00000000000000000000000000200000"), hex!("00000000000000000000000000400000"), hex!("00000000000000000000000000800000"), hex!("00000000000000000000000000000100"), hex!("00000000000000000000000000000200"), hex!("00000000000000000000000000000400"), hex!("00000000000000000000000000000800"), hex!("00000000000000000000000000001000"), hex!("00000000000000000000000000002000"), hex!("00000000000000000000000000004000"), hex!("00000000000000000000000000008000"), hex!("00000000000000000000000000000001"), hex!("00000000000000000000000000000002"), hex!("00000000000000000000000000000004"), hex!("00000000000000000000000000000008"), hex!("00000000000000000000000000000010"), hex!("00000000000000000000000000000020"), hex!("00000000000000000000000000000040"), hex!("00000000000000000000000000000080"), hex!("010000000000000000000000000000c2"), ]; } polyval-0.6.1/tests/lib.rs000064400000000000000000000013740072674642500136310ustar 00000000000000use hex_literal::hex; use polyval::{ universal_hash::{KeyInit, UniversalHash}, Polyval, BLOCK_SIZE, }; // // Test vectors for POLYVAL from RFC 8452 Appendix A // // const H: [u8; BLOCK_SIZE] = hex!("25629347589242761d31f826ba4b757b"); const X_1: [u8; BLOCK_SIZE] = hex!("4f4f95668c83dfb6401762bb2d01a262"); const X_2: [u8; BLOCK_SIZE] = hex!("d1a24ddd2721d006bbe45f20d3c9f362"); /// POLYVAL(H, X_1, X_2) const POLYVAL_RESULT: [u8; BLOCK_SIZE] = hex!("f7a3b47b846119fae5b7866cf5e5b77e"); #[test] fn polyval_test_vector() { let mut poly = Polyval::new(&H.into()); poly.update(&[X_1.into(), X_2.into()]); let result = poly.finalize(); assert_eq!(&POLYVAL_RESULT[..], result.as_slice()); }