Skip to content

Commit

Permalink
pkcs8: eagerly decode PEM labels (#1163)
Browse files Browse the repository at this point in the history
This should give better errors for invalid PEM type labels even if there
are subsequent Base64 processing errors, which might occur if e.g.
Base64 is wrapped at a nonstandard width.

Notably such errors will include the expected PEM type label.
  • Loading branch information
tarcieri authored Jul 23, 2023
1 parent 4e07915 commit 47a73cc
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
8 changes: 6 additions & 2 deletions pem-rfc7468/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ pub enum Error {

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
match *self {
Error::Base64(err) => write!(f, "PEM Base64 error: {}", err),
Error::CharacterEncoding => f.write_str("PEM character encoding error"),
Error::EncapsulatedText => f.write_str("PEM error in encapsulated text"),
Expand All @@ -60,7 +60,11 @@ impl fmt::Display for Error {
f.write_str("PEM error in post-encapsulation boundary")
}
Error::UnexpectedTypeLabel { expected } => {
write!(f, "unexpected PEM type label: expecting \"{}\"", expected)
write!(
f,
"unexpected PEM type label: expecting \"BEGIN {}\"",
expected
)
}
}
}
Expand Down
17 changes: 12 additions & 5 deletions pkcs8/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,14 @@ use {
};

#[cfg(feature = "pem")]
use {crate::LineEnding, alloc::string::String, der::zeroize::Zeroizing};

#[cfg(feature = "pem")]
use der::pem::PemLabel;
use {
crate::LineEnding,
alloc::string::String,
der::{
pem::{self, PemLabel},
zeroize::Zeroizing,
},
};

#[cfg(feature = "std")]
use std::path::Path;
Expand Down Expand Up @@ -43,8 +47,11 @@ pub trait DecodePrivateKey: Sized {
/// ```
#[cfg(feature = "pem")]
fn from_pkcs8_pem(s: &str) -> Result<Self> {
let (label, doc) = SecretDocument::from_pem(s)?;
// Validate PEM label
let label = pem::decode_label(s.as_bytes())?;
PrivateKeyInfo::validate_pem_label(label)?;

let doc = SecretDocument::from_pem(s)?.1;
Self::from_pkcs8_der(doc.as_bytes())
}

Expand Down

0 comments on commit 47a73cc

Please sign in to comment.