diff --git a/.github/workflows/cts.yaml b/.github/workflows/cts.yaml new file mode 100644 index 0000000..88eda00 --- /dev/null +++ b/.github/workflows/cts.yaml @@ -0,0 +1,60 @@ +name: cts + +on: + pull_request: + paths: + - "cts/**" + - "Cargo.*" + push: + branches: master + +defaults: + run: + working-directory: cts + +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 d899f9d..6c37f55 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,17 @@ # It is not intended for manual editing. version = 3 +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher 0.4.4", + "cpufeatures", +] + [[package]] name = "aes" version = "0.9.0-pre.2" @@ -9,25 +20,34 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7856582c758ade85d71daf27ec6bcea6c1c73913692b07b8dffea2dc03531c9" dependencies = [ "cfg-if", - "cipher", + "cipher 0.5.0-pre.7", "cpufeatures", ] +[[package]] +name = "belt-block" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9aa1eef3994e2ccd304a78fe3fea4a73e5792007f85f09b79bb82143ca5f82b" +dependencies = [ + "cipher 0.4.4", +] + [[package]] name = "belt-block" version = "0.2.0-pre.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6df0a14d60362d7b6041d3fe85dfd787ced16c4928f93d72152142c67d01d0bc" dependencies = [ - "cipher", + "cipher 0.5.0-pre.7", ] [[package]] name = "belt-ctr" version = "0.2.0-pre" dependencies = [ - "belt-block", - "cipher", + "belt-block 0.2.0-pre.2", + "cipher 0.5.0-pre.7", "hex-literal", ] @@ -50,8 +70,8 @@ dependencies = [ name = "cbc" version = "0.2.0-pre.2" dependencies = [ - "aes", - "cipher", + "aes 0.9.0-pre.2", + "cipher 0.5.0-pre.7", "hex-literal", ] @@ -59,9 +79,9 @@ dependencies = [ name = "cfb-mode" version = "0.9.0-pre" dependencies = [ - "aes", - "belt-block", - "cipher", + "aes 0.9.0-pre.2", + "belt-block 0.2.0-pre.2", + "cipher 0.5.0-pre.7", "hex-literal", ] @@ -69,8 +89,8 @@ dependencies = [ name = "cfb8" version = "0.9.0-pre" dependencies = [ - "aes", - "cipher", + "aes 0.9.0-pre.2", + "cipher 0.5.0-pre.7", "hex-literal", ] @@ -80,6 +100,17 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "blobby", + "crypto-common 0.1.6", + "inout 0.1.3", +] + [[package]] name = "cipher" version = "0.5.0-pre.7" @@ -87,20 +118,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b1425e6ce000f05a73096556cabcfb6a10a3ffe3bb4d75416ca8f00819c0b6a" dependencies = [ "blobby", - "crypto-common", - "inout", + "crypto-common 0.2.0-rc.1", + "inout 0.2.0-rc.0", "zeroize", ] [[package]] name = "cpufeatures" -version = "0.2.13" +version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "51e852e6dc9a5bed1fae92dd2375037bf2b768725bf3be87811edee3249d09ad" +checksum = "608697df725056feaccfa42cffdaeeec3fccc4ffc38358ecd19b243e716a78e0" dependencies = [ "libc", ] +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "crypto-common" version = "0.2.0-rc.1" @@ -116,13 +157,33 @@ dependencies = [ name = "ctr" version = "0.10.0-pre.2" dependencies = [ - "aes", - "cipher", + "aes 0.9.0-pre.2", + "cipher 0.5.0-pre.7", "hex-literal", "kuznyechik", "magma", ] +[[package]] +name = "cts" +version = "0.1.0" +dependencies = [ + "aes 0.8.4", + "belt-block 0.1.2", + "cipher 0.4.4", + "hex-literal", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "getrandom" version = "0.2.15" @@ -153,11 +214,20 @@ dependencies = [ name = "ige" version = "0.2.0-pre" dependencies = [ - "aes", - "cipher", + "aes 0.9.0-pre.2", + "cipher 0.5.0-pre.7", "hex-literal", ] +[[package]] +name = "inout" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0c10553d664a4d0bcff9f4215d0aac67a639cc68ef660840afe309b807bc9f5" +dependencies = [ + "generic-array", +] + [[package]] name = "inout" version = "0.2.0-rc.0" @@ -175,14 +245,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bd136ca56393426d0aeca01643adef06b1f30d667fdebf31f7cf11724cbd9051" dependencies = [ "cfg-if", - "cipher", + "cipher 0.5.0-pre.7", ] [[package]] name = "libc" -version = "0.2.155" +version = "0.2.161" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" +checksum = "8e9489c2807c139ffd9c1794f4af0ebe86a828db53ecdc7fea2111d0fed085d1" [[package]] name = "magma" @@ -190,15 +260,15 @@ version = "0.10.0-pre.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9fd466f879a2c01f141f168c4e045a26dca5a60aef79efa8bb96e9c701bb8ea" dependencies = [ - "cipher", + "cipher 0.5.0-pre.7", ] [[package]] name = "ofb" version = "0.7.0-pre" dependencies = [ - "aes", - "cipher", + "aes 0.9.0-pre.2", + "cipher 0.5.0-pre.7", "hex-literal", ] @@ -206,8 +276,8 @@ dependencies = [ name = "pcbc" version = "0.2.0-pre" dependencies = [ - "aes", - "cipher", + "aes 0.9.0-pre.2", + "cipher 0.5.0-pre.7", "hex-literal", ] @@ -226,6 +296,12 @@ version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" diff --git a/Cargo.toml b/Cargo.toml index 4db8e0a..adffbe5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "2" -members = ["belt-ctr", "cbc", "cfb8", "cfb-mode", "ctr", "ige", "ofb", "pcbc"] +members = ["belt-ctr", "cbc", "cts", "cfb8", "cfb-mode", "ctr", "ige", "ofb", "pcbc"] [profile.dev] opt-level = 2 diff --git a/cts/CHANGELOG.md b/cts/CHANGELOG.md new file mode 100644 index 0000000..5d70799 --- /dev/null +++ b/cts/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 (2024-11-01) +- Initial release ([#70]) + +[#70]: https://github.com/RustCrypto/block-modes/pull/70 \ No newline at end of file diff --git a/cts/Cargo.toml b/cts/Cargo.toml new file mode 100644 index 0000000..cc65ad3 --- /dev/null +++ b/cts/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "cts" +version = "0.1.0" +description = "Generic implementation of the ciphertext stealing block modes of operation" +authors = ["RustCrypto Developers"] +license = "MIT OR Apache-2.0" +edition = "2021" +rust-version = "1.81" +readme = "README.md" +documentation = "https://docs.rs/cts" +repository = "https://github.com/RustCrypto/block-modes" +keywords = ["crypto", "block-mode", "ciphers"] +categories = ["cryptography", "no-std"] + +[dependencies] +cipher = "0.4.2" + +[dev-dependencies] +cipher = { version = "0.4.2", features = ["dev"] } +hex-literal = "0.4" +aes = "0.8" +belt-block = "0.1" + +[package.metadata.docs.rs] +all-features = true +rustdoc-args = ["--cfg", "docsrs"] diff --git a/cts/LICENSE-APACHE b/cts/LICENSE-APACHE new file mode 100644 index 0000000..78173fa --- /dev/null +++ b/cts/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/cts/LICENSE-MIT b/cts/LICENSE-MIT new file mode 100644 index 0000000..e92e140 --- /dev/null +++ b/cts/LICENSE-MIT @@ -0,0 +1,26 @@ +Copyright (c) 2024 RustCrypto Developers +Copyright (c) 2024 Artyom Pavlov + +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/cts/README.md b/cts/README.md new file mode 100644 index 0000000..93f9c77 --- /dev/null +++ b/cts/README.md @@ -0,0 +1,76 @@ +# RustCrypto: CTS + +[![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 [ciphertext stealing] block cipher modes of operation. + +## Example +```rust +use aes::Aes128; +use cts::{CbcCs3Dec, CbcCs3Enc, Decrypt, Encrypt, KeyIvInit}; +use hex_literal::hex; + +let key = [0x42; 16]; +let iv = [0x24; 16]; + +// Message must be bigger than block size (16 bytes for AES-128) +let msg = b"Lorem ipsum dolor sit amet"; +let mut buf = [0u8; 26]; + +let enc_mode = CbcCs3Enc::::new(&key.into(), &iv.into()); +enc_mode.encrypt_b2b(msg, &mut buf).unwrap(); +assert_eq!(buf, hex!("68ec97f172e322fdd38e74fca65cee52658ae2124beb5e4e5315")); + +let dec_mode = CbcCs3Dec::::new(&key.into(), &iv.into()); +dec_mode.decrypt(&mut buf).unwrap(); +assert_eq!(&buf, msg); +``` + +## Minimum Supported Rust Version + +Rust **1.57** 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/cts.svg +[crate-link]: https://crates.io/crates/cts +[docs-image]: https://docs.rs/cts/badge.svg +[docs-link]: https://docs.rs/cts/ +[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg +[rustc-image]: https://img.shields.io/badge/rustc-1.56+-blue.svg +[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg +[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/308460-block-modes +[build-image]: https://github.com/RustCrypto/block-modes/workflows/cts/badge.svg?branch=master&event=push +[build-link]: https://github.com/RustCrypto/block-modes/actions?query=workflow%3Acts+branch%3Amaster + +[//]: # (general links) + +[ciphertext stealing]: https://en.wikipedia.org/wiki/Ciphertext_stealing diff --git a/cts/src/cbc_cs1_dec.rs b/cts/src/cbc_cs1_dec.rs new file mode 100644 index 0000000..abbf32e --- /dev/null +++ b/cts/src/cbc_cs1_dec.rs @@ -0,0 +1,88 @@ +use crate::{cbc_dec, xor, Decrypt, Error}; +use cipher::{ + crypto_common::InnerUser, generic_array::GenericArray, inout::InOutBuf, typenum::Unsigned, + ArrayLength, Block, BlockBackend, BlockClosure, BlockDecrypt, BlockSizeUser, InnerIvInit, + IvSizeUser, +}; + +/// The CBC-CS-1 ciphertext stealing mode decryptor. +#[derive(Clone)] +pub struct CbcCs1Dec { + cipher: C, + iv: Block, +} + +impl InnerUser for CbcCs1Dec { + type Inner = C; +} + +impl IvSizeUser for CbcCs1Dec { + type IvSize = C::BlockSize; +} + +impl InnerIvInit for CbcCs1Dec { + fn inner_iv_init(cipher: Self::Inner, iv: &cipher::Iv) -> Self { + Self { + cipher, + iv: iv.clone(), + } + } +} + +impl Decrypt for CbcCs1Dec { + fn decrypt_inout(self, buf: InOutBuf<'_, '_, u8>) -> Result<(), Error> { + if buf.len() < C::BlockSize::USIZE { + return Err(Error); + } + let Self { cipher, iv } = self; + cipher.decrypt_with_backend(Closure { iv, buf }); + Ok(()) + } +} + +struct Closure<'a, BS: ArrayLength> { + iv: GenericArray, + buf: InOutBuf<'a, 'a, u8>, +} + +impl> BlockSizeUser for Closure<'_, BS> { + type BlockSize = BS; +} + +impl> BlockClosure for Closure<'_, BS> { + fn call>(self, cipher: &mut B) { + let Self { mut iv, mut buf } = self; + + let (mut blocks, tail) = buf.reborrow().into_chunks(); + + if !tail.is_empty() { + let mid = blocks.len() - 1; + blocks = blocks.split_at(mid).0; + }; + + cbc_dec(cipher, &mut iv, blocks); + + if tail.is_empty() { + return; + } + + let tail_len = tail.len(); + let bs = B::BlockSize::USIZE; + let mid = buf.len() - (bs + tail_len); + let mut rem = buf.split_at(mid).1; + + let n = rem.len() - bs; + let mut block1 = Block::::clone_from_slice(&rem.get_in()[..bs]); + let mut block2 = Block::::clone_from_slice(&rem.get_in()[n..]); + + cipher.proc_block_inplace(&mut block2); + block1[n..].copy_from_slice(&block2[n..]); + xor(&mut block2, &block1); + + cipher.proc_block_inplace(&mut block1); + xor(&mut block1, &iv); + + rem.get_out()[..bs].copy_from_slice(&block1); + rem.get_out()[bs..].copy_from_slice(&block2[..n]); + } +} diff --git a/cts/src/cbc_cs1_enc.rs b/cts/src/cbc_cs1_enc.rs new file mode 100644 index 0000000..9b2652c --- /dev/null +++ b/cts/src/cbc_cs1_enc.rs @@ -0,0 +1,71 @@ +use crate::{cbc_enc, xor, Encrypt, Error}; +use cipher::{ + crypto_common::InnerUser, generic_array::GenericArray, inout::InOutBuf, typenum::Unsigned, + ArrayLength, Block, BlockBackend, BlockClosure, BlockEncrypt, BlockSizeUser, InnerIvInit, + IvSizeUser, +}; + +/// The CBC-CS-1 ciphertext stealing mode encryptor. +#[derive(Clone)] +pub struct CbcCs1Enc { + cipher: C, + iv: Block, +} + +impl InnerUser for CbcCs1Enc { + type Inner = C; +} + +impl IvSizeUser for CbcCs1Enc { + type IvSize = C::BlockSize; +} + +impl InnerIvInit for CbcCs1Enc { + fn inner_iv_init(cipher: Self::Inner, iv: &cipher::Iv) -> Self { + Self { + cipher, + iv: iv.clone(), + } + } +} + +impl Encrypt for CbcCs1Enc { + fn encrypt_inout(self, buf: InOutBuf<'_, '_, u8>) -> Result<(), Error> { + if buf.len() < C::BlockSize::USIZE { + return Err(Error); + } + let Self { cipher, iv } = self; + cipher.encrypt_with_backend(Closure { iv, buf }); + Ok(()) + } +} + +struct Closure<'a, BS: ArrayLength> { + iv: GenericArray, + buf: InOutBuf<'a, 'a, u8>, +} + +impl> BlockSizeUser for Closure<'_, BS> { + type BlockSize = BS; +} + +impl> BlockClosure for Closure<'_, BS> { + fn call>(self, cipher: &mut B) { + let Self { mut iv, mut buf } = self; + let (blocks, tail) = buf.reborrow().into_chunks(); + + cbc_enc(cipher, &mut iv, blocks); + + if tail.is_empty() { + return; + } + + let mut block = Block::::default(); + block[..tail.len()].copy_from_slice(tail.get_in()); + xor(&mut block, &iv); + cipher.proc_block_inplace(&mut block); + + let pos = buf.len() - B::BlockSize::USIZE; + buf.get_out()[pos..].copy_from_slice(&block); + } +} diff --git a/cts/src/cbc_cs2_dec.rs b/cts/src/cbc_cs2_dec.rs new file mode 100644 index 0000000..53063c1 --- /dev/null +++ b/cts/src/cbc_cs2_dec.rs @@ -0,0 +1,90 @@ +use crate::{cbc_dec, xor, Decrypt, Error}; +use cipher::{ + crypto_common::InnerUser, generic_array::GenericArray, inout::InOutBuf, typenum::Unsigned, + ArrayLength, Block, BlockBackend, BlockClosure, BlockDecrypt, BlockSizeUser, InnerIvInit, + IvSizeUser, +}; + +/// The CBC-CS-2 ciphertext stealing mode decryptor. +#[derive(Clone)] +pub struct CbcCs2Dec { + cipher: C, + iv: Block, +} + +impl InnerUser for CbcCs2Dec { + type Inner = C; +} + +impl IvSizeUser for CbcCs2Dec { + type IvSize = C::BlockSize; +} + +impl InnerIvInit for CbcCs2Dec { + fn inner_iv_init(cipher: Self::Inner, iv: &cipher::Iv) -> Self { + Self { + cipher, + iv: iv.clone(), + } + } +} + +impl Decrypt for CbcCs2Dec { + fn decrypt_inout(self, buf: InOutBuf<'_, '_, u8>) -> Result<(), Error> { + if buf.len() < C::BlockSize::USIZE { + return Err(Error); + } + let Self { cipher, iv } = self; + cipher.decrypt_with_backend(Closure { iv, buf }); + Ok(()) + } +} + +struct Closure<'a, BS: ArrayLength> { + iv: GenericArray, + buf: InOutBuf<'a, 'a, u8>, +} + +impl> BlockSizeUser for Closure<'_, BS> { + type BlockSize = BS; +} + +impl> BlockClosure for Closure<'_, BS> { + fn call>(self, cipher: &mut B) { + let Self { mut iv, mut buf } = self; + + let (mut blocks, tail) = buf.reborrow().into_chunks(); + + if !tail.is_empty() { + let mid = blocks.len() - 1; + blocks = blocks.split_at(mid).0; + }; + + cbc_dec(cipher, &mut iv, blocks); + + if tail.is_empty() { + return; + } + + let tail_len = tail.len(); + let bs = B::BlockSize::USIZE; + let mid = buf.len() - (bs + tail_len); + let mut rem = buf.split_at(mid).1; + + let n = rem.len() - bs; + let mut block1 = Block::::clone_from_slice(&rem.get_in()[..bs]); + cipher.proc_block_inplace(&mut block1); + + let mut block2 = Block::::default(); + block2[..n].copy_from_slice(&rem.get_in()[bs..]); + block2[n..].copy_from_slice(&block1[n..]); + + xor(&mut block1, &block2); + + cipher.proc_block_inplace(&mut block2); + xor(&mut block2, &iv); + + rem.get_out()[..bs].copy_from_slice(&block2); + rem.get_out()[bs..].copy_from_slice(&block1[..n]); + } +} diff --git a/cts/src/cbc_cs2_enc.rs b/cts/src/cbc_cs2_enc.rs new file mode 100644 index 0000000..2ebedfb --- /dev/null +++ b/cts/src/cbc_cs2_enc.rs @@ -0,0 +1,72 @@ +use crate::{cbc_enc, xor, Encrypt, Error}; +use cipher::{ + crypto_common::InnerUser, generic_array::GenericArray, inout::InOutBuf, typenum::Unsigned, + ArrayLength, Block, BlockBackend, BlockClosure, BlockEncrypt, BlockSizeUser, InnerIvInit, + IvSizeUser, +}; + +/// The CBC-CS-2 ciphertext stealing mode encryptor. +#[derive(Clone)] +pub struct CbcCs2Enc { + cipher: C, + iv: Block, +} + +impl InnerUser for CbcCs2Enc { + type Inner = C; +} + +impl IvSizeUser for CbcCs2Enc { + type IvSize = C::BlockSize; +} + +impl InnerIvInit for CbcCs2Enc { + fn inner_iv_init(cipher: Self::Inner, iv: &cipher::Iv) -> Self { + Self { + cipher, + iv: iv.clone(), + } + } +} + +impl Encrypt for CbcCs2Enc { + fn encrypt_inout(self, buf: InOutBuf<'_, '_, u8>) -> Result<(), Error> { + if buf.len() < C::BlockSize::USIZE { + return Err(Error); + } + let Self { cipher, iv } = self; + cipher.encrypt_with_backend(Closure { iv, buf }); + Ok(()) + } +} + +struct Closure<'a, BS: ArrayLength> { + iv: GenericArray, + buf: InOutBuf<'a, 'a, u8>, +} + +impl> BlockSizeUser for Closure<'_, BS> { + type BlockSize = BS; +} + +impl> BlockClosure for Closure<'_, BS> { + fn call>(self, cipher: &mut B) { + let Self { mut iv, mut buf } = self; + let (mut blocks, mut tail) = buf.reborrow().into_chunks(); + + cbc_enc(cipher, &mut iv, blocks.reborrow()); + + if tail.is_empty() { + return; + } + + let mut block = Block::::default(); + block[..tail.len()].copy_from_slice(tail.get_in()); + xor(&mut block, &iv); + cipher.proc_block_inplace(&mut block); + + let penult_block = core::mem::replace(blocks.get_out().last_mut().unwrap(), block); + let tail_val = &penult_block[..tail.len()]; + tail.get_out().copy_from_slice(tail_val); + } +} diff --git a/cts/src/cbc_cs3_dec.rs b/cts/src/cbc_cs3_dec.rs new file mode 100644 index 0000000..dafc509 --- /dev/null +++ b/cts/src/cbc_cs3_dec.rs @@ -0,0 +1,82 @@ +use crate::{cbc_dec, xor, Decrypt, Error}; +use cipher::{ + crypto_common::InnerUser, generic_array::GenericArray, inout::InOutBuf, typenum::Unsigned, + ArrayLength, Block, BlockBackend, BlockClosure, BlockDecrypt, BlockSizeUser, InnerIvInit, + IvSizeUser, +}; + +/// The CBC-CS-3 ciphertext stealing mode decryptor. +#[derive(Clone)] +pub struct CbcCs3Dec { + cipher: C, + iv: Block, +} + +impl InnerUser for CbcCs3Dec { + type Inner = C; +} + +impl IvSizeUser for CbcCs3Dec { + type IvSize = C::BlockSize; +} + +impl InnerIvInit for CbcCs3Dec { + fn inner_iv_init(cipher: Self::Inner, iv: &cipher::Iv) -> Self { + Self { + cipher, + iv: iv.clone(), + } + } +} + +impl Decrypt for CbcCs3Dec { + fn decrypt_inout(self, buf: InOutBuf<'_, '_, u8>) -> Result<(), Error> { + if buf.len() < C::BlockSize::USIZE { + return Err(Error); + } + let Self { cipher, iv } = self; + cipher.decrypt_with_backend(Closure { iv, buf }); + Ok(()) + } +} + +struct Closure<'a, BS: ArrayLength> { + iv: GenericArray, + buf: InOutBuf<'a, 'a, u8>, +} + +impl> BlockSizeUser for Closure<'_, BS> { + type BlockSize = BS; +} + +impl> BlockClosure for Closure<'_, BS> { + fn call>(self, cipher: &mut B) { + let Self { mut iv, buf } = self; + + let bs = B::BlockSize::USIZE; + let blocks_len = buf.len().div_ceil(bs); + let main_blocks = blocks_len.saturating_sub(2); + + let (blocks, mut tail) = buf.split_at(bs * main_blocks); + let (blocks, rem) = blocks.into_chunks(); + debug_assert_eq!(rem.len(), 0); + + cbc_dec(cipher, &mut iv, blocks); + + let n = tail.len() - bs; + let mut block1 = GenericArray::clone_from_slice(&tail.get_in()[..bs]); + cipher.proc_block_inplace(&mut block1); + + let mut block2 = GenericArray::::default(); + block2[..n].copy_from_slice(&tail.get_in()[bs..]); + block2[n..].copy_from_slice(&block1[n..]); + xor(&mut block1, &block2); + + cipher.proc_block_inplace(&mut block2); + xor(&mut block2, &iv); + + let (l, r) = tail.get_out().split_at_mut(bs); + l.copy_from_slice(&block2); + r.copy_from_slice(&block1[..n]); + } +} diff --git a/cts/src/cbc_cs3_enc.rs b/cts/src/cbc_cs3_enc.rs new file mode 100644 index 0000000..e00bebc --- /dev/null +++ b/cts/src/cbc_cs3_enc.rs @@ -0,0 +1,77 @@ +use crate::{cbc_enc, xor, Encrypt, Error}; +use cipher::{ + crypto_common::InnerUser, generic_array::GenericArray, inout::InOutBuf, typenum::Unsigned, + ArrayLength, Block, BlockBackend, BlockClosure, BlockEncrypt, BlockSizeUser, InnerIvInit, + IvSizeUser, +}; + +/// The CBC-CS-3 ciphertext stealing mode encryptor. +#[derive(Clone)] +pub struct CbcCs3Enc { + cipher: C, + iv: Block, +} + +impl InnerUser for CbcCs3Enc { + type Inner = C; +} + +impl IvSizeUser for CbcCs3Enc { + type IvSize = C::BlockSize; +} + +impl InnerIvInit for CbcCs3Enc { + fn inner_iv_init(cipher: Self::Inner, iv: &cipher::Iv) -> Self { + Self { + cipher, + iv: iv.clone(), + } + } +} + +impl Encrypt for CbcCs3Enc { + fn encrypt_inout(self, buf: InOutBuf<'_, '_, u8>) -> Result<(), Error> { + if buf.len() < C::BlockSize::USIZE { + return Err(Error); + } + let Self { cipher, iv } = self; + cipher.encrypt_with_backend(Closure { iv, buf }); + Ok(()) + } +} + +struct Closure<'a, BS: ArrayLength> { + iv: GenericArray, + buf: InOutBuf<'a, 'a, u8>, +} + +impl> BlockSizeUser for Closure<'_, BS> { + type BlockSize = BS; +} + +impl> BlockClosure for Closure<'_, BS> { + fn call>(self, cipher: &mut B) { + let Self { mut iv, mut buf } = self; + let (mut blocks, mut tail) = buf.reborrow().into_chunks(); + + cbc_enc(cipher, &mut iv, blocks.reborrow()); + + if tail.is_empty() && blocks.len() > 1 { + let blocks = blocks.get_out(); + let (last, rest) = blocks.split_last_mut().unwrap(); + let (penultimate, _) = rest.split_last_mut().unwrap(); + core::mem::swap(penultimate, last); + } else { + let mut block = Block::::default(); + block[..tail.len()].copy_from_slice(tail.get_in()); + xor(&mut block, &iv); + cipher.proc_block_inplace(&mut block); + + let penult_block = blocks.get_out().last_mut().unwrap(); + let val = core::mem::replace(penult_block, block); + + let tail_val = &val[..tail.len()]; + tail.get_out().copy_from_slice(tail_val); + } + } +} diff --git a/cts/src/ecb_cs1_dec.rs b/cts/src/ecb_cs1_dec.rs new file mode 100644 index 0000000..5aeaf02 --- /dev/null +++ b/cts/src/ecb_cs1_dec.rs @@ -0,0 +1,86 @@ +use super::{ecb_dec, Decrypt, Error}; +use cipher::{ + crypto_common::{InnerInit, InnerUser}, + inout::InOutBuf, + typenum::Unsigned, + ArrayLength, Block, BlockBackend, BlockClosure, BlockDecrypt, BlockSizeUser, IvSizeUser, +}; +use core::marker::PhantomData; + +/// The ECB-CS-1 ciphertext stealing mode decryptor. +#[derive(Clone)] +pub struct EcbCs1Dec { + cipher: C, +} + +impl InnerUser for EcbCs1Dec { + type Inner = C; +} + +impl IvSizeUser for EcbCs1Dec { + type IvSize = C::BlockSize; +} + +impl InnerInit for EcbCs1Dec { + fn inner_init(cipher: Self::Inner) -> Self { + Self { cipher } + } +} + +impl Decrypt for EcbCs1Dec { + fn decrypt_inout(self, buf: InOutBuf<'_, '_, u8>) -> Result<(), Error> { + if buf.len() < C::BlockSize::USIZE { + return Err(Error); + } + self.cipher.decrypt_with_backend(Closure { + buf, + _pd: PhantomData, + }); + Ok(()) + } +} + +struct Closure<'a, BS: ArrayLength> { + buf: InOutBuf<'a, 'a, u8>, + _pd: PhantomData, +} + +impl> BlockSizeUser for Closure<'_, BS> { + type BlockSize = BS; +} + +impl> BlockClosure for Closure<'_, BS> { + fn call>(self, cipher: &mut B) { + let Self { mut buf, _pd } = self; + + let (mut blocks, tail) = buf.reborrow().into_chunks(); + + if !tail.is_empty() { + let mid = blocks.len() - 1; + blocks = blocks.split_at(mid).0; + }; + + ecb_dec(cipher, blocks); + + if tail.is_empty() { + return; + } + + let tail_len = tail.len(); + let bs = B::BlockSize::USIZE; + let mid = buf.len() - (bs + tail_len); + let mut rem = buf.split_at(mid).1; + + let n = rem.len() - bs; + let mut block1 = Block::::clone_from_slice(&rem.get_in()[..bs]); + let mut block2 = Block::::clone_from_slice(&rem.get_in()[n..]); + + cipher.proc_block_inplace(&mut block2); + block1[n..].copy_from_slice(&block2[n..]); + + cipher.proc_block_inplace(&mut block1); + + rem.get_out()[..bs].copy_from_slice(&block1); + rem.get_out()[bs..].copy_from_slice(&block2[..n]); + } +} diff --git a/cts/src/ecb_cs1_enc.rs b/cts/src/ecb_cs1_enc.rs new file mode 100644 index 0000000..ddc243d --- /dev/null +++ b/cts/src/ecb_cs1_enc.rs @@ -0,0 +1,75 @@ +use crate::{ecb_enc, Encrypt, Error}; +use cipher::{ + crypto_common::{InnerInit, InnerUser}, + inout::InOutBuf, + typenum::Unsigned, + ArrayLength, Block, BlockBackend, BlockClosure, BlockEncrypt, BlockSizeUser, IvSizeUser, +}; +use core::marker::PhantomData; + +/// The ECB-CS-1 ciphertext stealing mode encryptor. +#[derive(Clone)] +pub struct EcbCs1Enc { + cipher: C, +} + +impl InnerUser for EcbCs1Enc { + type Inner = C; +} + +impl IvSizeUser for EcbCs1Enc { + type IvSize = C::BlockSize; +} + +impl InnerInit for EcbCs1Enc { + fn inner_init(cipher: Self::Inner) -> Self { + Self { cipher } + } +} + +impl Encrypt for EcbCs1Enc { + fn encrypt_inout(self, buf: InOutBuf<'_, '_, u8>) -> Result<(), Error> { + if buf.len() < C::BlockSize::USIZE { + return Err(Error); + } + self.cipher.encrypt_with_backend(Closure { + buf, + _pd: PhantomData, + }); + Ok(()) + } +} + +struct Closure<'a, BS: ArrayLength> { + buf: InOutBuf<'a, 'a, u8>, + _pd: PhantomData, +} + +impl> BlockSizeUser for Closure<'_, BS> { + type BlockSize = BS; +} + +impl> BlockClosure for Closure<'_, BS> { + fn call>(self, cipher: &mut B) { + let Self { mut buf, _pd } = self; + let (mut blocks, tail) = buf.reborrow().into_chunks(); + + ecb_enc(cipher, blocks.reborrow()); + + if tail.is_empty() { + return; + } + + let last_block = blocks.get_out().last_mut().unwrap(); + let mut block = Block::::default(); + + let n = tail.len(); + + block[..n].copy_from_slice(tail.get_in()); + block[n..].copy_from_slice(&last_block[n..]); + cipher.proc_block_inplace(&mut block); + + let pos = buf.len() - block.len(); + buf.get_out()[pos..].copy_from_slice(&block); + } +} diff --git a/cts/src/ecb_cs2_dec.rs b/cts/src/ecb_cs2_dec.rs new file mode 100644 index 0000000..0bb2010 --- /dev/null +++ b/cts/src/ecb_cs2_dec.rs @@ -0,0 +1,76 @@ +use crate::{ecb_dec, Decrypt, Error}; +use cipher::{ + crypto_common::{InnerInit, InnerUser}, + inout::InOutBuf, + typenum::Unsigned, + ArrayLength, Block, BlockBackend, BlockClosure, BlockDecrypt, BlockSizeUser, IvSizeUser, +}; +use core::marker::PhantomData; + +/// The ECB-CS-2 ciphertext stealing mode decryptor. +#[derive(Clone)] +pub struct EcbCs2Dec { + cipher: C, +} + +impl InnerUser for EcbCs2Dec { + type Inner = C; +} + +impl IvSizeUser for EcbCs2Dec { + type IvSize = C::BlockSize; +} + +impl InnerInit for EcbCs2Dec { + fn inner_init(cipher: Self::Inner) -> Self { + Self { cipher } + } +} + +impl Decrypt for EcbCs2Dec { + fn decrypt_inout(self, buf: InOutBuf<'_, '_, u8>) -> Result<(), Error> { + if buf.len() < C::BlockSize::USIZE { + return Err(Error); + } + self.cipher.decrypt_with_backend(Closure { + buf, + _pd: PhantomData, + }); + Ok(()) + } +} + +struct Closure<'a, BS: ArrayLength> { + buf: InOutBuf<'a, 'a, u8>, + _pd: PhantomData, +} + +impl> BlockSizeUser for Closure<'_, BS> { + type BlockSize = BS; +} + +impl> BlockClosure for Closure<'_, BS> { + fn call>(self, cipher: &mut B) { + let Self { mut buf, _pd } = self; + + let (mut blocks, mut tail) = buf.reborrow().into_chunks(); + + ecb_dec(cipher, blocks.reborrow()); + + if tail.is_empty() { + return; + } + + let last_block = blocks.get_out().last_mut().unwrap(); + + let tail_len = tail.len(); + let mut block = Block::::default(); + block[..tail_len].copy_from_slice(tail.get_in()); + block[tail_len..].copy_from_slice(&last_block[tail_len..]); + tail.get_out().copy_from_slice(&last_block[..tail_len]); + + cipher.proc_block_inplace(&mut block); + + *last_block = block; + } +} diff --git a/cts/src/ecb_cs2_enc.rs b/cts/src/ecb_cs2_enc.rs new file mode 100644 index 0000000..b910789 --- /dev/null +++ b/cts/src/ecb_cs2_enc.rs @@ -0,0 +1,75 @@ +use crate::{ecb_enc, Encrypt, Error}; +use cipher::{ + crypto_common::{InnerInit, InnerUser}, + inout::InOutBuf, + typenum::Unsigned, + ArrayLength, Block, BlockBackend, BlockClosure, BlockEncrypt, BlockSizeUser, IvSizeUser, +}; +use core::marker::PhantomData; + +/// The ECB-CS-2 ciphertext stealing mode encryptor. +#[derive(Clone)] +pub struct EcbCs2Enc { + cipher: C, +} + +impl InnerUser for EcbCs2Enc { + type Inner = C; +} + +impl IvSizeUser for EcbCs2Enc { + type IvSize = C::BlockSize; +} + +impl InnerInit for EcbCs2Enc { + fn inner_init(cipher: Self::Inner) -> Self { + Self { cipher } + } +} + +impl Encrypt for EcbCs2Enc { + fn encrypt_inout(self, buf: InOutBuf<'_, '_, u8>) -> Result<(), Error> { + if buf.len() < C::BlockSize::USIZE { + return Err(Error); + } + self.cipher.encrypt_with_backend(Closure { + buf, + _pd: PhantomData, + }); + Ok(()) + } +} + +struct Closure<'a, BS: ArrayLength> { + buf: InOutBuf<'a, 'a, u8>, + _pd: PhantomData, +} + +impl> BlockSizeUser for Closure<'_, BS> { + type BlockSize = BS; +} + +impl> BlockClosure for Closure<'_, BS> { + fn call>(self, cipher: &mut B) { + let Self { mut buf, _pd } = self; + let (mut blocks, mut tail) = buf.reborrow().into_chunks(); + + ecb_enc(cipher, blocks.reborrow()); + + if tail.is_empty() { + return; + } + + let last_block = blocks.get_out().last_mut().unwrap(); + + let n = tail.len(); + + let mut block = Block::::default(); + block[..n].copy_from_slice(tail.get_in()); + block[n..].copy_from_slice(&last_block[n..]); + cipher.proc_block_inplace(&mut block); + + tail.get_out().copy_from_slice(&last_block[..n]); + *last_block = block; + } +} diff --git a/cts/src/ecb_cs3_dec.rs b/cts/src/ecb_cs3_dec.rs new file mode 100644 index 0000000..124883d --- /dev/null +++ b/cts/src/ecb_cs3_dec.rs @@ -0,0 +1,78 @@ +use crate::{ecb_dec, Decrypt, Error}; +use cipher::{ + crypto_common::{InnerInit, InnerUser}, + inout::InOutBuf, + typenum::Unsigned, + ArrayLength, Block, BlockBackend, BlockClosure, BlockDecrypt, BlockSizeUser, IvSizeUser, +}; +use core::marker::PhantomData; + +/// The ECB-CS-3 ciphertext stealing mode decryptor. +#[derive(Clone)] +pub struct EcbCs3Dec { + cipher: C, +} + +impl InnerUser for EcbCs3Dec { + type Inner = C; +} + +impl IvSizeUser for EcbCs3Dec { + type IvSize = C::BlockSize; +} + +impl InnerInit for EcbCs3Dec { + fn inner_init(cipher: Self::Inner) -> Self { + Self { cipher } + } +} + +impl Decrypt for EcbCs3Dec { + fn decrypt_inout(self, buf: InOutBuf<'_, '_, u8>) -> Result<(), Error> { + if buf.len() < C::BlockSize::USIZE { + return Err(Error); + } + self.cipher.decrypt_with_backend(Closure { + buf, + _pd: PhantomData, + }); + Ok(()) + } +} + +struct Closure<'a, BS: ArrayLength> { + buf: InOutBuf<'a, 'a, u8>, + _pd: PhantomData, +} + +impl> BlockSizeUser for Closure<'_, BS> { + type BlockSize = BS; +} + +impl> BlockClosure for Closure<'_, BS> { + fn call>(self, cipher: &mut B) { + let Self { mut buf, _pd } = self; + + let (mut blocks, mut tail) = buf.reborrow().into_chunks(); + + ecb_dec(cipher, blocks.reborrow()); + + if tail.is_empty() && blocks.len() > 1 { + let blocks = blocks.get_out(); + let (last, rest) = blocks.split_last_mut().unwrap(); + let (penultimate, _) = rest.split_last_mut().unwrap(); + core::mem::swap(penultimate, last); + } else { + let last_block = blocks.get_out().last_mut().unwrap(); + + let n = tail.len(); + let mut block = Block::::default(); + block[..n].copy_from_slice(tail.get_in()); + block[n..].copy_from_slice(&last_block[n..]); + tail.get_out().copy_from_slice(&last_block[..n]); + + cipher.proc_block_inplace(&mut block); + *last_block = block; + } + } +} diff --git a/cts/src/ecb_cs3_enc.rs b/cts/src/ecb_cs3_enc.rs new file mode 100644 index 0000000..4b1a230 --- /dev/null +++ b/cts/src/ecb_cs3_enc.rs @@ -0,0 +1,78 @@ +use crate::{ecb_enc, Encrypt, Error}; +use cipher::{ + crypto_common::{InnerInit, InnerUser}, + inout::InOutBuf, + typenum::Unsigned, + ArrayLength, Block, BlockBackend, BlockClosure, BlockEncrypt, BlockSizeUser, IvSizeUser, +}; +use core::marker::PhantomData; + +/// The ECB-CS-3 ciphertext stealing mode encryptor. +#[derive(Clone)] +pub struct EcbCs3Enc { + cipher: C, +} + +impl InnerUser for EcbCs3Enc { + type Inner = C; +} + +impl IvSizeUser for EcbCs3Enc { + type IvSize = C::BlockSize; +} + +impl InnerInit for EcbCs3Enc { + fn inner_init(cipher: Self::Inner) -> Self { + Self { cipher } + } +} + +impl Encrypt for EcbCs3Enc { + fn encrypt_inout(self, buf: InOutBuf<'_, '_, u8>) -> Result<(), Error> { + if buf.len() < C::BlockSize::USIZE { + return Err(Error); + } + self.cipher.encrypt_with_backend(Closure { + buf, + _pd: PhantomData, + }); + Ok(()) + } +} + +struct Closure<'a, BS: ArrayLength> { + buf: InOutBuf<'a, 'a, u8>, + _pd: PhantomData, +} + +impl> BlockSizeUser for Closure<'_, BS> { + type BlockSize = BS; +} + +impl> BlockClosure for Closure<'_, BS> { + fn call>(self, cipher: &mut B) { + let Self { mut buf, _pd } = self; + let (mut blocks, mut tail) = buf.reborrow().into_chunks(); + + ecb_enc(cipher, blocks.reborrow()); + + if tail.is_empty() && blocks.len() > 1 { + let blocks = blocks.get_out(); + let (last, rest) = blocks.split_last_mut().unwrap(); + let (penultimate, _) = rest.split_last_mut().unwrap(); + core::mem::swap(penultimate, last); + } else { + let last_block = blocks.get_out().last_mut().unwrap(); + + let n = tail.len(); + + let mut block = Block::::default(); + block[..n].copy_from_slice(tail.get_in()); + block[n..].copy_from_slice(&last_block[n..]); + cipher.proc_block_inplace(&mut block); + + tail.get_out().copy_from_slice(&last_block[..n]); + *last_block = block; + } + } +} diff --git a/cts/src/lib.rs b/cts/src/lib.rs new file mode 100644 index 0000000..a201ac5 --- /dev/null +++ b/cts/src/lib.rs @@ -0,0 +1,176 @@ +#![no_std] +#![doc = include_str!("../README.md")] +#![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" +)] +#![deny(unsafe_code)] +#![cfg_attr(docsrs, feature(doc_cfg))] +#![warn(missing_docs, rust_2018_idioms)] + +pub use cipher; + +pub use cipher::{KeyInit, KeyIvInit}; + +mod cbc_cs1_enc; +pub use cbc_cs1_enc::CbcCs1Enc; + +mod cbc_cs1_dec; +pub use cbc_cs1_dec::CbcCs1Dec; + +mod cbc_cs2_enc; +pub use cbc_cs2_enc::CbcCs2Enc; + +mod cbc_cs2_dec; +pub use cbc_cs2_dec::CbcCs2Dec; + +mod cbc_cs3_enc; +pub use cbc_cs3_enc::CbcCs3Enc; + +mod cbc_cs3_dec; +pub use cbc_cs3_dec::CbcCs3Dec; + +mod ecb_cs1_enc; +pub use ecb_cs1_enc::EcbCs1Enc; + +mod ecb_cs1_dec; +pub use ecb_cs1_dec::EcbCs1Dec; + +mod ecb_cs2_enc; +pub use ecb_cs2_enc::EcbCs2Enc; + +mod ecb_cs2_dec; +pub use ecb_cs2_dec::EcbCs2Dec; + +mod ecb_cs3_enc; +pub use ecb_cs3_enc::EcbCs3Enc; + +mod ecb_cs3_dec; +pub use ecb_cs3_dec::EcbCs3Dec; + +use cipher::{ + generic_array::{typenum::Unsigned, GenericArray}, + inout::{InOutBuf, NotEqualError}, + ArrayLength, Block, BlockBackend, +}; + +/// Error which indicates that message is smaller than cipher's block size. +#[derive(Copy, Clone, Debug)] +pub struct Error; + +/// Encryption functionality of CTS modes. +pub trait Encrypt: Sized { + /// Encrypt `inout` buffer. + fn encrypt_inout(self, buf: InOutBuf<'_, '_, u8>) -> Result<(), Error>; + + /// Encrypt data in-place. + fn encrypt(self, buf: &mut [u8]) -> Result<(), Error> { + self.encrypt_inout(buf.into()) + } + + /// Encrypt data buffer-to-buffer. + fn encrypt_b2b(self, in_buf: &[u8], out_buf: &mut [u8]) -> Result<(), Error> { + InOutBuf::new(in_buf, out_buf) + .map_err(|NotEqualError| Error) + .and_then(|buf| self.encrypt_inout(buf)) + } +} + +/// Decryption functionality of CTS modes. +pub trait Decrypt: Sized { + /// Decrypt `inout` buffer. + fn decrypt_inout(self, buf: InOutBuf<'_, '_, u8>) -> Result<(), Error>; + + /// Decrypt data in-place. + fn decrypt(self, buf: &mut [u8]) -> Result<(), Error> { + self.decrypt_inout(buf.into()) + } + + /// Decrypt data buffer-to-buffer. + fn decrypt_b2b(self, in_buf: &[u8], out_buf: &mut [u8]) -> Result<(), Error> { + InOutBuf::new(in_buf, out_buf) + .map_err(|NotEqualError| Error) + .and_then(|buf| self.decrypt_inout(buf)) + } +} + +fn ecb_enc(cipher: &mut B, mut blocks: InOutBuf<'_, '_, Block>) { + if B::ParBlocksSize::USIZE > 1 { + let (par_blocks, rem_blocks) = blocks.into_chunks(); + blocks = rem_blocks; + for blocks in par_blocks { + cipher.proc_par_blocks(blocks); + } + } + for block in blocks { + cipher.proc_block(block); + } +} + +fn ecb_dec(cipher: &mut B, mut blocks: InOutBuf<'_, '_, Block>) { + if B::ParBlocksSize::USIZE > 1 { + let (par_blocks, rem_blocks) = blocks.into_chunks(); + blocks = rem_blocks; + for blocks in par_blocks { + cipher.proc_par_blocks(blocks); + } + } + for block in blocks { + cipher.proc_block(block); + } +} + +fn cbc_enc( + cipher: &mut B, + iv: &mut Block, + mut blocks: InOutBuf<'_, '_, Block>, +) { + for mut block in blocks.reborrow() { + let mut t = block.clone_in(); + xor(&mut t, iv); + cipher.proc_block_inplace(&mut t); + *iv = t.clone(); + *block.get_out() = t; + } +} + +fn cbc_dec( + cipher: &mut B, + iv: &mut Block, + mut blocks: InOutBuf<'_, '_, Block>, +) { + if B::ParBlocksSize::USIZE > 1 { + let (par_blocks, rem_blocks) = blocks.into_chunks(); + blocks = rem_blocks; + + for mut blocks in par_blocks { + let in_blocks = blocks.clone_in(); + let mut t = blocks.clone_in(); + + cipher.proc_par_blocks_inplace(&mut t); + let n = t.len(); + xor(&mut t[0], iv); + for i in 1..n { + xor(&mut t[i], &in_blocks[i - 1]) + } + *blocks.get_out() = t; + *iv = in_blocks[n - 1].clone(); + } + } + + for mut block in blocks { + let in_block = block.clone_in(); + let mut t = block.clone_in(); + cipher.proc_block_inplace(&mut t); + xor(&mut t, iv); + *block.get_out() = t; + *iv = in_block; + } +} + +#[inline(always)] +fn xor>(out: &mut GenericArray, buf: &GenericArray) { + for (a, b) in out.iter_mut().zip(buf) { + *a ^= *b; + } +} diff --git a/cts/tests/aes128_roundtrip.rs b/cts/tests/aes128_roundtrip.rs new file mode 100644 index 0000000..014b064 --- /dev/null +++ b/cts/tests/aes128_roundtrip.rs @@ -0,0 +1,133 @@ +use aes::Aes128; +use cts::{ + cipher::{crypto_common::InnerInit, InnerIvInit, KeyInit}, + Decrypt, Encrypt, +}; + +const KEY: [u8; 16] = [0x42; 16]; +const IV: [u8; 16] = [0x24; 16]; + +const N: usize = 64; +const MSG: [u8; N] = { + let mut res = [0u8; N]; + let mut i = 0; + while i < N { + res[i] = i as u8; + i += 1; + } + res +}; + +#[test] +fn aes128_cbc_cs1_roundtrip() { + let mut buf1 = [0u8; 64]; + let mut buf2 = [0u8; 64]; + + let cipher = Aes128::new(&KEY.into()); + for i in 16..MSG.len() { + let enc_mode = cts::CbcCs1Enc::inner_iv_init(&cipher, &IV.into()); + let ct = &mut buf1[..i]; + enc_mode.encrypt_b2b(&MSG[..i], ct).unwrap(); + + let dec_mode = cts::CbcCs1Dec::inner_iv_init(&cipher, &IV.into()); + let pt = &mut buf2[..i]; + dec_mode.decrypt_b2b(ct, pt).unwrap(); + + assert_eq!(pt, &MSG[..i]); + } +} + +#[test] +fn aes128_cbc_cs2_roundtrip() { + let mut buf1 = [0u8; 64]; + let mut buf2 = [0u8; 64]; + + let cipher = Aes128::new(&KEY.into()); + for i in 16..MSG.len() { + let enc_mode = cts::CbcCs2Enc::inner_iv_init(&cipher, &IV.into()); + let ct = &mut buf1[..i]; + enc_mode.encrypt_b2b(&MSG[..i], ct).unwrap(); + + let dec_mode = cts::CbcCs2Dec::inner_iv_init(&cipher, &IV.into()); + let pt = &mut buf2[..i]; + dec_mode.decrypt_b2b(ct, pt).unwrap(); + + assert_eq!(pt, &MSG[..i]); + } +} + +#[test] +fn aes128_cbc_cs3_roundtrip() { + let mut buf1 = [0u8; 64]; + let mut buf2 = [0u8; 64]; + + let cipher = Aes128::new(&KEY.into()); + for i in 16..MSG.len() { + let enc_mode = cts::CbcCs3Enc::inner_iv_init(&cipher, &IV.into()); + let ct = &mut buf1[..i]; + enc_mode.encrypt_b2b(&MSG[..i], ct).unwrap(); + + let dec_mode = cts::CbcCs3Dec::inner_iv_init(&cipher, &IV.into()); + let pt = &mut buf2[..i]; + dec_mode.decrypt_b2b(ct, pt).unwrap(); + + assert_eq!(pt, &MSG[..i]); + } +} + +#[test] +fn aes128_ecb_cs1_roundtrip() { + let mut buf1 = [0u8; 64]; + let mut buf2 = [0u8; 64]; + + let cipher = Aes128::new(&KEY.into()); + for i in 16..MSG.len() { + let enc_mode = cts::EcbCs1Enc::inner_init(&cipher); + let ct = &mut buf1[..i]; + enc_mode.encrypt_b2b(&MSG[..i], ct).unwrap(); + + let dec_mode = cts::EcbCs1Dec::inner_init(&cipher); + let pt = &mut buf2[..i]; + dec_mode.decrypt_b2b(ct, pt).unwrap(); + + assert_eq!(pt, &MSG[..i]); + } +} + +#[test] +fn aes128_ecb_cs2_roundtrip() { + let mut buf1 = [0u8; 64]; + let mut buf2 = [0u8; 64]; + + let cipher = Aes128::new(&KEY.into()); + for i in 16..MSG.len() { + let enc_mode = cts::EcbCs2Enc::inner_init(&cipher); + let ct = &mut buf1[..i]; + enc_mode.encrypt_b2b(&MSG[..i], ct).unwrap(); + + let dec_mode = cts::EcbCs2Dec::inner_init(&cipher); + let pt = &mut buf2[..i]; + dec_mode.decrypt_b2b(ct, pt).unwrap(); + + assert_eq!(pt, &MSG[..i]); + } +} + +#[test] +fn aes128_ecb_cs3_roundtrip() { + let mut buf1 = [0u8; 64]; + let mut buf2 = [0u8; 64]; + + let cipher = Aes128::new(&KEY.into()); + for i in 16..MSG.len() { + let enc_mode = cts::EcbCs3Enc::inner_init(&cipher); + let ct = &mut buf1[..i]; + enc_mode.encrypt_b2b(&MSG[..i], ct).unwrap(); + + let dec_mode = cts::EcbCs3Dec::inner_init(&cipher); + let pt = &mut buf2[..i]; + dec_mode.decrypt_b2b(ct, pt).unwrap(); + + assert_eq!(pt, &MSG[..i]); + } +} diff --git a/cts/tests/belt_ecb.rs b/cts/tests/belt_ecb.rs new file mode 100644 index 0000000..dbed70f --- /dev/null +++ b/cts/tests/belt_ecb.rs @@ -0,0 +1,93 @@ +//! Test vectors from STB 34.101.31-2020 (section А.4, tables A.9-10): +//! https://apmi.bsu.by/assets/files/std/belt-spec371.pdf +use belt_block::BeltBlock; +use cts::{Decrypt, Encrypt, KeyInit}; +use hex_literal::hex; + +struct TestVector { + key: &'static [u8; 32], + pt: &'static [u8], + ct: &'static [u8], +} + +static TEST_VECTORS: &[TestVector] = &[ + TestVector { + key: &hex!( + "E9DEE72C 8F0C0FA6 2DDB49F4 6F739647" + "06075316 ED247A37 39CBA383 03A98BF6" + ), + pt: &hex!( + "B194BAC8 0A08F53B 366D008E 584A5DE4" + "8504FA9D 1BB6C7AC 252E72C2 02FDCE0D" + "5BE3D612 17B96181 FE6786AD 716B890B" + ), + ct: &hex!( + "69CCA1C9 3557C9E3 D66BC3E0 FA88FA6E" + "5F23102E F1097107 75017F73 806DA9DC" + "46FB2ED2 CE771F26 DCB5E5D1 569F9AB0" + ), + }, + TestVector { + key: &hex!( + "E9DEE72C 8F0C0FA6 2DDB49F4 6F739647" + "06075316 ED247A37 39CBA383 03A98BF6" + ), + pt: &hex!( + "B194BAC8 0A08F53B 366D008E 584A5DE4" + "8504FA9D 1BB6C7AC 252E72C2 02FDCE0D" + "5BE3D612 17B96181 FE6786AD 716B89" + ), + ct: &hex!( + "69CCA1C9 3557C9E3 D66BC3E0 FA88FA6E" + "36F00CFE D6D1CA14 98C12798 F4BEB207" + "5F23102E F1097107 75017F73 806DA9" + ), + }, + TestVector { + key: &hex!( + "92BD9B1C E5D14101 5445FBC9 5E4D0EF2" + "682080AA 227D642F 2687F934 90405511" + ), + pt: &hex!( + "0DC53006 00CAB840 B38448E5 E993F421" + "E55A239F 2AB5C5D5 FDB6E81B 40938E2A" + "54120CA3 E6E19C7A D750FC35 31DAEAB7" + ), + ct: &hex!( + "E12BDC1A E28257EC 703FCCF0 95EE8DF1" + "C1AB7638 9FE678CA F7C6F860 D5BB9C4F" + "F33C657B 637C306A DD4EA779 9EB23D31" + ), + }, + TestVector { + key: &hex!( + "92BD9B1C E5D14101 5445FBC9 5E4D0EF2" + "682080AA 227D642F 2687F934 90405511" + ), + pt: &hex!( + "0DC53006 00CAB840 B38448E5 E993F421" + "5780A6E2 B69EAFBB 258726D7 B6718523" + "E55A239F" + ), + ct: &hex!( + "E12BDC1A E28257EC 703FCCF0 95EE8DF1" + "C1AB7638 9FE678CA F7C6F860 D5BB9C4F" + "F33C657B" + ), + }, +]; + +#[test] +fn belt_ecb() { + let mut buf = [0u8; 48]; + for &TestVector { key, pt, ct } in TEST_VECTORS { + let buf = &mut buf[..pt.len()]; + let enc_mode = cts::EcbCs2Enc::::new(key.into()); + enc_mode.encrypt_b2b(pt, buf).unwrap(); + assert_eq!(buf, ct); + + let dec_mode = cts::EcbCs2Dec::::new(key.into()); + dec_mode.decrypt(buf).unwrap(); + assert_eq!(buf, pt); + } +} diff --git a/cts/tests/rfc3962.rs b/cts/tests/rfc3962.rs new file mode 100644 index 0000000..84a3bee --- /dev/null +++ b/cts/tests/rfc3962.rs @@ -0,0 +1,98 @@ +//! Test vectors from RFC 3962: https://www.rfc-editor.org/rfc/rfc3962 +use aes::Aes128; +use cipher::{InnerIvInit, KeyInit}; +use cts::{Decrypt, Encrypt}; +use hex_literal::hex; + +const KEY: [u8; 16] = hex!("636869636b656e207465726979616b69"); +const IV: [u8; 16] = [0u8; 16]; + +static TEST_VECTORS: &[(&[u8], &[u8])] = &[ + ( + &hex!( + "4920776f756c64206c696b6520746865" + "20" + ), + &hex!( + "c6353568f2bf8cb4d8a580362da7ff7f" + "97" + ), + ), + ( + &hex!( + "4920776f756c64206c696b6520746865" + "2047656e6572616c20476175277320" + ), + &hex!( + "fc00783e0efdb2c1d445d4c8eff7ed22" + "97687268d6ecccc0c07b25e25ecfe5" + ), + ), + ( + &hex!( + "4920776f756c64206c696b6520746865" + "2047656e6572616c2047617527732043" + ), + &hex!( + "39312523a78662d5be7fcbcc98ebf5a8" + "97687268d6ecccc0c07b25e25ecfe584" + ), + ), + ( + &hex!( + "4920776f756c64206c696b6520746865" + "2047656e6572616c2047617527732043" + "6869636b656e2c20706c656173652c" + ), + &hex!( + "97687268d6ecccc0c07b25e25ecfe584" + "b3fffd940c16a18c1b5549d2f838029e" + "39312523a78662d5be7fcbcc98ebf5" + ), + ), + ( + &hex!( + "4920776f756c64206c696b6520746865" + "2047656e6572616c2047617527732043" + "6869636b656e2c20706c656173652c20" + ), + &hex!( + "97687268d6ecccc0c07b25e25ecfe584" + "9dad8bbb96c4cdc03bc103e1a194bbd8" + "39312523a78662d5be7fcbcc98ebf5a8" + ), + ), + ( + &hex!( + "4920776f756c64206c696b6520746865" + "2047656e6572616c2047617527732043" + "6869636b656e2c20706c656173652c20" + "616e6420776f6e746f6e20736f75702e" + ), + &hex!( + "97687268d6ecccc0c07b25e25ecfe584" + "39312523a78662d5be7fcbcc98ebf5a8" + "4807efe836ee89a526730dbc2f7bc840" + "9dad8bbb96c4cdc03bc103e1a194bbd8" + ), + ), +]; + +#[test] +fn rfc3962() { + let cipher = Aes128::new(&KEY.into()); + let iv = IV.into(); + + let mut buf = [0u8; 64]; + for &(input, output) in TEST_VECTORS { + let buf = &mut buf[..input.len()]; + + let enc_mode = cts::CbcCs3Enc::inner_iv_init(&cipher, &iv); + enc_mode.encrypt_b2b(input, buf).unwrap(); + assert_eq!(buf, output); + + let dec_mode = cts::CbcCs3Dec::inner_iv_init(&cipher, &iv); + dec_mode.decrypt_b2b(output, buf).unwrap(); + assert_eq!(buf, input); + } +}