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}
11
12#[derive(Debug, PartialEq, Hash, Copy, Clone, Serialize, Deserialize)]
14pub enum Algorithm {
15 HS256,
17 HS384,
19 HS512,
21
22 ES256,
24 ES384,
26
27 RS256,
29 RS384,
31 RS512,
33
34 PS256,
36 PS384,
38 PS512,
40}
41
42impl Default for Algorithm {
43 fn default() -> Self {
44 Algorithm::HS256
45 }
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 _ => Err(ErrorKind::InvalidAlgorithmName.into()),
64 }
65 }
66}
67
68impl Algorithm {
69 pub(crate) fn family(self) -> AlgorithmFamily {
70 match self {
71 Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512 => AlgorithmFamily::Hmac,
72 Algorithm::RS256
73 | Algorithm::RS384
74 | Algorithm::RS512
75 | Algorithm::PS256
76 | Algorithm::PS384
77 | Algorithm::PS512 => AlgorithmFamily::Rsa,
78 Algorithm::ES256 | Algorithm::ES384 => AlgorithmFamily::Ec,
79 }
80 }
81}
82
83#[cfg(test)]
84mod tests {
85 use super::*;
86
87 #[test]
88 fn generate_algorithm_enum_from_str() {
89 assert!(Algorithm::from_str("HS256").is_ok());
90 assert!(Algorithm::from_str("HS384").is_ok());
91 assert!(Algorithm::from_str("HS512").is_ok());
92 assert!(Algorithm::from_str("RS256").is_ok());
93 assert!(Algorithm::from_str("RS384").is_ok());
94 assert!(Algorithm::from_str("RS512").is_ok());
95 assert!(Algorithm::from_str("PS256").is_ok());
96 assert!(Algorithm::from_str("PS384").is_ok());
97 assert!(Algorithm::from_str("PS512").is_ok());
98 assert!(Algorithm::from_str("").is_err());
99 }
100}