use crate::{AlgorithmIdentifier, Attributes, Error, Result, Version};
use core::{
convert::{TryFrom, TryInto},
fmt,
};
use der::{
asn1::{Any, BitString, ContextSpecific, OctetString},
Decodable, Encodable, Message, TagNumber,
};
#[cfg(feature = "alloc")]
use crate::PrivateKeyDocument;
#[cfg(feature = "encryption")]
use {
crate::EncryptedPrivateKeyDocument,
rand_core::{CryptoRng, RngCore},
};
#[cfg(feature = "pem")]
use {
crate::{error, pem, LineEnding},
alloc::string::String,
zeroize::Zeroizing,
};
const ATTRIBUTES_TAG: TagNumber = TagNumber::new(0);
const PUBLIC_KEY_TAG: TagNumber = TagNumber::new(1);
#[cfg(feature = "pem")]
pub(crate) const PEM_TYPE_LABEL: &str = "PRIVATE KEY";
#[derive(Clone)]
pub struct PrivateKeyInfo<'a> {
pub algorithm: AlgorithmIdentifier<'a>,
pub private_key: &'a [u8],
pub attributes: Option<Attributes<'a>>,
pub public_key: Option<&'a [u8]>,
}
impl<'a> PrivateKeyInfo<'a> {
pub fn new(algorithm: AlgorithmIdentifier<'a>, private_key: &'a [u8]) -> Self {
Self {
algorithm,
private_key,
attributes: None,
public_key: None,
}
}
pub fn version(&self) -> Version {
if self.public_key.is_some() {
Version::V2
} else {
Version::V1
}
}
#[cfg(feature = "encryption")]
#[cfg_attr(docsrs, doc(cfg(feature = "encryption")))]
pub fn encrypt(
&self,
rng: impl CryptoRng + RngCore,
password: impl AsRef<[u8]>,
) -> Result<EncryptedPrivateKeyDocument> {
PrivateKeyDocument::from(self).encrypt(rng, password)
}
#[cfg(feature = "alloc")]
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub fn to_der(&self) -> PrivateKeyDocument {
self.into()
}
#[cfg(feature = "pem")]
#[cfg_attr(docsrs, doc(cfg(feature = "pem")))]
pub fn to_pem(&self) -> Zeroizing<String> {
self.to_pem_with_le(LineEnding::default())
}
#[cfg(feature = "pem")]
#[cfg_attr(docsrs, doc(cfg(feature = "pem")))]
pub fn to_pem_with_le(&self, line_ending: LineEnding) -> Zeroizing<String> {
Zeroizing::new(
pem::encode_string(PEM_TYPE_LABEL, line_ending, self.to_der().as_ref())
.expect(error::PEM_ENCODING_MSG),
)
}
}
impl<'a> TryFrom<&'a [u8]> for PrivateKeyInfo<'a> {
type Error = Error;
fn try_from(bytes: &'a [u8]) -> Result<Self> {
Ok(Self::from_der(bytes)?)
}
}
impl<'a> TryFrom<Any<'a>> for PrivateKeyInfo<'a> {
type Error = der::Error;
fn try_from(any: Any<'a>) -> der::Result<PrivateKeyInfo<'a>> {
any.sequence(|decoder| {
let version = Version::decode(decoder)?;
let algorithm = decoder.decode()?;
let private_key = decoder.octet_string()?.into();
let attributes = decoder
.context_specific(ATTRIBUTES_TAG)?
.map(TryInto::try_into)
.transpose()?;
let public_key = decoder
.context_specific(PUBLIC_KEY_TAG)?
.map(|any| any.bit_string())
.transpose()?
.map(|bs| bs.as_bytes());
if version.has_public_key() != public_key.is_some() {
return Err(decoder.value_error(der::Tag::ContextSpecific(PUBLIC_KEY_TAG)));
}
while !decoder.is_finished() {
decoder.decode::<ContextSpecific<'_>>()?;
}
Ok(Self {
algorithm,
private_key,
attributes,
public_key,
})
})
}
}
impl<'a> Message<'a> for PrivateKeyInfo<'a> {
fn fields<F, T>(&self, f: F) -> der::Result<T>
where
F: FnOnce(&[&dyn Encodable]) -> der::Result<T>,
{
f(&[
&u8::from(self.version()),
&self.algorithm,
&OctetString::new(self.private_key)?,
&self.attributes.map(|value| ContextSpecific {
tag_number: ATTRIBUTES_TAG,
value: value.into(),
}),
&self
.public_key
.map(|pk| {
BitString::new(pk).map(|value| ContextSpecific {
tag_number: PUBLIC_KEY_TAG,
value: value.into(),
})
})
.transpose()?,
])
}
}
impl<'a> fmt::Debug for PrivateKeyInfo<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PrivateKeyInfo")
.field("version", &self.version())
.field("algorithm", &self.algorithm)
.field("attributes", &self.attributes)
.field("public_key", &self.public_key)
.finish() }
}