use ::pkcs8::der::Decode;
use ::pkcs8::pkcs5::pbes2::{Kdf, Pbkdf2Prf};
use ::pkcs8::pkcs5::EncryptionScheme as Pkcs5Scheme;
use ::pkcs8::{EncryptedPrivateKeyInfoRef, PrivateKeyInfoRef};
use zeroize::Zeroizing;
use crate::error::{JoseError, Result};
use crate::jwk::Jwk;
use crate::password::Password;
pub const PKCS8_MIN_ITERATIONS: u32 = 2_048;
pub const PKCS8_DEFAULT_ITERATIONS: u32 = 600_000;
pub const PKCS8_DEFAULT_MAX_ITERATIONS: u32 = 10_000_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pkcs8Encryption {
Aes128CbcPbkdf2HmacSha256 {
iterations: u32,
},
Aes256CbcPbkdf2HmacSha256 {
iterations: u32,
},
}
impl Default for Pkcs8Encryption {
fn default() -> Self {
Pkcs8Encryption::Aes256CbcPbkdf2HmacSha256 {
iterations: PKCS8_DEFAULT_ITERATIONS,
}
}
}
impl Pkcs8Encryption {
pub fn iterations(self) -> u32 {
match self {
Pkcs8Encryption::Aes128CbcPbkdf2HmacSha256 { iterations } => iterations,
Pkcs8Encryption::Aes256CbcPbkdf2HmacSha256 { iterations } => iterations,
}
}
pub fn with_iterations(self, iterations: u32) -> Self {
match self {
Pkcs8Encryption::Aes128CbcPbkdf2HmacSha256 { .. } => {
Pkcs8Encryption::Aes128CbcPbkdf2HmacSha256 { iterations }
}
Pkcs8Encryption::Aes256CbcPbkdf2HmacSha256 { .. } => {
Pkcs8Encryption::Aes256CbcPbkdf2HmacSha256 { iterations }
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Pkcs8ReadOptions {
max_iterations: u32,
}
impl Default for Pkcs8ReadOptions {
fn default() -> Self {
Pkcs8ReadOptions {
max_iterations: PKCS8_DEFAULT_MAX_ITERATIONS,
}
}
}
impl Pkcs8ReadOptions {
pub fn with_max_iterations(mut self, max_iterations: u32) -> Self {
self.max_iterations = max_iterations;
self
}
pub fn max_iterations(&self) -> u32 {
self.max_iterations
}
}
pub fn jwk_from_encrypted_pkcs8_der(der: &[u8], password: &Password) -> Result<Jwk> {
jwk_from_encrypted_pkcs8_der_with_options(der, password, &Pkcs8ReadOptions::default())
}
pub fn jwk_from_encrypted_pkcs8_der_with_options(
der: &[u8],
password: &Password,
options: &Pkcs8ReadOptions,
) -> Result<Jwk> {
crate::ensure_emit_size(der.len())?;
let info = EncryptedPrivateKeyInfoRef::from_der(der).map_err(|e| {
if let Some(reason) = unsupported_oid_hint(der) {
return JoseError::Key(reason);
}
JoseError::Key(format!("invalid EncryptedPrivateKeyInfo DER: {e}"))
})?;
describe_scheme(&info.encryption_algorithm, options.max_iterations())?;
let decryption_failed = || {
JoseError::Key(
"PKCS#8 decryption failed (wrong password, or the file is not intact)".into(),
)
};
let mut plaintext = Zeroizing::new(info.encrypted_data.as_bytes().to_vec());
let plaintext_len = info
.encryption_algorithm
.decrypt_in_place(password.as_bytes(), &mut plaintext)
.map_err(|_| decryption_failed())?
.len();
super::import::jwk_from_pkcs8_der(&plaintext[..plaintext_len]).map_err(|_| decryption_failed())
}
pub fn jwk_from_encrypted_pkcs8_pem(text: &str, password: &Password) -> Result<Jwk> {
jwk_from_encrypted_pkcs8_pem_with_options(text, password, &Pkcs8ReadOptions::default())
}
pub fn jwk_from_encrypted_pkcs8_pem_with_options(
text: &str,
password: &Password,
options: &Pkcs8ReadOptions,
) -> Result<Jwk> {
let (label, der) = super::pem::decompose(text)?;
if label != super::pem::LABEL_ENCRYPTED_PRIVATE {
return Err(JoseError::InvalidToken(format!(
"expected a PEM \"ENCRYPTED PRIVATE KEY\" block and found \"{label}\"; an \
unencrypted key must not be readable through the password path, or a caller \
cannot tell whether their key is protected"
)));
}
jwk_from_encrypted_pkcs8_der_with_options(&der, password, options)
}
pub fn encrypted_pkcs8_der_from_jwk(
jwk: &Jwk,
password: &Password,
scheme: &Pkcs8Encryption,
) -> Result<Zeroizing<Vec<u8>>> {
if password.is_empty() {
return Err(JoseError::Key(
"refusing to encrypt a key with an empty password: an unset secret and an \
intentionally empty one produce indistinguishable files, and the caller cannot \
tell them apart later"
.into(),
));
}
let iterations = scheme.iterations();
if iterations < PKCS8_MIN_ITERATIONS {
return Err(JoseError::Key(format!(
"PKCS#8 iteration count {iterations} is below the minimum of {PKCS8_MIN_ITERATIONS}; \
that floor is what OpenSSL and cryptography emit by default, so a file below it is \
one other tools will not read either"
)));
}
let software = super::convert::jwk_to_software_key(jwk)?;
let plain = super::pem::pkcs8_portable_form(software.export_private()?.as_ref())?;
let info = PrivateKeyInfoRef::from_der(&plain).map_err(|e| {
JoseError::Key(format!(
"PKCS#8 export from the backend did not parse: {e:?}"
))
})?;
let mut salt = [0u8; 16];
let mut iv = [0u8; 16];
getrandom::fill(&mut salt)
.map_err(|e| JoseError::Key(format!("operating-system randomness failed: {e}")))?;
getrandom::fill(&mut iv)
.map_err(|e| JoseError::Key(format!("operating-system randomness failed: {e}")))?;
let params = match scheme {
Pkcs8Encryption::Aes128CbcPbkdf2HmacSha256 { .. } => {
::pkcs8::pkcs5::pbes2::Parameters::generate_pbkdf2_sha256_aes128cbc(
iterations, &salt, iv,
)
}
Pkcs8Encryption::Aes256CbcPbkdf2HmacSha256 { .. } => {
::pkcs8::pkcs5::pbes2::Parameters::generate_pbkdf2_sha256_aes256cbc(
iterations, &salt, iv,
)
}
}
.map_err(|e| JoseError::Key(format!("PKCS#8 PBES2 parameters were rejected: {e:?}")))?;
let encrypted = info
.encrypt_with_params(params, password.as_bytes())
.map_err(|e| JoseError::Key(format!("PKCS#8 encryption failed: {e:?}")))?;
Ok(Zeroizing::new(encrypted.as_bytes().to_vec()))
}
pub fn encrypted_pkcs8_pem_from_jwk(
jwk: &Jwk,
password: &Password,
scheme: &Pkcs8Encryption,
) -> Result<String> {
let der = encrypted_pkcs8_der_from_jwk(jwk, password, scheme)?;
super::pem::encode_with_label("ENCRYPTED PRIVATE KEY", der.as_ref())
}
fn describe_scheme(scheme: &Pkcs5Scheme, max_iterations: u32) -> Result<u32> {
match scheme {
Pkcs5Scheme::Pbes1(_) => Err(JoseError::Key(
"PBES1 (RFC 8018 §6.1) encrypted PKCS#8 is unsupported: its PRF family is \
HMAC-SHA1-based and its ciphers are DES and RC2, and no parameter choice brings \
it up to what this crate will accept. Re-export the key with PBES2/AES-CBC"
.into(),
)),
Pkcs5Scheme::Pbes2(params) => match (¶ms.kdf, ¶ms.encryption) {
(Kdf::Scrypt(_), _) => Err(JoseError::Key(
"scrypt-based encrypted PKCS#8 is unsupported: scrypt's cost comes from the \
file's own (log N, r, p) parameters, and this crate's bound is a PBKDF2 \
iteration count, so accepting it would mean accepting a work cost it cannot \
bound. Note that this is also what `pkcs8`'s default export form uses, which \
is why this crate neither emits nor reads it"
.into(),
)),
(Kdf::Pbkdf2(kdf), cipher) => {
match kdf.prf {
Pbkdf2Prf::HmacWithSha256
| Pbkdf2Prf::HmacWithSha384
| Pbkdf2Prf::HmacWithSha512 => {}
Pbkdf2Prf::HmacWithSha1 => {
return Err(JoseError::Key(
"PBKDF2 with HMAC-SHA1 is outside this crate's scheme allow-list; \
re-export the key with hmacWithSHA256 or better"
.into(),
));
}
Pbkdf2Prf::HmacWithSha224 => {
return Err(JoseError::Key(
"PBKDF2 with HMAC-SHA224 is outside this crate's scheme allow-list \
(SHA-256, SHA-384, SHA-512)"
.into(),
));
}
other => {
return Err(JoseError::Key(format!(
"PBKDF2 with an unknown PRF ({other:?}) is outside this crate's \
scheme allow-list (SHA-256, SHA-384, SHA-512)"
)));
}
}
match cipher {
::pkcs8::pkcs5::pbes2::EncryptionScheme::Aes128Cbc { .. }
| ::pkcs8::pkcs5::pbes2::EncryptionScheme::Aes256Cbc { .. } => {}
other => {
return Err(JoseError::Key(format!(
"PBES2 cipher {other:?} is outside this crate's scheme allow-list \
(AES-128-CBC and AES-256-CBC)"
)));
}
}
let iterations = kdf.iteration_count;
if iterations < PKCS8_MIN_ITERATIONS {
return Err(JoseError::Key(format!(
"encrypted PKCS#8 names {iterations} PBKDF2 iterations, below the \
minimum of {PKCS8_MIN_ITERATIONS} (the count OpenSSL and cryptography \
emit by default); decrypt and re-export it with a real count"
)));
}
if iterations > max_iterations {
return Err(JoseError::Key(format!(
"encrypted PKCS#8 names {iterations} PBKDF2 iterations, above this \
call's budget of {max_iterations}; the file chooses this number and \
this process pays it, so it is bounded (raise it per call with \
Pkcs8ReadOptions::with_max_iterations)"
)));
}
Ok(iterations)
}
(other_kdf, _) => Err(JoseError::Key(format!(
"encrypted PKCS#8 names a key derivation function this crate does not know \
({other_kdf:?})"
))),
},
other => Err(JoseError::Key(format!(
"encrypted PKCS#8 names a password-based encryption scheme this crate does not \
know ({other:?}); unknown means unimplemented, not acceptable"
))),
}
}
mod oids {
pub const PBES1: [u8; 3] = [0x06, 0x09, 0x2A];
pub const PKCS5_PBASE: &[u8] = &[0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x05];
pub const SCRYPT: &[u8] = &[0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x04, 0x0B];
pub const HMAC_WITH_SHA1: &[u8] = &[0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x07];
pub const HMAC_WITH_SHA224: &[u8] = &[0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x08];
pub const DES_EDE3_CBC: &[u8] = &[0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x03, 0x07];
pub const DES_CBC: &[u8] = &[0x2B, 0x0E, 0x03, 0x02, 0x07];
pub const AES_192_CBC: &[u8] = &[0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x16];
}
fn contains_oid(der: &[u8], oid: &[u8]) -> bool {
let mut needle = [0u8; 11];
if oid.len() > 9 {
return false;
}
needle[0] = 0x06;
needle[1] = oid.len() as u8;
needle[2..2 + oid.len()].copy_from_slice(oid);
der.windows(2 + oid.len())
.any(|w| w == &needle[..2 + oid.len()])
}
fn unsupported_oid_hint(der: &[u8]) -> Option<String> {
if contains_oid(der, oids::DES_EDE3_CBC) {
return Some(
"3DES-CBC encrypted PKCS#8 is unsupported — the dependency is compiled without \
3DES, so the file cannot even be parsed far enough to refuse it politely. \
Re-export the key with AES-CBC"
.into(),
);
}
if contains_oid(der, oids::DES_CBC) {
return Some(
"DES-CBC encrypted PKCS#8 is unsupported; re-export the key with AES-CBC".into(),
);
}
if contains_oid(der, oids::AES_192_CBC) {
return Some(
"AES-192-CBC encrypted PKCS#8 is unsupported (AES-128-CBC and AES-256-CBC are); \
re-export the key with one of those"
.into(),
);
}
if contains_oid(der, oids::HMAC_WITH_SHA1) {
return Some(
"PBKDF2 with HMAC-SHA1 is outside this crate's scheme allow-list; re-export the \
key with hmacWithSHA256 or better"
.into(),
);
}
if contains_oid(der, oids::HMAC_WITH_SHA224) {
return Some(
"PBKDF2 with HMAC-SHA224 is outside this crate's scheme allow-list (SHA-256, \
SHA-384, SHA-512)"
.into(),
);
}
if contains_oid(der, oids::SCRYPT) {
return Some(
"scrypt-based encrypted PKCS#8 is unsupported: its cost comes from the file's own \
parameters, and this crate's bound is a PBKDF2 iteration count"
.into(),
);
}
if !contains_oid(der, oids::PKCS5_PBASE) && der.starts_with(&[0x30]) {
return Some(
"encrypted PKCS#8 names an algorithm outside the PKCS#5 pbes2 arc; PBES1 \
(RFC 8018 §6.1) is unsupported — its PRFs are MD2/MD5/HMAC-SHA1 and its cipher is \
DES"
.into(),
);
}
let _ = oids::PBES1;
None
}
#[cfg(test)]
mod tests {
use super::*;
use crate::jwk::{self};
use std::time::Instant;
fn ec_jwk() -> Jwk {
crate::jwk::generate_ec("P-256").expect("generate")
}
#[test]
fn round_trip_recovers_the_same_key_material() {
let key = ec_jwk();
let password = Password::from_utf8("hunter2");
let der = encrypted_pkcs8_der_from_jwk(&key, &password, &Pkcs8Encryption::default())
.expect("encrypt");
let back = jwk_from_encrypted_pkcs8_der(&der, &password).expect("decrypt");
assert_eq!(back.kty, key.kty);
assert_eq!(back.crv, key.crv);
assert_eq!(back.x, key.x);
assert_eq!(back.d, key.d);
}
#[test]
fn two_exports_of_one_key_share_no_prefix() {
let key = ec_jwk();
let password = Password::from_utf8("same password");
let a =
encrypted_pkcs8_pem_from_jwk(&key, &password, &Pkcs8Encryption::default()).expect("a");
let b =
encrypted_pkcs8_pem_from_jwk(&key, &password, &Pkcs8Encryption::default()).expect("b");
assert_ne!(a, b);
assert!(a.starts_with("-----BEGIN ENCRYPTED PRIVATE KEY-----"));
assert!(b.contains("-----END ENCRYPTED PRIVATE KEY-----\n"));
}
#[test]
fn wrong_password_is_refused_not_misinterpreted() {
let key = ec_jwk();
let der = encrypted_pkcs8_der_from_jwk(
&key,
&Password::from_utf8("right"),
&Pkcs8Encryption::default(),
)
.expect("encrypt");
let err = jwk_from_encrypted_pkcs8_der(&der, &Password::from_utf8("wrong"))
.expect_err("wrong password must not import");
let msg = err.to_string();
assert!(msg.contains("decryption failed"), "{msg}");
assert!(!msg.contains("EC"), "{msg}");
}
#[test]
fn tampered_ciphertext_is_refused() {
let key = ec_jwk();
let password = Password::from_utf8("password");
let mut der = encrypted_pkcs8_der_from_jwk(&key, &password, &Pkcs8Encryption::default())
.expect("encrypt");
let last = der.len() - 5;
der[last] ^= 0x01;
let err = jwk_from_encrypted_pkcs8_der(&der, &password).expect_err("tampered");
assert!(err.to_string().contains("decryption failed"), "{err}");
}
#[test]
fn padding_valid_invalid_plaintext_is_indistinguishable_from_a_wrong_password() {
let key = ec_jwk();
let password = Password::from_utf8("right");
let mut der = encrypted_pkcs8_der_from_jwk(&key, &password, &Pkcs8Encryption::default())
.expect("encrypt");
let wrong_password =
jwk_from_encrypted_pkcs8_der(&der, &Password::from_utf8("wrong")).unwrap_err();
let info = EncryptedPrivateKeyInfoRef::from_der(&der).expect("parse envelope");
let offset = der.len() - info.encrypted_data.as_bytes().len();
der[offset] ^= 1;
let invalid_plaintext = jwk_from_encrypted_pkcs8_der(&der, &password).unwrap_err();
assert_eq!(invalid_plaintext.to_string(), wrong_password.to_string());
}
#[test]
fn plaintext_forms_are_refused_without_a_fallback() {
let pem = jwk::private_pem_from_jwk(&ec_jwk()).expect("plaintext PEM");
let err = jwk_from_encrypted_pkcs8_pem(&pem, &Password::from_utf8("x"))
.expect_err("the password path must not read an unencrypted file");
let msg = err.to_string();
assert!(msg.contains("ENCRYPTED PRIVATE KEY"), "{msg}");
assert!(msg.contains("protected"), "{msg}");
let encrypted = jwk::encrypted_pkcs8_pem_from_jwk(
&ec_jwk(),
&Password::from_utf8("x"),
&Pkcs8Encryption::default(),
)
.expect("encrypt");
let err = jwk::jwk_from_pem(&encrypted).expect_err("plaintext door must refuse");
assert!(
err.to_string().contains("jwk_from_encrypted_pkcs8_pem"),
"{err}"
);
}
#[test]
fn iteration_budget_is_enforced_before_deriving() {
let key = ec_jwk();
let password = Password::from_utf8("x");
let cheap = encrypted_pkcs8_der_from_jwk(
&key,
&password,
&Pkcs8Encryption::Aes256CbcPbkdf2HmacSha256 { iterations: 4_096 },
)
.expect("4096 is above the floor");
assert!(jwk_from_encrypted_pkcs8_der(&cheap, &password).is_ok());
let err = jwk_from_encrypted_pkcs8_der_with_options(
&cheap,
&password,
&Pkcs8ReadOptions::default().with_max_iterations(2_048),
)
.expect_err("over budget");
let msg = err.to_string();
assert!(msg.contains("4096"), "{msg}");
assert!(msg.contains("budget"), "{msg}");
let err = encrypted_pkcs8_der_from_jwk(
&key,
&password,
&Pkcs8Encryption::Aes256CbcPbkdf2HmacSha256 { iterations: 1 },
)
.expect_err("one iteration is not protection");
assert!(err.to_string().contains("2048"), "{err}");
}
#[test]
fn rsa_and_ed25519_keys_round_trip_through_encrypted_pkcs8() {
let password = Password::from_utf8("pass");
for curve in ["RSA", "Ed25519"] {
let key = if curve == "RSA" {
crate::jwk::generate_rsa(2048).expect("rsa")
} else {
crate::jwk::generate_ed25519().expect("ed25519")
};
let der = encrypted_pkcs8_der_from_jwk(
&key,
&password,
&Pkcs8Encryption::Aes128CbcPbkdf2HmacSha256 {
iterations: PKCS8_MIN_ITERATIONS,
},
)
.expect("encrypt");
let back = jwk_from_encrypted_pkcs8_der(&der, &password).expect("decrypt");
assert_eq!(back.kty, key.kty, "{curve}");
assert_eq!(back.crv, key.crv, "{curve}");
assert_eq!(back.n, key.n, "{curve}");
assert_eq!(back.d, key.d, "{curve}");
}
}
#[test]
fn public_only_jwks_cannot_be_exported_as_private_keys() {
let public = ec_jwk().to_public_jwk();
let err = encrypted_pkcs8_der_from_jwk(
&public,
&Password::from_utf8("x"),
&Pkcs8Encryption::default(),
)
.expect_err("no private part");
assert!(err.to_string().contains("no private material"), "{err}");
}
#[test]
fn a_des_file_is_refused_by_name_not_as_corruption() {
let mut der = vec![0x30, 0x00];
der.extend_from_slice(&[0x06, 0x08, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x03, 0x07]);
let hint = unsupported_oid_hint(&der).expect("named");
assert!(hint.contains("3DES"), "{hint}");
assert!(contains_oid(&der, oids::DES_EDE3_CBC));
assert!(!contains_oid(
&[0x06, 0x07, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x03],
oids::DES_EDE3_CBC
));
}
#[test]
fn ed25519_exports_encrypt_the_portable_form() {
use ::pkcs8::der::Decode;
for key in [
crate::jwk::generate_ed25519().expect("ed25519"),
crate::jwk::generate_ec("P-256").expect("ec"),
] {
let password = Password::from_utf8("x");
let der = encrypted_pkcs8_der_from_jwk(&key, &password, &Pkcs8Encryption::default())
.expect("encrypt");
let info = EncryptedPrivateKeyInfoRef::from_der(&der).expect("parse");
let inner = info.decrypt(password.as_bytes()).expect("decrypt");
let inner_info = PrivateKeyInfoRef::from_der(inner.as_bytes()).expect("inner pkcs8");
assert!(
inner_info.public_key.is_none(),
"{}: encrypted payload still carries the OneAsymmetricKey publicKey attribute",
key.crv.as_deref().unwrap_or("?")
);
}
}
#[test]
fn scrypt_files_are_refused_even_though_pkcs8_writes_them() {
use ::pkcs8::der::Decode;
let key = ec_jwk();
let plain = super::super::convert::jwk_to_software_key(&key)
.expect("convert")
.export_private()
.expect("pkcs8");
let info = PrivateKeyInfoRef::from_der(plain.as_ref()).expect("parse");
let scrypt_file = info
.encrypt_with_rng(&mut getrandom::SysRng, b"hunter2")
.expect("scrypt encrypt");
let err =
jwk_from_encrypted_pkcs8_der(scrypt_file.as_bytes(), &Password::from_utf8("hunter2"))
.expect_err("scrypt must be refused");
let msg = err.to_string();
assert!(msg.contains("scrypt"), "{msg}");
assert!(msg.contains("bound"), "{msg}");
let hint = unsupported_oid_hint(scrypt_file.as_bytes()).expect("hint");
assert!(hint.contains("scrypt"), "{hint}");
}
#[test]
#[ignore = "wall-clock benchmark"]
fn pkcs8_work_budget_benchmark() {
let salt = [0x22u8; 16];
let iv = [0x33u8; 16];
for iterations in [
PKCS8_MIN_ITERATIONS,
PKCS8_DEFAULT_ITERATIONS,
PKCS8_DEFAULT_MAX_ITERATIONS,
] {
let params = ::pkcs8::pkcs5::pbes2::Parameters::generate_pbkdf2_sha256_aes256cbc(
iterations, &salt, iv,
)
.expect("parameters");
let started = Instant::now();
params
.encrypt(b"benchmark password", b"payload".as_slice())
.expect("derive");
println!(
"PBES2 PBKDF2-HMAC-SHA256/AES-256-CBC {iterations:>10} iterations: {:?}",
started.elapsed()
);
}
}
}