diff --git a/.github/workflows/belt-dwp.yml b/.github/workflows/belt-dwp.yml new file mode 100644 index 00000000..3358d34d --- /dev/null +++ b/.github/workflows/belt-dwp.yml @@ -0,0 +1,69 @@ +name: belt-dwp + +on: + pull_request: + paths: + - ".github/workflows/belt-dwp.yml" + - "belt-dwp/**" + - "Cargo.*" + push: + branches: master + +defaults: + run: + working-directory: belt-dwp + +env: + CARGO_INCREMENTAL: 0 + RUSTFLAGS: "-Dwarnings" + +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@v4 + - uses: dtolnay/rust-toolchain@master + with: + toolchain: ${{ matrix.rust }} + targets: ${{ matrix.target }} + - run: cargo build --no-default-features --release --target ${{ matrix.target }} + + 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@v4 + - 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 --features heapless + - run: cargo test --target ${{ matrix.target }} --release --all-features + - run: cargo build --target ${{ matrix.target }} --benches diff --git a/Cargo.lock b/Cargo.lock index bfb48af1..65af07d2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -42,7 +42,7 @@ dependencies = [ "cipher", "ctr", "ghash", - "hex-literal", + "hex-literal 0.4.1", "subtle", "zeroize", ] @@ -72,7 +72,7 @@ dependencies = [ "ctr", "dbl", "digest", - "hex-literal", + "hex-literal 0.4.1", "pmac", "zeroize", ] @@ -102,6 +102,38 @@ dependencies = [ "zeroize", ] +[[package]] +name = "belt-block" +version = "0.2.0-pre.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20cce8d102fb5accb008983fb54f0975834bc5f7789080e6564b0f7e13ffe37a" +dependencies = [ + "cipher", +] + +[[package]] +name = "belt-ctr" +version = "0.2.0-pre" +source = "git+https://github.com/RustCrypto/block-modes.git#3ec1c8191dea30def40c033513bbc8bdb3a9cd78" +dependencies = [ + "belt-block", + "cipher", +] + +[[package]] +name = "belt-dwp" +version = "0.1.0" +dependencies = [ + "aead", + "belt-block", + "belt-ctr", + "hex-literal 1.0.0", + "opaque-debug", + "subtle", + "universal-hash", + "zeroize", +] + [[package]] name = "bitflags" version = "2.9.0" @@ -149,7 +181,7 @@ dependencies = [ "aes", "cipher", "ctr", - "hex-literal", + "hex-literal 0.4.1", "subtle", ] @@ -189,6 +221,7 @@ checksum = "276974d2acb7cf592603150941fc1ff6442acdeb1dc653ac2825928f4703c131" dependencies = [ "crypto-common", "inout", + "zeroize", ] [[package]] @@ -243,7 +276,7 @@ version = "0.1.0" dependencies = [ "aead", "aes", - "hex-literal", + "hex-literal 0.4.1", "inout", "subtle", "zeroize", @@ -318,6 +351,12 @@ version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6fe2267d4ed49bc07b63801559be28c718ea06c4738b7a03c94df7386d2cde46" +[[package]] +name = "hex-literal" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bcaaec4551594c969335c98c903c1397853d4198408ea609190f420500f6be71" + [[package]] name = "hybrid-array" version = "0.3.0" @@ -325,6 +364,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4dab50e193aebe510fe0e40230145820e02f48dae0cf339ea4204e6e708ff7bd" dependencies = [ "typenum", + "zeroize", ] [[package]] @@ -352,7 +392,7 @@ dependencies = [ "cipher", "ctr", "dbl", - "hex-literal", + "hex-literal 0.4.1", "subtle", "zeroize", ] @@ -570,7 +610,7 @@ dependencies = [ "aes", "aes-gcm", "cipher", - "hex-literal", + "hex-literal 0.4.1", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index bfec3ed2..81472c3a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,7 @@ members = [ "aes-gcm-siv", "aes-siv", "ascon-aead", + "belt-dwp", "ccm", "chacha20poly1305", "deoxys", @@ -28,3 +29,5 @@ ctr = { git = "https://github.com/RustCrypto/block-modes.git" } ghash = { git = "https://github.com/RustCrypto/universal-hashes.git" } pmac = { git = "https://github.com/RustCrypto/MACs.git" } + +belt-ctr = { git = "https://github.com/RustCrypto/block-modes.git" } \ No newline at end of file diff --git a/belt-dwp/Cargo.toml b/belt-dwp/Cargo.toml new file mode 100644 index 00000000..d0bb180d --- /dev/null +++ b/belt-dwp/Cargo.toml @@ -0,0 +1,39 @@ +[package] +name = "belt-dwp" +version = "0.1.0" +description = "Pure Rust implementation of the Belt-DWP authenticated encryption algorithm (STB 34.101.31-2020)" +edition = "2024" +license = "Apache-2.0 OR MIT" +readme = "README.md" +documentation = "https://docs.rs/belt-dwp" +repository = "https://github.com/RustCrypto/AEADs/tree/master/belt-dwp" +keywords = ["aead", "belt-dwp"] +categories = ["cryptography", "no-std"] +rust-version = "1.85" + +[dependencies] +aead = { version = "0.6.0-rc.0", default-features = false } +zeroize = { version = "1.7", default-features = false, optional = true } +universal-hash = { version = "0.6.0-rc.0" } +opaque-debug = { version = "0.3" } +subtle = { version = "2", default-features = false } + +belt-block = { version = "0.2.0-pre.2" } +belt-ctr = { version = "0.2.0-pre" } + +[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"] +heapless = ["aead/heapless"] +rand_core = ["aead/rand_core"] +reduced-round = [] +zeroize = ["dep:zeroize", "belt-ctr/zeroize"] + +[package.metadata.docs.rs] +all-features = true diff --git a/belt-dwp/README.md b/belt-dwp/README.md new file mode 100644 index 00000000..58a0f7dc --- /dev/null +++ b/belt-dwp/README.md @@ -0,0 +1,57 @@ +# RustCrypto: BeltDwp + +[![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 **BeltDwp** ([STB 34.101.31-2020][1]): an +[Authenticated Encryption with Associated Data (AEAD)][2]. + +## About + +BeltDwp is republic of Belarus standard for authenticated encryption with associated data. + +## 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](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://buildstats.info/crate/belt-dwp +[crate-link]: https://crates.io/crates/belt-dwp +[docs-image]: https://docs.rs/belt-dwp/badge.svg +[docs-link]: https://docs.rs/belt-dwp/ +[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-dwp/badge.svg?branch=master&event=push +[build-link]: https://github.com/RustCrypto/AEADs/actions + +[//]: # (general links) + +[1]: https://apmi.bsu.by/assets/files/std/belt-spec372.pdf +[2]: https://en.wikipedia.org/wiki/Authenticated_encryption +[3]: https://github.com/RustCrypto/stream-ciphers/tree/master/belt-dwp +[4]: https://github.com/RustCrypto/universal-hashes/tree/master/belt-dwp \ No newline at end of file diff --git a/belt-dwp/src/gf.rs b/belt-dwp/src/gf.rs new file mode 100644 index 00000000..48d3ea3b --- /dev/null +++ b/belt-dwp/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-dwp/src/gf/gf128_soft64.rs b/belt-dwp/src/gf/gf128_soft64.rs new file mode 100644 index 00000000..c3ae47f7 --- /dev/null +++ b/belt-dwp/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 polynominal 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-dwp/src/gf/utils.rs b/belt-dwp/src/gf/utils.rs new file mode 100644 index 00000000..0c7b7f97 --- /dev/null +++ b/belt-dwp/src/gf/utils.rs @@ -0,0 +1,30 @@ +#![allow(unused)] +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-dwp/src/ghash.rs b/belt-dwp/src/ghash.rs new file mode 100644 index 00000000..2a136665 --- /dev/null +++ b/belt-dwp/src/ghash.rs @@ -0,0 +1,79 @@ +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), + } + } + + pub(crate) fn xor_s(&mut self, x: &Block) { + self.s = self.s + Element::from(x); + } +} + +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 * self.h).into() + } +} + +impl Reset for GHash { + fn reset(&mut self) { + self.s = Element::default(); + } +} + +opaque_debug::implement!(GHash); diff --git a/belt-dwp/src/lib.rs b/belt-dwp/src/lib.rs new file mode 100644 index 00000000..9d1f6c78 --- /dev/null +++ b/belt-dwp/src/lib.rs @@ -0,0 +1,267 @@ +#![no_std] +#![cfg_attr(docsrs, feature(doc_cfg))] +#![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" +)] +#![warn(missing_docs, rust_2018_idioms)] + +//! # Usage +//! +//! Simple usage (allocating, no associated data): +//! +#![cfg_attr(all(feature = "os_rng", feature = "heapless"), doc = "```")] +#![cfg_attr(not(all(feature = "os_rng", feature = "heapless")), doc = "```ignore")] +//! # fn main() -> Result<(), Box> { +//! use belt_dwp::{ +//! aead::{Aead, AeadCore, KeyInit}, Nonce, BeltDwp +//! }; +//! +//! let key = BeltDwp::generate_key().unwrap(); +//! let cipher = BeltDwp::new(&key); +//! let nonce = BeltDwp::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 [`AeadInPlace::encrypt_in_place`] and [`AeadInPlace::decrypt_in_place`] +//! methods accept any type that impls the [`aead::Buffer`] trait which +//! contains the plaintext for encryption or ciphertext for decryption. +//! +//! Note that if you enable the `heapless` feature of this crate, +//! you will receive an impl of [`aead::Buffer`] for `heapless::Vec` +//! (re-exported from the [`aead`] crate as [`aead::heapless::Vec`]), +//! which can then be passed as the `buffer` parameter to the in-place encrypt +//! and decrypt methods: +//! +#![cfg_attr(all(feature = "os_rng", feature = "heapless"), doc = "```")] +#![cfg_attr(not(all(feature = "os_rng", feature = "heapless")), doc = "```ignore")] +//! # fn main() -> Result<(), Box> { +//! use belt_dwp::{ +//! aead::{AeadInPlace, AeadInPlaceDetached, KeyInit, heapless::Vec}, +//! Nonce, BeltDwp +//! }; +//! +//! let key = BeltDwp::generate_key().unwrap(); +//! let cipher = BeltDwp::new(&key); +//! let nonce = Nonce::try_from(&b"unique nonce1234"[..]).unwrap(); // 128-bits; unique per message +//! +//! let mut buffer: Vec = Vec::new(); // Note: buffer needs 16-bytes overhead for auth tag +//! buffer.extend_from_slice(b"plaintext message"); +//! +//! // Encrypt `buffer` in-place, replacing the plaintext contents with ciphertext +//! cipher.encrypt_in_place(&nonce, b"", &mut buffer)?; +//! +//! // `buffer` now contains the message ciphertext +//! assert_ne!(&buffer, b"plaintext message"); +//! +//! // Decrypt `buffer` in-place, replacing its ciphertext context with the original plaintext +//! cipher.decrypt_in_place(&nonce, b"", &mut buffer)?; +//! assert_eq!(&buffer, b"plaintext message"); +//! # Ok(()) +//! # } +//! ``` +//! +//! Similarly, 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`]). + +use aead::consts::{U8, U16}; +pub use aead::{self, AeadCore, AeadInPlace, Error, Key, KeyInit, KeySizeUser}; +use aead::{AeadInPlaceDetached, PostfixTagged}; +pub use belt_block::BeltBlock; +use belt_block::cipher::crypto_common::InnerUser; +use belt_block::cipher::{Block, BlockCipherEncrypt, StreamCipher}; +use belt_ctr::cipher::InnerIvInit; +use belt_ctr::{BeltCtr, BeltCtrCore}; +use universal_hash::UniversalHash; +use universal_hash::crypto_common::{BlockSizeUser, InnerInit}; + +use crate::ghash::GHash; + +/// Nonce type for [`Dwp`] +pub type Nonce = aead::Nonce; + +/// Tag type for [`Dwp`] +pub type Tag = aead::Tag; + +mod gf; +mod ghash; + +/// T from the STB 34.101.31-2020 +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 +pub type BeltDwp = Dwp; + +/// Belt-DWP authenticated encryption with associated data (AEAD) cipher, defined in +/// STB 34.101.31-2020 +pub struct Dwp +where + C: BlockCipherEncrypt + BlockSizeUser, +{ + cipher: C, +} + +impl InnerUser for Dwp +where + C: BlockCipherEncrypt + BlockSizeUser, +{ + type Inner = C; +} + +impl InnerInit for Dwp +where + C: BlockCipherEncrypt + BlockSizeUser, +{ + fn inner_init(inner: Self::Inner) -> Self { + Self { cipher: inner } + } +} + +impl AeadInPlaceDetached for Dwp +where + C: BlockCipherEncrypt + BlockSizeUser, +{ + fn encrypt_in_place_detached( + &self, + nonce: &Nonce, + associated_data: &[u8], + buffer: &mut [u8], + ) -> aead::Result { + 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. π‘Ÿ ← belt-block(𝑠, 𝐾); + let mut r = s; + self.cipher.encrypt_block(&mut r); + + // Initialize GHash + let mut ghash = GHash::new_with_init_block( + &Key::::try_from(&r[..]).expect("Key is always 16 bytes"), + T, + ); + + // Initialize CTR mode + let core = BeltCtrCore::inner_iv_init(&self.cipher, nonce); + let mut enc_cipher = BeltCtr::from_core(core); + + // 3. For 𝑖 = 1, 2, . . . , π‘š do: + // 3.1 𝑑 ← 𝑑 βŠ• (𝐼𝑖 β€– 0^{128βˆ’|𝐼𝑖|}) + // 3.2 𝑑 ← 𝑑 * π‘Ÿ. + ghash.update_padded(associated_data); + + // 4. For 𝑖 = 1, 2, . . . , 𝑛 do: + // 4.1 𝑠 ← 𝑠 ⊞ ⟨1⟩_128 + // 4.2 π‘Œπ‘– ← 𝑋𝑖 βŠ• Lo(belt-block(𝑠, 𝐾), |𝑋𝑖|) + // 4.3 𝑑 ← 𝑑 βŠ• (π‘Œπ‘– β€– 0^{128βˆ’|π‘Œπ‘–|}) + // 4.4 𝑑 ← 𝑑 * π‘Ÿ. + buffer.chunks_mut(16).for_each(|block| { + enc_cipher.apply_keystream(block); + ghash.update_padded(block); + }); + + // 5. 𝑑 ← 𝑑 βŠ• (⟨|𝐼|⟩_64 β€– ⟨|𝑋|⟩_64) + ghash.xor_s(&sizes_block); + + // 6. 𝑑 ← belt-block(𝑑 * π‘Ÿ, 𝐾). + let mut tag = ghash.finalize_reset(); + self.cipher.encrypt_block(&mut tag); + + Ok(Tag::try_from(&tag[..8]).expect("Tag is always 8 bytes")) + } + + fn decrypt_in_place_detached( + &self, + nonce: &Nonce, + associated_data: &[u8], + buffer: &mut [u8], + tag: &Tag, + ) -> aead::Result<()> { + 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. π‘Ÿ ← belt-block(𝑠, 𝐾); + let mut r = s; + self.cipher.encrypt_block(&mut r); + + // Initialize GHash + let mut ghash = GHash::new_with_init_block( + &Key::::try_from(&r[..]).expect("Key is always 16 bytes"), + 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); + + // 5. 𝑑 ← 𝑑 βŠ• (⟨|𝐼|⟩_64 β€– ⟨|𝑋|⟩_64) + ghash.xor_s(&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[..8].ct_eq(tag).into() { + // 8. For 𝑖 = 1,2,...,𝑛 do: + // 8.1. 𝑠 ← 𝑠 ⊞ ⟨1⟩128; + // 8.2. 𝑋𝑖 ← π‘Œπ‘– βŠ• Lo(belt-block(𝑠, 𝐾), |π‘Œπ‘–|) + let core = BeltCtrCore::inner_iv_init(&self.cipher, nonce); + let mut enc_cipher = BeltCtr::from_core(core); + enc_cipher.apply_keystream(buffer); + Ok(()) + } else { + Err(Error) + } + } +} + +impl PostfixTagged for Dwp where C: BlockCipherEncrypt + BlockSizeUser {} + +impl AeadCore for Dwp +where + C: BlockCipherEncrypt + BlockSizeUser, +{ + type NonceSize = C::BlockSize; + type TagSize = U8; +} + +/// 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 Dwp {} diff --git a/belt-dwp/tests/belt.rs b/belt-dwp/tests/belt.rs new file mode 100644 index 00000000..f405a71b --- /dev/null +++ b/belt-dwp/tests/belt.rs @@ -0,0 +1,48 @@ +use aead::AeadInPlaceDetached; +use belt_dwp::{BeltDwp, KeyInit}; +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_dwp() { + struct TestVector { + i: [u8; 32], + k: [u8; 32], + s: [u8; 16], + x: [u8; 16], + y: [u8; 16], + t: [u8; 8], + } + + let test_vectors = [ + TestVector { + i: hex!("8504FA9D 1BB6C7AC 252E72C2 02FDCE0D 5BE3D612 17B96181 FE6786AD 716B890B"), + k: hex!("E9DEE72C 8F0C0FA6 2DDB49F4 6F739647 06075316 ED247A37 39CBA383 03A98BF6"), + s: hex!("BE329713 43FC9A48 A02A885F 194B09A1"), + x: hex!("B194BAC8 0A08F53B 366D008E 584A5DE4"), + y: hex!("52C9AF96 FF50F644 35FC43DE F56BD797"), + t: hex!("3B2E0AEB 2B91854B"), + }, + TestVector { + i: hex!("C1AB7638 9FE678CA F7C6F860 D5BB9C4F F33C657B 637C306A DD4EA779 9EB23D31"), + k: hex!("92BD9B1C E5D14101 5445FBC9 5E4D0EF2 682080AA 227D642F 2687F934 90405511"), + s: hex!("7ECDA4D0 1544AF8C A58450BF 66D2E88A"), + x: hex!("DF181ED0 08A20F43 DCBBB936 50DAD34B"), + y: hex!("E12BDC1A E28257EC 703FCCF0 95EE8DF1"), + t: hex!("6A2C2C94 C4150DC0"), + }, + ]; + + for vec in test_vectors { + let mut x = vec.x; + let belt_dwp = BeltDwp::new_from_slice(&vec.k).unwrap(); + let tag = belt_dwp.encrypt_in_place_detached(&vec.s.into(), &vec.i, &mut x); + assert_eq!(vec.t, *tag.unwrap()); + assert_eq!(vec.y, x); + belt_dwp + .decrypt_in_place_detached(&vec.s.into(), &vec.i, &mut x, &tag.unwrap()) + .unwrap(); + assert_eq!(x, vec.x); + } +} diff --git a/benches/src/belt-dwp.rs b/benches/src/belt-dwp.rs new file mode 100644 index 00000000..357f9a98 --- /dev/null +++ b/benches/src/belt-dwp.rs @@ -0,0 +1,48 @@ +use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput}; + +use belt_dwp::aead::{Aead, KeyInit}; +use belt_dwp::BeltDwp; + +const KB: usize = 1024; + +#[cfg(not(any(target_arch = "x86_64", target_arch = "x86")))] +type Benchmarker = Criterion; +#[cfg(any(target_arch = "x86_64", target_arch = "x86"))] +type Benchmarker = Criterion; + +fn bench(c: &mut Benchmarker) { + let mut group = c.benchmark_group("beltdwp"); + + for size in &[KB, 2 * KB, 4 * KB, 8 * KB, 16 * KB] { + let buf = vec![0u8; *size]; + + group.throughput(Throughput::Bytes(*size as u64)); + + group.bench_function(BenchmarkId::new("encrypt", size), |b| { + let cipher = BeltDwp::new(&Default::default()); + b.iter(|| cipher.encrypt(&Default::default(), &*buf)) + }); + group.bench_function(BenchmarkId::new("decrypt", size), |b| { + let cipher = BeltDwp::new(&Default::default()); + b.iter(|| cipher.decrypt(&Default::default(), &*buf)) + }); + } + + group.finish(); +} + +#[cfg(not(any(target_arch = "x86_64", target_arch = "x86")))] +criterion_group!( + name = benches; + config = Criterion::default(); + targets = bench +); + +#[cfg(any(target_arch = "x86_64", target_arch = "x86"))] +criterion_group!( + name = benches; + config = Criterion::default().with_measurement(criterion_cycles_per_byte::CyclesPerByte); + targets = bench +); + +criterion_main!(benches);