jsonwebtoken/
algorithms.rs1use 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, PartialEq, Eq, Hash, Copy, Clone, Serialize, Deserialize)]
16pub enum Algorithm {
17 HS256,
19 HS384,
21 HS512,
23
24 ES256,
26 ES384,
28
29 RS256,
31 RS384,
33 RS512,
35
36 PS256,
38 PS384,
40 PS512,
42
43 EdDSA,
45}
46
47impl Default for Algorithm {
48 fn default() -> Self {
49 Algorithm::HS256
50 }
51}
52
53impl FromStr for Algorithm {
54 type Err = Error;
55 fn from_str(s: &str) -> Result<Self> {
56 match s {
57 "HS256" => Ok(Algorithm::HS256),
58 "HS384" => Ok(Algorithm::HS384),
59 "HS512" => Ok(Algorithm::HS512),
60 "ES256" => Ok(Algorithm::ES256),
61 "ES384" => Ok(Algorithm::ES384),
62 "RS256" => Ok(Algorithm::RS256),
63 "RS384" => Ok(Algorithm::RS384),
64 "PS256" => Ok(Algorithm::PS256),
65 "PS384" => Ok(Algorithm::PS384),
66 "PS512" => Ok(Algorithm::PS512),
67 "RS512" => Ok(Algorithm::RS512),
68 "EdDSA" => Ok(Algorithm::EdDSA),
69 _ => Err(ErrorKind::InvalidAlgorithmName.into()),
70 }
71 }
72}
73
74impl Algorithm {
75 pub(crate) fn family(self) -> AlgorithmFamily {
76 match self {
77 Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512 => AlgorithmFamily::Hmac,
78 Algorithm::RS256
79 | Algorithm::RS384
80 | Algorithm::RS512
81 | Algorithm::PS256
82 | Algorithm::PS384
83 | Algorithm::PS512 => AlgorithmFamily::Rsa,
84 Algorithm::ES256 | Algorithm::ES384 => AlgorithmFamily::Ec,
85 Algorithm::EdDSA => AlgorithmFamily::Ed,
86 }
87 }
88}
89
90#[cfg(test)]
91mod tests {
92 use super::*;
93
94 #[test]
95 fn generate_algorithm_enum_from_str() {
96 assert!(Algorithm::from_str("HS256").is_ok());
97 assert!(Algorithm::from_str("HS384").is_ok());
98 assert!(Algorithm::from_str("HS512").is_ok());
99 assert!(Algorithm::from_str("RS256").is_ok());
100 assert!(Algorithm::from_str("RS384").is_ok());
101 assert!(Algorithm::from_str("RS512").is_ok());
102 assert!(Algorithm::from_str("PS256").is_ok());
103 assert!(Algorithm::from_str("PS384").is_ok());
104 assert!(Algorithm::from_str("PS512").is_ok());
105 assert!(Algorithm::from_str("").is_err());
106 }
107}