identity_kit/jose/
algorithm.rs1use core::fmt;
4use core::str::FromStr;
5
6use serde::{Deserialize, Serialize};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
33#[non_exhaustive]
34pub enum JwsAlgorithm {
35 EdDSA,
37 ES256,
39 ES256K,
41 ES384,
43 RS256,
45 PS256,
47}
48
49impl JwsAlgorithm {
50 pub const ALL: &'static [JwsAlgorithm] = &[
52 Self::EdDSA,
53 Self::ES256,
54 Self::ES256K,
55 Self::ES384,
56 Self::RS256,
57 Self::PS256,
58 ];
59
60 pub const fn as_str(self) -> &'static str {
62 match self {
63 Self::EdDSA => "EdDSA",
64 Self::ES256 => "ES256",
65 Self::ES256K => "ES256K",
66 Self::ES384 => "ES384",
67 Self::RS256 => "RS256",
68 Self::PS256 => "PS256",
69 }
70 }
71
72 pub const fn is_ecdsa(self) -> bool {
74 matches!(self, Self::ES256 | Self::ES256K | Self::ES384)
75 }
76}
77
78impl fmt::Display for JwsAlgorithm {
79 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80 f.write_str(self.as_str())
81 }
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
86#[error("unknown or unsupported JWS algorithm `{0}`")]
87pub struct UnknownAlgorithm(String);
88
89impl UnknownAlgorithm {
90 pub fn name(&self) -> &str {
92 &self.0
93 }
94}
95
96impl FromStr for JwsAlgorithm {
97 type Err = UnknownAlgorithm;
98
99 fn from_str(s: &str) -> Result<Self, Self::Err> {
100 Self::ALL
101 .iter()
102 .copied()
103 .find(|alg| alg.as_str() == s)
104 .ok_or_else(|| UnknownAlgorithm(s.to_owned()))
105 }
106}
107
108impl TryFrom<jsonwebtoken::Algorithm> for JwsAlgorithm {
109 type Error = UnknownAlgorithm;
110
111 fn try_from(alg: jsonwebtoken::Algorithm) -> Result<Self, Self::Error> {
113 use jsonwebtoken::Algorithm as A;
114 match alg {
115 A::EdDSA => Ok(Self::EdDSA),
116 A::ES256 => Ok(Self::ES256),
117 A::ES384 => Ok(Self::ES384),
118 A::RS256 => Ok(Self::RS256),
119 A::PS256 => Ok(Self::PS256),
120 other => Err(UnknownAlgorithm(format!("{other:?}"))),
121 }
122 }
123}
124
125impl TryFrom<JwsAlgorithm> for jsonwebtoken::Algorithm {
126 type Error = UnknownAlgorithm;
127
128 fn try_from(alg: JwsAlgorithm) -> Result<Self, Self::Error> {
130 match alg {
131 JwsAlgorithm::EdDSA => Ok(Self::EdDSA),
132 JwsAlgorithm::ES256 => Ok(Self::ES256),
133 JwsAlgorithm::ES384 => Ok(Self::ES384),
134 JwsAlgorithm::RS256 => Ok(Self::RS256),
135 JwsAlgorithm::PS256 => Ok(Self::PS256),
136 other => Err(UnknownAlgorithm(other.as_str().to_owned())),
137 }
138 }
139}