diff --git a/.github/workflows/xts.yaml b/.github/workflows/xts.yaml new file mode 100644 index 0000000..3146519 --- /dev/null +++ b/.github/workflows/xts.yaml @@ -0,0 +1,60 @@ +name: xts + +on: + pull_request: + paths: + - "xts/**" + - "Cargo.*" + push: + branches: [master] + +defaults: + run: + working-directory: xts + +env: + CARGO_INCREMENTAL: 0 + RUSTFLAGS: "-Dwarnings" + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + rust: + - 1.81.0 # MSRV + - stable + target: + - thumbv7em-none-eabi + - wasm32-unknown-unknown + steps: + - uses: actions/checkout@v4 + - uses: RustCrypto/actions/cargo-cache@master + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ matrix.rust }} + targets: ${{ matrix.target }} + - run: cargo build --no-default-features --release --target ${{ matrix.target }} + + minimal-versions: + # disabled until belt-block gets published + if: false + uses: RustCrypto/actions/.github/workflows/minimal-versions.yml@master + with: + working-directory: ${{ github.workflow }} + + test: + runs-on: ubuntu-latest + strategy: + matrix: + rust: + - 1.81.0 # MSRV + - stable + steps: + - uses: actions/checkout@v4 + - uses: RustCrypto/actions/cargo-cache@master + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ matrix.rust }} + - run: cargo test + - run: cargo test --all-features diff --git a/Cargo.lock b/Cargo.lock index fec7cd7..6b5b5da 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -242,6 +242,15 @@ version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +[[package]] +name = "xts" +version = "0.1.0" +dependencies = [ + "aes", + "cipher", + "hex-literal", +] + [[package]] name = "zeroize" version = "1.8.1" diff --git a/Cargo.toml b/Cargo.toml index adffbe5..432a71c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "2" -members = ["belt-ctr", "cbc", "cts", "cfb8", "cfb-mode", "ctr", "ige", "ofb", "pcbc"] +members = ["belt-ctr", "cbc", "cts", "cfb8", "cfb-mode", "ctr", "ige", "ofb", "pcbc", "xts"] [profile.dev] opt-level = 2 diff --git a/README.md b/README.md index 3a365da..cf4f881 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ less error-prone than manual integrity verification. | [Infinite Garble Extension][IGE] | [`ige`] | [![crates.io](https://img.shields.io/crates/v/ige.svg)](https://crates.io/crates/ige) | [![Documentation](https://docs.rs/ige/badge.svg)](https://docs.rs/ige) | ![MSRV 1.81][msrv-1.81] | | [Output Feedback][OFB] | [`ofb`] | [![crates.io](https://img.shields.io/crates/v/ofb.svg)](https://crates.io/crates/ofb) | [![Documentation](https://docs.rs/ofb/badge.svg)](https://docs.rs/ofb) | ![MSRV 1.81][msrv-1.81] | | [Propagating Cipher Block Chaining][PCBC] | [`pcbc`] | [![crates.io](https://img.shields.io/crates/v/pcbc.svg)](https://crates.io/crates/pcbc) | [![Documentation](https://docs.rs/pcbc/badge.svg)](https://docs.rs/pcbc) | ![MSRV 1.81][msrv-1.81] | +| [Xor-Encrypt-Xor Tweaked-codebook with ciphertext Stealing][XTS] | [`xts`] | [![crates.io](https://img.shields.io/crates/v/xts.svg)](https://crates.io/crates/xts) | [![Documentation](https://docs.rs/xts/badge.svg)](https://docs.rs/xts) | ![MSRV 1.81][msrv-1.81] | ### Minimum Supported Rust Version (MSRV) Policy @@ -73,6 +74,7 @@ Unless you explicitly state otherwise, any contribution intentionally submitted [`ige`]: ./ige [`ofb`]: ./ofb [`pcbc`]: ./pcbc +[`xts`]: ./xts [//]: # (links) @@ -87,3 +89,4 @@ Unless you explicitly state otherwise, any contribution intentionally submitted [IGE]: https://www.links.org/files/openssl-ige.pdf [OFB]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Output_feedback_(OFB) [PCBC]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Propagating_cipher_block_chaining_(PCBC) +[XTS]: https://en.wikipedia.org/wiki/Disk_encryption_theory#XTS diff --git a/xts/CHANGELOG.md b/xts/CHANGELOG.md new file mode 100644 index 0000000..e5d4046 --- /dev/null +++ b/xts/CHANGELOG.md @@ -0,0 +1,11 @@ +# 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.1.0 (2022-02-10) +- Initial release ([#TODO]) + +[#TODO]: https://github.com/RustCrypto/block-modes/pull/TODO \ No newline at end of file diff --git a/xts/Cargo.toml b/xts/Cargo.toml new file mode 100644 index 0000000..e51a85d --- /dev/null +++ b/xts/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "xts" +version = "0.1.0" +description = "Xor-Encrypt-Xor Tweaked-codebook with ciphertext Stealing (XTS) block cipher mode of operation" +authors = ["zer0x64"] +license = "MIT OR Apache-2.0" +edition = "2021" +rust-version = "1.81" +readme = "README.md" +documentation = "https://docs.rs/xts" +repository = "https://github.com/RustCrypto/block-modes" +keywords = ["crypto", "block-mode", "ciphers"] +categories = ["cryptography", "no-std"] + +[dependencies] +cipher = "=0.5.0-pre.7" + +[dev-dependencies] +aes = "=0.9.0-pre.2" +cipher = { version = "=0.5.0-pre.7", features = ["dev"] } +hex-literal = "0.4" + +[features] +default = [] +alloc = ["cipher/alloc"] +std = ["cipher/std", "alloc"] +zeroize = ["cipher/zeroize"] + +[package.metadata.docs.rs] +all-features = true +rustdoc-args = ["--cfg", "docsrs"] diff --git a/xts/LICENSE-APACHE b/xts/LICENSE-APACHE new file mode 100644 index 0000000..54891b3 --- /dev/null +++ b/xts/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright 2024 zer0x64 + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/xts/LICENSE-MIT b/xts/LICENSE-MIT new file mode 100644 index 0000000..676061d --- /dev/null +++ b/xts/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2024 zer0x64 + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/xts/README.md b/xts/README.md new file mode 100644 index 0000000..d758974 --- /dev/null +++ b/xts/README.md @@ -0,0 +1,58 @@ +# RustCrypto: XTS + +[![crate][crate-image]][crate-link] +[![Docs][docs-image]][docs-link] +![Apache2/MIT licensed][license-image] +![Rust Version][rustc-image] +[![Project Chat][chat-image]][chat-link] +[![Build Status][build-image]][build-link] + +Generic implementation of the [Xor-encrypt-xor Tweaked-codebook with ciphertext Stealing][XTS] (XTS) block cipher +mode of operation. + +See [documentation][cipher-doc] of the `cipher` crate for additional information. + +## Minimum Supported Rust Version + +Rust **1.81** or higher. + +Minimum supported Rust version can be changed in the future, but it will be +done with a minor version bump. + +## SemVer Policy + +- All on-by-default features of this library are covered by SemVer +- MSRV is considered exempt from SemVer as noted above + +## License + +Licensed under either of: + + * [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) + * [MIT license](http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. + +[//]: # (badges) + +[crate-image]: https://img.shields.io/crates/v/xts.svg +[crate-link]: https://crates.io/crates/xts +[docs-image]: https://docs.rs/xts/badge.svg +[docs-link]: https://docs.rs/xts/ +[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg +[rustc-image]: https://img.shields.io/badge/rustc-1.81+-blue.svg +[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg +[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/308460-block-modes +[build-image]: https://github.com/RustCrypto/block-modes/workflows/xts/badge.svg?branch=master&event=push +[build-link]: https://github.com/RustCrypto/block-modes/actions?query=workflow%3Axts+branch%3Amaster + +[//]: # (general links) + +[xts]: https://en.wikipedia.org/wiki/Disk_encryption_theory#XTS +[cipher-doc]: https://docs.rs/cipher/ diff --git a/xts/benches/aes.rs b/xts/benches/aes.rs new file mode 100644 index 0000000..e131f22 --- /dev/null +++ b/xts/benches/aes.rs @@ -0,0 +1,28 @@ +#![feature(test)] +extern crate test; + +use aes::{Aes128, Aes256}; + +cipher::block_encryptor_bench!( + KeyIv: xts::Encryptor, + xts_aes128_encrypt_block, + xts_aes128_encrypt_blocks, +); + +cipher::block_decryptor_bench!( + KeyIv: xts::Decryptor, + xts_aes128_decrypt_block, + xts_aes128_decrypt_blocks, +); + +cipher::block_encryptor_bench!( + KeyIv: xts::Encryptor, + xts_aes256_encrypt_block, + xts_aes256_encrypt_blocks, +); + +cipher::block_decryptor_bench!( + KeyIv: xts::Decryptor, + xts_aes256_decrypt_block, + xts_aes256_decrypt_blocks, +); diff --git a/xts/src/decrypt.rs b/xts/src/decrypt.rs new file mode 100644 index 0000000..68fd56f --- /dev/null +++ b/xts/src/decrypt.rs @@ -0,0 +1,357 @@ +use core::{fmt, ops::Add}; + +use crate::xts_core::{precompute_iv, Stealer, Xts}; +use crate::{Error, Result}; +use cipher::{ + array::ArraySize, + crypto_common::{BlockSizes, IvSizeUser}, + inout::InOut, + typenum::Sum, + AlgorithmName, Block, BlockCipherDecBackend, BlockCipherDecClosure, BlockCipherDecrypt, + BlockCipherEncrypt, BlockModeDecBackend, BlockModeDecClosure, BlockModeDecrypt, BlockSizeUser, + InOutBuf, Iv, IvState, Key, KeyInit, KeyIvInit, KeySizeUser, ParBlocks, ParBlocksSizeUser, +}; + +#[cfg(feature = "zeroize")] +use cipher::zeroize::{Zeroize, ZeroizeOnDrop}; + +/// XTS mode decryptor. +pub type Decryptor = SplitDecryptor; + +/// XTS mode decryptor. +/// This structure allows using different ciphers for the cipher itself and the tweak. +#[derive(Clone)] +pub struct SplitDecryptor +where + Cipher: BlockCipherDecrypt, + Tweaker: BlockCipherEncrypt, +{ + cipher: Cipher, + tweaker: Tweaker, + iv: Block, +} + +impl KeySizeUser for SplitDecryptor +where + KS1: ArraySize + Add, + KS2: ArraySize, + >::Output: ArraySize, + BS: BlockSizes, + C: BlockCipherDecrypt + KeySizeUser, + T: BlockCipherEncrypt + KeySizeUser, +{ + type KeySize = Sum; +} + +impl KeyIvInit for SplitDecryptor +where + BS: BlockSizes, + C: BlockCipherDecrypt + KeySizeUser + KeyInit, + T: BlockCipherEncrypt + KeySizeUser + KeyInit, + SplitDecryptor: KeySizeUser, +{ + /// Create a new instance of the cipher and initialize it. + /// This assumes a single key, which is a concatenation of the cipher key and the tweak key, in that order. + /// To use different key, use `new_from_split_keys` + fn new(key: &Key, iv: &Iv) -> Self { + // Split the key and call split key constructor + // Assumes the key is cipher_key + tweak_key + let k1 = <&Key>::try_from(&key[..C::key_size()]) + .expect("Due to trait bounds, k1 should always be half the size of the XTS key"); + let k2 = <&Key>::try_from(&key[C::key_size()..]) + .expect("Due to trait bounds, k2 should always be half the size of the XTS key"); + + Self::new_from_split_keys(k1, k2, iv) + } +} + +impl SplitDecryptor +where + BS: BlockSizes, + C: BlockCipherDecrypt + KeyInit + KeySizeUser, + T: BlockCipherEncrypt + KeyInit + KeySizeUser, +{ + /// Create an XTS context and precompute the tweak. + pub fn new_from_split_keys(cipher_key: &Key, tweak_key: &Key, iv: &Block) -> Self { + let cipher = C::new(cipher_key); + let tweaker = T::new(tweak_key); + let iv = precompute_iv(&tweaker, iv); + + Self { + cipher, + tweaker, + iv, + } + } + + /// Change the IV/sector number. + pub fn reset_iv(&mut self, iv: &Block) { + self.iv = precompute_iv(&self.tweaker, iv) + } + + /// Decrypt `inout` buffer. + pub fn decrypt_inout(&mut self, buf: InOutBuf<'_, '_, u8>) -> Result<()> { + if buf.len() < BS::USIZE { + return Err(Error); + }; + + if buf.len() % BS::USIZE == 0 { + // No need for stealing + let (blocks, _) = buf.into_chunks(); + self.decrypt_blocks_inout(blocks); + } else { + let full_blocks = (buf.len() / BS::USIZE - 1) * BS::USIZE; + + let (blocks, mut tail) = buf.split_at(full_blocks); + let (blocks, _) = blocks.into_chunks(); + self.decrypt_blocks_inout(blocks); + + for mut b in tail.reborrow() { + *b.get_out() = *b.get_in(); + } + + self.ciphertext_stealing(tail.get_out()); + } + + Ok(()) + } + + /// Decrypt data in-place. + pub fn decrypt(&mut self, buf: &mut [u8]) -> Result<()> { + self.decrypt_inout(buf.into()) + } + + /// Decrypt data buffer-to-buffer. + pub fn decrypt_b2b(&mut self, in_buf: &[u8], out_buf: &mut [u8]) -> Result<()> { + InOutBuf::new(in_buf, out_buf) + .map_err(|_| Error) + .and_then(|buf| self.decrypt_inout(buf)) + } +} + +impl BlockSizeUser for SplitDecryptor +where + BS: BlockSizes, + C: BlockCipherDecrypt, + T: BlockCipherEncrypt, +{ + type BlockSize = BS; +} + +impl BlockModeDecrypt for SplitDecryptor +where + BS: BlockSizes, + C: BlockCipherDecrypt, + T: BlockCipherEncrypt, +{ + fn decrypt_with_backend(&mut self, f: impl BlockModeDecClosure) { + struct Closure<'a, BS, BC> + where + BS: BlockSizes, + BC: BlockModeDecClosure, + { + iv: &'a mut Block, + f: BC, + } + + impl BlockSizeUser for Closure<'_, BS, BC> + where + BS: BlockSizes, + BC: BlockModeDecClosure, + { + type BlockSize = BS; + } + + impl BlockCipherDecClosure for Closure<'_, BS, BC> + where + BS: BlockSizes, + BC: BlockModeDecClosure, + { + #[inline(always)] + fn call>( + self, + cipher_backend: &B, + ) { + let Self { iv, f } = self; + f.call(&mut Backend { iv, cipher_backend }); + } + } + + // tweaker is only used when setting up IV + let Self { + cipher, + tweaker: _, + iv, + } = self; + cipher.decrypt_with_backend(Closure { iv, f }) + } +} + +impl Stealer for SplitDecryptor +where + BS: BlockSizes, + C: BlockCipherDecrypt, + T: BlockCipherEncrypt, +{ + fn process_block(&self, block: &mut Block) { + self.cipher.decrypt_block(block); + } + + fn get_iv(&self) -> &Block { + &self.iv + } + + fn get_iv_mut(&mut self) -> &mut Block { + &mut self.iv + } + + #[inline(always)] + fn is_decrypt() -> bool { + true + } +} + +impl IvSizeUser for SplitDecryptor +where + BS: BlockSizes, + C: BlockCipherDecrypt, + T: BlockCipherEncrypt, +{ + type IvSize = BS; +} + +impl IvState for SplitDecryptor +where + BS: BlockSizes, + C: BlockCipherDecrypt, + T: BlockCipherEncrypt, +{ + #[inline] + fn iv_state(&self) -> Iv { + self.iv.clone() + } +} + +impl AlgorithmName for SplitDecryptor +where + BS: BlockSizes, + C: BlockCipherDecrypt + AlgorithmName, + T: BlockCipherEncrypt + AlgorithmName, +{ + fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("xts::Decryptor<")?; + ::write_alg_name(f)?; + f.write_str(",")?; + ::write_alg_name(f)?; + f.write_str(">") + } +} + +impl fmt::Debug for SplitDecryptor +where + BS: BlockSizes, + C: BlockCipherDecrypt + AlgorithmName, + T: BlockCipherEncrypt + AlgorithmName, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Self::write_alg_name(f) + } +} + +impl Drop for SplitDecryptor +where + C: BlockCipherDecrypt, + T: BlockCipherEncrypt, +{ + fn drop(&mut self) { + #[cfg(feature = "zeroize")] + self.iv.zeroize(); + } +} + +#[cfg(feature = "zeroize")] +impl ZeroizeOnDrop for SplitDecryptor +where + C: BlockCipherDecrypt + ZeroizeOnDrop, + T: BlockCipherEncrypt + ZeroizeOnDrop, +{ +} + +struct Backend<'a, BS, BK> +where + BS: BlockSizes, + BK: BlockCipherDecBackend, +{ + iv: &'a mut Block, + cipher_backend: &'a BK, +} + +impl BlockSizeUser for Backend<'_, BS, BK> +where + BS: BlockSizes, + BK: BlockCipherDecBackend, +{ + type BlockSize = BS; +} + +impl ParBlocksSizeUser for Backend<'_, BS, BK> +where + BS: BlockSizes, + BK: BlockCipherDecBackend, +{ + type ParBlocksSize = BK::ParBlocksSize; +} + +impl BlockModeDecBackend for Backend<'_, BS, BK> +where + BS: BlockSizes, + BK: BlockCipherDecBackend, +{ + #[inline(always)] + fn decrypt_block(&mut self, block: InOut<'_, '_, Block>) { + self.process_block(block); + } + + #[inline(always)] + fn decrypt_par_blocks(&mut self, blocks: InOut<'_, '_, ParBlocks>) { + self.process_par_blocks(blocks); + } + + #[inline(always)] + fn decrypt_block_inplace(&mut self, block: &mut Block) { + self.process_block_inplace(block); + } + + #[inline(always)] + fn decrypt_par_blocks_inplace(&mut self, blocks: &mut ParBlocks) { + self.process_par_blocks_inplace(blocks); + } + + #[inline(always)] + fn decrypt_tail_blocks(&mut self, blocks: cipher::InOutBuf<'_, '_, Block>) { + self.process_tail_blocks(blocks); + } + + #[inline(always)] + fn decrypt_tail_blocks_inplace(&mut self, blocks: &mut [Block]) { + self.process_tail_blocks_inplace(blocks); + } +} + +impl Xts for Backend<'_, BS, BC> +where + BS: BlockSizes, + BC: BlockCipherDecBackend, +{ + fn process_inplace(&self, block: &mut Block) { + self.cipher_backend.decrypt_block_inplace(block); + } + + fn process_par_inplace(&self, blocks: &mut ParBlocks) { + self.cipher_backend.decrypt_par_blocks_inplace(blocks); + } + + fn get_iv_mut(&mut self) -> &mut Block { + self.iv + } +} diff --git a/xts/src/encrypt.rs b/xts/src/encrypt.rs new file mode 100644 index 0000000..6bf1466 --- /dev/null +++ b/xts/src/encrypt.rs @@ -0,0 +1,350 @@ +use crate::xts_core::{precompute_iv, Stealer, Xts}; +use crate::{Error, Result}; + +use cipher::InOutBuf; +use cipher::{ + array::ArraySize, crypto_common::BlockSizes, typenum::Sum, AlgorithmName, Block, + BlockCipherEncBackend, BlockCipherEncClosure, BlockCipherEncrypt, BlockModeEncBackend, + BlockModeEncClosure, BlockModeEncrypt, BlockSizeUser, InOut, Iv, IvSizeUser, IvState, Key, + KeyInit, KeyIvInit, KeySizeUser, ParBlocks, ParBlocksSizeUser, +}; +use core::{fmt, ops::Add}; + +#[cfg(feature = "zeroize")] +use cipher::zeroize::{Zeroize, ZeroizeOnDrop}; + +/// XTS mode encryptor. +pub type Encryptor = SplitEncryptor; + +/// XTS mode encryptor. +/// This structure allows using different ciphers for the cipher itself and the tweak. +#[derive(Clone)] +pub struct SplitEncryptor +where + Cipher: BlockCipherEncrypt, + Tweaker: BlockCipherEncrypt, +{ + cipher: Cipher, + tweaker: Tweaker, + iv: Block, +} + +// This would probably be the cleanest way to do it, but it would require a way to multiply a typenum by 2 +impl KeySizeUser for SplitEncryptor +where + KS1: ArraySize + Add, + KS2: ArraySize, + >::Output: ArraySize, + BS: BlockSizes, + C: BlockCipherEncrypt + KeySizeUser, + T: BlockCipherEncrypt + KeySizeUser, +{ + type KeySize = Sum; +} + +impl KeyIvInit for SplitEncryptor +where + BS: BlockSizes, + C: BlockCipherEncrypt + KeySizeUser + KeyInit, + T: BlockCipherEncrypt + KeySizeUser + KeyInit, + SplitEncryptor: KeySizeUser, +{ + /// Create a new instance of the cipher and initialize it. + /// This assumes a single key, which is a concatenation of the cipher key and the tweak key, in that order. + /// To use different key, use `new_from_split_keys` + fn new(key: &Key, iv: &Iv) -> Self { + // Split the key and call split key constructor + // Assumes the key is cipher_key + tweak_key + let k1 = <&Key>::try_from(&key[..C::key_size()]) + .expect("Due to trait bounds, k1 should always be half the size of the XTS key"); + let k2 = <&Key>::try_from(&key[C::key_size()..]) + .expect("Due to trait bounds, k2 should always be half the size of the XTS key"); + + Self::new_from_split_keys(k1, k2, iv) + } +} + +impl SplitEncryptor +where + BS: BlockSizes, + C: BlockCipherEncrypt + KeyInit + KeySizeUser, + T: BlockCipherEncrypt + KeyInit + KeySizeUser, +{ + /// Create an XTS context and precompute the tweak. + pub fn new_from_split_keys(k1: &Key, k2: &Key, iv: &Block) -> Self { + let cipher = C::new(k1); + let tweaker = T::new(k2); + let iv = precompute_iv(&tweaker, iv); + + Self { + cipher, + tweaker, + iv, + } + } + + /// Change the IV/sector number. + pub fn reset_iv(&mut self, iv: &Block) { + self.iv = precompute_iv(&self.tweaker, iv) + } + + /// Encrypt `inout` buffer. + pub fn encrypt_inout(&mut self, buf: InOutBuf<'_, '_, u8>) -> Result<()> { + if buf.len() < BS::USIZE { + return Err(Error); + }; + + if buf.len() % BS::USIZE == 0 { + // No need for stealing + let (blocks, _) = buf.into_chunks(); + self.encrypt_blocks_inout(blocks); + } else { + let full_blocks = (buf.len() / BS::USIZE - 1) * BS::USIZE; + + let (blocks, mut tail) = buf.split_at(full_blocks); + let (blocks, _) = blocks.into_chunks(); + self.encrypt_blocks_inout(blocks); + + for mut b in tail.reborrow() { + *b.get_out() = *b.get_in(); + } + + self.ciphertext_stealing(tail.get_out()); + } + + Ok(()) + } + + /// Encrypt data in-place. + pub fn encrypt(&mut self, buf: &mut [u8]) -> Result<()> { + self.encrypt_inout(buf.into()) + } + + /// Encrypt data buffer-to-buffer. + pub fn encrypt_b2b(&mut self, in_buf: &[u8], out_buf: &mut [u8]) -> Result<()> { + InOutBuf::new(in_buf, out_buf) + .map_err(|_| Error) + .and_then(|buf| self.encrypt_inout(buf)) + } +} + +impl BlockSizeUser for SplitEncryptor +where + BS: BlockSizes, + C: BlockCipherEncrypt, + T: BlockCipherEncrypt, +{ + type BlockSize = BS; +} + +impl IvSizeUser for SplitEncryptor +where + BS: BlockSizes, + C: BlockCipherEncrypt, + T: BlockCipherEncrypt, +{ + type IvSize = BS; +} + +impl IvState for SplitEncryptor +where + BS: BlockSizes, + C: BlockCipherEncrypt, + T: BlockCipherEncrypt, +{ + #[inline] + fn iv_state(&self) -> Iv { + self.iv.clone() + } +} + +impl BlockModeEncrypt for SplitEncryptor +where + BS: BlockSizes, + C: BlockCipherEncrypt, + T: BlockCipherEncrypt, +{ + fn encrypt_with_backend(&mut self, f: impl BlockModeEncClosure) { + struct Closure<'a, BS, BM> + where + BS: BlockSizes, + BM: BlockModeEncClosure, + { + iv: &'a mut Block, + f: BM, + } + + impl BlockSizeUser for Closure<'_, BS, BM> + where + BS: BlockSizes, + BM: BlockModeEncClosure, + { + type BlockSize = BS; + } + + impl BlockCipherEncClosure for Closure<'_, BS, BM> + where + BS: BlockSizes, + BM: BlockModeEncClosure, + { + #[inline(always)] + fn call>(self, cipher_backend: &B) { + let Self { iv, f } = self; + f.call(&mut Backend { iv, cipher_backend }); + } + } + + // tweaker is only used when setting up IV + let Self { + cipher, + tweaker: _, + iv, + } = self; + + let f = Closure { iv, f }; + cipher.encrypt_with_backend(f) + } +} + +impl Stealer for SplitEncryptor +where + BS: BlockSizes, + C: BlockCipherEncrypt, + T: BlockCipherEncrypt, +{ + fn process_block(&self, block: &mut Block) { + self.cipher.encrypt_block(block); + } + + fn get_iv(&self) -> &Block { + &self.iv + } + + fn get_iv_mut(&mut self) -> &mut Block { + &mut self.iv + } + + #[inline(always)] + fn is_decrypt() -> bool { + false + } +} + +impl AlgorithmName for SplitEncryptor +where + BS: BlockSizes, + C: BlockCipherEncrypt + AlgorithmName, + T: BlockCipherEncrypt + AlgorithmName, +{ + fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("xts::Encryptor<")?; + ::write_alg_name(f)?; + f.write_str(",")?; + ::write_alg_name(f)?; + f.write_str(">") + } +} + +impl fmt::Debug for SplitEncryptor +where + BS: BlockSizes, + C: BlockCipherEncrypt + AlgorithmName, + T: BlockCipherEncrypt + AlgorithmName, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + Self::write_alg_name(f) + } +} + +impl Drop for SplitEncryptor +where + C: BlockCipherEncrypt, + T: BlockCipherEncrypt, +{ + fn drop(&mut self) { + #[cfg(feature = "zeroize")] + self.iv.zeroize(); + } +} + +#[cfg(feature = "zeroize")] +impl ZeroizeOnDrop for SplitEncryptor {} + +struct Backend<'a, BS, BC> +where + BS: BlockSizes, + BC: BlockCipherEncBackend, +{ + iv: &'a mut Block, + cipher_backend: &'a BC, +} + +impl BlockSizeUser for Backend<'_, BS, BK> +where + BS: BlockSizes, + BK: BlockCipherEncBackend, +{ + type BlockSize = BS; +} + +impl ParBlocksSizeUser for Backend<'_, BS, BK> +where + BS: BlockSizes, + BK: BlockCipherEncBackend, +{ + type ParBlocksSize = BK::ParBlocksSize; +} + +impl BlockModeEncBackend for Backend<'_, BS, BK> +where + BS: BlockSizes, + BK: BlockCipherEncBackend, +{ + #[inline(always)] + fn encrypt_block(&mut self, block: InOut<'_, '_, Block>) { + self.process_block(block); + } + + #[inline(always)] + fn encrypt_par_blocks(&mut self, blocks: InOut<'_, '_, ParBlocks>) { + self.process_par_blocks(blocks); + } + + #[inline(always)] + fn encrypt_block_inplace(&mut self, block: &mut Block) { + self.process_block_inplace(block); + } + + #[inline(always)] + fn encrypt_par_blocks_inplace(&mut self, blocks: &mut ParBlocks) { + self.process_par_blocks_inplace(blocks); + } + + #[inline(always)] + fn encrypt_tail_blocks(&mut self, blocks: cipher::InOutBuf<'_, '_, Block>) { + self.process_tail_blocks(blocks); + } + + #[inline(always)] + fn encrypt_tail_blocks_inplace(&mut self, blocks: &mut [Block]) { + self.process_tail_blocks_inplace(blocks); + } +} + +impl Xts for Backend<'_, BS, BC> +where + BS: BlockSizes, + BC: BlockCipherEncBackend, +{ + fn process_inplace(&self, block: &mut Block) { + self.cipher_backend.encrypt_block_inplace(block); + } + + fn process_par_inplace(&self, blocks: &mut ParBlocks) { + self.cipher_backend.encrypt_par_blocks_inplace(blocks); + } + + fn get_iv_mut(&mut self) -> &mut Block { + self.iv + } +} diff --git a/xts/src/gf.rs b/xts/src/gf.rs new file mode 100644 index 0000000..70c7431 --- /dev/null +++ b/xts/src/gf.rs @@ -0,0 +1,109 @@ +use cipher::{crypto_common::BlockSizes, Array}; + +/// Derived from the polynomial x^128 + x^5 + x + 1 +const GF_MOD: u8 = 0x87; + +pub fn gf_mul(tweak: &mut Array) -> u8 +where + BS: BlockSizes, +{ + let mut carry = 0; + + for i in 0..BS::to_usize() { + // Save carry from previous byte + let old_carry = carry; + + // Check if there is a carry for this shift + carry = (tweak[i] & 0x80) >> 7; + + // Shift left + tweak[i] <<= 1; + + // Carry over bit from last carry + tweak[i] |= old_carry; + } + + // If there is a carry, we mod by the polynomial + tweak[0] ^= 0u8.wrapping_sub(carry) & GF_MOD; + + carry +} + +// This is only used once when decrypting with ciphertext stealing +pub fn gf_reverse_mul(tweak: &mut Array, carry: u8) +where + BS: BlockSizes, +{ + tweak[0] ^= 0u8.wrapping_sub(carry) & GF_MOD; + + let mut new_carry = 0; + + for i in (0..BS::to_usize()).rev() { + // Save carry from previous byte + let old_carry = new_carry; + + // Check if there is a carry for this shift + new_carry = tweak[i] & 1; + + // Shift right + tweak[i] >>= 1; + + // Carry over bit from last carry + tweak[i] |= old_carry << 7; + } + + // If there is a carry, we mod by the polynomial + *tweak.last_mut().expect("tweak should never be empty") |= carry << 7; +} + +#[cfg(test)] +mod tests { + use cipher::{consts::U16, Array}; + + use crate::gf::{gf_mul, gf_reverse_mul}; + + #[test] + fn test_gf_mul() { + let mut input = Array::::from([0x55; 16]); + let expected_output = [0xAA; 16]; + + let carry = gf_mul(&mut input); + + assert_eq!(carry, 0); + assert_eq!(input, expected_output); + } + + #[test] + fn test_gf_mul_overflow() { + let mut input = Array::::from([0xAA; 16]); + let mut expected_output = [0x55; 16]; + expected_output[0] = 0xd3; + + let carry = gf_mul(&mut input); + + assert_eq!(carry, 1); + assert_eq!(input, expected_output) + } + + #[test] + fn test_gf_reverse_mul() { + let mut input = Array::::from([0xAA; 16]); + let expected_output = [0x55; 16]; + + gf_reverse_mul(&mut input, 0); + + assert_eq!(input, expected_output); + } + + #[test] + fn test_gf_reverse_mul_overflow() { + let mut input = Array::::from([0xAA; 16]); + let mut expected_output = [0x55; 16]; + expected_output[0] = 0x16; + expected_output[15] = 0xd5; + + gf_reverse_mul(&mut input, 1); + + assert_eq!(input, expected_output); + } +} diff --git a/xts/src/lib.rs b/xts/src/lib.rs new file mode 100644 index 0000000..0ae60f2 --- /dev/null +++ b/xts/src/lib.rs @@ -0,0 +1,91 @@ +//! [Xor-Encrypt-Xor Tweaked-codebook with ciphertext Stealing][1] (XTS) mode. +//! +//! Mode functionality is accessed using traits from re-exported [`cipher`] crate. +//! +//! # ⚠️ Security Warning: Hazmat! +//! +//! This crate does not ensure ciphertexts are authentic! Thus ciphertext integrity +//! is not verified, which can lead to serious vulnerabilities! +//! [AEADs](https://github.com/RustCrypto/AEADs) provide simple authenticated encryption, +//! which is much less error-prone than manual integrity verification. +//! +//! # Example +//! ``` +//! use aes::cipher::KeyIvInit; +//! use hex_literal::hex; +//! +//! type Aes128XtsEnc = xts::Encryptor; +//! type Aes128XtsDec = xts::Decryptor; +//! +//! let key = [0x42u8; 32]; +//! let mut tweak = [0x24u8; 16]; +//! tweak[8..].fill(0); +//! +//! let plaintext = *b"hello world! this is my plaintext."; +//! let ciphertext = hex!( // TODO fix this +//! "bf970595626410ad91f032cc5fa36bcafb5cfe9c2bfe7e226582ec079a27e8c8521c" +//! ); +//! +//! // encrypt/decrypt in-place +//! // XTS does not need padding, so output is the same length as the buffer +//! let pt_len = plaintext.len(); +//! let mut buf = vec![0u8; pt_len]; +//! buf.copy_from_slice(&plaintext); +//! +//! Aes128XtsEnc::new(&key.into(), &tweak.into()) +//! .encrypt(&mut buf) +//! .unwrap(); +//! assert_eq!(&buf, &ciphertext); +//! +//! Aes128XtsDec::new(&key.into(), &tweak.into()) +//! .decrypt(&mut buf) +//! .unwrap(); +//! assert_eq!(&buf, &plaintext); +//! +//! // encrypt/decrypt from buffer to buffer +//! let mut buf = vec![0u8; pt_len]; +//! Aes128XtsEnc::new(&key.into(), &tweak.into()) +//! .encrypt_b2b(&plaintext, &mut buf) +//! .unwrap(); +//! assert_eq!(&buf, &ciphertext); +//! +//! Aes128XtsDec::new(&key.into(), &tweak.into()) +//! .decrypt_b2b(&ciphertext, &mut buf) +//! .unwrap(); +//! assert_eq!(&buf, &plaintext); +//! ``` +//! [1]: https://en.wikipedia.org/wiki/Disk_encryption_theory#XTS + +#![no_std] +#![doc( + html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg", + html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg" +)] +#![forbid(unsafe_code)] +#![cfg_attr(docsrs, feature(doc_auto_cfg))] +#![warn(missing_debug_implementations, missing_docs, rust_2018_idioms)] + +use cipher::array::{Array, ArraySize}; + +mod decrypt; +mod encrypt; +mod gf; +mod xts_core; + +pub use cipher; +pub use decrypt::{Decryptor, SplitDecryptor}; +pub use encrypt::{Encryptor, SplitEncryptor}; + +/// Error which indicates that message is smaller than cipher's block size. +#[derive(Copy, Clone, Debug)] +pub struct Error; + +/// Result type of the crate. +pub type Result = core::result::Result; + +#[inline(always)] +fn xor(out: &mut Array, buf: &Array) { + for (a, b) in out.iter_mut().zip(buf) { + *a ^= *b; + } +} diff --git a/xts/src/xts_core.rs b/xts/src/xts_core.rs new file mode 100644 index 0000000..a093b4f --- /dev/null +++ b/xts/src/xts_core.rs @@ -0,0 +1,181 @@ +use cipher::{ + crypto_common::BlockSizes, Array, Block, BlockCipherEncrypt, BlockSizeUser, InOut, InOutBuf, + ParBlocks, ParBlocksSizeUser, +}; + +use crate::gf::{gf_mul, gf_reverse_mul}; +use crate::xor; + +/// Since the traits does not allow using two engines, this is used to pre-compute the IV. +pub fn precompute_iv(cipher: &BC, iv: &Block) -> Block +where + BS: BlockSizes, + BC: BlockCipherEncrypt, +{ + let mut output = iv.clone(); + cipher.encrypt_block(&mut output); + output +} + +/// Core implementation of XTS mode +pub trait Xts: ParBlocksSizeUser + BlockSizeUser { + /// Method to encrypt/decrypt a single block without mode. + fn process_inplace(&self, block: &mut Block); // Array); + + /// Method to encrypt/decrypt multiple blocks in parallel without mode. + fn process_par_inplace(&self, blocks: &mut ParBlocks); + + /// Gets the IV reference. + fn get_iv_mut(&mut self) -> &mut Array; + + //Unused but keeping for now just in case + fn _process(&self, mut block: InOut<'_, '_, Block>) { + let mut b = block.clone_in(); + self.process_inplace(&mut b); + + *block.get_out() = b; + } + + fn _process_par(&self, blocks: InOut<'_, '_, ParBlocks>) { + let mut blocks = blocks.clone_in(); + self.process_par_inplace(&mut blocks); + } + + fn process_block_inplace(&mut self, block: &mut Block) { + { + let iv = self.get_iv_mut(); + xor(block, iv); + } + + self.process_inplace(block); + + let iv = self.get_iv_mut(); + xor(block, iv); + + gf_mul(iv); + } + + /// Encrypt/decrypt a block using XTS and update the tweak + fn process_block(&mut self, mut block: InOut<'_, '_, Array>) { + let mut b = block.clone_in(); + self.process_block_inplace(&mut b); + + *block.get_out() = b; + } + + /// Encrypt/decrypt multiple blocks in parrallel using XTS and update the tweak + fn process_par_blocks_inplace(&mut self, blocks: &mut ParBlocks) { + let mut iv_array: ParBlocks = Default::default(); + { + let iv = self.get_iv_mut(); + + for (b, i) in blocks.iter_mut().zip(iv_array.iter_mut()) { + *i = iv.clone(); + xor(b, iv); + + gf_mul(iv); + } + } + + self.process_par_inplace(blocks); + + for (b, i) in blocks.iter_mut().zip(iv_array.iter_mut()) { + xor(b, i); + } + } + + fn process_par_blocks(&mut self, mut blocks: InOut<'_, '_, ParBlocks>) { + let mut b = blocks.clone_in(); + self.process_par_blocks_inplace(&mut b); + + *blocks.get_out() = b; + } + + fn process_tail_blocks_inplace(&mut self, blocks: &mut [Block]) { + for b in blocks { + { + let iv = self.get_iv_mut(); + xor(b, iv); + } + + self.process_block_inplace(b); + + let iv = self.get_iv_mut(); + xor(b, iv); + + let _ = gf_mul(iv); + } + } + + fn process_tail_blocks(&mut self, blocks: InOutBuf<'_, '_, Block>) { + for mut block in blocks { + let mut b = block.clone_in(); + self.process_block_inplace(&mut b); + *block.get_out() = b; + } + } +} + +pub(crate) trait Stealer: BlockSizeUser { + /// Encrypt/Decrypt the block + fn process_block(&self, block: &mut Block); + + /// Gets the IV reference. + fn get_iv(&self) -> &Array; + + /// Gets the IV reference. + fn get_iv_mut(&mut self) -> &mut Array; + + /// There is a slight difference regarding the tweak during decryption + fn is_decrypt() -> bool; + + fn process_xts_block(&mut self, block: &mut Block) { + xor(block, self.get_iv()); + self.process_block(block); + xor(block, self.get_iv()); + + let iv = self.get_iv_mut(); + gf_mul(iv); + } + + /// Perform the ciphertext stealing phase + fn ciphertext_stealing(&mut self, buffer: &mut [u8]) { + let remaining_bytes = buffer.len() - Self::block_size(); + + // We split the buffer into the two blocks + let (second_to_last_block, last_block) = buffer.split_at_mut(Self::block_size()); + + let second_to_last_block: &mut Block = second_to_last_block + .try_into() + .expect("Not a full block on second to last block!"); + + if Self::is_decrypt() { + // We fast forward the multiplication here + let carry = { + let iv = self.get_iv_mut(); + let carry = gf_mul(iv); + + xor(second_to_last_block, iv); + + carry + }; + + self.process_block(second_to_last_block); + + { + let iv = self.get_iv_mut(); + xor(second_to_last_block, iv); + + gf_reverse_mul(iv, carry); + } + } else { + // Process normally + self.process_xts_block(second_to_last_block); + } + + // We first swap the remaining bytes with the previous block's + second_to_last_block[..remaining_bytes].swap_with_slice(last_block); + + self.process_xts_block(second_to_last_block); + } +} diff --git a/xts/tests/aes.rs b/xts/tests/aes.rs new file mode 100644 index 0000000..c5eff7b --- /dev/null +++ b/xts/tests/aes.rs @@ -0,0 +1,53 @@ +use aes::*; +use cipher::{block_mode_dec_test, block_mode_enc_test}; +use xts::{Decryptor, Encryptor}; + +mod macros; + +// Test vectors from IEEE 1619-2018 +block_mode_enc_test!(aes128_xts_enc_vec1_test, "ieee_vec1", Encryptor); +block_mode_dec_test!(aes128_xts_dec_vec1_test, "ieee_vec1", Decryptor); +block_mode_enc_test!(aes128_xts_enc_vec2_test, "ieee_vec2", Encryptor); +block_mode_dec_test!(aes128_xts_dec_vec2_test, "ieee_vec2", Decryptor); +block_mode_enc_test!(aes128_xts_enc_vec3_test, "ieee_vec3", Encryptor); +block_mode_dec_test!(aes128_xts_dec_vec3_test, "ieee_vec3", Decryptor); +block_mode_enc_test!(aes128_xts_enc_vec4_test, "ieee_vec4", Encryptor); +block_mode_dec_test!(aes128_xts_dec_vec4_test, "ieee_vec4", Decryptor); +block_mode_enc_test!(aes128_xts_enc_vec5_test, "ieee_vec5", Encryptor); +block_mode_dec_test!(aes128_xts_dec_vec5_test, "ieee_vec5", Decryptor); +block_mode_enc_test!(aes128_xts_enc_vec6_test, "ieee_vec6", Encryptor); +block_mode_dec_test!(aes128_xts_dec_vec6_test, "ieee_vec6", Decryptor); +block_mode_enc_test!(aes128_xts_enc_vec7_test, "ieee_vec7", Encryptor); +block_mode_dec_test!(aes128_xts_dec_vec7_test, "ieee_vec7", Decryptor); +block_mode_enc_test!(aes128_xts_enc_vec8_test, "ieee_vec8", Encryptor); +block_mode_dec_test!(aes128_xts_dec_vec8_test, "ieee_vec8", Decryptor); +block_mode_enc_test!(aes128_xts_enc_vec9_test, "ieee_vec9", Encryptor); +block_mode_dec_test!(aes128_xts_dec_vec9_test, "ieee_vec9", Decryptor); +block_mode_enc_test!(aes256_xts_enc_vec10_test, "ieee_vec10", Encryptor); +block_mode_dec_test!(aes256_xts_dec_vec10_test, "ieee_vec10", Decryptor); +block_mode_enc_test!(aes256_xts_enc_vec11_test, "ieee_vec11", Encryptor); +block_mode_dec_test!(aes256_xts_dec_vec11_test, "ieee_vec11", Decryptor); +block_mode_enc_test!(aes256_xts_enc_vec12_test, "ieee_vec12", Encryptor); +block_mode_dec_test!(aes256_xts_dec_vec12_test, "ieee_vec12", Decryptor); +block_mode_enc_test!(aes256_xts_enc_vec13_test, "ieee_vec13", Encryptor); +block_mode_dec_test!(aes256_xts_dec_vec13_test, "ieee_vec13", Decryptor); +block_mode_enc_test!(aes256_xts_enc_vec14_test, "ieee_vec14", Encryptor); +block_mode_dec_test!(aes256_xts_dec_vec14_test, "ieee_vec14", Decryptor); + +// Those tests ciphertext stealing, which cannot be done using the `cipher` macro, since the macro asserts +// that the plaintext/ciphertext length is a multiple of the block size +block_mode_enc_stealing_test!(aes128_xts_enc_vec15_test, "ieee_vec15", Aes128); +block_mode_dec_stealing_test!(aes128_xts_dec_vec15_test, "ieee_vec15", Aes128); +block_mode_enc_stealing_test!(aes128_xts_enc_vec16_test, "ieee_vec16", Aes128); +block_mode_dec_stealing_test!(aes128_xts_dec_vec16_test, "ieee_vec16", Aes128); +block_mode_enc_stealing_test!(aes128_xts_enc_vec17_test, "ieee_vec17", Aes128); +block_mode_dec_stealing_test!(aes128_xts_dec_vec17_test, "ieee_vec17", Aes128); +block_mode_enc_stealing_test!(aes128_xts_enc_vec18_test, "ieee_vec18", Aes128); +block_mode_dec_stealing_test!(aes128_xts_dec_vec18_test, "ieee_vec18", Aes128); + +// Those tests checks that the custom methods works without ciphertext stealing +block_mode_enc_stealing_test!(aes128_xts_enc_custom_api_test, "ieee_vec1", Aes128); +block_mode_dec_stealing_test!(aes128_xts_dec_custom_api_test, "ieee_vec1", Aes128); + +block_mode_enc_test!(aes128_xts_enc_vec19_test, "ieee_vec19", Encryptor); +block_mode_dec_test!(aes128_xts_dec_vec19_test, "ieee_vec19", Decryptor); diff --git a/xts/tests/data/ieee_vec1.blb b/xts/tests/data/ieee_vec1.blb new file mode 100644 index 0000000..076cc91 Binary files /dev/null and b/xts/tests/data/ieee_vec1.blb differ diff --git a/xts/tests/data/ieee_vec10.blb b/xts/tests/data/ieee_vec10.blb new file mode 100644 index 0000000..b59545a Binary files /dev/null and b/xts/tests/data/ieee_vec10.blb differ diff --git a/xts/tests/data/ieee_vec11.blb b/xts/tests/data/ieee_vec11.blb new file mode 100644 index 0000000..2503214 Binary files /dev/null and b/xts/tests/data/ieee_vec11.blb differ diff --git a/xts/tests/data/ieee_vec12.blb b/xts/tests/data/ieee_vec12.blb new file mode 100644 index 0000000..c8bb8d1 Binary files /dev/null and b/xts/tests/data/ieee_vec12.blb differ diff --git a/xts/tests/data/ieee_vec13.blb b/xts/tests/data/ieee_vec13.blb new file mode 100644 index 0000000..d2ddca8 Binary files /dev/null and b/xts/tests/data/ieee_vec13.blb differ diff --git a/xts/tests/data/ieee_vec14.blb b/xts/tests/data/ieee_vec14.blb new file mode 100644 index 0000000..2d36633 Binary files /dev/null and b/xts/tests/data/ieee_vec14.blb differ diff --git a/xts/tests/data/ieee_vec15.blb b/xts/tests/data/ieee_vec15.blb new file mode 100644 index 0000000..98b9064 Binary files /dev/null and b/xts/tests/data/ieee_vec15.blb differ diff --git a/xts/tests/data/ieee_vec16.blb b/xts/tests/data/ieee_vec16.blb new file mode 100644 index 0000000..aa1ad76 Binary files /dev/null and b/xts/tests/data/ieee_vec16.blb differ diff --git a/xts/tests/data/ieee_vec17.blb b/xts/tests/data/ieee_vec17.blb new file mode 100644 index 0000000..861d33e Binary files /dev/null and b/xts/tests/data/ieee_vec17.blb differ diff --git a/xts/tests/data/ieee_vec18.blb b/xts/tests/data/ieee_vec18.blb new file mode 100644 index 0000000..265504a Binary files /dev/null and b/xts/tests/data/ieee_vec18.blb differ diff --git a/xts/tests/data/ieee_vec19.blb b/xts/tests/data/ieee_vec19.blb new file mode 100644 index 0000000..dbcd357 Binary files /dev/null and b/xts/tests/data/ieee_vec19.blb differ diff --git a/xts/tests/data/ieee_vec2.blb b/xts/tests/data/ieee_vec2.blb new file mode 100644 index 0000000..304038c Binary files /dev/null and b/xts/tests/data/ieee_vec2.blb differ diff --git a/xts/tests/data/ieee_vec3.blb b/xts/tests/data/ieee_vec3.blb new file mode 100644 index 0000000..7a0a71a Binary files /dev/null and b/xts/tests/data/ieee_vec3.blb differ diff --git a/xts/tests/data/ieee_vec4.blb b/xts/tests/data/ieee_vec4.blb new file mode 100644 index 0000000..e705443 Binary files /dev/null and b/xts/tests/data/ieee_vec4.blb differ diff --git a/xts/tests/data/ieee_vec5.blb b/xts/tests/data/ieee_vec5.blb new file mode 100644 index 0000000..0bc223b Binary files /dev/null and b/xts/tests/data/ieee_vec5.blb differ diff --git a/xts/tests/data/ieee_vec6.blb b/xts/tests/data/ieee_vec6.blb new file mode 100644 index 0000000..66e8cb1 Binary files /dev/null and b/xts/tests/data/ieee_vec6.blb differ diff --git a/xts/tests/data/ieee_vec7.blb b/xts/tests/data/ieee_vec7.blb new file mode 100644 index 0000000..73cb712 Binary files /dev/null and b/xts/tests/data/ieee_vec7.blb differ diff --git a/xts/tests/data/ieee_vec8.blb b/xts/tests/data/ieee_vec8.blb new file mode 100644 index 0000000..a8a408d Binary files /dev/null and b/xts/tests/data/ieee_vec8.blb differ diff --git a/xts/tests/data/ieee_vec9.blb b/xts/tests/data/ieee_vec9.blb new file mode 100644 index 0000000..9f63b1c Binary files /dev/null and b/xts/tests/data/ieee_vec9.blb differ diff --git a/xts/tests/macros.rs b/xts/tests/macros.rs new file mode 100644 index 0000000..d684348 --- /dev/null +++ b/xts/tests/macros.rs @@ -0,0 +1,94 @@ +/// Pasted from the `cipher` crate and adapted to support XTS tests + +#[macro_export] +macro_rules! block_mode_enc_stealing_test { + ($name:ident, $test_name:expr, $cipher:ty $(,)?) => { + #[test] + fn $name() { + use cipher::{blobby::Blob4Iterator, KeyIvInit}; + + use xts::Encryptor; + + fn run_test(i: usize, key: &[u8], iv: &[u8], pt: &[u8], ct: &[u8]) { + assert_eq!(pt.len(), ct.len()); + // test block-by-block processing + + // MODIFICATION: We hardcode XTS encryptor here + let mut state = + as KeyIvInit>::new_from_slices(key, iv).unwrap(); + + let mut out = vec![0u8; ct.len()]; + + // MODIFICATION: We don't split the block and we call encrypt_directly + state.encrypt_b2b(pt, &mut out).unwrap(); + + // MODIFICATION: Crash here so we can get the actual output + if out != ct { + panic!( + "\n\ + Failed test №{}\n\ + key:\t{:?}\n\ + iv:\t{:?}\n\ + plaintext:\t{:?}\n\ + ciphertext:\t{:?}\n\ + actual_ct:\t{:?}\n", + i, key, iv, pt, ct, out + ); + } + } + + let data = include_bytes!(concat!("data/", $test_name, ".blb")); + for (i, row) in Blob4Iterator::new(data).unwrap().enumerate() { + let [key, iv, pt, ct] = row.unwrap(); + run_test(i, key, iv, pt, ct); + } + } + }; +} + +/// Define block mode decryption test +#[macro_export] +macro_rules! block_mode_dec_stealing_test { + ($name:ident, $test_name:expr, $cipher:ty $(,)?) => { + #[test] + fn $name() { + use cipher::{blobby::Blob4Iterator, KeyIvInit}; + + use xts::Decryptor; + + fn run_test(i: usize, key: &[u8], iv: &[u8], pt: &[u8], ct: &[u8]) { + assert_eq!(pt.len(), ct.len()); + // test block-by-block processing + + // MODIFICATION: We hardcode XTS encryptor here + let mut state = + as KeyIvInit>::new_from_slices(key, iv).unwrap(); + + let mut out = vec![0u8; ct.len()]; + + // MODIFICATION: We don't split the block and we call encrypt_directly + state.decrypt_b2b(ct, &mut out).unwrap(); + + // MODIFICATION: Crash here so we can get the actual output + if out != pt { + panic!( + "\n\ + Failed test №{}\n\ + key:\t{:?}\n\ + iv:\t{:?}\n\ + plaintext:\t{:?}\n\ + ciphertext:\t{:?}\n\ + actual_pt:\t{:?}\n", + i, key, iv, pt, ct, out + ); + } + } + + let data = include_bytes!(concat!("data/", $test_name, ".blb")); + for (i, row) in Blob4Iterator::new(data).unwrap().enumerate() { + let [key, iv, pt, ct] = row.unwrap(); + run_test(i, key, iv, pt, ct); + } + } + }; +}