use p12_keystore::{
Certificate as Pkcs12Certificate, KeyStore, KeyStoreEntry, Pkcs12ImportPolicy, PrivateKey,
PrivateKeyChain,
};
use crate::{Error, Result};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Identity {
pub certificate: Vec<u8>,
pub private_key: Vec<u8>,
pub friendly_name: Option<String>,
}
impl Identity {
pub fn from_pem(data: &[u8]) -> Result<Self> {
Ok(Self {
certificate: crate::der::pem_block(data, crate::der::PEM_CERTIFICATE)?,
private_key: crate::der::decode_private_key(data)?,
friendly_name: None,
})
}
pub fn to_pem(&self) -> String {
let mut output = crate::der::to_pem(crate::der::PEM_CERTIFICATE, &self.certificate);
output.push_str(&crate::der::to_pem(
crate::der::PEM_PRIVATE_KEY,
&self.private_key,
));
output
}
pub fn to_pkcs12(&self, password: &str) -> Result<Vec<u8>> {
encode(self, password)
}
pub fn to_pkcs12_pem(&self, password: &str) -> Result<String> {
Ok(crate::der::to_pem(
crate::der::PEM_PKCS12,
&self.to_pkcs12(password)?,
))
}
}
pub fn is_combined_pem(data: &[u8]) -> bool {
std::str::from_utf8(data).is_ok_and(|text| {
text.contains("-----BEGIN CERTIFICATE-----")
&& (text.contains("-----BEGIN PRIVATE KEY-----")
|| text.contains("-----BEGIN RSA PRIVATE KEY-----"))
})
}
pub fn decode_identity(data: &[u8], password: Option<&str>) -> Result<Identity> {
if is_combined_pem(data) {
return Identity::from_pem(data);
}
let password =
password.ok_or_else(|| Error::other("a PKCS#12 identity requires a password"))?;
decode(&crate::der::pem_or_der(data)?, password)
}
pub fn decode(data: &[u8], password: &str) -> Result<Identity> {
let store = KeyStore::from_pkcs12(data, password, Pkcs12ImportPolicy::Strict).map_err(
|error| {
Error::other(format!(
"could not decode PKCS#12 (the password may be wrong, or the container uses an unsupported algorithm): {error}"
))
},
)?;
let mut identities = store.entries().filter_map(|(alias, entry)| match entry {
KeyStoreEntry::PrivateKeyChain(chain) => Some((alias, chain)),
_ => None,
});
let Some((alias, chain)) = identities.next() else {
return Err(Error::other(
"the PKCS#12 container has no private key with a matching certificate",
));
};
if identities.next().is_some() {
return Err(Error::other(
"the PKCS#12 container contains more than one identity",
));
}
let certificate = chain
.certs()
.first()
.ok_or_else(|| Error::other("the PKCS#12 private key has no matching leaf certificate"))?;
Ok(Identity {
certificate: certificate.as_der().to_vec(),
private_key: chain.key().as_der().to_vec(),
friendly_name: (!alias.is_empty()).then(|| alias.to_string()),
})
}
pub fn encode(identity: &Identity, password: &str) -> Result<Vec<u8>> {
let certificate = Pkcs12Certificate::from_der(&identity.certificate)
.map_err(|error| Error::other(format!("could not encode PKCS#12 certificate: {error}")))?;
let private_key = PrivateKey::from_der(&identity.private_key)
.map_err(|error| Error::other(format!("could not encode PKCS#12 private key: {error}")))?;
let public_key_hash = crate::der::Certificate::parse(&identity.certificate)?.public_key_hash();
let alias = identity.friendly_name.as_deref().unwrap_or("identity");
let chain = PrivateKeyChain::new(public_key_hash.as_slice(), private_key, [certificate]);
let mut store = KeyStore::new();
store.add_entry(alias, KeyStoreEntry::PrivateKeyChain(chain));
store
.writer(password)
.write()
.map_err(|error| Error::other(format!("could not encode PKCS#12: {error}")))
}
#[cfg(test)]
mod identity_tests {
use super::*;
fn pkcs1_rsa_key() -> Vec<u8> {
let mut key = vec![0x30, 0x1b, 0x02, 0x01, 0x00];
for value in 1..=8 {
key.extend_from_slice(&[0x02, 0x01, value]);
}
key
}
#[test]
fn combined_pem_round_trips_through_the_high_level_api() {
let identity = Identity {
certificate: vec![1, 2, 3],
private_key: crate::der::decode_private_key(&pkcs1_rsa_key()).unwrap(),
friendly_name: None,
};
let pem = identity.to_pem();
assert_eq!(decode_identity(pem.as_bytes(), None).unwrap(), identity);
}
#[test]
fn combined_pem_accepts_a_traditional_rsa_private_key() {
let certificate = vec![1, 2, 3];
let pkcs1 = pkcs1_rsa_key();
let pem = format!(
"{}{}",
crate::der::to_pem(crate::der::PEM_CERTIFICATE, &certificate),
crate::der::to_pem("RSA PRIVATE KEY", &pkcs1),
);
assert!(is_combined_pem(pem.as_bytes()));
let identity = decode_identity(pem.as_bytes(), None).expect("decode combined PEM");
assert_eq!(identity.certificate, certificate);
let key = crate::der::PrivateKeyInfo::parse(&identity.private_key).expect("parse PKCS#8");
assert!(key.is_rsa());
assert_eq!(key.private_key, pkcs1);
}
#[test]
fn a_container_requires_an_explicit_password() {
assert!(decode_identity(&[0x30, 0], None).is_err());
}
}