diff options
Diffstat (limited to '')
-rw-r--r-- | rust/vendor/ctr/.cargo-checksum.json | 1 | ||||
-rw-r--r-- | rust/vendor/ctr/CHANGELOG.md | 59 | ||||
-rw-r--r-- | rust/vendor/ctr/Cargo.toml | 42 | ||||
-rw-r--r-- | rust/vendor/ctr/LICENSE-APACHE | 201 | ||||
-rw-r--r-- | rust/vendor/ctr/LICENSE-MIT | 25 | ||||
-rw-r--r-- | rust/vendor/ctr/README.md | 74 | ||||
-rw-r--r-- | rust/vendor/ctr/benches/aes128.rs | 3 | ||||
-rw-r--r-- | rust/vendor/ctr/src/flavors.rs | 44 | ||||
-rw-r--r-- | rust/vendor/ctr/src/flavors/ctr128.rs | 143 | ||||
-rw-r--r-- | rust/vendor/ctr/src/flavors/ctr32.rs | 143 | ||||
-rw-r--r-- | rust/vendor/ctr/src/flavors/ctr64.rs | 143 | ||||
-rw-r--r-- | rust/vendor/ctr/src/lib.rs | 243 | ||||
-rw-r--r-- | rust/vendor/ctr/tests/ctr128/data/aes128-ctr.blb | bin | 0 -> 2039 bytes | |||
-rw-r--r-- | rust/vendor/ctr/tests/ctr128/data/aes256-ctr.blb | bin | 0 -> 2055 bytes | |||
-rw-r--r-- | rust/vendor/ctr/tests/ctr128/mod.rs | 7 | ||||
-rw-r--r-- | rust/vendor/ctr/tests/ctr32/big_endian.rs | 80 | ||||
-rw-r--r-- | rust/vendor/ctr/tests/ctr32/little_endian.rs | 87 | ||||
-rw-r--r-- | rust/vendor/ctr/tests/ctr32/mod.rs | 9 | ||||
-rw-r--r-- | rust/vendor/ctr/tests/gost/mod.rs | 57 | ||||
-rw-r--r-- | rust/vendor/ctr/tests/lib.rs | 5 |
20 files changed, 1366 insertions, 0 deletions
diff --git a/rust/vendor/ctr/.cargo-checksum.json b/rust/vendor/ctr/.cargo-checksum.json new file mode 100644 index 0000000..55e4f81 --- /dev/null +++ b/rust/vendor/ctr/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"6ce46263eaf0ae5397f34f2ed940464e22756b7e70ee2ec218866cf930d05348","Cargo.toml":"a28ca7f94800fa1f6643750534e83e84c8803b4e037b89a531864cd19412ad47","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"f7e8ab639afef15573680c97f796166835cbeb3865175882fea41c60d106b733","README.md":"3993153d537e73ac1684b3717db16f0e3e2013f912601f0368bcb19bbfe056a7","benches/aes128.rs":"3c497e53504c122e560c10df2ec302df0ad4a029bb4f6850aca695e837ede841","src/flavors.rs":"536f9748fd94b126d474a53ca07f816e9f9fe219d36c74cd8405b94ab64519c4","src/flavors/ctr128.rs":"9ceae02fce32fd11fe4a6c656785551d2e3ec37cc62e11363af89650bf77fd1e","src/flavors/ctr32.rs":"7d60779f68db210954bf791483ea874183774ded8a7b50077bb9c38689da51a8","src/flavors/ctr64.rs":"441decbe21c12caeadadd93e446ed8b46ac0743d79a32ca76b7f7af017702919","src/lib.rs":"d4e53956981e9832f6de178947ac905366764b7551d13096f7e68158c7895775","tests/ctr128/data/aes128-ctr.blb":"352e39148ee059c5398935c86585db078a04fe9529440006c8a90dcd4084ba65","tests/ctr128/data/aes256-ctr.blb":"4970e3dd51b252cfb8e1879a37b098e4653b70bac2e1d2b45b1994cec7a6468a","tests/ctr128/mod.rs":"88a5a7064e3897d14cbab3806a0e3caa06b8d4c130d2ac76841771d167a213e1","tests/ctr32/big_endian.rs":"a75691d648a7de623866ab8258d4881519625a509d50e72d7e5cc33924ea3a46","tests/ctr32/little_endian.rs":"c5e6ff7127cbd2d2467c0f3f56f369dc957dd148272b46f8121d27f278a0fad4","tests/ctr32/mod.rs":"e7aba3d5920557d9eb41e67bdbc10aad5a7671a8acc81f38598cde008fad8cd1","tests/gost/mod.rs":"dbfa950a21c63a4b031797c7fc1bc05918f6029849c741f3ef5ca88b39b5b96b","tests/lib.rs":"7ad05b663e5d8a1be10de069cf2f3424c5c5552be1716cc7c1bbe940605d3656"},"package":"049bb91fb4aaf0e3c7efa6cd5ef877dbbbd15b39dad06d9948de4ec8a75761ea"}
\ No newline at end of file diff --git a/rust/vendor/ctr/CHANGELOG.md b/rust/vendor/ctr/CHANGELOG.md new file mode 100644 index 0000000..857b3ec --- /dev/null +++ b/rust/vendor/ctr/CHANGELOG.md @@ -0,0 +1,59 @@ +# 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.8.0 (2021-07-08) +### Changed +- Make implementation generic over block size (previously it +was generic only over 128-bit block ciphers). Breaking changes +in the `CtrFlavor` API. ([#252]). + +[#252]: https://github.com/RustCrypto/stream-ciphers/pull/252 + +## 0.7.0 (2020-04-29) +### Changed +- Generic implementation of CTR ([#195]) +- Removed `Ctr32LE` mask bit ([#197]) +- Bump `cipher` crate dependency to v0.3 ([#226]) + +[#195]: https://github.com/RustCrypto/stream-ciphers/pull/195 +[#197]: https://github.com/RustCrypto/stream-ciphers/pull/197 +[#226]: https://github.com/RustCrypto/stream-ciphers/pull/226 + +## 0.6.0 (2020-10-16) +### Added +- `Ctr32BE` and `Ctr32LE` ([#170]) + +### Changed +- Replace `block-cipher`/`stream-cipher` with `cipher` crate ([#177]) + +[#177]: https://github.com/RustCrypto/stream-ciphers/pull/177 +[#170]: https://github.com/RustCrypto/stream-ciphers/pull/170 + +## 0.5.0 (2020-08-26) +### Changed +- Bump `stream-cipher` dependency to v0.7, implement the `FromBlockCipher` trait ([#161], [#164]) + +[#161]: https://github.com/RustCrypto/stream-ciphers/pull/161 +[#164]: https://github.com/RustCrypto/stream-ciphers/pull/164 + +## 0.4.0 (2020-06-06) +### Changed +- Upgrade to the `stream-cipher` v0.4 crate ([#116], [#138]) +- Upgrade to Rust 2018 edition ([#116]) + +[#138]: https://github.com/RustCrypto/stream-ciphers/pull/138 +[#116]: https://github.com/RustCrypto/stream-ciphers/pull/121 + +## 0.3.2 (2019-03-11) + +## 0.3.0 (2018-11-01) + +## 0.2.0 (2018-10-13) + +## 0.1.1 (2018-10-13) + +## 0.1.0 (2018-07-30) diff --git a/rust/vendor/ctr/Cargo.toml b/rust/vendor/ctr/Cargo.toml new file mode 100644 index 0000000..701d540 --- /dev/null +++ b/rust/vendor/ctr/Cargo.toml @@ -0,0 +1,42 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you believe there's an error in this file please file an +# issue against the rust-lang/cargo repository. If you're +# editing this file be aware that the upstream Cargo.toml +# will likely look very different (and much more reasonable) + +[package] +edition = "2018" +name = "ctr" +version = "0.8.0" +authors = ["RustCrypto Developers"] +description = "CTR block mode of operation" +documentation = "https://docs.rs/ctr" +readme = "README.md" +keywords = ["crypto", "stream-cipher", "trait"] +categories = ["cryptography", "no-std"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/RustCrypto/stream-ciphers" +[dependencies.cipher] +version = "0.3" +[dev-dependencies.aes] +version = "0.7" +features = ["force-soft"] + +[dev-dependencies.cipher] +version = "0.3" +features = ["dev"] + +[dev-dependencies.hex-literal] +version = "0.2" + +[dev-dependencies.kuznyechik] +version = "0.7" + +[dev-dependencies.magma] +version = "0.7" diff --git a/rust/vendor/ctr/LICENSE-APACHE b/rust/vendor/ctr/LICENSE-APACHE new file mode 100644 index 0000000..78173fa --- /dev/null +++ b/rust/vendor/ctr/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/rust/vendor/ctr/LICENSE-MIT b/rust/vendor/ctr/LICENSE-MIT new file mode 100644 index 0000000..f5b157a --- /dev/null +++ b/rust/vendor/ctr/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2018 Artyom Pavlov + +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/rust/vendor/ctr/README.md b/rust/vendor/ctr/README.md new file mode 100644 index 0000000..8a4caff --- /dev/null +++ b/rust/vendor/ctr/README.md @@ -0,0 +1,74 @@ +# RustCrypto: Counter Mode (CTR) + +[![Crate][crate-image]][crate-link] +[![Docs][docs-image]][docs-link] +![Apache2/MIT licensed][license-image] +![Rust Version][rustc-image] +[![Project Chat][chat-image]][chat-link] +[![Build Status][build-image]][build-link] +[![HAZMAT][hazmat-image]][hazmat-link] + +Generic implementations of the [Counter Mode (CTR)][1] of operation for +block ciphers, which enables adapting block ciphers into stream ciphers. + +[Documentation][docs-link] + +<img alt="diagram" src="https://raw.githubusercontent.com/RustCrypto/meta/master/img/stream-ciphers/ctr.png" width="500px"> + +## ⚠️ Security Warning: [Hazmat!][hazmat-link] + +This crate does not ensure ciphertexts are authentic (i.e. by using a MAC to +verify ciphertext integrity), which can lead to serious vulnerabilities +if used incorrectly! + +No security audits of this crate have ever been performed, and it has not been +thoroughly assessed to ensure its operation is constant-time on common CPU +architectures. + +**USE AT YOUR OWN RISK!** + +## Minimum Supported Rust Version + +Rust **1.41** or higher. + +Minimum supported Rust version can be changed in the future, but it will be +done with a minor version bump. + +## SemVer Policy + +- All on-by-default features of this library are covered by SemVer +- MSRV is considered exempt from SemVer as noted above + +## 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/ctr.svg +[crate-link]: https://crates.io/crates/ctr +[docs-image]: https://docs.rs/ctr/badge.svg +[docs-link]: https://docs.rs/ctr/ +[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg +[rustc-image]: https://img.shields.io/badge/rustc-1.41+-blue.svg +[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg +[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260049-stream-ciphers +[build-image]: https://github.com/RustCrypto/stream-ciphers/workflows/ctr/badge.svg?branch=master&event=push +[build-link]: https://github.com/RustCrypto/stream-ciphers/actions?query=workflow%3Actr +[hazmat-image]: https://img.shields.io/badge/crypto-hazmat%E2%9A%A0-red.svg +[hazmat-link]: https://github.com/RustCrypto/meta/blob/master/HAZMAT.md + +[//]: # (footnotes) + +[1]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#CTR diff --git a/rust/vendor/ctr/benches/aes128.rs b/rust/vendor/ctr/benches/aes128.rs new file mode 100644 index 0000000..f3262a0 --- /dev/null +++ b/rust/vendor/ctr/benches/aes128.rs @@ -0,0 +1,3 @@ +#![feature(test)] + +cipher::stream_cipher_sync_bench!(ctr::Ctr128<aes::Aes128>); diff --git a/rust/vendor/ctr/src/flavors.rs b/rust/vendor/ctr/src/flavors.rs new file mode 100644 index 0000000..225e302 --- /dev/null +++ b/rust/vendor/ctr/src/flavors.rs @@ -0,0 +1,44 @@ +//! CTR mode flavors + +use cipher::{ + generic_array::{ArrayLength, GenericArray}, + SeekNum, +}; + +mod ctr128; +mod ctr32; +mod ctr64; + +pub use ctr128::*; +pub use ctr32::*; +pub use ctr64::*; + +/// Trait implemented by different counter types used in the CTR mode. +pub trait CtrFlavor<B> +where + Self: Default + Clone, + B: ArrayLength<u8>, +{ + /// Inner representation of nonce. + type Nonce: Clone; + /// Backend numeric type + type Backend: SeekNum; + + /// Generate block for given `nonce` value. + fn generate_block(&self, nonce: &Self::Nonce) -> GenericArray<u8, B>; + + /// Load nonce value from bytes. + fn load(block: &GenericArray<u8, B>) -> Self::Nonce; + + /// Checked addition. + fn checked_add(&self, rhs: usize) -> Option<Self>; + + /// Wrapped increment. + fn increment(&mut self); + + /// Convert from a backend value + fn from_backend(v: Self::Backend) -> Self; + + /// Convert to a backend value + fn to_backend(&self) -> Self::Backend; +} diff --git a/rust/vendor/ctr/src/flavors/ctr128.rs b/rust/vendor/ctr/src/flavors/ctr128.rs new file mode 100644 index 0000000..f5a85de --- /dev/null +++ b/rust/vendor/ctr/src/flavors/ctr128.rs @@ -0,0 +1,143 @@ +//! 128-bit counter falvors. +use super::CtrFlavor; +use cipher::generic_array::{ + typenum::{operator_aliases::PartialQuot, type_operators::PartialDiv, Unsigned, U16}, + ArrayLength, GenericArray, +}; +use core::convert::TryInto; + +type ChunkSize = U16; +type Chunks<B> = PartialQuot<B, ChunkSize>; +const CS: usize = ChunkSize::USIZE; + +/// 128-bit big endian counter flavor. +#[derive(Default, Clone)] +#[repr(transparent)] +pub struct Ctr128BE(u128); + +impl<B> CtrFlavor<B> for Ctr128BE +where + Self: Default + Clone, + B: ArrayLength<u8> + PartialDiv<ChunkSize>, + Chunks<B>: ArrayLength<u128>, +{ + type Nonce = GenericArray<u128, Chunks<B>>; + type Backend = u128; + + #[inline] + fn generate_block(&self, nonce: &Self::Nonce) -> GenericArray<u8, B> { + let mut block = GenericArray::<u8, B>::default(); + for i in 0..Chunks::<B>::USIZE { + let t = if i == Chunks::<B>::USIZE - 1 { + self.0.wrapping_add(nonce[i]).to_be_bytes() + } else { + nonce[i].to_ne_bytes() + }; + block[CS * i..][..CS].copy_from_slice(&t); + } + block + } + + #[inline] + fn load(block: &GenericArray<u8, B>) -> Self::Nonce { + let mut res = Self::Nonce::default(); + for i in 0..Chunks::<B>::USIZE { + let chunk = block[CS * i..][..CS].try_into().unwrap(); + res[i] = if i == Chunks::<B>::USIZE - 1 { + u128::from_be_bytes(chunk) + } else { + u128::from_ne_bytes(chunk) + } + } + res + } + + #[inline] + fn checked_add(&self, rhs: usize) -> Option<Self> { + rhs.try_into() + .ok() + .and_then(|rhs| self.0.checked_add(rhs)) + .map(Self) + } + + #[inline] + fn increment(&mut self) { + self.0 = self.0.wrapping_add(1); + } + + #[inline] + fn to_backend(&self) -> Self::Backend { + self.0 + } + + #[inline] + fn from_backend(v: Self::Backend) -> Self { + Self(v) + } +} + +/// 128-bit little endian counter flavor. +#[derive(Default, Clone)] +#[repr(transparent)] +pub struct Ctr128LE(u128); + +impl<B> CtrFlavor<B> for Ctr128LE +where + Self: Default + Clone, + B: ArrayLength<u8> + PartialDiv<ChunkSize>, + Chunks<B>: ArrayLength<u128>, +{ + type Nonce = GenericArray<u128, Chunks<B>>; + type Backend = u128; + + #[inline] + fn generate_block(&self, nonce: &Self::Nonce) -> GenericArray<u8, B> { + let mut block = GenericArray::<u8, B>::default(); + for i in 0..Chunks::<B>::USIZE { + let t = if i == 0 { + self.0.wrapping_add(nonce[i]).to_le_bytes() + } else { + nonce[i].to_ne_bytes() + }; + block[CS * i..][..CS].copy_from_slice(&t); + } + block + } + + #[inline] + fn load(block: &GenericArray<u8, B>) -> Self::Nonce { + let mut res = Self::Nonce::default(); + for i in 0..Chunks::<B>::USIZE { + let chunk = block[CS * i..][..CS].try_into().unwrap(); + res[i] = if i == 0 { + u128::from_le_bytes(chunk) + } else { + u128::from_ne_bytes(chunk) + } + } + res + } + + #[inline] + fn checked_add(&self, rhs: usize) -> Option<Self> { + rhs.try_into() + .ok() + .and_then(|rhs| self.0.checked_add(rhs)) + .map(Self) + } + + #[inline] + fn increment(&mut self) { + self.0 = self.0.wrapping_add(1); + } + + #[inline] + fn to_backend(&self) -> Self::Backend { + self.0 + } + + #[inline] + fn from_backend(v: Self::Backend) -> Self { + Self(v) + } +} diff --git a/rust/vendor/ctr/src/flavors/ctr32.rs b/rust/vendor/ctr/src/flavors/ctr32.rs new file mode 100644 index 0000000..b9d1003 --- /dev/null +++ b/rust/vendor/ctr/src/flavors/ctr32.rs @@ -0,0 +1,143 @@ +//! 32-bit counter falvors. +use super::CtrFlavor; +use cipher::generic_array::{ + typenum::{operator_aliases::PartialQuot, type_operators::PartialDiv, Unsigned, U4}, + ArrayLength, GenericArray, +}; +use core::convert::TryInto; + +type ChunkSize = U4; +type Chunks<B> = PartialQuot<B, ChunkSize>; +const CS: usize = ChunkSize::USIZE; + +/// 32-bit big endian counter flavor. +#[derive(Default, Copy, Clone)] +#[repr(transparent)] +pub struct Ctr32BE(u32); + +impl<B> CtrFlavor<B> for Ctr32BE +where + Self: Default + Clone, + B: ArrayLength<u8> + PartialDiv<ChunkSize>, + Chunks<B>: ArrayLength<u32>, +{ + type Nonce = GenericArray<u32, Chunks<B>>; + type Backend = u32; + + #[inline] + fn generate_block(&self, nonce: &Self::Nonce) -> GenericArray<u8, B> { + let mut block = GenericArray::<u8, B>::default(); + for i in 0..Chunks::<B>::USIZE { + let t = if i == Chunks::<B>::USIZE - 1 { + self.0.wrapping_add(nonce[i]).to_be_bytes() + } else { + nonce[i].to_ne_bytes() + }; + block[CS * i..][..CS].copy_from_slice(&t); + } + block + } + + #[inline] + fn load(block: &GenericArray<u8, B>) -> Self::Nonce { + let mut res = Self::Nonce::default(); + for i in 0..Chunks::<B>::USIZE { + let chunk = block[CS * i..][..CS].try_into().unwrap(); + res[i] = if i == Chunks::<B>::USIZE - 1 { + u32::from_be_bytes(chunk) + } else { + u32::from_ne_bytes(chunk) + } + } + res + } + + #[inline] + fn checked_add(&self, rhs: usize) -> Option<Self> { + rhs.try_into() + .ok() + .and_then(|rhs| self.0.checked_add(rhs)) + .map(Self) + } + + #[inline] + fn increment(&mut self) { + self.0 = self.0.wrapping_add(1); + } + + #[inline] + fn to_backend(&self) -> Self::Backend { + self.0 + } + + #[inline] + fn from_backend(v: Self::Backend) -> Self { + Self(v) + } +} + +/// 32-bit little endian counter flavor. +#[derive(Default, Clone)] +#[repr(transparent)] +pub struct Ctr32LE(u32); + +impl<B> CtrFlavor<B> for Ctr32LE +where + Self: Default + Clone, + B: ArrayLength<u8> + PartialDiv<ChunkSize>, + Chunks<B>: ArrayLength<u32>, +{ + type Nonce = GenericArray<u32, Chunks<B>>; + type Backend = u32; + + #[inline] + fn generate_block(&self, nonce: &Self::Nonce) -> GenericArray<u8, B> { + let mut block = GenericArray::<u8, B>::default(); + for i in 0..Chunks::<B>::USIZE { + let t = if i == 0 { + self.0.wrapping_add(nonce[i]).to_le_bytes() + } else { + nonce[i].to_ne_bytes() + }; + block[CS * i..][..CS].copy_from_slice(&t); + } + block + } + + #[inline] + fn load(block: &GenericArray<u8, B>) -> Self::Nonce { + let mut res = Self::Nonce::default(); + for i in 0..Chunks::<B>::USIZE { + let chunk = block[CS * i..][..CS].try_into().unwrap(); + res[i] = if i == 0 { + u32::from_le_bytes(chunk) + } else { + u32::from_ne_bytes(chunk) + } + } + res + } + + #[inline] + fn checked_add(&self, rhs: usize) -> Option<Self> { + rhs.try_into() + .ok() + .and_then(|rhs| self.0.checked_add(rhs)) + .map(Self) + } + + #[inline] + fn increment(&mut self) { + self.0 = self.0.wrapping_add(1); + } + + #[inline] + fn to_backend(&self) -> Self::Backend { + self.0 + } + + #[inline] + fn from_backend(v: Self::Backend) -> Self { + Self(v) + } +} diff --git a/rust/vendor/ctr/src/flavors/ctr64.rs b/rust/vendor/ctr/src/flavors/ctr64.rs new file mode 100644 index 0000000..bad1a78 --- /dev/null +++ b/rust/vendor/ctr/src/flavors/ctr64.rs @@ -0,0 +1,143 @@ +//! 64-bit counter falvors. +use super::CtrFlavor; +use cipher::generic_array::{ + typenum::{operator_aliases::PartialQuot, type_operators::PartialDiv, Unsigned, U8}, + ArrayLength, GenericArray, +}; +use core::convert::TryInto; + +type ChunkSize = U8; +type Chunks<B> = PartialQuot<B, ChunkSize>; +const CS: usize = ChunkSize::USIZE; + +/// 64-bit big endian counter flavor. +#[derive(Default, Copy, Clone)] +#[repr(transparent)] +pub struct Ctr64BE(u64); + +impl<B> CtrFlavor<B> for Ctr64BE +where + Self: Default + Clone, + B: ArrayLength<u8> + PartialDiv<ChunkSize>, + Chunks<B>: ArrayLength<u64>, +{ + type Nonce = GenericArray<u64, Chunks<B>>; + type Backend = u64; + + #[inline] + fn generate_block(&self, nonce: &Self::Nonce) -> GenericArray<u8, B> { + let mut block = GenericArray::<u8, B>::default(); + for i in 0..Chunks::<B>::USIZE { + let t = if i == Chunks::<B>::USIZE - 1 { + self.0.wrapping_add(nonce[i]).to_be_bytes() + } else { + nonce[i].to_ne_bytes() + }; + block[CS * i..][..CS].copy_from_slice(&t); + } + block + } + + #[inline] + fn load(block: &GenericArray<u8, B>) -> Self::Nonce { + let mut res = Self::Nonce::default(); + for i in 0..Chunks::<B>::USIZE { + let chunk = block[CS * i..][..CS].try_into().unwrap(); + res[i] = if i == Chunks::<B>::USIZE - 1 { + u64::from_be_bytes(chunk) + } else { + u64::from_ne_bytes(chunk) + } + } + res + } + + #[inline] + fn checked_add(&self, rhs: usize) -> Option<Self> { + rhs.try_into() + .ok() + .and_then(|rhs| self.0.checked_add(rhs)) + .map(Self) + } + + #[inline] + fn increment(&mut self) { + self.0 = self.0.wrapping_add(1); + } + + #[inline] + fn to_backend(&self) -> Self::Backend { + self.0 + } + + #[inline] + fn from_backend(v: Self::Backend) -> Self { + Self(v) + } +} + +/// 64-bit little endian counter flavor. +#[derive(Default, Clone)] +#[repr(transparent)] +pub struct Ctr64LE(u64); + +impl<B> CtrFlavor<B> for Ctr64LE +where + Self: Default + Clone, + B: ArrayLength<u8> + PartialDiv<ChunkSize>, + Chunks<B>: ArrayLength<u64>, +{ + type Nonce = GenericArray<u64, Chunks<B>>; + type Backend = u64; + + #[inline] + fn generate_block(&self, nonce: &Self::Nonce) -> GenericArray<u8, B> { + let mut block = GenericArray::<u8, B>::default(); + for i in 0..Chunks::<B>::USIZE { + let t = if i == 0 { + self.0.wrapping_add(nonce[i]).to_le_bytes() + } else { + nonce[i].to_ne_bytes() + }; + block[CS * i..][..CS].copy_from_slice(&t); + } + block + } + + #[inline] + fn load(block: &GenericArray<u8, B>) -> Self::Nonce { + let mut res = Self::Nonce::default(); + for i in 0..Chunks::<B>::USIZE { + let chunk = block[CS * i..][..CS].try_into().unwrap(); + res[i] = if i == 0 { + u64::from_le_bytes(chunk) + } else { + u64::from_ne_bytes(chunk) + } + } + res + } + + #[inline] + fn checked_add(&self, rhs: usize) -> Option<Self> { + rhs.try_into() + .ok() + .and_then(|rhs| self.0.checked_add(rhs)) + .map(Self) + } + + #[inline] + fn increment(&mut self) { + self.0 = self.0.wrapping_add(1); + } + + #[inline] + fn to_backend(&self) -> Self::Backend { + self.0 + } + + #[inline] + fn from_backend(v: Self::Backend) -> Self { + Self(v) + } +} diff --git a/rust/vendor/ctr/src/lib.rs b/rust/vendor/ctr/src/lib.rs new file mode 100644 index 0000000..c75a901 --- /dev/null +++ b/rust/vendor/ctr/src/lib.rs @@ -0,0 +1,243 @@ +//! Generic implementations of CTR mode for block ciphers. +//! +//! Mode functionality is accessed using traits from re-exported +//! [`cipher`](https://docs.rs/cipher) crate. +//! +//! # ⚠️ Security Warning: [Hazmat!] +//! +//! This crate does not ensure ciphertexts are authentic! Thus ciphertext integrity +//! is not verified, which can lead to serious vulnerabilities! +//! +//! # `Ctr128` Usage Example +//! +//! ``` +//! use ctr::cipher::{NewCipher, StreamCipher, StreamCipherSeek}; +//! +//! // `aes` crate provides AES block cipher implementation +//! type Aes128Ctr = ctr::Ctr128BE<aes::Aes128>; +//! +//! let mut data = [1, 2, 3, 4, 5, 6, 7]; +//! +//! let key = b"very secret key."; +//! let nonce = b"and secret nonce"; +//! +//! // create cipher instance +//! let mut cipher = Aes128Ctr::new(key.into(), nonce.into()); +//! +//! // apply keystream (encrypt) +//! cipher.apply_keystream(&mut data); +//! assert_eq!(data, [6, 245, 126, 124, 180, 146, 37]); +//! +//! // seek to the keystream beginning and apply it again to the `data` (decrypt) +//! cipher.seek(0); +//! cipher.apply_keystream(&mut data); +//! assert_eq!(data, [1, 2, 3, 4, 5, 6, 7]); +//! ``` +//! +//! [Hazmat!]: https://github.com/RustCrypto/meta/blob/master/HAZMAT.md + +#![no_std] +#![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)] + +pub use cipher; +use cipher::{ + errors::{LoopError, OverflowError}, + generic_array::typenum::Unsigned, + Block, BlockEncrypt, FromBlockCipher, ParBlocks, SeekNum, StreamCipher, StreamCipherSeek, +}; +use core::fmt; + +pub mod flavors; +use flavors::CtrFlavor; + +/// CTR mode with 128-bit big endian counter. +pub type Ctr128BE<B> = Ctr<B, flavors::Ctr128BE>; +/// CTR mode with 128-bit little endian counter. +pub type Ctr128LE<B> = Ctr<B, flavors::Ctr128LE>; +/// CTR mode with 64-bit big endian counter. +pub type Ctr64BE<B> = Ctr<B, flavors::Ctr64BE>; +/// CTR mode with 64-bit little endian counter. +pub type Ctr64LE<B> = Ctr<B, flavors::Ctr64LE>; +/// CTR mode with 32-bit big endian counter. +pub type Ctr32BE<B> = Ctr<B, flavors::Ctr32BE>; +/// CTR mode with 32-bit little endian counter. +pub type Ctr32LE<B> = Ctr<B, flavors::Ctr32LE>; + +/// Generic CTR block mode isntance. +#[derive(Clone)] +pub struct Ctr<B, F> +where + B: BlockEncrypt, + F: CtrFlavor<B::BlockSize>, +{ + cipher: B, + nonce: <F as CtrFlavor<B::BlockSize>>::Nonce, + counter: F, + buffer: Block<B>, + buf_pos: u8, +} + +impl<B, F> Ctr<B, F> +where + B: BlockEncrypt, + F: CtrFlavor<B::BlockSize>, +{ + fn check_data_len(&self, data: &[u8]) -> Result<(), LoopError> { + let bs = B::BlockSize::USIZE; + let leftover_bytes = bs - self.buf_pos as usize; + if data.len() < leftover_bytes { + return Ok(()); + } + let blocks = 1 + (data.len() - leftover_bytes) / bs; + self.counter + .checked_add(blocks) + .ok_or(LoopError) + .map(|_| ()) + } + + /// Seek to the given block + // TODO: replace with a trait-based method + pub fn seek_block(&mut self, block: F::Backend) { + self.counter = F::from_backend(block); + } + + /// Return number of the current block + // TODO: replace with a trait-based method + pub fn current_block(&self) -> F::Backend { + self.counter.to_backend() + } +} + +impl<B, F> FromBlockCipher for Ctr<B, F> +where + B: BlockEncrypt, + F: CtrFlavor<B::BlockSize>, +{ + type BlockCipher = B; + type NonceSize = B::BlockSize; + + #[inline] + fn from_block_cipher(cipher: B, nonce: &Block<B>) -> Self { + let nonce = F::load(nonce); + Self { + cipher, + buffer: Default::default(), + nonce, + counter: Default::default(), + buf_pos: 0, + } + } +} + +impl<B, F> StreamCipher for Ctr<B, F> +where + B: BlockEncrypt, + F: CtrFlavor<B::BlockSize>, +{ + fn try_apply_keystream(&mut self, mut data: &mut [u8]) -> Result<(), LoopError> { + self.check_data_len(data)?; + let bs = B::BlockSize::USIZE; + let pos = self.buf_pos as usize; + debug_assert!(bs > pos); + + let mut counter = self.counter.clone(); + if pos != 0 { + if data.len() < bs - pos { + let n = pos + data.len(); + xor(data, &self.buffer[pos..n]); + self.buf_pos = n as u8; + return Ok(()); + } else { + let (l, r) = data.split_at_mut(bs - pos); + data = r; + xor(l, &self.buffer[pos..]); + counter.increment(); + } + } + + // Process blocks in parallel if cipher supports it + let pb = B::ParBlocks::USIZE; + if pb != 1 { + let mut chunks = data.chunks_exact_mut(bs * pb); + let mut blocks: ParBlocks<B> = Default::default(); + for chunk in &mut chunks { + for b in blocks.iter_mut() { + *b = counter.generate_block(&self.nonce); + counter.increment(); + } + + self.cipher.encrypt_par_blocks(&mut blocks); + xor(chunk, to_slice::<B>(&blocks)); + } + data = chunks.into_remainder(); + } + + let mut chunks = data.chunks_exact_mut(bs); + for chunk in &mut chunks { + let mut block = counter.generate_block(&self.nonce); + counter.increment(); + self.cipher.encrypt_block(&mut block); + xor(chunk, &block); + } + + let rem = chunks.into_remainder(); + if !rem.is_empty() { + self.buffer = counter.generate_block(&self.nonce); + self.cipher.encrypt_block(&mut self.buffer); + xor(rem, &self.buffer[..rem.len()]); + } + self.buf_pos = rem.len() as u8; + self.counter = counter; + Ok(()) + } +} + +impl<B, F> StreamCipherSeek for Ctr<B, F> +where + B: BlockEncrypt, + F: CtrFlavor<B::BlockSize>, +{ + fn try_current_pos<T: SeekNum>(&self) -> Result<T, OverflowError> { + T::from_block_byte(self.counter.to_backend(), self.buf_pos, B::BlockSize::U8) + } + + fn try_seek<S: SeekNum>(&mut self, pos: S) -> Result<(), LoopError> { + let res: (F::Backend, u8) = pos.to_block_byte(B::BlockSize::U8)?; + self.counter = F::from_backend(res.0); + self.buf_pos = res.1; + if self.buf_pos != 0 { + let mut block = self.counter.generate_block(&self.nonce); + self.cipher.encrypt_block(&mut block); + self.buffer = block; + } + Ok(()) + } +} + +impl<B, F> fmt::Debug for Ctr<B, F> +where + B: BlockEncrypt + fmt::Debug, + F: CtrFlavor<B::BlockSize> + fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + write!(f, "Ctr-{:?}-{:?}", self.counter, self.cipher) + } +} + +#[inline(always)] +fn xor(buf: &mut [u8], key: &[u8]) { + debug_assert_eq!(buf.len(), key.len()); + for (a, b) in buf.iter_mut().zip(key) { + *a ^= *b; + } +} + +#[inline(always)] +fn to_slice<C: BlockEncrypt>(blocks: &ParBlocks<C>) -> &[u8] { + let blocks_len = C::BlockSize::to_usize() * C::ParBlocks::to_usize(); + unsafe { core::slice::from_raw_parts(blocks.as_ptr() as *const u8, blocks_len) } +} diff --git a/rust/vendor/ctr/tests/ctr128/data/aes128-ctr.blb b/rust/vendor/ctr/tests/ctr128/data/aes128-ctr.blb Binary files differnew file mode 100644 index 0000000..d721e4e --- /dev/null +++ b/rust/vendor/ctr/tests/ctr128/data/aes128-ctr.blb diff --git a/rust/vendor/ctr/tests/ctr128/data/aes256-ctr.blb b/rust/vendor/ctr/tests/ctr128/data/aes256-ctr.blb Binary files differnew file mode 100644 index 0000000..47daaf8 --- /dev/null +++ b/rust/vendor/ctr/tests/ctr128/data/aes256-ctr.blb diff --git a/rust/vendor/ctr/tests/ctr128/mod.rs b/rust/vendor/ctr/tests/ctr128/mod.rs new file mode 100644 index 0000000..af26765 --- /dev/null +++ b/rust/vendor/ctr/tests/ctr128/mod.rs @@ -0,0 +1,7 @@ +type Aes128Ctr = ctr::Ctr128BE<aes::Aes128>; +type Aes256Ctr = ctr::Ctr128BE<aes::Aes256>; + +cipher::stream_cipher_test!(aes128_ctr_core, Aes128Ctr, "aes128-ctr"); +cipher::stream_cipher_test!(aes256_ctr_core, Aes256Ctr, "aes256-ctr"); +cipher::stream_cipher_seek_test!(aes128_ctr_seek, Aes128Ctr); +cipher::stream_cipher_seek_test!(aes256_ctr_seek, Aes256Ctr); diff --git a/rust/vendor/ctr/tests/ctr32/big_endian.rs b/rust/vendor/ctr/tests/ctr32/big_endian.rs new file mode 100644 index 0000000..5206fa7 --- /dev/null +++ b/rust/vendor/ctr/tests/ctr32/big_endian.rs @@ -0,0 +1,80 @@ +//! Counter Mode with a 32-bit big endian counter + +use cipher::{NewCipher, StreamCipher}; +use hex_literal::hex; + +type Aes128Ctr = ctr::Ctr32BE<aes::Aes128>; + +const KEY: &[u8; 16] = &hex!("000102030405060708090A0B0C0D0E0F"); +const NONCE1: &[u8; 16] = &hex!("11111111111111111111111111111111"); +const NONCE2: &[u8; 16] = &hex!("222222222222222222222222FFFFFFFE"); + +#[test] +fn counter_incr() { + let mut ctr = Aes128Ctr::new(KEY.into(), NONCE1.into()); + assert_eq!(ctr.current_block(), 0); + + let mut buffer = [0u8; 64]; + ctr.apply_keystream(&mut buffer); + + assert_eq!(ctr.current_block(), 4); + assert_eq!( + &buffer[..], + &hex!( + "35D14E6D3E3A279CF01E343E34E7DED36EEADB04F42E2251AB4377F257856DBA + 0AB37657B9C2AA09762E518FC9395D5304E96C34CCD2F0A95CDE7321852D90C0" + )[..] + ); +} + +#[test] +fn counter_seek() { + let mut ctr = Aes128Ctr::new(KEY.into(), NONCE1.into()); + ctr.seek_block(1); + assert_eq!(ctr.current_block(), 1); + + let mut buffer = [0u8; 64]; + ctr.apply_keystream(&mut buffer); + + assert_eq!(ctr.current_block(), 5); + assert_eq!( + &buffer[..], + &hex!( + "6EEADB04F42E2251AB4377F257856DBA0AB37657B9C2AA09762E518FC9395D53 + 04E96C34CCD2F0A95CDE7321852D90C0F7441EAB3811A03FDBD162AEC402F5AA" + )[..] + ); +} + +#[test] +fn keystream_xor() { + let mut ctr = Aes128Ctr::new(KEY.into(), NONCE1.into()); + let mut buffer = [1u8; 64]; + + ctr.apply_keystream(&mut buffer); + assert_eq!( + &buffer[..], + &hex!( + "34D04F6C3F3B269DF11F353F35E6DFD26FEBDA05F52F2350AA4276F356846CBB + 0BB27756B8C3AB08772F508EC8385C5205E86D35CDD3F1A85DDF7220842C91C1" + )[..] + ); +} + +#[test] +fn counter_wrap() { + let mut ctr = Aes128Ctr::new(KEY.into(), NONCE2.into()); + assert_eq!(ctr.current_block(), 0); + + let mut buffer = [0u8; 64]; + ctr.apply_keystream(&mut buffer); + + assert_eq!(ctr.current_block(), 4); + assert_eq!( + &buffer[..], + &hex!( + "58FC849D1CF53C54C63E1B1D15CB3C8AAA335F72135585E9FF943F4DAC77CB63 + BD1AE8716BE69C3B4D886B222B9B4E1E67548EF896A96E2746D8CA6476D8B183" + )[..] + ); +} diff --git a/rust/vendor/ctr/tests/ctr32/little_endian.rs b/rust/vendor/ctr/tests/ctr32/little_endian.rs new file mode 100644 index 0000000..c6a7a2c --- /dev/null +++ b/rust/vendor/ctr/tests/ctr32/little_endian.rs @@ -0,0 +1,87 @@ +//! Counter Mode with a 32-bit little endian counter + +use cipher::{consts::U16, generic_array::GenericArray, NewCipher, StreamCipher}; +use hex_literal::hex; + +type Aes128Ctr = ctr::Ctr32LE<aes::Aes128>; + +const KEY: &[u8; 16] = &hex!("000102030405060708090A0B0C0D0E0F"); +const NONCE1: &[u8; 16] = &hex!("11111111111111111111111111111111"); +const NONCE2: &[u8; 16] = &hex!("FEFFFFFF222222222222222222222222"); + +/// Compute nonce as used by AES-GCM-SIV +fn nonce(bytes: &[u8; 16]) -> GenericArray<u8, U16> { + let mut n = *bytes; + n[15] |= 0x80; + n.into() +} + +#[test] +fn counter_incr() { + let mut ctr = Aes128Ctr::new(KEY.into(), &nonce(NONCE1)); + assert_eq!(ctr.current_block(), 0); + + let mut buffer = [0u8; 64]; + ctr.apply_keystream(&mut buffer); + + // assert_eq!(ctr.current_ctr(), 4); + assert_eq!( + &buffer[..], + &hex!( + "2A0680B210CAD45E886D7EF6DAB357C9F18B39AFF6930FDB2D9FCE34261FF699 + EB96774669D24B560C9AD028C5C39C4580775A82065256B4787DC91C6942B700" + )[..] + ); +} + +#[test] +fn counter_seek() { + let mut ctr = Aes128Ctr::new(KEY.into(), &nonce(NONCE1)); + ctr.seek_block(1); + assert_eq!(ctr.current_block(), 1); + + let mut buffer = [0u8; 64]; + ctr.apply_keystream(&mut buffer); + + assert_eq!(ctr.current_block(), 5); + assert_eq!( + &buffer[..], + &hex!( + "F18B39AFF6930FDB2D9FCE34261FF699EB96774669D24B560C9AD028C5C39C45 + 80775A82065256B4787DC91C6942B7001564DDA1B07DCED9201AB71BAF06905B" + )[..] + ); +} + +#[test] +fn keystream_xor() { + let mut ctr = Aes128Ctr::new(KEY.into(), &nonce(NONCE1)); + let mut buffer = [1u8; 64]; + + ctr.apply_keystream(&mut buffer); + assert_eq!( + &buffer[..], + &hex!( + "2B0781B311CBD55F896C7FF7DBB256C8F08A38AEF7920EDA2C9ECF35271EF798 + EA97764768D34A570D9BD129C4C29D4481765B83075357B5797CC81D6843B601" + )[..] + ); +} + +#[test] +fn counter_wrap() { + let mut ctr = Aes128Ctr::new(KEY.into(), &nonce(NONCE2)); + assert_eq!(ctr.current_block(), 0); + + let mut buffer = [0u8; 64]; + ctr.apply_keystream(&mut buffer); + + assert_eq!(ctr.current_block(), 4); + assert_eq!( + &buffer[..], + &hex!( + "A1E649D8B382293DC28375C42443BB6A226BAADC9E9CCA8214F56E07A4024E06 + 6355A0DA2E08FB00112FFA38C26189EE55DD5B0B130ED87096FE01B59A665A60" + )[..] + ); +} diff --git a/rust/vendor/ctr/tests/ctr32/mod.rs b/rust/vendor/ctr/tests/ctr32/mod.rs new file mode 100644 index 0000000..c957701 --- /dev/null +++ b/rust/vendor/ctr/tests/ctr32/mod.rs @@ -0,0 +1,9 @@ +//! Counter Mode with a 32-bit counter. +//! +//! NOTE: AES-128-CTR test vectors used by these tests were generated by first +//! integration testing the implementation in the contexts of AES-GCM and +//! AES-GCM-SIV, with the former tested against the NIST CAVS vectors, and the +//! latter against the RFC8452 test vectors. + +mod big_endian; +mod little_endian; diff --git a/rust/vendor/ctr/tests/gost/mod.rs b/rust/vendor/ctr/tests/gost/mod.rs new file mode 100644 index 0000000..ac35da3 --- /dev/null +++ b/rust/vendor/ctr/tests/gost/mod.rs @@ -0,0 +1,57 @@ +use cipher::{NewCipher, StreamCipher}; +use hex_literal::hex; + +type MagmaCtr = ctr::Ctr32BE<magma::Magma>; +type KuznyechikCtr = ctr::Ctr64BE<kuznyechik::Kuznyechik>; + +/// Test vectors from GOST R 34.13-2015 (Section A.1.2) +#[test] +#[rustfmt::skip] +fn kuznyechik() { + let key = hex!(" + 8899aabbccddeeff0011223344556677 + fedcba98765432100123456789abcdef + "); + let nonce = hex!("1234567890abcef00000000000000000"); + let mut pt = hex!(" + 1122334455667700ffeeddccbbaa9988 + 00112233445566778899aabbcceeff0a + 112233445566778899aabbcceeff0a00 + 2233445566778899aabbcceeff0a0011 + "); + let ct = hex!(" + f195d8bec10ed1dbd57b5fa240bda1b8 + 85eee733f6a13e5df33ce4b33c45dee4 + a5eae88be6356ed3d5e877f13564a3a5 + cb91fab1f20cbab6d1c6d15820bdba73 + "); + let mut cipher = KuznyechikCtr::new(&key.into(), &nonce.into()); + cipher.apply_keystream(&mut pt); + assert_eq!(pt[..], ct[..]); +} + +/// Test vectors from GOST R 34.13-2015 (Section A.2.2) +#[test] +#[rustfmt::skip] +fn magma() { + let key = hex!(" + ffeeddccbbaa99887766554433221100 + f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff + "); + let nonce = hex!("1234567800000000"); + let mut pt = hex!(" + 92def06b3c130a59 + db54c704f8189d20 + 4a98fb2e67a8024c + 8912409b17b57e41 + "); + let ct = hex!(" + 4e98110c97b7b93c + 3e250d93d6e85d69 + 136d868807b2dbef + 568eb680ab52a12d + "); + let mut cipher = MagmaCtr::new(&key.into(), &nonce.into()); + cipher.apply_keystream(&mut pt); + assert_eq!(pt[..], ct[..]); +} diff --git a/rust/vendor/ctr/tests/lib.rs b/rust/vendor/ctr/tests/lib.rs new file mode 100644 index 0000000..0f91835 --- /dev/null +++ b/rust/vendor/ctr/tests/lib.rs @@ -0,0 +1,5 @@ +//! Counter Mode Tests + +mod ctr128; +mod ctr32; +mod gost; |