diff --git a/.github/workflows/xaes-256-gcm.yml b/.github/workflows/xaes-256-gcm.yml new file mode 100644 index 00000000..96fd81f1 --- /dev/null +++ b/.github/workflows/xaes-256-gcm.yml @@ -0,0 +1,69 @@ +name: xaes-256-gcm + +on: + pull_request: + paths: + - ".github/workflows/xaes-256-gcm.yml" + - "xaes-256-gcm/**" + - "Cargo.*" + push: + branches: master + +defaults: + run: + working-directory: xaes-256-gcm + +env: + CARGO_INCREMENTAL: 0 + RUSTFLAGS: "-Dwarnings" + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + rust: + - 1.72.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.72.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.72.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 stream,std + - 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 49c63547..0168050c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -40,6 +40,20 @@ dependencies = [ "zeroize", ] +[[package]] +name = "aes-gcm" +version = "0.11.0-pre.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4ca4317859cecdb9849cf94087998a04efc7beedc07855836cb2534fd9aa4db" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + [[package]] name = "aes-gcm-siv" version = "0.12.0-pre.1" @@ -122,9 +136,9 @@ dependencies = [ [[package]] name = "byteorder" -version = "1.4.3" +version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "ccm" @@ -262,9 +276,9 @@ dependencies = [ [[package]] name = "getrandom" -version = "0.2.12" +version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "190092ea657667030ac6a35e305e62fc4dd69fd98ac98631e5d3a2b1575a12b5" +checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" dependencies = [ "cfg-if", "libc", @@ -327,9 +341,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.153" +version = "0.2.155" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd" +checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" [[package]] name = "ocb3" @@ -387,18 +401,18 @@ dependencies = [ [[package]] name = "proc-macro2" -version = "1.0.79" +version = "1.0.86" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e835ff2298f5721608eb1a980ecaee1aef2c132bf95ecc026a11b7bf3c01c02e" +checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.35" +version = "1.0.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" +checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" dependencies = [ "proc-macro2", ] @@ -420,15 +434,15 @@ checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" [[package]] name = "subtle" -version = "2.5.0" +version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "81cdd64d312baedb58e21336b31bc043b77e01cc99033ce76ef539f78e965ebc" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "syn" -version = "2.0.55" +version = "2.0.72" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "002a1b3dbf967edfafc32655d0f377ab0bb7b994aa1d32c8cc7e9b8bf3ebb8f0" +checksum = "dc4b9b9bf2add8093d3f2c0204471e951b2285580335de42f9d2534f3ae7a8af" dependencies = [ "proc-macro2", "quote", @@ -463,6 +477,17 @@ version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" +[[package]] +name = "xaes-256-gcm" +version = "0.0.1-pre.0" +dependencies = [ + "aead", + "aes", + "aes-gcm 0.11.0-pre.1 (registry+https://github.com/rust-lang/crates.io-index)", + "cipher", + "hex-literal", +] + [[package]] name = "zeroize" version = "1.8.1" diff --git a/Cargo.toml b/Cargo.toml index aa571994..803c983a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,5 +9,6 @@ members = [ "deoxys", "eax", "ocb3", + "xaes-256-gcm", ] resolver = "2" diff --git a/aes-gcm/tests/aes128gcm.rs b/aes-gcm/tests/aes128gcm.rs index 4ded9592..3a26c820 100644 --- a/aes-gcm/tests/aes128gcm.rs +++ b/aes-gcm/tests/aes128gcm.rs @@ -15,7 +15,7 @@ use hex_literal::hex; /// /// /// From: `gcmEncryptExtIV128.rsp` -const TEST_VECTORS: &[TestVector<[u8; 16]>] = &[ +const TEST_VECTORS: &[TestVector<[u8; 16], [u8; 12]>] = &[ TestVector { key: &hex!("11754cd72aec309bf52f7687212e8957"), nonce: &hex!("3c819d9a9bed087615030b65"), diff --git a/aes-gcm/tests/aes256gcm.rs b/aes-gcm/tests/aes256gcm.rs index 294d6a53..eaec80e2 100644 --- a/aes-gcm/tests/aes256gcm.rs +++ b/aes-gcm/tests/aes256gcm.rs @@ -15,7 +15,7 @@ use hex_literal::hex; /// /// /// From: `gcmEncryptExtIV256.rsp` -const TEST_VECTORS: &[TestVector<[u8; 32]>] = &[ +const TEST_VECTORS: &[TestVector<[u8; 32], [u8; 12]>] = &[ TestVector { key: &hex!("b52c505a37d78eda5dd34f20c22540ea1b58963cf8e5bf8ffa85f9f2492505b4"), nonce: &hex!("516c33929df5a3284ff463d7"), diff --git a/aes-gcm/tests/common/mod.rs b/aes-gcm/tests/common/mod.rs index 8760ca63..2cef5f9a 100644 --- a/aes-gcm/tests/common/mod.rs +++ b/aes-gcm/tests/common/mod.rs @@ -2,9 +2,9 @@ /// Test vectors #[derive(Debug)] -pub struct TestVector { +pub struct TestVector { pub key: &'static K, - pub nonce: &'static [u8; 12], + pub nonce: &'static N, pub aad: &'static [u8], pub plaintext: &'static [u8], pub ciphertext: &'static [u8], @@ -27,8 +27,11 @@ macro_rules! tests { let cipher = <$aead>::new(&key); let ciphertext = cipher.encrypt(&nonce, payload).unwrap(); let (ct, tag) = ciphertext.split_at(ciphertext.len() - 16); - assert_eq!(vector.ciphertext, ct); - assert_eq!(vector.tag, tag); + assert_eq!( + vector.ciphertext, ct, + "ciphertext mismatch (expected != actual)" + ); + assert_eq!(vector.tag, tag, "tag mismatch (expected != actual)"); } } @@ -48,7 +51,7 @@ macro_rules! tests { let cipher = <$aead>::new(&key); let plaintext = cipher.decrypt(&nonce, payload).unwrap(); - assert_eq!(vector.plaintext, plaintext.as_slice()); + assert_eq!(vector.plaintext, plaintext.as_slice(), "plaintext mismatch"); } } diff --git a/xaes-256-gcm/CHANGELOG.md b/xaes-256-gcm/CHANGELOG.md new file mode 100644 index 00000000..8297e1ee --- /dev/null +++ b/xaes-256-gcm/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 (TBD) +- Initial release diff --git a/xaes-256-gcm/Cargo.toml b/xaes-256-gcm/Cargo.toml new file mode 100644 index 00000000..2fe1d2c7 --- /dev/null +++ b/xaes-256-gcm/Cargo.toml @@ -0,0 +1,40 @@ +[package] +name = "xaes-256-gcm" +version = "0.0.1-pre.0" +description = """ +Pure Rust implementation of the XAES-256-GCM extended-nonce Authenticated +Encryption with Associated Data (AEAD). +""" +authors = ["RustCrypto Developers"] +edition = "2021" +license = "Apache-2.0 OR MIT" +readme = "README.md" +documentation = "https://docs.rs/xaes-256-gcm" +repository = "https://github.com/RustCrypto/AEADs" +keywords = ["aead", "aes", "xaes", "encryption", "extended-nonce"] +categories = ["cryptography", "no-std"] +rust-version = "1.72" + +[dependencies] +aead = { version = "0.6.0-rc.0", default-features = false } +aes = "=0.9.0-pre.1" +aes-gcm = { version = "=0.11.0-pre.1", default-features = false, features = ["aes"] } +cipher = "=0.5.0-pre.6" + +[dev-dependencies] +aead = { version = "0.6.0-rc.0", features = ["dev"], default-features = false } +hex-literal = "0.4" + +[features] +default = ["alloc", "getrandom"] +std = ["aead/std", "aes-gcm/std", "cipher/std", "alloc"] +alloc = ["aead/alloc", "aes-gcm/alloc"] +arrayvec = ["aead/arrayvec", "aes-gcm/arrayvec"] +getrandom = ["aead/getrandom", "aes-gcm/getrandom", "rand_core"] +heapless = ["aead/heapless", "aes-gcm/heapless"] +rand_core = ["aead/rand_core", "aes-gcm/rand_core"] +stream = ["aead/stream", "aes-gcm/stream"] + +[package.metadata.docs.rs] +all-features = true +rustdoc-args = ["--cfg", "docsrs"] diff --git a/xaes-256-gcm/LICENSE-APACHE b/xaes-256-gcm/LICENSE-APACHE new file mode 100644 index 00000000..78173fa2 --- /dev/null +++ b/xaes-256-gcm/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/xaes-256-gcm/LICENSE-MIT b/xaes-256-gcm/LICENSE-MIT new file mode 100644 index 00000000..455de7c8 --- /dev/null +++ b/xaes-256-gcm/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2024 The RustCrypto Project Developers + +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/xaes-256-gcm/README.md b/xaes-256-gcm/README.md new file mode 100644 index 00000000..b71e0508 --- /dev/null +++ b/xaes-256-gcm/README.md @@ -0,0 +1,56 @@ +# RustCrypto: XAES-256-GCM + +[![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 [XAES-256-GCM][4] extended-nonce +[Authenticated Encryption with Associated Data (AEAD)][1]. + +[Documentation][docs-link] +## Security Notes + +This crate has *NOT* received any security audit. + +Although encryption and decryption passes the test vector, there is no guarantee +of constant-time operation. + +**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/xaes-256-gcm +[crate-link]: https://crates.io/crates/xaes-256-gcm +[docs-image]: https://docs.rs/xaes-256-gcm/badge.svg +[docs-link]: https://docs.rs/xaes-256-gcm/ +[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg +[rustc-image]: https://img.shields.io/badge/rustc-1.56+-blue.svg +[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg +[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260038-AEADs +[build-image]: https://github.com/RustCrypto/AEADs/workflows/xaes-256-gcm/badge.svg?branch=master&event=push +[build-link]: https://github.com/RustCrypto/AEADs/actions + +[//]: # (general links) + +[1]: https://en.wikipedia.org/wiki/Authenticated_encryption +[2]: https://research.nccgroup.com/2020/02/26/public-report-rustcrypto-xaes-256-gcm-and-chacha20poly1305-implementation-review/ +[3]: https://www.mobilecoin.com/ +[4]: https://github.com/C2SP/C2SP/blob/main/XAES-256-GCM.md diff --git a/xaes-256-gcm/src/lib.rs b/xaes-256-gcm/src/lib.rs new file mode 100644 index 00000000..6f6aee46 --- /dev/null +++ b/xaes-256-gcm/src/lib.rs @@ -0,0 +1,197 @@ +#![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" +)] +#![deny(unsafe_code)] +#![warn(missing_docs, rust_2018_idioms)] + +//! # Usage +//! +//! Simple usage (allocating, no associated data): +//! +#![cfg_attr( + all(feature = "getrandom", feature = "heapless", feature = "std"), + doc = "```" +)] +#![cfg_attr( + not(all(feature = "getrandom", feature = "heapless", feature = "std")), + doc = "```ignore" +)] +//! use xaes_256_gcm::{ +//! Xaes256Gcm, Nonce, Key, +//! aead::{Aead, AeadCore, KeyInit, OsRng}, +//! }; +//! +//! # fn gen_key() -> Result<(), core::array::TryFromSliceError> { +//! // The encryption key can be generated randomly: +//! # #[cfg(all(feature = "getrandom", feature = "std"))] { +//! let key = Xaes256Gcm::generate_key().expect("generate key"); +//! # } +//! +//! // Transformed from a byte array: +//! let key: &[u8; 32] = &[42; 32]; +//! let key: &Key = key.into(); +//! +//! // Note that you can get byte array from slice using the `TryInto` trait: +//! let key: &[u8] = &[42; 32]; +//! let key: [u8; 32] = key.try_into()?; +//! # Ok(()) } +//! +//! # fn main() -> Result<(), Box> { +//! // Alternatively, the key can be transformed directly from a byte slice +//! // (panics on length mismatch): +//! # let key: &[u8] = &[42; 32]; +//! let key = ::from_slice(key); +//! +//! let cipher = Xaes256Gcm::new(&key); +//! let nonce = Xaes256Gcm::generate_nonce()?; // 192-bits +//! 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(()) +//! # } +//! ``` + +pub use aead; +pub use aes; +pub use aes_gcm; + +use core::ops::{Div, Mul}; + +use aead::{array::Array, AeadCore, AeadInPlace, Error, KeyInit, KeySizeUser}; +use aes::Aes256; +use aes_gcm::Aes256Gcm; +use cipher::{consts::U2, BlockCipherEncrypt, BlockSizeUser}; + +/// XAES-256-GCM +#[derive(Clone)] +pub struct Xaes256Gcm { + aes: Aes256, + k1: Block, +} + +type KeySize = ::KeySize; +type NonceSize = <::NonceSize as Mul>::Output; +type TagSize = ::TagSize; +type CiphertextOverhead = ::CiphertextOverhead; +type Block = Array::BlockSize>; + +/// XAES-256-GCM nonce. +pub type Nonce = aes_gcm::Nonce; + +/// XAES-256-GCM key. +pub type Key = aes_gcm::Key; + +/// XAES-256-GCM tag. +pub type Tag = aes_gcm::Tag; + +/// Maximum length of plaintext. +pub const P_MAX: u64 = 1 << 36; + +/// Maximum length of associated data. +// pub const A_MAX: u64 = 1 << 61; +pub const A_MAX: u64 = 1 << 36; + +/// Maximum length of ciphertext. +pub const C_MAX: u64 = (1 << 36) + 16; + +impl AeadCore for Xaes256Gcm { + type NonceSize = NonceSize; + type TagSize = TagSize; + type CiphertextOverhead = CiphertextOverhead; +} + +impl KeySizeUser for Xaes256Gcm { + type KeySize = KeySize; +} + +impl KeyInit for Xaes256Gcm { + // Implements step 1 and 2 of the spec. + fn new(key: &Key) -> Self { + let aes = Aes256::new(key); + + // L = AES-256ₖ(0¹²⁸) + let mut k1 = Block::default(); + aes.encrypt_block(&mut k1); + + // If MSB₁(L) = 0 then K1 = L << 1 Else K1 = (L << 1) ⊕ 0¹²⁰10000111 + let mut msb = 0; + for i in (0..k1.len()).rev() { + let new_msb = k1[i] >> 7; + k1[i] = (k1[i] << 1) | msb; + msb = new_msb; + } + + let b = k1.len() - 1; + k1[b] ^= msb * 0b10000111; + + Self { aes, k1 } + } +} + +impl AeadInPlace for Xaes256Gcm { + fn encrypt_in_place_detached( + &self, + nonce: &Nonce, + associated_data: &[u8], + buffer: &mut [u8], + ) -> Result { + if buffer.len() as u64 > P_MAX || associated_data.len() as u64 > A_MAX { + return Err(Error); + } + + let (n1, n) = nonce.split_ref::<>::Output>(); + let k = self.derive_key(n1); + Aes256Gcm::new(&k).encrypt_in_place_detached(n, associated_data, buffer) + } + + fn decrypt_in_place_detached( + &self, + nonce: &Nonce, + associated_data: &[u8], + buffer: &mut [u8], + tag: &Tag, + ) -> Result<(), Error> { + if buffer.len() as u64 > C_MAX || associated_data.len() as u64 > A_MAX { + return Err(Error); + } + + let (n1, n) = nonce.split_ref::<>::Output>(); + let k = self.derive_key(n1); + Aes256Gcm::new(&k).decrypt_in_place_detached(n, associated_data, buffer, tag) + } +} + +impl Xaes256Gcm { + // Implements steps 3 - 5 of the spec. + fn derive_key(&self, n1: &Nonce<>::Output>) -> Key { + // M1 = 0x00 || 0x01 || X || 0x00 || N[:12] + let mut m1 = Block::default(); + m1[..4].copy_from_slice(&[0, 1, b'X', 0]); + m1[4..].copy_from_slice(n1); + + // M2 = 0x00 || 0x02 || X || 0x00 || N[:12] + let mut m2 = Block::default(); + m2[..4].copy_from_slice(&[0, 2, b'X', 0]); + m2[4..].copy_from_slice(n1); + + // Kₘ = AES-256ₖ(M1 ⊕ K1) + // Kₙ = AES-256ₖ(M2 ⊕ K1) + // Kₓ = Kₘ || Kₙ = AES-256ₖ(M1 ⊕ K1) || AES-256ₖ(M2 ⊕ K1) + let mut key: Key = Array::default(); + let (km, kn) = key.split_ref_mut::<>::Output>(); + for i in 0..km.len() { + km[i] = m1[i] ^ self.k1[i]; + } + for i in 0..kn.len() { + kn[i] = m2[i] ^ self.k1[i]; + } + + self.aes.encrypt_block(km); + self.aes.encrypt_block(kn); + key + } +} diff --git a/xaes-256-gcm/tests/xaes256gcm.rs b/xaes-256-gcm/tests/xaes256gcm.rs new file mode 100644 index 00000000..47d9bde7 --- /dev/null +++ b/xaes-256-gcm/tests/xaes256gcm.rs @@ -0,0 +1,34 @@ +//! XAES-256-GCM test vectors + +#[macro_use] +#[path = "../../aes-gcm/tests/common/mod.rs"] +mod common; + +use aes_gcm::aead::{array::Array, Aead, AeadInPlace, KeyInit, Payload}; +use common::TestVector; +use hex_literal::hex; +use xaes_256_gcm::Xaes256Gcm; + +/// C2SP XAES-256-GCM test vectors +/// +/// +const TEST_VECTORS: &[TestVector<[u8; 32], [u8; 24]>] = &[ + TestVector { + key: &hex!("0101010101010101010101010101010101010101010101010101010101010101"), + nonce: b"ABCDEFGHIJKLMNOPQRSTUVWX", + plaintext: b"XAES-256-GCM", + aad: b"", + ciphertext: &hex!("ce546ef63c9cc60765923609"), + tag: &hex!("b33a9a1974e96e52daf2fcf7075e2271"), + }, + TestVector { + key: &hex!("0303030303030303030303030303030303030303030303030303030303030303"), + nonce: b"ABCDEFGHIJKLMNOPQRSTUVWX", + plaintext: b"XAES-256-GCM", + aad: b"c2sp.org/XAES-256-GCM", + ciphertext: &hex!("986ec1832593df5443a17943"), + tag: &hex!("7fd083bf3fdb41abd740a21f71eb769d"), + }, +]; + +tests!(Xaes256Gcm, TEST_VECTORS);