rsa/pss/
signature.rs

1pub use ::signature::SignatureEncoding;
2use spki::{
3    der::{asn1::BitString, Result as DerResult},
4    SignatureBitStringEncoding,
5};
6
7use crate::algorithms::pad::uint_to_be_pad;
8use alloc::{boxed::Box, string::ToString};
9use core::fmt::{Debug, Display, Formatter, LowerHex, UpperHex};
10use num_bigint::BigUint;
11
12/// RSASSA-PSS signatures as described in [RFC8017 § 8.1].
13///
14/// [RFC8017 § 8.1]: https://datatracker.ietf.org/doc/html/rfc8017#section-8.1
15#[derive(Clone, PartialEq, Eq)]
16pub struct Signature {
17    pub(super) inner: BigUint,
18    pub(super) len: usize,
19}
20
21impl SignatureEncoding for Signature {
22    type Repr = Box<[u8]>;
23}
24
25impl SignatureBitStringEncoding for Signature {
26    fn to_bitstring(&self) -> DerResult<BitString> {
27        BitString::new(0, self.to_vec())
28    }
29}
30
31impl TryFrom<&[u8]> for Signature {
32    type Error = signature::Error;
33
34    fn try_from(bytes: &[u8]) -> signature::Result<Self> {
35        Ok(Self {
36            len: bytes.len(),
37            inner: BigUint::from_bytes_be(bytes),
38        })
39    }
40}
41
42impl From<Signature> for Box<[u8]> {
43    fn from(signature: Signature) -> Box<[u8]> {
44        uint_to_be_pad(signature.inner, signature.len)
45            .expect("RSASSA-PKCS1-v1_5 length invariants should've been enforced")
46            .into_boxed_slice()
47    }
48}
49
50impl Debug for Signature {
51    fn fmt(&self, fmt: &mut Formatter<'_>) -> core::result::Result<(), core::fmt::Error> {
52        fmt.debug_tuple("Signature")
53            .field(&self.to_string())
54            .finish()
55    }
56}
57
58impl LowerHex for Signature {
59    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
60        write!(f, "{:x}", &self.inner)
61    }
62}
63
64impl UpperHex for Signature {
65    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
66        write!(f, "{:X}", &self.inner)
67    }
68}
69
70impl Display for Signature {
71    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
72        write!(f, "{:X}", self)
73    }
74}