Skip to main content

yimi_rutool/jwt/
algorithms.rs

1//! JWT signing algorithms and key management
2
3use crate::jwt::errors::{JwtError, JwtResult};
4use serde::{Deserialize, Serialize};
5
6/// Supported JWT signing algorithms
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
8pub enum Algorithm {
9    /// HMAC using SHA-256
10    #[default]
11    HS256,
12    /// HMAC using SHA-384  
13    HS384,
14    /// HMAC using SHA-512
15    HS512,
16    /// RSA using SHA-256
17    RS256,
18    /// RSA using SHA-384
19    RS384,
20    /// RSA using SHA-512
21    RS512,
22    /// ECDSA using SHA-256
23    ES256,
24    /// ECDSA using SHA-384
25    ES384,
26    /// ECDSA using SHA-512
27    ES512,
28}
29
30impl Algorithm {
31    /// Get the algorithm name as used in JWT headers
32    pub fn as_str(&self) -> &'static str {
33        match self {
34            Algorithm::HS256 => "HS256",
35            Algorithm::HS384 => "HS384",
36            Algorithm::HS512 => "HS512",
37            Algorithm::RS256 => "RS256",
38            Algorithm::RS384 => "RS384",
39            Algorithm::RS512 => "RS512",
40            Algorithm::ES256 => "ES256",
41            Algorithm::ES384 => "ES384",
42            Algorithm::ES512 => "ES512",
43        }
44    }
45
46    /// Parse algorithm from string
47    ///
48    /// # Errors
49    ///
50    /// Returns `JwtError::InvalidAlgorithm` if the string is not a valid algorithm name
51    pub fn from_str(s: &str) -> JwtResult<Self> {
52        match s {
53            "HS256" => Ok(Algorithm::HS256),
54            "HS384" => Ok(Algorithm::HS384),
55            "HS512" => Ok(Algorithm::HS512),
56            "RS256" => Ok(Algorithm::RS256),
57            "RS384" => Ok(Algorithm::RS384),
58            "RS512" => Ok(Algorithm::RS512),
59            "ES256" => Ok(Algorithm::ES256),
60            "ES384" => Ok(Algorithm::ES384),
61            "ES512" => Ok(Algorithm::ES512),
62            _ => Err(JwtError::invalid_algorithm(s)),
63        }
64    }
65
66    /// Check if algorithm uses HMAC (symmetric)
67    pub fn is_hmac(&self) -> bool {
68        matches!(self, Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512)
69    }
70
71    /// Check if algorithm uses RSA (asymmetric)
72    pub fn is_rsa(&self) -> bool {
73        matches!(self, Algorithm::RS256 | Algorithm::RS384 | Algorithm::RS512)
74    }
75
76    /// Check if algorithm uses ECDSA (asymmetric)
77    pub fn is_ecdsa(&self) -> bool {
78        matches!(self, Algorithm::ES256 | Algorithm::ES384 | Algorithm::ES512)
79    }
80
81    /// Check if algorithm is asymmetric
82    pub fn is_asymmetric(&self) -> bool {
83        self.is_rsa() || self.is_ecdsa()
84    }
85}
86
87impl std::fmt::Display for Algorithm {
88    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
89        write!(f, "{}", self.as_str())
90    }
91}
92
93/// Signing key for JWT operations
94#[derive(Debug, Clone)]
95pub enum SigningKey {
96    /// HMAC secret key (for HS* algorithms)
97    Hmac(Vec<u8>),
98    /// RSA private key in PEM format (for RS* algorithms)
99    RsaPrivate(String),
100    /// RSA public key in PEM format (for verification)
101    RsaPublic(String),
102    /// ECDSA private key in PEM format (for ES* algorithms)
103    EcdsaPrivate(String),
104    /// ECDSA public key in PEM format (for verification)  
105    EcdsaPublic(String),
106}
107
108impl SigningKey {
109    /// Create HMAC key from string
110    pub fn hmac_from_string(secret: impl Into<String>) -> Self {
111        Self::Hmac(secret.into().into_bytes())
112    }
113
114    /// Create HMAC key from bytes
115    pub fn hmac_from_bytes(secret: Vec<u8>) -> Self {
116        Self::Hmac(secret)
117    }
118
119    /// Create RSA private key from PEM string
120    pub fn rsa_private_from_pem(pem: impl Into<String>) -> Self {
121        Self::RsaPrivate(pem.into())
122    }
123
124    /// Create RSA public key from PEM string
125    pub fn rsa_public_from_pem(pem: impl Into<String>) -> Self {
126        Self::RsaPublic(pem.into())
127    }
128
129    /// Create ECDSA private key from PEM string
130    pub fn ecdsa_private_from_pem(pem: impl Into<String>) -> Self {
131        Self::EcdsaPrivate(pem.into())
132    }
133
134    /// Create ECDSA public key from PEM string
135    pub fn ecdsa_public_from_pem(pem: impl Into<String>) -> Self {
136        Self::EcdsaPublic(pem.into())
137    }
138
139    /// Check if key is compatible with algorithm
140    pub fn is_compatible_with(&self, algorithm: Algorithm) -> bool {
141        match (self, algorithm) {
142            (SigningKey::Hmac(_), alg) if alg.is_hmac() => true,
143            (SigningKey::RsaPrivate(_) | SigningKey::RsaPublic(_), alg) if alg.is_rsa() => true,
144            (SigningKey::EcdsaPrivate(_) | SigningKey::EcdsaPublic(_), alg) if alg.is_ecdsa() => {
145                true
146            }
147            _ => false,
148        }
149    }
150
151    /// Check if key can be used for signing (private keys)
152    pub fn can_sign(&self) -> bool {
153        matches!(
154            self,
155            SigningKey::Hmac(_) | SigningKey::RsaPrivate(_) | SigningKey::EcdsaPrivate(_)
156        )
157    }
158
159    /// Check if key can be used for verification
160    pub fn can_verify(&self) -> bool {
161        // All keys can verify, but private keys are typically used for signing
162        true
163    }
164}
165
166#[cfg(feature = "jsonwebtoken")]
167impl TryFrom<Algorithm> for jsonwebtoken::Algorithm {
168    type Error = JwtError;
169
170    fn try_from(alg: Algorithm) -> Result<Self, Self::Error> {
171        match alg {
172            Algorithm::HS256 => Ok(jsonwebtoken::Algorithm::HS256),
173            Algorithm::HS384 => Ok(jsonwebtoken::Algorithm::HS384),
174            Algorithm::HS512 => Ok(jsonwebtoken::Algorithm::HS512),
175            Algorithm::RS256 => Ok(jsonwebtoken::Algorithm::RS256),
176            Algorithm::RS384 => Ok(jsonwebtoken::Algorithm::RS384),
177            Algorithm::RS512 => Ok(jsonwebtoken::Algorithm::RS512),
178            Algorithm::ES256 => Ok(jsonwebtoken::Algorithm::ES256),
179            Algorithm::ES384 => Ok(jsonwebtoken::Algorithm::ES384),
180            // ES512 not supported by jsonwebtoken crate
181            Algorithm::ES512 => Err(JwtError::invalid_algorithm(
182                "ES512 not supported by jsonwebtoken",
183            )),
184        }
185    }
186}
187
188#[cfg(feature = "jsonwebtoken")]
189impl TryFrom<jsonwebtoken::Algorithm> for Algorithm {
190    type Error = JwtError;
191
192    fn try_from(alg: jsonwebtoken::Algorithm) -> Result<Self, Self::Error> {
193        match alg {
194            jsonwebtoken::Algorithm::HS256 => Ok(Algorithm::HS256),
195            jsonwebtoken::Algorithm::HS384 => Ok(Algorithm::HS384),
196            jsonwebtoken::Algorithm::HS512 => Ok(Algorithm::HS512),
197            jsonwebtoken::Algorithm::RS256 => Ok(Algorithm::RS256),
198            jsonwebtoken::Algorithm::RS384 => Ok(Algorithm::RS384),
199            jsonwebtoken::Algorithm::RS512 => Ok(Algorithm::RS512),
200            jsonwebtoken::Algorithm::ES256 => Ok(Algorithm::ES256),
201            jsonwebtoken::Algorithm::ES384 => Ok(Algorithm::ES384),
202            // ES512 not supported by jsonwebtoken crate
203            // jsonwebtoken::Algorithm::ES512 => Ok(Algorithm::ES512),
204            _ => Err(JwtError::invalid_algorithm("Unsupported algorithm")),
205        }
206    }
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    #[test]
214    fn test_algorithm_string_conversion() {
215        assert_eq!(Algorithm::HS256.as_str(), "HS256");
216        assert_eq!(Algorithm::RS256.as_str(), "RS256");
217        assert_eq!(Algorithm::ES256.as_str(), "ES256");
218
219        assert_eq!(Algorithm::from_str("HS256").unwrap(), Algorithm::HS256);
220        assert_eq!(Algorithm::from_str("RS256").unwrap(), Algorithm::RS256);
221        assert_eq!(Algorithm::from_str("ES256").unwrap(), Algorithm::ES256);
222
223        assert!(Algorithm::from_str("INVALID").is_err());
224    }
225
226    #[test]
227    fn test_algorithm_types() {
228        assert!(Algorithm::HS256.is_hmac());
229        assert!(!Algorithm::HS256.is_rsa());
230        assert!(!Algorithm::HS256.is_ecdsa());
231        assert!(!Algorithm::HS256.is_asymmetric());
232
233        assert!(!Algorithm::RS256.is_hmac());
234        assert!(Algorithm::RS256.is_rsa());
235        assert!(!Algorithm::RS256.is_ecdsa());
236        assert!(Algorithm::RS256.is_asymmetric());
237
238        assert!(!Algorithm::ES256.is_hmac());
239        assert!(!Algorithm::ES256.is_rsa());
240        assert!(Algorithm::ES256.is_ecdsa());
241        assert!(Algorithm::ES256.is_asymmetric());
242    }
243
244    #[test]
245    fn test_signing_key_compatibility() {
246        let hmac_key = SigningKey::hmac_from_string("secret");
247        let rsa_private = SigningKey::rsa_private_from_pem("-----BEGIN PRIVATE KEY-----");
248        let rsa_public = SigningKey::rsa_public_from_pem("-----BEGIN PUBLIC KEY-----");
249
250        assert!(hmac_key.is_compatible_with(Algorithm::HS256));
251        assert!(!hmac_key.is_compatible_with(Algorithm::RS256));
252
253        assert!(rsa_private.is_compatible_with(Algorithm::RS256));
254        assert!(!rsa_private.is_compatible_with(Algorithm::HS256));
255
256        assert!(rsa_public.is_compatible_with(Algorithm::RS256));
257        assert!(!rsa_public.is_compatible_with(Algorithm::ES256));
258    }
259
260    #[test]
261    fn test_signing_capabilities() {
262        let hmac_key = SigningKey::hmac_from_string("secret");
263        let rsa_private = SigningKey::rsa_private_from_pem("private");
264        let rsa_public = SigningKey::rsa_public_from_pem("public");
265
266        assert!(hmac_key.can_sign());
267        assert!(hmac_key.can_verify());
268
269        assert!(rsa_private.can_sign());
270        assert!(rsa_private.can_verify());
271
272        assert!(!rsa_public.can_sign());
273        assert!(rsa_public.can_verify());
274    }
275}