1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
use super::AlgorithmName;
use crate::{
  error::{HttpSigError, HttpSigResult},
  trace::*,
};
use base64::{engine::general_purpose, Engine as _};
use hmac::{Hmac, Mac};
use sha2::{Digest, Sha256};

type HmacSha256 = Hmac<sha2::Sha256>;

/* -------------------------------- */
#[derive(Debug, Clone)]
/// Shared key for http signature
/// Name conventions follow [Section 6.2.2, RFC9421](https://datatracker.ietf.org/doc/html/rfc9421#section-6.2.2)
pub enum SharedKey {
  /// hmac-sha256
  HmacSha256(Vec<u8>),
}

impl SharedKey {
  /// Create a new shared key from base64 encoded string
  pub fn from_base64(key: &str) -> HttpSigResult<Self> {
    debug!("Create SharedKey from base64 string");
    let key = general_purpose::STANDARD.decode(key)?;
    Ok(SharedKey::HmacSha256(key))
  }
}

impl super::SigningKey for SharedKey {
  /// Sign the data
  fn sign(&self, data: &[u8]) -> HttpSigResult<Vec<u8>> {
    match self {
      SharedKey::HmacSha256(key) => {
        debug!("Sign HmacSha256");
        let mut mac = HmacSha256::new_from_slice(key).unwrap();
        mac.update(data);
        Ok(mac.finalize().into_bytes().to_vec())
      }
    }
  }
  /// Get the key id
  fn key_id(&self) -> String {
    use super::VerifyingKey;
    <Self as VerifyingKey>::key_id(self)
  }
  /// Get the algorithm name
  fn alg(&self) -> AlgorithmName {
    use super::VerifyingKey;
    <Self as VerifyingKey>::alg(self)
  }
}
impl super::VerifyingKey for SharedKey {
  /// Verify the mac
  fn verify(&self, data: &[u8], expected_mac: &[u8]) -> HttpSigResult<()> {
    use super::SigningKey;
    debug!("Verify HmacSha256");
    let calcurated_mac = self.sign(data)?;
    if calcurated_mac == expected_mac {
      Ok(())
    } else {
      Err(HttpSigError::InvalidSignature("Invalid MAC".to_string()))
    }
  }

  /// Get the key id
  fn key_id(&self) -> String {
    match self {
      SharedKey::HmacSha256(key) => {
        let mut hasher = <Sha256 as Digest>::new();
        hasher.update(key);
        let hash = hasher.finalize();
        general_purpose::STANDARD.encode(hash)
      }
    }
  }
  /// Get the algorithm name
  fn alg(&self) -> AlgorithmName {
    match self {
      SharedKey::HmacSha256(_) => AlgorithmName::HmacSha256,
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn symmetric_key_works() {
    use super::super::{SigningKey, VerifyingKey};
    let inner = b"01234567890123456789012345678901";
    let key = SharedKey::HmacSha256(inner.to_vec());
    let data = b"hello";
    let signature = key.sign(data).unwrap();
    let res = key.verify(data, &signature);
    assert!(res.is_ok());
  }
}