chore: checkpoint before Python removal

This commit is contained in:
2026-03-26 22:33:59 +00:00
parent 683cec9307
commit e568ddf82a
29972 changed files with 11269302 additions and 2 deletions

1
vendor/pkcs5/.cargo-checksum.json vendored Normal file

File diff suppressed because one or more lines are too long

99
vendor/pkcs5/CHANGELOG.md vendored Normal file
View File

@@ -0,0 +1,99 @@
# 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.7.1 (2023-03-05)
### Changed
- Bump `pbkdf2` to v0.12 ([#913])
- Bump `scrypt` to v0.11 ([#913])
[#913]: https://github.com/RustCrypto/formats/pull/913
## 0.7.0 (2023-02-26) [YANKED]
### Changed
- Bump `der` dependency to v0.7 ([#899])
- Bump `spki` dependency to v0.7 ([#900])
[#899]: https://github.com/RustCrypto/formats/pull/899
[#900]: https://github.com/RustCrypto/formats/pull/900
## 0.6.0 (Skipped)
- Skipped to synchronize version number with `der` and `spki`
## 0.5.0 (2022-05-08)
### Changed
- Update `hmac`, `pbkdf2`, and `sha2`
- Update cipher v0.4 crates ([#411])
- Switch from `sha-1` to `sha1`; `sha1` feature is renamed to `sha1-insecure` ([#426])
- Bump `scrypt` dependency to v0.9 ([#441])
- Bump `der` to v0.6 ([#653])
- Bump `spki` to v0.6 ([#654])
[#411]: https://github.com/RustCrypto/formats/pull/411
[#426]: https://github.com/RustCrypto/formats/pull/426
[#441]: https://github.com/RustCrypto/formats/pull/441
[#653]: https://github.com/RustCrypto/formats/pull/653
[#654]: https://github.com/RustCrypto/formats/pull/654
## 0.4.0 (2021-11-15)
### Changed
- Introduce `Error` enum with new error cases ([#26])
- Introduce specialized `Result` type for crate ([#26])
- Rust 2021 edition upgrade; MSRV 1.56 ([#136])
- Bump `der` dependency to v0.5 ([#222])
- Bump `spki` dependency to v0.5 ([#223])
### Removed
- Legacy DES encryption support ([#25])
[#25]: https://github.com/RustCrypto/formats/pull/25
[#26]: https://github.com/RustCrypto/formats/pull/26
[#136]: https://github.com/RustCrypto/formats/pull/136
[#222]: https://github.com/RustCrypto/formats/pull/222
[#223]: https://github.com/RustCrypto/formats/pull/223
## 0.3.2 (2021-09-14)
### Added
- `3des` and `des-insecure` features
- `sha1` feature
- Support for AES-192-CBC
### Changed
- Moved to `formats` repo ([#2])
[#2]: https://github.com/RustCrypto/formats/pull/2
## 0.3.1 (2021-08-30)
### Changed
- Bump `scrypt` dependency to 0.8
- Bump `pbkdf2` dependency to v0.9
## 0.3.0 (2021-06-07)
### Changed
- Bump `der` crate dependency to v0.4
- Bump `spki` crate dependency to v0.4
## 0.2.2 (2021-05-26)
### Added
- `scrypt` support as specified in RFC 7914
## 0.2.1 (2021-04-29)
### Changed
- Bump `aes` to v0.7
- Bump `block-modes` to v0.8
- Bump `hmac` to v0.11
- Bump `pbkdf2` to v0.8
## 0.2.0 (2021-03-22)
### Changed
- Bump `der` to v0.3
- Bump `spki` to v0.3
## 0.1.1 (2021-02-23)
### Added
- Encryption support
## 0.1.0 (2021-02-20)
- Initial release

109
vendor/pkcs5/Cargo.toml vendored Normal file
View File

@@ -0,0 +1,109 @@
# 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.65"
name = "pkcs5"
version = "0.7.1"
authors = ["RustCrypto Developers"]
description = """
Pure Rust implementation of Public-Key Cryptography Standards (PKCS) #5:
Password-Based Cryptography Specification Version 2.1 (RFC 8018)
"""
readme = "README.md"
keywords = [
"crypto",
"key",
"pkcs",
"password",
]
categories = [
"cryptography",
"data-structures",
"encoding",
"no-std",
]
license = "Apache-2.0 OR MIT"
repository = "https://github.com/RustCrypto/formats/tree/master/pkcs5"
[package.metadata.docs.rs]
all-features = true
rustdoc-args = [
"--cfg",
"docsrs",
]
[dependencies.aes]
version = "0.8.2"
optional = true
default-features = false
[dependencies.cbc]
version = "0.1.2"
optional = true
[dependencies.der]
version = "0.7"
features = ["oid"]
[dependencies.des]
version = "0.8.1"
optional = true
default-features = false
[dependencies.pbkdf2]
version = "0.12.1"
optional = true
default-features = false
[dependencies.scrypt]
version = "0.11"
optional = true
default-features = false
[dependencies.sha1]
version = "0.10.1"
optional = true
default-features = false
[dependencies.sha2]
version = "0.10.2"
optional = true
default-features = false
[dependencies.spki]
version = "0.7"
[dev-dependencies.hex-literal]
version = "0.3"
[features]
3des = [
"dep:des",
"pbes2",
]
alloc = []
des-insecure = [
"dep:des",
"pbes2",
]
pbes2 = [
"dep:aes",
"dep:cbc",
"dep:pbkdf2",
"dep:scrypt",
"dep:sha2",
]
sha1-insecure = [
"dep:sha1",
"pbes2",
]

201
vendor/pkcs5/LICENSE-APACHE vendored Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

25
vendor/pkcs5/LICENSE-MIT vendored Normal file
View File

@@ -0,0 +1,25 @@
Copyright (c) 2021-2023 The RustCrypto Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

53
vendor/pkcs5/README.md vendored Normal file
View File

@@ -0,0 +1,53 @@
# [RustCrypto]: PKCS#5
[![crate][crate-image]][crate-link]
[![Docs][docs-image]][docs-link]
[![Build Status][build-image]][build-link]
![Apache2/MIT licensed][license-image]
![Rust Version][rustc-image]
[![Project Chat][chat-image]][chat-link]
Pure Rust implementation of Public-Key Cryptography Standards (PKCS) #5:
Password-Based Cryptography Specification Version 2.1 ([RFC 8018]).
[Documentation][docs-link]
## Minimum Supported Rust Version
This crate requires **Rust 1.65** at a minimum.
We may change the MSRV in the future, but it will be accompanied by a minor
version bump.
## 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://buildstats.info/crate/pkcs5
[crate-link]: https://crates.io/crates/pkcs5
[docs-image]: https://docs.rs/pkcs5/badge.svg
[docs-link]: https://docs.rs/pkcs5/
[build-image]: https://github.com/RustCrypto/formats/actions/workflows/pkcs5.yml/badge.svg
[build-link]: https://github.com/RustCrypto/formats/actions/workflows/pkcs5.yml
[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg
[rustc-image]: https://img.shields.io/badge/rustc-1.65+-blue.svg
[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg
[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/300570-formats
[//]: # (links)
[RustCrypto]: https://github.com/rustcrypto
[RFC 8018]: https://tools.ietf.org/html/rfc8018

56
vendor/pkcs5/src/error.rs vendored Normal file
View File

@@ -0,0 +1,56 @@
//! Error types
use core::fmt;
use der::asn1::ObjectIdentifier;
/// Result type
pub type Result<T> = core::result::Result<T, Error>;
/// Error type
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Error {
/// Given parameters are invalid for this algorithm
AlgorithmParametersInvalid {
/// OID for algorithm for which the parameters were invalid
oid: ObjectIdentifier,
},
/// Decryption Failed
DecryptFailed,
/// Encryption Failed
EncryptFailed,
/// Pbes1 support is limited to parsing; encryption/decryption is not supported (won't fix)
#[cfg(feature = "pbes2")]
NoPbes1CryptSupport,
/// Algorithm is not supported
///
/// This may be due to a disabled crate feature
/// Or the algorithm is not supported at all.
UnsupportedAlgorithm {
/// OID of unsupported algorithm
oid: ObjectIdentifier,
},
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::AlgorithmParametersInvalid { oid } => {
write!(f, "PKCS#5 parameters for algorithm {} are invalid", oid)
}
Error::DecryptFailed => f.write_str("PKCS#5 decryption failed"),
Error::EncryptFailed => f.write_str("PKCS#5 encryption failed"),
#[cfg(feature = "pbes2")]
Error::NoPbes1CryptSupport => {
f.write_str("PKCS#5 encryption/decryption unsupported for PBES1 (won't fix)")
}
Error::UnsupportedAlgorithm { oid } => {
write!(f, "PKCS#5 algorithm {} is unsupported", oid)
}
}
}
}

208
vendor/pkcs5/src/lib.rs vendored Normal file
View File

@@ -0,0 +1,208 @@
#![no_std]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![doc = include_str!("../README.md")]
#![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)]
#![warn(
clippy::mod_module_files,
clippy::unwrap_used,
missing_docs,
rust_2018_idioms,
unused_lifetimes,
unused_qualifications
)]
//! # Usage
//!
//! The main API for this crate is the [`EncryptionScheme`] enum, which impls
//! the [`Decode`] and [`Encode`] traits from the [`der`] crate, and can be
//! used for decoding/encoding PKCS#5 `AlgorithmIdentifier` fields.
//!
//! [RFC 8018]: https://tools.ietf.org/html/rfc8018
#[cfg(all(feature = "alloc", feature = "pbes2"))]
extern crate alloc;
mod error;
pub mod pbes1;
pub mod pbes2;
pub use crate::error::{Error, Result};
pub use der::{self, asn1::ObjectIdentifier};
pub use spki::AlgorithmIdentifierRef;
use der::{
Decode, DecodeValue, Encode, EncodeValue, Header, Length, Reader, Sequence, Tag, Writer,
};
#[cfg(feature = "pbes2")]
pub use scrypt;
#[cfg(all(feature = "alloc", feature = "pbes2"))]
use alloc::vec::Vec;
/// Supported PKCS#5 password-based encryption schemes.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
#[allow(clippy::large_enum_variant)]
pub enum EncryptionScheme<'a> {
/// Password-Based Encryption Scheme 1 as defined in [RFC 8018 Section 6.1].
///
/// [RFC 8018 Section 6.1]: https://tools.ietf.org/html/rfc8018#section-6.1
Pbes1(pbes1::Algorithm),
/// Password-Based Encryption Scheme 2 as defined in [RFC 8018 Section 6.2].
///
/// [RFC 8018 Section 6.2]: https://tools.ietf.org/html/rfc8018#section-6.2
Pbes2(pbes2::Parameters<'a>),
}
impl<'a> EncryptionScheme<'a> {
/// Attempt to decrypt the given ciphertext, allocating and returning a
/// byte vector containing the plaintext.
#[cfg(all(feature = "alloc", feature = "pbes2"))]
pub fn decrypt(&self, password: impl AsRef<[u8]>, ciphertext: &[u8]) -> Result<Vec<u8>> {
match self {
Self::Pbes2(params) => params.decrypt(password, ciphertext),
Self::Pbes1(_) => Err(Error::NoPbes1CryptSupport),
}
}
/// Attempt to decrypt the given ciphertext in-place using a key derived
/// from the provided password and this scheme's parameters.
///
/// Returns an error if the algorithm specified in this scheme's parameters
/// is unsupported, or if the ciphertext is malformed (e.g. not a multiple
/// of a block mode's padding)
#[cfg(feature = "pbes2")]
pub fn decrypt_in_place<'b>(
&self,
password: impl AsRef<[u8]>,
buffer: &'b mut [u8],
) -> Result<&'b [u8]> {
match self {
Self::Pbes2(params) => params.decrypt_in_place(password, buffer),
Self::Pbes1(_) => Err(Error::NoPbes1CryptSupport),
}
}
/// Encrypt the given plaintext, allocating and returning a vector
/// containing the ciphertext.
#[cfg(all(feature = "alloc", feature = "pbes2"))]
pub fn encrypt(&self, password: impl AsRef<[u8]>, plaintext: &[u8]) -> Result<Vec<u8>> {
match self {
Self::Pbes2(params) => params.encrypt(password, plaintext),
Self::Pbes1(_) => Err(Error::NoPbes1CryptSupport),
}
}
/// Encrypt the given ciphertext in-place using a key derived from the
/// provided password and this scheme's parameters.
#[cfg(feature = "pbes2")]
pub fn encrypt_in_place<'b>(
&self,
password: impl AsRef<[u8]>,
buffer: &'b mut [u8],
pos: usize,
) -> Result<&'b [u8]> {
match self {
Self::Pbes2(params) => params.encrypt_in_place(password, buffer, pos),
Self::Pbes1(_) => Err(Error::NoPbes1CryptSupport),
}
}
/// Get the [`ObjectIdentifier`] (a.k.a OID) for this algorithm.
pub fn oid(&self) -> ObjectIdentifier {
match self {
Self::Pbes1(params) => params.oid(),
Self::Pbes2(_) => pbes2::PBES2_OID,
}
}
/// Get [`pbes1::Parameters`] if it is the selected algorithm.
pub fn pbes1(&self) -> Option<&pbes1::Algorithm> {
match self {
Self::Pbes1(alg) => Some(alg),
_ => None,
}
}
/// Get [`pbes2::Parameters`] if it is the selected algorithm.
pub fn pbes2(&self) -> Option<&pbes2::Parameters<'a>> {
match self {
Self::Pbes2(params) => Some(params),
_ => None,
}
}
}
impl<'a> DecodeValue<'a> for EncryptionScheme<'a> {
fn decode_value<R: Reader<'a>>(decoder: &mut R, header: Header) -> der::Result<Self> {
AlgorithmIdentifierRef::decode_value(decoder, header)?.try_into()
}
}
impl EncodeValue for EncryptionScheme<'_> {
fn value_len(&self) -> der::Result<Length> {
match self {
Self::Pbes1(pbes1) => pbes1.oid().encoded_len()? + pbes1.parameters.encoded_len()?,
Self::Pbes2(pbes2) => pbes2::PBES2_OID.encoded_len()? + pbes2.encoded_len()?,
}
}
fn encode_value(&self, writer: &mut impl Writer) -> der::Result<()> {
match self {
Self::Pbes1(pbes1) => {
pbes1.oid().encode(writer)?;
pbes1.parameters.encode(writer)?;
}
Self::Pbes2(pbes2) => {
pbes2::PBES2_OID.encode(writer)?;
pbes2.encode(writer)?;
}
}
Ok(())
}
}
impl<'a> Sequence<'a> for EncryptionScheme<'a> {}
impl<'a> From<pbes1::Algorithm> for EncryptionScheme<'a> {
fn from(alg: pbes1::Algorithm) -> EncryptionScheme<'a> {
Self::Pbes1(alg)
}
}
impl<'a> From<pbes2::Parameters<'a>> for EncryptionScheme<'a> {
fn from(params: pbes2::Parameters<'a>) -> EncryptionScheme<'a> {
Self::Pbes2(params)
}
}
impl<'a> TryFrom<AlgorithmIdentifierRef<'a>> for EncryptionScheme<'a> {
type Error = der::Error;
fn try_from(alg: AlgorithmIdentifierRef<'a>) -> der::Result<EncryptionScheme<'_>> {
if alg.oid == pbes2::PBES2_OID {
match alg.parameters {
Some(params) => pbes2::Parameters::try_from(params).map(Into::into),
None => Err(Tag::OctetString.value_error()),
}
} else {
pbes1::Algorithm::try_from(alg).map(Into::into)
}
}
}
impl<'a> TryFrom<&'a [u8]> for EncryptionScheme<'a> {
type Error = der::Error;
fn try_from(bytes: &'a [u8]) -> der::Result<EncryptionScheme<'a>> {
AlgorithmIdentifierRef::from_der(bytes)?.try_into()
}
}

272
vendor/pkcs5/src/pbes1.rs vendored Normal file
View File

@@ -0,0 +1,272 @@
//! Password-Based Encryption Scheme 1 as defined in [RFC 8018 Section 6.1].
//!
//! [RFC 8018 Section 6.1]: https://tools.ietf.org/html/rfc8018#section-6.1
use crate::AlgorithmIdentifierRef;
use der::{
asn1::{AnyRef, ObjectIdentifier, OctetStringRef},
Decode, DecodeValue, Encode, EncodeValue, ErrorKind, Length, Reader, Sequence, Tag, Writer,
};
/// `pbeWithMD2AndDES-CBC` Object Identifier (OID).
pub const PBE_WITH_MD2_AND_DES_CBC_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.2.840.113549.1.5.1");
/// `pbeWithMD2AndRC2-CBC` Object Identifier (OID).
pub const PBE_WITH_MD2_AND_RC2_CBC_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.2.840.113549.1.5.4");
/// `pbeWithMD5AndDES-CBC` Object Identifier (OID).
pub const PBE_WITH_MD5_AND_DES_CBC_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.2.840.113549.1.5.3");
/// `pbeWithMD5AndRC2-CBC` Object Identifier (OID).
pub const PBE_WITH_MD5_AND_RC2_CBC_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.2.840.113549.1.5.6");
/// `pbeWithSHA1AndDES-CBC` Object Identifier (OID).
pub const PBE_WITH_SHA1_AND_DES_CBC_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.2.840.113549.1.5.10");
/// `pbeWithSHA1AndRC2-CBC` Object Identifier (OID).
pub const PBE_WITH_SHA1_AND_RC2_CBC_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.2.840.113549.1.5.11");
/// Length of a PBES1 salt (as defined in the `PBEParameter` ASN.1 message).
pub const SALT_LENGTH: usize = 8;
/// Password-Based Encryption Scheme 1 algorithms as defined in [RFC 8018 Appendix A.C].
///
/// ```text
/// PBES1Algorithms ALGORITHM-IDENTIFIER ::= {
/// {PBEParameter IDENTIFIED BY pbeWithMD2AndDES-CBC} |
/// {PBEParameter IDENTIFIED BY pbeWithMD2AndRC2-CBC} |
/// {PBEParameter IDENTIFIED BY pbeWithMD5AndDES-CBC} |
/// {PBEParameter IDENTIFIED BY pbeWithMD5AndRC2-CBC} |
/// {PBEParameter IDENTIFIED BY pbeWithSHA1AndDES-CBC} |
/// {PBEParameter IDENTIFIED BY pbeWithSHA1AndRC2-CBC},
/// ...
/// }
/// ```
///
/// [RFC 8018 Appendix A.C]: https://datatracker.ietf.org/doc/html/rfc8018#appendix-C
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Algorithm {
/// Encryption scheme.
pub encryption: EncryptionScheme,
/// Scheme parameters.
pub parameters: Parameters,
}
impl Algorithm {
/// Get the [`ObjectIdentifier`] (a.k.a OID) for this algorithm.
pub fn oid(&self) -> ObjectIdentifier {
self.encryption.oid()
}
}
impl<'a> DecodeValue<'a> for Algorithm {
fn decode_value<R: Reader<'a>>(reader: &mut R, header: der::Header) -> der::Result<Self> {
AlgorithmIdentifierRef::decode_value(reader, header)?.try_into()
}
}
impl EncodeValue for Algorithm {
fn value_len(&self) -> der::Result<Length> {
self.encryption.encoded_len()? + self.parameters.encoded_len()?
}
fn encode_value(&self, writer: &mut impl Writer) -> der::Result<()> {
self.encryption.encode(writer)?;
self.parameters.encode(writer)?;
Ok(())
}
}
impl Sequence<'_> for Algorithm {}
impl<'a> TryFrom<AlgorithmIdentifierRef<'a>> for Algorithm {
type Error = der::Error;
fn try_from(alg: AlgorithmIdentifierRef<'a>) -> der::Result<Self> {
// Ensure that we have a supported PBES1 algorithm identifier
let encryption = EncryptionScheme::try_from(alg.oid)
.map_err(|_| der::Tag::ObjectIdentifier.value_error())?;
let parameters = alg
.parameters
.ok_or_else(|| Tag::OctetString.value_error())?
.try_into()?;
Ok(Self {
encryption,
parameters,
})
}
}
/// Password-Based Encryption Scheme 1 parameters as defined in [RFC 8018 Appendix A.3].
///
/// ```text
/// PBEParameter ::= SEQUENCE {
/// salt OCTET STRING (SIZE(8)),
/// iterationCount INTEGER }
/// ```
///
/// [RFC 8018 Appendix A.3]: https://tools.ietf.org/html/rfc8018#appendix-A.3
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Parameters {
/// Salt value
pub salt: [u8; SALT_LENGTH],
/// Iteration count
pub iteration_count: u16,
}
impl<'a> DecodeValue<'a> for Parameters {
fn decode_value<R: Reader<'a>>(reader: &mut R, header: der::Header) -> der::Result<Self> {
AnyRef::decode_value(reader, header)?.try_into()
}
}
impl EncodeValue for Parameters {
fn value_len(&self) -> der::Result<Length> {
OctetStringRef::new(&self.salt)?.encoded_len()? + self.iteration_count.encoded_len()?
}
fn encode_value(&self, writer: &mut impl Writer) -> der::Result<()> {
OctetStringRef::new(&self.salt)?.encode(writer)?;
self.iteration_count.encode(writer)?;
Ok(())
}
}
impl Sequence<'_> for Parameters {}
impl TryFrom<AnyRef<'_>> for Parameters {
type Error = der::Error;
fn try_from(any: AnyRef<'_>) -> der::Result<Parameters> {
any.sequence(|reader| {
Ok(Parameters {
salt: OctetStringRef::decode(reader)?
.as_bytes()
.try_into()
.map_err(|_| der::Tag::OctetString.value_error())?,
iteration_count: reader.decode()?,
})
})
}
}
/// Password-Based Encryption Scheme 1 ciphersuites as defined in [RFC 8018 Appendix A.3].
///
/// [RFC 8018 Appendix A.3]: https://tools.ietf.org/html/rfc8018#appendix-A.3
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum EncryptionScheme {
/// `pbeWithMD2AndDES-CBC`
PbeWithMd2AndDesCbc,
/// `pbeWithMD2AndRC2-CBC`
PbeWithMd2AndRc2Cbc,
/// `pbeWithMD5AndDES-CBC`
PbeWithMd5AndDesCbc,
/// `pbeWithMD5AndRC2-CBC`
PbeWithMd5AndRc2Cbc,
/// `pbeWithSHA1AndDES-CBC`
PbeWithSha1AndDesCbc,
/// `pbeWithSHA1AndRC2-CBC`
PbeWithSha1AndRc2Cbc,
}
impl TryFrom<ObjectIdentifier> for EncryptionScheme {
type Error = der::Error;
fn try_from(oid: ObjectIdentifier) -> der::Result<Self> {
match oid {
PBE_WITH_MD2_AND_DES_CBC_OID => Ok(Self::PbeWithMd2AndDesCbc),
PBE_WITH_MD2_AND_RC2_CBC_OID => Ok(Self::PbeWithMd2AndRc2Cbc),
PBE_WITH_MD5_AND_DES_CBC_OID => Ok(Self::PbeWithMd5AndDesCbc),
PBE_WITH_MD5_AND_RC2_CBC_OID => Ok(Self::PbeWithMd5AndRc2Cbc),
PBE_WITH_SHA1_AND_DES_CBC_OID => Ok(Self::PbeWithSha1AndDesCbc),
PBE_WITH_SHA1_AND_RC2_CBC_OID => Ok(Self::PbeWithSha1AndRc2Cbc),
_ => Err(ErrorKind::OidUnknown { oid }.into()),
}
}
}
impl EncryptionScheme {
/// Get the [`SymmetricCipher`] to be used.
pub fn cipher(self) -> SymmetricCipher {
match self {
Self::PbeWithMd2AndDesCbc => SymmetricCipher::DesCbc,
Self::PbeWithMd2AndRc2Cbc => SymmetricCipher::Rc2Cbc,
Self::PbeWithMd5AndDesCbc => SymmetricCipher::DesCbc,
Self::PbeWithMd5AndRc2Cbc => SymmetricCipher::Rc2Cbc,
Self::PbeWithSha1AndDesCbc => SymmetricCipher::DesCbc,
Self::PbeWithSha1AndRc2Cbc => SymmetricCipher::Rc2Cbc,
}
}
/// Get the [`DigestAlgorithm`] to be used.
pub fn digest(self) -> DigestAlgorithm {
match self {
Self::PbeWithMd2AndDesCbc => DigestAlgorithm::Md2,
Self::PbeWithMd2AndRc2Cbc => DigestAlgorithm::Md2,
Self::PbeWithMd5AndDesCbc => DigestAlgorithm::Md5,
Self::PbeWithMd5AndRc2Cbc => DigestAlgorithm::Md5,
Self::PbeWithSha1AndDesCbc => DigestAlgorithm::Sha1,
Self::PbeWithSha1AndRc2Cbc => DigestAlgorithm::Sha1,
}
}
/// Get the [`ObjectIdentifier`] (a.k.a OID) for this algorithm.
pub fn oid(self) -> ObjectIdentifier {
match self {
Self::PbeWithMd2AndDesCbc => PBE_WITH_MD2_AND_DES_CBC_OID,
Self::PbeWithMd2AndRc2Cbc => PBE_WITH_MD2_AND_RC2_CBC_OID,
Self::PbeWithMd5AndDesCbc => PBE_WITH_MD5_AND_DES_CBC_OID,
Self::PbeWithMd5AndRc2Cbc => PBE_WITH_MD5_AND_RC2_CBC_OID,
Self::PbeWithSha1AndDesCbc => PBE_WITH_SHA1_AND_DES_CBC_OID,
Self::PbeWithSha1AndRc2Cbc => PBE_WITH_SHA1_AND_RC2_CBC_OID,
}
}
}
impl Encode for EncryptionScheme {
fn encoded_len(&self) -> der::Result<Length> {
self.oid().encoded_len()
}
fn encode(&self, writer: &mut impl Writer) -> der::Result<()> {
self.oid().encode(writer)
}
}
/// Digest algorithms supported by PBES1.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum DigestAlgorithm {
/// MD2
Md2,
/// MD5
Md5,
/// SHA-1
Sha1,
}
/// Symmetric encryption ciphers supported by PBES1.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum SymmetricCipher {
/// DES in CBC mode
DesCbc,
/// RC2 in CBC mode
Rc2Cbc,
}

381
vendor/pkcs5/src/pbes2.rs vendored Normal file
View File

@@ -0,0 +1,381 @@
//! Password-Based Encryption Scheme 2 as defined in [RFC 8018 Section 6.2].
//!
//! [RFC 8018 Section 6.2]: https://tools.ietf.org/html/rfc8018#section-6.2
mod kdf;
#[cfg(feature = "pbes2")]
mod encryption;
pub use self::kdf::{
Kdf, Pbkdf2Params, Pbkdf2Prf, ScryptParams, HMAC_WITH_SHA1_OID, HMAC_WITH_SHA256_OID,
PBKDF2_OID, SCRYPT_OID,
};
use crate::{AlgorithmIdentifierRef, Error, Result};
use der::{
asn1::{AnyRef, ObjectIdentifier, OctetStringRef},
Decode, DecodeValue, Encode, EncodeValue, ErrorKind, Length, Reader, Sequence, Tag, Writer,
};
#[cfg(all(feature = "alloc", feature = "pbes2"))]
use alloc::vec::Vec;
/// 128-bit Advanced Encryption Standard (AES) algorithm with Cipher-Block
/// Chaining (CBC) mode of operation.
pub const AES_128_CBC_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.1.2");
/// 192-bit Advanced Encryption Standard (AES) algorithm with Cipher-Block
/// Chaining (CBC) mode of operation.
pub const AES_192_CBC_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.1.22");
/// 256-bit Advanced Encryption Standard (AES) algorithm with Cipher-Block
/// Chaining (CBC) mode of operation.
pub const AES_256_CBC_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.1.42");
/// DES operating in CBC mode
#[cfg(feature = "des-insecure")]
pub const DES_CBC_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.14.3.2.7");
/// Triple DES operating in CBC mode
#[cfg(feature = "3des")]
pub const DES_EDE3_CBC_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.3.7");
/// Password-Based Encryption Scheme 2 (PBES2) OID.
///
/// <https://tools.ietf.org/html/rfc8018#section-6.2>
pub const PBES2_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.5.13");
/// AES cipher block size
const AES_BLOCK_SIZE: usize = 16;
/// DES / Triple DES block size
#[cfg(any(feature = "3des", feature = "des-insecure"))]
const DES_BLOCK_SIZE: usize = 8;
/// Password-Based Encryption Scheme 2 parameters as defined in [RFC 8018 Appendix A.4].
///
/// ```text
/// PBES2-params ::= SEQUENCE {
/// keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},
/// encryptionScheme AlgorithmIdentifier {{PBES2-Encs}} }
/// ```
///
/// [RFC 8018 Appendix A.4]: https://tools.ietf.org/html/rfc8018#appendix-A.4
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Parameters<'a> {
/// Key derivation function
pub kdf: Kdf<'a>,
/// Encryption scheme
pub encryption: EncryptionScheme<'a>,
}
impl<'a> Parameters<'a> {
/// Initialize PBES2 parameters using PBKDF2-SHA256 as the password-based
/// key derivation function and AES-128-CBC as the symmetric cipher.
pub fn pbkdf2_sha256_aes128cbc(
pbkdf2_iterations: u32,
pbkdf2_salt: &'a [u8],
aes_iv: &'a [u8; AES_BLOCK_SIZE],
) -> Result<Self> {
let kdf = Pbkdf2Params::hmac_with_sha256(pbkdf2_iterations, pbkdf2_salt)?.into();
let encryption = EncryptionScheme::Aes128Cbc { iv: aes_iv };
Ok(Self { kdf, encryption })
}
/// Initialize PBES2 parameters using PBKDF2-SHA256 as the password-based
/// key derivation function and AES-256-CBC as the symmetric cipher.
pub fn pbkdf2_sha256_aes256cbc(
pbkdf2_iterations: u32,
pbkdf2_salt: &'a [u8],
aes_iv: &'a [u8; AES_BLOCK_SIZE],
) -> Result<Self> {
let kdf = Pbkdf2Params::hmac_with_sha256(pbkdf2_iterations, pbkdf2_salt)?.into();
let encryption = EncryptionScheme::Aes256Cbc { iv: aes_iv };
Ok(Self { kdf, encryption })
}
/// Initialize PBES2 parameters using scrypt as the password-based
/// key derivation function and AES-128-CBC as the symmetric cipher.
///
/// For more information on scrypt parameters, see documentation for the
/// [`scrypt::Params`] struct.
// TODO(tarcieri): encapsulate `scrypt::Params`?
#[cfg(feature = "pbes2")]
pub fn scrypt_aes128cbc(
params: scrypt::Params,
salt: &'a [u8],
aes_iv: &'a [u8; AES_BLOCK_SIZE],
) -> Result<Self> {
let kdf = ScryptParams::from_params_and_salt(params, salt)?.into();
let encryption = EncryptionScheme::Aes128Cbc { iv: aes_iv };
Ok(Self { kdf, encryption })
}
/// Initialize PBES2 parameters using scrypt as the password-based
/// key derivation function and AES-256-CBC as the symmetric cipher.
///
/// For more information on scrypt parameters, see documentation for the
/// [`scrypt::Params`] struct.
///
/// When in doubt, use `Default::default()` as the [`scrypt::Params`].
/// This also avoids the need to import the type from the `scrypt` crate.
// TODO(tarcieri): encapsulate `scrypt::Params`?
#[cfg(feature = "pbes2")]
pub fn scrypt_aes256cbc(
params: scrypt::Params,
salt: &'a [u8],
aes_iv: &'a [u8; AES_BLOCK_SIZE],
) -> Result<Self> {
let kdf = ScryptParams::from_params_and_salt(params, salt)?.into();
let encryption = EncryptionScheme::Aes256Cbc { iv: aes_iv };
Ok(Self { kdf, encryption })
}
/// Attempt to decrypt the given ciphertext, allocating and returning a
/// byte vector containing the plaintext.
#[cfg(all(feature = "alloc", feature = "pbes2"))]
pub fn decrypt(&self, password: impl AsRef<[u8]>, ciphertext: &[u8]) -> Result<Vec<u8>> {
let mut buffer = ciphertext.to_vec();
let pt_len = self.decrypt_in_place(password, &mut buffer)?.len();
buffer.truncate(pt_len);
Ok(buffer)
}
/// Attempt to decrypt the given ciphertext in-place using a key derived
/// from the provided password and this scheme's parameters.
///
/// Returns an error if the algorithm specified in this scheme's parameters
/// is unsupported, or if the ciphertext is malformed (e.g. not a multiple
/// of a block mode's padding)
#[cfg(feature = "pbes2")]
pub fn decrypt_in_place<'b>(
&self,
password: impl AsRef<[u8]>,
buffer: &'b mut [u8],
) -> Result<&'b [u8]> {
encryption::decrypt_in_place(self, password, buffer)
}
/// Encrypt the given plaintext, allocating and returning a vector
/// containing the ciphertext.
#[cfg(all(feature = "alloc", feature = "pbes2"))]
pub fn encrypt(&self, password: impl AsRef<[u8]>, plaintext: &[u8]) -> Result<Vec<u8>> {
// TODO(tarcieri): support non-AES ciphers?
let mut buffer = Vec::with_capacity(plaintext.len() + AES_BLOCK_SIZE);
buffer.extend_from_slice(plaintext);
buffer.extend_from_slice(&[0u8; AES_BLOCK_SIZE]);
let ct_len = self
.encrypt_in_place(password, &mut buffer, plaintext.len())?
.len();
buffer.truncate(ct_len);
Ok(buffer)
}
/// Encrypt the given plaintext in-place using a key derived from the
/// provided password and this scheme's parameters, writing the ciphertext
/// into the same buffer.
#[cfg(feature = "pbes2")]
pub fn encrypt_in_place<'b>(
&self,
password: impl AsRef<[u8]>,
buffer: &'b mut [u8],
pos: usize,
) -> Result<&'b [u8]> {
encryption::encrypt_in_place(self, password, buffer, pos)
}
}
impl<'a> DecodeValue<'a> for Parameters<'a> {
fn decode_value<R: Reader<'a>>(reader: &mut R, header: der::Header) -> der::Result<Self> {
AnyRef::decode_value(reader, header)?.try_into()
}
}
impl EncodeValue for Parameters<'_> {
fn value_len(&self) -> der::Result<Length> {
self.kdf.encoded_len()? + self.encryption.encoded_len()?
}
fn encode_value(&self, writer: &mut impl Writer) -> der::Result<()> {
self.kdf.encode(writer)?;
self.encryption.encode(writer)?;
Ok(())
}
}
impl<'a> Sequence<'a> for Parameters<'a> {}
impl<'a> TryFrom<AnyRef<'a>> for Parameters<'a> {
type Error = der::Error;
fn try_from(any: AnyRef<'a>) -> der::Result<Self> {
any.sequence(|params| {
let kdf = AlgorithmIdentifierRef::decode(params)?;
let encryption = AlgorithmIdentifierRef::decode(params)?;
Ok(Self {
kdf: kdf.try_into()?,
encryption: encryption.try_into()?,
})
})
}
}
/// Symmetric encryption scheme used by PBES2.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum EncryptionScheme<'a> {
/// AES-128 in CBC mode
Aes128Cbc {
/// Initialization vector
iv: &'a [u8; AES_BLOCK_SIZE],
},
/// AES-192 in CBC mode
Aes192Cbc {
/// Initialization vector
iv: &'a [u8; AES_BLOCK_SIZE],
},
/// AES-256 in CBC mode
Aes256Cbc {
/// Initialization vector
iv: &'a [u8; AES_BLOCK_SIZE],
},
/// 3-Key Triple DES in CBC mode
#[cfg(feature = "3des")]
DesEde3Cbc {
/// Initialisation vector
iv: &'a [u8; DES_BLOCK_SIZE],
},
/// DES in CBC mode
#[cfg(feature = "des-insecure")]
DesCbc {
/// Initialisation vector
iv: &'a [u8; DES_BLOCK_SIZE],
},
}
impl<'a> EncryptionScheme<'a> {
/// Get the size of a key used by this algorithm in bytes.
pub fn key_size(&self) -> usize {
match self {
Self::Aes128Cbc { .. } => 16,
Self::Aes192Cbc { .. } => 24,
Self::Aes256Cbc { .. } => 32,
#[cfg(feature = "des-insecure")]
Self::DesCbc { .. } => 8,
#[cfg(feature = "3des")]
Self::DesEde3Cbc { .. } => 24,
}
}
/// Get the [`ObjectIdentifier`] (a.k.a OID) for this algorithm.
pub fn oid(&self) -> ObjectIdentifier {
match self {
Self::Aes128Cbc { .. } => AES_128_CBC_OID,
Self::Aes192Cbc { .. } => AES_192_CBC_OID,
Self::Aes256Cbc { .. } => AES_256_CBC_OID,
#[cfg(feature = "des-insecure")]
Self::DesCbc { .. } => DES_CBC_OID,
#[cfg(feature = "3des")]
Self::DesEde3Cbc { .. } => DES_EDE3_CBC_OID,
}
}
/// Convenience function to turn the OID (see [`oid`](Self::oid))
/// of this [`EncryptionScheme`] into error case
/// [`Error::AlgorithmParametersInvalid`]
pub fn to_alg_params_invalid(&self) -> Error {
Error::AlgorithmParametersInvalid { oid: self.oid() }
}
}
impl<'a> Decode<'a> for EncryptionScheme<'a> {
fn decode<R: Reader<'a>>(reader: &mut R) -> der::Result<Self> {
AlgorithmIdentifierRef::decode(reader).and_then(TryInto::try_into)
}
}
impl<'a> TryFrom<AlgorithmIdentifierRef<'a>> for EncryptionScheme<'a> {
type Error = der::Error;
fn try_from(alg: AlgorithmIdentifierRef<'a>) -> der::Result<Self> {
// TODO(tarcieri): support for non-AES algorithms?
let iv = match alg.parameters {
Some(params) => params.decode_as::<OctetStringRef<'a>>()?.as_bytes(),
None => return Err(Tag::OctetString.value_error()),
};
match alg.oid {
AES_128_CBC_OID => Ok(Self::Aes128Cbc {
iv: iv
.try_into()
.map_err(|_| der::Tag::OctetString.value_error())?,
}),
AES_192_CBC_OID => Ok(Self::Aes192Cbc {
iv: iv
.try_into()
.map_err(|_| der::Tag::OctetString.value_error())?,
}),
AES_256_CBC_OID => Ok(Self::Aes256Cbc {
iv: iv
.try_into()
.map_err(|_| der::Tag::OctetString.value_error())?,
}),
#[cfg(feature = "des-insecure")]
DES_CBC_OID => Ok(Self::DesCbc {
iv: iv[0..DES_BLOCK_SIZE]
.try_into()
.map_err(|_| der::Tag::OctetString.value_error())?,
}),
#[cfg(feature = "3des")]
DES_EDE3_CBC_OID => Ok(Self::DesEde3Cbc {
iv: iv[0..DES_BLOCK_SIZE]
.try_into()
.map_err(|_| der::Tag::OctetString.value_error())?,
}),
oid => Err(ErrorKind::OidUnknown { oid }.into()),
}
}
}
impl<'a> TryFrom<EncryptionScheme<'a>> for AlgorithmIdentifierRef<'a> {
type Error = der::Error;
fn try_from(scheme: EncryptionScheme<'a>) -> der::Result<Self> {
let parameters = OctetStringRef::new(match scheme {
EncryptionScheme::Aes128Cbc { iv } => iv,
EncryptionScheme::Aes192Cbc { iv } => iv,
EncryptionScheme::Aes256Cbc { iv } => iv,
#[cfg(feature = "des-insecure")]
EncryptionScheme::DesCbc { iv } => iv,
#[cfg(feature = "3des")]
EncryptionScheme::DesEde3Cbc { iv } => iv,
})?;
Ok(AlgorithmIdentifierRef {
oid: scheme.oid(),
parameters: Some(parameters.into()),
})
}
}
impl<'a> Encode for EncryptionScheme<'a> {
fn encoded_len(&self) -> der::Result<Length> {
AlgorithmIdentifierRef::try_from(*self)?.encoded_len()
}
fn encode(&self, writer: &mut impl Writer) -> der::Result<()> {
AlgorithmIdentifierRef::try_from(*self)?.encode(writer)
}
}

205
vendor/pkcs5/src/pbes2/encryption.rs vendored Normal file
View File

@@ -0,0 +1,205 @@
//! PBES2 encryption.
use super::{EncryptionScheme, Kdf, Parameters, Pbkdf2Params, Pbkdf2Prf, ScryptParams};
use crate::{Error, Result};
use cbc::cipher::{
block_padding::Pkcs7, BlockCipher, BlockDecryptMut, BlockEncryptMut, KeyInit, KeyIvInit,
};
use pbkdf2::{
hmac::digest::{
block_buffer::Eager,
core_api::{BlockSizeUser, BufferKindUser, CoreProxy, FixedOutputCore, UpdateCore},
generic_array::typenum::{IsLess, Le, NonZero, U256},
HashMarker,
},
pbkdf2_hmac,
};
use scrypt::scrypt;
/// Maximum size of a derived encryption key
const MAX_KEY_LEN: usize = 32;
fn cbc_encrypt<'a, C: BlockEncryptMut + BlockCipher + KeyInit>(
es: EncryptionScheme<'_>,
key: EncryptionKey,
iv: &[u8],
buffer: &'a mut [u8],
pos: usize,
) -> Result<&'a [u8]> {
cbc::Encryptor::<C>::new_from_slices(key.as_slice(), iv)
.map_err(|_| es.to_alg_params_invalid())?
.encrypt_padded_mut::<Pkcs7>(buffer, pos)
.map_err(|_| Error::EncryptFailed)
}
fn cbc_decrypt<'a, C: BlockDecryptMut + BlockCipher + KeyInit>(
es: EncryptionScheme<'_>,
key: EncryptionKey,
iv: &[u8],
buffer: &'a mut [u8],
) -> Result<&'a [u8]> {
cbc::Decryptor::<C>::new_from_slices(key.as_slice(), iv)
.map_err(|_| es.to_alg_params_invalid())?
.decrypt_padded_mut::<Pkcs7>(buffer)
.map_err(|_| Error::EncryptFailed)
}
pub fn encrypt_in_place<'b>(
params: &Parameters<'_>,
password: impl AsRef<[u8]>,
buf: &'b mut [u8],
pos: usize,
) -> Result<&'b [u8]> {
let es = params.encryption;
let key_size = es.key_size();
if key_size > MAX_KEY_LEN {
return Err(es.to_alg_params_invalid());
}
let key = EncryptionKey::derive_from_password(password.as_ref(), &params.kdf, key_size)?;
match es {
EncryptionScheme::Aes128Cbc { iv } => cbc_encrypt::<aes::Aes128Enc>(es, key, iv, buf, pos),
EncryptionScheme::Aes192Cbc { iv } => cbc_encrypt::<aes::Aes192Enc>(es, key, iv, buf, pos),
EncryptionScheme::Aes256Cbc { iv } => cbc_encrypt::<aes::Aes256Enc>(es, key, iv, buf, pos),
#[cfg(feature = "3des")]
EncryptionScheme::DesEde3Cbc { iv } => cbc_encrypt::<des::TdesEde3>(es, key, iv, buf, pos),
#[cfg(feature = "des-insecure")]
EncryptionScheme::DesCbc { .. } => Err(Error::UnsupportedAlgorithm {
oid: super::DES_CBC_OID,
}),
}
}
/// Decrypt a message encrypted with PBES2-based key derivation
pub fn decrypt_in_place<'a>(
params: &Parameters<'_>,
password: impl AsRef<[u8]>,
buf: &'a mut [u8],
) -> Result<&'a [u8]> {
let es = params.encryption;
let key = EncryptionKey::derive_from_password(password.as_ref(), &params.kdf, es.key_size())?;
match es {
EncryptionScheme::Aes128Cbc { iv } => cbc_decrypt::<aes::Aes128Dec>(es, key, iv, buf),
EncryptionScheme::Aes192Cbc { iv } => cbc_decrypt::<aes::Aes192Dec>(es, key, iv, buf),
EncryptionScheme::Aes256Cbc { iv } => cbc_decrypt::<aes::Aes256Dec>(es, key, iv, buf),
#[cfg(feature = "3des")]
EncryptionScheme::DesEde3Cbc { iv } => cbc_decrypt::<des::TdesEde3>(es, key, iv, buf),
#[cfg(feature = "des-insecure")]
EncryptionScheme::DesCbc { iv } => cbc_decrypt::<des::Des>(es, key, iv, buf),
}
}
/// Encryption key as derived by PBKDF2
// TODO(tarcieri): zeroize?
struct EncryptionKey {
buffer: [u8; MAX_KEY_LEN],
length: usize,
}
impl EncryptionKey {
/// Derive an encryption key using the supplied PBKDF parameters.
pub fn derive_from_password(password: &[u8], kdf: &Kdf<'_>, key_size: usize) -> Result<Self> {
// if the kdf params defined a key length, ensure it matches the required key size
if let Some(len) = kdf.key_length() {
if key_size != len.into() {
return Err(kdf.to_alg_params_invalid());
}
}
match kdf {
Kdf::Pbkdf2(pbkdf2_params) => {
let key = match pbkdf2_params.prf {
#[cfg(feature = "sha1-insecure")]
Pbkdf2Prf::HmacWithSha1 => EncryptionKey::derive_with_pbkdf2::<sha1::Sha1>(
password,
pbkdf2_params,
key_size,
),
#[cfg(not(feature = "sha1-insecure"))]
Pbkdf2Prf::HmacWithSha1 => {
return Err(Error::UnsupportedAlgorithm {
oid: super::HMAC_WITH_SHA1_OID,
})
}
Pbkdf2Prf::HmacWithSha224 => EncryptionKey::derive_with_pbkdf2::<sha2::Sha224>(
password,
pbkdf2_params,
key_size,
),
Pbkdf2Prf::HmacWithSha256 => EncryptionKey::derive_with_pbkdf2::<sha2::Sha256>(
password,
pbkdf2_params,
key_size,
),
Pbkdf2Prf::HmacWithSha384 => EncryptionKey::derive_with_pbkdf2::<sha2::Sha384>(
password,
pbkdf2_params,
key_size,
),
Pbkdf2Prf::HmacWithSha512 => EncryptionKey::derive_with_pbkdf2::<sha2::Sha512>(
password,
pbkdf2_params,
key_size,
),
};
Ok(key)
}
Kdf::Scrypt(scrypt_params) => {
EncryptionKey::derive_with_scrypt(password, scrypt_params, key_size)
}
}
}
/// Derive key using PBKDF2.
fn derive_with_pbkdf2<D>(password: &[u8], params: &Pbkdf2Params<'_>, length: usize) -> Self
where
D: CoreProxy,
D::Core: Sync
+ HashMarker
+ UpdateCore
+ FixedOutputCore
+ BufferKindUser<BufferKind = Eager>
+ Default
+ Clone,
<D::Core as BlockSizeUser>::BlockSize: IsLess<U256>,
Le<<D::Core as BlockSizeUser>::BlockSize, U256>: NonZero,
{
let mut buffer = [0u8; MAX_KEY_LEN];
pbkdf2_hmac::<D>(
password,
params.salt,
params.iteration_count,
&mut buffer[..length],
);
Self { buffer, length }
}
/// Derive key using scrypt.
fn derive_with_scrypt(
password: &[u8],
params: &ScryptParams<'_>,
length: usize,
) -> Result<Self> {
let mut buffer = [0u8; MAX_KEY_LEN];
scrypt(
password,
params.salt,
&params.try_into()?,
&mut buffer[..length],
)
.map_err(|_| Error::AlgorithmParametersInvalid {
oid: super::SCRYPT_OID,
})?;
Ok(Self { buffer, length })
}
/// Get the key material as a slice
fn as_slice(&self) -> &[u8] {
&self.buffer[..self.length]
}
}

490
vendor/pkcs5/src/pbes2/kdf.rs vendored Normal file
View File

@@ -0,0 +1,490 @@
//! Key derivation functions.
use crate::{AlgorithmIdentifierRef, Error, Result};
use der::{
asn1::{AnyRef, ObjectIdentifier, OctetStringRef},
Decode, DecodeValue, Encode, EncodeValue, ErrorKind, Length, Reader, Sequence, Tag, Tagged,
Writer,
};
/// Password-Based Key Derivation Function (PBKDF2) OID.
pub const PBKDF2_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.1.5.12");
/// HMAC-SHA1 (for use with PBKDF2)
pub const HMAC_WITH_SHA1_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.2.7");
/// HMAC-SHA-224 (for use with PBKDF2)
pub const HMAC_WITH_SHA224_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.2.840.113549.2.8");
/// HMAC-SHA-256 (for use with PBKDF2)
pub const HMAC_WITH_SHA256_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.2.840.113549.2.9");
/// HMAC-SHA-384 (for use with PBKDF2)
pub const HMAC_WITH_SHA384_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.2.840.113549.2.10");
/// HMAC-SHA-512 (for use with PBKDF2)
pub const HMAC_WITH_SHA512_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.2.840.113549.2.11");
/// `id-scrypt` ([RFC 7914])
///
/// [RFC 7914]: https://datatracker.ietf.org/doc/html/rfc7914#section-7
pub const SCRYPT_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.6.1.4.1.11591.4.11");
/// Type used for expressing scrypt cost
type ScryptCost = u64;
/// Password-based key derivation function.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Kdf<'a> {
/// Password-Based Key Derivation Function 2 (PBKDF2).
Pbkdf2(Pbkdf2Params<'a>),
/// scrypt sequential memory-hard password hashing function.
Scrypt(ScryptParams<'a>),
}
impl<'a> Kdf<'a> {
/// Get derived key length in bytes, if defined.
// TODO(tarcieri): rename to `key_size` to match `EncryptionScheme::key_size`?
pub fn key_length(&self) -> Option<u16> {
match self {
Self::Pbkdf2(params) => params.key_length,
Self::Scrypt(params) => params.key_length,
}
}
/// Get the [`ObjectIdentifier`] (a.k.a OID) for this algorithm.
pub fn oid(&self) -> ObjectIdentifier {
match self {
Self::Pbkdf2(_) => PBKDF2_OID,
Self::Scrypt(_) => SCRYPT_OID,
}
}
/// Get [`Pbkdf2Params`] if it is the selected algorithm.
pub fn pbkdf2(&self) -> Option<&Pbkdf2Params<'a>> {
match self {
Self::Pbkdf2(params) => Some(params),
_ => None,
}
}
/// Get [`ScryptParams`] if it is the selected algorithm.
pub fn scrypt(&self) -> Option<&ScryptParams<'a>> {
match self {
Self::Scrypt(params) => Some(params),
_ => None,
}
}
/// Is the selected KDF PBKDF2?
pub fn is_pbkdf2(&self) -> bool {
self.pbkdf2().is_some()
}
/// Is the selected KDF scrypt?
pub fn is_scrypt(&self) -> bool {
self.scrypt().is_some()
}
/// Convenience function to turn the OID (see [`oid`](Self::oid))
/// of this [`Kdf`] into error case [`Error::AlgorithmParametersInvalid`]
pub fn to_alg_params_invalid(&self) -> Error {
Error::AlgorithmParametersInvalid { oid: self.oid() }
}
}
impl<'a> DecodeValue<'a> for Kdf<'a> {
fn decode_value<R: Reader<'a>>(reader: &mut R, header: der::Header) -> der::Result<Self> {
AlgorithmIdentifierRef::decode_value(reader, header)?.try_into()
}
}
impl EncodeValue for Kdf<'_> {
fn value_len(&self) -> der::Result<Length> {
self.oid().encoded_len()?
+ match self {
Self::Pbkdf2(params) => params.encoded_len()?,
Self::Scrypt(params) => params.encoded_len()?,
}
}
fn encode_value(&self, writer: &mut impl Writer) -> der::Result<()> {
self.oid().encode(writer)?;
match self {
Self::Pbkdf2(params) => params.encode(writer)?,
Self::Scrypt(params) => params.encode(writer)?,
}
Ok(())
}
}
impl<'a> Sequence<'a> for Kdf<'a> {}
impl<'a> From<Pbkdf2Params<'a>> for Kdf<'a> {
fn from(params: Pbkdf2Params<'a>) -> Self {
Kdf::Pbkdf2(params)
}
}
impl<'a> From<ScryptParams<'a>> for Kdf<'a> {
fn from(params: ScryptParams<'a>) -> Self {
Kdf::Scrypt(params)
}
}
impl<'a> TryFrom<AlgorithmIdentifierRef<'a>> for Kdf<'a> {
type Error = der::Error;
fn try_from(alg: AlgorithmIdentifierRef<'a>) -> der::Result<Self> {
if let Some(params) = alg.parameters {
match alg.oid {
PBKDF2_OID => params.try_into().map(Self::Pbkdf2),
SCRYPT_OID => params.try_into().map(Self::Scrypt),
oid => Err(ErrorKind::OidUnknown { oid }.into()),
}
} else {
Err(Tag::OctetString.value_error())
}
}
}
/// Password-Based Key Derivation Scheme 2 parameters as defined in
/// [RFC 8018 Appendix A.2].
///
/// ```text
/// PBKDF2-params ::= SEQUENCE {
/// salt CHOICE {
/// specified OCTET STRING,
/// otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}}
/// },
/// iterationCount INTEGER (1..MAX),
/// keyLength INTEGER (1..MAX) OPTIONAL,
/// prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT
/// algid-hmacWithSHA1 }
/// ```
///
/// [RFC 8018 Appendix A.2]: https://tools.ietf.org/html/rfc8018#appendix-A.2
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Pbkdf2Params<'a> {
/// PBKDF2 salt
// TODO(tarcieri): support `CHOICE` with `otherSource`
pub salt: &'a [u8],
/// PBKDF2 iteration count
pub iteration_count: u32,
/// PBKDF2 output length
pub key_length: Option<u16>,
/// Pseudo-random function to use with PBKDF2
pub prf: Pbkdf2Prf,
}
impl<'a> Pbkdf2Params<'a> {
/// Implementation defined maximum iteration count of 100,000,000.
///
/// > For especially critical keys, or
/// > for very powerful systems or systems where user-perceived
/// > performance is not critical, an iteration count of 10,000,000 may
/// > be appropriate.
///
/// See [RFC 8018, §4.2](https://datatracker.ietf.org/doc/html/rfc8018#section-4.2)
/// and [RFC 8018, §A.2](https://datatracker.ietf.org/doc/html/rfc8018#appendix-A.2)
pub const MAX_ITERATION_COUNT: u32 = 100_000_000;
const INVALID_ERR: Error = Error::AlgorithmParametersInvalid { oid: PBKDF2_OID };
/// Initialize PBKDF2-SHA256 with the given iteration count and salt
pub fn hmac_with_sha256(iteration_count: u32, salt: &'a [u8]) -> Result<Self> {
if iteration_count > Self::MAX_ITERATION_COUNT {
return Err(Self::INVALID_ERR);
}
Ok(Self {
salt,
iteration_count,
key_length: None,
prf: Pbkdf2Prf::HmacWithSha256,
})
}
}
impl<'a> DecodeValue<'a> for Pbkdf2Params<'a> {
fn decode_value<R: Reader<'a>>(reader: &mut R, header: der::Header) -> der::Result<Self> {
AnyRef::decode_value(reader, header)?.try_into()
}
}
impl EncodeValue for Pbkdf2Params<'_> {
fn value_len(&self) -> der::Result<Length> {
let len = OctetStringRef::new(self.salt)?.encoded_len()?
+ self.iteration_count.encoded_len()?
+ self.key_length.encoded_len()?;
if self.prf == Pbkdf2Prf::default() {
len
} else {
len + self.prf.encoded_len()?
}
}
fn encode_value(&self, writer: &mut impl Writer) -> der::Result<()> {
OctetStringRef::new(self.salt)?.encode(writer)?;
self.iteration_count.encode(writer)?;
self.key_length.encode(writer)?;
if self.prf == Pbkdf2Prf::default() {
Ok(())
} else {
self.prf.encode(writer)
}
}
}
impl<'a> Sequence<'a> for Pbkdf2Params<'a> {}
impl<'a> TryFrom<AnyRef<'a>> for Pbkdf2Params<'a> {
type Error = der::Error;
fn try_from(any: AnyRef<'a>) -> der::Result<Self> {
any.sequence(|reader| {
// TODO(tarcieri): support salt `CHOICE` w\ `AlgorithmIdentifier`
Ok(Self {
salt: OctetStringRef::decode(reader)?.as_bytes(),
iteration_count: reader.decode()?,
key_length: reader.decode()?,
prf: Option::<AlgorithmIdentifierRef<'_>>::decode(reader)?
.map(TryInto::try_into)
.transpose()?
.unwrap_or_default(),
})
})
}
}
/// Pseudo-random function used by PBKDF2.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Pbkdf2Prf {
/// HMAC with SHA1
HmacWithSha1,
/// HMAC with SHA-224
HmacWithSha224,
/// HMAC with SHA-256
HmacWithSha256,
/// HMAC with SHA-384
HmacWithSha384,
/// HMAC with SHA-512
HmacWithSha512,
}
impl Pbkdf2Prf {
/// Get the [`ObjectIdentifier`] (a.k.a OID) for this algorithm.
pub fn oid(self) -> ObjectIdentifier {
match self {
Self::HmacWithSha1 => HMAC_WITH_SHA1_OID,
Self::HmacWithSha224 => HMAC_WITH_SHA224_OID,
Self::HmacWithSha256 => HMAC_WITH_SHA256_OID,
Self::HmacWithSha384 => HMAC_WITH_SHA384_OID,
Self::HmacWithSha512 => HMAC_WITH_SHA512_OID,
}
}
}
/// Default PRF as specified in RFC 8018 Appendix A.2:
///
/// ```text
/// prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1
/// ```
///
/// Note that modern usage should avoid the use of SHA-1, despite it being
/// the "default" here.
impl Default for Pbkdf2Prf {
fn default() -> Self {
Self::HmacWithSha1
}
}
impl<'a> TryFrom<AlgorithmIdentifierRef<'a>> for Pbkdf2Prf {
type Error = der::Error;
fn try_from(alg: AlgorithmIdentifierRef<'a>) -> der::Result<Self> {
if let Some(params) = alg.parameters {
// TODO(tarcieri): support non-NULL parameters?
if !params.is_null() {
return Err(params.tag().value_error());
}
} else {
// TODO(tarcieri): support OPTIONAL parameters?
return Err(Tag::Null.value_error());
}
match alg.oid {
HMAC_WITH_SHA1_OID => Ok(Self::HmacWithSha1),
HMAC_WITH_SHA224_OID => Ok(Self::HmacWithSha224),
HMAC_WITH_SHA256_OID => Ok(Self::HmacWithSha256),
HMAC_WITH_SHA384_OID => Ok(Self::HmacWithSha384),
HMAC_WITH_SHA512_OID => Ok(Self::HmacWithSha512),
oid => Err(ErrorKind::OidUnknown { oid }.into()),
}
}
}
impl<'a> From<Pbkdf2Prf> for AlgorithmIdentifierRef<'a> {
fn from(prf: Pbkdf2Prf) -> Self {
// TODO(tarcieri): support non-NULL parameters?
let parameters = der::asn1::Null;
AlgorithmIdentifierRef {
oid: prf.oid(),
parameters: Some(parameters.into()),
}
}
}
impl Encode for Pbkdf2Prf {
fn encoded_len(&self) -> der::Result<Length> {
AlgorithmIdentifierRef::try_from(*self)?.encoded_len()
}
fn encode(&self, writer: &mut impl Writer) -> der::Result<()> {
AlgorithmIdentifierRef::try_from(*self)?.encode(writer)
}
}
/// scrypt parameters as defined in [RFC 7914 Section 7.1].
///
/// ```text
/// scrypt-params ::= SEQUENCE {
/// salt OCTET STRING,
/// costParameter INTEGER (1..MAX),
/// blockSize INTEGER (1..MAX),
/// parallelizationParameter INTEGER (1..MAX),
/// keyLength INTEGER (1..MAX) OPTIONAL
/// }
/// ```
///
/// [RFC 7914 Section 7.1]: https://datatracker.ietf.org/doc/html/rfc7914#section-7.1
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct ScryptParams<'a> {
/// scrypt salt
pub salt: &'a [u8],
/// CPU/Memory cost parameter `N`.
pub cost_parameter: ScryptCost,
/// Block size parameter `r`.
pub block_size: u16,
/// Parallelization parameter `p`.
pub parallelization: u16,
/// PBKDF2 output length
pub key_length: Option<u16>,
}
impl<'a> ScryptParams<'a> {
#[cfg(feature = "pbes2")]
const INVALID_ERR: Error = Error::AlgorithmParametersInvalid { oid: SCRYPT_OID };
/// Get the [`ScryptParams`] for the provided upstream [`scrypt::Params`]
/// and a provided salt string.
// TODO(tarcieri): encapsulate `scrypt::Params`?
#[cfg(feature = "pbes2")]
pub fn from_params_and_salt(params: scrypt::Params, salt: &'a [u8]) -> Result<Self> {
Ok(Self {
salt,
cost_parameter: 1 << params.log_n(),
block_size: params.r().try_into().map_err(|_| Self::INVALID_ERR)?,
parallelization: params.p().try_into().map_err(|_| Self::INVALID_ERR)?,
key_length: None,
})
}
}
impl<'a> DecodeValue<'a> for ScryptParams<'a> {
fn decode_value<R: Reader<'a>>(reader: &mut R, header: der::Header) -> der::Result<Self> {
AnyRef::decode_value(reader, header)?.try_into()
}
}
impl EncodeValue for ScryptParams<'_> {
fn value_len(&self) -> der::Result<Length> {
OctetStringRef::new(self.salt)?.encoded_len()?
+ self.cost_parameter.encoded_len()?
+ self.block_size.encoded_len()?
+ self.parallelization.encoded_len()?
+ self.key_length.encoded_len()?
}
fn encode_value(&self, writer: &mut impl Writer) -> der::Result<()> {
OctetStringRef::new(self.salt)?.encode(writer)?;
self.cost_parameter.encode(writer)?;
self.block_size.encode(writer)?;
self.parallelization.encode(writer)?;
self.key_length.encode(writer)?;
Ok(())
}
}
impl<'a> Sequence<'a> for ScryptParams<'a> {}
impl<'a> TryFrom<AnyRef<'a>> for ScryptParams<'a> {
type Error = der::Error;
fn try_from(any: AnyRef<'a>) -> der::Result<Self> {
any.sequence(|reader| {
Ok(Self {
salt: OctetStringRef::decode(reader)?.as_bytes(),
cost_parameter: reader.decode()?,
block_size: reader.decode()?,
parallelization: reader.decode()?,
key_length: reader.decode()?,
})
})
}
}
#[cfg(feature = "pbes2")]
impl<'a> TryFrom<ScryptParams<'a>> for scrypt::Params {
type Error = Error;
fn try_from(params: ScryptParams<'a>) -> Result<scrypt::Params> {
scrypt::Params::try_from(&params)
}
}
#[cfg(feature = "pbes2")]
impl<'a> TryFrom<&ScryptParams<'a>> for scrypt::Params {
type Error = Error;
fn try_from(params: &ScryptParams<'a>) -> Result<scrypt::Params> {
let n = params.cost_parameter;
// Compute log2 and verify its correctness
let log_n = ((8 * core::mem::size_of::<ScryptCost>() as u32) - n.leading_zeros() - 1) as u8;
if 1 << log_n != n {
return Err(ScryptParams::INVALID_ERR);
}
scrypt::Params::new(
log_n,
params.block_size.into(),
params.parallelization.into(),
scrypt::Params::RECOMMENDED_LEN,
)
.map_err(|_| ScryptParams::INVALID_ERR)
}
}

Binary file not shown.

View File

View File

@@ -0,0 +1 @@
{"name":"pkcs5","vers":"0.7.1","deps":[{"name":"aes","req":"^0.8.2","features":[],"optional":true,"default_features":false,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"cbc","req":"^0.1.2","features":[],"optional":true,"default_features":true,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"der","req":"^0.7","features":["oid"],"optional":false,"default_features":true,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"des","req":"^0.8.1","features":[],"optional":true,"default_features":false,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"pbkdf2","req":"^0.12.1","features":[],"optional":true,"default_features":false,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"scrypt","req":"^0.11","features":[],"optional":true,"default_features":false,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"sha1","req":"^0.10.1","features":[],"optional":true,"default_features":false,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"sha2","req":"^0.10.2","features":[],"optional":true,"default_features":false,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"spki","req":"^0.7","features":[],"optional":false,"default_features":true,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"hex-literal","req":"^0.3","features":[],"optional":false,"default_features":true,"target":null,"kind":"dev","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false}],"features":{"3des":["dep:des","pbes2"],"alloc":[],"des-insecure":["dep:des","pbes2"],"pbes2":["dep:aes","dep:cbc","dep:pbkdf2","dep:scrypt","dep:sha2"],"sha1-insecure":["dep:sha1","pbes2"]},"features2":null,"cksum":"750aff0698e85ca8a34808b92b2406ec8e86a33375212b50bf79fb7b1f6e3aad","yanked":null,"links":null,"rust_version":null,"v":2}

Binary file not shown.

129
vendor/pkcs5/tests/encryption.rs vendored Normal file
View File

@@ -0,0 +1,129 @@
//! PBES2 encryption tests
#![cfg(feature = "pbes2")]
use hex_literal::hex;
/// PBES2 + PBKDF2-SHA256 + AES-256-CBC `AlgorithmIdentifier` example.
///
/// Generated by OpenSSL and extracted from the `pkcs8` crate's
/// `tests/examples/ed25519-encpriv-aes256-pbkdf2-sha256.der` test vector.
const PBES2_PBKDF2_SHA256_AES256CBC_ALG_ID: &[u8] = &hex!(
"305706092a864886f70d01050d304a302906092a864886f70d01050c301c0408
79d982e70df91a8802020800300c06082a864886f70d02090500301d06096086
4801650304012a0410b2d02d78b2efd9dff694cf8e0af40925"
);
/// PBES2 + scrypt + AES-256-CBC `AlgorithmIdentifier` example.
///
/// Generated by OpenSSL and extracted from the `pkcs8` crate's
/// `ed25519-encpriv-aes256-scrypt.der` test vector.
const PBES2_SCRYPT_AES256CBC_ALG_ID: &[u8] = &hex!(
"304f06092a864886f70d01050d3042302106092b06010401da47040b30140408
e6211e2348ad69e002024000020108020101301d060960864801650304012a041
09bd0a6251f2254f9fd5963887c27cf01"
);
/// Plaintext of Ed25519 PKCS#8 private key.
///
/// This is the hex-encoded contents of `ed25519-priv.der` from
/// `pkcs8/tests/examples`.
const ED25519_PKCS8_KEY_PLAINTEXT: &[u8] = &hex!(
"302e020100300506032b65700422042017ed9c73e9db649ec189a612831c5fc5
70238207c1aa9dfbd2c53e3ff5e5ea85"
);
/// Ciphertext of Ed25519 PKCS#8 private key when encrypted using
/// PBKDF2-SHA256 as the KDF.
///
/// Extracted with:
/// $ openssl asn1parse -inform der -in pkcs8/tests/examples/ed25519-encpriv-aes256-pbkdf2-sha256.der
const ED25519_PKCS8_KEY_CIPHERTEXT_PBKDF2_SHA256: &[u8] = &hex!(
"D0CD6C770F4BB87176422305C17401809E226674CE74185D221BFDAA95069890
C8882FCE02B05D41BCBF54B035595BCD4154B32593708469B86AACF8815A7B2B"
);
/// Ciphertext of Ed25519 PKCS#8 private key when encrypted using
/// scrypt as the KDF.
///
/// Extracted with:
/// $ openssl asn1parse -inform der -in pkcs8/tests/examples/ed25519-encpriv-aes256-scrypt.der
const ED25519_PKCS8_KEY_CIPHERTEXT_SCRYPT: &[u8] = &hex!(
"CC62BA773C0F495FAB3668E4FCEFCDB08E78A0EE15E0A15013F62ABE08DAA742
065EEB366D6E6C98CC3B0E7E69BDC861C88AFEB8F03DBA1E2C6D99D06D17360C"
);
/// PBES2 + DES-EDE3-CBC + PBKDF-SHA2 `AlgorithmIdentifier` example.
///
/// Generated by OpenSSL and extracted from the `pkcs8` crate's
/// `ed25519-encpriv-des3-pbkdf-sha256.der` test vector.
#[cfg(feature = "3des")]
const PBES2_PBKDF2_SHA256_DESEDE3CBC_ALG_ID: &[u8] = &hex!(
"304e06092a864886f70d01050d 3041302906092a864886f70d01050c301c0408
32a0ae2e01bbe32902020800300c06082a864886f70d02090500301406 082a864
886f70d0307040897e8f53ab0aca359"
);
/// Ciphertext of Ed25519 PKCS8 private key encrypted with DES-EDE3-CBC
/// and PBKDF2-SHA265
#[cfg(feature = "3des")]
const ED25519_PKCS8_KEY_CIPHERTEXT_DESEDE3CBC: &[u8] = &hex!(
"2D8E4CBA271A1D33659426883BB7B405D5CFFC64AEE868AB0B5774B88C12056FE
C6CAE1D9A12DDE51140DFD799D825ACD592172763866F93"
);
/// PBES2 + DES-CBC + PBKDF-SHA2 `AlgorithmIdentifier` example.
///
/// Generated by OpenSSL and extracted from the `pkcs8` crate's
/// `ed25519-encpriv-des-pbkdf-sha256.der` test vector.
#[cfg(feature = "des-insecure")]
const PBES2_PBKDF2_SHA256_DESCBC_ALG_ID: &[u8] = &hex!(
"304b06092a864886f70d01050d303e302906092a864886f70d01050c301c04080
9e7edfbd9f21e2b02020800300c06082a864886f70d02090500301106052b0e030
2070408f4aaf206a18de7ad"
);
/// Ciphertext of Ed25519 PKCS8 private key encrypted with DES-EDE3-CBC
/// and PBKDF2-SHA265
#[cfg(feature = "des-insecure")]
const ED25519_PKCS8_KEY_CIPHERTEXT_DESCBC: &[u8] = &hex!(
"FE9BB48DBEB61112A44CD9A20870CAEA642B4D3110AE7783022B4E3A84CC9F7
93E4E3893840181FBC63D75297B416A0B96CB7F9AB45CEABA"
);
/// Password used to encrypt the keys.
const PASSWORD: &[u8] = b"hunter42"; // Bad password; don't actually use outside tests!
#[test]
fn decrypt_pbes2_pbkdf2_sha256_aes256cbc() {
let scheme = pkcs5::EncryptionScheme::try_from(PBES2_PBKDF2_SHA256_AES256CBC_ALG_ID).unwrap();
let mut buffer = Vec::from(ED25519_PKCS8_KEY_CIPHERTEXT_PBKDF2_SHA256);
let plaintext = scheme.decrypt_in_place(PASSWORD, &mut buffer).unwrap();
assert_eq!(plaintext, ED25519_PKCS8_KEY_PLAINTEXT);
}
#[test]
fn decrypt_pbes2_scrypt_aes256cbc() {
let scheme = pkcs5::EncryptionScheme::try_from(PBES2_SCRYPT_AES256CBC_ALG_ID).unwrap();
let mut buffer = Vec::from(ED25519_PKCS8_KEY_CIPHERTEXT_SCRYPT);
let plaintext = scheme.decrypt_in_place(PASSWORD, &mut buffer).unwrap();
assert_eq!(plaintext, ED25519_PKCS8_KEY_PLAINTEXT);
}
#[test]
#[cfg(feature = "3des")]
fn decrypt_pbes2_pbkdf2_sha256_desede3cbc() {
let scheme = pkcs5::EncryptionScheme::try_from(PBES2_PBKDF2_SHA256_DESEDE3CBC_ALG_ID).unwrap();
let mut buffer = Vec::from(ED25519_PKCS8_KEY_CIPHERTEXT_DESEDE3CBC);
let plaintext = scheme.decrypt_in_place(PASSWORD, &mut buffer).unwrap();
assert_eq!(plaintext, ED25519_PKCS8_KEY_PLAINTEXT);
}
#[test]
#[cfg(feature = "des-insecure")]
fn decrypt_pbes2_pbkdf2_sha256_descbc() {
let scheme = pkcs5::EncryptionScheme::try_from(PBES2_PBKDF2_SHA256_DESCBC_ALG_ID).unwrap();
let mut buffer = Vec::from(ED25519_PKCS8_KEY_CIPHERTEXT_DESCBC);
let plaintext = scheme.decrypt_in_place(PASSWORD, &mut buffer).unwrap();
assert_eq!(plaintext, ED25519_PKCS8_KEY_PLAINTEXT);
}

View File

@@ -0,0 +1,3 @@
0H *├H├В

0;0 *├H├В

View File

@@ -0,0 +1,2 @@
0H *├H├В


View File

@@ -0,0 +1,2 @@
0H *†H†÷


View File

@@ -0,0 +1,2 @@
ÞØ)<1F>wí‰6^’ç¥z#×oì4IÝÖüƒÍeÛ¿²Ã5eEY<45>ÍjñÑyqÂá
À[öw¼m€QH0©jÀƒ(,WX}Wñ!Õý<C395>ö<EFBFBD>âк ˆA‰±ŒT-“ÏX-{ãP˜ìã<qør¹®Èöðç”$õ

53
vendor/pkcs5/tests/examples/re-gen.sh vendored Executable file
View File

@@ -0,0 +1,53 @@
#!/usr/bin/env bash
# http://redsymbol.net/articles/unofficial-bash-strict-mode/
set -euo pipefail
IFS=$'\n\t'
password="hunter2"
passout="pass:${password}"
openssl genrsa -out rsa_sk.pkcs1.pem 1024
openssl pkcs8 -topk8 -in rsa_sk.pkcs1.pem -outform DER -out rsa_sk.pkcs8.der -nocrypt
gen_pkcs8 () {
local aes_mode="${1:?}"
local prf="${2:?}"
openssl pkcs8 \
-topk8 \
-in rsa_sk.pkcs1.pem \
-v2 "$aes_mode" \
-v2prf "$prf" \
-iter 10 \
-passout "$passout" \
-outform DER -out "rsa_sk_${aes_mode}_${prf}.pkcs8.der"
}
for aes_mode in "aes-128-cbc" "aes-192-cbc" "aes-256-cbc"
do
for prf in "hmacWithSHA1" "hmacWithSHA224" "hmacWithSHA256" "hmacWithSHA384" "hmacWithSHA512"
do
gen_pkcs8 "$aes_mode" "$prf"
done
done
extract () {
local aes_mode="${1:?}"
local prf="${2:?}"
local algid_len="${3:?}"
dd bs=1 skip=4 count="$algid_len" if="rsa_sk_${aes_mode}_${prf}.pkcs8.der" of="pbes2_${aes_mode}_${prf}_algid.der"
dd bs=1 skip="$(expr $algid_len + 8)" if="rsa_sk_${aes_mode}_${prf}.pkcs8.der" of="pbes2_${aes_mode}_${prf}_ciphertext.bin"
}
for aes_mode in "aes-128-cbc" "aes-192-cbc" "aes-256-cbc"
do
extract "$aes_mode" "hmacWithSHA1" 74
for prf in "hmacWithSHA224" "hmacWithSHA256" "hmacWithSHA384" "hmacWithSHA512"
do
extract "$aes_mode" "$prf" 88
done
done

View File

@@ -0,0 +1,15 @@
-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQC8kFIo73BV0oUpAzYB0yFQydoJX4XhJU89biicA133jJd8MkVE
DQrnFNsjckBB9yretNvJxIG30cBc6139Goowj0q7Ocwb32LONYYhuU4wG8zl8L8B
EaC1mi4J02OUChZ7JCw6W9nat69kMaEbOWZxSDkfybXBelh6OxUGdXd3cwIDAQAB
AoGAawDi/sPRVYJfekSOMz7iWvwQtNz2Fiub6dpHRTFL85xeomXMlK9qDnPxXw4I
lOZz92leiALxMaTfqlsOPQEAhU5XoA8jGwVSC2T6urfrSzQzKfLn4rKyEQCYIiIe
Q2b7ScxFUFxaOXxELK1AzGnTJ2NUCkk5+SdNSP8DzYeRwnECQQD7Bzca+7Qgff6l
y9mXj3sz4RAF1t8lGf/2dzGmRXwIq87O74s50jBl0tvdEg5RUj7bQ09XdRuMjBKp
1DOJS3U/AkEAwExkpLgT35HU0D1Y1zWlpERX8qGbLlBp/AlRgRuwFSPnmoFyVutV
ahgOH5KayVN55rwJRLH9jEhjrtjZyGxszQJAB4q69BuV2NgQO4j5W51a9T8QzSwc
fi/eydfg7P7vcA9BYmQ+CZmwDI8ePfEZ7wWKj+ngy17gWgOnV+ThO4HB3wJBAJM4
aTzqaNybCzC6Js/slHnkkOiC7QlSKzH3+Fw91Fr6+A+D1wPQe74T2Iw3cyV7MTKC
9x2OnyzNJvPvtRwKVmkCQGTiqQybnnZ4PSY6fIe5AnvcO9tK4BchySkOQ2Ws726G
zGcbmmz1ShDo7tPNUk4hcWUOJFbR6/1zDYJIzmACvL0=
-----END RSA PRIVATE KEY-----

Binary file not shown.

View File

@@ -0,0 +1,3 @@
0Î0H *†H†÷

0;0 *†H†÷

199
vendor/pkcs5/tests/pbes2.rs vendored Normal file
View File

@@ -0,0 +1,199 @@
//! Password-Based Encryption Scheme 2 tests
use der::Encode;
use hex_literal::hex;
use pkcs5::pbes2;
/// PBES2 + PBKDF2-SHA1 + AES-128-CBC `AlgorithmIdentifier` example.
///
/// Generated by OpenSSL and extracted from the `pkcs8` crate's
/// `tests/examples/ed25519-encpriv-aes128-pbkdf2-sha1.der` test vector.
const PBES2_PBKDF2_SHA1_AES128CBC_ALG_ID: &[u8] = &hex!(
"304906092a864886f70d01050d303c301b06092a864886f70d01050c300e0408
e8765e01e43b6bad02020800301d06096086480165030401020410223080a71b
cd2b9a256d876c924979d2"
);
/// PBES2 + PBKDF2-SHA256 + AES-256-CBC `AlgorithmIdentifier` example.
///
/// Generated by OpenSSL and extracted from the `pkcs8` crate's
/// `tests/examples/ed25519-encpriv-aes256-pbkdf2-sha256.der` test vector.
const PBES2_PBKDF2_SHA256_AES256CBC_ALG_ID: &[u8] = &hex!(
"305706092a864886f70d01050d304a302906092a864886f70d01050c301c0408
79d982e70df91a8802020800300c06082a864886f70d02090500301d06096086
4801650304012a0410b2d02d78b2efd9dff694cf8e0af40925"
);
/// PBES2 + scrypt + AES-256-CBC `AlgorithmIdentifier` example.
///
/// Generated by OpenSSL and extracted from the `pkcs8` crate's
/// `ed25519-encpriv-aes256-scrypt.der` test vector.
const PBES2_SCRYPT_AES256CBC_ALG_ID: &[u8] = &hex!(
"304f06092a864886f70d01050d3042302106092b06010401da47040b30140408
e6211e2348ad69e002024000020108020101301d060960864801650304012a041
09bd0a6251f2254f9fd5963887c27cf01"
);
/// PBES2 + DES-EDE3-CBC + PBKDF-SHA2 `AlgorithmIdentifier` example.
///
/// Generated by OpenSSL and extracted from the `pkcs8` crate's
/// `ed25519-encpriv-des3-pbkdf-sha256.der` test vector.
#[cfg(feature = "3des")]
const PBES2_PBKDF2_SHA256_DESEDE3CBC_ALG_ID: &[u8] = &hex!(
"304e06092a864886f70d01050d 3041302906092a864886f70d01050c301c0408
32a0ae2e01bbe32902020800300c06082a864886f70d02090500301406 082a864
886f70d0307040897e8f53ab0aca359"
);
/// PBES2 + DES-CBC + PBKDF-SHA2 `AlgorithmIdentifier` example.
///
/// Generated by OpenSSL and extracted from the `pkcs8` crate's
/// `ed25519-encpriv-des-pbkdf-sha256.der` test vector.
#[cfg(feature = "des-insecure")]
const PBES2_PBKDF2_SHA256_DESCBC_ALG_ID: &[u8] = &hex!(
"304b06092a864886f70d01050d303e302906092a864886f70d01050c301c04080
9e7edfbd9f21e2b02020800300c06082a864886f70d02090500301106052b0e030
2070408f4aaf206a18de7ad"
);
/// Decoding test for PBES2 + PBKDF2-SHA1 + AES-128-CBC `AlgorithmIdentifier`
#[test]
fn decode_pbes2_pbkdf2_sha1_aes128cbc() {
let scheme = pkcs5::EncryptionScheme::try_from(PBES2_PBKDF2_SHA1_AES128CBC_ALG_ID).unwrap();
let params = scheme.pbes2().unwrap();
let pbkdf2_params = params.kdf.pbkdf2().unwrap();
assert_eq!(pbkdf2_params.salt, &hex!("e8765e01e43b6bad"));
assert_eq!(pbkdf2_params.iteration_count, 2048);
assert_eq!(pbkdf2_params.key_length, None);
assert_eq!(pbkdf2_params.prf, pbes2::Pbkdf2Prf::HmacWithSha1);
match params.encryption {
pbes2::EncryptionScheme::Aes128Cbc { iv } => {
assert_eq!(iv, &hex!("223080a71bcd2b9a256d876c924979d2"));
}
other => panic!("unexpected encryption scheme: {:?}", other),
}
}
/// Decoding test for PBES2 + PBKDF2-SHA256 + AES-256-CBC `AlgorithmIdentifier`
#[test]
fn decode_pbes2_pbkdf2_sha256_aes256cbc() {
let scheme = pkcs5::EncryptionScheme::try_from(PBES2_PBKDF2_SHA256_AES256CBC_ALG_ID).unwrap();
let params = scheme.pbes2().unwrap();
let pbkdf2_params = params.kdf.pbkdf2().unwrap();
assert_eq!(pbkdf2_params.salt, &hex!("79d982e70df91a88"));
assert_eq!(pbkdf2_params.iteration_count, 2048);
assert_eq!(pbkdf2_params.key_length, None);
assert_eq!(pbkdf2_params.prf, pbes2::Pbkdf2Prf::HmacWithSha256);
match params.encryption {
pbes2::EncryptionScheme::Aes256Cbc { iv } => {
assert_eq!(iv, &hex!("b2d02d78b2efd9dff694cf8e0af40925"));
}
other => panic!("unexpected encryption scheme: {:?}", other),
}
}
/// Decoding test for PBES2 + scrypt + AES-256-CBC `AlgorithmIdentifier`
#[test]
fn decode_pbes2_scrypt_aes256cbc() {
let scheme = pkcs5::EncryptionScheme::try_from(PBES2_SCRYPT_AES256CBC_ALG_ID).unwrap();
let params = scheme.pbes2().unwrap();
let scrypt_params = params.kdf.scrypt().unwrap();
assert_eq!(scrypt_params.salt, &hex!("E6211E2348AD69E0"));
assert_eq!(scrypt_params.cost_parameter, 16384);
assert_eq!(scrypt_params.block_size, 8);
assert_eq!(scrypt_params.parallelization, 1);
assert_eq!(scrypt_params.key_length, None);
match params.encryption {
pbes2::EncryptionScheme::Aes256Cbc { iv } => {
assert_eq!(iv, &hex!("9BD0A6251F2254F9FD5963887C27CF01"));
}
other => panic!("unexpected encryption scheme: {:?}", other),
}
}
/// Decoding test for PBES2 + PBKDF2-SHA256 + DES-EDE3-CBC `AlgorithmIdentifier`
#[cfg(feature = "3des")]
#[test]
fn decode_pbes2_pbkdf2_sha256_desede3cbc() {
let scheme = pkcs5::EncryptionScheme::try_from(PBES2_PBKDF2_SHA256_DESEDE3CBC_ALG_ID).unwrap();
let params = scheme.pbes2().unwrap();
let pbkdf2_params = params.kdf.pbkdf2().unwrap();
assert_eq!(pbkdf2_params.salt, &hex!("32A0AE2E01BBE329"));
assert_eq!(pbkdf2_params.key_length, None);
assert_eq!(pbkdf2_params.prf, pbes2::Pbkdf2Prf::HmacWithSha256);
assert_eq!(pbkdf2_params.iteration_count, 2048);
match params.encryption {
pbes2::EncryptionScheme::DesEde3Cbc { iv } => {
assert_eq!(iv, &hex!("97E8F53AB0ACA359"));
}
other => panic!("unexpected encryption scheme: {:?}", other),
}
}
/// Decoding test for PBES2 + PBKDF2-SHA256 + DES-CBC `AlgorithmIdentifier`
#[cfg(feature = "des-insecure")]
#[test]
fn decode_pbes2_pbkdf2_sha256_descbc() {
let scheme = pkcs5::EncryptionScheme::try_from(PBES2_PBKDF2_SHA256_DESCBC_ALG_ID).unwrap();
let params = scheme.pbes2().unwrap();
let pbkdf2_params = params.kdf.pbkdf2().unwrap();
assert_eq!(pbkdf2_params.salt, &hex!("09E7EDFBD9F21E2B"));
assert_eq!(pbkdf2_params.key_length, None);
assert_eq!(pbkdf2_params.prf, pbes2::Pbkdf2Prf::HmacWithSha256);
assert_eq!(pbkdf2_params.iteration_count, 2048);
match params.encryption {
pbes2::EncryptionScheme::DesCbc { iv } => {
assert_eq!(iv, &hex!("F4AAF206A18DE7AD"));
}
other => panic!("unexpected encryption scheme: {:?}", other),
}
}
/// Encoding test for PBES2 + PBKDF2-SHA1 + AES-128-CBC `AlgorithmIdentifier`
#[test]
fn encode_pbes2_pbkdf2_sha1_aes128cbc() {
let mut buffer = [0u8; 1024];
let scheme = pkcs5::EncryptionScheme::try_from(PBES2_PBKDF2_SHA1_AES128CBC_ALG_ID).unwrap();
let mut encoder = der::SliceWriter::new(&mut buffer);
scheme.encode(&mut encoder).unwrap();
let encoded_der = encoder.finish().unwrap();
assert_eq!(encoded_der, PBES2_PBKDF2_SHA1_AES128CBC_ALG_ID);
}
/// Encoding test for PBES2 + PBKDF2-SHA256 + AES-256-CBC `AlgorithmIdentifier`
#[test]
fn encode_pbes2_pbkdf2_sha256_aes256cbc() {
let mut buffer = [0u8; 1024];
let scheme = pkcs5::EncryptionScheme::try_from(PBES2_PBKDF2_SHA256_AES256CBC_ALG_ID).unwrap();
let mut encoder = der::SliceWriter::new(&mut buffer);
scheme.encode(&mut encoder).unwrap();
let encoded_der = encoder.finish().unwrap();
assert_eq!(encoded_der, PBES2_PBKDF2_SHA256_AES256CBC_ALG_ID);
}
/// Encoding test for PBES2 + scrypt + AES-256-CBC `AlgorithmIdentifier`
#[test]
fn encode_pbes2_scrypt_aes256cbc() {
let mut buffer = [0u8; 1024];
let scheme = pkcs5::EncryptionScheme::try_from(PBES2_SCRYPT_AES256CBC_ALG_ID).unwrap();
let mut encoder = der::SliceWriter::new(&mut buffer);
scheme.encode(&mut encoder).unwrap();
let encoded_der = encoder.finish().unwrap();
assert_eq!(encoded_der, PBES2_SCRYPT_AES256CBC_ALG_ID);
}

View File

@@ -0,0 +1,56 @@
//! PBES2 PBKDF2 decryption tests
#[cfg(feature = "pbes2")]
use std::fs;
#[cfg(feature = "pbes2")]
fn run_combinations(prfs: &[&str]) {
/// Password used to encrypt the keys.
const PASSWORD: &[u8] = b"hunter2"; // Bad password; don't actually use outside tests!
let sk_path = "./tests/examples/rsa_sk.pkcs8.der";
let sk_bytes = fs::read(&sk_path).expect(&format!("Failed to read from {}", &sk_path));
for aes_mode in ["aes-128-cbc", "aes-192-cbc", "aes-256-cbc"] {
for prf in prfs {
let algid_path = format!("./tests/examples/pbes2_{}_{}_algid.der", aes_mode, prf);
let algid_bytes =
fs::read(&algid_path).expect(&format!("Failed to read from {}", &algid_path));
let scheme = pkcs5::EncryptionScheme::try_from(algid_bytes.as_slice())
.expect(&format!("Failed to interpret scheme {} {}", aes_mode, prf));
let ciphertext_path =
format!("./tests/examples/pbes2_{}_{}_ciphertext.bin", aes_mode, prf);
let mut ciphertext_bytes = fs::read(&ciphertext_path)
.expect(&format!("Failed to read from {}", &ciphertext_path));
assert_eq!(640, ciphertext_bytes.len());
let plaintext = scheme
.decrypt_in_place(PASSWORD, &mut ciphertext_bytes)
.expect(&format!("pbes2 decryption of {} {}", aes_mode, prf));
assert_eq!(sk_bytes, plaintext);
}
}
}
#[cfg(feature = "sha1-insecure")]
#[test]
fn all_combinations_with_sha1() {
let prfs = vec!["hmacWithSHA1"];
run_combinations(&prfs);
}
#[cfg(feature = "pbes2")]
#[test]
fn all_combinations_with_sha2() {
let prfs = vec![
"hmacWithSHA224",
"hmacWithSHA256",
"hmacWithSHA384",
"hmacWithSHA512",
];
run_combinations(&prfs);
}