cfb-mode-0.8.2/.cargo_vcs_info.json 0000644 00000000146 00000000001 0012520 0 ustar {
"git": {
"sha1": "7ba177e7b3e3098818b926759cc779fa77e0c1c8"
},
"path_in_vcs": "cfb-mode"
} cfb-mode-0.8.2/CHANGELOG.md 0000644 0000000 0000000 00000003653 10461020230 0013127 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.8.2 (2022-09-13)
### Added
- `BufferEncryptor` and `BufferDecryptor` types ([#19])
[#19]: https://github.com/RustCrypto/block-modes/pull/19
## 0.8.1 (2022-02-17)
### Fixed
- Minimal versions build ([#9])
[#9]: https://github.com/RustCrypto/block-modes/pull/9
## 0.8.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.7.1 (2021-04-30)
### Changed
- Removed redundant `NewBlockCipher` bound from `FromBlockCipher` implementation ([#236])
[#236]: https://github.com/RustCrypto/stream-ciphers/pull/236
## 0.7.0 (2021-04-29)
### Changed
- Bump `cipher` dependency to v0.3 release ([#226])
- Bump `aes` dev dependency to v0.7 release ([#232])
[#226]: https://github.com/RustCrypto/stream-ciphers/pull/226
[#232]: https://github.com/RustCrypto/stream-ciphers/pull/232
## 0.6.0 (2020-10-16)
### Changed
- Replace `block-cipher`/`stream-cipher` with `cipher` crate ([#177])
[#177]: https://github.com/RustCrypto/stream-ciphers/pull/177
## 0.5.0 (2020-08-25)
### 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-08)
### Changed
- Bump `stream-cipher` dependency to v0.4 ([#119])
- Upgrade to Rust 2018 edition ([#119])
[#119]: https://github.com/RustCrypto/stream-ciphers/pull/119
## 0.3.2 (2019-03-11)
## 0.3.1 (2018-11-01)
## 0.3.0 (2018-11-01)
## 0.2.0 (2018-10-13)
## 0.1.0 (2018-10-01)
cfb-mode-0.8.2/Cargo.toml 0000644 00000002560 00000000001 0010520 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 = "cfb-mode"
version = "0.8.2"
authors = ["RustCrypto Developers"]
description = "Cipher Feedback (CFB) block cipher mode of operation"
documentation = "https://docs.rs/cfb-mode"
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"
[features]
alloc = ["cipher/alloc"]
block-padding = ["cipher/block-padding"]
std = [
"cipher/std",
"alloc",
]
zeroize = ["cipher/zeroize"]
cfb-mode-0.8.2/Cargo.toml.orig 0000644 00000001441 00000000001 0011454 0 ustar [package]
name = "cfb-mode"
version = "0.8.2"
description = "Cipher Feedback (CFB) block cipher mode of operation"
authors = ["RustCrypto Developers"]
license = "MIT OR Apache-2.0"
edition = "2021"
rust-version = "1.56"
readme = "README.md"
documentation = "https://docs.rs/cfb-mode"
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"
cipher = { version = "0.4.2", features = ["dev"] }
hex-literal = "0.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"]
cfb-mode-0.8.2/Cargo.toml.orig 0000644 0000000 0000000 00000001441 10461020230 0014176 0 ustar 0000000 0000000 [package]
name = "cfb-mode"
version = "0.8.2"
description = "Cipher Feedback (CFB) block cipher mode of operation"
authors = ["RustCrypto Developers"]
license = "MIT OR Apache-2.0"
edition = "2021"
rust-version = "1.56"
readme = "README.md"
documentation = "https://docs.rs/cfb-mode"
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"
cipher = { version = "0.4.2", features = ["dev"] }
hex-literal = "0.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"]
cfb-mode-0.8.2/LICENSE-APACHE 0000644 0000000 0000000 00000025141 10461020230 0013236 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.
cfb-mode-0.8.2/LICENSE-MIT 0000644 0000000 0000000 00000002117 10461020230 0012744 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.
cfb-mode-0.8.2/README.md 0000644 0000000 0000000 00000004325 10461020230 0012572 0 ustar 0000000 0000000 # RustCrypto: CFB
[![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 [Cipher Feedback][CFB] (CFB) 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/cfb-mode.svg
[crate-link]: https://crates.io/crates/cfb-mode
[docs-image]: https://docs.rs/cfb-mode/badge.svg
[docs-link]: https://docs.rs/cfb-mode/
[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/cfb-mode/badge.svg?branch=master&event=push
[build-link]: https://github.com/RustCrypto/block-modes/actions?query=workflow%3Acfb-mode+branch%3Amaster
[//]: # (general links)
[CFB]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_feedback_(CFB)
[cipher-doc]: https://docs.rs/cipher/
cfb-mode-0.8.2/src/decrypt.rs 0000644 0000000 0000000 00000017323 10461020230 0014124 0 ustar 0000000 0000000 use cipher::{
crypto_common::{InnerUser, IvSizeUser},
generic_array::{ArrayLength, GenericArray},
inout::InOut,
AlgorithmName, AsyncStreamCipher, Block, BlockBackend, BlockCipher, BlockClosure, BlockDecrypt,
BlockDecryptMut, BlockEncryptMut, BlockSizeUser, InnerIvInit, Iv, IvState, ParBlocks,
ParBlocksSizeUser, Unsigned,
};
use core::fmt;
#[cfg(feature = "zeroize")]
use cipher::zeroize::{Zeroize, ZeroizeOnDrop};
/// CFB mode decryptor.
#[derive(Clone)]
pub struct Decryptor
where
C: BlockEncryptMut + BlockCipher,
{
cipher: C,
iv: Block,
}
/// CFB mode buffered decryptor.
#[derive(Clone)]
pub struct BufDecryptor
where
C: BlockEncryptMut + BlockCipher,
{
cipher: C,
iv: Block,
pos: usize,
}
impl BufDecryptor
where
C: BlockEncryptMut + BlockCipher,
{
/// Decrypt a buffer in multiple parts.
pub fn decrypt(&mut self, mut data: &mut [u8]) {
let bs = C::BlockSize::to_usize();
let n = data.len();
if n < bs - self.pos {
xor_set2(data, &mut self.iv[self.pos..self.pos + n]);
self.pos += n;
return;
}
let (left, right) = { data }.split_at_mut(bs - self.pos);
data = right;
let mut iv = self.iv.clone();
xor_set2(left, &mut iv[self.pos..]);
self.cipher.encrypt_block_mut(&mut iv);
let mut chunks = data.chunks_exact_mut(bs);
for chunk in &mut chunks {
xor_set2(chunk, iv.as_mut_slice());
self.cipher.encrypt_block_mut(&mut iv);
}
let rem = chunks.into_remainder();
xor_set2(rem, iv.as_mut_slice());
self.pos = rem.len();
self.iv = iv;
}
/// Returns the current state (block and position) of the decryptor.
pub fn get_state(&self) -> (&Block, usize) {
(&self.iv, self.pos)
}
/// Restore from the given state for resumption.
pub fn from_state(cipher: C, iv: &Block, pos: usize) -> Self {
Self {
cipher,
iv: iv.clone(),
pos,
}
}
}
impl BlockSizeUser for Decryptor
where
C: BlockEncryptMut + BlockCipher,
{
type BlockSize = C::BlockSize;
}
impl BlockDecryptMut for Decryptor
where
C: BlockEncryptMut + BlockCipher,
{
fn decrypt_with_backend_mut(&mut self, f: impl BlockClosure) {
let Self { cipher, iv } = self;
cipher.encrypt_with_backend_mut(Closure { iv, f })
}
}
impl AsyncStreamCipher for Decryptor where C: BlockEncryptMut + BlockCipher {}
impl InnerUser for Decryptor
where
C: BlockEncryptMut + BlockCipher,
{
type Inner = C;
}
impl InnerUser for BufDecryptor
where
C: BlockEncryptMut + BlockCipher,
{
type Inner = C;
}
impl IvSizeUser for Decryptor
where
C: BlockEncryptMut + BlockCipher,
{
type IvSize = C::BlockSize;
}
impl IvSizeUser for BufDecryptor
where
C: BlockEncryptMut + BlockCipher,
{
type IvSize = C::BlockSize;
}
impl InnerIvInit for Decryptor
where
C: BlockEncryptMut + BlockCipher,
{
#[inline]
fn inner_iv_init(mut cipher: C, iv: &Iv) -> Self {
let mut iv = iv.clone();
cipher.encrypt_block_mut(&mut iv);
Self { cipher, iv }
}
}
impl InnerIvInit for BufDecryptor
where
C: BlockEncryptMut + BlockCipher,
{
#[inline]
fn inner_iv_init(mut cipher: C, iv: &Iv) -> Self {
let mut iv = iv.clone();
cipher.encrypt_block_mut(&mut iv);
Self { cipher, iv, pos: 0 }
}
}
impl IvState for Decryptor
where
C: BlockEncryptMut + BlockDecrypt + BlockCipher,
{
#[inline]
fn iv_state(&self) -> Iv {
let mut res = self.iv.clone();
self.cipher.decrypt_block(&mut res);
res
}
}
impl AlgorithmName for Decryptor
where
C: BlockEncryptMut + BlockCipher + AlgorithmName,
{
fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("cfb::Decryptor<")?;
::write_alg_name(f)?;
f.write_str(">")
}
}
impl AlgorithmName for BufDecryptor
where
C: BlockEncryptMut + BlockCipher + AlgorithmName,
{
fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("cfb::BufDecryptor<")?;
::write_alg_name(f)?;
f.write_str(">")
}
}
impl fmt::Debug for Decryptor
where
C: BlockEncryptMut + BlockCipher + AlgorithmName,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("cfb::Decryptor<")?;
::write_alg_name(f)?;
f.write_str("> { ... }")
}
}
impl fmt::Debug for BufDecryptor
where
C: BlockEncryptMut + BlockCipher + AlgorithmName,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("cfb::BufDecryptor<")?;
::write_alg_name(f)?;
f.write_str("> { ... }")
}
}
#[cfg(feature = "zeroize")]
#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
impl Drop for Decryptor {
fn drop(&mut self) {
self.iv.zeroize();
}
}
#[cfg(feature = "zeroize")]
#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
impl Drop for BufDecryptor {
fn drop(&mut self) {
self.iv.zeroize();
}
}
#[cfg(feature = "zeroize")]
#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
impl ZeroizeOnDrop for Decryptor {}
#[cfg(feature = "zeroize")]
#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
impl ZeroizeOnDrop for BufDecryptor {}
struct Closure<'a, BS, BC>
where
BS: ArrayLength,
BC: BlockClosure,
{
iv: &'a mut GenericArray,
f: BC,
}
impl<'a, BS, BC> BlockSizeUser for Closure<'a, BS, BC>
where
BS: ArrayLength,
BC: BlockClosure,
{
type BlockSize = BS;
}
impl<'a, BS, BC> BlockClosure for Closure<'a, BS, BC>
where
BS: ArrayLength,
BC: BlockClosure,
{
#[inline(always)]
fn call>(self, backend: &mut B) {
let Self { iv, f } = self;
f.call(&mut Backend { iv, backend });
}
}
struct Backend<'a, BS, BK>
where
BS: ArrayLength,
BK: BlockBackend,
{
iv: &'a mut GenericArray,
backend: &'a mut BK,
}
impl<'a, BS, BK> BlockSizeUser for Backend<'a, BS, BK>
where
BS: ArrayLength,
BK: BlockBackend,
{
type BlockSize = BS;
}
impl<'a, BS, BK> ParBlocksSizeUser for Backend<'a, BS, BK>
where
BS: ArrayLength,
BK: BlockBackend,
{
type ParBlocksSize = BK::ParBlocksSize;
}
impl<'a, BS, BK> BlockBackend for Backend<'a, BS, BK>
where
BS: ArrayLength,
BK: BlockBackend,
{
#[inline(always)]
fn proc_block(&mut self, mut block: InOut<'_, '_, Block>) {
let mut t = block.clone_in();
block.xor_in2out(self.iv);
self.backend.proc_block((&mut t).into());
*self.iv = t;
}
#[inline(always)]
fn proc_par_blocks(&mut self, mut blocks: InOut<'_, '_, ParBlocks>) {
let mut t = ParBlocks::::default();
let b = (blocks.get_in(), &mut t).into();
self.backend.proc_par_blocks(b);
let n = t.len();
blocks.get(0).xor_in2out(self.iv);
for i in 1..n {
blocks.get(i).xor_in2out(&t[i - 1])
}
*self.iv = t[n - 1].clone();
}
}
#[inline(always)]
fn xor_set2(buf1: &mut [u8], buf2: &mut [u8]) {
for (a, b) in buf1.iter_mut().zip(buf2) {
let t = *a;
*a ^= *b;
*b = t;
}
}
cfb-mode-0.8.2/src/encrypt.rs 0000644 0000000 0000000 00000016404 10461020230 0014135 0 ustar 0000000 0000000 use cipher::{
consts::U1,
crypto_common::{InnerUser, IvSizeUser},
generic_array::{ArrayLength, GenericArray},
inout::InOut,
AlgorithmName, AsyncStreamCipher, Block, BlockBackend, BlockCipher, BlockClosure, BlockDecrypt,
BlockEncryptMut, BlockSizeUser, InnerIvInit, Iv, IvState, ParBlocksSizeUser, Unsigned,
};
use core::fmt;
#[cfg(feature = "zeroize")]
use cipher::zeroize::{Zeroize, ZeroizeOnDrop};
/// CFB mode encryptor.
#[derive(Clone)]
pub struct Encryptor
where
C: BlockEncryptMut + BlockCipher,
{
cipher: C,
iv: Block,
}
/// CFB mode buffered encryptor.
#[derive(Clone)]
pub struct BufEncryptor
where
C: BlockEncryptMut + BlockCipher,
{
cipher: C,
iv: Block,
pos: usize,
}
impl BufEncryptor
where
C: BlockEncryptMut + BlockCipher,
{
/// Encrypt a buffer in multiple parts.
pub fn encrypt(&mut self, mut data: &mut [u8]) {
let bs = C::BlockSize::USIZE;
let n = data.len();
if n < bs - self.pos {
xor_set1(data, &mut self.iv[self.pos..self.pos + n]);
self.pos += n;
return;
}
let (left, right) = { data }.split_at_mut(bs - self.pos);
data = right;
let mut iv = self.iv.clone();
xor_set1(left, &mut iv[self.pos..]);
self.cipher.encrypt_block_mut(&mut iv);
let mut chunks = data.chunks_exact_mut(bs);
for chunk in &mut chunks {
xor_set1(chunk, iv.as_mut_slice());
self.cipher.encrypt_block_mut(&mut iv);
}
let rem = chunks.into_remainder();
xor_set1(rem, iv.as_mut_slice());
self.pos = rem.len();
self.iv = iv;
}
/// Returns the current state (block and position) of the decryptor.
pub fn get_state(&self) -> (&Block, usize) {
(&self.iv, self.pos)
}
/// Restore from the given state for resumption.
pub fn from_state(cipher: C, iv: &Block, pos: usize) -> Self {
Self {
cipher,
iv: iv.clone(),
pos,
}
}
}
impl BlockSizeUser for Encryptor
where
C: BlockEncryptMut + BlockCipher,
{
type BlockSize = C::BlockSize;
}
impl BlockEncryptMut for Encryptor
where
C: BlockEncryptMut + BlockCipher,
{
fn encrypt_with_backend_mut(&mut self, f: impl BlockClosure) {
let Self { cipher, iv } = self;
cipher.encrypt_with_backend_mut(Closure { iv, f })
}
}
impl AsyncStreamCipher for Encryptor where C: BlockEncryptMut + BlockCipher {}
impl InnerUser for Encryptor
where
C: BlockEncryptMut + BlockCipher,
{
type Inner = C;
}
impl InnerUser for BufEncryptor
where
C: BlockEncryptMut + BlockCipher,
{
type Inner = C;
}
impl IvSizeUser for Encryptor
where
C: BlockEncryptMut + BlockCipher,
{
type IvSize = C::BlockSize;
}
impl IvSizeUser for BufEncryptor
where
C: BlockEncryptMut + BlockCipher,
{
type IvSize = C::BlockSize;
}
impl InnerIvInit for Encryptor
where
C: BlockEncryptMut + BlockCipher,
{
#[inline]
fn inner_iv_init(mut cipher: C, iv: &Iv) -> Self {
let mut iv = iv.clone();
cipher.encrypt_block_mut(&mut iv);
Self { cipher, iv }
}
}
impl InnerIvInit for BufEncryptor
where
C: BlockEncryptMut + BlockCipher,
{
#[inline]
fn inner_iv_init(mut cipher: C, iv: &Iv) -> Self {
let mut iv = iv.clone();
cipher.encrypt_block_mut(&mut iv);
Self { cipher, iv, pos: 0 }
}
}
impl IvState for Encryptor
where
C: BlockEncryptMut + BlockDecrypt + BlockCipher,
{
#[inline]
fn iv_state(&self) -> Iv {
let mut res = self.iv.clone();
self.cipher.decrypt_block(&mut res);
res
}
}
impl AlgorithmName for BufEncryptor
where
C: BlockEncryptMut + BlockCipher + AlgorithmName,
{
fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("cfb::BufEncryptor<")?;
::write_alg_name(f)?;
f.write_str(">")
}
}
impl AlgorithmName for Encryptor
where
C: BlockEncryptMut + BlockCipher + AlgorithmName,
{
fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("cfb::Encryptor<")?;
::write_alg_name(f)?;
f.write_str(">")
}
}
impl fmt::Debug for Encryptor
where
C: BlockEncryptMut + BlockCipher + AlgorithmName,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("cfb::Encryptor<")?;
::write_alg_name(f)?;
f.write_str("> { ... }")
}
}
impl fmt::Debug for BufEncryptor
where
C: BlockEncryptMut + BlockCipher + AlgorithmName,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("cfb::BufEncryptor<")?;
::write_alg_name(f)?;
f.write_str("> { ... }")
}
}
#[cfg(feature = "zeroize")]
#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
impl Drop for Encryptor {
fn drop(&mut self) {
self.iv.zeroize();
}
}
#[cfg(feature = "zeroize")]
#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
impl Drop for BufEncryptor {
fn drop(&mut self) {
self.iv.zeroize();
}
}
#[cfg(feature = "zeroize")]
#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
impl ZeroizeOnDrop for Encryptor {}
#[cfg(feature = "zeroize")]
#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
impl ZeroizeOnDrop for BufEncryptor {}
struct Closure<'a, BS, BC>
where
BS: ArrayLength,
BC: BlockClosure,
{
iv: &'a mut GenericArray,
f: BC,
}
impl<'a, BS, BC> BlockSizeUser for Closure<'a, BS, BC>
where
BS: ArrayLength,
BC: BlockClosure,
{
type BlockSize = BS;
}
impl<'a, BS, BC> BlockClosure for Closure<'a, BS, BC>
where
BS: ArrayLength,
BC: BlockClosure,
{
#[inline(always)]
fn call>(self, backend: &mut B) {
let Self { iv, f } = self;
f.call(&mut Backend { iv, backend });
}
}
struct Backend<'a, BS, BK>
where
BS: ArrayLength,
BK: BlockBackend,
{
iv: &'a mut GenericArray,
backend: &'a mut BK,
}
impl<'a, BS, BK> BlockSizeUser for Backend<'a, BS, BK>
where
BS: ArrayLength,
BK: BlockBackend,
{
type BlockSize = BS;
}
impl<'a, BS, BK> ParBlocksSizeUser for Backend<'a, BS, BK>
where
BS: ArrayLength,
BK: BlockBackend,
{
type ParBlocksSize = U1;
}
impl<'a, BS, BK> BlockBackend for Backend<'a, BS, BK>
where
BS: ArrayLength,
BK: BlockBackend,
{
#[inline(always)]
fn proc_block(&mut self, mut block: InOut<'_, '_, Block>) {
block.xor_in2out(self.iv);
let mut t = block.get_out().clone();
self.backend.proc_block((&mut t).into());
*self.iv = t;
}
}
#[inline(always)]
fn xor_set1(buf1: &mut [u8], buf2: &mut [u8]) {
for (a, b) in buf1.iter_mut().zip(buf2) {
let t = *a ^ *b;
*a = t;
*b = t;
}
}
cfb-mode-0.8.2/src/lib.rs 0000644 0000000 0000000 00000004442 10461020230 0013216 0 ustar 0000000 0000000 //! [Cipher feedback][1] (CFB) mode with full block feedback.
//!
//!
//!
//!
//! 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::{AsyncStreamCipher, KeyIvInit};
//! use hex_literal::hex;
//!
//! type Aes128CfbEnc = cfb_mode::Encryptor;
//! type Aes128CfbDec = cfb_mode::Decryptor;
//!
//! let key = [0x42; 16];
//! let iv = [0x24; 16];
//! let plaintext = *b"hello world! this is my plaintext.";
//! let ciphertext = hex!(
//! "3357121ebb5a29468bd861467596ce3d6f99e251cc2d9f0a598032ae386d0ab995b3"
//! );
//!
//! // encrypt/decrypt in-place
//! let mut buf = plaintext.to_vec();
//! Aes128CfbEnc::new(&key.into(), &iv.into()).encrypt(&mut buf);
//! assert_eq!(buf[..], ciphertext[..]);
//!
//! Aes128CfbDec::new(&key.into(), &iv.into()).decrypt(&mut buf);
//! assert_eq!(buf[..], plaintext[..]);
//!
//! // encrypt/decrypt from buffer to buffer
//! // buffer length must be equal to input length
//! let mut buf1 = [0u8; 34];
//! Aes128CfbEnc::new(&key.into(), &iv.into())
//! .encrypt_b2b(&plaintext, &mut buf1)
//! .unwrap();
//! assert_eq!(buf1[..], ciphertext[..]);
//!
//! let mut buf2 = [0u8; 34];
//! Aes128CfbDec::new(&key.into(), &iv.into())
//! .decrypt_b2b(&buf1, &mut buf2)
//! .unwrap();
//! assert_eq!(buf2[..], plaintext[..]);
//! ```
//!
//! [1]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_feedback_(CFB)
#![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)]
mod decrypt;
mod encrypt;
pub use cipher;
pub use decrypt::{BufDecryptor, Decryptor};
pub use encrypt::{BufEncryptor, Encryptor};
cfb-mode-0.8.2/tests/aes.rs 0000644 0000000 0000000 00000010162 10461020230 0013567 0 ustar 0000000 0000000 use aes::*;
use cfb_mode::{BufDecryptor, BufEncryptor, Decryptor, Encryptor};
use cipher::{block_mode_dec_test, block_mode_enc_test, iv_state_test, KeyInit};
iv_state_test!(aes128_cfb_enc_iv_state, Encryptor, encrypt);
iv_state_test!(aes128_cfb_dec_iv_state, Decryptor, decrypt);
iv_state_test!(aes192_cfb_enc_iv_state, Encryptor, encrypt);
iv_state_test!(aes192_cfb_dec_iv_state, Decryptor, decrypt);
iv_state_test!(aes256_cfb_enc_iv_state, Encryptor, encrypt);
iv_state_test!(aes256_cfb_dec_iv_state, Decryptor, decrypt);
// Test vectors from CVAP "AES Multiblock Message Test (MMT) Sample Vectors":
//
block_mode_enc_test!(aes128_cfb_enc_test, "aes128", Encryptor);
block_mode_dec_test!(aes128_cfb_dec_test, "aes128", Decryptor);
block_mode_enc_test!(aes128enc_cfb_enc_test, "aes128", Encryptor);
block_mode_dec_test!(aes128enc_cfb_dec_test, "aes128", Decryptor);
block_mode_enc_test!(aes192_cfb_enc_test, "aes192", Encryptor);
block_mode_dec_test!(aes192_cfb_dec_test, "aes192", Decryptor);
block_mode_enc_test!(aes192enc_cfb_enc_test, "aes192", Encryptor);
block_mode_dec_test!(aes192dec_cfb_dec_test, "aes192", Decryptor);
block_mode_enc_test!(aes256_cfb_enc_test, "aes256", Encryptor);
block_mode_dec_test!(aes256_cfb_dec_test, "aes256", Decryptor);
block_mode_enc_test!(aes256enc_cfb_enc_test, "aes256", Encryptor);
block_mode_dec_test!(aes256dec_cfb_dec_test, "aes256", Decryptor);
/// Test methods from the `AsyncStreamCipher` trait.
#[test]
fn aes128_cfb_async_test() {
use cipher::{AsyncStreamCipher, KeyIvInit};
type Enc = Encryptor;
type Dec = Decryptor;
let key = [42; 16];
let iv = [24; 16];
let mut pt = [0u8; 101];
for (i, b) in pt.iter_mut().enumerate() {
*b = (i % 11) as u8;
}
let enc = Enc::new_from_slices(&key, &iv).unwrap();
let mut ct = pt.clone();
enc.encrypt(&mut ct);
for i in 1..100 {
let enc = Enc::new_from_slices(&key, &iv).unwrap();
let mut t = pt.clone();
let t = &mut t[..i];
enc.encrypt(t);
assert_eq!(t, &ct[..i]);
let dec = Dec::new_from_slices(&key, &iv).unwrap();
dec.decrypt(t);
assert_eq!(t, &pt[..i]);
}
}
#[test]
fn aes128_cfb_buffered_test() {
use cipher::{AsyncStreamCipher, KeyIvInit};
type Enc = Encryptor;
type BufEnc = BufEncryptor;
type BufDec = BufDecryptor;
let key = [42; 16];
let iv = [24; 16];
let mut pt = [0u8; 101];
for (i, b) in pt.iter_mut().enumerate() {
*b = (i % 11) as u8;
}
// unbuffered
let enc = Enc::new_from_slices(&key, &iv).unwrap();
let mut ct = pt.clone();
enc.encrypt(&mut ct);
// buffered
for i in 1..100 {
let mut buf_enc = BufEnc::new_from_slices(&key, &iv).unwrap();
let mut ct2 = pt.clone();
for chunk in ct2.chunks_mut(i) {
buf_enc.encrypt(chunk);
}
assert_eq!(ct2, ct);
let mut buf_dec = BufDec::new_from_slices(&key, &iv).unwrap();
for chunk in ct2.chunks_mut(i) {
buf_dec.decrypt(chunk);
}
assert_eq!(ct2, pt);
}
// buffered with restore
for i in 1..100 {
let mut buf_enc = BufEnc::new_from_slices(&key, &iv).unwrap();
let mut ct2 = pt.clone();
for chunk in ct2.chunks_mut(i) {
let (iv, pos) = buf_enc.get_state();
let cipher = Aes128::new_from_slice(&key).unwrap();
buf_enc = BufEnc::from_state(cipher, iv, pos);
buf_enc.encrypt(chunk);
}
assert_eq!(ct2, ct);
let mut buf_dec = BufDec::new_from_slices(&key, &iv).unwrap();
for chunk in ct2.chunks_mut(i) {
let (iv, pos) = buf_dec.get_state();
let cipher = Aes128::new_from_slice(&key).unwrap();
buf_dec = BufDec::from_state(cipher, iv, pos);
buf_dec.decrypt(chunk);
}
assert_eq!(ct2, pt);
}
}
cfb-mode-0.8.2/tests/data/aes128.blb 0000644 0000000 0000000 00000010255 10461020230 0015051 0 ustar 0000000 0000000 [xG5 X+RKVڒRHd KZ"`)3p9Lj ,϶رՋp pL6Z̹W S7 MX`ޖi@rfv%ca'HR]}@ ;
%h;Xy
]U:~m)1
vl"0i ɟ %y赮s7`Oe!Ȏ5Ұa ]ij eEml6y3|K`Ѻ%+, 4Uj >hJ^`Gt4K~ ðuR>L ,đج+_=W QRS:{M pZA |00K:
&a~p ܻ=F%JE͇
s'aCo
|Z%V/lHd_žFUJ㴂ZFxI56 YG^g{$!n G""0_.0!s iB6S'5<x~Ks.NجF穤cǧ)C/Va1c?/Xx/A ?Q@稺Fy 2hZ/vwta>㞍(;.T2|2erWL(co;n7JG+we exit FY<!͊1Kр@2.ZK4-0B3E9LWL,o.iZ&Y:aD<.7lYGh%'pkZ5<