aes-siv-0.7.0/.cargo_vcs_info.json0000644000000001450000000000100124070ustar { "git": { "sha1": "15cf3b247290676a19d1b7f6cc24b1bf924a2caf" }, "path_in_vcs": "aes-siv" }aes-siv-0.7.0/CHANGELOG.md000064400000000000000000000054540072674642500130500ustar 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.7.0 (2022-07-30) ### Added - `getrandom` feature ([#446]) ### Changed - Relax `zeroize` requirement to `^1` ([#360], [#401]) - Bump `aes` crate to v0.8 ([#431]) - Rust 2021 edition upgrade; MSRV 1.56+ ([#435]) - Bump `aead` crate dependency to v0.5 ([#444]) [#360]: https://github.com/RustCrypto/AEADs/pull/360 [#401]: https://github.com/RustCrypto/AEADs/pull/401 [#431]: https://github.com/RustCrypto/AEADs/pull/431 [#435]: https://github.com/RustCrypto/AEADs/pull/435 [#444]: https://github.com/RustCrypto/AEADs/pull/444 [#446]: https://github.com/RustCrypto/AEADs/pull/446 ## 0.6.2 (2021-07-20) ### Changed - Pin `zeroize` dependency to v1.3 ([#349]) [#349]: https://github.com/RustCrypto/AEADs/pull/349 ## 0.6.1 (2021-06-26) ### Fixed - `pmac` crate feature ([#321]) [#321]: https://github.com/RustCrypto/AEADs/pull/321 ## 0.6.0 (2021-04-29) ### Added - AES-SIV-CMAC Wycheproof test vectors ([#276]) ### 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]) [#270]: https://github.com/RustCrypto/AEADs/pull/270 [#276]: https://github.com/RustCrypto/AEADs/pull/276 [#283]: https://github.com/RustCrypto/AEADs/pull/283 [#285]: https://github.com/RustCrypto/AEADs/pull/285 ## 0.5.0 (2020-10-16) ### Changed - Replace `block-cipher`/`stream-cipher` with `cipher` crate ([#229]) - Bump `aes` dependency to v0.6 ([#229]) [#229]: https://github.com/RustCrypto/AEADs/pull/229 ## 0.4.0 (2020-09-17) ### Added - Optional `std` feature; disabled by default ([#217]) ### Changed - Upgrade `aes` to v0.5; `block-cipher` to v0.8 ([#209]) [#217]: https://github.com/RustCrypto/AEADs/pull/217 [#209]: https://github.com/RustCrypto/AEADs/pull/209 ## 0.3.0 (2019-06-06) ### Changed - Bump `aead` crate dependency to v0.3.0; MSRV 1.41+ ([#143]) - Use `copy_within` ([#57]) [#143]: https://github.com/RustCrypto/AEADs/pull/143 [#57]: https://github.com/RustCrypto/AEADs/pull/57 ## 0.2.0 (2019-11-26) ### Added - `heapless` feature ([#51]) ### Changed - Switch from `AeadMut` to `Aead` ([#47]) - Make `Siv::new` type-safe via `typenum` arithmetic ([#45]) - Upgrade `aead` crate to v0.2; `alloc` now optional ([#44]) [#51]: https://github.com/RustCrypto/AEADs/pull/51 [#47]: https://github.com/RustCrypto/AEADs/pull/47 [#45]: https://github.com/RustCrypto/AEADs/pull/45 [#44]: https://github.com/RustCrypto/AEADs/pull/44 ## 0.1.2 (2019-11-14) ### Changed - Upgrade to `zeroize` 1.0 ([#36]) [#36]: https://github.com/RustCrypto/AEADs/pull/36 ## 0.1.1 (2019-10-06) - Initial release aes-siv-0.7.0/Cargo.toml0000644000000034250000000000100104110ustar # 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 = "aes-siv" version = "0.7.0" authors = ["RustCrypto Developers"] description = """ Pure Rust implementation of the AES-SIV Misuse-Resistant Authenticated Encryption Cipher (RFC 5297) with optional architecture-specific hardware acceleration """ documentation = "https://docs.rs/aes-siv" readme = "README.md" keywords = [ "aead", "aes", "encryption", "siv", ] 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" [dependencies.aes] version = "0.8" [dependencies.cipher] version = "0.4" [dependencies.cmac] version = "0.7" [dependencies.ctr] version = "0.9" [dependencies.dbl] version = "0.3" [dependencies.digest] version = "0.10" features = ["mac"] [dependencies.pmac] version = "0.7" optional = true [dependencies.zeroize] version = "1" default-features = false [dev-dependencies.blobby] version = "0.3" [dev-dependencies.hex-literal] version = "0.3" [features] alloc = ["aead/alloc"] default = [ "alloc", "getrandom", ] getrandom = ["aead/getrandom"] heapless = ["aead/heapless"] std = [ "aead/std", "alloc", ] stream = ["aead/stream"] aes-siv-0.7.0/Cargo.toml.orig000064400000000000000000000021360072674642500141200ustar 00000000000000[package] name = "aes-siv" version = "0.7.0" description = """ Pure Rust implementation of the AES-SIV Misuse-Resistant Authenticated Encryption Cipher (RFC 5297) with optional architecture-specific hardware acceleration """ authors = ["RustCrypto Developers"] edition = "2021" license = "Apache-2.0 OR MIT" readme = "README.md" documentation = "https://docs.rs/aes-siv" repository = "https://github.com/RustCrypto/AEADs" keywords = ["aead", "aes", "encryption", "siv"] categories = ["cryptography", "no-std"] rust-version = "1.56" [dependencies] aead = "0.5" aes = "0.8" cipher = "0.4" cmac = "0.7" ctr = "0.9" dbl = "0.3" digest = { version = "0.10", features = ["mac"] } zeroize = { version = "1", default-features = false } # optional dependencies pmac = { version = "0.7", optional = true } [dev-dependencies] blobby = "0.3" hex-literal = "0.3" [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"] aes-siv-0.7.0/LICENSE-APACHE000064400000000000000000000251410072674642500131560ustar 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. aes-siv-0.7.0/LICENSE-MIT000064400000000000000000000020650072674642500126660ustar 00000000000000Copyright (c) 2019 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. aes-siv-0.7.0/README.md000064400000000000000000000044510072674642500125120ustar 00000000000000# RustCrypto: AES-SIV (Misuse-Resistant Authenticated Encryption Cipher) [![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] [AES-SIV][1] ([RFC 5297][2]) is an [Authenticated Encryption with Associated Data (AEAD)][3] cipher which also provides [nonce reuse misuse resistance][4]. [Documentation][docs-link] ## Security Warning No security audits of this crate have ever been performed, and it has not been thoroughly assessed to ensure its operation is constant-time on common CPU architectures. USE AT YOUR OWN RISK! ## License Licensed under either of: * [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) * [MIT license](http://decryptsource.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/aes-siv.svg [crate-link]: https://crates.io/crates/aes-siv [docs-image]: https://docs.rs/aes-siv/badge.svg [docs-link]: https://docs.rs/aes-siv/ [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/aes-siv/badge.svg?branch=master&event=push [build-link]: https://github.com/RustCrypto/AEADs/actions [//]: # (general links) [1]: https://github.com/miscreant/meta/wiki/AES-SIV [2]: https://tools.ietf.org/html/rfc5297 [3]: https://en.wikipedia.org/wiki/Authenticated_encryption [4]: https://github.com/miscreant/meta/wiki/Nonce-Reuse-Misuse-Resistance [5]: https://www.imperialviolet.org/2017/05/14/aesgcmsiv.html [6]: https://codahale.com/towards-a-safer-footgun/ aes-siv-0.7.0/src/lib.rs000064400000000000000000000214170072674642500131370ustar 00000000000000//! [AES-SIV][1] ([RFC 5297][2]): //! [Authenticated Encryption with Associated Data (AEAD)][3] cipher which also //! provides [nonce reuse misuse resistance][4]. //! //! # 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_siv::{ //! aead::{Aead, KeyInit, OsRng}, //! Aes256SivAead, Nonce // Or `Aes128SivAead` //! }; //! //! let key = Aes256SivAead::generate_key(&mut OsRng); //! let cipher = Aes256SivAead::new(&key); //! let nonce = Nonce::from_slice(b"any unique nonce"); // 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_attr( all(feature = "getrandom", feature = "heapless", feature = "std"), doc = "```" )] #![cfg_attr( not(all(feature = "getrandom", feature = "heapless", feature = "std")), doc = "```ignore" )] //! # fn main() -> Result<(), Box> { //! use aes_siv::{ //! aead::{AeadInPlace, KeyInit, OsRng, heapless::Vec}, //! Aes256SivAead, Nonce, // Or `Aes128SivAead` //! }; //! //! let key = Aes256SivAead::generate_key(&mut OsRng); //! let cipher = Aes256SivAead::new(&key); //! let nonce = Nonce::from_slice(b"any unique nonce"); // 128-bits; unique per message //! //! let mut buffer: Vec = Vec::new(); // Note: buffer needs 16-bytes overhead for auth tag tag //! 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)?; //! //! // `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)?; //! assert_eq!(&buffer, b"plaintext message"); //! # Ok(()) //! # } //! ``` //! //! [1]: https://github.com/miscreant/meta/wiki/AES-SIV //! [2]: https://tools.ietf.org/html/rfc5297 //! [3]: https://en.wikipedia.org/wiki/Authenticated_encryption //! [4]: https://github.com/miscreant/meta/wiki/Nonce-Reuse-Misuse-Resistance #![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" )] #![warn(missing_docs, rust_2018_idioms, unused_qualifications)] #[cfg(feature = "alloc")] extern crate alloc; pub mod siv; pub use aead::{self, AeadCore, AeadInPlace, Error, Key, KeyInit, KeySizeUser}; use crate::siv::Siv; use aead::{ consts::{U0, U16, U32, U64}, generic_array::GenericArray, Buffer, }; use aes::{Aes128, Aes256}; use cipher::{BlockCipher, BlockEncryptMut}; use cmac::Cmac; use core::{marker::PhantomData, ops::Add}; use digest::{FixedOutputReset, Mac}; #[cfg(feature = "pmac")] use pmac::Pmac; /// AES-SIV nonces pub type Nonce = GenericArray; /// AES-SIV tags (i.e. the Synthetic Initialization Vector value) pub type Tag = GenericArray; /// The `SivAead` type wraps the more powerful `Siv` interface in a more /// commonly used Authenticated Encryption with Associated Data (AEAD) API, /// which accepts a key, nonce, and associated data when encrypting/decrypting. pub struct SivAead where Self: KeySizeUser, C: BlockCipher + BlockEncryptMut + KeyInit + KeySizeUser, M: Mac + FixedOutputReset + KeyInit, ::KeySize: Add, { key: GenericArray::KeySize>, mac: PhantomData, // TODO(tarcieri): include `M` in `KeySize` calculation } /// SIV AEAD modes based on CMAC pub type CmacSivAead = SivAead>; /// SIV AEAD modes based on PMAC #[cfg(feature = "pmac")] #[cfg_attr(docsrs, doc(cfg(feature = "pmac")))] pub type PmacSivAead = SivAead>; /// AES-CMAC-SIV in AEAD mode with 256-bit key size (128-bit security) pub type Aes128SivAead = CmacSivAead; /// AES-CMAC-SIV in AEAD mode with 512-bit key size (256-bit security) pub type Aes256SivAead = CmacSivAead; /// AES-PMAC-SIV in AEAD mode with 256-bit key size (128-bit security) #[cfg(feature = "pmac")] #[cfg_attr(docsrs, doc(cfg(feature = "pmac")))] pub type Aes128PmacSivAead = PmacSivAead; /// AES-PMAC-SIV in AEAD mode with 512-bit key size (256-bit security) #[cfg(feature = "pmac")] #[cfg_attr(docsrs, doc(cfg(feature = "pmac")))] pub type Aes256PmacSivAead = PmacSivAead; impl KeySizeUser for SivAead where M: Mac + FixedOutputReset + KeyInit, { type KeySize = U32; } impl KeySizeUser for SivAead where M: Mac + FixedOutputReset + KeyInit, { type KeySize = U64; } impl KeyInit for SivAead where M: Mac + FixedOutputReset + KeyInit, { fn new(key: &GenericArray) -> Self { Self { key: *key, mac: PhantomData, } } } impl KeyInit for SivAead where M: Mac + FixedOutputReset + KeyInit, { fn new(key: &GenericArray) -> Self { Self { key: *key, mac: PhantomData, } } } impl AeadCore for SivAead where Self: KeySizeUser, C: BlockCipher + BlockEncryptMut + KeyInit + KeySizeUser, M: Mac + FixedOutputReset + KeyInit, ::KeySize: Add, { // "If the nonce is random, it SHOULD be at least 128 bits in length" // https://tools.ietf.org/html/rfc5297#section-3 // TODO(tarcieri): generic nonce sizes type NonceSize = U16; type TagSize = U16; type CiphertextOverhead = U0; } impl AeadInPlace for SivAead where Self: KeySizeUser, Siv: KeyInit + KeySizeUser::KeySize>, C: BlockCipher + BlockEncryptMut + KeyInit + KeySizeUser, M: Mac + FixedOutputReset + KeyInit, ::KeySize: Add, { fn encrypt_in_place( &self, nonce: &GenericArray, associated_data: &[u8], buffer: &mut dyn Buffer, ) -> Result<(), Error> { // "SIV performs nonce-based authenticated encryption when a component of // the associated data is a nonce. For purposes of interoperability the // final component -- i.e., the string immediately preceding the // plaintext in the vector input to S2V -- is used for the nonce." // https://tools.ietf.org/html/rfc5297#section-3 Siv::::new(&self.key).encrypt_in_place(&[associated_data, nonce.as_slice()], buffer) } fn encrypt_in_place_detached( &self, nonce: &GenericArray, associated_data: &[u8], buffer: &mut [u8], ) -> Result, Error> { Siv::::new(&self.key) .encrypt_in_place_detached(&[associated_data, nonce.as_slice()], buffer) } fn decrypt_in_place( &self, nonce: &GenericArray, associated_data: &[u8], buffer: &mut dyn Buffer, ) -> Result<(), Error> { Siv::::new(&self.key).decrypt_in_place(&[associated_data, nonce.as_slice()], buffer) } fn decrypt_in_place_detached( &self, nonce: &GenericArray, associated_data: &[u8], buffer: &mut [u8], tag: &GenericArray, ) -> Result<(), Error> { Siv::::new(&self.key).decrypt_in_place_detached( &[associated_data, nonce.as_slice()], buffer, tag, ) } } aes-siv-0.7.0/src/siv.rs000064400000000000000000000243050072674642500131710ustar 00000000000000//! The Synthetic Initialization Vector (SIV) misuse-resistant block cipher //! mode of operation ([RFC 5297][1]). //! //! [1]: https://tools.ietf.org/html/rfc5297 use crate::Tag; use aead::{ generic_array::{ typenum::{Unsigned, U16}, ArrayLength, GenericArray, }, Buffer, Error, }; use aes::{Aes128, Aes256}; use cipher::{ BlockCipher, BlockEncryptMut, InnerIvInit, Key, KeyInit, KeySizeUser, StreamCipherCore, }; use cmac::Cmac; use core::ops::Add; use dbl::Dbl; use digest::{CtOutput, FixedOutputReset, Mac}; use zeroize::Zeroize; #[cfg(feature = "alloc")] use alloc::vec::Vec; #[cfg(feature = "pmac")] use pmac::Pmac; /// Size of the (synthetic) initialization vector in bytes pub const IV_SIZE: usize = 16; /// Maximum number of header items on the encrypted message pub const MAX_HEADERS: usize = 126; /// Counter mode with a 128-bit big endian counter. type Ctr128BE = ctr::CtrCore; /// Size of an AES-SIV key given a particular cipher pub type KeySize = <::KeySize as Add>::Output; /// Synthetic Initialization Vector (SIV) mode, providing misuse-resistant /// authenticated encryption (MRAE). pub struct Siv where C: BlockCipher + BlockEncryptMut + KeyInit + KeySizeUser, M: Mac, { encryption_key: Key, mac: M, } /// SIV modes based on CMAC pub type CmacSiv = Siv>; /// SIV modes based on PMAC #[cfg(feature = "pmac")] #[cfg_attr(docsrs, doc(cfg(feature = "pmac")))] pub type PmacSiv = Siv>; /// AES-CMAC-SIV with a 128-bit key pub type Aes128Siv = CmacSiv; /// AES-CMAC-SIV with a 256-bit key pub type Aes256Siv = CmacSiv; /// AES-PMAC-SIV with a 128-bit key #[cfg(feature = "pmac")] #[cfg_attr(docsrs, doc(cfg(feature = "pmac")))] pub type Aes128PmacSiv = PmacSiv; /// AES-PMAC-SIV with a 256-bit key #[cfg(feature = "pmac")] #[cfg_attr(docsrs, doc(cfg(feature = "pmac")))] pub type Aes256PmacSiv = PmacSiv; impl KeySizeUser for Siv where C: BlockCipher + BlockEncryptMut + KeyInit + KeySizeUser, M: Mac + FixedOutputReset + KeyInit, ::KeySize: Add, KeySize: ArrayLength, { type KeySize = KeySize; } impl KeyInit for Siv where C: BlockCipher + BlockEncryptMut + KeyInit + KeySizeUser, M: Mac + FixedOutputReset + KeyInit, ::KeySize: Add, KeySize: ArrayLength, { /// Create a new AES-SIV instance fn new(key: &GenericArray>) -> Self { // Use the first half of the key as the encryption key let encryption_key = GenericArray::clone_from_slice(&key[M::key_size()..]); // Use the second half of the key as the MAC key let mac = ::new(GenericArray::from_slice(&key[..M::KeySize::to_usize()])); Self { encryption_key, mac, } } } impl Siv where C: BlockCipher + BlockEncryptMut + KeyInit + KeySizeUser, M: Mac + FixedOutputReset + KeyInit, { /// Encrypt the given plaintext, allocating and returning a `Vec` for /// the ciphertext. /// /// # Errors /// /// Returns [`Error`] if `plaintext.len()` is less than `M::OutputSize`. /// Returns [`Error`] if `headers.len()` is greater than [`MAX_HEADERS`]. #[cfg(feature = "alloc")] pub fn encrypt(&mut self, headers: I, plaintext: &[u8]) -> Result, Error> where I: IntoIterator, T: AsRef<[u8]>, { let mut buffer = Vec::with_capacity(plaintext.len() + IV_SIZE); buffer.extend_from_slice(plaintext); self.encrypt_in_place(headers, &mut buffer)?; Ok(buffer) } /// Encrypt the given buffer containing a plaintext message in-place. /// /// # Errors /// /// Returns [`Error`] if `plaintext.len()` is less than `M::OutputSize`. /// Returns [`Error`] if `headers.len()` is greater than [`MAX_HEADERS`]. pub fn encrypt_in_place( &mut self, headers: I, buffer: &mut dyn Buffer, ) -> Result<(), Error> where I: IntoIterator, T: AsRef<[u8]>, { let pt_len = buffer.len(); // Make room in the buffer for the SIV tag. It needs to be prepended. buffer.extend_from_slice(Tag::default().as_slice())?; // TODO(tarcieri): add offset param to `encrypt_in_place_detached` buffer.as_mut().copy_within(..pt_len, IV_SIZE); let tag = self.encrypt_in_place_detached(headers, &mut buffer.as_mut()[IV_SIZE..])?; buffer.as_mut()[..IV_SIZE].copy_from_slice(tag.as_slice()); Ok(()) } /// Encrypt the given plaintext in-place, returning the SIV tag on success. /// /// # Errors /// /// Returns [`Error`] if `plaintext.len()` is less than `M::OutputSize`. /// Returns [`Error`] if `headers.len()` is greater than [`MAX_HEADERS`]. pub fn encrypt_in_place_detached( &mut self, headers: I, plaintext: &mut [u8], ) -> Result where I: IntoIterator, T: AsRef<[u8]>, { // Compute the synthetic IV for this plaintext let siv_tag = s2v(&mut self.mac, headers, plaintext)?; self.xor_with_keystream(siv_tag, plaintext); Ok(siv_tag) } /// Decrypt the given ciphertext, allocating and returning a Vec for the plaintext #[cfg(feature = "alloc")] pub fn decrypt(&mut self, headers: I, ciphertext: &[u8]) -> Result, Error> where I: IntoIterator, T: AsRef<[u8]>, { let mut buffer = ciphertext.to_vec(); self.decrypt_in_place(headers, &mut buffer)?; Ok(buffer) } /// 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. pub fn decrypt_in_place( &mut self, headers: I, buffer: &mut dyn Buffer, ) -> Result<(), Error> where I: IntoIterator, T: AsRef<[u8]>, { if buffer.len() < IV_SIZE { return Err(Error); } let siv_tag = Tag::clone_from_slice(&buffer.as_ref()[..IV_SIZE]); self.decrypt_in_place_detached(headers, &mut buffer.as_mut()[IV_SIZE..], &siv_tag)?; let pt_len = buffer.len() - IV_SIZE; // TODO(tarcieri): add offset param to `encrypt_in_place_detached` buffer.as_mut().copy_within(IV_SIZE.., 0); buffer.truncate(pt_len); Ok(()) } /// Decrypt the given ciphertext in-place, authenticating it against the /// provided SIV tag. /// /// # Errors /// /// Returns [`Error`] if the ciphertext is not authentic pub fn decrypt_in_place_detached( &mut self, headers: I, ciphertext: &mut [u8], siv_tag: &Tag, ) -> Result<(), Error> where I: IntoIterator, T: AsRef<[u8]>, { self.xor_with_keystream(*siv_tag, ciphertext); let computed_siv_tag = s2v(&mut self.mac, headers, ciphertext)?; // Note: `CtOutput` provides constant-time equality if CtOutput::::new(computed_siv_tag) == CtOutput::new(*siv_tag) { Ok(()) } else { // Re-encrypt the decrypted plaintext to avoid revealing it self.xor_with_keystream(*siv_tag, ciphertext); Err(Error) } } /// XOR the given buffer with the keystream for the given IV fn xor_with_keystream(&mut self, mut iv: Tag, msg: &mut [u8]) { // "We zero-out the top bit in each of the last two 32-bit words // of the IV before assigning it to Ctr" // — http://web.cs.ucdavis.edu/~rogaway/papers/siv.pdf iv[8] &= 0x7f; iv[12] &= 0x7f; Ctr128BE::::inner_iv_init(C::new(&self.encryption_key), &iv) .apply_keystream_partial(msg.into()); } } impl Drop for Siv where C: BlockCipher + BlockEncryptMut + KeyInit + KeySizeUser, M: Mac, { fn drop(&mut self) { self.encryption_key.zeroize() } } /// "S2V" is a vectorized pseudorandom function (sometimes referred to as a /// vector MAC or "vMAC") which performs a "dbl"-and-xor operation on the /// outputs of a pseudo-random function (CMAC or PMAC). /// /// In the RFC 5297 SIV construction (see Section 2.4), message headers /// (e.g. nonce, associated data) and the plaintext are used as inputs to /// S2V, together with a message authentication key. The output is the /// eponymous "synthetic IV" (SIV), which has a dual role as both /// initialization vector (for AES-CTR encryption) and MAC. fn s2v(mac: &mut M, headers: I, message: &[u8]) -> Result where M: Mac + FixedOutputReset, I: IntoIterator, T: AsRef<[u8]>, { Mac::update(mac, &Tag::default()); let mut state = mac.finalize_reset().into_bytes(); for (i, header) in headers.into_iter().enumerate() { if i >= MAX_HEADERS { return Err(Error); } state = state.dbl(); Mac::update(mac, header.as_ref()); let code = mac.finalize_reset().into_bytes(); xor_in_place(&mut state, &code); } if message.len() >= IV_SIZE { let n = message.len().checked_sub(IV_SIZE).unwrap(); Mac::update(mac, &message[..n]); xor_in_place(&mut state, &message[n..]); } else { state = state.dbl(); xor_in_place(&mut state, message); state[message.len()] ^= 0x80; }; Mac::update(mac, state.as_ref()); Ok(mac.finalize_reset().into_bytes()) } /// XOR the second argument into the first in-place. Slices do not have to be /// aligned in memory. /// /// Panics if the destination slice is smaller than the source. #[inline] fn xor_in_place(dst: &mut [u8], src: &[u8]) { for (a, b) in dst[..src.len()].iter_mut().zip(src) { *a ^= *b; } } aes-siv-0.7.0/tests/aead.rs000064400000000000000000000123070072674642500136340ustar 00000000000000#[macro_use] extern crate hex_literal; /// 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_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.as_slice()); } } #[test] fn encrypt_in_place_detached() { for vector in $vectors { let key = GenericArray::from_slice(vector.key); let nonce = GenericArray::from_slice(vector.nonce); let mut buffer = vector.plaintext.to_vec(); let cipher = <$aead>::new(key); let tag = cipher .encrypt_in_place_detached(nonce, vector.aad, &mut buffer) .unwrap(); let (expected_tag, expected_ciphertext) = vector.ciphertext.split_at(16); assert_eq!(expected_tag, &tag[..]); assert_eq!(expected_ciphertext, &buffer[..]); } } #[test] fn decrypt() { for vector in $vectors { let key = GenericArray::from_slice(vector.key); let nonce = GenericArray::from_slice(vector.nonce); let payload = Payload { msg: vector.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_in_place_detached() { for vector in $vectors { let key = GenericArray::from_slice(vector.key); let nonce = GenericArray::from_slice(vector.nonce); let tag = GenericArray::clone_from_slice(&vector.ciphertext[..16]); let mut buffer = vector.ciphertext[16..].to_vec(); <$aead>::new(key) .decrypt_in_place_detached(nonce, vector.aad, &mut buffer, &tag) .unwrap(); assert_eq!(vector.plaintext, buffer.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 } }; } mod aes128cmacsivaead { use super::TestVector; use aes_siv::aead::{generic_array::GenericArray, Aead, AeadInPlace, KeyInit, Payload}; use aes_siv::Aes128SivAead; /// AES-128-CMAC-SIV test vectors const TEST_VECTORS: &[TestVector<[u8; 32]>] = &[ TestVector { key: &hex!("7f7e7d7c7b7a79787776757473727170404142434445464748494a4b4c4d4e4f"), nonce: &hex!("09f911029d74e35bd84156c5635688c0"), aad: &hex!("00112233445566778899aabbccddeeffdeaddadadeaddadaffeeddccbbaa99887766554433221100"), plaintext: &hex!("7468697320697320736f6d6520706c61696e7465787420746f20656e6372797074207573696e67205349562d414553"), ciphertext: &hex!("85825e22e90cf2ddda2c548dc7c1b6310dcdaca0cebf9dc6cb90583f5bf1506e02cd48832b00e4e598b2b22a53e6199d4df0c1666a35a0433b250dc134d776"), }, ]; tests!(Aes128SivAead, TEST_VECTORS); } #[cfg(feature = "pmac")] mod aes128pmacsivaead { use super::TestVector; use aes_siv::aead::{generic_array::GenericArray, Aead, AeadInPlace, KeyInit, Payload}; use aes_siv::Aes128PmacSivAead; /// AES-128-PMAC-SIV test vectors const AES_128_PMAC_SIV_TEST_VECTORS: &[TestVector<[u8; 32]>] = &[ TestVector { key: &hex!("7f7e7d7c7b7a79787776757473727170404142434445464748494a4b4c4d4e4f"), nonce: &hex!("09f911029d74e35bd84156c5635688c0"), aad: &hex!("00112233445566778899aabbccddeeffdeaddadadeaddadaffeeddccbbaa99887766554433221100"), plaintext: &hex!("7468697320697320736f6d6520706c61696e7465787420746f20656e6372797074207573696e67205349562d414553"), ciphertext: &hex!("1463d1119b2a2797241bb1674633dff13b9de11e5e2f526048b36c40c7722667b2957018023bf0e52792b703a01e88aacd49898cecfce943d7f61a2337a097"), }, ]; tests!(Aes128PmacSivAead, AES_128_PMAC_SIV_TEST_VECTORS); } aes-siv-0.7.0/tests/data/wycheproof-256.blb000064400000000000000000000154140072674642500164670ustar 00000000000000  0123456789:;<=>?@ABC0123456789:;<=>?01234567 @0 !"#$%&'"3DUfwh½ia[ )zC(US?+d._ RٚfA5(@"\9@v l>yU]OZwy@mͳgm` =Ů O0ˈCNnp R͗ `;egM@a.xCήaԖ%IOS ΦQ+96 ]9^0 E 7_tZ/@ȱ@ǜu ʌkʡŏ`qw[Y $@o3V <!"i ^+? d@~Mj&|neO($s[[`'Od݀HFYA1'v謕D!2iDA@d7>h.<&Tu 2(O| ڳ :cΉ{ 1`9G:<aV֐b6j ޏr=طWfvZw.0 rLV Q UqX(zKl_Ѯ 1`.@)b3Z^b{N"BB<߰aVcL7_\\mUI"\}|aـ[@x1VPzkmqf,CWS;SBMYaI\ק| $|rXl$q|@ ="#"ߟ:Z9 yX"ElapS/\S&܉am@ .դ&g 佉EqGMic4Ǜ&,{dAqx(͂Go3cb)7 &@͏>|RPmFI&c o>r餰.?p V{*(4_'``He@N7=mf#kocJOV1̫G7 _<ܙKp ԛw,n'{]Zy@V]A:{|[Z/?Y&4R&BcRHL;.9&^˽l՗g}G@.LxYfOl߀fmǠ 2> < xA%q[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$y=H1\mk6(Aa]eZaes-siv-0.7.0/tests/siv.rs000064400000000000000000000267120072674642500135500ustar 00000000000000//! AES-SIV tests for the raw SIV interface use aes_siv::aead::generic_array::GenericArray; /// Test vectors #[derive(Debug)] pub struct TestVector { pub key: &'static K, pub aad: &'static [&'static [u8]], pub plaintext: &'static [u8], pub ciphertext: &'static [u8], } macro_rules! tests { ($siv:ty, $vectors:expr) => { #[test] fn encrypt() { for vector in $vectors { let mut cipher = <$siv>::new(GenericArray::from_slice(vector.key)); let ciphertext = cipher.encrypt(vector.aad, vector.plaintext).unwrap(); assert_eq!(vector.ciphertext, ciphertext.as_slice()); } } #[test] fn decrypt() { for vector in $vectors { let mut cipher = <$siv>::new(GenericArray::from_slice(vector.key)); let plaintext = cipher.decrypt(vector.aad, vector.ciphertext).unwrap(); assert_eq!(vector.plaintext, plaintext.as_slice()); } } #[test] fn decrypt_modified() { let vector = &$vectors[0]; let mut ciphertext = Vec::from(vector.ciphertext); // Tweak the first byte ciphertext[0] ^= 0xaa; let mut cipher = <$siv>::new(GenericArray::from_slice(vector.key)); assert!(cipher.decrypt(vector.aad, &ciphertext).is_err()); // TODO(tarcieri): test ciphertext is unmodified in in-place API } }; } macro_rules! wycheproof_tests { ($siv:ty, $name:ident, $test_name:expr) => { #[test] fn $name() { use blobby::Blob5Iterator; let data = include_bytes!(concat!("data/", $test_name, ".blb")); fn run_test( key: &[u8], aad: &[u8], pt: &[u8], ct: &[u8], pass: bool, ) -> Option<&'static str> { let mut cipher = <$siv>::new(GenericArray::from_slice(key)); let ciphertext = cipher.encrypt(&[aad], pt).unwrap(); if pass && ct != ciphertext.as_slice() { return Some("encryption mismatch"); } if !pass && ct == ciphertext.as_slice() { return Some("unexpected encryption match"); } match cipher.decrypt(&[aad], ct) { Ok(_plaintext) if !pass => Some("unexpected decryption success"), Ok(plaintext) => { if pt == plaintext.as_slice() { None } else { Some("decryption mismatch") } } Err(_) if pass => Some("decryption failure"), Err(_) => None, } } for (i, row) in Blob5Iterator::new(data).unwrap().enumerate() { let [key, aad, pt, ct, status] = row.unwrap(); let pass = match status[0] { 0 => false, 1 => true, _ => panic!("invalid value for pass flag"), }; if let Some(desc) = run_test(key, aad, pt, ct, pass) { panic!( "\n\ Failed test №{}: {}\n\ key:\t{:?}\n\ aad:\t{:?}\n\ pt:\t{:?}\n\ ct:\t{:?}\n\ pass:\t{:?}\n", i, desc, key, aad, pt, ct, pass, ); } } } }; } mod aes128cmacsiv { use super::{GenericArray, TestVector}; use aes_siv::{siv::Aes128Siv, KeyInit}; use hex_literal::hex; /// AES-128-CMAC-SIV test vectors const TEST_VECTORS: &[TestVector<[u8; 32]>] = &[ TestVector { key: &hex!("fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"), aad: &[&hex!("101112131415161718191a1b1c1d1e1f2021222324252627")], plaintext: &hex!("112233445566778899aabbccddee"), ciphertext: &hex!("85632d07c6e8f37f950acd320a2ecc9340c02b9690c4dc04daef7f6afe5c") }, TestVector { key: &hex!("7f7e7d7c7b7a79787776757473727170404142434445464748494a4b4c4d4e4f"), aad: &[ &hex!("00112233445566778899aabbccddeeffdeaddadadeaddadaffeeddccbbaa99887766554433221100"), &hex!("102030405060708090a0"), &hex!("09f911029d74e35bd84156c5635688c0") ], plaintext: &hex!("7468697320697320736f6d6520706c61696e7465787420746f20656e6372797074207573696e67205349562d414553"), ciphertext: &hex!("7bdb6e3b432667eb06f4d14bff2fbd0fcb900f2fddbe404326601965c889bf17dba77ceb094fa663b7a3f748ba8af829ea64ad544a272e9c485b62a3fd5c0d") }, TestVector { key: &hex!("fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"), aad: &[], plaintext: b"", ciphertext: &hex!("f2007a5beb2b8900c588a7adf599f172") }, TestVector { key: &hex!("fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"), aad: &[], plaintext: &hex!("00112233445566778899aabbccddeeff"), ciphertext: &hex!("f304f912863e303d5b540e5057c7010c942ffaf45b0e5ca5fb9a56a5263bb065") } ]; tests!(Aes128Siv, TEST_VECTORS); wycheproof_tests!(Aes128Siv, wycheproof, "wycheproof-256"); } mod aes256cmacsiv { use super::{GenericArray, TestVector}; use aes_siv::{siv::Aes256Siv, KeyInit}; use hex_literal::hex; /// AES-256-CMAC-SIV test vectors const TEST_VECTORS: &[TestVector<[u8; 64]>] = &[ TestVector { key: &hex!("fffefdfcfbfaf9f8f7f6f5f4f3f2f1f06f6e6d6c6b6a69686766656463626160f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff000102030405060708090a0b0c0d0e0f"), aad: &[&hex!("101112131415161718191a1b1c1d1e1f2021222324252627")], plaintext:&hex!("112233445566778899aabbccddee"), ciphertext:&hex!("f125274c598065cfc26b0e71575029088b035217e380cac8919ee800c126") }, TestVector { key:&hex!("7f7e7d7c7b7a797877767574737271706f6e6d6c6b6a69686766656463626160404142434445464748494a4b4c4d4e4f505152535455565758595a5b5b5d5e5f"), aad: &[ &hex!("00112233445566778899aabbccddeeffdeaddadadeaddadaffeeddccbbaa99887766554433221100"), &hex!("102030405060708090a0"), &hex!("09f911029d74e35bd84156c5635688c0") ], plaintext: &hex!("7468697320697320736f6d6520706c61696e7465787420746f20656e6372797074207573696e67205349562d414553"), ciphertext: &hex!("85b8167310038db7dc4692c0281ca35868181b2762f3c24f2efa5fb80cb143516ce6c434b898a6fd8eb98a418842f51f66fc67de43ac185a66dd72475bbb08") }, ]; tests!(Aes256Siv, TEST_VECTORS); wycheproof_tests!(Aes256Siv, wycheproof, "wycheproof-512"); } #[cfg(feature = "pmac")] mod aes128pmaccsiv { use super::{GenericArray, TestVector}; use aes_siv::{siv::Aes128PmacSiv, KeyInit}; use hex_literal::hex; /// AES-128-PMAC-SIV test vectors const TEST_VECTORS: &[TestVector<[u8; 32]>] = &[ TestVector { key: &hex!("fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"), aad: &[&hex!("101112131415161718191a1b1c1d1e1f2021222324252627")], plaintext: &hex!("112233445566778899aabbccddee"), ciphertext: &hex!("8c4b814216140fc9b34a41716aa61633ea66abe16b2f6e4bceeda6e9077f") }, TestVector { key: &hex!("7f7e7d7c7b7a79787776757473727170404142434445464748494a4b4c4d4e4f"), aad: &[ &hex!("00112233445566778899aabbccddeeffdeaddadadeaddadaffeeddccbbaa99887766554433221100"), &hex!("102030405060708090a0"), &hex!("09f911029d74e35bd84156c5635688c0") ], plaintext: &hex!("7468697320697320736f6d6520706c61696e7465787420746f20656e6372797074207573696e67205349562d414553"), ciphertext: &hex!("acb9cbc95dbed8e766d25ad59deb65bcda7aff9214153273f88e89ebe580c77defc15d28448f420e0a17d42722e6d42776849aa3bec375c5a05e54f519e9fd") }, TestVector { key: &hex!("fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"), aad: &[], plaintext: &hex!(""), ciphertext: &hex!("19f25e5ea8a96ef27067d4626fdd3677") }, TestVector { key: &hex!("fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"), aad: &[&hex!("101112131415161718191a1b1c1d1e1f2021222324252627")], plaintext: &hex!("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f70"), ciphertext: &hex!("34cbb315120924e6ad05240a1582018b3dc965941308e0535680344cf9cf40cb5aa00b449548f9a4d9718fd22057d19f5ea89450d2d3bf905e858aaec4fc594aa27948ea205ca90102fc463f5c1cbbfb171d296d727ec77f892fb192a4eb9897b7d48d50e474a1238f02a82b122a7b16aa5cc1c04b10b839e478662ff1cec7cabc") }, ]; tests!(Aes128PmacSiv, TEST_VECTORS); } #[cfg(feature = "pmac")] mod aes256pmaccsiv { use super::{GenericArray, TestVector}; use aes_siv::{siv::Aes256PmacSiv, KeyInit}; use hex_literal::hex; /// AES-256-PMAC-SIV test vectors const TEST_VECTORS: &[TestVector<[u8; 64]>] = &[ TestVector { key: &hex!("fffefdfcfbfaf9f8f7f6f5f4f3f2f1f06f6e6d6c6b6a69686766656463626160f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff000102030405060708090a0b0c0d0e0f"), aad: &[&hex!("101112131415161718191a1b1c1d1e1f2021222324252627")], plaintext: &hex!("112233445566778899aabbccddee"), ciphertext: &hex!("77097bb3e160988e8b262c1942f983885f826d0d7e047e975e2fc4ea6776") }, TestVector { key: &hex!("7f7e7d7c7b7a797877767574737271706f6e6d6c6b6a69686766656463626160404142434445464748494a4b4c4d4e4f505152535455565758595a5b5b5d5e5f"), aad: &[ &hex!("00112233445566778899aabbccddeeffdeaddadadeaddadaffeeddccbbaa99887766554433221100"), &hex!("102030405060708090a0"), &hex!("09f911029d74e35bd84156c5635688c0") ], plaintext: &hex!("7468697320697320736f6d6520706c61696e7465787420746f20656e6372797074207573696e67205349562d414553"), ciphertext: &hex!("cd07d56dca0fe1569b8ecb3cf2346604290726e12529fc5948546b6be39fed9cd8652256c594c8f56208c7496789de8dfb4f161627c91482f9ecf809652a9e") }, TestVector { key: &hex!("7f7e7d7c7b7a797877767574737271706f6e6d6c6b6a69686766656463626160404142434445464748494a4b4c4d4e4f505152535455565758595a5b5b5d5e5f"), aad: &[&hex!("101112131415161718191a1b1c1d1e1f2021222324252627")], plaintext: &hex!("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f70"), ciphertext: &hex!("045ba64522c5c980835674d1c5a9264eca3e9f7aceafe9b5485b33f7d2c9114fe5c4b24f9c814d88e78b6150028d630289d023015b8569af338de0af8534827732b365ace1ac99d278431b22eafe31b94297b1c6a2de41383ed8b39f17e748aea128a8bd7d0ee80ec899f1b940c9c0463f22fc2b5a145cb6e90a32801dd1950f92") } ]; tests!(Aes256PmacSiv, TEST_VECTORS); }