eax-0.5.0/.cargo_vcs_info.json0000644000000001410000000000100116070ustar { "git": { "sha1": "c66e1e9095f038a3601db9aaed010eef9fe581c6" }, "path_in_vcs": "eax" }eax-0.5.0/CHANGELOG.md000064400000000000000000000037130072674642500122500ustar 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.0 (2022-07-30) ### Added - `getrandom` feature ([#446]) ### Changed - Relax `subtle` and `zeroize` requirements ([#360]) - Rust 2021 edition upgrade; MSRV 1.56+ ([#435]) - Bump `aead` crate dependency to v0.5 ([#444]) - Bump `cipher` to v0.4 ([#451]) [#360]: https://github.com/RustCrypto/AEADs/pull/360 [#435]: https://github.com/RustCrypto/AEADs/pull/435 [#444]: https://github.com/RustCrypto/AEADs/pull/444 [#446]: https://github.com/RustCrypto/AEADs/pull/446 [#451]: https://github.com/RustCrypto/AEADs/pull/451 ## 0.4.1 (2021-07-20) ### Changed - Pin `subtle` dependency to v2.4 ([#349]) [#349]: https://github.com/RustCrypto/AEADs/pull/349 ## 0.4.0 (2021-04-29) ### Added - Allow variable tag length ([#231]) ### Changed - Bump `aead` crate dependency to v0.4 ([#270]) - Bump `aes` and `ctr` crate dependencies to v0.7 ([#283]) - Bump `cmac` and `pmac` deps to v0.6 releases ([#285]) [#231]: https://github.com/RustCrypto/AEADs/pull/231 [#270]: https://github.com/RustCrypto/AEADs/pull/270 [#283]: https://github.com/RustCrypto/AEADs/pull/283 [#285]: https://github.com/RustCrypto/AEADs/pull/285 ## 0.3.0 (2020-10-16) ### Changed - Replace `block-cipher`/`stream-cipher` with `cipher` crate ([#229]) [#229]: https://github.com/RustCrypto/AEADs/pull/229 ## 0.2.0 (2020-09-30 ### Added - API for online encryption/decryption ([#214]) - Optional `std` feature; disabled by default ([#217]) ### Changed - Use `aead` crate; MSRV 1.41+ - Upgrade `aes` to v0.5, `block-cipher` to v0.8, `cmac` to v0.4, `ctr` to v0.5 ([#209]) [#217]: https://github.com/RustCrypto/AEADs/pull/217 [#214]: https://github.com/RustCrypto/AEADs/pull/214 [#209]: https://github.com/RustCrypto/AEADs/pull/209 ## 0.1.0 (2019-03-29) - Initial release eax-0.5.0/Cargo.toml0000644000000034470000000000100076210ustar # 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 = "eax" version = "0.5.0" authors = ["RustCrypto Developers"] description = """ Pure Rust implementation of the EAX Authenticated Encryption with Associated Data (AEAD) Cipher with optional architecture-specific hardware acceleration This scheme is only based on a block cipher. It uses counter mode (CTR) for encryption and CBC mode for generating a OMAC/CMAC/CBCMAC (all names for the same thing). """ documentation = "https://docs.rs/eax" readme = "README.md" keywords = [ "aead", "aes", "encryption", ] categories = [ "cryptography", "no-std", ] license = "Apache-2.0 OR MIT" repository = "https://github.com/RustCrypto/AEADs" [package.metadata.docs.rs] all-features = true rustdoc-args = [ "--cfg", "docsrs", ] [dependencies.aead] version = "0.5" default-features = false [dependencies.cipher] version = "0.4" [dependencies.cmac] version = "0.7" [dependencies.ctr] version = "0.9" [dependencies.subtle] version = "2" default-features = false [dev-dependencies.aead] version = "0.5" features = ["dev"] default-features = false [dev-dependencies.aes] version = "0.8" [features] alloc = ["aead/alloc"] default = [ "alloc", "getrandom", ] getrandom = ["aead/getrandom"] heapless = ["aead/heapless"] std = [ "aead/std", "alloc", ] stream = ["aead/stream"] eax-0.5.0/Cargo.toml.orig000064400000000000000000000022740072674642500133270ustar 00000000000000[package] name = "eax" version = "0.5.0" description = """ Pure Rust implementation of the EAX Authenticated Encryption with Associated Data (AEAD) Cipher with optional architecture-specific hardware acceleration This scheme is only based on a block cipher. It uses counter mode (CTR) for encryption and CBC mode for generating a OMAC/CMAC/CBCMAC (all names for the same thing). """ authors = ["RustCrypto Developers"] edition = "2021" license = "Apache-2.0 OR MIT" readme = "README.md" documentation = "https://docs.rs/eax" repository = "https://github.com/RustCrypto/AEADs" keywords = ["aead", "aes", "encryption"] categories = ["cryptography", "no-std"] rust-version = "1.56" [dependencies] aead = { version = "0.5", default-features = false } cipher = "0.4" cmac = "0.7" ctr = "0.9" subtle = { version = "2", default-features = false } [dev-dependencies] aead = { version = "0.5", features = ["dev"], default-features = false } aes = "0.8" [features] default = ["alloc", "getrandom"] std = ["aead/std", "alloc"] alloc = ["aead/alloc"] getrandom = ["aead/getrandom"] heapless = ["aead/heapless"] stream = ["aead/stream"] [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg", "docsrs"] eax-0.5.0/LICENSE-APACHE000064400000000000000000000251410072674642500123620ustar 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. eax-0.5.0/LICENSE-MIT000064400000000000000000000020650072674642500120720ustar 00000000000000Copyright (c) 2020 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. eax-0.5.0/README.md000064400000000000000000000032670072674642500117220ustar 00000000000000# RustCrypto: EAX [![crate][crate-image]][crate-link] [![Docs][docs-image]][docs-link] ![Apache2/MIT licensed][license-image] ![Rust Version][rustc-image] [![CodeCov Status][codecov-image]][codecov-link] [![Project Chat][chat-image]][chat-link] [![Build Status][build-image]][build-link] Pure Rust implementation of the EAX [Authenticated Encryption with Associated Data (AEAD)][1] cipher. [Documentation][docs-link] ## 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/eax.svg [crate-link]: https://crates.io/crates/eax [docs-image]: https://docs.rs/eax/badge.svg [docs-link]: https://docs.rs/eax/ [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 [codecov-image]: https://codecov.io/gh/RustCrypto/AEADs/branch/master/graph/badge.svg [codecov-link]: https://codecov.io/gh/RustCrypto/AEADs [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/eax/badge.svg?branch=master&event=push [build-link]: https://github.com/RustCrypto/AEADs/actions [//]: # (general links) [1]: https://en.wikipedia.org/wiki/Authenticated_encryption eax-0.5.0/src/lib.rs000064400000000000000000000232020072674642500123350ustar 00000000000000//! EAX: [Authenticated Encryption and Associated Data (AEAD)][1] cipher //! based on AES in counter mode. //! //! # Usage //! //! Simple usage (allocating, no associated data): //! #![cfg_attr(all(feature = "getrandom", feature = "std"), doc = "```")] #![cfg_attr(not(all(feature = "getrandom", feature = "std")), doc = "```ignore")] //! # fn main() -> Result<(), Box> { //! use aes::Aes256; //! use eax::{ //! aead::{Aead, KeyInit, OsRng, generic_array::GenericArray}, //! Eax, Nonce //! }; //! //! pub type Aes256Eax = Eax; //! //! let key = Aes256Eax::generate_key(&mut OsRng); //! let cipher = Aes256Eax::new(&key); //! let nonce = GenericArray::from_slice(b"my unique nonces"); // 128-bits; unique per message //! let ciphertext = cipher.encrypt(nonce, b"plaintext message".as_ref())?; //! let plaintext = cipher.decrypt(nonce, ciphertext.as_ref())?; //! assert_eq!(&plaintext, b"plaintext message"); //! # Ok(()) //! # } //! ``` //! //! ## In-place Usage (eliminates `alloc` requirement) //! //! This crate has an optional `alloc` feature which can be disabled in e.g. //! microcontroller environments that don't have a heap. //! //! The [`AeadInPlace::encrypt_in_place`] and [`AeadInPlace::decrypt_in_place`] //! methods accept any type that impls the [`aead::Buffer`] trait which //! contains the plaintext for encryption or ciphertext for decryption. //! //! Note that if you enable the `heapless` feature of this crate, //! you will receive an impl of [`aead::Buffer`] for `heapless::Vec` //! (re-exported from the [`aead`] crate as [`aead::heapless::Vec`]), //! which can then be passed as the `buffer` parameter to the in-place encrypt //! and decrypt methods: //! //! ``` //! # #[cfg(feature = "heapless")] //! # { //! use aes::Aes256; //! use eax::Eax; //! use eax::aead::{AeadInPlace, KeyInit, generic_array::GenericArray}; //! use eax::aead::heapless::Vec; //! //! let key = GenericArray::from_slice(b"an example very very secret key."); //! let cipher = Eax::::new(key); //! //! let nonce = GenericArray::from_slice(b"my unique nonces"); // 128-bits; unique per message //! //! let mut buffer: Vec = Vec::new(); //! buffer.extend_from_slice(b"plaintext message"); //! //! // Encrypt `buffer` in-place, replacing the plaintext contents with ciphertext //! cipher.encrypt_in_place(nonce, b"", &mut buffer).expect("encryption failure!"); //! //! // `buffer` now contains the message ciphertext //! assert_ne!(&buffer, b"plaintext message"); //! //! // Decrypt `buffer` in-place, replacing its ciphertext context with the original plaintext //! cipher.decrypt_in_place(nonce, b"", &mut buffer).expect("decryption failure!"); //! assert_eq!(&buffer, b"plaintext message"); //! # } //! ``` //! //! ## Custom Tag Length //! //! The tag for eax is usually 16 bytes long but it can be shortened if needed. //! The second generic argument of `Eax` can be set to the tag length: //! //! ``` //! # #[cfg(feature = "heapless")] //! # { //! use aes::Aes256; //! use eax::Eax; //! use eax::aead::{AeadInPlace, KeyInit, generic_array::GenericArray}; //! use eax::aead::heapless::Vec; //! use eax::aead::consts::{U8, U128}; //! //! let key = GenericArray::from_slice(b"an example very very secret key."); //! let cipher = Eax::::new(key); //! //! let nonce = GenericArray::from_slice(b"my unique nonces"); // 128-bits; unique per message //! //! let mut buffer: Vec = Vec::new(); //! buffer.extend_from_slice(b"plaintext message"); //! //! // Encrypt `buffer` in-place, replacing the plaintext contents with ciphertext //! let tag = cipher.encrypt_in_place_detached(nonce, b"", &mut buffer).expect("encryption failure!"); //! //! // The tag has only 8 bytes, compared to the usual 16 bytes //! assert_eq!(tag.len(), 8); //! //! // `buffer` now contains the message ciphertext //! assert_ne!(&buffer, b"plaintext message"); //! //! // Decrypt `buffer` in-place, replacing its ciphertext context with the original plaintext //! cipher.decrypt_in_place_detached(nonce, b"", &mut buffer, &tag).expect("decryption failure!"); //! assert_eq!(&buffer, b"plaintext message"); //! # } //! ``` //! //! [1]: https://en.wikipedia.org/wiki/Authenticated_encryption #![no_std] #![cfg_attr(docsrs, feature(doc_cfg))] #![doc( html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg", html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg" )] #![deny(unsafe_code)] #![warn(missing_docs, rust_2018_idioms)] pub use aead::{self, AeadCore, AeadInPlace, Error, Key, KeyInit, KeySizeUser}; pub use cipher; use cipher::{ consts::{U0, U16}, generic_array::{functional::FunctionalSequence, GenericArray}, BlockCipher, BlockEncrypt, InnerIvInit, StreamCipherCore, }; use cmac::{digest::Output, Cmac, Mac}; use core::marker::PhantomData; mod traits; use traits::TagSize; // TODO Max values? /// Maximum length of associated data pub const A_MAX: u64 = 1 << 36; /// Maximum length of plaintext pub const P_MAX: u64 = 1 << 36; /// Maximum length of ciphertext pub const C_MAX: u64 = (1 << 36) + 16; /// EAX nonces pub type Nonce = GenericArray; /// EAX tags pub type Tag = GenericArray; pub mod online; /// Counter mode with a 128-bit big endian counter. type Ctr128BE = ctr::CtrCore; /// EAX: generic over an underlying block cipher implementation. /// /// This type is generic to support substituting alternative cipher /// implementations. /// /// If in doubt, use the built-in [`Aes128Eax`] and [`Aes256Eax`] type aliases. /// /// Type parameters: /// - `Cipher`: block cipher. /// - `M`: size of MAC tag, valid values: up to `U16`. #[derive(Clone)] pub struct Eax where Cipher: BlockCipher + BlockEncrypt + Clone + KeyInit, M: TagSize, { /// Encryption key key: Key, _tag_size: PhantomData, } impl KeySizeUser for Eax where Cipher: BlockCipher + BlockEncrypt + Clone + KeyInit, M: TagSize, { type KeySize = Cipher::KeySize; } impl KeyInit for Eax where Cipher: BlockCipher + BlockEncrypt + Clone + KeyInit, M: TagSize, { fn new(key: &Key) -> Self { Self { key: key.clone(), _tag_size: PhantomData, } } } impl AeadCore for Eax where Cipher: BlockCipher + BlockEncrypt + Clone + KeyInit, M: TagSize, { type NonceSize = Cipher::BlockSize; type TagSize = M; type CiphertextOverhead = U0; } impl AeadInPlace for Eax where Cipher: BlockCipher + BlockEncrypt + Clone + KeyInit, M: TagSize, { fn encrypt_in_place_detached( &self, nonce: &Nonce, associated_data: &[u8], buffer: &mut [u8], ) -> Result, Error> { if buffer.len() as u64 > P_MAX || associated_data.len() as u64 > A_MAX { return Err(Error); } // https://crypto.stackexchange.com/questions/26948/eax-cipher-mode-with-nonce-equal-header // has an explanation of eax. // l = block cipher size = 128 (for AES-128) = 16 byte // 1. n ← OMAC(0 || Nonce) // (the 0 means the number zero in l bits) let n = Self::cmac_with_iv(&self.key, 0, nonce); // 2. h ← OMAC(1 || associated data) let h = Self::cmac_with_iv(&self.key, 1, associated_data); // 3. enc ← CTR(M) using n as iv Ctr128BE::::inner_iv_init(Cipher::new(&self.key), &n) .apply_keystream_partial(buffer.into()); // 4. c ← OMAC(2 || enc) let c = Self::cmac_with_iv(&self.key, 2, buffer); // 5. tag ← n ^ h ^ c // (^ means xor) let full_tag = n.zip(h, |a, b| a ^ b).zip(c, |a, b| a ^ b); let tag = Tag::::clone_from_slice(&full_tag[..M::to_usize()]); Ok(tag) } fn decrypt_in_place_detached( &self, nonce: &Nonce, associated_data: &[u8], buffer: &mut [u8], tag: &Tag, ) -> Result<(), Error> { if buffer.len() as u64 > C_MAX || associated_data.len() as u64 > A_MAX { return Err(Error); } // 1. n ← OMAC(0 || Nonce) let n = Self::cmac_with_iv(&self.key, 0, nonce); // 2. h ← OMAC(1 || associated data) let h = Self::cmac_with_iv(&self.key, 1, associated_data); // 4. c ← OMAC(2 || enc) let c = Self::cmac_with_iv(&self.key, 2, buffer); // 5. tag ← n ^ h ^ c // (^ means xor) let expected_tag = n.zip(h, |a, b| a ^ b).zip(c, |a, b| a ^ b); let expected_tag = &expected_tag[..tag.len()]; // Constant-time MAC comparison use subtle::ConstantTimeEq; if expected_tag.ct_eq(tag).into() { // Decrypt Ctr128BE::::inner_iv_init(Cipher::new(&self.key), &n) .apply_keystream_partial(buffer.into()); Ok(()) } else { Err(Error) } } } impl Eax where Cipher: BlockCipher + BlockEncrypt + Clone + KeyInit, M: TagSize, { /// CMAC/OMAC1 /// /// To avoid constructing new buffers on the heap, an iv encoded into 16 /// bytes is prepended inside this function. fn cmac_with_iv( key: &GenericArray, iv: u8, data: &[u8], ) -> Output> { let mut mac = as Mac>::new(key); mac.update(&[0; 15]); mac.update(&[iv]); mac.update(data); mac.finalize().into_bytes() } } eax-0.5.0/src/online.rs000064400000000000000000000376100072674642500130630ustar 00000000000000//! Online[1] variant of the EAX mode. //! //! # Authentication //! Due to *AE* (authenticated encryption) nature of EAX, it is vital to verify //! that both public (also called *associated*) and privacy-protected //! (encrypted) data has not been tampered with. //! //! Because of this, it is required for the consumers to explicitly call //! [`finish`] after the encryption/decryption operation is complete. //! This will either return a *tag* (when encrypting) used to authenticate data //! or a `Result` (when decrypting) that signifies whether the data is authentic, //! which is when the resulting tag is equal to the one created during encryption. //! //! ## Example //! ``` //! use eax::{Error, online::{Eax, Decrypt, Encrypt}, cipher::generic_array::GenericArray}; //! use aes::Aes256; //! //! let key = GenericArray::from_slice(b"an example very very secret key."); //! let nonce = GenericArray::from_slice(b"my unique nonces"); // 128-bits; unique per message //! let assoc = b"my associated data"; //! let plaintext = b"plaintext message"; //! let mut buffer: [u8; 17] = *plaintext; //! //!// Encrypt a simple message //! let mut cipher = Eax::::with_key_and_nonce(key, nonce); //! cipher.update_assoc(&assoc[..]); //! cipher.encrypt(&mut buffer[..9]); //! cipher.encrypt(&mut buffer[9..]); //! let tag = cipher.finish(); //! //! assert_ne!(buffer, *plaintext); //! //! let mut cloned = buffer; //! //! // Now decrypt it, using the same key and nonce //! let mut cipher = Eax::::with_key_and_nonce(key, nonce); //! cipher.update_assoc(&assoc[..]); //! cipher.decrypt_unauthenticated_hazmat(&mut buffer[..5]); //! cipher.decrypt_unauthenticated_hazmat(&mut buffer[5..10]); //! cipher.decrypt_unauthenticated_hazmat(&mut buffer[10..]); //! let res = cipher.finish(&tag); //! //! assert_eq!(res, Ok(())); //! assert_eq!(buffer, *plaintext); //! //! // Decrypting the ciphertext with tampered associated data should fail //! let mut cipher = Eax::::with_key_and_nonce(key, nonce); //! cipher.update_assoc(b"tampered"); //! cipher.decrypt_unauthenticated_hazmat(&mut cloned); //! let res = cipher.finish(&tag); //! //! assert_eq!(res, Err(Error)); //! ``` //! [1]: https://en.wikipedia.org/wiki/Online_algorithm //! [`Eax`]: struct.Eax.html //! [`Decrypt`]: struct.Decrypt.html //! [`finish`]: #method.finish use crate::{Cmac, Error, Nonce, Tag, TagSize}; use aead::consts::U16; use cipher::{ generic_array::functional::FunctionalSequence, BlockCipher, BlockEncrypt, Key, KeyInit, KeyIvInit, StreamCipher, }; use cmac::Mac; use core::marker::PhantomData; pub use Eax as EaxOnline; /// Marker trait denoting whether the EAX stream is used for encryption/decryption. pub trait CipherOp {} /// Marker struct for EAX stream used in encryption mode. pub struct Encrypt; impl CipherOp for Encrypt {} /// Marker struct for EAX stream used in decryption mode. pub struct Decrypt; impl CipherOp for Decrypt {} /// Online[1] variant of the EAX mode. /// /// This type is generic to support substituting alternative cipher /// implementations. /// /// In contrast to [`Eax`], can be used in an online[1] fashion and /// operates in-place. /// /// # Authentication /// Due to *AE* (authenticated encryption) nature of EAX, it is vital to verify /// that both public (also called *associated*) and privacy-protected /// (encrypted) data has not been tampered with. /// /// Because of this, it is required for the consumers to explicitly call /// [`finish`] after the encryption/decryption operation is complete. /// This will either return a *tag* (when encrypting) used to authenticate data /// or a `Result` (when decrypting) that signifies whether the data is authentic, /// which is when the resulting tag is equal to the one created during encryption. /// /// ## Example /// ``` /// use eax::{Error, online::{Eax, Decrypt, Encrypt}, cipher::generic_array::GenericArray}; /// use aes::Aes256; /// /// let key = GenericArray::from_slice(b"an example very very secret key."); /// /// let nonce = GenericArray::from_slice(b"my unique nonces"); // 128-bits; unique per message /// /// let assoc = b"my associated data"; /// let plaintext = b"plaintext message"; /// /// let mut buffer: [u8; 17] = *plaintext; /// /// // Encrypt a simple message /// let mut cipher = Eax::::with_key_and_nonce(key, nonce); /// cipher.update_assoc(&assoc[..]); /// cipher.encrypt(&mut buffer[..9]); /// cipher.encrypt(&mut buffer[9..]); /// let tag = cipher.finish(); /// /// assert_ne!(buffer, *plaintext); /// /// let mut cloned = buffer; /// /// // Now decrypt it, using the same key and nonce /// let mut cipher = Eax::::with_key_and_nonce(key, nonce); /// cipher.update_assoc(&assoc[..]); /// cipher.decrypt_unauthenticated_hazmat(&mut buffer[..5]); /// cipher.decrypt_unauthenticated_hazmat(&mut buffer[5..10]); /// cipher.decrypt_unauthenticated_hazmat(&mut buffer[10..]); /// let res = cipher.finish(&tag); /// /// assert_eq!(res, Ok(())); /// assert_eq!(buffer, *plaintext); /// /// // Decrypting the ciphertext with tampered associated data should fail /// let mut cipher = Eax::::with_key_and_nonce(key, nonce); /// /// cipher.update_assoc(b"tampered"); /// cipher.decrypt_unauthenticated_hazmat(&mut cloned); /// let res = cipher.finish(&tag); /// /// assert_eq!(res, Err(Error)); /// ``` /// /// [1]: https://en.wikipedia.org/wiki/Online_algorithm /// [`Eax`]: ../struct.Eax.html /// [`Decrypt`]: struct.Decrypt.html /// [`finish`]: #method.finish pub struct Eax where Cipher: BlockCipher + BlockEncrypt + Clone + KeyInit, Op: CipherOp, M: TagSize, { imp: EaxImpl, /// Denotes whether this stream is used for encryption or decryption. marker: PhantomData, } impl Eax where Cipher: BlockCipher + BlockEncrypt + Clone + KeyInit, Op: CipherOp, M: TagSize, { /// Creates a stateful EAX instance that is capable of processing both /// the associated data and the plaintext in an "on-line" fashion. pub fn with_key_and_nonce(key: &Key, nonce: &Nonce) -> Self { let imp = EaxImpl::::with_key_and_nonce(key, nonce); Self { imp, marker: PhantomData, } } /// Process the associated data (AD). #[inline] pub fn update_assoc(&mut self, aad: &[u8]) { self.imp.update_assoc(aad); } /// Derives the tag from the encrypted/decrypted message so far. /// /// If the encryption/decryption operation is finished, [`finish`] method /// *must* be called instead. /// ///[`finish`]: #method.finish #[inline] pub fn tag_clone(&self) -> Tag { self.imp.tag_clone() } } impl Eax where Cipher: BlockCipher + BlockEncrypt + Clone + KeyInit, M: TagSize, { /// Applies encryption to the plaintext. #[inline] pub fn encrypt(&mut self, msg: &mut [u8]) { self.imp.encrypt(msg) } /// Finishes the encryption stream, returning the derived tag. /// /// This *must* be called after the stream encryption is finished. #[must_use = "tag must be saved to later verify decrypted data"] #[inline] pub fn finish(self) -> Tag { self.imp.tag() } } impl Eax where Cipher: BlockCipher + BlockEncrypt + Clone + KeyInit, M: TagSize, { /// Applies decryption to the ciphertext **without** verifying the /// authenticity of decrypted message. /// /// To correctly verify the authenticity, use the [`finish`] associated /// function. /// /// # ☣️ BEWARE! ☣️ /// This is a low-level operation that simultaneously decrypts the data and /// calculates an intermediate tag used to verify the authenticity of the /// data (used when the online decryption is finished). /// /// Because this is exposed solely as a building block operation, an extra /// care must be taken when using this function. /// /// Specifically, when misused this may be vulnerable to a chosen-ciphertext /// attack (IND-CCA). Due to online nature of this function, the decryption /// and partial tag calculation is done simultaneously, per chunk. /// An attacker might choose ciphertexts to be decrypted and, while the /// final decryption will fail because the attacker can't calculate tag /// authenticating the message, obtained decryptions may leak information /// about the decryption scheme (e.g. leaking parts of the secret key). /// /// [`finish`]: #method.finish #[inline] pub fn decrypt_unauthenticated_hazmat(&mut self, msg: &mut [u8]) { self.imp.decrypt(msg) } /// Finishes the decryption stream, verifying whether the associated and /// decrypted data stream has not been tampered with. /// /// This *must* be called after the stream decryption is finished. #[must_use = "decrypted data stream must be verified for authenticity"] pub fn finish(self, expected: &Tag) -> Result<(), Error> { self.imp.verify_ct(expected) } } /// Implementation of the raw EAX operations. /// /// Main reason behind extracting the logic to a single, separate type is to /// facilitate testing of the internal logic. #[doc(hidden)] struct EaxImpl where Cipher: BlockCipher + BlockEncrypt + Clone + KeyInit, M: TagSize, { nonce: Nonce, data: Cmac, message: Cmac, ctr: ctr::Ctr128BE, // HACK: Needed for the test harness due to AEAD trait online/offline interface mismatch #[cfg(test)] key: Key, _tag_size: PhantomData, } impl EaxImpl where Cipher: BlockCipher + BlockEncrypt + Clone + KeyInit, M: TagSize, { /// Creates a stateful EAX instance that is capable of processing both /// the associated data and the plaintext in an "on-line" fashion. fn with_key_and_nonce(key: &Key, nonce: &Nonce) -> Self { let prepend_cmac = |key, init_val, data| { let mut cmac = as Mac>::new(key); cmac.update(&[0; 15]); cmac.update(&[init_val]); cmac.update(data); cmac }; // https://crypto.stackexchange.com/questions/26948/eax-cipher-mode-with-nonce-equal-header // has an explanation of eax. // l = block cipher size = 128 (for AES-128) = 16 byte // 1. n ← OMAC(0 || Nonce) // (the 0 means the number zero in l bits) let n = prepend_cmac(key, 0, nonce); let n = n.finalize().into_bytes(); // NOTE: These can be updated online later // 2. h ← OMAC(1 || associated data) let h = prepend_cmac(key, 1, &[]); // 3. c ← OMAC(2 || enc) let c = prepend_cmac(key, 2, &[]); let cipher = ctr::Ctr128BE::::new(key, &n); Self { nonce: n, data: h, message: c, ctr: cipher, #[cfg(test)] key: key.clone(), _tag_size: Default::default(), } } /// Process the associated data (AD). #[inline] pub fn update_assoc(&mut self, aad: &[u8]) { self.data.update(aad); } /// Applies encryption to the plaintext. #[inline] fn encrypt(&mut self, msg: &mut [u8]) { self.ctr.apply_keystream(msg); self.message.update(msg); } /// Applies decryption to the ciphertext. #[inline] fn decrypt(&mut self, msg: &mut [u8]) { self.message.update(msg); self.ctr.apply_keystream(msg); } /// Derives the tag from the encrypted/decrypted message so far. #[inline] fn tag(self) -> Tag { let h = self.data.finalize().into_bytes(); let c = self.message.finalize().into_bytes(); let full_tag = self.nonce.zip(h, |a, b| a ^ b).zip(c, |a, b| a ^ b); Tag::::clone_from_slice(&full_tag[..M::to_usize()]) } /// Derives the tag from the encrypted/decrypted message so far. #[inline] fn tag_clone(&self) -> Tag { let h = self.data.clone().finalize().into_bytes(); let c = self.message.clone().finalize().into_bytes(); let full_tag = self.nonce.zip(h, |a, b| a ^ b).zip(c, |a, b| a ^ b); Tag::::clone_from_slice(&full_tag[..M::to_usize()]) } /// Finishes the decryption stream, verifying whether the associated and /// decrypted data stream has not been tampered with. fn verify_ct(self, expected: &Tag) -> Result<(), Error> { // Check MAC using secure comparison use subtle::ConstantTimeEq; let resulting_tag = &self.tag()[..expected.len()]; if resulting_tag.ct_eq(expected).into() { Ok(()) } else { Err(Error) } } } // Because the current AEAD test harness expects the types to implement both // `KeyInit` and `AeadMutInPlace` traits, do so here so that we can test the // internal logic used by the public interface for the online EAX variant. // These are not publicly implemented in general, because the traits are // designed for offline usage and are somewhat wasteful when used in online mode. #[cfg(test)] mod test_impl { use super::*; use aead::{ consts::U0, generic_array::GenericArray, AeadCore, AeadMutInPlace, KeyInit, KeySizeUser, }; impl KeySizeUser for EaxImpl where Cipher: BlockCipher + BlockEncrypt + Clone + KeyInit, M: TagSize, { type KeySize = Cipher::KeySize; } impl KeyInit for EaxImpl where Cipher: BlockCipher + BlockEncrypt + Clone + KeyInit, M: TagSize, { fn new(key: &Key) -> Self { // HACK: The nonce will be initialized by the appropriate // decrypt/encrypt functions from `AeadMutInPlace` implementation. // This is currently done so because that trait only implements // offline operations and thus need to re-initialize the `EaxImpl` // instance. let nonce = GenericArray::default(); Self::with_key_and_nonce(key, &nonce) } } impl AeadCore for super::EaxImpl where Cipher: BlockCipher + BlockEncrypt + Clone + KeyInit, M: TagSize, { type NonceSize = Cipher::BlockSize; type TagSize = M; type CiphertextOverhead = U0; } impl AeadMutInPlace for super::EaxImpl where Cipher: BlockCipher + BlockEncrypt + Clone + KeyInit, M: TagSize, { fn encrypt_in_place_detached( &mut self, nonce: &Nonce, associated_data: &[u8], buffer: &mut [u8], ) -> Result, Error> { // HACK: Reinitialize the instance *self = Self::with_key_and_nonce(&self.key.clone(), nonce); self.update_assoc(associated_data); self.encrypt(buffer); Ok(self.tag_clone()) } fn decrypt_in_place_detached( &mut self, nonce: &Nonce, associated_data: &[u8], buffer: &mut [u8], expected_tag: &Tag, ) -> Result<(), Error> { // HACK: Reinitialize the instance *self = Self::with_key_and_nonce(&self.key.clone(), nonce); self.update_assoc(associated_data); self.decrypt(buffer); let tag = self.tag_clone(); // Check mac using secure comparison use subtle::ConstantTimeEq; if expected_tag.ct_eq(&tag).into() { Ok(()) } else { Err(Error) } } } } eax-0.5.0/src/traits.rs000064400000000000000000000011470072674642500131010ustar 00000000000000use aead::consts::{U16, U4}; use aead::generic_array::typenum::type_operators::{IsGreaterOrEqual, IsLessOrEqual}; use aead::generic_array::typenum::Unsigned; use aead::generic_array::ArrayLength; mod private { // Sealed traits stop other crates from implementing any traits that use it. pub trait SealedTag {} impl SealedTag for T where T: super::IsGreaterOrEqual + super::IsLessOrEqual { } } pub trait TagSize: ArrayLength + Unsigned + private::SealedTag {} impl TagSize for T where T: ArrayLength + IsGreaterOrEqual + IsLessOrEqual {} eax-0.5.0/tests/aes128eax.rs000064400000000000000000000002600072674642500136420ustar 00000000000000//! Test vectors from Appendix G: //! https://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf use aes::Aes128; use eax::Eax; aead::new_test!(aes128eax, "aes128eax", Eax); eax-0.5.0/tests/common/mod.rs000064400000000000000000000042150072674642500142140ustar 00000000000000//! Common functionality shared by tests /// Test vectors #[derive(Debug)] pub struct TestVector { pub key: &'static K, pub nonce: &'static [u8; 16], pub aad: &'static [u8], pub plaintext: &'static [u8], pub ciphertext: &'static [u8], } #[macro_export] macro_rules! tests { ($aead:ty, $vectors:expr) => { #[test] fn encrypt() { for vector in $vectors { let key = GenericArray::from_slice(vector.key); let nonce = GenericArray::from_slice(vector.nonce); let payload = Payload { msg: vector.plaintext, aad: vector.aad, }; let cipher = <$aead>::new(key); let ciphertext = cipher.encrypt(nonce, payload).unwrap(); assert_eq!(vector.ciphertext, ciphertext); } } #[test] fn decrypt() { for vector in $vectors { let key = GenericArray::from_slice(vector.key); let nonce = GenericArray::from_slice(vector.nonce); let ciphertext = Vec::from(vector.ciphertext); let payload = Payload { msg: &ciphertext, aad: vector.aad, }; let cipher = <$aead>::new(key); let plaintext = cipher.decrypt(nonce, payload).unwrap(); assert_eq!(vector.plaintext, plaintext.as_slice()); } } #[test] fn decrypt_modified() { let vector = &$vectors[0]; let key = GenericArray::from_slice(vector.key); let nonce = GenericArray::from_slice(vector.nonce); let mut ciphertext = Vec::from(vector.ciphertext); // Tweak the first byte ciphertext[0] ^= 0xaa; let payload = Payload { msg: &ciphertext, aad: vector.aad, }; let cipher = <$aead>::new(key); assert!(cipher.decrypt(nonce, payload).is_err()); // TODO(tarcieri): test ciphertext is unmodified in in-place API } }; } eax-0.5.0/tests/data/aes128eax.blb000064400000000000000000000014770072674642500147010ustar 00000000000000 #9R_mox bgäĐ1kO~k 7{Z-e' ]?M ^"U C=1,f޽;HS$\L1 ڰ'tyg J@w =# pO &6]+^#J4c&J GI3*Qպ:Y8>9&f& |˷f' <+F3 H9*c*h"]Ut 5X+EW fv\aBvn)p @},uw6:jND nG^`hxL8/" n\-P^FH-M\?9$[}8[]t>5rdO̸iG! O |wլGz.} =89;+Vey%(" y0l6B>9yH&00s'In _ /5I[ 囗"mM+U&TNj $+Ί}+-VD.{,ITǺHͮ;`Ec** x+>m4a# _ޗH"XV~$lg +걨D8D zs98#/_ [֗ f "їRҕj%;FR7$n