ctr-0.9.2/.cargo_vcs_info.json0000644000000001410000000000100116300ustar { "git": { "sha1": "65320945adb1b6f7290e61b033f9e04ccdb2581b" }, "path_in_vcs": "ctr" }ctr-0.9.2/CHANGELOG.md000064400000000000000000000044331046102023000122410ustar 00000000000000# 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.9.2 (2022-09-30) ### Changed - Implement `Clone` directly for `CtrCore`, so it would work with non-`Clone` flavors ([#24]) [#24]: https://github.com/RustCrypto/block-modes/pull/24 ## 0.9.1 (2022-02-17) ### Fixed - Minimal versions build ([#9]) [#9]: https://github.com/RustCrypto/block-modes/pull/9 ## 0.9.0 (2022-02-10) ### Changed - Update `cipher` dependency to v0.4 and move crate to the [RustCrypto/block-modes] repository ([#2]) [#2]: https://github.com/RustCrypto/block-modes/pull/2 [RustCrypto/block-modes]: https://github.com/RustCrypto/block-modes ## 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` 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) ctr-0.9.2/Cargo.toml0000644000000026510000000000100076360ustar # 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 are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.56" name = "ctr" version = "0.9.2" authors = ["RustCrypto Developers"] description = "CTR block modes of operation" documentation = "https://docs.rs/ctr" readme = "README.md" keywords = [ "crypto", "block-mode", "stream-cipher", "ciphers", ] categories = [ "cryptography", "no-std", ] license = "MIT OR Apache-2.0" repository = "https://github.com/RustCrypto/block-modes" resolver = "1" [package.metadata.docs.rs] all-features = true rustdoc-args = [ "--cfg", "docsrs", ] [dependencies.cipher] version = "0.4.2" [dev-dependencies.aes] version = "0.8" [dev-dependencies.cipher] version = "0.4.2" features = ["dev"] [dev-dependencies.hex-literal] version = "0.3.3" [dev-dependencies.kuznyechik] version = "0.8" [dev-dependencies.magma] version = "0.8" [features] alloc = ["cipher/alloc"] block-padding = ["cipher/block-padding"] std = [ "cipher/std", "alloc", ] zeroize = ["cipher/zeroize"] ctr-0.9.2/Cargo.toml.orig0000644000000014420000000000100105720ustar [package] name = "ctr" version = "0.9.2" description = "CTR block modes of operation" authors = ["RustCrypto Developers"] license = "MIT OR Apache-2.0" edition = "2021" rust-version = "1.56" readme = "README.md" documentation = "https://docs.rs/ctr" repository = "https://github.com/RustCrypto/block-modes" keywords = ["crypto", "block-mode", "stream-cipher", "ciphers"] categories = ["cryptography", "no-std"] [dependencies] cipher = "0.4.2" [dev-dependencies] aes = "0.8" magma = "0.8" kuznyechik = "0.8" cipher = { version = "0.4.2", features = ["dev"] } hex-literal = "0.3.3" [features] alloc = ["cipher/alloc"] std = ["cipher/std", "alloc"] block-padding = ["cipher/block-padding"] zeroize = ["cipher/zeroize"] [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg", "docsrs"] ctr-0.9.2/Cargo.toml.orig000064400000000000000000000014421046102023000133140ustar 00000000000000[package] name = "ctr" version = "0.9.2" description = "CTR block modes of operation" authors = ["RustCrypto Developers"] license = "MIT OR Apache-2.0" edition = "2021" rust-version = "1.56" readme = "README.md" documentation = "https://docs.rs/ctr" repository = "https://github.com/RustCrypto/block-modes" keywords = ["crypto", "block-mode", "stream-cipher", "ciphers"] categories = ["cryptography", "no-std"] [dependencies] cipher = "0.4.2" [dev-dependencies] aes = "0.8" magma = "0.8" kuznyechik = "0.8" cipher = { version = "0.4.2", features = ["dev"] } hex-literal = "0.3.3" [features] alloc = ["cipher/alloc"] std = ["cipher/std", "alloc"] block-padding = ["cipher/block-padding"] zeroize = ["cipher/zeroize"] [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg", "docsrs"] ctr-0.9.2/LICENSE-APACHE000064400000000000000000000251411046102023000123530ustar 00000000000000 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. ctr-0.9.2/LICENSE-MIT000064400000000000000000000021171046102023000120610ustar 00000000000000Copyright (c) 2018-2022 RustCrypto Developers 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. ctr-0.9.2/README.md000064400000000000000000000042471046102023000117120ustar 00000000000000# RustCrypto: 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] Generic implementation of the [Counter][CTR] (CTR) block cipher mode of operation. See [documentation][cipher-doc] of the `cipher` crate for additional information. ## Minimum Supported Rust Version Rust **1.56** 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.56+-blue.svg [chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg [chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/308460-block-modes [build-image]: https://github.com/RustCrypto/block-modes/workflows/ctr/badge.svg?branch=master&event=push [build-link]: https://github.com/RustCrypto/block-modes/actions?query=workflow%3Actr+branch%3Amaster [//]: # (general links) [CTR]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_(CTR) [cipher-doc]: https://docs.rs/cipher/ ctr-0.9.2/src/backend.rs000064400000000000000000000037301046102023000131530ustar 00000000000000use crate::CtrFlavor; use cipher::{ generic_array::ArrayLength, Block, BlockBackend, BlockClosure, BlockSizeUser, ParBlocks, ParBlocksSizeUser, StreamBackend, StreamClosure, }; struct Backend<'a, F, B> where F: CtrFlavor, B: BlockBackend, { ctr_nonce: &'a mut F::CtrNonce, backend: &'a mut B, } impl<'a, F, B> BlockSizeUser for Backend<'a, F, B> where F: CtrFlavor, B: BlockBackend, { type BlockSize = B::BlockSize; } impl<'a, F, B> ParBlocksSizeUser for Backend<'a, F, B> where F: CtrFlavor, B: BlockBackend, { type ParBlocksSize = B::ParBlocksSize; } impl<'a, F, B> StreamBackend for Backend<'a, F, B> where F: CtrFlavor, B: BlockBackend, { #[inline(always)] fn gen_ks_block(&mut self, block: &mut Block) { let tmp = F::next_block(self.ctr_nonce); self.backend.proc_block((&tmp, block).into()); } #[inline(always)] fn gen_par_ks_blocks(&mut self, blocks: &mut ParBlocks) { let mut tmp = ParBlocks::::default(); for block in tmp.iter_mut() { *block = F::next_block(self.ctr_nonce); } self.backend.proc_par_blocks((&tmp, blocks).into()); } } pub(crate) struct Closure<'a, F, BS, SC> where F: CtrFlavor, BS: ArrayLength, SC: StreamClosure, { pub(crate) ctr_nonce: &'a mut F::CtrNonce, pub(crate) f: SC, } impl<'a, F, BS, SC> BlockSizeUser for Closure<'a, F, BS, SC> where F: CtrFlavor, BS: ArrayLength, SC: StreamClosure, { type BlockSize = BS; } impl<'a, F, BS, SC> BlockClosure for Closure<'a, F, BS, SC> where F: CtrFlavor, BS: ArrayLength, SC: StreamClosure, { #[inline(always)] fn call>(self, backend: &mut B) { let Self { ctr_nonce, f } = self; f.call(&mut Backend:: { ctr_nonce, backend }) } } ctr-0.9.2/src/ctr_core.rs000064400000000000000000000070631046102023000133670ustar 00000000000000use crate::{backend::Closure, CtrFlavor}; use cipher::{ crypto_common::{InnerUser, IvSizeUser}, AlgorithmName, BlockCipher, BlockEncryptMut, BlockSizeUser, InnerIvInit, Iv, IvState, StreamCipherCore, StreamCipherSeekCore, StreamClosure, }; use core::fmt; #[cfg(feature = "zeroize")] use cipher::zeroize::ZeroizeOnDrop; /// Generic CTR block mode instance. pub struct CtrCore where C: BlockEncryptMut + BlockCipher, F: CtrFlavor, { cipher: C, ctr_nonce: F::CtrNonce, } impl BlockSizeUser for CtrCore where C: BlockEncryptMut + BlockCipher, F: CtrFlavor, { type BlockSize = C::BlockSize; } impl StreamCipherCore for CtrCore where C: BlockEncryptMut + BlockCipher, F: CtrFlavor, { #[inline] fn remaining_blocks(&self) -> Option { F::remaining(&self.ctr_nonce) } #[inline] fn process_with_backend(&mut self, f: impl StreamClosure) { let Self { cipher, ctr_nonce } = self; cipher.encrypt_with_backend_mut(Closure:: { ctr_nonce, f }); } } impl StreamCipherSeekCore for CtrCore where C: BlockEncryptMut + BlockCipher, F: CtrFlavor, { type Counter = F::Backend; #[inline] fn get_block_pos(&self) -> Self::Counter { F::as_backend(&self.ctr_nonce) } #[inline] fn set_block_pos(&mut self, pos: Self::Counter) { F::set_from_backend(&mut self.ctr_nonce, pos); } } impl InnerUser for CtrCore where C: BlockEncryptMut + BlockCipher, F: CtrFlavor, { type Inner = C; } impl IvSizeUser for CtrCore where C: BlockEncryptMut + BlockCipher, F: CtrFlavor, { type IvSize = C::BlockSize; } impl InnerIvInit for CtrCore where C: BlockEncryptMut + BlockCipher, F: CtrFlavor, { #[inline] fn inner_iv_init(cipher: C, iv: &Iv) -> Self { Self { cipher, ctr_nonce: F::from_nonce(iv), } } } impl IvState for CtrCore where C: BlockEncryptMut + BlockCipher, F: CtrFlavor, { #[inline] fn iv_state(&self) -> Iv { F::current_block(&self.ctr_nonce) } } impl AlgorithmName for CtrCore where C: BlockEncryptMut + BlockCipher + AlgorithmName, F: CtrFlavor, { fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("Ctr")?; f.write_str(F::NAME)?; f.write_str("<")?; ::write_alg_name(f)?; f.write_str(">") } } impl Clone for CtrCore where C: BlockEncryptMut + BlockCipher + Clone, F: CtrFlavor, { #[inline] fn clone(&self) -> Self { Self { cipher: self.cipher.clone(), ctr_nonce: self.ctr_nonce.clone(), } } } impl fmt::Debug for CtrCore where C: BlockEncryptMut + BlockCipher + AlgorithmName, F: CtrFlavor, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("Ctr")?; f.write_str(F::NAME)?; f.write_str("<")?; ::write_alg_name(f)?; f.write_str("> { ... }") } } #[cfg(feature = "zeroize")] #[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))] impl ZeroizeOnDrop for CtrCore where C: BlockEncryptMut + BlockCipher + ZeroizeOnDrop, F: CtrFlavor, F::CtrNonce: ZeroizeOnDrop, { } ctr-0.9.2/src/flavors/ctr128.rs000064400000000000000000000102731046102023000142630ustar 00000000000000//! 128-bit counter falvors. use super::CtrFlavor; use cipher::{ generic_array::{ArrayLength, GenericArray}, typenum::{PartialDiv, PartialQuot, Unsigned, U16}, }; #[cfg(feature = "zeroize")] use cipher::zeroize::{Zeroize, ZeroizeOnDrop}; type ChunkSize = U16; type Chunks = PartialQuot; const CS: usize = ChunkSize::USIZE; #[derive(Clone)] pub struct CtrNonce128> { ctr: u128, nonce: GenericArray, } #[cfg(feature = "zeroize")] impl> Drop for CtrNonce128 { fn drop(&mut self) { self.ctr.zeroize(); self.nonce.zeroize(); } } #[cfg(feature = "zeroize")] impl> ZeroizeOnDrop for CtrNonce128 {} /// 128-bit big endian counter flavor. pub enum Ctr128BE {} impl CtrFlavor for Ctr128BE where B: ArrayLength + PartialDiv, Chunks: ArrayLength, { type CtrNonce = CtrNonce128>; type Backend = u128; const NAME: &'static str = "128BE"; #[inline] fn remaining(cn: &Self::CtrNonce) -> Option { (core::u128::MAX - cn.ctr).try_into().ok() } #[inline(always)] fn current_block(cn: &Self::CtrNonce) -> GenericArray { let mut block = GenericArray::::default(); for i in 0..Chunks::::USIZE { let t = if i == Chunks::::USIZE - 1 { cn.ctr.wrapping_add(cn.nonce[i]).to_be_bytes() } else { cn.nonce[i].to_ne_bytes() }; block[CS * i..][..CS].copy_from_slice(&t); } block } #[inline] fn next_block(cn: &mut Self::CtrNonce) -> GenericArray { let block = Self::current_block(cn); cn.ctr = cn.ctr.wrapping_add(1); block } #[inline] fn from_nonce(block: &GenericArray) -> Self::CtrNonce { let mut nonce = GenericArray::>::default(); for i in 0..Chunks::::USIZE { let chunk = block[CS * i..][..CS].try_into().unwrap(); nonce[i] = if i == Chunks::::USIZE - 1 { u128::from_be_bytes(chunk) } else { u128::from_ne_bytes(chunk) } } let ctr = 0; Self::CtrNonce { ctr, nonce } } #[inline] fn as_backend(cn: &Self::CtrNonce) -> Self::Backend { cn.ctr } #[inline] fn set_from_backend(cn: &mut Self::CtrNonce, v: Self::Backend) { cn.ctr = v; } } /// 128-bit big endian counter flavor. pub enum Ctr128LE {} impl CtrFlavor for Ctr128LE where B: ArrayLength + PartialDiv, Chunks: ArrayLength, { type CtrNonce = CtrNonce128>; type Backend = u128; const NAME: &'static str = "128LE"; #[inline] fn remaining(cn: &Self::CtrNonce) -> Option { (core::u128::MAX - cn.ctr).try_into().ok() } #[inline(always)] fn current_block(cn: &Self::CtrNonce) -> GenericArray { let mut block = GenericArray::::default(); for i in 0..Chunks::::USIZE { let t = if i == 0 { cn.ctr.wrapping_add(cn.nonce[i]).to_le_bytes() } else { cn.nonce[i].to_ne_bytes() }; block[CS * i..][..CS].copy_from_slice(&t); } block } #[inline] fn next_block(cn: &mut Self::CtrNonce) -> GenericArray { let block = Self::current_block(cn); cn.ctr = cn.ctr.wrapping_add(1); block } #[inline] fn from_nonce(block: &GenericArray) -> Self::CtrNonce { let mut nonce = GenericArray::>::default(); for i in 0..Chunks::::USIZE { let chunk = block[CS * i..][..CS].try_into().unwrap(); nonce[i] = if i == 0 { u128::from_le_bytes(chunk) } else { u128::from_ne_bytes(chunk) } } let ctr = 0; Self::CtrNonce { ctr, nonce } } #[inline] fn as_backend(cn: &Self::CtrNonce) -> Self::Backend { cn.ctr } #[inline] fn set_from_backend(cn: &mut Self::CtrNonce, v: Self::Backend) { cn.ctr = v; } } ctr-0.9.2/src/flavors/ctr32.rs000064400000000000000000000102321046102023000141700ustar 00000000000000//! 32-bit counter falvors. use super::CtrFlavor; use cipher::{ generic_array::{ArrayLength, GenericArray}, typenum::{PartialDiv, PartialQuot, Unsigned, U4}, }; #[cfg(feature = "zeroize")] use cipher::zeroize::{Zeroize, ZeroizeOnDrop}; type ChunkSize = U4; type Chunks = PartialQuot; const CS: usize = ChunkSize::USIZE; #[derive(Clone)] pub struct CtrNonce32> { ctr: u32, nonce: GenericArray, } #[cfg(feature = "zeroize")] impl> Drop for CtrNonce32 { fn drop(&mut self) { self.ctr.zeroize(); self.nonce.zeroize(); } } #[cfg(feature = "zeroize")] impl> ZeroizeOnDrop for CtrNonce32 {} /// 32-bit big endian counter flavor. pub enum Ctr32BE {} impl CtrFlavor for Ctr32BE where B: ArrayLength + PartialDiv, Chunks: ArrayLength, { type CtrNonce = CtrNonce32>; type Backend = u32; const NAME: &'static str = "32BE"; #[inline] fn remaining(cn: &Self::CtrNonce) -> Option { (core::u32::MAX - cn.ctr).try_into().ok() } #[inline(always)] fn current_block(cn: &Self::CtrNonce) -> GenericArray { let mut block = GenericArray::::default(); for i in 0..Chunks::::USIZE { let t = if i == Chunks::::USIZE - 1 { cn.ctr.wrapping_add(cn.nonce[i]).to_be_bytes() } else { cn.nonce[i].to_ne_bytes() }; block[CS * i..][..CS].copy_from_slice(&t); } block } #[inline] fn next_block(cn: &mut Self::CtrNonce) -> GenericArray { let block = Self::current_block(cn); cn.ctr = cn.ctr.wrapping_add(1); block } #[inline] fn from_nonce(block: &GenericArray) -> Self::CtrNonce { let mut nonce = GenericArray::>::default(); for i in 0..Chunks::::USIZE { let chunk = block[CS * i..][..CS].try_into().unwrap(); nonce[i] = if i == Chunks::::USIZE - 1 { u32::from_be_bytes(chunk) } else { u32::from_ne_bytes(chunk) } } let ctr = 0; Self::CtrNonce { ctr, nonce } } #[inline] fn as_backend(cn: &Self::CtrNonce) -> Self::Backend { cn.ctr } #[inline] fn set_from_backend(cn: &mut Self::CtrNonce, v: Self::Backend) { cn.ctr = v; } } /// 32-bit big endian counter flavor. pub enum Ctr32LE {} impl CtrFlavor for Ctr32LE where B: ArrayLength + PartialDiv, Chunks: ArrayLength, { type CtrNonce = CtrNonce32>; type Backend = u32; const NAME: &'static str = "32LE"; #[inline] fn remaining(cn: &Self::CtrNonce) -> Option { (core::u32::MAX - cn.ctr).try_into().ok() } #[inline(always)] fn current_block(cn: &Self::CtrNonce) -> GenericArray { let mut block = GenericArray::::default(); for i in 0..Chunks::::USIZE { let t = if i == 0 { cn.ctr.wrapping_add(cn.nonce[i]).to_le_bytes() } else { cn.nonce[i].to_ne_bytes() }; block[CS * i..][..CS].copy_from_slice(&t); } block } #[inline] fn next_block(cn: &mut Self::CtrNonce) -> GenericArray { let block = Self::current_block(cn); cn.ctr = cn.ctr.wrapping_add(1); block } #[inline] fn from_nonce(block: &GenericArray) -> Self::CtrNonce { let mut nonce = GenericArray::>::default(); for i in 0..Chunks::::USIZE { let chunk = block[CS * i..][..CS].try_into().unwrap(); nonce[i] = if i == 0 { u32::from_le_bytes(chunk) } else { u32::from_ne_bytes(chunk) } } let ctr = 0; Self::CtrNonce { ctr, nonce } } #[inline] fn as_backend(cn: &Self::CtrNonce) -> Self::Backend { cn.ctr } #[inline] fn set_from_backend(cn: &mut Self::CtrNonce, v: Self::Backend) { cn.ctr = v; } } ctr-0.9.2/src/flavors/ctr64.rs000064400000000000000000000102321046102023000141750ustar 00000000000000//! 64-bit counter falvors. use super::CtrFlavor; use cipher::{ generic_array::{ArrayLength, GenericArray}, typenum::{PartialDiv, PartialQuot, Unsigned, U8}, }; #[cfg(feature = "zeroize")] use cipher::zeroize::{Zeroize, ZeroizeOnDrop}; type ChunkSize = U8; type Chunks = PartialQuot; const CS: usize = ChunkSize::USIZE; #[derive(Clone)] pub struct CtrNonce64> { ctr: u64, nonce: GenericArray, } #[cfg(feature = "zeroize")] impl> Drop for CtrNonce64 { fn drop(&mut self) { self.ctr.zeroize(); self.nonce.zeroize(); } } #[cfg(feature = "zeroize")] impl> ZeroizeOnDrop for CtrNonce64 {} /// 64-bit big endian counter flavor. pub enum Ctr64BE {} impl CtrFlavor for Ctr64BE where B: ArrayLength + PartialDiv, Chunks: ArrayLength, { type CtrNonce = CtrNonce64>; type Backend = u64; const NAME: &'static str = "64BE"; #[inline] fn remaining(cn: &Self::CtrNonce) -> Option { (core::u64::MAX - cn.ctr).try_into().ok() } #[inline(always)] fn current_block(cn: &Self::CtrNonce) -> GenericArray { let mut block = GenericArray::::default(); for i in 0..Chunks::::USIZE { let t = if i == Chunks::::USIZE - 1 { cn.ctr.wrapping_add(cn.nonce[i]).to_be_bytes() } else { cn.nonce[i].to_ne_bytes() }; block[CS * i..][..CS].copy_from_slice(&t); } block } #[inline] fn next_block(cn: &mut Self::CtrNonce) -> GenericArray { let block = Self::current_block(cn); cn.ctr = cn.ctr.wrapping_add(1); block } #[inline] fn from_nonce(block: &GenericArray) -> Self::CtrNonce { let mut nonce = GenericArray::>::default(); for i in 0..Chunks::::USIZE { let chunk = block[CS * i..][..CS].try_into().unwrap(); nonce[i] = if i == Chunks::::USIZE - 1 { u64::from_be_bytes(chunk) } else { u64::from_ne_bytes(chunk) } } let ctr = 0; Self::CtrNonce { ctr, nonce } } #[inline] fn as_backend(cn: &Self::CtrNonce) -> Self::Backend { cn.ctr } #[inline] fn set_from_backend(cn: &mut Self::CtrNonce, v: Self::Backend) { cn.ctr = v; } } /// 64-bit big endian counter flavor. pub enum Ctr64LE {} impl CtrFlavor for Ctr64LE where B: ArrayLength + PartialDiv, Chunks: ArrayLength, { type CtrNonce = CtrNonce64>; type Backend = u64; const NAME: &'static str = "64LE"; #[inline] fn remaining(cn: &Self::CtrNonce) -> Option { (core::u64::MAX - cn.ctr).try_into().ok() } #[inline(always)] fn current_block(cn: &Self::CtrNonce) -> GenericArray { let mut block = GenericArray::::default(); for i in 0..Chunks::::USIZE { let t = if i == 0 { cn.ctr.wrapping_add(cn.nonce[i]).to_le_bytes() } else { cn.nonce[i].to_ne_bytes() }; block[CS * i..][..CS].copy_from_slice(&t); } block } #[inline] fn next_block(cn: &mut Self::CtrNonce) -> GenericArray { let block = Self::current_block(cn); cn.ctr = cn.ctr.wrapping_add(1); block } #[inline] fn from_nonce(block: &GenericArray) -> Self::CtrNonce { let mut nonce = GenericArray::>::default(); for i in 0..Chunks::::USIZE { let chunk = block[CS * i..][..CS].try_into().unwrap(); nonce[i] = if i == 0 { u64::from_le_bytes(chunk) } else { u64::from_ne_bytes(chunk) } } let ctr = 0; Self::CtrNonce { ctr, nonce } } #[inline] fn as_backend(cn: &Self::CtrNonce) -> Self::Backend { cn.ctr } #[inline] fn set_from_backend(cn: &mut Self::CtrNonce, v: Self::Backend) { cn.ctr = v; } } ctr-0.9.2/src/flavors.rs000064400000000000000000000023351046102023000132400ustar 00000000000000//! CTR mode flavors use cipher::{ generic_array::{ArrayLength, GenericArray}, Counter, }; mod ctr128; mod ctr32; mod ctr64; pub use ctr128::{Ctr128BE, Ctr128LE}; pub use ctr32::{Ctr32BE, Ctr32LE}; pub use ctr64::{Ctr64BE, Ctr64LE}; /// Trait implemented by different CTR flavors. pub trait CtrFlavor> { /// Inner representation of nonce. type CtrNonce: Clone; /// Backend numeric type type Backend: Counter; /// Flavor name const NAME: &'static str; /// Return number of remaining blocks. /// /// If result does not fit into `usize`, returns `None`. fn remaining(cn: &Self::CtrNonce) -> Option; /// Generate block for given `nonce` and current counter value. fn next_block(cn: &mut Self::CtrNonce) -> GenericArray; /// Generate block for given `nonce` and current counter value. fn current_block(cn: &Self::CtrNonce) -> GenericArray; /// Initialize from bytes. fn from_nonce(block: &GenericArray) -> Self::CtrNonce; /// Convert from a backend value fn set_from_backend(cn: &mut Self::CtrNonce, v: Self::Backend); /// Convert to a backend value fn as_backend(cn: &Self::CtrNonce) -> Self::Backend; } ctr-0.9.2/src/lib.rs000064400000000000000000000063151046102023000123340ustar 00000000000000//! Generic implementations of [CTR mode][1] for block ciphers. //! //! //! //! //! Mode functionality is accessed using traits from re-exported [`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! //! //! # Example //! ``` //! use aes::cipher::{KeyIvInit, StreamCipher, StreamCipherSeek}; //! use hex_literal::hex; //! //! type Aes128Ctr64LE = ctr::Ctr64LE; //! //! let key = [0x42; 16]; //! let iv = [0x24; 16]; //! let plaintext = *b"hello world! this is my plaintext."; //! let ciphertext = hex!( //! "3357121ebb5a29468bd861467596ce3da59bdee42dcc0614dea955368d8a5dc0cad4" //! ); //! //! // encrypt in-place //! let mut buf = plaintext.to_vec(); //! let mut cipher = Aes128Ctr64LE::new(&key.into(), &iv.into()); //! cipher.apply_keystream(&mut buf); //! assert_eq!(buf[..], ciphertext[..]); //! //! // CTR mode can be used with streaming messages //! let mut cipher = Aes128Ctr64LE::new(&key.into(), &iv.into()); //! for chunk in buf.chunks_mut(3) { //! cipher.apply_keystream(chunk); //! } //! assert_eq!(buf[..], plaintext[..]); //! //! // CTR mode supports seeking. The parameter is zero-based _bytes_ counter (not _blocks_). //! cipher.seek(0u32); //! //! // encrypt/decrypt from buffer to buffer //! // buffer length must be equal to input length //! let mut buf1 = [0u8; 34]; //! cipher //! .apply_keystream_b2b(&plaintext, &mut buf1) //! .unwrap(); //! assert_eq!(buf1[..], ciphertext[..]); //! //! let mut buf2 = [0u8; 34]; //! cipher.seek(0u32); //! cipher.apply_keystream_b2b(&buf1, &mut buf2).unwrap(); //! assert_eq!(buf2[..], plaintext[..]); //! ``` //! //! [1]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#CTR #![no_std] #![doc( html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg", html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg" )] #![forbid(unsafe_code)] #![cfg_attr(docsrs, feature(doc_cfg))] #![warn(missing_docs, rust_2018_idioms)] pub mod flavors; mod backend; mod ctr_core; pub use cipher; pub use flavors::CtrFlavor; use cipher::StreamCipherCoreWrapper; pub use ctr_core::CtrCore; /// CTR mode with 128-bit big endian counter. pub type Ctr128BE = StreamCipherCoreWrapper>; /// CTR mode with 128-bit little endian counter. pub type Ctr128LE = StreamCipherCoreWrapper>; /// CTR mode with 64-bit big endian counter. pub type Ctr64BE = StreamCipherCoreWrapper>; /// CTR mode with 64-bit little endian counter. pub type Ctr64LE = StreamCipherCoreWrapper>; /// CTR mode with 32-bit big endian counter. pub type Ctr32BE = StreamCipherCoreWrapper>; /// CTR mode with 32-bit little endian counter. pub type Ctr32LE = StreamCipherCoreWrapper>; ctr-0.9.2/tests/ctr128/data/aes128-ctr.blb000064400000000000000000000037671046102023000160110ustar 00000000000000 +0`[b{#lDm} I01'`,PLpt=I-2b2SEs1lS7*^Ճȧ7e3 ::X=Z*:b}K-V/KQZS WF2{Vr@= z:L(~۾0ܲjxi/=UE0ޢ}ex­ 9 ]:$xڀzϥ\h24]!_iϻvzAT YɅIɁNjLzi'f҂ٱ$+XyU*Nk.] J씴 cm0 CBԵh &JAmLdzEx|a n2m93ܺ2jZ|j4VH~ ,j{Px^[(> eV_ 2-EP.X$gEQG?iђ(/vSKq1DGhK..Ħu: $+>Ø`'QDЭ:m`\YĴ\h)sl|zp w@~R-$9reAM~}QGn岀s.$>lm72sW<`䧝үH40JͲnDjxu-"UK_=- Dd,3r% |D4۟ s!*es}-&~R; EDЄG=L:She̶gU NѤdUqe,ZV&_.^W?uM:)_λcilu?a%_xy>1=Bfӱ&tf%_-#`@]9&Qdxa$juž0$6Ui SwDD]7wNPK   Oaiwa,zms苼ɀ:˱بR8ɗ)^j$o1NJ8W?!ם^n ۑ&! /k(vd:#5!^cP۶M2g e榗CLf| RH~=nFxΡN#+d ټ?>Xh_ݶOu"B6Xgp0u2onٻSEtXhFW`zK 9א7 վ-?fI#⡵RzRFZ_>  gSk ŃLY2p0Sǹd:{k@sWF4=27y D-evpYSpxRH~;tڝn{ja#PyQB#34064ѫ[quhӒHO4-˙[3쁶ZXk3b#,:h'b,Zdc]ށEjjk-ZLG3 \ mno+D9mPь?Ϭw'/z&լFR10hUA"42Ht77,"Kk4i$!+Yxp૙LNG/*WYBIrPqW@u_\,9[aܮtꀪK&^ @M9T;.G,9CSmI';|-9(ρYpմ %ѥ@?B;t*+lWœ#BlVs$MEpd3rjAbG\N0)?(YÅ.L!y{vNo:Xr< `r#F`á9:/[MbZEɭ8Ȱ}LƤpYz%ǰs~$RD|7?R8ɗ]`t'\#cy-j#-3w Z9⥵0UuD;sw.m`ǬE̐ ېny&gH1a'vOI: KPr( bٹ;q>5??İ?vEM(0dTko. qĽJ,)LSD& >gHY&u)!~5$_\noL|_Bu0vhS=o#> +[?Z#-BۦcmeU"/v$3ZƥYlDё;(_+7SѕLbLy3[d+^'fCA *]Bީ,Ξ#c!-_ XNɱͱhc?[oj]2#CA@/2myHTm)ѡ]GSJt7ャ"a??7GԺP6eF&t01.k9m3>UT1?+f,ʺq%K#U;F\ GɑGvŀtZ]Wھ;G`:8%3 O*)Z[fi:i}cR%NaGtFH i*dk4TVY\UqYnadFS޻N'z?q[R8_͈;*I gútT+;H+#b]6'I@`Ŏݓ$Lr)$O pOYohАe%"k5.經;'qlNUzz-Ǽ!WO ]b'/FB8#73:|ح6B%gfX8۲t] iҌ`V .Cq[Zh%i`9z<]T95ȰxEaq 䓌uƵN8#kF"2”۬ؽl@I80(KNɁ)[/^ރ[ݹyv*F9hQ2EDETB J ՘זw'{X%Li -hUM7ediX9# zS6C&Cڍcc=wCݨtm @`%81,te6N{=KKv-m Gv1yB/5יduL+k8W aM]r/+ѥmfh)/fͦMθELv=Hctr-0.9.2/tests/ctr128/mod.rs000064400000000000000000000007231046102023000137400ustar 00000000000000use aes::{Aes128, Aes256}; use ctr::{flavors, Ctr128BE, CtrCore}; cipher::stream_cipher_test!(aes128_ctr_core, "aes128-ctr", Ctr128BE); cipher::stream_cipher_test!(aes256_ctr_core, "aes256-ctr", Ctr128BE); cipher::stream_cipher_seek_test!(aes128_ctr_seek, Ctr128BE); cipher::stream_cipher_seek_test!(aes256_ctr_seek, Ctr128BE); cipher::iv_state_test!( aes128_ctr_iv_state, CtrCore, apply_ks, ); ctr-0.9.2/tests/ctr32/be.rs000064400000000000000000000045601046102023000134640ustar 00000000000000//! Counter Mode with a 32-bit big endian counter use cipher::{KeyIvInit, StreamCipher, StreamCipherSeek, StreamCipherSeekCore}; use hex_literal::hex; type Aes128Ctr = ctr::Ctr32BE; 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.get_core().get_block_pos(), 0); let mut buffer = [0u8; 64]; ctr.apply_keystream(&mut buffer); assert_eq!(ctr.get_core().get_block_pos(), 4); assert_eq!( &buffer[..], &hex!( "35D14E6D3E3A279CF01E343E34E7DED36EEADB04F42E2251AB4377F257856DBA" "0AB37657B9C2AA09762E518FC9395D5304E96C34CCD2F0A95CDE7321852D90C0" )[..] ); } #[test] fn counter_seek() { let mut ctr = Aes128Ctr::new(KEY.into(), NONCE1.into()); ctr.seek(16); assert_eq!(ctr.get_core().get_block_pos(), 1); let mut buffer = [0u8; 64]; ctr.apply_keystream(&mut buffer); assert_eq!(ctr.get_core().get_block_pos(), 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.get_core().get_block_pos(), 0); let mut buffer = [0u8; 64]; ctr.apply_keystream(&mut buffer); assert_eq!(ctr.get_core().get_block_pos(), 4); assert_eq!( &buffer[..], &hex!( "58FC849D1CF53C54C63E1B1D15CB3C8AAA335F72135585E9FF943F4DAC77CB63" "BD1AE8716BE69C3B4D886B222B9B4E1E67548EF896A96E2746D8CA6476D8B183" )[..] ); } cipher::iv_state_test!( iv_state, ctr::CtrCore, apply_ks, ); ctr-0.9.2/tests/ctr32/le.rs000064400000000000000000000050741046102023000134770ustar 00000000000000//! Counter Mode with a 32-bit little endian counter use cipher::{ consts::U16, generic_array::GenericArray, KeyIvInit, StreamCipher, StreamCipherSeek, StreamCipherSeekCore, }; use hex_literal::hex; type Aes128Ctr = ctr::Ctr32LE; 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 { 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.get_core().get_block_pos(), 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(16); assert_eq!(ctr.get_core().get_block_pos(), 1); let mut buffer = [0u8; 64]; ctr.apply_keystream(&mut buffer); assert_eq!(ctr.get_core().get_block_pos(), 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.get_core().get_block_pos(), 0); let mut buffer = [0u8; 64]; ctr.apply_keystream(&mut buffer); assert_eq!(ctr.get_core().get_block_pos(), 4); assert_eq!( &buffer[..], &hex!( "A1E649D8B382293DC28375C42443BB6A226BAADC9E9CCA8214F56E07A4024E06" "6355A0DA2E08FB00112FFA38C26189EE55DD5B0B130ED87096FE01B59A665A60" )[..] ); } cipher::iv_state_test!( iv_state, ctr::CtrCore, apply_ks, ); ctr-0.9.2/tests/ctr32/mod.rs000064400000000000000000000005221046102023000136470ustar 00000000000000//! 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 be; mod le; ctr-0.9.2/tests/gost/mod.rs000064400000000000000000000030771046102023000136760ustar 00000000000000use cipher::{KeyIvInit, StreamCipher}; use hex_literal::hex; type MagmaCtr = ctr::Ctr32BE; type KuznyechikCtr = ctr::Ctr64BE; /// Test vectors from GOST R 34.13-2015 (Section A.1.2) #[test] 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] 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[..]); } ctr-0.9.2/tests/mod.rs000064400000000000000000000000711046102023000127110ustar 00000000000000//! Counter Mode Tests mod ctr128; mod ctr32; mod gost;