diff --git a/.github/workflows/xaes-256-gcm.yml b/.github/workflows/xaes-256-gcm.yml new file mode 100644 index 00000000..889090fa --- /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.81.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.81.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.81.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 a68bd3b1..d824e9e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -48,6 +48,20 @@ dependencies = [ "zeroize", ] +[[package]] +name = "aes-gcm" +version = "0.11.0-pre.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cce27af05d45b901bb28da33ff8b2b2b2044f595b24fc0f36d4882dae91d484" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + [[package]] name = "aes-gcm-siv" version = "0.12.0-pre.2" @@ -80,9 +94,9 @@ dependencies = [ [[package]] name = "arrayvec" -version = "0.7.6" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" +checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" [[package]] name = "ascon" @@ -112,9 +126,9 @@ checksum = "847495c209977a90e8aad588b959d0ca9f5dc228096d29a6bd3defd53f35eaec" [[package]] name = "block-buffer" -version = "0.11.0-rc.1" +version = "0.11.0-rc.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8969801e57d15e15bc4d7cdc5600dc15ca06a9a62b622bd4871c2d21d8aeb42d" +checksum = "17092d478f4fadfb35a7e082f62e49f0907fdf048801d9d706277e34f9df8a78" dependencies = [ "crypto-common", ] @@ -136,9 +150,9 @@ checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" [[package]] name = "bytes" -version = "1.7.2" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "428d9aa8fbc0670b7b8d6030a7fadd0f86151cae55e4dbbece15f3780a3dfaf3" +checksum = "9ac0150caa2ae65ca5bd83f25c7de183dea78d4d366469f148435e2acfbad0da" [[package]] name = "ccm" @@ -204,9 +218,9 @@ dependencies = [ [[package]] name = "cpufeatures" -version = "0.2.14" +version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "608697df725056feaccfa42cffdaeeec3fccc4ffc38358ecd19b243e716a78e0" +checksum = "53fe5e26ff1b7aef8bca9c6080520cfb8d9333c7568e1829cef191a9723e5504" dependencies = [ "libc", ] @@ -341,9 +355,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.158" +version = "0.2.155" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d8adc4bb1803a324070e64a98ae98f38934d91957a99cfb3a43dcbc01bc56439" +checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" [[package]] name = "ocb3" @@ -410,9 +424,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.37" +version = "1.0.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5b9d34b8991d19d98081b46eacdd8eb58c6f2b201139f7c5f643cc155a633af" +checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" dependencies = [ "proc-macro2", ] @@ -440,9 +454,9 @@ checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] name = "syn" -version = "2.0.77" +version = "2.0.72" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f35bcdf61fd8e7be6caf75f429fdca8beb3ed76584befb503b1569faee373ed" +checksum = "dc4b9b9bf2add8093d3f2c0204471e951b2285580335de42f9d2534f3ae7a8af" dependencies = [ "proc-macro2", "quote", @@ -457,9 +471,9 @@ checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825" [[package]] name = "unicode-ident" -version = "1.0.13" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e91b56cd4cadaeb79bbf1a5645f6b4f8dc5bde8834ad5894a8db35fda9efa1fe" +checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "universal-hash" @@ -477,6 +491,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.2 (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 d6f1c0df..a5c5c263 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,5 +10,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..ecd0db3f --- /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.81" + +[dependencies] +aead = { version = "0.6.0-rc.0", default-features = false } +aes = "=0.9.0-pre.2" +aes-gcm = { version = "=0.11.0-pre.2", default-features = false, features = ["aes"] } +cipher = "=0.5.0-pre.7" + +[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..0be396fa --- /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://img.shields.io/crates/v/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.81+-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);