use alloc::{boxed::Box, vec};
use core::borrow::Borrow;
use der::{
DecodeValue, EncodeValue, FixedTag, Length, Tag,
asn1::{OctetString, OctetStringRef},
oid::db::rfc6268,
};
use x509_cert::{attr::Attribute, time::Time};
use crate::signed_data::SignerInfo;
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct MessageDigest(pub OctetString);
impl MessageDigest {
#[inline]
pub fn as_bytes(&self) -> &[u8] {
self.0.as_bytes()
}
#[inline]
pub fn into_bytes(self) -> Box<[u8]> {
self.0.into_bytes()
}
#[inline]
pub fn len(&self) -> Length {
self.0.len()
}
#[cfg(feature = "digest")]
pub fn from_digest<D>(digest: D) -> der::Result<Self>
where
D: digest::Digest,
{
Ok(MessageDigest(OctetString::new(digest.finalize().to_vec())?))
}
#[inline]
pub fn as_octet_string_ref(&self) -> &OctetStringRef {
self.0.borrow()
}
}
impl AsRef<[u8]> for MessageDigest {
#[inline]
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl AsRef<OctetString> for MessageDigest {
#[inline]
fn as_ref(&self) -> &OctetString {
&self.0
}
}
impl<'a> DecodeValue<'a> for MessageDigest {
type Error = <OctetString as DecodeValue<'a>>::Error;
#[inline]
fn decode_value<R: der::Reader<'a>>(reader: &mut R, header: der::Header) -> der::Result<Self> {
OctetString::decode_value(reader, header).map(Self)
}
}
impl EncodeValue for MessageDigest {
#[inline]
fn value_len(&self) -> der::Result<Length> {
self.0.value_len()
}
#[inline]
fn encode_value(&self, writer: &mut impl der::Writer) -> der::Result<()> {
self.0.encode_value(writer)
}
}
impl FixedTag for MessageDigest {
const TAG: Tag = OctetString::TAG;
}
impl From<MessageDigest> for vec::Vec<u8> {
#[inline]
fn from(value: MessageDigest) -> vec::Vec<u8> {
value.0.into_bytes().into()
}
}
impl TryFrom<&Attribute> for MessageDigest {
type Error = der::Error;
fn try_from(attr: &Attribute) -> Result<Self, Self::Error> {
if attr.oid != rfc6268::ID_MESSAGE_DIGEST {
return Err(der::ErrorKind::OidUnknown { oid: attr.oid }.into());
}
if attr.values.len() != 1 {
return Err(der::ErrorKind::Value { tag: Tag::Set }.into());
}
let message_digest = attr
.values
.get(0)
.expect("Invariant violation, only one value is present in the attribute");
message_digest.decode_as::<OctetString>().map(Self)
}
}
pub type SigningTime = Time;
pub type Countersignature = SignerInfo;