jsonwebtoken/
algorithms.rs
1use crate::errors::{Error, ErrorKind, Result};
2use serde::{Deserialize, Serialize};
3use std::str::FromStr;
4
5#[derive(Debug, Eq, PartialEq, Copy, Clone, Serialize, Deserialize)]
6pub(crate) enum AlgorithmFamily {
7 Hmac,
8 Rsa,
9 Ec,
10 Ed,
11}
12
13#[allow(clippy::upper_case_acronyms)]
15#[derive(Debug, Default, PartialEq, Eq, Hash, Copy, Clone, Serialize, Deserialize)]
16pub enum Algorithm {
17 #[default]
19 HS256,
20 HS384,
22 HS512,
24
25 ES256,
27 ES384,
29
30 RS256,
32 RS384,
34 RS512,
36
37 PS256,
39 PS384,
41 PS512,
43
44 EdDSA,
46}
47
48impl FromStr for Algorithm {
49 type Err = Error;
50 fn from_str(s: &str) -> Result<Self> {
51 match s {
52 "HS256" => Ok(Algorithm::HS256),
53 "HS384" => Ok(Algorithm::HS384),
54 "HS512" => Ok(Algorithm::HS512),
55 "ES256" => Ok(Algorithm::ES256),
56 "ES384" => Ok(Algorithm::ES384),
57 "RS256" => Ok(Algorithm::RS256),
58 "RS384" => Ok(Algorithm::RS384),
59 "PS256" => Ok(Algorithm::PS256),
60 "PS384" => Ok(Algorithm::PS384),
61 "PS512" => Ok(Algorithm::PS512),
62 "RS512" => Ok(Algorithm::RS512),
63 "EdDSA" => Ok(Algorithm::EdDSA),
64 _ => Err(ErrorKind::InvalidAlgorithmName.into()),
65 }
66 }
67}
68
69impl Algorithm {
70 pub(crate) fn family(self) -> AlgorithmFamily {
71 match self {
72 Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512 => AlgorithmFamily::Hmac,
73 Algorithm::RS256
74 | Algorithm::RS384
75 | Algorithm::RS512
76 | Algorithm::PS256
77 | Algorithm::PS384
78 | Algorithm::PS512 => AlgorithmFamily::Rsa,
79 Algorithm::ES256 | Algorithm::ES384 => AlgorithmFamily::Ec,
80 Algorithm::EdDSA => AlgorithmFamily::Ed,
81 }
82 }
83}
84
85#[cfg(test)]
86mod tests {
87 use wasm_bindgen_test::wasm_bindgen_test;
88
89 use super::*;
90
91 #[test]
92 #[wasm_bindgen_test]
93 fn generate_algorithm_enum_from_str() {
94 assert!(Algorithm::from_str("HS256").is_ok());
95 assert!(Algorithm::from_str("HS384").is_ok());
96 assert!(Algorithm::from_str("HS512").is_ok());
97 assert!(Algorithm::from_str("RS256").is_ok());
98 assert!(Algorithm::from_str("RS384").is_ok());
99 assert!(Algorithm::from_str("RS512").is_ok());
100 assert!(Algorithm::from_str("PS256").is_ok());
101 assert!(Algorithm::from_str("PS384").is_ok());
102 assert!(Algorithm::from_str("PS512").is_ok());
103 assert!(Algorithm::from_str("").is_err());
104 }
105}