From de5868d346b14b696b1f47ee0be75390b81b566e Mon Sep 17 00:00:00 2001 From: Shun Sakai Date: Wed, 21 Jan 2026 09:23:31 +0900 Subject: [PATCH] feat: Implement Simon --- .github/workflows/simon.yml | 72 ++++++++ Cargo.lock | 8 + Cargo.toml | 1 + README.md | 3 + simon/Cargo.toml | 26 +++ simon/LICENSE-APACHE | 201 ++++++++++++++++++++++ simon/LICENSE-MIT | 26 +++ simon/README.md | 57 ++++++ simon/src/lib.rs | 334 ++++++++++++++++++++++++++++++++++++ simon/tests/mod.rs | 114 ++++++++++++ 10 files changed, 842 insertions(+) create mode 100644 .github/workflows/simon.yml create mode 100644 simon/Cargo.toml create mode 100644 simon/LICENSE-APACHE create mode 100644 simon/LICENSE-MIT create mode 100644 simon/README.md create mode 100644 simon/src/lib.rs create mode 100644 simon/tests/mod.rs diff --git a/.github/workflows/simon.yml b/.github/workflows/simon.yml new file mode 100644 index 00000000..8917a16d --- /dev/null +++ b/.github/workflows/simon.yml @@ -0,0 +1,72 @@ +name: simon + +on: + pull_request: + paths: + - ".github/workflows/simon.yml" + - "simon/**" + - "Cargo.*" + push: + branches: master + +defaults: + run: + working-directory: simon + +env: + CARGO_INCREMENTAL: 0 + RUSTFLAGS: "-Dwarnings" + +# Cancels CI jobs when new commits are pushed to a PR branch +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + rust: + - 1.85.0 # MSRV + - stable + target: + - thumbv7em-none-eabi + - wasm32-unknown-unknown + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ matrix.rust }} + targets: ${{ matrix.target }} + - run: cargo build --no-default-features --release --target ${{ matrix.target }} + + minimal-versions: + if: false # TODO: temp disabled due to unpublished prerelease dependencies + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@master + with: + toolchain: nightly + - run: rm ../Cargo.toml + - run: cargo update -Z minimal-versions + - run: cargo test --release + - run: cargo test --release --all-features + + test: + runs-on: ubuntu-latest + strategy: + matrix: + rust: + - 1.85.0 # MSRV + - stable + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ matrix.rust }} + - run: cargo check --all-features + - run: cargo test --no-default-features + - run: cargo test + - run: cargo test --all-features diff --git a/Cargo.lock b/Cargo.lock index 1d8e547f..a4dfa9c1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -220,6 +220,14 @@ dependencies = [ "cipher", ] +[[package]] +name = "simon-cipher" +version = "0.1.0" +dependencies = [ + "cipher", + "hex-literal", +] + [[package]] name = "sm4" version = "0.6.0-rc.2" diff --git a/Cargo.toml b/Cargo.toml index 675e575f..37da67e3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,6 +17,7 @@ members = [ "rc5", "rc6", "serpent", + "simon", "sm4", "speck", "twofish", diff --git a/README.md b/README.md index be164d0e..a0a1adcd 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,7 @@ It's generally recommended not to use other cipher implementations in this repos | [RC5] | [`rc5`] | [![crates.io](https://img.shields.io/crates/v/rc5.svg)](https://crates.io/crates/rc5) | [![Documentation](https://docs.rs/rc5/badge.svg)](https://docs.rs/rc5) | ![MSRV 1.85][msrv-1.85] | | [RC6] | [`rc6`] | [![crates.io](https://img.shields.io/crates/v/rc6.svg)](https://crates.io/crates/rc6) | [![Documentation](https://docs.rs/rc6/badge.svg)](https://docs.rs/rc6) | ![MSRV 1.85][msrv-1.85] | | [Serpent] | [`serpent`] | [![crates.io](https://img.shields.io/crates/v/serpent.svg)](https://crates.io/crates/serpent) | [![Documentation](https://docs.rs/serpent/badge.svg)](https://docs.rs/serpent) | ![MSRV 1.85][msrv-1.85] | +| [Simon] | [`simon-cipher`] | [![crates.io](https://img.shields.io/crates/v/simon-cipher.svg)](https://crates.io/crates/simon-cipher) | [![Documentation](https://docs.rs/simon-cipher/badge.svg)](https://docs.rs/simon-cipher) | ![MSRV 1.85][msrv-1.85] | | [SM4] | [`sm4`] | [![crates.io](https://img.shields.io/crates/v/sm4.svg)](https://crates.io/crates/sm4) | [![Documentation](https://docs.rs/sm4/badge.svg)](https://docs.rs/sm4) | ![MSRV 1.85][msrv-1.85] | | [Speck] | [`speck-cipher`] | [![crates.io](https://img.shields.io/crates/v/speck-cipher.svg)](https://crates.io/crates/speck-cipher) | [![Documentation](https://docs.rs/speck-cipher/badge.svg)](https://docs.rs/speck-cipher) | ![MSRV 1.85][msrv-1.85] | | [Threefish] | [`threefish`] | [![crates.io](https://img.shields.io/crates/v/threefish.svg)](https://crates.io/crates/threefish) | [![Documentation](https://docs.rs/threefish/badge.svg)](https://docs.rs/threefish) | ![MSRV 1.85][msrv-1.85] | @@ -102,6 +103,7 @@ dual licensed as above, without any additional terms or conditions. [`rc5`]: ./rc5 [`rc6`]: ./rc6 [`serpent`]: ./serpent +[`simon-cipher`]: ./simon [`sm4`]: ./sm4 [`speck-cipher`]: ./speck [`threefish`]: ./threefish @@ -131,6 +133,7 @@ dual licensed as above, without any additional terms or conditions. [RC5]: https://en.wikipedia.org/wiki/RC5 [RC6]: https://en.wikipedia.org/wiki/RC6 [Serpent]: https://en.wikipedia.org/wiki/Serpent_(cipher) +[Simon]: https://en.wikipedia.org/wiki/Simon_(cipher) [SM4]: https://en.wikipedia.org/wiki/SM4_(cipher) [Speck]: https://en.wikipedia.org/wiki/Speck_(cipher) [Threefish]: https://en.wikipedia.org/wiki/Threefish diff --git a/simon/Cargo.toml b/simon/Cargo.toml new file mode 100644 index 00000000..040a5780 --- /dev/null +++ b/simon/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "simon-cipher" +version = "0.1.0" +authors = ["RustCrypto Developers"] +license = "Apache-2.0 OR MIT" +description = "Simon block cipher algorithm" +documentation = "https://docs.rs/simon-cipher" +repository = "https://github.com/RustCrypto/block-ciphers/tree/master/simon" +readme = "README.md" +edition = "2024" +rust-version = "1.85" +keywords = ["crypto", "simon", "block-cipher"] +categories = ["cryptography", "no-std"] + +[dependencies] +cipher = "0.5.0-rc.3" + +[dev-dependencies] +cipher = { version = "0.5.0-rc.3", features = ["dev"] } +hex-literal = "1" + +[features] +zeroize = ["cipher/zeroize"] + +[package.metadata.docs.rs] +all-features = true diff --git a/simon/LICENSE-APACHE b/simon/LICENSE-APACHE new file mode 100644 index 00000000..78173fa2 --- /dev/null +++ b/simon/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/simon/LICENSE-MIT b/simon/LICENSE-MIT new file mode 100644 index 00000000..592b2548 --- /dev/null +++ b/simon/LICENSE-MIT @@ -0,0 +1,26 @@ +Copyright (c) 2023-2024 The RustCrypto Project Developers +Copyright (c) 2026 Shun Sakai + +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/simon/README.md b/simon/README.md new file mode 100644 index 00000000..9e95472d --- /dev/null +++ b/simon/README.md @@ -0,0 +1,57 @@ +# RustCrypto: Simon Cipher + +[![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] +[![HAZMAT][hazmat-image]][hazmat-link] + +Pure Rust implementation of the [Simon block cipher][1]. + +## ⚠️ Security Warning: [Hazmat!][hazmat-link] + +This crate does not ensure ciphertexts are authentic (i.e. by using a MAC to +verify ciphertext integrity), which can lead to serious vulnerabilities +if used incorrectly! + +No security audits of this crate have ever been performed, and it has not been +thoroughly assessed to ensure its operation is constant-time on common CPU +architectures. + +USE AT YOUR OWN RISK! + +## License + +Licensed under either of: + + * [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0) + * [MIT license](http://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/simon-cipher.svg +[crate-link]: https://crates.io/crates/simon-cipher +[docs-image]: https://docs.rs/simon-cipher/badge.svg +[docs-link]: https://docs.rs/simon-cipher/ +[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg +[rustc-image]: https://img.shields.io/badge/rustc-1.85+-blue.svg +[hazmat-image]: https://img.shields.io/badge/crypto-hazmat%E2%9A%A0-red.svg +[hazmat-link]: https://github.com/RustCrypto/meta/blob/master/HAZMAT.md +[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg +[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260039-block-ciphers +[build-image]: https://github.com/RustCrypto/block-ciphers/workflows/simon/badge.svg?branch=master&event=push +[build-link]: https://github.com/RustCrypto/block-ciphers/actions?query=workflow%3Asimon + +[//]: # (general links) + +[1]: https://en.wikipedia.org/wiki/Simon_(cipher) diff --git a/simon/src/lib.rs b/simon/src/lib.rs new file mode 100644 index 00000000..dc5b2b8d --- /dev/null +++ b/simon/src/lib.rs @@ -0,0 +1,334 @@ +//! Pure Rust implementation of the [Simon] block cipher. +//! +//! [Simon]: https://en.wikipedia.org/wiki/Simon_(cipher) + +#![no_std] +#![doc( + html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/26acc39f/logo.svg", + html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/26acc39f/logo.svg" +)] +#![deny(unsafe_code)] +#![cfg_attr(docsrs, feature(doc_cfg))] +#![warn(missing_docs, rust_2018_idioms)] + +pub use cipher; + +use cipher::{ + AlgorithmName, Block, BlockCipherDecBackend, BlockCipherDecClosure, BlockCipherDecrypt, + BlockCipherEncBackend, BlockCipherEncClosure, BlockCipherEncrypt, BlockSizeUser, InOut, Key, + KeyInit, KeySizeUser, ParBlocksSizeUser, consts::*, +}; +use core::{fmt, mem::size_of}; + +#[cfg(feature = "zeroize")] +use cipher::zeroize::{Zeroize, ZeroizeOnDrop}; + +macro_rules! define_simon_impl { + ( + $name:ident, + $block_size:ty, + $key_size:ty, + $word_type:ty, + $n:literal, + $m:literal, + $z:literal, + $mask:literal, + $rounds:literal, + $doc:expr $(,)? + ) => { + #[doc=$doc] + #[doc = "block cipher"] + #[derive(Clone)] + pub struct $name { + k: [$word_type; $rounds], + } + + impl $name { + #[inline] + fn from_be_bytes(bytes: &[u8]) -> $word_type { + let mut tmp = [0u8; size_of::<$word_type>()]; + let offset = size_of::<$word_type>() - $n / 8; + tmp[offset..].copy_from_slice(bytes); + <$word_type>::from_be_bytes(tmp) + } + + #[inline] + #[allow(clippy::wrong_self_convention)] + fn to_be_bytes(word: $word_type) -> [u8; $n / 8] { + let tmp = word.to_be_bytes(); + let offset = size_of::<$word_type>() - $n / 8; + tmp[offset..].try_into().unwrap() + } + + #[inline] + fn rotate_right(x: $word_type, pos: $word_type) -> $word_type { + // We can't use $word_type.rotate_right here because the word size might be different from the word type. + (x >> pos) | (x << ($n - pos)) + } + + #[inline] + fn rotate_left(x: $word_type, pos: $word_type) -> $word_type { + // We can't use $word_type.rotate_left here because the word size might be different from the word type. + (x << pos) | (x >> ($n - pos)) + } + + #[inline] + fn f(x: $word_type) -> $word_type { + ($name::rotate_left(x, 1) & $name::rotate_left(x, 8)) ^ $name::rotate_left(x, 2) + } + + #[inline] + fn round_function( + k: $word_type, + mut x: $word_type, + mut y: $word_type, + ) -> ($word_type, $word_type) { + (x, y) = ((y ^ $name::f(x) ^ k) & $mask, x); + (x, y) + } + + #[inline] + fn inverse_round_function( + k: $word_type, + mut x: $word_type, + mut y: $word_type, + ) -> ($word_type, $word_type) { + (x, y) = (y, (x ^ $name::f(y) ^ k) & $mask); + (x, y) + } + } + + impl KeySizeUser for $name { + type KeySize = $key_size; + } + + impl KeyInit for $name { + fn new(key: &Key) -> Self { + let mut k = [0; $rounds]; + for i in 0..$m { + k[i] = $name::from_be_bytes(&key[($m - 1 - i) * ($n / 8)..($m - i) * ($n / 8)]); + } + + for i in $m..$rounds { + let mut tmp = $name::rotate_right(k[i - 1], 3); + if $m == 4 { + tmp ^= k[i - 3]; + tmp &= $mask; + } + tmp ^= $name::rotate_right(tmp, 1); + let lfsr_bit = <$word_type>::try_from(($z >> ((i - $m) % 62)) & 1).unwrap(); + k[i] = (!k[i - $m] ^ tmp ^ lfsr_bit ^ 3) & $mask; + } + + Self { k } + } + } + + impl BlockSizeUser for $name { + type BlockSize = $block_size; + } + + impl ParBlocksSizeUser for $name { + type ParBlocksSize = U1; + } + + impl BlockCipherEncrypt for $name { + #[inline] + fn encrypt_with_backend( + &self, + f: impl BlockCipherEncClosure, + ) { + f.call(self) + } + } + + impl BlockCipherEncBackend for $name { + #[inline] + fn encrypt_block(&self, mut block: InOut<'_, '_, Block>) { + let b = block.get_in(); + let mut x = $name::from_be_bytes(&b[0..($n / 8)]); + let mut y = $name::from_be_bytes(&b[($n / 8)..2 * ($n / 8)]); + for i in 0..$rounds { + let res = $name::round_function(self.k[i], x, y); + x = res.0; + y = res.1; + } + + let b = block.get_out(); + b[0..($n / 8)].copy_from_slice(&$name::to_be_bytes(x)); + b[($n / 8)..2 * ($n / 8)].copy_from_slice(&$name::to_be_bytes(y)); + } + } + + impl BlockCipherDecrypt for $name { + #[inline] + fn decrypt_with_backend( + &self, + f: impl BlockCipherDecClosure, + ) { + f.call(self) + } + } + + impl BlockCipherDecBackend for $name { + #[inline] + fn decrypt_block(&self, mut block: InOut<'_, '_, Block>) { + let b = block.get_in(); + let mut x = $name::from_be_bytes(&b[0..($n / 8)]); + let mut y = $name::from_be_bytes(&b[($n / 8)..2 * ($n / 8)]); + for i in (0..$rounds).rev() { + let res = $name::inverse_round_function(self.k[i], x, y); + x = res.0; + y = res.1; + } + + let b = block.get_out(); + b[0..($n / 8)].copy_from_slice(&$name::to_be_bytes(x)); + b[($n / 8)..2 * ($n / 8)].copy_from_slice(&$name::to_be_bytes(y)); + } + } + + impl fmt::Debug for $name { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(concat!(stringify!($name), " { .. }")) + } + } + + impl AlgorithmName for $name { + fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(stringify!($name)) + } + } + + impl Drop for $name { + fn drop(&mut self) { + #[cfg(feature = "zeroize")] + self.k.zeroize(); + } + } + + #[cfg(feature = "zeroize")] + impl ZeroizeOnDrop for $name {} + }; +} + +define_simon_impl!( + Simon32_64, + U4, + U8, + u16, + 16, + 4, + 0xD9C3522FB386A45Fu64, + 0xFFFF, + 32, + "Simon32/64" +); +define_simon_impl!( + Simon48_72, + U6, + U9, + u32, + 24, + 3, + 0xD9C3522FB386A45Fu64, + 0xFFFFFF, + 36, + "Simon48/72" +); +define_simon_impl!( + Simon48_96, + U6, + U12, + u32, + 24, + 4, + 0x56864FB8AD0C9F71u64, + 0xFFFFFF, + 36, + "Simon48/96" +); +define_simon_impl!( + Simon64_96, + U8, + U12, + u32, + 32, + 3, + 0x7369F885192C0EF5u64, + 0xFFFFFFFF, + 42, + "Simon64/96" +); +define_simon_impl!( + Simon64_128, + U8, + U16, + u32, + 32, + 4, + 0xFC2CE51207A635DBu64, + 0xFFFFFFFF, + 44, + "Simon64/128" +); +define_simon_impl!( + Simon96_96, + U12, + U12, + u64, + 48, + 2, + 0x7369F885192C0EF5u64, + 0xFFFFFFFFFFFF, + 52, + "Simon96/96" +); +define_simon_impl!( + Simon96_144, + U12, + U18, + u64, + 48, + 3, + 0xFC2CE51207A635DBu64, + 0xFFFFFFFFFFFF, + 54, + "Simon96/144" +); +define_simon_impl!( + Simon128_128, + U16, + U16, + u64, + 64, + 2, + 0x7369F885192C0EF5u64, + 0xFFFFFFFFFFFFFFFF, + 68, + "Simon128/128" +); +define_simon_impl!( + Simon128_192, + U16, + U24, + u64, + 64, + 3, + 0xFC2CE51207A635DBu64, + 0xFFFFFFFFFFFFFFFF, + 69, + "Simon128/192" +); +define_simon_impl!( + Simon128_256, + U16, + U32, + u64, + 64, + 4, + 0xFDC94C3A046D678Bu64, + 0xFFFFFFFFFFFFFFFF, + 72, + "Simon128/256" +); diff --git a/simon/tests/mod.rs b/simon/tests/mod.rs new file mode 100644 index 00000000..d4da92f6 --- /dev/null +++ b/simon/tests/mod.rs @@ -0,0 +1,114 @@ +//! Test vectors are from The Simon and Simon Families of Lightweight Block Ciphers (Appendix C) + +use cipher::{BlockCipherDecrypt, BlockCipherEncrypt, KeyInit}; +use hex_literal::hex; +use simon_cipher::{ + Simon32_64, Simon48_72, Simon48_96, Simon64_96, Simon64_128, Simon96_96, Simon96_144, + Simon128_128, Simon128_192, Simon128_256, +}; + +macro_rules! new_test { + ( + $name:ident, + $cipher:ident, + $key_hex:expr, + $pt_hex:expr, + $ct_hex:expr + ) => { + #[test] + fn $name() { + let key = hex!($key_hex); + let plaintext = hex!($pt_hex); + let ciphertext = hex!($ct_hex); + let cipher = $cipher::new(&key.into()); + + let mut block = plaintext.clone().into(); + cipher.encrypt_block(&mut block); + + assert_eq!(&ciphertext, block.as_slice()); + + cipher.decrypt_block(&mut block); + assert_eq!(&plaintext, block.as_slice()); + } + }; +} + +new_test!( + simon32_64, + Simon32_64, + "1918111009080100", + "65656877", + "c69be9bb" +); + +new_test!( + simon48_72, + Simon48_72, + "1211100a0908020100", + "6120676e696c", + "dae5ac292cac" +); + +new_test!( + simon48_96, + Simon48_96, + "1a19181211100a0908020100", + "72696320646e", + "6e06a5acf156" +); + +new_test!( + simon64_96, + Simon64_96, + "131211100b0a090803020100", + "6f7220676e696c63", + "5ca2e27f111a8fc8" +); + +new_test!( + simon64_128, + Simon64_128, + "1b1a1918131211100b0a090803020100", + "656b696c20646e75", + "44c8fc20b9dfa07a" +); + +new_test!( + simon96_96, + Simon96_96, + "0d0c0b0a0908050403020100", + "2072616c6c69702065687420", + "602807a462b469063d8ff082" +); + +new_test!( + simon96_144, + Simon96_144, + "1514131211100d0c0b0a0908050403020100", + "74616874207473756420666f", + "ecad1c6c451e3f59c5db1ae9" +); + +new_test!( + simon128_128, + Simon128_128, + "0f0e0d0c0b0a09080706050403020100", + "63736564207372656c6c657661727420", + "49681b1e1e54fe3f65aa832af84e0bbc" +); + +new_test!( + simon128_192, + Simon128_192, + "17161514131211100f0e0d0c0b0a09080706050403020100", + "206572656874206e6568772065626972", + "c4ac61effcdc0d4f6c9c8d6e2597b85b" +); + +new_test!( + simon128_256, + Simon128_256, + "1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100", + "74206e69206d6f6f6d69732061207369", + "8d2b5579afc8a3a03bf72a87efe7b868" +);