Skip to main content

json_web_token/
signer.rs

1use basekit::base64::{Base64EncodeConfig, ALPHABET_BASE64_URL, PADDING_BASE64};
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: Base64EncodeConfig =
11        Base64EncodeConfig::new(&ALPHABET_BASE64_URL, PADDING_BASE64);
12}
13
14#[derive(Debug, Clone)]
15pub enum SigningAlgorithm {
16    HS256,
17}
18
19impl Default for SigningAlgorithm {
20    #[inline]
21    fn default() -> Self {
22        SigningAlgorithm::HS256
23    }
24}
25
26impl ToString for SigningAlgorithm {
27    #[inline]
28    fn to_string(&self) -> String {
29        match self {
30            SigningAlgorithm::HS256 => "HS256".into(),
31        }
32    }
33}
34
35impl Serialize for SigningAlgorithm {
36    #[inline]
37    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
38    where
39        S: Serializer,
40    {
41        serializer.serialize_str(&self.to_string())
42    }
43}
44
45#[derive(Clone)]
46pub enum Signer {
47    HmacSha256(Hmac<Sha256>),
48}
49
50impl Signer {
51    pub fn header(&self) -> Header {
52        match self {
53            Signer::HmacSha256(_) => Header {
54                algorithm: SigningAlgorithm::HS256,
55                r#type: Some("JWT".into()),
56            },
57        }
58    }
59
60    pub fn signature_length(&self) -> usize {
61        match self {
62            Signer::HmacSha256(_) => 32,
63        }
64    }
65
66    pub fn signature(self, bytes: &[u8]) -> Vec<u8> {
67        match self {
68            Signer::HmacSha256(mut signer) => {
69                signer.update(bytes);
70                signer.finalize().into_bytes().to_vec()
71            }
72        }
73    }
74}