ctr-0.9.2/.cargo_vcs_info.json 0000644 00000000141 00000000001 0011630 0 ustar {
"git": {
"sha1": "65320945adb1b6f7290e61b033f9e04ccdb2581b"
},
"path_in_vcs": "ctr"
} ctr-0.9.2/CHANGELOG.md 0000644 0000000 0000000 00000004433 10461020230 0012241 0 ustar 0000000 0000000 # 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.toml 0000644 00000002651 00000000001 0007636 0 ustar # 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.orig 0000644 00000001442 00000000001 0010572 0 ustar [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.orig 0000644 0000000 0000000 00000001442 10461020230 0013314 0 ustar 0000000 0000000 [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-APACHE 0000644 0000000 0000000 00000025141 10461020230 0012353 0 ustar 0000000 0000000 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-MIT 0000644 0000000 0000000 00000002117 10461020230 0012061 0 ustar 0000000 0000000 Copyright (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.md 0000644 0000000 0000000 00000004247 10461020230 0011712 0 ustar 0000000 0000000 # 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.rs 0000644 0000000 0000000 00000003730 10461020230 0013153 0 ustar 0000000 0000000 use 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.rs 0000644 0000000 0000000 00000007063 10461020230 0013367 0 ustar 0000000 0000000 use 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.rs 0000644 0000000 0000000 00000010273 10461020230 0014263 0 ustar 0000000 0000000 //! 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.rs 0000644 0000000 0000000 00000010232 10461020230 0014170 0 ustar 0000000 0000000 //! 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.rs 0000644 0000000 0000000 00000010232 10461020230 0014175 0 ustar 0000000 0000000 //! 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.rs 0000644 0000000 0000000 00000002335 10461020230 0013240 0 ustar 0000000 0000000 //! 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.rs 0000644 0000000 0000000 00000006315 10461020230 0012334 0 ustar 0000000 0000000 //! 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.blb 0000644 0000000 0000000 00000003767 10461020230 0016011 0 ustar 0000000 0000000 +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ϻvzATYɅIɁNjLzi'f҂ٱ$+XyU*Nk.] J씴 cm0 CBԵh&JAmLdzEx|an2m9 3ܺ2jZ|j4VH~,j{Px^[(>eV_
2-EP.X$ gEQG?i