Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Decoupled crypto backends #410

Draft
wants to merge 9 commits into
base: new-backends
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ ed25519-dalek = { version = "2.1.1" }
p256 = { version = "0.13.2", features = ["ecdsa"] }
p384 = { version = "0.13.0", features = ["ecdsa"] }
rand_core = "0.6.4"
signature = "2.2.0"
[target.'cfg(target_arch = "wasm32")'.dependencies]
js-sys = "0.3"

Expand Down
197 changes: 126 additions & 71 deletions src/crypto/hmac.rs
Original file line number Diff line number Diff line change
@@ -1,106 +1,161 @@
//! Implementations of the [`JwtSigner`] and [`JwtVerifier`] traits for the
//! HMAC family of algorithms.

use base64::{engine::general_purpose::STANDARD, Engine};
use hmac::{Hmac, Mac};
use sha2::{Sha256, Sha384, Sha512};
use signature::{Signer, Verifier};

use crate::errors::Result;
use crate::serialization::{b64_decode, b64_encode};
use crate::Algorithm;

use super::{JwtSigner, JwtVerifier};

type HmacSha256 = Hmac<Sha256>;
type HmacSha384 = Hmac<Sha384>;
type HmacSha512 = Hmac<Sha512>;

pub(crate) fn sign_hmac(alg: Algorithm, key: &[u8], message: &[u8]) -> Result<String> {
let mut hmac = create_hmac(alg, key)?;
let digest = hmac.sign(message);
Ok(b64_encode(digest))
/// The shared secret used for the HMAC family of algorithms.
#[derive(Debug)]
pub struct HmacSecret(Vec<u8>);

impl HmacSecret {
/// If you're using an HMAC secret that is not base64, use that.
pub fn from_secret(secret: &[u8]) -> Self {
Self(secret.to_vec())
}

/// If you have a base64 HMAC secret, use that.
pub fn from_base64_secret(secret: &str) -> Result<Self> {
Ok(Self(STANDARD.decode(secret)?))
}
}

pub(crate) fn hmac_verify(
alg: Algorithm,
signature: &str,
key: &[u8],
message: &[u8],
) -> Result<bool> {
let mut hmac = create_hmac(alg, key)?;
let signature = b64_decode(signature)?;
Ok(hmac.verify(&signature, message))
pub struct Hs256(HmacSha256);

impl Hs256 {
pub(crate) fn new(secret: HmacSecret) -> Result<Self> {
let inner = HmacSha256::new_from_slice(&secret.0)
.map_err(|_e| crate::errors::ErrorKind::InvalidKeyFormat)?;

Ok(Self(inner))
}
}

fn create_hmac(alg: Algorithm, key: &[u8]) -> Result<Box<dyn HmacAlgorithm>> {
let hmac: Box<dyn HmacAlgorithm> = match alg {
Algorithm::HS256 => {
let sha256 = HmacSha256::new_from_slice(key)
.map_err(|_e| crate::errors::ErrorKind::InvalidKeyFormat)?;
Box::new(sha256)
}
Algorithm::HS384 => {
let sha384 = HmacSha384::new_from_slice(key)
.map_err(|_e| crate::errors::ErrorKind::InvalidKeyFormat)?;
Box::new(sha384)
}
Algorithm::HS512 => {
let sha512 = HmacSha512::new_from_slice(key)
.map_err(|_e| crate::errors::ErrorKind::InvalidKeyFormat)?;
Box::new(sha512)
}
_ => {
return Err(crate::errors::new_error(crate::errors::ErrorKind::InvalidAlgorithm));
}
};
Ok(hmac)
impl Signer<Vec<u8>> for Hs256 {
fn try_sign(&self, msg: &[u8]) -> std::result::Result<Vec<u8>, signature::Error> {
let mut signer = self.0.clone();
signer.reset();
signer.update(msg);

Ok(signer.finalize().into_bytes().to_vec())
}
}

trait HmacAlgorithm {
fn sign(&mut self, message: &[u8]) -> Vec<u8>;
fn verify(&mut self, signature: &[u8], message: &[u8]) -> bool;
impl JwtSigner for Hs256 {
fn algorithm(&self) -> Algorithm {
Algorithm::HS256
}
}

impl HmacAlgorithm for Box<dyn HmacAlgorithm + '_> {
fn sign(&mut self, message: &[u8]) -> Vec<u8> {
(**self).sign(message)
impl Verifier<Vec<u8>> for Hs256 {
fn verify(&self, msg: &[u8], signature: &Vec<u8>) -> std::result::Result<(), signature::Error> {
let mut verifier = self.0.clone();
verifier.reset();
verifier.update(msg);

verifier.verify_slice(signature).map_err(|e| signature::Error::from_source(e))
}
}

fn verify(&mut self, signature: &[u8], message: &[u8]) -> bool {
(**self).verify(signature, message)
impl JwtVerifier for Hs256 {
fn algorithm(&self) -> Algorithm {
Algorithm::HS256
}
}

impl HmacAlgorithm for HmacSha256 {
fn sign(&mut self, message: &[u8]) -> Vec<u8> {
self.reset();
self.update(message);
self.clone().finalize().into_bytes().to_vec()
pub(crate) struct Hs384(HmacSha384);

impl Hs384 {
pub(crate) fn new(secret: HmacSecret) -> Result<Self> {
let inner = HmacSha384::new_from_slice(&secret.0)
.map_err(|_e| crate::errors::ErrorKind::InvalidKeyFormat)?;

Ok(Self(inner))
}
fn verify(&mut self, signature: &[u8], message: &[u8]) -> bool {
self.reset();
self.update(message);
self.clone().verify_slice(signature).is_ok()
}

impl Signer<Vec<u8>> for Hs384 {
fn try_sign(&self, msg: &[u8]) -> std::result::Result<Vec<u8>, signature::Error> {
let mut signer = self.0.clone();
signer.reset();
signer.update(msg);

Ok(signer.finalize().into_bytes().to_vec())
}
}

impl HmacAlgorithm for HmacSha384 {
fn sign(&mut self, message: &[u8]) -> Vec<u8> {
self.reset();
self.update(message);
self.clone().finalize().into_bytes().to_vec()
impl JwtSigner for Hs384 {
fn algorithm(&self) -> Algorithm {
Algorithm::HS384
}
fn verify(&mut self, signature: &[u8], message: &[u8]) -> bool {
self.reset();
self.update(message);
self.clone().verify_slice(signature).is_ok()
}

impl Verifier<Vec<u8>> for Hs384 {
fn verify(&self, msg: &[u8], signature: &Vec<u8>) -> std::result::Result<(), signature::Error> {
let mut verifier = self.0.clone();
verifier.reset();
verifier.update(msg);

verifier.verify_slice(signature).map_err(|e| signature::Error::from_source(e))
}
}

impl JwtVerifier for Hs384 {
fn algorithm(&self) -> Algorithm {
Algorithm::HS384
}
}

impl HmacAlgorithm for HmacSha512 {
fn sign(&mut self, message: &[u8]) -> Vec<u8> {
self.reset();
self.update(message);
self.clone().finalize().into_bytes().to_vec()
pub struct Hs512(HmacSha512);

impl Hs512 {
pub(crate) fn new(secret: HmacSecret) -> Result<Self> {
let inner = HmacSha512::new_from_slice(&secret.0)
.map_err(|_e| crate::errors::ErrorKind::InvalidKeyFormat)?;

Ok(Self(inner))
}
}

impl Signer<Vec<u8>> for Hs512 {
fn try_sign(&self, msg: &[u8]) -> std::result::Result<Vec<u8>, signature::Error> {
let mut signer = self.0.clone();
signer.reset();
signer.update(msg);

Ok(signer.finalize().into_bytes().to_vec())
}
}

impl JwtSigner for Hs512 {
fn algorithm(&self) -> Algorithm {
Algorithm::HS512
}
}

impl Verifier<Vec<u8>> for Hs512 {
fn verify(&self, msg: &[u8], signature: &Vec<u8>) -> std::result::Result<(), signature::Error> {
let mut verifier = self.0.clone();
verifier.reset();
verifier.update(msg);

verifier.verify_slice(signature).map_err(|e| signature::Error::from_source(e))
}
}

fn verify(&mut self, signature: &[u8], message: &[u8]) -> bool {
self.reset();
self.update(message);
self.clone().verify_slice(signature).is_ok()
impl JwtVerifier for Hs512 {
fn algorithm(&self) -> Algorithm {
Algorithm::HS512
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like the kind of code that could be simplified with macros

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For repeated things that that, sure it could 👍

I feel that we are only repeating it a couple times so I don't believe the complexity of a macro is worth it. I also find it easier to read normal Rust code. But maybe that is just me 🤷

}
}
77 changes: 19 additions & 58 deletions src/crypto/mod.rs
Original file line number Diff line number Diff line change
@@ -1,67 +1,28 @@
//! The cryptography of the `jsonwebtoken` crate is decoupled behind
//! [`JwtSigner`] and [`JwtVerifier`] traits. These make use of `RustCrypto`'s
//! [`Signer`] and [`Verifier`] traits respectively.

use crate::algorithms::Algorithm;
use crate::decoding::{DecodingKey, DecodingKeyKind};
use crate::encoding::EncodingKey;
use crate::errors::Result;

pub(crate) mod ecdsa;
pub(crate) mod eddsa;
// pub(crate) mod ecdsa;
// pub(crate) mod eddsa;
pub(crate) mod hmac;
pub(crate) mod rsa;
// pub(crate) mod rsa;

use signature::{Signer, Verifier};

/// Take the payload of a JWT, sign it using the algorithm given and return
/// the base64 url safe encoded of the result.
/// Trait providing the functionality to sign a JWT.
///
/// If you just want to encode a JWT, use `encode` instead.
pub fn sign(message: &[u8], key: &EncodingKey, algorithm: Algorithm) -> Result<String> {
match algorithm {
Algorithm::ES256 | Algorithm::ES384 => ecdsa::sign(algorithm, key.inner(), message),
Algorithm::EdDSA => eddsa::sign(key.inner(), message),
Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512 => {
hmac::sign_hmac(algorithm, key.inner(), message)
}
Algorithm::RS256
| Algorithm::RS384
| Algorithm::RS512
| Algorithm::PS256
| Algorithm::PS384
| Algorithm::PS512 => rsa::sign(algorithm, key.inner(), message),
}
/// Allows an arbitrary crypto backend to be provided.
pub trait JwtSigner: Signer<Vec<u8>> {
/// Return the [`Algorithm`] corresponding to the signing module.
fn algorithm(&self) -> Algorithm;
}

/// Compares the signature given with a re-computed signature for HMAC or using the public key
/// for RSA/EC.
///
/// If you just want to decode a JWT, use `decode` instead.
///
/// `signature` is the signature part of a jwt (text after the second '.')
/// Trait providing the functionality to verify a JWT.
///
/// `message` is base64(header) + "." + base64(claims)
pub fn verify(
signature: &str,
message: &[u8],
key: &DecodingKey,
algorithm: Algorithm,
) -> Result<bool> {
match algorithm {
Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512 => {
hmac::hmac_verify(algorithm, signature, key.as_bytes(), message)
}
Algorithm::ES256 | Algorithm::ES384 => {
ecdsa::verify(algorithm, signature, message, key.as_bytes())
}
Algorithm::EdDSA => eddsa::verify(signature, message, key.as_bytes()),
Algorithm::RS256
| Algorithm::RS384
| Algorithm::RS512
| Algorithm::PS256
| Algorithm::PS384
| Algorithm::PS512 => match &key.kind {
DecodingKeyKind::SecretOrDer(bytes) => {
rsa::verify_der(algorithm, signature, message, bytes)
}
DecodingKeyKind::RsaModulusExponent { n, e } => {
rsa::verify_from_components(algorithm, signature, message, (n, e))
}
},
}
/// Allows an arbitrary crypto backend to be provided.
pub trait JwtVerifier: Verifier<Vec<u8>> {
/// Return the [`Algorithm`] corresponding to the signing module.
fn algorithm(&self) -> Algorithm;
}
Loading