diff --git a/.github/workflows/aead-stream.yml b/.github/workflows/aead-stream.yml new file mode 100644 index 00000000..5f3f2720 --- /dev/null +++ b/.github/workflows/aead-stream.yml @@ -0,0 +1,67 @@ +name: aead-stream + +on: + pull_request: + paths: + - ".github/workflows/aead-stream.yml" + - "aead-stream/**" + - "Cargo.*" + push: + branches: master + +defaults: + run: + working-directory: aead-stream + +env: + CARGO_INCREMENTAL: 0 + RUSTFLAGS: "-Dwarnings" + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + rust: + - 1.65.0 # MSRV + - stable + target: + - thumbv7em-none-eabi + - wasm32-unknown-unknown + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ matrix.rust }} + targets: ${{ matrix.target }} + - run: cargo build --no-default-features --release --target ${{ matrix.target }} + + test: + runs-on: ubuntu-latest + strategy: + matrix: + include: + # 32-bit Linux + - target: i686-unknown-linux-gnu + rust: 1.65.0 # MSRV + deps: sudo apt update && sudo apt install gcc-multilib + - target: i686-unknown-linux-gnu + rust: stable + deps: sudo apt update && sudo apt install gcc-multilib + + # 64-bit Linux + - target: x86_64-unknown-linux-gnu + rust: 1.65.0 # MSRV + - target: x86_64-unknown-linux-gnu + rust: stable + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ matrix.rust }} + targets: ${{ matrix.target }} + - run: ${{ matrix.deps }} + - run: cargo test --target ${{ matrix.target }} --release --no-default-features + - run: cargo test --target ${{ matrix.target }} --release + - run: cargo test --target ${{ matrix.target }} --release --all-features + - run: cargo build --target ${{ matrix.target }} --benches diff --git a/Cargo.lock b/Cargo.lock index 49c63547..af9862e6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -15,6 +15,13 @@ dependencies = [ "heapless", ] +[[package]] +name = "aead-stream" +version = "0.6.0-pre" +dependencies = [ + "aead", +] + [[package]] name = "aes" version = "0.9.0-pre.1" @@ -72,9 +79,9 @@ dependencies = [ [[package]] name = "arrayvec" -version = "0.7.4" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" [[package]] name = "ascon" @@ -104,9 +111,9 @@ checksum = "847495c209977a90e8aad588b959d0ca9f5dc228096d29a6bd3defd53f35eaec" [[package]] name = "block-buffer" -version = "0.11.0-rc.0" +version = "0.11.0-rc.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17092d478f4fadfb35a7e082f62e49f0907fdf048801d9d706277e34f9df8a78" +checksum = "8969801e57d15e15bc4d7cdc5600dc15ca06a9a62b622bd4871c2d21d8aeb42d" dependencies = [ "crypto-common", ] @@ -122,9 +129,9 @@ dependencies = [ [[package]] name = "byteorder" -version = "1.4.3" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "ccm" @@ -190,18 +197,18 @@ dependencies = [ [[package]] name = "cpufeatures" -version = "0.2.12" +version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "53fe5e26ff1b7aef8bca9c6080520cfb8d9333c7568e1829cef191a9723e5504" +checksum = "608697df725056feaccfa42cffdaeeec3fccc4ffc38358ecd19b243e716a78e0" dependencies = [ "libc", ] [[package]] name = "crypto-common" -version = "0.2.0-rc.0" +version = "0.2.0-rc.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c070b79a496dccd931229780ad5bbedd535ceff6c3565605a8e440e18e1aa2b" +checksum = "b0b8ce8218c97789f16356e7896b3714f26c2ee1079b79c0b7ae7064bb9089fa" dependencies = [ "getrandom", "hybrid-array", @@ -262,9 +269,9 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.12" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "190092ea657667030ac6a35e305e62fc4dd69fd98ac98631e5d3a2b1575a12b5" +checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" dependencies = [ "cfg-if", "libc", @@ -327,9 +334,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.153" +version = "0.2.158" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd" +checksum = "d8adc4bb1803a324070e64a98ae98f38934d91957a99cfb3a43dcbc01bc56439" [[package]] name = "ocb3" @@ -387,18 +394,18 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.79" +version = "1.0.86" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e835ff2298f5721608eb1a980ecaee1aef2c132bf95ecc026a11b7bf3c01c02e" +checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.35" +version = "1.0.37" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" +checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" dependencies = [ "proc-macro2", ] @@ -420,15 +427,15 @@ checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" [[package]] name = "subtle" -version = "2.5.0" +version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "syn" -version = "2.0.55" +version = "2.0.77" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "002a1b3dbf967edfafc32655d0f377ab0bb7b994aa1d32c8cc7e9b8bf3ebb8f0" +checksum = "9f35bcdf61fd8e7be6caf75f429fdca8beb3ed76584befb503b1569faee373ed" dependencies = [ "proc-macro2", "quote", @@ -443,9 +450,9 @@ checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" [[package]] name = "unicode-ident" -version = "1.0.12" +version = "1.0.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" +checksum = "e91b56cd4cadaeb79bbf1a5645f6b4f8dc5bde8834ad5894a8db35fda9efa1fe" [[package]] name = "universal-hash" diff --git a/Cargo.toml b/Cargo.toml index aa571994..d6f1c0df 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,6 @@ [workspace] members = [ + "aead-stream", "aes-gcm", "aes-gcm-siv", "aes-siv", diff --git a/README.md b/README.md index bf56003a..97732fa7 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ crate. | Name | Algorithm | Crates.io | Documentation | MSRV | |----------------------|------------------------------|-----------|---------------|-------| +| [`aead-stream`] | [STREAM] | [![crates.io](https://img.shields.io/crates/v/aead-stream.svg)](https://crates.io/crates/aead-stream) | [![Documentation](https://docs.rs/aead-stream/badge.svg)](https://docs.rs/aead-stream) | 1.65 | | [`aes-gcm-siv`] | [AES-GCM-SIV] | [![crates.io](https://img.shields.io/crates/v/aes-gcm-siv.svg)](https://crates.io/crates/aes-gcm-siv) | [![Documentation](https://docs.rs/aes-gcm-siv/badge.svg)](https://docs.rs/aes-gcm-siv) | 1.51 | | [`aes-gcm`] | [AES-GCM] | [![crates.io](https://img.shields.io/crates/v/aes-gcm.svg)](https://crates.io/crates/aes-gcm) | [![Documentation](https://docs.rs/aes-gcm/badge.svg)](https://docs.rs/aes-gcm) | 1.51 | | [`aes-siv`] | [AES-SIV] | [![crates.io](https://img.shields.io/crates/v/aes-siv.svg)](https://crates.io/crates/aes-siv) | [![Documentation](https://docs.rs/aes-siv/badge.svg)](https://docs.rs/aes-siv) | 1.51 | @@ -76,6 +77,7 @@ dual licensed as above, without any additional terms or conditions. [//]: # (algorithms) +[STREAM]: https://eprint.iacr.org/2015/189.pdf [AES-GCM]: https://en.wikipedia.org/wiki/Galois/Counter_Mode [AES-GCM-SIV]: https://en.wikipedia.org/wiki/AES-GCM-SIV [AES-SIV]: https://github.com/miscreant/meta/wiki/AES-SIV diff --git a/aead-stream/CHANGELOG.md b/aead-stream/CHANGELOG.md new file mode 100644 index 00000000..c0efc932 --- /dev/null +++ b/aead-stream/CHANGELOG.md @@ -0,0 +1,8 @@ +# 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). + +## UNRELEASED +- Initial release diff --git a/aead-stream/Cargo.toml b/aead-stream/Cargo.toml new file mode 100644 index 00000000..0cbf1ae2 --- /dev/null +++ b/aead-stream/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "aead-stream" +version = "0.6.0-pre" +description = "Generic implementation of the STREAM online authenticated encryption construction" +authors = ["RustCrypto Developers"] +edition = "2021" +license = "Apache-2.0 OR MIT" +readme = "README.md" +documentation = "https://docs.rs/aead-stream" +repository = "https://github.com/RustCrypto/AEADs" +keywords = ["aead", "stream", "encryption"] +categories = ["cryptography", "no-std"] +rust-version = "1.65" + +[dependencies] +aead = { version = "=0.6.0-rc.0", default-features = false, features = ["stream"] } + +[features] +alloc = ["aead/alloc"] diff --git a/aead-stream/LICENSE-APACHE b/aead-stream/LICENSE-APACHE new file mode 100644 index 00000000..78173fa2 --- /dev/null +++ b/aead-stream/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/aead-stream/LICENSE-MIT b/aead-stream/LICENSE-MIT new file mode 100644 index 00000000..455de7c8 --- /dev/null +++ b/aead-stream/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2024 The RustCrypto Project 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. diff --git a/aead-stream/README.md b/aead-stream/README.md new file mode 100644 index 00000000..e1e7822e --- /dev/null +++ b/aead-stream/README.md @@ -0,0 +1,67 @@ +# RustCrypto: AEAD-STREAM + +[![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] + +Generic pure-Rust 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 + +## 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-stream +[crate-link]: https://crates.io/crates/aead-stream +[docs-image]: https://docs.rs/aead-stream/badge.svg +[docs-link]: https://docs.rs/aead-stream/ +[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg +[rustc-image]: https://img.shields.io/badge/rustc-1.65+-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/AEADs/workflows/aead-stream/badge.svg?branch=master&event=push +[build-link]: https://github.com/RustCrypto/AEADs/actions + +[//]: # (general links) + +[1]: https://eprint.iacr.org/2015/189.pdf diff --git a/aead-stream/src/lib.rs b/aead-stream/src/lib.rs new file mode 100644 index 00000000..7b5d5215 --- /dev/null +++ b/aead-stream/src/lib.rs @@ -0,0 +1,229 @@ +#![no_std] +#![doc = include_str!("../README.md")] +#![allow(clippy::upper_case_acronyms)] + +#[cfg(feature = "alloc")] +extern crate alloc; + +use aead::array::{ + typenum::{Unsigned, U4, U5}, + Array, ArraySize, +}; +use aead::{AeadCore, AeadInPlace, Buffer, Error, Result}; +use core::ops::Sub; + +pub use aead; + +pub use aead::{ + stream::{Decryptor, Encryptor, NewStream, StreamPrimitive}, + Key, KeyInit, +}; + +/// Nonce as used by a given AEAD construction and STREAM primitive. +pub type Nonce = Array>; + +/// 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>; + +/// 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 +#[derive(Debug)] +pub struct StreamBE32 +where + A: AeadInPlace, + A::NonceSize: Sub, + <::NonceSize as Sub>::Output: ArraySize, +{ + /// 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: ArraySize, +{ + 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: ArraySize, +{ + type NonceOverhead = U5; + type Counter = u32; + const COUNTER_INCR: u32 = 1; + const COUNTER_MAX: u32 = 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: ArraySize, +{ + /// Compute the full AEAD nonce including the STREAM counter and last + /// block flag. + fn aead_nonce(&self, position: u32, last_block: bool) -> aead::Nonce { + let mut result = Array::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. +#[derive(Debug)] +pub struct StreamLE31 +where + A: AeadInPlace, + A::NonceSize: Sub, + <::NonceSize as Sub>::Output: ArraySize, +{ + /// 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: ArraySize, +{ + 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: ArraySize, +{ + 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: ArraySize, +{ + /// 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 = Array::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) + } +}