json_web_token/
signer.rs

1use b64_url::{B64Config, B64ConfigPadding};
2use hmac::{Hmac, Mac};
3use lazy_static::lazy_static;
4use serde::{Serialize, Serializer};
5use sha2::Sha256;
6
7use crate::Header;
8
9lazy_static! {
10    static ref B64_CONFIG: B64Config = B64Config {
11        padding: B64ConfigPadding { omit: true }
12    };
13}
14
15#[derive(Debug, Clone)]
16pub enum SigningAlgorithm {
17    HS256,
18}
19
20impl Default for SigningAlgorithm {
21    #[inline]
22    fn default() -> Self {
23        SigningAlgorithm::HS256
24    }
25}
26
27impl ToString for SigningAlgorithm {
28    #[inline]
29    fn to_string(&self) -> String {
30        match self {
31            SigningAlgorithm::HS256 => "HS256".into(),
32        }
33    }
34}
35
36impl Serialize for SigningAlgorithm {
37    #[inline]
38    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
39    where
40        S: Serializer,
41    {
42        serializer.serialize_str(&self.to_string())
43    }
44}
45
46#[derive(Clone)]
47pub enum Signer {
48    HmacSha256(Hmac<Sha256>),
49}
50
51impl Signer {
52    pub fn header(&self) -> Header {
53        match self {
54            Signer::HmacSha256(_) => Header {
55                algorithm: SigningAlgorithm::HS256,
56                r#type: Some("JWT".into()),
57            },
58        }
59    }
60
61    pub fn signature_length(&self) -> usize {
62        match self {
63            Signer::HmacSha256(_) => 32,
64        }
65    }
66
67    pub fn signature(self, bytes: &[u8]) -> Vec<u8> {
68        match self {
69            Signer::HmacSha256(mut signer) => {
70                signer.update(bytes);
71                signer.finalize().into_bytes().to_vec()
72            }
73        }
74    }
75}