jsonwebtoken/crypto/
mod.rs

1//! The cryptography of the `jsonwebtoken` crate is decoupled behind
2//! [`JwtSigner`] and [`JwtVerifier`] traits. These make use of `RustCrypto`'s
3//! [`Signer`] and [`Verifier`] traits respectively.
4//!
5//! [`JwtSigner`]: crate::crypto::JwtSigner
6//! [`JwtVerifier`]: crate::crypto::JwtVerifier
7//! [`Signer`]: signature::Signer
8//! [`Verifier`]: signature::Verifier
9
10use crate::algorithms::Algorithm;
11use crate::errors::Result;
12use crate::{DecodingKey, EncodingKey};
13
14#[cfg(feature = "aws_lc_rs")]
15pub(crate) mod aws_lc;
16#[cfg(feature = "rust_crypto")]
17pub(crate) mod rust_crypto;
18
19use crate::serialization::{b64_decode, b64_encode};
20use signature::{Signer, Verifier};
21
22/// Trait providing the functionality to sign a JWT.
23///
24/// Allows an arbitrary crypto backend to be provided.
25pub trait JwtSigner: Signer<Vec<u8>> {
26    /// Return the [`Algorithm`] corresponding to the signing module.
27    fn algorithm(&self) -> Algorithm;
28}
29
30/// Trait providing the functionality to verify a JWT.
31///
32/// Allows an arbitrary crypto backend to be provided.
33pub trait JwtVerifier: Verifier<Vec<u8>> {
34    /// Return the [`Algorithm`] corresponding to the signing module.
35    fn algorithm(&self) -> Algorithm;
36}
37
38/// Take the payload of a JWT, sign it using the algorithm given and return
39/// the base64 url safe encoded of the result.
40///
41/// If you just want to encode a JWT, use `encode` instead.
42pub fn sign(message: &[u8], key: &EncodingKey, algorithm: Algorithm) -> Result<String> {
43    let provider = crate::encoding::jwt_signer_factory(&algorithm, key)?;
44    Ok(b64_encode(provider.sign(message)))
45}
46
47/// Compares the signature given with a re-computed signature for HMAC or using the public key
48/// for RSA/EC.
49///
50/// If you just want to decode a JWT, use `decode` instead.
51///
52/// `signature` is the signature part of a jwt (text after the second '.')
53///
54/// `message` is base64(header) + "." + base64(claims)
55pub fn verify(
56    signature: &str,
57    message: &[u8],
58    key: &DecodingKey,
59    algorithm: Algorithm,
60) -> Result<bool> {
61    let provider = crate::decoding::jwt_verifier_factory(&algorithm, key)?;
62    Ok(provider.verify(message, &b64_decode(signature)?).is_ok())
63}