Skip to main content

jsonwebtoken/
encoding.rs

1use std::fmt::{Debug, Formatter};
2
3use base64::{
4    Engine,
5    engine::general_purpose::{STANDARD, URL_SAFE},
6};
7use serde::ser::Serialize;
8use zeroize::{Zeroize, ZeroizeOnDrop};
9
10use crate::algorithms::AlgorithmFamily;
11use crate::crypto::CryptoProvider;
12use crate::errors::{ErrorKind, Result, new_error};
13use crate::header::Header;
14#[cfg(feature = "use_pem")]
15use crate::pem::decoder::PemEncodedKey;
16use crate::serialization::{b64_encode, b64_encode_part};
17
18/// A key to encode a JWT with. Can be a secret, a PEM-encoded key or a DER-encoded key.
19/// This key can be re-used so make sure you only initialize it once if you can for better performance.
20#[derive(Clone, Zeroize, ZeroizeOnDrop)]
21pub struct EncodingKey {
22    #[zeroize(skip)]
23    family: AlgorithmFamily,
24    content: Vec<u8>,
25}
26
27impl EncodingKey {
28    /// The algorithm family this key is for.
29    pub fn family(&self) -> AlgorithmFamily {
30        self.family
31    }
32
33    /// If you're using a HMAC secret that is not base64, use that.
34    pub fn from_secret(secret: &[u8]) -> Self {
35        EncodingKey { family: AlgorithmFamily::Hmac, content: secret.to_vec() }
36    }
37
38    /// If you have a base64 HMAC secret, use that.
39    pub fn from_base64_secret(secret: &str) -> Result<Self> {
40        let out = STANDARD.decode(secret)?;
41        Ok(EncodingKey { family: AlgorithmFamily::Hmac, content: out })
42    }
43
44    /// For loading websafe base64 HMAC secrets, ex: ACME EAB credentials.
45    pub fn from_urlsafe_base64_secret(secret: &str) -> Result<Self> {
46        let out = URL_SAFE.decode(secret)?;
47        Ok(EncodingKey { family: AlgorithmFamily::Hmac, content: out })
48    }
49
50    /// If you are loading a RSA key from a .pem file.
51    /// This errors if the key is not a valid RSA key.
52    /// Only exists if the feature `use_pem` is enabled.
53    ///
54    /// # NOTE
55    ///
56    /// According to the [ring doc](https://docs.rs/ring/latest/ring/signature/struct.RsaKeyPair.html#method.from_pkcs8),
57    /// the key should be at least 2047 bits.
58    ///
59    #[cfg(feature = "use_pem")]
60    pub fn from_rsa_pem(key: &[u8]) -> Result<Self> {
61        let pem_key = PemEncodedKey::new(key)?;
62        let content = pem_key.as_rsa_key()?;
63        Ok(EncodingKey { family: AlgorithmFamily::Rsa, content: content.to_vec() })
64    }
65
66    /// If you are loading a ECDSA key from a .pem file
67    /// This errors if the key is not a valid private EC key
68    /// Only exists if the feature `use_pem` is enabled.
69    ///
70    /// # NOTE
71    ///
72    /// The key should be in PKCS#8 form.
73    ///
74    /// You can generate a key with the following:
75    ///
76    /// ```sh
77    /// openssl ecparam -genkey -noout -name prime256v1 \
78    ///     | openssl pkcs8 -topk8 -nocrypt -out ec-private.pem
79    /// ```
80    #[cfg(feature = "use_pem")]
81    pub fn from_ec_pem(key: &[u8]) -> Result<Self> {
82        let pem_key = PemEncodedKey::new(key)?;
83        let content = pem_key.as_ec_private_key()?;
84        Ok(EncodingKey { family: AlgorithmFamily::Ec, content: content.to_vec() })
85    }
86
87    /// If you are loading a EdDSA key from a .pem file
88    /// This errors if the key is not a valid private Ed key
89    /// Only exists if the feature `use_pem` is enabled.
90    #[cfg(feature = "use_pem")]
91    pub fn from_ed_pem(key: &[u8]) -> Result<Self> {
92        let pem_key = PemEncodedKey::new(key)?;
93        let content = pem_key.as_ed_private_key()?;
94        Ok(EncodingKey { family: AlgorithmFamily::Ed, content: content.to_vec() })
95    }
96
97    /// If you know what you're doing and have the DER-encoded key, for RSA only
98    pub fn from_rsa_der(der: &[u8]) -> Self {
99        EncodingKey { family: AlgorithmFamily::Rsa, content: der.to_vec() }
100    }
101
102    /// If you know what you're doing and have the DER-encoded key, for ECDSA
103    pub fn from_ec_der(der: &[u8]) -> Self {
104        EncodingKey { family: AlgorithmFamily::Ec, content: der.to_vec() }
105    }
106
107    /// If you know what you're doing and have the DER-encoded key, for EdDSA
108    pub fn from_ed_der(der: &[u8]) -> Self {
109        EncodingKey { family: AlgorithmFamily::Ed, content: der.to_vec() }
110    }
111
112    /// Get the value of the key.
113    ///
114    /// To be used for defining your own `CryptoProvider`.
115    pub fn as_bytes(&self) -> &[u8] {
116        &self.content
117    }
118}
119
120impl Debug for EncodingKey {
121    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
122        f.debug_struct("EncodingKey")
123            .field("family", &self.family)
124            .field("content", &"[redacted]")
125            .finish()
126    }
127}
128
129/// Encode the header and claims given and sign the payload using the algorithm from the header and the key.
130/// If the algorithm given is RSA or EC, the key needs to be in the PEM format.
131///
132/// ```rust
133/// use serde::{Deserialize, Serialize};
134/// use jsonwebtoken::{encode, Algorithm, Header, EncodingKey};
135///
136/// #[derive(Debug, Serialize, Deserialize)]
137/// struct Claims {
138///    sub: String,
139///    company: String
140/// }
141///
142/// let my_claims = Claims {
143///     sub: "b@b.com".to_owned(),
144///     company: "ACME".to_owned()
145/// };
146///
147/// // my_claims is a struct that implements Serialize
148/// // This will create a JWT using HS256 as algorithm
149/// let token = encode(&Header::default(), &my_claims, &EncodingKey::from_secret("secret".as_ref())).unwrap();
150/// ```
151pub fn encode<T: Serialize>(header: &Header, claims: &T, key: &EncodingKey) -> Result<String> {
152    if key.family != header.alg.family() {
153        return Err(new_error(ErrorKind::InvalidAlgorithm));
154    }
155
156    let signing_provider = (CryptoProvider::get_default().signer_factory)(&header.alg, key)?;
157
158    if signing_provider.algorithm() != header.alg {
159        return Err(new_error(ErrorKind::InvalidAlgorithm));
160    }
161
162    let encoded_header = b64_encode_part(&header)?;
163    let encoded_claims = b64_encode_part(claims)?;
164    let message = [encoded_header, encoded_claims].join(".");
165
166    let signature = b64_encode(signing_provider.try_sign(message.as_bytes())?);
167
168    Ok([message, signature].join("."))
169}