warg_crypto/signing/
signature.rs1use super::{SignatureAlgorithm, SignatureAlgorithmParseError};
2use base64::{engine::general_purpose::STANDARD, Engine};
3use core::fmt;
4use p256;
5use serde::{Deserialize, Serialize};
6use signature::Error as SignatureError;
7use std::str::FromStr;
8use thiserror::Error;
9
10#[derive(Clone, Debug, PartialEq, Eq)]
11pub enum Signature {
12 P256(p256::ecdsa::Signature),
13}
14
15impl Signature {
16 pub fn signature_algorithm(&self) -> SignatureAlgorithm {
18 match self {
19 Signature::P256(_) => SignatureAlgorithm::EcdsaP256,
20 }
21 }
22
23 pub fn bytes(&self) -> Vec<u8> {
25 match self {
26 Signature::P256(key) => key.to_der().to_bytes().to_vec(),
27 }
28 }
29}
30
31impl fmt::Display for Signature {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 write!(
34 f,
35 "{}:{}",
36 self.signature_algorithm(),
37 STANDARD.encode(self.bytes())
38 )
39 }
40}
41
42impl FromStr for Signature {
43 type Err = SignatureParseError;
44
45 fn from_str(s: &str) -> Result<Self, Self::Err> {
46 let parts: Vec<&str> = s.split(|c| c == ':').collect();
47 if parts.len() != 2 {
48 return Err(SignatureParseError::IncorrectStructure(parts.len()));
49 }
50 let algo = parts[0].parse::<SignatureAlgorithm>()?;
51 let bytes = STANDARD.decode(parts[1])?;
52
53 let sig = match algo {
54 SignatureAlgorithm::EcdsaP256 => {
55 Signature::P256(p256::ecdsa::Signature::from_der(&bytes)?)
56 }
57 };
58
59 Ok(sig)
60 }
61}
62
63impl Serialize for Signature {
64 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
65 serializer.serialize_str(&self.to_string())
66 }
67}
68
69impl<'de> Deserialize<'de> for Signature {
70 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
71 where
72 D: serde::Deserializer<'de>,
73 {
74 let string: String = String::deserialize(deserializer)?;
75 Self::from_str(&string).map_err(serde::de::Error::custom)
76 }
77}
78
79#[derive(Error, Debug)]
80pub enum SignatureParseError {
81 #[error("expected 2 parts, found {0}")]
82 IncorrectStructure(usize),
83
84 #[error("unable to parse signature algorithm")]
85 SignatureAlgorithmParseError(#[from] SignatureAlgorithmParseError),
86
87 #[error("base64 decode failed")]
88 Base64DecodeError(#[from] base64::DecodeError),
89
90 #[error("signature could not be constructed from bytes")]
91 SignatureError(#[from] SignatureError),
92}