jsonwebtoken_rustcrypto/
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, Default)]
14pub enum Algorithm {
15 #[default]
17 HS256,
18 HS384,
20 HS512,
22
23 ES256,
25 ES384,
27
28 RS256,
30 RS384,
32 RS512,
34 PS256,
36 PS384,
38 PS512,
40}
41
42impl FromStr for Algorithm {
43 type Err = Error;
44 fn from_str(s: &str) -> Result<Self> {
45 match s {
46 "HS256" => Ok(Algorithm::HS256),
47 "HS384" => Ok(Algorithm::HS384),
48 "HS512" => Ok(Algorithm::HS512),
49 "ES256" => Ok(Algorithm::ES256),
50 "ES384" => Ok(Algorithm::ES384),
51 "RS256" => Ok(Algorithm::RS256),
52 "RS384" => Ok(Algorithm::RS384),
53 "PS256" => Ok(Algorithm::PS256),
54 "PS384" => Ok(Algorithm::PS384),
55 "PS512" => Ok(Algorithm::PS512),
56 "RS512" => Ok(Algorithm::RS512),
57 _ => Err(ErrorKind::InvalidAlgorithmName.into()),
58 }
59 }
60}
61
62#[cfg(test)]
63mod tests {
64 use super::*;
65
66 #[test]
67 fn generate_algorithm_enum_from_str() {
68 assert!(Algorithm::from_str("HS256").is_ok());
69 assert!(Algorithm::from_str("HS384").is_ok());
70 assert!(Algorithm::from_str("HS512").is_ok());
71 assert!(Algorithm::from_str("RS256").is_ok());
72 assert!(Algorithm::from_str("RS384").is_ok());
73 assert!(Algorithm::from_str("RS512").is_ok());
74 assert!(Algorithm::from_str("PS256").is_ok());
75 assert!(Algorithm::from_str("PS384").is_ok());
76 assert!(Algorithm::from_str("PS512").is_ok());
77 assert!(Algorithm::from_str("").is_err());
78 }
79}