-
Notifications
You must be signed in to change notification settings - Fork 276
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
sidrubs
wants to merge
9
commits into
Keats:new-backends
Choose a base branch
from
sidrubs:decoupled-crypto-backends
base: new-backends
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 5 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
502faa4
feat(encoder): Add encoder builder
sidrubs a701547
feat(encoder): Convert to dynamic dispatch
sidrubs 6a41ba7
feat(decoder): Create decoder
sidrubs 66d54be
test: Get HMAC tests passing
sidrubs 0886064
docs: Neaten up docstrings
sidrubs 337f9ed
feat(crypto): Implement JwtSigner and JwtVerifier for aws-lc-rs
sidrubs a0431d8
feat: Remove builder style implementation
sidrubs 4225e1f
feat: Use original encoding and decoding key structs
sidrubs 78e84c1
feat(crypto): Add RSA family
sidrubs File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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 🤷