diff --git a/.github/workflows/belt-che.yml b/.github/workflows/belt-che.yml new file mode 100644 index 00000000..17bedae0 --- /dev/null +++ b/.github/workflows/belt-che.yml @@ -0,0 +1,81 @@ +name: belt-che + +on: + pull_request: + paths: + - ".github/workflows/belt-che.yml" + - "belt-che/**" + - "Cargo.*" + push: + branches: master + +defaults: + run: + working-directory: belt-che + +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: + - armv7a-none-eabi + - thumbv7em-none-eabi + - wasm32-unknown-unknown + steps: + - uses: actions/checkout@v5 + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ matrix.rust }} + targets: ${{ matrix.target }} + - run: cargo build --no-default-features --release --target ${{ matrix.target }} + + benches: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: dtolnay/rust-toolchain@master + with: + toolchain: nightly-2025-07-31 + - run: cargo build --benches + + test: + runs-on: ubuntu-latest + strategy: + matrix: + include: + # 32-bit Linux + - target: i686-unknown-linux-gnu + rust: 1.85.0 # MSRV + deps: sudo apt update && sudo apt install gcc-multilib + - target: i686-unknown-linux-gnu + rust: stable + deps: sudo apt update && sudo apt install gcc-multilib + + # 64-bit Linux + - target: x86_64-unknown-linux-gnu + rust: 1.85.0 # MSRV + - target: x86_64-unknown-linux-gnu + rust: stable + steps: + - uses: actions/checkout@v5 + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ matrix.rust }} + targets: ${{ matrix.target }} + - run: ${{ matrix.deps }} + - run: cargo test --target ${{ matrix.target }} --release --no-default-features --lib + - run: cargo test --target ${{ matrix.target }} --release + - run: cargo test --target ${{ matrix.target }} --release --all-features diff --git a/Cargo.lock b/Cargo.lock index 8e4df6ce..6e35c1e4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -111,6 +111,20 @@ dependencies = [ "cipher", ] +[[package]] +name = "belt-che" +version = "0.1.0-pre" +dependencies = [ + "aead", + "belt-block", + "belt-ctr", + "hex-literal 1.0.0", + "opaque-debug", + "subtle", + "universal-hash", + "zeroize", +] + [[package]] name = "belt-ctr" version = "0.2.0-rc.1" diff --git a/Cargo.toml b/Cargo.toml index 382379e3..ccaf6dba 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,7 @@ members = [ "aes-gcm-siv", "aes-siv", "ascon-aead128", + "belt-che", "belt-dwp", "ccm", "chacha20poly1305", diff --git a/belt-che/CHANGELOG.md b/belt-che/CHANGELOG.md new file mode 100644 index 00000000..fa000c8b --- /dev/null +++ b/belt-che/CHANGELOG.md @@ -0,0 +1,8 @@ +# 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 (UNRELEASED) +- Initial release diff --git a/belt-che/Cargo.toml b/belt-che/Cargo.toml new file mode 100644 index 00000000..9d40c748 --- /dev/null +++ b/belt-che/Cargo.toml @@ -0,0 +1,37 @@ +[package] +name = "belt-che" +version = "0.1.0-pre" +description = "Pure Rust implementation of the Belt-CHE authenticated encryption algorithm (STB 34.101.31-2020)" +edition = "2024" +license = "Apache-2.0 OR MIT" +readme = "README.md" +documentation = "https://docs.rs/belt-che" +repository = "https://github.com/RustCrypto/AEADs/tree/master/belt-che" +keywords = ["aead", "belt-che"] +categories = ["cryptography", "no-std"] +rust-version = "1.85" + +[dependencies] +aead = { version = "0.6.0-rc.2", default-features = false } +belt-block = { version = "0.2.0-rc.1" } +belt-ctr = { version = "0.2.0-rc.1" } +opaque-debug = { version = "0.3" } +subtle = { version = "2", default-features = false } +universal-hash = { version = "0.6.0-rc.2" } +zeroize = { version = "1.8", default-features = false, optional = true } + +[dev-dependencies] +hex-literal = "1" + +[features] +default = ["alloc", "os_rng"] +alloc = ["aead/alloc"] +arrayvec = ["aead/arrayvec"] +bytes = ["aead/bytes"] +os_rng = ["aead/os_rng", "rand_core"] +rand_core = ["aead/rand_core"] +reduced-round = [] +zeroize = ["dep:zeroize", "belt-ctr/zeroize"] + +[package.metadata.docs.rs] +all-features = true diff --git a/belt-che/LICENSE-APACHE b/belt-che/LICENSE-APACHE new file mode 100644 index 00000000..69d3d818 --- /dev/null +++ b/belt-che/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 2021 The RustCrypto Project Developers + +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/belt-che/LICENSE-MIT b/belt-che/LICENSE-MIT new file mode 100644 index 00000000..fa2fe6bb --- /dev/null +++ b/belt-che/LICENSE-MIT @@ -0,0 +1,26 @@ +Copyright (c) 2025 The RustCrypto Project Developers +Copyright (c) 2025 Alexandr Kitaev + +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/belt-che/README.md b/belt-che/README.md new file mode 100644 index 00000000..daf6f87f --- /dev/null +++ b/belt-che/README.md @@ -0,0 +1,51 @@ +# RustCrypto: BeltChe + +[![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] + +Pure Rust implementation of the `belt-che` [AEAD] algorithm +specified in the republic of Belarus standard [STB 34.101.31-2020] (Scheme 2). + +## Security Notes + +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](https://www.apache.org/licenses/LICENSE-2.0) +* [MIT license](https://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://buildstats.info/crate/belt-che +[crate-link]: https://crates.io/crates/belt-che +[docs-image]: https://docs.rs/belt-che/badge.svg +[docs-link]: https://docs.rs/belt-che/ +[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 +[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg +[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260038-AEADs +[downloads-image]: https://img.shields.io/crates/d/chacha20poly1305.svg +[build-image]: https://github.com/RustCrypto/AEADs/workflows/belt-che/badge.svg?branch=master&event=push +[build-link]: https://github.com/RustCrypto/AEADs/actions + +[//]: # (general links) + +[STB 34.101.31-2020]: https://apmi.bsu.by/assets/files/std/belt-spec372.pdf +[AEAD]: https://en.wikipedia.org/wiki/Authenticated_encryption diff --git a/belt-che/benches/mod.rs b/belt-che/benches/mod.rs new file mode 100644 index 00000000..511bf72f --- /dev/null +++ b/belt-che/benches/mod.rs @@ -0,0 +1,85 @@ +#![feature(test)] +extern crate test; + +use aead::{ + AeadInOut, KeyInit, + array::Array, + consts::{U16, U32}, +}; +use belt_che::BeltChe; +use hex_literal::hex; +use test::Bencher; + +const KEY: Array = Array(hex!( + "8899AABBCCDDEEFF0011223344556677" + "FEDCBA98765432100123456789ABCDEF" +)); +const NONCE: Array = Array(hex!("1122334455667700FFEEDDCCBBAA9988")); + +#[bench] +fn encrypt_aad_only_16kb(b: &mut Bencher) { + let c = BeltChe::new(&KEY); + let aad = vec![0; 16 * 1024]; + let mut buf = []; + + b.iter(|| { + let (aad, buf, nonce) = test::black_box((&aad, &mut buf[..], &NONCE)); + let res = c.encrypt_inout_detached(nonce, aad, buf.into()).unwrap(); + test::black_box(res); + }); + + b.bytes = 16 * 1024; +} + +#[bench] +fn encrypt_msg_only_16kb(b: &mut Bencher) { + let c = BeltChe::new(&KEY); + let aad = []; + let mut buf = vec![0; 16 * 1024]; + + b.iter(|| { + let (aad, buf, nonce) = test::black_box((&aad, &mut buf[..], &NONCE)); + let res = c.encrypt_inout_detached(nonce, aad, buf.into()).unwrap(); + test::black_box(res); + }); + + b.bytes = 16 * 1024; +} + +#[bench] +fn decrypt_aad_only_16kb(b: &mut Bencher) { + let c = BeltChe::new(&KEY); + let aad = vec![0; 16 * 1024]; + let mut buf = []; + let tag = c + .encrypt_inout_detached(&NONCE, &aad, (&mut buf[..]).into()) + .unwrap(); + + b.iter(|| { + let (aad, buf, nonce, tag) = test::black_box((&aad, &mut buf[..], &NONCE, &tag)); + let res = c.decrypt_inout_detached(nonce, aad, buf.into(), tag); + let _ = test::black_box(res); + }); + + b.bytes = 16 * 1024; +} + +#[bench] +fn decrypt_msg_only_16kb(b: &mut Bencher) { + let c = BeltChe::new(&KEY); + let aad = []; + let mut ct_buf = vec![0u8; 16 * 1024]; + let tag = c + .encrypt_inout_detached(&NONCE, &aad, (&mut ct_buf[..]).into()) + .unwrap(); + + let mut buf = ct_buf.clone(); + b.iter(|| { + let (aad, buf, nonce, tag) = test::black_box((&aad, &mut buf[..], &NONCE, &tag)); + let res = c.decrypt_inout_detached(nonce, aad, buf.into(), tag); + let _ = test::black_box(res); + buf.copy_from_slice(&ct_buf); + }); + + b.bytes = 16 * 1024; +} diff --git a/belt-che/src/gf.rs b/belt-che/src/gf.rs new file mode 100644 index 00000000..48d3ea3b --- /dev/null +++ b/belt-che/src/gf.rs @@ -0,0 +1,46 @@ +use aead::array::{Array, ArraySize}; + +mod utils; + +pub(crate) mod gf128_soft64; + +pub trait GfElement { + type N: ArraySize; + + fn new() -> Self; + fn into_bytes(self) -> Array; + fn mul_sum(&mut self, a: &Array, b: &Array); +} + +/// Tests from Appendix A, table 18 of [STB 34.101.31-2020](https://apmi.bsu.by/assets/files/std/belt-spec372.pdf) +#[test] +fn test_a18() { + use crate::gf::gf128_soft64::Element; + use aead::consts::U16; + use hex_literal::hex; + + type Block = Array; + + let test_vectors = [ + ( + hex!("34904055 11BE3297 1343724C 5AB793E9"), + hex!("22481783 8761A9D6 E3EC9689 110FB0F3"), + hex!("0001D107 FC67DE40 04DC2C80 3DFD95C3"), + ), + ( + hex!("703FCCF0 95EE8DF1 C1ABF8EE 8DF1C1AB"), + hex!("2055704E 2EDB48FE 87E74075 A5E77EB1"), + hex!("4A5C9593 8B3FE8F6 74D59BC1 EB356079"), + ), + ]; + for (u, v, w) in test_vectors { + let a = Block::try_from(&u[..]).unwrap(); + let b = Block::try_from(&v[..]).unwrap(); + let c = Block::try_from(&w[..]).unwrap(); + + let mut elem = Element::new(); + elem.mul_sum(&a, &b); + + assert_eq!(c, elem.into_bytes()); + } +} diff --git a/belt-che/src/gf/gf128_soft64.rs b/belt-che/src/gf/gf128_soft64.rs new file mode 100644 index 00000000..78213ddb --- /dev/null +++ b/belt-che/src/gf/gf128_soft64.rs @@ -0,0 +1,103 @@ +use aead::{array::Array, consts::U16}; +use core::ops::{Add, Mul}; + +use super::{GfElement, utils::bmul64}; + +#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)] +pub struct Element(u64, u64); + +type Block = Array; + +impl GfElement for Element { + type N = U16; + + #[inline(always)] + fn new() -> Self { + Self(0, 0) + } + + #[inline(always)] + fn into_bytes(self) -> Block { + let mut block = Block::default(); + block[8..].copy_from_slice(&self.0.to_le_bytes()); + block[..8].copy_from_slice(&self.1.to_le_bytes()); + block + } + + #[allow(clippy::many_single_char_names)] + fn mul_sum(&mut self, a: &Block, b: &Block) { + let [a1, a0] = from_block(a); + let [b1, b0] = from_block(b); + + let a2 = a1 ^ a0; + let b2 = b1 ^ b0; + + // Multiply using Karatsuba multiplication + let c = bmul64(a1, b1); + let d = bmul64(a0, b0); + let e = bmul64(a2, b2); + let t = c ^ d ^ e; + let v0 = d as u64; + let v1 = ((d >> 64) ^ t) as u64; + let v2 = (c ^ (t >> 64)) as u64; + let v3 = (c >> 64) as u64; + + // reduce over polynomial f(w) = w^128 + w^7 + w^2 + w + 1 + let d = v2 ^ (v3 >> 63) ^ (v3 >> 62) ^ (v3 >> 57); + self.1 ^= v0 ^ d ^ (d << 1) ^ (d << 2) ^ (d << 7); + self.0 ^= v1 ^ v3 ^ (v3 << 1) ^ (v3 << 2) ^ (v3 << 7) ^ (d >> 63) ^ (d >> 62) ^ (d >> 57); + } +} + +impl From for Element { + fn from(x: u128) -> Self { + Self((x >> 64) as u64, x as u64) + } +} + +impl From for Element { + fn from(block: Block) -> Self { + let [a, b] = from_block(&block); + Self(a, b) + } +} + +impl From for Block { + fn from(element: Element) -> Self { + element.into_bytes() + } +} + +impl From<&Block> for Element { + fn from(block: &Block) -> Self { + let [a, b] = from_block(block); + Self(a, b) + } +} + +#[inline(always)] +fn from_block(block: &Block) -> [u64; 2] { + let (a, b) = block.split_at(8); + [ + u64::from_le_bytes(b.try_into().unwrap()), + u64::from_le_bytes(a.try_into().unwrap()), + ] +} + +impl Add for Element { + type Output = Self; + + fn add(self, rhs: Self) -> Self { + Self(self.0 ^ rhs.0, self.1 ^ rhs.1) + } +} + +impl Mul for Element { + type Output = Self; + + fn mul(self, rhs: Self) -> Self { + let mut res = Self::new(); + res.mul_sum(&self.into_bytes(), &rhs.into_bytes()); + res + } +} diff --git a/belt-che/src/gf/utils.rs b/belt-che/src/gf/utils.rs new file mode 100644 index 00000000..ace56682 --- /dev/null +++ b/belt-che/src/gf/utils.rs @@ -0,0 +1,29 @@ +use core::num::Wrapping; + +/// Multiplication in GF(2)[X], truncated to the low 64-bits, with β€œholes” +/// (sequences of zeroes) to avoid carry spilling. +/// +/// When carries do occur, they wind up in a "hole" and are subsequently masked +/// out of the result. +pub(super) fn bmul64(x: u64, y: u64) -> u128 { + let x0 = Wrapping((x & 0x1111_1111_1111_1111) as u128); + let x1 = Wrapping((x & 0x2222_2222_2222_2222) as u128); + let x2 = Wrapping((x & 0x4444_4444_4444_4444) as u128); + let x3 = Wrapping((x & 0x8888_8888_8888_8888) as u128); + let y0 = Wrapping((y & 0x1111_1111_1111_1111) as u128); + let y1 = Wrapping((y & 0x2222_2222_2222_2222) as u128); + let y2 = Wrapping((y & 0x4444_4444_4444_4444) as u128); + let y3 = Wrapping((y & 0x8888_8888_8888_8888) as u128); + + let mut z0 = ((x0 * y0) ^ (x1 * y3) ^ (x2 * y2) ^ (x3 * y1)).0; + let mut z1 = ((x0 * y1) ^ (x1 * y0) ^ (x2 * y3) ^ (x3 * y2)).0; + let mut z2 = ((x0 * y2) ^ (x1 * y1) ^ (x2 * y0) ^ (x3 * y3)).0; + let mut z3 = ((x0 * y3) ^ (x1 * y2) ^ (x2 * y1) ^ (x3 * y0)).0; + + z0 &= 0x1111_1111_1111_1111_1111_1111_1111_1111; + z1 &= 0x2222_2222_2222_2222_2222_2222_2222_2222; + z2 &= 0x4444_4444_4444_4444_4444_4444_4444_4444; + z3 &= 0x8888_8888_8888_8888_8888_8888_8888_8888; + + z0 | z1 | z2 | z3 +} diff --git a/belt-che/src/ghash.rs b/belt-che/src/ghash.rs new file mode 100644 index 00000000..c05dc04f --- /dev/null +++ b/belt-che/src/ghash.rs @@ -0,0 +1,75 @@ +use aead::array::Array; +use aead::consts::{U1, U16}; +use aead::{KeyInit, KeySizeUser}; +use belt_block::cipher::{BlockSizeUser, ParBlocksSizeUser}; +use universal_hash::{Reset, UhfBackend, UhfClosure, UniversalHash}; + +use crate::gf::gf128_soft64::Element; + +/// GHASH keys (16-bytes) +pub type Key = Array; + +/// GHASH blocks (16-bytes) +pub type Block = Array; + +/// GHASH tags (16-bytes) +pub type Tag = Array; + +#[derive(Clone)] +pub struct GHash { + s: Element, + h: Element, +} + +impl KeySizeUser for GHash { + type KeySize = U16; +} + +impl BlockSizeUser for GHash { + type BlockSize = U16; +} + +impl KeyInit for GHash { + fn new(h: &Key) -> Self { + Self::new_with_init_block(h, 0) + } +} + +impl GHash { + pub(crate) fn new_with_init_block(h: &Key, s: u128) -> Self { + Self { + s: Element::from(s), + h: Element::from(h), + } + } +} + +impl ParBlocksSizeUser for GHash { + type ParBlocksSize = U1; +} + +impl UhfBackend for GHash { + fn proc_block(&mut self, x: &Block) { + self.s = (self.s + Element::from(x)) * self.h; + } +} + +impl UniversalHash for GHash { + fn update_with_backend(&mut self, f: impl UhfClosure) { + f.call(self) + } + + /// Get GHASH output + #[inline] + fn finalize(self) -> Tag { + self.s.into() + } +} + +impl Reset for GHash { + fn reset(&mut self) { + self.s = Element::default(); + } +} + +opaque_debug::implement!(GHash); diff --git a/belt-che/src/lib.rs b/belt-che/src/lib.rs new file mode 100644 index 00000000..080383ae --- /dev/null +++ b/belt-che/src/lib.rs @@ -0,0 +1,317 @@ +#![no_std] +#![doc = include_str!("../README.md")] +#![doc( + html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg", + html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg" +)] +#![cfg_attr(docsrs, feature(doc_auto_cfg))] +#![warn(missing_docs)] + +//! # Usage +//! +//! Simple usage (allocating, no associated data): +//! +//! ``` +//! # fn main() -> Result<(), Box> { +//! # #[cfg(feature = "os_rng")] { +//! use belt_che::{ +//! aead::{Aead, AeadCore, KeyInit}, Nonce, BeltChe +//! }; +//! +//! let key = BeltChe::generate_key().unwrap(); +//! let cipher = BeltChe::new(&key); +//! let nonce = BeltChe::generate_nonce().unwrap(); // 128-bits; unique per message +//! let ciphertext = cipher.encrypt(&nonce, b"plaintext message".as_ref())?; +//! let plaintext = cipher.decrypt(&nonce, ciphertext.as_ref())?; +//! assert_eq!(&plaintext, b"plaintext message"); +//! # }; Ok(()) } +//! ``` +//! +//! ## In-place Usage (eliminates `alloc` requirement) +//! +//! This crate has an optional `alloc` feature which can be disabled in e.g. +//! microcontroller environments that don't have a heap. +//! +//! The [`AeadInOut::encrypt_in_place`] and [`AeadInOut::decrypt_in_place`] +//! methods accept any type that impls the [`aead::Buffer`] trait which +//! contains the plaintext for encryption or ciphertext for decryption. +//! +//! Enabling the `arrayvec` feature of this crate will provide an impl of +//! [`aead::Buffer`] for `arrayvec::ArrayVec` (re-exported from the [`aead`] crate as +//! [`aead::arrayvec::ArrayVec`]). +//! +//! It can then be passed as the `buffer` parameter to the in-place encrypt +//! and decrypt methods: +//! +//! ``` +//! # fn main() -> Result<(), Box> { +//! # #[cfg(all(feature = "os_rng", feature = "arrayvec"))] { +//! use belt_che::{ +//! aead::{AeadInOut, KeyInit, arrayvec::ArrayVec}, +//! Nonce, BeltChe +//! }; +//! +//! let key = BeltChe::generate_key().unwrap(); +//! let cipher = BeltChe::new(&key); +//! let nonce = Nonce::try_from(&b"unique nonce1234"[..]).unwrap(); // 128-bits; unique per message +//! +//! let mut buffer: ArrayVec = ArrayVec::new(); // Note: buffer needs 16-bytes overhead for auth tag +//! buffer.try_extend_from_slice(b"plaintext message").unwrap(); +//! +//! // Encrypt `buffer` in-place, replacing the plaintext contents with ciphertext +//! cipher.encrypt_in_place(&nonce, b"", &mut buffer)?; +//! +//! // `buffer` now contains the message ciphertext +//! assert_ne!(buffer.as_ref(), b"plaintext message"); +//! +//! // Decrypt `buffer` in-place, replacing its ciphertext context with the original plaintext +//! cipher.decrypt_in_place(&nonce, b"", &mut buffer)?; +//! assert_eq!(buffer.as_ref(), b"plaintext message"); +//! # }; Ok(()) } +//! ``` + +pub use aead::{self, AeadCore, AeadInOut, Error, Key, KeyInit, KeySizeUser, Tag}; +pub use belt_block::BeltBlock; + +use aead::array::ArraySize; +use aead::consts::{True, U8, U16}; +use aead::{TagPosition, inout::InOutBuf}; +use belt_block::cipher::crypto_common::InnerUser; +use belt_block::cipher::{Block, BlockCipherEncrypt}; +use core::marker::PhantomData; +use universal_hash::UniversalHash; +use universal_hash::crypto_common::{BlockSizeUser, InnerInit}; +use universal_hash::typenum::{IsLessOrEqual, NonZero}; + +/// Nonce type for [`Che`] +pub type Nonce = aead::Nonce; + +mod gf; +mod ghash; + +use crate::gf::gf128_soft64::Element; +use ghash::GHash; + +/// Constant `T` from the STB 34.101.31-2020 +const T: u128 = 0xE45D_4A58_8E00_6D36_3BF5_080A_C8BA_94B1; + +/// `C` = `0x02 || 0^120`, represents polynomial x +const C: u128 = 0x02; + +/// `belt-Che` authenticated encryption with associated data (AEAD) cipher, +/// defined in STB 34.101.31-2020 (scheme 2). +pub type BeltChe = Che; + +/// `belt-Che` authenticated encryption with associated data (AEAD) cipher +/// defined in STB 34.101.31-2020 generic over block cipher implementation +/// and tag size. +pub struct Che +where + C: BlockCipherEncrypt + BlockSizeUser, + TagSize: ArraySize + NonZero + IsLessOrEqual, +{ + cipher: C, + _pd: PhantomData, +} + +impl InnerUser for Che +where + C: BlockCipherEncrypt + BlockSizeUser, + TagSize: ArraySize + NonZero + IsLessOrEqual, +{ + type Inner = C; +} + +impl InnerInit for Che +where + C: BlockCipherEncrypt + BlockSizeUser, + TagSize: ArraySize + NonZero + IsLessOrEqual, +{ + fn inner_init(cipher: Self::Inner) -> Self { + Self { + cipher, + _pd: PhantomData, + } + } +} + +impl AeadInOut for Che +where + C: BlockCipherEncrypt + BlockSizeUser, + TagSize: ArraySize + NonZero + IsLessOrEqual, +{ + fn encrypt_inout_detached( + &self, + nonce: &Nonce, + associated_data: &[u8], + buffer: InOutBuf<'_, '_, u8>, + ) -> aead::Result> { + let buffer_len = buffer.len(); + let sizes_block = get_sizes_block(associated_data.len(), buffer_len); + + // 2.1. 𝑠 ← belt-block(𝑆, 𝐾) + let mut s = *nonce; + self.cipher.encrypt_block(&mut s); + + // 2.2. π‘Ÿ ← 𝑠 + let r = s; + + // 2.3. 𝑑 ← T + let mut ghash = GHash::new_with_init_block(&r, T); + + // 3. For 𝑖 = 1, 2, . . . , π‘š do: + // 3.1 𝑑 ← 𝑑 βŠ• (𝐼𝑖 β€– 0^{128βˆ’|𝐼𝑖|}) + // 3.2 𝑑 ← 𝑑 * π‘Ÿ + ghash.update_padded(associated_data); + + // 4. For 𝑖 = 1, 2, . . . , 𝑛 do: + let c_element = Element::from(C); + let (chunks, mut tail) = buffer.into_chunks::(); + + for mut chunk in chunks { + // 4.1 𝑠 ← (𝑠 * 𝐢) βŠ• ⟨1⟩128 + update_che_counter(&mut s, c_element); + + // 4.2 π‘Œπ‘– ← 𝑋𝑖 βŠ• Lo(belt-block(𝑠, 𝐾), |𝑋𝑖|) + let mut keystream = s; + self.cipher.encrypt_block(&mut keystream); + chunk.xor_in2out(&keystream); + + // 4.3 𝑑 ← 𝑑 βŠ• (π‘Œπ‘– β€– 0^{128βˆ’|π‘Œπ‘–|}) + // 4.4 𝑑 ← 𝑑 * π‘Ÿ + ghash.update_padded(chunk.get_out()); + } + + // 4.1 𝑠 ← (𝑠 * 𝐢) βŠ• ⟨1⟩128 + update_che_counter(&mut s, c_element); + + // 4.2 π‘Œπ‘– ← 𝑋𝑖 βŠ• Lo(belt-block(𝑠, 𝐾), |𝑋𝑖|) + let mut keystream = s; + self.cipher.encrypt_block(&mut keystream); + tail.xor_in2out(&keystream[..tail.len()]); + + // 4.3 𝑑 ← 𝑑 βŠ• (π‘Œπ‘– β€– 0^{128βˆ’|π‘Œπ‘–|}) + // 4.4 𝑑 ← 𝑑 * π‘Ÿ + ghash.update_padded(tail.get_out()); + + // 5. 𝑑 ← 𝑑 βŠ• (⟨|𝐼|⟩64 β€– ⟨|𝑋|⟩64) + ghash.update_padded(&sizes_block); + + // 6. 𝑑 ← belt-block(𝑑 * π‘Ÿ, 𝐾) + let mut tag = ghash.finalize_reset(); + self.cipher.encrypt_block(&mut tag); + + // 7. 𝑇 ← Lo(𝑑, 64) + let tag = &tag[..TagSize::USIZE]; + Ok(tag.try_into().expect("Tag size mismatch")) + } + + fn decrypt_inout_detached( + &self, + nonce: &Nonce, + associated_data: &[u8], + buffer: InOutBuf<'_, '_, u8>, + tag: &Tag, + ) -> aead::Result<()> { + let buffer_len = buffer.len(); + let sizes_block = get_sizes_block(associated_data.len(), buffer_len); + + // 2.1. 𝑠 ← belt-block(𝑆, 𝐾) + let mut s = *nonce; + self.cipher.encrypt_block(&mut s); + + // 2.2. π‘Ÿ ← 𝑠 + let r = s; + + // 2.3. 𝑑 ← T + let mut ghash = GHash::new_with_init_block(&r, T); + + // 3. For 𝑖 = 1, 2, . . . , π‘š do: + // 3.1 𝑑 ← 𝑑 βŠ• (𝐼𝑖 β€– 0^{128βˆ’|𝐼𝑖|}) + // 3.2 𝑑 ← 𝑑 * π‘Ÿ + ghash.update_padded(associated_data); + + // 4. For 𝑖 = 1, 2, . . . , 𝑛 do: + // 4.1 𝑑 ← 𝑑 βŠ• (π‘Œπ‘– β€– 0^{128βˆ’|π‘Œπ‘–|}) + // 4.2 𝑑 ← 𝑑 * π‘Ÿ + ghash.update_padded(buffer.get_in()); + + // 5. 𝑑 ← 𝑑 βŠ• (⟨|𝐼|⟩64 β€– ⟨|π‘Œ|⟩64) + ghash.update_padded(&sizes_block); + + // 6. 𝑑 ← belt-block(𝑑 * π‘Ÿ, 𝐾) + let mut tag_exact = ghash.finalize_reset(); + self.cipher.encrypt_block(&mut tag_exact); + + use subtle::ConstantTimeEq; + + // 7. If 𝑇 β‰  Lo(𝑑, 64), return βŠ₯ + if tag_exact[..TagSize::USIZE].ct_eq(tag).into() { + // 8. For 𝑖 = 1, 2, . . . , 𝑛 do: + let c_element = Element::from(C); + let (chunks, mut tail) = buffer.into_chunks::(); + + for mut chunk in chunks { + // 8.1 𝑠 ← (𝑠 * 𝐢) βŠ• ⟨1⟩128 + update_che_counter(&mut s, c_element); + + // 8.2 𝑋𝑖 ← π‘Œπ‘– βŠ• Lo(belt-block(𝑠, 𝐾), |π‘Œπ‘–|) + let mut keystream = s; + self.cipher.encrypt_block(&mut keystream); + chunk.xor_in2out(&keystream); + } + + // 8.1 𝑠 ← (𝑠 * 𝐢) βŠ• ⟨1⟩128 + update_che_counter(&mut s, c_element); + + // 8.2 𝑋𝑖 ← π‘Œπ‘– βŠ• Lo(belt-block(𝑠, 𝐾), |π‘Œπ‘–|) + let mut keystream = s; + self.cipher.encrypt_block(&mut keystream); + tail.xor_in2out(&keystream[..tail.len()]); + + Ok(()) + } else { + Err(Error) + } + } +} + +impl AeadCore for Che +where + C: BlockCipherEncrypt + BlockSizeUser, + TagSize: ArraySize + NonZero + IsLessOrEqual, +{ + type NonceSize = C::BlockSize; + type TagSize = TagSize; + const TAG_POSITION: TagPosition = TagPosition::Postfix; +} + +/// Updates CHE counter: s ← s * c βŠ• 0x01 +#[inline(always)] +fn update_che_counter(s: &mut Block, c: Element) { + let mut s_elem = Element::from(&*s); + s_elem = s_elem * c; + *s = s_elem.into(); + s[0] ^= 0x01; +} + +/// Get the sizes block for the GHASH +fn get_sizes_block(aad_len: usize, msg_len: usize) -> Block { + let aad_bit_len = aad_len as u64 * 8; + let msg_bit_len = msg_len as u64 * 8; + + let mut sizes_block: Block = Default::default(); + + sizes_block[..8].copy_from_slice(&aad_bit_len.to_le_bytes()); + sizes_block[8..].copy_from_slice(&msg_bit_len.to_le_bytes()); + + sizes_block +} + +#[cfg(feature = "zeroize")] +impl zeroize::ZeroizeOnDrop for Che +where + C: zeroize::ZeroizeOnDrop + BlockCipherEncrypt + BlockSizeUser, + TagSize: ArraySize + NonZero + IsLessOrEqual, +{ +} diff --git a/belt-che/tests/belt.rs b/belt-che/tests/belt.rs new file mode 100644 index 00000000..4d154acb --- /dev/null +++ b/belt-che/tests/belt.rs @@ -0,0 +1,56 @@ +use aead::{AeadInOut, KeyInit}; +use belt_che::BeltChe; +use hex_literal::hex; + +/// Test from Appendix A, tables 19-20 of STB 34.101.31-2020: +/// https://apmi.bsu.by/assets/files/std/belt-spec372.pdf +#[test] +fn test_belt_che() { + struct TestVector { + i: Vec, + k: [u8; 32], + s: [u8; 16], + x: Vec, + y: Vec, + t: [u8; 8], + } + + let test_vectors = [ + TestVector { + i: hex!("8504FA9D 1BB6C7AC 252E72C2 02FDCE0D 5BE3D612 17B96181 FE6786AD 716B890B") + .to_vec(), + k: hex!("E9DEE72C 8F0C0FA6 2DDB49F4 6F739647 06075316 ED247A37 39CBA383 03A98BF6"), + s: hex!("BE329713 43FC9A48 A02A885F 194B09A1"), + x: hex!("B194BAC8 0A08F53B 366D008E 584A5D").to_vec(), + y: hex!("BF3DAEAF 5D18D2BC C30EA62D 2E70A4").to_vec(), + t: hex!("548622B8 44123FF7"), + }, + TestVector { + i: hex!("C1AB7638 9FE678CA F7C6F860 D5BB9C4F F33C657B 637C306A DD4EA779 9EB23D31") + .to_vec(), + k: hex!("92BD9B1C E5D14101 5445FBC9 5E4D0EF2 682080AA 227D642F 2687F934 90405511"), + s: hex!("7ECDA4D0 1544AF8C A58450BF 66D2E88A"), + x: hex!("2BABF43E B37B5398 A9068F31 A3C758B7 62F44AA9").to_vec(), + y: hex!("E12BDC1A E28257EC 703FCCF0 95EE8DF1 C1AB7638").to_vec(), + t: hex!("7D9D4F59 D40D197D"), + }, + ]; + + for vec in test_vectors { + let mut buffer = vec.x.clone(); + let belt_che = BeltChe::new(&vec.k.into()); + + let tag = belt_che + .encrypt_inout_detached(&vec.s.into(), &vec.i, (&mut buffer[..]).into()) + .unwrap(); + + assert_eq!(&vec.t[..], tag.as_slice()); + assert_eq!(&vec.y, &buffer); + + belt_che + .decrypt_inout_detached(&vec.s.into(), &vec.i, (&mut buffer[..]).into(), &tag) + .unwrap(); + + assert_eq!(&vec.x, &buffer); + } +} diff --git a/belt-dwp/README.md b/belt-dwp/README.md index 1b8bb43a..475f1a04 100644 --- a/belt-dwp/README.md +++ b/belt-dwp/README.md @@ -8,7 +8,7 @@ [![Build Status][build-image]][build-link] Pure Rust implementation of the `belt-dwp` [AEAD] algorithm -specified in the republic of Belarus standard [STB 34.101.31-2020]. +specified in the republic of Belarus standard [STB 34.101.31-2020] (Scheme 1). ## Security Notes diff --git a/belt-dwp/src/lib.rs b/belt-dwp/src/lib.rs index 899263e6..0149cb0e 100644 --- a/belt-dwp/src/lib.rs +++ b/belt-dwp/src/lib.rs @@ -97,7 +97,7 @@ use ghash::GHash; const T: u128 = 0xE45D_4A58_8E00_6D36_3BF5_080A_C8BA_94B1; /// `belt-dwp` authenticated encryption with associated data (AEAD) cipher, -/// defined in STB 34.101.31-2020. +/// defined in STB 34.101.31-2020 (Scheme 1). pub type BeltDwp = Dwp; /// `belt-dwp` authenticated encryption with associated data (AEAD) cipher