aead-0.5.2/.cargo_vcs_info.json0000644000000001420000000000100117270ustar { "git": { "sha1": "1ae238c527c204dd9590e3abc406cfbb342d46ea" }, "path_in_vcs": "aead" }aead-0.5.2/CHANGELOG.md000064400000000000000000000057511046102023000123430ustar 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.5.2 (2023-04-02) ### Added - `arrayvec` feature ([#1219]) [#1219]: https://github.com/RustCrypto/traits/pull/1219 ## 0.5.1 (2022-08-09) ### Added - `AeadCore::generate_nonce` ([#1073]) [#1073]: https://github.com/RustCrypto/traits/pull/1073 ## 0.5.0 (2022-07-23) ### Added - Optional support for `BytesMut` as a `Buffer` ([#956]) - `getrandom` feature ([#1042]) ### Changed - Replace `NewAead` trait with `KeyInit` trait from `crypto-common` ([#1033]) - Rust 2021 edition upgrade; MSRV 1.56+ ([#1044]) [#956]: https://github.com/RustCrypto/traits/pull/956 [#1033]: https://github.com/RustCrypto/traits/pull/1033 [#1042]: https://github.com/RustCrypto/traits/pull/1042 [#1044]: https://github.com/RustCrypto/traits/pull/1044 ## 0.4.3 (2021-08-29) ### Added - `Result` type alias ([#725]) [#725]: https://github.com/RustCrypto/traits/pull/725 ## 0.4.2 (2021-07-12) ### Added - Re-export `rand_core` ([#682]) [#682]: https://github.com/RustCrypto/traits/pull/682 ## 0.4.1 (2021-05-03) ### Changed - Bump `heapless` dependency to v0.7 ([#628]) [#628]: https://github.com/RustCrypto/traits/pull/628 ## 0.4.0 (2021-02-05) [YANKED] ### Added - `stream` module ([#436], [#445], [#447]) - `NewAead::generate_key` method gated under `rand_core` feature ([#513]) ### Changed - Extract `AeadCore` trait ([#508]) - Rename `NewAead::new_var` to `::new_from_slice` ([#512]) - Disable alloc by default ([#514]) - Bump `heapless` dependency to v0.6 ([#522]) [#436]: https://github.com/RustCrypto/traits/pull/436 [#445]: https://github.com/RustCrypto/traits/pull/445 [#447]: https://github.com/RustCrypto/traits/pull/447 [#508]: https://github.com/RustCrypto/traits/pull/508 [#512]: https://github.com/RustCrypto/traits/pull/512 [#513]: https://github.com/RustCrypto/traits/pull/513 [#514]: https://github.com/RustCrypto/traits/pull/514 [#522]: https://github.com/RustCrypto/traits/pull/522 ## 0.3.2 (2020-07-01) ### Added - `dev` module ([#194]) [#194]: https://github.com/RustCrypto/traits/pull/194 ## 0.3.1 (2020-06-12) ### Added - `NewAead::new_varkey` method ([#191]) [#191]: https://github.com/RustCrypto/traits/pull/191 ## 0.3.0 (2020-06-04) ### Added - Type aliases for `Key`, `Nonce`, and `Tag` ([#125]) - Optional `std` feature ([#63]) ### Changed - `NewAead` now borrows the key ([#124]) - Split `Aead`/`AeadMut` into `AeadInPlace`/`AeadMutInPlace` ([#120]) - Bump `generic-array` dependency to v0.14 ([#95]) [#125]: https://github.com/RustCrypto/traits/pull/125 [#124]: https://github.com/RustCrypto/traits/pull/124 [#120]: https://github.com/RustCrypto/traits/pull/120 [#95]: https://github.com/RustCrypto/traits/pull/95 [#63]: https://github.com/RustCrypto/traits/pull/63 ## 0.2.0 (2019-11-17) ## 0.1.2 (2019-11-17) [YANKED] ## 0.1.1 (2019-08-30) ## 0.1.0 (2019-08-29) aead-0.5.2/Cargo.toml0000644000000033000000000000100077240ustar # 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 = "aead" version = "0.5.2" authors = ["RustCrypto Developers"] description = """ Traits for Authenticated Encryption with Associated Data (AEAD) algorithms, such as AES-GCM as ChaCha20Poly1305, which provide a high-level API """ documentation = "https://docs.rs/aead" readme = "README.md" keywords = [ "crypto", "encryption", ] categories = [ "cryptography", "no-std", ] license = "MIT OR Apache-2.0" repository = "https://github.com/RustCrypto/traits" [package.metadata.docs.rs] all-features = true rustdoc-args = [ "--cfg", "docsrs", ] [dependencies.arrayvec] version = "0.7" optional = true default-features = false [dependencies.blobby] version = "0.3" optional = true [dependencies.bytes] version = "1" optional = true default-features = false [dependencies.crypto-common] version = "0.1.4" [dependencies.generic-array] version = "0.14" default-features = false [dependencies.heapless] version = "0.7" optional = true default-features = false [features] alloc = [] default = ["rand_core"] dev = ["blobby"] getrandom = [ "crypto-common/getrandom", "rand_core", ] rand_core = ["crypto-common/rand_core"] std = [ "alloc", "crypto-common/std", ] stream = [] aead-0.5.2/Cargo.toml.orig000064400000000000000000000022351046102023000134130ustar 00000000000000[package] name = "aead" version = "0.5.2" description = """ Traits for Authenticated Encryption with Associated Data (AEAD) algorithms, such as AES-GCM as ChaCha20Poly1305, which provide a high-level API """ authors = ["RustCrypto Developers"] edition = "2021" license = "MIT OR Apache-2.0" readme = "README.md" documentation = "https://docs.rs/aead" repository = "https://github.com/RustCrypto/traits" keywords = ["crypto", "encryption"] categories = ["cryptography", "no-std"] rust-version = "1.56" [dependencies] crypto-common = "0.1.4" generic-array = { version = "0.14", default-features = false } # optional dependencies arrayvec = { version = "0.7", optional = true, default-features = false } blobby = { version = "0.3", optional = true } bytes = { version = "1", optional = true, default-features = false } heapless = { version = "0.7", optional = true, default-features = false } [features] default = ["rand_core"] alloc = [] std = ["alloc", "crypto-common/std"] dev = ["blobby"] getrandom = ["crypto-common/getrandom", "rand_core"] rand_core = ["crypto-common/rand_core"] stream = [] [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg", "docsrs"] aead-0.5.2/LICENSE-APACHE000064400000000000000000000251421046102023000124520ustar 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. aead-0.5.2/LICENSE-MIT000064400000000000000000000021301046102023000121520ustar 00000000000000Copyright (c) 2019 The RustCrypto Project Developers Copyright (c) 2019 MobileCoin, LLC 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. aead-0.5.2/README.md000064400000000000000000000046451046102023000120120ustar 00000000000000# RustCrypto: Authenticated Encryption with Additional Data Traits [![crate][crate-image]][crate-link] [![Docs][docs-image]][docs-link] ![Apache2/MIT licensed][license-image] ![Rust Version][rustc-image] [![Project Chat][chat-image]][chat-link] [![Build Status][build-image]][build-link] This crate provides an abstract interface for [AEAD] ciphers, which guarantee both confidentiality and integrity, even from a powerful attacker who is able to execute [chosen-ciphertext attacks]. The resulting security property, [ciphertext indistinguishability], is considered a basic requirement for modern cryptographic implementations. See [RustCrypto/AEADs] for cipher implementations which use this trait. [Documentation][docs-link] ## Minimum Supported Rust Version Rust **1.56** or higher. Minimum supported Rust version can be changed in the future, but it will be done with a minor version bump. ## SemVer Policy - All on-by-default features of this library are covered by SemVer - MSRV is considered exempt from SemVer as noted above ## License Licensed under either of: * [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) * [MIT license](http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. [//]: # (badges) [crate-image]: https://img.shields.io/crates/v/aead.svg [crate-link]: https://crates.io/crates/aead [docs-image]: https://docs.rs/aead/badge.svg [docs-link]: https://docs.rs/aead/ [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 [chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg [chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260038-AEADs [build-image]: https://github.com/RustCrypto/traits/workflows/aead/badge.svg?branch=master&event=push [build-link]: https://github.com/RustCrypto/traits/actions?query=workflow%3Aaead [//]: # (general links) [AEAD]: https://en.wikipedia.org/wiki/Authenticated_encryption [chosen-ciphertext attacks]: https://en.wikipedia.org/wiki/Chosen-ciphertext_attack [ciphertext indistinguishability]: https://en.wikipedia.org/wiki/Ciphertext_indistinguishability [RustCrypto/AEADs]: https://github.com/RustCrypto/AEADs aead-0.5.2/src/dev.rs000064400000000000000000000054771046102023000124520ustar 00000000000000//! Development-related functionality pub use blobby; /// Define AEAD test #[macro_export] #[cfg_attr(docsrs, doc(cfg(feature = "dev")))] macro_rules! new_test { ($name:ident, $test_name:expr, $cipher:ty $(,)?) => { #[test] fn $name() { use aead::{ dev::blobby::Blob6Iterator, generic_array::{typenum::Unsigned, GenericArray}, Aead, KeyInit, Payload, }; fn run_test( key: &[u8], nonce: &[u8], aad: &[u8], pt: &[u8], ct: &[u8], pass: bool, ) -> Result<(), &'static str> { let key = key.try_into().map_err(|_| "wrong key size")?; let cipher = <$cipher>::new(key); let nonce = nonce.try_into().map_err(|_| "wrong nonce size")?; if !pass { let res = cipher.decrypt(nonce, Payload { aad: aad, msg: ct }); if res.is_ok() { return Err("decryption must return error"); } return Ok(()); } let res = cipher .encrypt(nonce, Payload { aad: aad, msg: pt }) .map_err(|_| "encryption failure")?; if res != ct { return Err("encrypted data is different from target ciphertext"); } let res = cipher .decrypt(nonce, Payload { aad: aad, msg: ct }) .map_err(|_| "decryption failure")?; if res != pt { return Err("decrypted data is different from target plaintext"); } Ok(()) } let data = include_bytes!(concat!("data/", $test_name, ".blb")); for (i, row) in Blob6Iterator::new(data).unwrap().enumerate() { let [key, nonce, aad, pt, ct, status] = row.unwrap(); let pass = match status[0] { 0 => false, 1 => true, _ => panic!("invalid value for pass flag"), }; if let Err(reason) = run_test(key, nonce, aad, pt, ct, pass) { panic!( "\n\ Failed test β„–{}\n\ reason: \t{:?}\n\ key:\t{:?}\n\ nonce:\t{:?}\n\ aad:\t{:?}\n\ plaintext:\t{:?}\n\ ciphertext:\t{:?}\n\ pass:\t{}\n\ ", i, reason, key, nonce, aad, pt, ct, pass, ); } } } }; } aead-0.5.2/src/lib.rs000064400000000000000000000475321046102023000124400ustar 00000000000000//! [Authenticated Encryption with Associated Data] (AEAD) traits //! //! This crate provides an abstract interface for AEAD ciphers, which guarantee //! both confidentiality and integrity, even from a powerful attacker who is //! able to execute [chosen-ciphertext attacks]. The resulting security property, //! [ciphertext indistinguishability], is considered a basic requirement for //! modern cryptographic implementations. //! //! See [RustCrypto/AEADs] for cipher implementations which use this trait. //! //! [Authenticated Encryption with Associated Data]: https://en.wikipedia.org/wiki/Authenticated_encryption //! [chosen-ciphertext attacks]: https://en.wikipedia.org/wiki/Chosen-ciphertext_attack //! [ciphertext indistinguishability]: https://en.wikipedia.org/wiki/Ciphertext_indistinguishability //! [RustCrypto/AEADs]: https://github.com/RustCrypto/AEADs #![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" )] #![forbid(unsafe_code)] #![warn(clippy::unwrap_used, missing_docs, rust_2018_idioms)] #[cfg(feature = "alloc")] extern crate alloc; #[cfg(feature = "std")] extern crate std; #[cfg(feature = "dev")] #[cfg_attr(docsrs, doc(cfg(feature = "dev")))] pub mod dev; #[cfg(feature = "stream")] #[cfg_attr(docsrs, doc(cfg(feature = "stream")))] pub mod stream; pub use crypto_common::{Key, KeyInit, KeySizeUser}; pub use generic_array::{self, typenum::consts}; #[cfg(feature = "arrayvec")] #[cfg_attr(docsrs, doc(cfg(feature = "arrayvec")))] pub use arrayvec; #[cfg(feature = "bytes")] #[cfg_attr(docsrs, doc(cfg(feature = "bytes")))] pub use bytes; #[cfg(feature = "getrandom")] #[cfg_attr(docsrs, doc(cfg(feature = "getrandom")))] pub use crypto_common::rand_core::OsRng; #[cfg(feature = "heapless")] #[cfg_attr(docsrs, doc(cfg(feature = "heapless")))] pub use heapless; #[cfg(feature = "rand_core")] #[cfg_attr(docsrs, doc(cfg(feature = "rand_core")))] pub use crypto_common::rand_core; use core::fmt; use generic_array::{typenum::Unsigned, ArrayLength, GenericArray}; #[cfg(feature = "alloc")] use alloc::vec::Vec; #[cfg(feature = "bytes")] use bytes::BytesMut; #[cfg(feature = "rand_core")] use rand_core::{CryptoRng, RngCore}; /// Error type. /// /// This type is deliberately opaque as to avoid potential side-channel /// leakage (e.g. padding oracle). #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct Error; /// Result type alias with [`Error`]. pub type Result = core::result::Result; impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("aead::Error") } } #[cfg(feature = "std")] impl std::error::Error for Error {} /// Nonce: single-use value for ensuring ciphertexts are unique pub type Nonce = GenericArray::NonceSize>; /// Tag: authentication code which ensures ciphertexts are authentic pub type Tag = GenericArray::TagSize>; /// Authenticated Encryption with Associated Data (AEAD) algorithm core trait. /// /// Defines nonce, tag, and overhead sizes that are consumed by various other /// `Aead*` traits. pub trait AeadCore { /// The length of a nonce. type NonceSize: ArrayLength; /// The maximum length of the nonce. type TagSize: ArrayLength; /// The upper bound amount of additional space required to support a /// ciphertext vs. a plaintext. type CiphertextOverhead: ArrayLength + Unsigned; /// Generate a random nonce for this AEAD algorithm. /// /// AEAD algorithms accept a parameter to encryption/decryption called /// a "nonce" which must be unique every time encryption is performed and /// never repeated for the same key. The nonce is often prepended to the /// ciphertext. The nonce used to produce a given ciphertext must be passed /// to the decryption function in order for it to decrypt correctly. /// /// Nonces don't necessarily have to be random, but it is one strategy /// which is implemented by this function. /// /// # ⚠️Security Warning /// /// AEAD algorithms often fail catastrophically if nonces are ever repeated /// (with SIV modes being an exception). /// /// Using random nonces runs the risk of repeating them unless the nonce /// size is particularly large (e.g. 192-bit extended nonces used by the /// `XChaCha20Poly1305` and `XSalsa20Poly1305` constructions. /// /// [NIST SP 800-38D] recommends the following: /// /// > The total number of invocations of the authenticated encryption /// > function shall not exceed 2^32, including all IV lengths and all /// > instances of the authenticated encryption function with the given key. /// /// Following this guideline, only 4,294,967,296 messages with random /// nonces can be encrypted under a given key. While this bound is high, /// it's possible to encounter in practice, and systems which might /// reach it should consider alternatives to purely random nonces, like /// a counter or a combination of a random nonce + counter. /// /// See the [`stream`] module for a ready-made implementation of the latter. /// /// [NIST SP 800-38D]: https://csrc.nist.gov/publications/detail/sp/800-38d/final #[cfg(feature = "rand_core")] #[cfg_attr(docsrs, doc(cfg(feature = "rand_core")))] fn generate_nonce(mut rng: impl CryptoRng + RngCore) -> Nonce where Nonce: Default, { let mut nonce = Nonce::::default(); rng.fill_bytes(&mut nonce); nonce } } /// Authenticated Encryption with Associated Data (AEAD) algorithm. /// /// This trait is intended for use with stateless AEAD algorithms. The /// [`AeadMut`] trait provides a stateful interface. #[cfg(feature = "alloc")] #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] pub trait Aead: AeadCore { /// Encrypt the given plaintext payload, and return the resulting /// ciphertext as a vector of bytes. /// /// The [`Payload`] type can be used to provide Additional Associated Data /// (AAD) along with the message: this is an optional bytestring which is /// not encrypted, but *is* authenticated along with the message. Failure /// to pass the same AAD that was used during encryption will cause /// decryption to fail, which is useful if you would like to "bind" the /// ciphertext to some other identifier, like a digital signature key /// or other identifier. /// /// If you don't care about AAD and just want to encrypt a plaintext /// message, `&[u8]` will automatically be coerced into a `Payload`: /// /// ```nobuild /// let plaintext = b"Top secret message, handle with care"; /// let ciphertext = cipher.encrypt(nonce, plaintext); /// ``` /// /// The default implementation assumes a postfix tag (ala AES-GCM, /// AES-GCM-SIV, ChaCha20Poly1305). [`Aead`] implementations which do not /// use a postfix tag will need to override this to correctly assemble the /// ciphertext message. fn encrypt<'msg, 'aad>( &self, nonce: &Nonce, plaintext: impl Into>, ) -> Result>; /// Decrypt the given ciphertext slice, and return the resulting plaintext /// as a vector of bytes. /// /// See notes on [`Aead::encrypt()`] about allowable message payloads and /// Associated Additional Data (AAD). /// /// If you have no AAD, you can call this as follows: /// /// ```nobuild /// let ciphertext = b"..."; /// let plaintext = cipher.decrypt(nonce, ciphertext)?; /// ``` /// /// The default implementation assumes a postfix tag (ala AES-GCM, /// AES-GCM-SIV, ChaCha20Poly1305). [`Aead`] implementations which do not /// use a postfix tag will need to override this to correctly parse the /// ciphertext message. fn decrypt<'msg, 'aad>( &self, nonce: &Nonce, ciphertext: impl Into>, ) -> Result>; } /// Stateful Authenticated Encryption with Associated Data algorithm. #[cfg(feature = "alloc")] #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] pub trait AeadMut: AeadCore { /// Encrypt the given plaintext slice, and return the resulting ciphertext /// as a vector of bytes. /// /// See notes on [`Aead::encrypt()`] about allowable message payloads and /// Associated Additional Data (AAD). fn encrypt<'msg, 'aad>( &mut self, nonce: &Nonce, plaintext: impl Into>, ) -> Result>; /// Decrypt the given ciphertext slice, and return the resulting plaintext /// as a vector of bytes. /// /// See notes on [`Aead::encrypt()`] and [`Aead::decrypt()`] about allowable /// message payloads and Associated Additional Data (AAD). fn decrypt<'msg, 'aad>( &mut self, nonce: &Nonce, ciphertext: impl Into>, ) -> Result>; } /// Implement the `decrypt_in_place` method on [`AeadInPlace`] and /// [`AeadMutInPlace]`, using a macro to gloss over the `&self` vs `&mut self`. /// /// Assumes a postfix authentication tag. AEAD ciphers which do not use a /// postfix authentication tag will need to define their own implementation. macro_rules! impl_decrypt_in_place { ($aead:expr, $nonce:expr, $aad:expr, $buffer:expr) => {{ if $buffer.len() < Self::TagSize::to_usize() { return Err(Error); } let tag_pos = $buffer.len() - Self::TagSize::to_usize(); let (msg, tag) = $buffer.as_mut().split_at_mut(tag_pos); $aead.decrypt_in_place_detached($nonce, $aad, msg, Tag::::from_slice(tag))?; $buffer.truncate(tag_pos); Ok(()) }}; } /// In-place stateless AEAD trait. /// /// This trait is both object safe and has no dependencies on `alloc` or `std`. pub trait AeadInPlace: AeadCore { /// Encrypt the given buffer containing a plaintext message in-place. /// /// The buffer must have sufficient capacity to store the ciphertext /// message, which will always be larger than the original plaintext. /// The exact size needed is cipher-dependent, but generally includes /// the size of an authentication tag. /// /// Returns an error if the buffer has insufficient capacity to store the /// resulting ciphertext message. fn encrypt_in_place( &self, nonce: &Nonce, associated_data: &[u8], buffer: &mut dyn Buffer, ) -> Result<()> { let tag = self.encrypt_in_place_detached(nonce, associated_data, buffer.as_mut())?; buffer.extend_from_slice(tag.as_slice())?; Ok(()) } /// Encrypt the data in-place, returning the authentication tag fn encrypt_in_place_detached( &self, nonce: &Nonce, associated_data: &[u8], buffer: &mut [u8], ) -> Result>; /// Decrypt the message in-place, returning an error in the event the /// provided authentication tag does not match the given ciphertext. /// /// The buffer will be truncated to the length of the original plaintext /// message upon success. fn decrypt_in_place( &self, nonce: &Nonce, associated_data: &[u8], buffer: &mut dyn Buffer, ) -> Result<()> { impl_decrypt_in_place!(self, nonce, associated_data, buffer) } /// Decrypt the message in-place, returning an error in the event the provided /// authentication tag does not match the given ciphertext (i.e. ciphertext /// is modified/unauthentic) fn decrypt_in_place_detached( &self, nonce: &Nonce, associated_data: &[u8], buffer: &mut [u8], tag: &Tag, ) -> Result<()>; } /// In-place stateful AEAD trait. /// /// This trait is both object safe and has no dependencies on `alloc` or `std`. pub trait AeadMutInPlace: AeadCore { /// Encrypt the given buffer containing a plaintext message in-place. /// /// The buffer must have sufficient capacity to store the ciphertext /// message, which will always be larger than the original plaintext. /// The exact size needed is cipher-dependent, but generally includes /// the size of an authentication tag. /// /// Returns an error if the buffer has insufficient capacity to store the /// resulting ciphertext message. fn encrypt_in_place( &mut self, nonce: &Nonce, associated_data: &[u8], buffer: &mut impl Buffer, ) -> Result<()> { let tag = self.encrypt_in_place_detached(nonce, associated_data, buffer.as_mut())?; buffer.extend_from_slice(tag.as_slice())?; Ok(()) } /// Encrypt the data in-place, returning the authentication tag fn encrypt_in_place_detached( &mut self, nonce: &Nonce, associated_data: &[u8], buffer: &mut [u8], ) -> Result>; /// Decrypt the message in-place, returning an error in the event the /// provided authentication tag does not match the given ciphertext. /// /// The buffer will be truncated to the length of the original plaintext /// message upon success. fn decrypt_in_place( &mut self, nonce: &Nonce, associated_data: &[u8], buffer: &mut impl Buffer, ) -> Result<()> { impl_decrypt_in_place!(self, nonce, associated_data, buffer) } /// Decrypt the data in-place, returning an error in the event the provided /// authentication tag does not match the given ciphertext (i.e. ciphertext /// is modified/unauthentic) fn decrypt_in_place_detached( &mut self, nonce: &Nonce, associated_data: &[u8], buffer: &mut [u8], tag: &Tag, ) -> Result<()>; } #[cfg(feature = "alloc")] impl Aead for Alg { fn encrypt<'msg, 'aad>( &self, nonce: &Nonce, plaintext: impl Into>, ) -> Result> { let payload = plaintext.into(); let mut buffer = Vec::with_capacity(payload.msg.len() + Self::TagSize::to_usize()); buffer.extend_from_slice(payload.msg); self.encrypt_in_place(nonce, payload.aad, &mut buffer)?; Ok(buffer) } fn decrypt<'msg, 'aad>( &self, nonce: &Nonce, ciphertext: impl Into>, ) -> Result> { let payload = ciphertext.into(); let mut buffer = Vec::from(payload.msg); self.decrypt_in_place(nonce, payload.aad, &mut buffer)?; Ok(buffer) } } #[cfg(feature = "alloc")] impl AeadMut for Alg { fn encrypt<'msg, 'aad>( &mut self, nonce: &Nonce, plaintext: impl Into>, ) -> Result> { let payload = plaintext.into(); let mut buffer = Vec::with_capacity(payload.msg.len() + Self::TagSize::to_usize()); buffer.extend_from_slice(payload.msg); self.encrypt_in_place(nonce, payload.aad, &mut buffer)?; Ok(buffer) } fn decrypt<'msg, 'aad>( &mut self, nonce: &Nonce, ciphertext: impl Into>, ) -> Result> { let payload = ciphertext.into(); let mut buffer = Vec::from(payload.msg); self.decrypt_in_place(nonce, payload.aad, &mut buffer)?; Ok(buffer) } } impl AeadMutInPlace for Alg { fn encrypt_in_place( &mut self, nonce: &Nonce, associated_data: &[u8], buffer: &mut impl Buffer, ) -> Result<()> { ::encrypt_in_place(self, nonce, associated_data, buffer) } fn encrypt_in_place_detached( &mut self, nonce: &Nonce, associated_data: &[u8], buffer: &mut [u8], ) -> Result> { ::encrypt_in_place_detached(self, nonce, associated_data, buffer) } fn decrypt_in_place( &mut self, nonce: &Nonce, associated_data: &[u8], buffer: &mut impl Buffer, ) -> Result<()> { ::decrypt_in_place(self, nonce, associated_data, buffer) } fn decrypt_in_place_detached( &mut self, nonce: &Nonce, associated_data: &[u8], buffer: &mut [u8], tag: &Tag, ) -> Result<()> { ::decrypt_in_place_detached(self, nonce, associated_data, buffer, tag) } } /// AEAD payloads (message + AAD). /// /// Combination of a message (plaintext or ciphertext) and /// "additional associated data" (AAD) to be authenticated (in cleartext) /// along with the message. /// /// If you don't care about AAD, you can pass a `&[u8]` as the payload to /// `encrypt`/`decrypt` and it will automatically be coerced to this type. #[cfg(feature = "alloc")] #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] pub struct Payload<'msg, 'aad> { /// Message to be encrypted/decrypted pub msg: &'msg [u8], /// Optional "additional associated data" to authenticate along with /// this message. If AAD is provided at the time the message is encrypted, /// the same AAD *MUST* be provided at the time the message is decrypted, /// or decryption will fail. pub aad: &'aad [u8], } #[cfg(feature = "alloc")] impl<'msg, 'aad> From<&'msg [u8]> for Payload<'msg, 'aad> { fn from(msg: &'msg [u8]) -> Self { Self { msg, aad: b"" } } } /// In-place encryption/decryption byte buffers. /// /// This trait defines the set of methods needed to support in-place operations /// on a `Vec`-like data type. pub trait Buffer: AsRef<[u8]> + AsMut<[u8]> { /// Get the length of the buffer fn len(&self) -> usize { self.as_ref().len() } /// Is the buffer empty? fn is_empty(&self) -> bool { self.as_ref().is_empty() } /// Extend this buffer from the given slice fn extend_from_slice(&mut self, other: &[u8]) -> Result<()>; /// Truncate this buffer to the given size fn truncate(&mut self, len: usize); } #[cfg(feature = "alloc")] impl Buffer for Vec { fn extend_from_slice(&mut self, other: &[u8]) -> Result<()> { Vec::extend_from_slice(self, other); Ok(()) } fn truncate(&mut self, len: usize) { Vec::truncate(self, len); } } #[cfg(feature = "bytes")] impl Buffer for BytesMut { fn len(&self) -> usize { BytesMut::len(self) } fn is_empty(&self) -> bool { BytesMut::is_empty(self) } fn extend_from_slice(&mut self, other: &[u8]) -> Result<()> { BytesMut::extend_from_slice(self, other); Ok(()) } fn truncate(&mut self, len: usize) { BytesMut::truncate(self, len); } } #[cfg(feature = "arrayvec")] impl Buffer for arrayvec::ArrayVec { fn extend_from_slice(&mut self, other: &[u8]) -> Result<()> { arrayvec::ArrayVec::try_extend_from_slice(self, other).map_err(|_| Error) } fn truncate(&mut self, len: usize) { arrayvec::ArrayVec::truncate(self, len); } } #[cfg(feature = "heapless")] impl Buffer for heapless::Vec { fn extend_from_slice(&mut self, other: &[u8]) -> Result<()> { heapless::Vec::extend_from_slice(self, other).map_err(|_| Error) } fn truncate(&mut self, len: usize) { heapless::Vec::truncate(self, len); } } #[cfg(test)] mod tests { use super::*; /// Ensure that `AeadInPlace` is object-safe #[allow(dead_code)] type DynAeadInPlace = dyn AeadInPlace; /// Ensure that `AeadMutInPlace` is object-safe #[allow(dead_code)] type DynAeadMutInPlace = dyn AeadMutInPlace; } aead-0.5.2/src/stream.rs000064400000000000000000000414121046102023000131540ustar 00000000000000//! Streaming AEAD support. //! //! Implementation of the STREAM online authenticated encryption construction //! as described in the paper //! [Online Authenticated-Encryption and its Nonce-Reuse Misuse-Resistance][1]. //! //! ## About //! //! The STREAM construction supports encrypting/decrypting sequences of AEAD //! message segments, which is useful in cases where the overall message is too //! large to fit in a single buffer and needs to be processed incrementally. //! //! STREAM defends against reordering and truncation attacks which are common //! in naive schemes which attempt to provide these properties, and is proven //! to meet the security definition of "nonce-based online authenticated //! encryption" (nOAE) as given in the aforementioned paper. //! //! ## Diagram //! //! ![STREAM Diagram](https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/img/AEADs/rogaway-stream.svg) //! //! Legend: //! //! - 𝐄k: AEAD encryption under key `k` //! - 𝐌: message //! - 𝐍: nonce //! - 𝐀: additional associated data //! - 𝐂: ciphertext //! - 𝜏: MAC tag //! //! [1]: https://eprint.iacr.org/2015/189.pdf #![allow(clippy::upper_case_acronyms)] use crate::{AeadCore, AeadInPlace, Buffer, Error, Key, KeyInit, Result}; use core::ops::{AddAssign, Sub}; use generic_array::{ typenum::{Unsigned, U4, U5}, ArrayLength, GenericArray, }; #[cfg(feature = "alloc")] use {crate::Payload, alloc::vec::Vec}; /// Nonce as used by a given AEAD construction and STREAM primitive. pub type Nonce = GenericArray>; /// Size of a nonce as used by a STREAM construction, sans the overhead of /// the STREAM protocol itself. pub type NonceSize = <::NonceSize as Sub<>::NonceOverhead>>::Output; /// STREAM encryptor instantiated with [`StreamBE32`] as the underlying /// STREAM primitive. pub type EncryptorBE32 = Encryptor>; /// STREAM decryptor instantiated with [`StreamBE32`] as the underlying /// STREAM primitive. pub type DecryptorBE32 = Decryptor>; /// STREAM encryptor instantiated with [`StreamLE31`] as the underlying /// STREAM primitive. pub type EncryptorLE31 = Encryptor>; /// STREAM decryptor instantiated with [`StreamLE31`] as the underlying /// STREAM primitive. pub type DecryptorLE31 = Decryptor>; /// Create a new STREAM from the provided AEAD. pub trait NewStream: StreamPrimitive where A: AeadInPlace, A::NonceSize: Sub, NonceSize: ArrayLength, { /// Create a new STREAM with the given key and nonce. fn new(key: &Key, nonce: &Nonce) -> Self where A: KeyInit, Self: Sized, { Self::from_aead(A::new(key), nonce) } /// Create a new STREAM from the given AEAD cipher. fn from_aead(aead: A, nonce: &Nonce) -> Self; } /// Low-level STREAM implementation. /// /// This trait provides a particular "flavor" of STREAM, as there are /// different ways the specifics of the construction can be implemented. /// /// Deliberately immutable and stateless to permit parallel operation. pub trait StreamPrimitive where A: AeadInPlace, A::NonceSize: Sub, NonceSize: ArrayLength, { /// Number of bytes this STREAM primitive requires from the nonce. type NonceOverhead: ArrayLength; /// Type used as the STREAM counter. type Counter: AddAssign + Copy + Default + Eq; /// Value to use when incrementing the STREAM counter (i.e. one) const COUNTER_INCR: Self::Counter; /// Maximum value of the STREAM counter. const COUNTER_MAX: Self::Counter; /// Encrypt an AEAD message in-place at the given position in the STREAM. fn encrypt_in_place( &self, position: Self::Counter, last_block: bool, associated_data: &[u8], buffer: &mut dyn Buffer, ) -> Result<()>; /// Decrypt an AEAD message in-place at the given position in the STREAM. fn decrypt_in_place( &self, position: Self::Counter, last_block: bool, associated_data: &[u8], buffer: &mut dyn Buffer, ) -> Result<()>; /// Encrypt the given plaintext payload, and return the resulting /// ciphertext as a vector of bytes. #[cfg(feature = "alloc")] #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] fn encrypt<'msg, 'aad>( &self, position: Self::Counter, last_block: bool, plaintext: impl Into>, ) -> Result> { let payload = plaintext.into(); let mut buffer = Vec::with_capacity(payload.msg.len() + A::TagSize::to_usize()); buffer.extend_from_slice(payload.msg); self.encrypt_in_place(position, last_block, payload.aad, &mut buffer)?; Ok(buffer) } /// Decrypt the given ciphertext slice, and return the resulting plaintext /// as a vector of bytes. #[cfg(feature = "alloc")] #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] fn decrypt<'msg, 'aad>( &self, position: Self::Counter, last_block: bool, ciphertext: impl Into>, ) -> Result> { let payload = ciphertext.into(); let mut buffer = Vec::from(payload.msg); self.decrypt_in_place(position, last_block, payload.aad, &mut buffer)?; Ok(buffer) } /// Obtain [`Encryptor`] for this [`StreamPrimitive`]. fn encryptor(self) -> Encryptor where Self: Sized, { Encryptor::from_stream_primitive(self) } /// Obtain [`Decryptor`] for this [`StreamPrimitive`]. fn decryptor(self) -> Decryptor where Self: Sized, { Decryptor::from_stream_primitive(self) } } /// Implement a stateful STREAM object (i.e. encryptor or decryptor) macro_rules! impl_stream_object { ( $name:ident, $next_method:tt, $next_in_place_method:tt, $last_method:tt, $last_in_place_method:tt, $op:tt, $in_place_op:tt, $op_desc:expr, $obj_desc:expr ) => { #[doc = "Stateful STREAM object which can"] #[doc = $op_desc] #[doc = "AEAD messages one-at-a-time."] #[doc = ""] #[doc = "This corresponds to the "] #[doc = $obj_desc] #[doc = "object as defined in the paper"] #[doc = "[Online Authenticated-Encryption and its Nonce-Reuse Misuse-Resistance][1]."] #[doc = ""] #[doc = "[1]: https://eprint.iacr.org/2015/189.pdf"] pub struct $name where A: AeadInPlace, S: StreamPrimitive, A::NonceSize: Sub<>::NonceOverhead>, NonceSize: ArrayLength, { /// Underlying STREAM primitive. stream: S, /// Current position in the STREAM. position: S::Counter, } impl $name where A: AeadInPlace, S: StreamPrimitive, A::NonceSize: Sub<>::NonceOverhead>, NonceSize: ArrayLength, { #[doc = "Create a"] #[doc = $obj_desc] #[doc = "object from the given AEAD key and nonce."] pub fn new(key: &Key, nonce: &Nonce) -> Self where A: KeyInit, S: NewStream, { Self::from_stream_primitive(S::new(key, nonce)) } #[doc = "Create a"] #[doc = $obj_desc] #[doc = "object from the given AEAD primitive."] pub fn from_aead(aead: A, nonce: &Nonce) -> Self where A: KeyInit, S: NewStream, { Self::from_stream_primitive(S::from_aead(aead, nonce)) } #[doc = "Create a"] #[doc = $obj_desc] #[doc = "object from the given STREAM primitive."] pub fn from_stream_primitive(stream: S) -> Self { Self { stream, position: Default::default(), } } #[doc = "Use the underlying AEAD to"] #[doc = $op_desc] #[doc = "the next AEAD message in this STREAM, returning the"] #[doc = "result as a [`Vec`]."] #[cfg(feature = "alloc")] #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] pub fn $next_method<'msg, 'aad>( &mut self, payload: impl Into>, ) -> Result> { if self.position == S::COUNTER_MAX { // Counter overflow. Note that the maximum counter value is // deliberately disallowed, as it would preclude being able // to encrypt a last block (i.e. with `$last_in_place_method`) return Err(Error); } let result = self.stream.$op(self.position, false, payload)?; // Note: overflow checked above self.position += S::COUNTER_INCR; Ok(result) } #[doc = "Use the underlying AEAD to"] #[doc = $op_desc] #[doc = "the next AEAD message in this STREAM in-place."] pub fn $next_in_place_method( &mut self, associated_data: &[u8], buffer: &mut dyn Buffer, ) -> Result<()> { if self.position == S::COUNTER_MAX { // Counter overflow. Note that the maximum counter value is // deliberately disallowed, as it would preclude being able // to encrypt a last block (i.e. with `$last_in_place_method`) return Err(Error); } self.stream .$in_place_op(self.position, false, associated_data, buffer)?; // Note: overflow checked above self.position += S::COUNTER_INCR; Ok(()) } #[doc = "Use the underlying AEAD to"] #[doc = $op_desc] #[doc = "the last AEAD message in this STREAM,"] #[doc = "consuming the "] #[doc = $obj_desc] #[doc = "object in order to prevent further use."] #[cfg(feature = "alloc")] #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] pub fn $last_method<'msg, 'aad>( self, payload: impl Into>, ) -> Result> { self.stream.$op(self.position, true, payload) } #[doc = "Use the underlying AEAD to"] #[doc = $op_desc] #[doc = "the last AEAD message in this STREAM in-place,"] #[doc = "consuming the "] #[doc = $obj_desc] #[doc = "object in order to prevent further use."] pub fn $last_in_place_method( self, associated_data: &[u8], buffer: &mut dyn Buffer, ) -> Result<()> { self.stream .$in_place_op(self.position, true, associated_data, buffer) } } }; } impl_stream_object!( Encryptor, encrypt_next, encrypt_next_in_place, encrypt_last, encrypt_last_in_place, encrypt, encrypt_in_place, "encrypt", "β„° STREAM encryptor" ); impl_stream_object!( Decryptor, decrypt_next, decrypt_next_in_place, decrypt_last, decrypt_last_in_place, decrypt, decrypt_in_place, "decrypt", "π’Ÿ STREAM decryptor" ); /// The original "Rogaway-flavored" STREAM as described in the paper /// [Online Authenticated-Encryption and its Nonce-Reuse Misuse-Resistance][1]. /// /// Uses a 32-bit big endian counter and 1-byte "last block" flag stored as /// the last 5-bytes of the AEAD nonce. /// /// [1]: https://eprint.iacr.org/2015/189.pdf pub struct StreamBE32 where A: AeadInPlace, A::NonceSize: Sub, <::NonceSize as Sub>::Output: ArrayLength, { /// Underlying AEAD cipher aead: A, /// Nonce (sans STREAM overhead) nonce: Nonce, } impl NewStream for StreamBE32 where A: AeadInPlace, A::NonceSize: Sub, <::NonceSize as Sub>::Output: ArrayLength, { fn from_aead(aead: A, nonce: &Nonce) -> Self { Self { aead, nonce: nonce.clone(), } } } impl StreamPrimitive for StreamBE32 where A: AeadInPlace, A::NonceSize: Sub, <::NonceSize as Sub>::Output: ArrayLength, { type NonceOverhead = U5; type Counter = u32; const COUNTER_INCR: u32 = 1; const COUNTER_MAX: u32 = core::u32::MAX; fn encrypt_in_place( &self, position: u32, last_block: bool, associated_data: &[u8], buffer: &mut dyn Buffer, ) -> Result<()> { let nonce = self.aead_nonce(position, last_block); self.aead.encrypt_in_place(&nonce, associated_data, buffer) } fn decrypt_in_place( &self, position: Self::Counter, last_block: bool, associated_data: &[u8], buffer: &mut dyn Buffer, ) -> Result<()> { let nonce = self.aead_nonce(position, last_block); self.aead.decrypt_in_place(&nonce, associated_data, buffer) } } impl StreamBE32 where A: AeadInPlace, A::NonceSize: Sub, <::NonceSize as Sub>::Output: ArrayLength, { /// Compute the full AEAD nonce including the STREAM counter and last /// block flag. fn aead_nonce(&self, position: u32, last_block: bool) -> crate::Nonce { let mut result = GenericArray::default(); // TODO(tarcieri): use `generic_array::sequence::Concat` (or const generics) let (prefix, tail) = result.split_at_mut(NonceSize::::to_usize()); prefix.copy_from_slice(&self.nonce); let (counter, flag) = tail.split_at_mut(4); counter.copy_from_slice(&position.to_be_bytes()); flag[0] = last_block as u8; result } } /// STREAM as instantiated with a 31-bit little endian counter and 1-bit /// "last block" flag stored as the most significant bit of the counter /// when interpreted as a 32-bit integer. /// /// The 31-bit + 1-bit value is stored as the last 4 bytes of the AEAD nonce. pub struct StreamLE31 where A: AeadInPlace, A::NonceSize: Sub, <::NonceSize as Sub>::Output: ArrayLength, { /// Underlying AEAD cipher aead: A, /// Nonce (sans STREAM overhead) nonce: Nonce, } impl NewStream for StreamLE31 where A: AeadInPlace, A::NonceSize: Sub, <::NonceSize as Sub>::Output: ArrayLength, { fn from_aead(aead: A, nonce: &Nonce) -> Self { Self { aead, nonce: nonce.clone(), } } } impl StreamPrimitive for StreamLE31 where A: AeadInPlace, A::NonceSize: Sub, <::NonceSize as Sub>::Output: ArrayLength, { type NonceOverhead = U4; type Counter = u32; const COUNTER_INCR: u32 = 1; const COUNTER_MAX: u32 = 0xfff_ffff; fn encrypt_in_place( &self, position: u32, last_block: bool, associated_data: &[u8], buffer: &mut dyn Buffer, ) -> Result<()> { let nonce = self.aead_nonce(position, last_block)?; self.aead.encrypt_in_place(&nonce, associated_data, buffer) } fn decrypt_in_place( &self, position: Self::Counter, last_block: bool, associated_data: &[u8], buffer: &mut dyn Buffer, ) -> Result<()> { let nonce = self.aead_nonce(position, last_block)?; self.aead.decrypt_in_place(&nonce, associated_data, buffer) } } impl StreamLE31 where A: AeadInPlace, A::NonceSize: Sub, <::NonceSize as Sub>::Output: ArrayLength, { /// Compute the full AEAD nonce including the STREAM counter and last /// block flag. fn aead_nonce(&self, position: u32, last_block: bool) -> Result> { if position > Self::COUNTER_MAX { return Err(Error); } let mut result = GenericArray::default(); // TODO(tarcieri): use `generic_array::sequence::Concat` (or const generics) let (prefix, tail) = result.split_at_mut(NonceSize::::to_usize()); prefix.copy_from_slice(&self.nonce); let position_with_flag = position | ((last_block as u32) << 31); tail.copy_from_slice(&position_with_flag.to_le_bytes()); Ok(result) } }