twizzler_security/keys/
sig.rs1use core::fmt::Display;
2
3#[cfg(feature = "log")]
4use log::error;
5use p256::ecdsa::Signature as EcdsaSignature;
6
7use crate::{SecurityError, SigningScheme};
8
9const MAX_SIG_SIZE: usize = 128;
10
11#[derive(Copy, Clone, Debug, PartialEq, Eq)]
12pub struct Signature {
13 buf: [u8; MAX_SIG_SIZE],
15 pub len: usize,
16 scheme: SigningScheme,
17}
18
19impl Signature {
20 fn as_bytes(&self) -> &[u8] {
21 &self.buf[0..self.len]
22 }
23}
24
25impl Display for Signature {
26 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
27 write!(
28 f,
29 "Signature(scheme: {:?}, len: {}, bytes: ",
30 self.scheme, self.len
31 )?;
32 for byte in &self.buf[0..self.len] {
33 write!(f, "{:02x}", byte)?;
34 }
35 write!(f, ")")
36 }
37}
38
39impl From<EcdsaSignature> for Signature {
40 fn from(value: EcdsaSignature) -> Self {
41 let mut buf = [0_u8; MAX_SIG_SIZE];
42 let binding = value.to_bytes();
43 let slice = binding.as_slice();
44 buf[0..slice.len()].copy_from_slice(slice);
45
46 Self {
47 buf,
48 len: slice.len(),
49 scheme: SigningScheme::Ecdsa,
50 }
51 }
52}
53
54impl TryFrom<&Signature> for EcdsaSignature {
55 type Error = SecurityError;
56 fn try_from(value: &Signature) -> Result<Self, Self::Error> {
57 if value.scheme != SigningScheme::Ecdsa {
58 #[cfg(feature = "log")]
59 error!("Cannot convert Signature to EcdsaSignature due to scheme mismatch. SigningScheme: {:?}", value.scheme);
60 return Err(SecurityError::InvalidScheme);
61 }
62
63 Ok(EcdsaSignature::from_slice(value.as_bytes()).map_err(|_e| {
64 #[cfg(feature = "log")]
65 error!("Failed to construct a EcdsaSignature due to: {:?}", _e);
66 SecurityError::SignatureMismatch
67 })?)
68 }
69}