Skip to main content

httpsig/crypto/
mod.rs

1mod asymmetric;
2mod symmetric;
3
4use crate::error::{HttpSigError, HttpSigResult};
5
6pub use asymmetric::{PublicKey, SecretKey};
7pub use symmetric::SharedKey;
8
9#[derive(Debug, PartialEq, Eq)]
10/// Algorithm names
11pub enum AlgorithmName {
12  HmacSha256,
13  EcdsaP256Sha256,
14  EcdsaP384Sha384,
15  Ed25519,
16  #[cfg(feature = "rsa-signature")]
17  RsaV1_5Sha256,
18  #[cfg(feature = "rsa-signature")]
19  RsaPssSha512,
20}
21
22impl AlgorithmName {
23  pub fn as_str(&self) -> &'static str {
24    match self {
25      AlgorithmName::HmacSha256 => "hmac-sha256",
26      AlgorithmName::EcdsaP256Sha256 => "ecdsa-p256-sha256",
27      AlgorithmName::EcdsaP384Sha384 => "ecdsa-p384-sha384",
28      AlgorithmName::Ed25519 => "ed25519",
29      #[cfg(feature = "rsa-signature")]
30      AlgorithmName::RsaV1_5Sha256 => "rsa-v1_5-sha256",
31      #[cfg(feature = "rsa-signature")]
32      AlgorithmName::RsaPssSha512 => "rsa-pss-sha512",
33    }
34  }
35}
36
37impl std::fmt::Display for AlgorithmName {
38  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39    write!(f, "{}", self.as_str())
40  }
41}
42
43impl core::str::FromStr for AlgorithmName {
44  type Err = HttpSigError;
45
46  fn from_str(s: &str) -> Result<Self, Self::Err> {
47    match s {
48      "hmac-sha256" => Ok(Self::HmacSha256),
49      "ecdsa-p256-sha256" => Ok(Self::EcdsaP256Sha256),
50      "ecdsa-p384-sha384" => Ok(Self::EcdsaP384Sha384),
51      "ed25519" => Ok(Self::Ed25519),
52      #[cfg(feature = "rsa-signature")]
53      "rsa-v1_5-sha256" => Ok(Self::RsaV1_5Sha256),
54      #[cfg(feature = "rsa-signature")]
55      "rsa-pss-sha512" => Ok(Self::RsaPssSha512),
56      _ => Err(HttpSigError::InvalidAlgorithmName(s.to_string())),
57    }
58  }
59}
60
61/// SigningKey trait
62pub trait SigningKey {
63  fn sign(&self, data: &[u8]) -> HttpSigResult<Vec<u8>>;
64  fn key_id(&self) -> String;
65  fn alg(&self) -> AlgorithmName;
66}
67
68/// VerifyingKey trait
69pub trait VerifyingKey {
70  fn verify(&self, data: &[u8], signature: &[u8]) -> HttpSigResult<()>;
71  fn key_id(&self) -> String;
72  fn alg(&self) -> AlgorithmName;
73}