use crate::error::{JoseError, Result};
use crate::jwk::Jwk;
use zeroize::Zeroizing;
const LABEL_PRIVATE: &str = "PRIVATE KEY";
const LABEL_PUBLIC: &str = "PUBLIC KEY";
const LABEL_RSA_PRIVATE: &str = "RSA PRIVATE KEY";
const MAX_PEM_LINE_LEN: usize = 64;
const LABEL_RSA_PUBLIC: &str = "RSA PUBLIC KEY";
const LABEL_EC_PRIVATE: &str = "EC PRIVATE KEY";
pub(crate) const LABEL_CERTIFICATE: &str = "CERTIFICATE";
pub(crate) const LABEL_ENCRYPTED_PRIVATE: &str = "ENCRYPTED PRIVATE KEY";
const KNOWN_BUT_UNSUPPORTED: &[(&str, &str)] = &[
(
"CERTIFICATE",
"an X.509 certificate; extract the public key through the certificate entry point",
),
(
"NEW CERTIFICATE REQUEST",
"a PKCS#10 certification request, not a key",
),
(
"PUBLIC KEY PARAMETERS",
"an SPKI group parameter set, not a key",
),
];
pub fn jwk_from_pem(text: &str) -> Result<Jwk> {
let (label, der) = decompose(text)?;
match label {
LABEL_PRIVATE => super::import::jwk_from_pkcs8_der(&der),
LABEL_PUBLIC => super::import::jwk_from_spki_der(&der),
LABEL_RSA_PRIVATE => super::import::jwk_from_pkcs1_der(&der),
LABEL_RSA_PUBLIC => super::import::jwk_from_pkcs1_public_der(&der),
LABEL_EC_PRIVATE => super::import::jwk_from_sec1_der(&der),
LABEL_CERTIFICATE => Err(JoseError::InvalidToken(
"PEM \"CERTIFICATE\" is an X.509 certificate, not a key; extract its subject public \
key with `jwk::public_jwk_from_certificate_pem`, which does not and cannot validate \
the certificate"
.into(),
)),
LABEL_ENCRYPTED_PRIVATE => Err(JoseError::InvalidToken(
"PEM \"ENCRYPTED PRIVATE KEY\" is a password-encrypted PKCS#8 key and needs the \
password-carrying entry point `jwk::jwk_from_encrypted_pkcs8_pem`"
.into(),
)),
other => Err(unsupported_label(other)),
}
}
pub fn jwk_from_pkcs8_pem(text: &str) -> Result<Jwk> {
let (label, der) = decompose(text)?;
if label != LABEL_PRIVATE {
return Err(JoseError::InvalidToken(format!(
"expected a PEM \"{LABEL_PRIVATE}\" block and found \"{label}\""
)));
}
super::import::jwk_from_pkcs8_der(&der)
}
pub fn jwk_from_spki_pem(text: &str) -> Result<Jwk> {
let (label, der) = decompose(text)?;
if label != LABEL_PUBLIC {
return Err(JoseError::InvalidToken(format!(
"expected a PEM \"{LABEL_PUBLIC}\" block and found \"{label}\""
)));
}
super::import::jwk_from_spki_der(&der)
}
pub fn private_pem_from_jwk(jwk: &Jwk) -> Result<String> {
if !has_private_material(jwk) {
return Err(JoseError::Key(
"PEM private export needs a key with its private part; this JWK has none. Use \
public_pem_from_jwk for the public half"
.into(),
));
}
let key = super::convert::jwk_to_software_key(jwk)?;
let der = key.export_private()?;
encode(LABEL_PRIVATE, &pkcs8_portable_form(&der)?)
}
pub(crate) fn pkcs8_portable_form(der: &[u8]) -> Result<Zeroizing<Vec<u8>>> {
use pkcs8::der::{Decode, Encode};
let info = pkcs8::PrivateKeyInfoRef::from_der(der).map_err(|e| {
JoseError::Key(format!(
"PKCS#8 export from the backend did not parse: {e:?}"
))
})?;
if info.public_key.is_none() {
return Ok(Zeroizing::new(der.to_vec()));
}
let slim = pkcs8::PrivateKeyInfoRef::new(info.algorithm, info.private_key);
let encoded_len = slim
.encoded_len()
.and_then(usize::try_from)
.map_err(|e| JoseError::Key(format!("PKCS#8 re-encoding length failed: {e:?}")))?;
let mut encoded = Zeroizing::new(vec![0; encoded_len]);
slim.encode_to_slice(&mut encoded)
.map_err(|e| JoseError::Key(format!("PKCS#8 re-encoding failed: {e:?}")))?;
Ok(encoded)
}
pub fn public_pem_from_jwk(jwk: &Jwk) -> Result<String> {
if let Some(refusal) = spki_refusal(jwk) {
return Err(JoseError::Key(refusal));
}
let key = super::convert::jwk_to_software_key(jwk)?;
let der = key.export_spki_der()?;
encode(LABEL_PUBLIC, &der)
}
fn spki_refusal(jwk: &Jwk) -> Option<String> {
let crv = jwk.crv.as_deref().unwrap_or("");
match (jwk.kty.as_str(), crv) {
("OKP", crv) if !matches!(crv, "Ed25519" | "Ed448") => Some(format!(
"{crv} public keys have no SPKI encoding in this backend — the public value is a \
bare coordinate, and wrapping it in a hand-made SPKI header would produce a file \
that claims a structure it does not have"
)),
_ => None,
}
}
fn has_private_material(jwk: &Jwk) -> bool {
match jwk.kty.as_str() {
"RSA" | "EC" | "OKP" => jwk.d.is_some(),
"oct" => jwk.k.is_some(),
_ => false,
}
}
fn unsupported_label(label: &str) -> JoseError {
match KNOWN_BUT_UNSUPPORTED
.iter()
.find(|(known, _)| *known == label)
{
Some((known, reason)) => JoseError::InvalidToken(format!(
"PEM block \"{known}\" is {reason}; this crate reads \"{LABEL_PRIVATE}\" \
(PKCS#8) and \"{LABEL_PUBLIC}\" (SPKI)"
)),
None => JoseError::InvalidToken(format!(
"unrecognized PEM block \"{label}\"; this crate reads \"{LABEL_PRIVATE}\" \
(PKCS#8) and \"{LABEL_PUBLIC}\" (SPKI)"
)),
}
}
pub(crate) fn decompose(text: &str) -> Result<(&str, Zeroizing<Vec<u8>>)> {
crate::ensure_emit_size(text.len())?;
if let Some(reason) = armor_problem(text) {
return Err(JoseError::InvalidToken(reason));
}
let input = text.trim().as_bytes();
let mut der = Zeroizing::new(vec![0; input.len()]);
let (label, decoded) = pem_rfc7468::decode(input, &mut der).map_err(armor_error)?;
let decoded_len = decoded.len();
der.truncate(decoded_len);
Ok((label, der))
}
fn armor_problem(text: &str) -> Option<String> {
let begin = "-----BEGIN ";
let first_begin = text.find(begin).ok_or(0);
let Ok(first_begin) = first_begin else {
return None;
};
if !text[..first_begin].chars().all(char::is_whitespace) {
return Some(
"PEM input has text before the -----BEGIN line; this crate reads a key file, not \
a document containing one"
.into(),
);
}
let blocks = text.matches(begin).count();
if blocks > 1 {
return Some(format!(
"PEM input contains {blocks} blocks; exactly one key is expected, so say which \
one by passing one block"
));
}
if let Some(long) = text
.lines()
.find(|line| line.len() > 64 && !line.starts_with("-----"))
{
return Some(format!(
"PEM base64 lines are limited to {} characters (RFC 7468 §3); this one is {}",
MAX_PEM_LINE_LEN,
long.len()
));
}
if let Some(end_at) = text.rfind("-----END ") {
let newline = text[end_at..].find('\n').map(|i| end_at + i);
let tail = match newline {
Some(after) => &text[after + 1..],
None => "",
};
if !tail.chars().all(char::is_whitespace) {
return Some(
"PEM input has text after the -----END line; a key file ends with its key".into(),
);
}
}
None
}
fn armor_error(err: pem_rfc7468::Error) -> JoseError {
use pem_rfc7468::Error as Pem;
match err {
Pem::HeaderDisallowed => JoseError::InvalidToken(
"PEM headers (Proc-Type / DEK-Info) mark a password-encrypted key in the legacy \
OpenSSL scheme; this crate does not decrypt that form"
.into(),
),
other => JoseError::InvalidToken(format!(
"malformed RFC 7468 PEM input ({other:?}); one base64 block between \
-----BEGIN and -----END, canonical padding, no text around it"
)),
}
}
pub(crate) fn encode_with_label(label: &str, der: &[u8]) -> Result<String> {
encode(label, der)
}
fn encode(label: &str, der: &[u8]) -> Result<String> {
pem_rfc7468::encode_string(label, pem_rfc7468::LineEnding::LF, der)
.map_err(|e| JoseError::Key(format!("PEM encoding failed: {e:?}")))
}