Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ tls_codec_derive = { path = "./tls_codec/derive" }
x509-tsp = { path = "./x509-tsp" }
x509-cert = { path = "./x509-cert" }
x509-ocsp = { path = "./x509-ocsp" }
# TODO: Remove after https://github.com/RustCrypto/key-wraps/pull/98
belt-kwp = { git = "https://github.com/makavity/key-wraps.git" }

[workspace.lints.clippy]
borrow_as_ptr = "warn"
Expand Down
6 changes: 6 additions & 0 deletions pkcs5/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ 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).

## Unreleased
### Added
- Support for using BELT-KWP with PBES2 ([#2408])

[#2408]: https://github.com/RustCrypto/formats/pull/2408

## 0.8.1 (2026-06-28)
### Added
- Support for using AES-GCM with PBES2 ([#1433], [#2313])
Expand Down
3 changes: 3 additions & 0 deletions pkcs5/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ spki = "0.8"
cbc = { version = "0.2", optional = true }
aes = { version = "0.9", optional = true, default-features = false }
aes-gcm = { version = "0.11", optional = true, default-features = false, features = ["aes"] }
belt-hash = { version = "0.2", optional = true, default-features = false }
belt-kwp = { version = "0.2", optional = true, default-features = false }
des = { version = "0.9", optional = true, default-features = false }
pbkdf2 = { version = "0.13", optional = true, default-features = false, features = ["hmac"] }
getrandom = { version = "0.4", optional = true, features = ["sys_rng"] }
Expand All @@ -39,6 +41,7 @@ alloc = []

3des = ["dep:des", "pbes2"]
des-insecure = ["dep:des", "pbes2"]
belt = ["dep:belt-hash", "dep:belt-kwp", "pbes2"]
getrandom = ["dep:getrandom", "rand_core"]
pbes2 = ["dep:aes", "dep:cbc", "dep:pbkdf2", "dep:scrypt", "dep:sha2", "dep:aes-gcm"]
rand_core = ["dep:rand_core"]
Expand Down
88 changes: 66 additions & 22 deletions pkcs5/src/pbes2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ pub const DES_CBC_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.3.14.3
#[cfg(feature = "3des")]
pub const DES_EDE3_CBC_OID: ObjectIdentifier = ObjectIdentifier::new_unwrap("1.2.840.113549.3.7");

/// `belt-kwp256` key wrap algorithm as defined in STB 34.101.31 Section 7.2.
#[cfg(feature = "belt")]
pub const BELT_KWP_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.2.112.0.2.0.34.101.31.73");

/// Password-Based Encryption Scheme 2 (PBES2) OID.
///
/// <https://tools.ietf.org/html/rfc8018#section-6.2>
Expand Down Expand Up @@ -185,6 +190,19 @@ impl Parameters {
Ok(Self { kdf, encryption })
}

/// Initialize PBES2 parameters using PBKDF2-HMAC-HBELT as the
/// password-based key derivation function and `belt-kwp256` as the key wrap
/// algorithm, as used by the STB 34.101.78 (`bpki`) private key container.
///
/// # Errors
/// Propagates errors from [`Pbkdf2Params::hmac_hbelt`].
#[cfg(feature = "belt")]
pub fn pbkdf2_hmac_hbelt_belt_kwp(pbkdf2_iterations: u32, pbkdf2_salt: &[u8]) -> Result<Self> {
let kdf = Pbkdf2Params::hmac_hbelt(pbkdf2_iterations, pbkdf2_salt)?.into();
let encryption = EncryptionScheme::BeltKwp;
Ok(Self { kdf, encryption })
}

/// Generate PBES2 parameters using scrypt as the password hashing
/// algorithm, using that algorithm's recommended algorithm settings
/// along with a randomly generated salt and IV.
Expand Down Expand Up @@ -463,6 +481,10 @@ pub enum EncryptionScheme {
/// Initialisation vector
iv: [u8; DES_BLOCK_SIZE],
},

/// BELT-KWP
#[cfg(feature = "belt")]
BeltKwp,
}

impl EncryptionScheme {
Expand All @@ -479,6 +501,8 @@ impl EncryptionScheme {
Self::DesCbc { .. } => 8,
#[cfg(feature = "3des")]
Self::DesEde3Cbc { .. } => 24,
#[cfg(feature = "belt")]
Self::BeltKwp => 32,
}
}

Expand All @@ -495,6 +519,8 @@ impl EncryptionScheme {
Self::DesCbc { .. } => DES_CBC_OID,
#[cfg(feature = "3des")]
Self::DesEde3Cbc { .. } => DES_EDE3_CBC_OID,
#[cfg(feature = "belt")]
Self::BeltKwp => BELT_KWP_OID,
}
}

Expand All @@ -515,40 +541,55 @@ impl<'a> Decode<'a> for EncryptionScheme {
}
}

/// Decode an IV/nonce of exactly `N` bytes from an `AlgorithmIdentifier`'s
/// OCTET STRING parameters.
fn decode_iv<const N: usize>(params: Option<AnyRef<'_>>) -> der::Result<[u8; N]> {
params
.ok_or_else(|| Tag::OctetString.value_error())?
.decode_as::<&OctetStringRef>()?
.as_bytes()
.try_into()
.map_err(|_| Tag::OctetString.value_error().into())
}

Comment on lines +544 to +554

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey, @tarcieri!
What do you think about that approach?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe I should separate it into another PR?

impl TryFrom<AlgorithmIdentifierRef<'_>> for EncryptionScheme {
type Error = der::Error;

fn try_from(alg: AlgorithmIdentifierRef<'_>) -> der::Result<Self> {
// TODO(tarcieri): support for non-AES algorithms?
let iv = match alg.parameters {
Some(params) => params.decode_as::<&OctetStringRef>()?.as_bytes(),
None => return Err(Tag::OctetString.value_error().into()),
};

match alg.oid {
AES_128_CBC_OID => Ok(Self::Aes128Cbc {
iv: iv.try_into().map_err(|_| Tag::OctetString.value_error())?,
iv: decode_iv(alg.parameters)?,
}),
AES_192_CBC_OID => Ok(Self::Aes192Cbc {
iv: iv.try_into().map_err(|_| Tag::OctetString.value_error())?,
iv: decode_iv(alg.parameters)?,
}),
AES_256_CBC_OID => Ok(Self::Aes256Cbc {
iv: iv.try_into().map_err(|_| Tag::OctetString.value_error())?,
iv: decode_iv(alg.parameters)?,
}),
AES_128_GCM_OID => Ok(Self::Aes128Gcm {
nonce: iv.try_into().map_err(|_| Tag::OctetString.value_error())?,
nonce: decode_iv(alg.parameters)?,
}),
AES_256_GCM_OID => Ok(Self::Aes256Gcm {
nonce: iv.try_into().map_err(|_| Tag::OctetString.value_error())?,
nonce: decode_iv(alg.parameters)?,
}),
#[cfg(feature = "des-insecure")]
DES_CBC_OID => Ok(Self::DesCbc {
iv: iv.try_into().map_err(|_| Tag::OctetString.value_error())?,
iv: decode_iv(alg.parameters)?,
}),
#[cfg(feature = "3des")]
DES_EDE3_CBC_OID => Ok(Self::DesEde3Cbc {
iv: iv.try_into().map_err(|_| Tag::OctetString.value_error())?,
iv: decode_iv(alg.parameters)?,
}),
// `belt-kwp` has no IV: STB 34.101.78 encodes NULL parameters.
#[cfg(feature = "belt")]
BELT_KWP_OID => {
if let Some(params) = alg.parameters {
params.decode_as::<()>()?;
}

Ok(Self::BeltKwp)
}
oid => Err(ErrorKind::OidUnknown { oid }.into()),
}
}
Expand All @@ -558,21 +599,24 @@ impl<'a> TryFrom<&'a EncryptionScheme> for AlgorithmIdentifierRef<'a> {
type Error = der::Error;

fn try_from(scheme: &'a EncryptionScheme) -> der::Result<Self> {
let parameters = OctetStringRef::new(match scheme {
EncryptionScheme::Aes128Cbc { iv } => iv.as_slice(),
EncryptionScheme::Aes192Cbc { iv } => iv.as_slice(),
EncryptionScheme::Aes256Cbc { iv } => iv.as_slice(),
EncryptionScheme::Aes128Gcm { nonce } => nonce.as_slice(),
EncryptionScheme::Aes256Gcm { nonce } => nonce.as_slice(),
let parameters = match scheme {
EncryptionScheme::Aes128Cbc { iv } => OctetStringRef::new(iv)?.into(),
EncryptionScheme::Aes192Cbc { iv } => OctetStringRef::new(iv)?.into(),
EncryptionScheme::Aes256Cbc { iv } => OctetStringRef::new(iv)?.into(),
EncryptionScheme::Aes128Gcm { nonce } => OctetStringRef::new(nonce)?.into(),
EncryptionScheme::Aes256Gcm { nonce } => OctetStringRef::new(nonce)?.into(),
#[cfg(feature = "des-insecure")]
EncryptionScheme::DesCbc { iv } => iv.as_slice(),
EncryptionScheme::DesCbc { iv } => OctetStringRef::new(iv)?.into(),
#[cfg(feature = "3des")]
EncryptionScheme::DesEde3Cbc { iv } => iv.as_slice(),
})?;
EncryptionScheme::DesEde3Cbc { iv } => OctetStringRef::new(iv)?.into(),
// `belt-kwp` has no IV and encodes NULL parameters (STB 34.101.78).
#[cfg(feature = "belt")]
EncryptionScheme::BeltKwp => AnyRef::NULL,
};

Ok(AlgorithmIdentifierRef {
oid: scheme.oid(),
parameters: Some(parameters.into()),
parameters: Some(parameters),
})
}
}
Expand Down
27 changes: 27 additions & 0 deletions pkcs5/src/pbes2/encryption.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
use super::{EncryptionScheme, Kdf, Parameters, Pbkdf2Params, Pbkdf2Prf, ScryptParams};
use crate::{Error, Result};
use aes_gcm::{KeyInit as GcmKeyInit, Nonce, Tag, aead::AeadInOut};
#[cfg(feature = "belt")]
use belt_hash::BeltHash;
use cbc::cipher::{
BlockCipherDecrypt, BlockCipherEncrypt, BlockModeDecrypt, BlockModeEncrypt, KeyInit, KeyIvInit,
block_padding::Pkcs7,
Expand Down Expand Up @@ -136,6 +138,10 @@ pub fn encrypt_in_place<'b>(
EncryptionScheme::DesCbc { .. } => Err(Error::UnsupportedAlgorithm {
oid: super::DES_CBC_OID,
}),
#[cfg(feature = "belt")]
EncryptionScheme::BeltKwp => belt_kwp(&key)?
.wrap_key_in_place(buf, pos, &BELT_KWP_HEADER)
.map_err(|_| Error::EncryptFailed),
}
}

Expand All @@ -162,9 +168,24 @@ pub fn decrypt_in_place<'a>(
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),
#[cfg(feature = "belt")]
EncryptionScheme::BeltKwp => belt_kwp(&key)?
.unwrap_key_in_place(buf, &BELT_KWP_HEADER)
.map_err(|_| Error::DecryptFailed),
}
}

/// The `belt-kwp` header `I`, which STB 34.101.78 fixes to `0^128`.
#[cfg(feature = "belt")]
const BELT_KWP_HEADER: [u8; belt_kwp::IV_LEN] = [0u8; belt_kwp::IV_LEN];

/// Build a `belt-kwp` instance from the derived key.
#[cfg(feature = "belt")]
fn belt_kwp(key: &EncryptionKey) -> Result<belt_kwp::BeltKwp> {
belt_kwp::BeltKwp::new_from_slice(key.as_slice())
.map_err(|_| EncryptionScheme::BeltKwp.to_alg_params_invalid())
}

/// Encryption key as derived by PBKDF2
// TODO(tarcieri): zeroize?
struct EncryptionKey {
Expand Down Expand Up @@ -217,6 +238,12 @@ impl EncryptionKey {
pbkdf2_params,
key_size,
),
#[cfg(feature = "belt")]
Pbkdf2Prf::HmacHbelt => EncryptionKey::derive_with_pbkdf2::<BeltHash>(
password,
pbkdf2_params,
key_size,
),
};

Ok(key)
Expand Down
32 changes: 32 additions & 0 deletions pkcs5/src/pbes2/kdf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ pub const HMAC_WITH_SHA384_OID: ObjectIdentifier =
pub const HMAC_WITH_SHA512_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.2.840.113549.2.11");

/// HMAC-HBELT (for use with PBKDF2)
#[cfg(feature = "belt")]
pub const HMAC_WITH_HBELT_OID: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.2.112.0.2.0.34.101.47.12");

/// `id-scrypt` ([RFC 7914])
///
/// [RFC 7914]: https://datatracker.ietf.org/doc/html/rfc7914#section-7
Expand Down Expand Up @@ -236,6 +241,25 @@ impl Pbkdf2Params {
prf: Pbkdf2Prf::HmacWithSha256,
})
}

/// Initialize PBKDF2-HMAC-HBELT with the given iteration count and salt.
///
/// # Errors
/// Returns [`Error::AlgorithmParametersInvalid`] if `iteration_count` exceeds
/// [`Pbkdf2Params::MAX_ITERATION_COUNT`] or `salt` exceeds [`Salt::MAX_LEN`].
#[cfg(feature = "belt")]
pub fn hmac_hbelt(iteration_count: u32, salt: &[u8]) -> Result<Self> {
if iteration_count > Self::MAX_ITERATION_COUNT {
return Err(Self::INVALID_ERR);
}

Ok(Self {
salt: salt.try_into().map_err(|_| Self::INVALID_ERR)?,
iteration_count,
key_length: None,
prf: Pbkdf2Prf::HmacHbelt,
})
}
}

impl<'a> DecodeValue<'a> for Pbkdf2Params {
Expand Down Expand Up @@ -310,6 +334,10 @@ pub enum Pbkdf2Prf {

/// HMAC with SHA-512
HmacWithSha512,

/// HMAC with HBELT
#[cfg(feature = "belt")]
HmacHbelt,
}

impl Pbkdf2Prf {
Expand All @@ -322,6 +350,8 @@ impl Pbkdf2Prf {
Self::HmacWithSha256 => HMAC_WITH_SHA256_OID,
Self::HmacWithSha384 => HMAC_WITH_SHA384_OID,
Self::HmacWithSha512 => HMAC_WITH_SHA512_OID,
#[cfg(feature = "belt")]
Self::HmacHbelt => HMAC_WITH_HBELT_OID,
}
}
}
Expand Down Expand Up @@ -357,6 +387,8 @@ impl TryFrom<AlgorithmIdentifierRef<'_>> for Pbkdf2Prf {
HMAC_WITH_SHA256_OID => Ok(Self::HmacWithSha256),
HMAC_WITH_SHA384_OID => Ok(Self::HmacWithSha384),
HMAC_WITH_SHA512_OID => Ok(Self::HmacWithSha512),
#[cfg(feature = "belt")]
HMAC_WITH_HBELT_OID => Ok(Self::HmacHbelt),
oid => Err(ErrorKind::OidUnknown { oid }.into()),
}
}
Expand Down
Loading
Loading