Skip to content

Commit 4225e1f

Browse files
committed
feat: Use original encoding and decoding key structs
1 parent a0431d8 commit 4225e1f

File tree

7 files changed

+102
-90
lines changed

7 files changed

+102
-90
lines changed

src/crypto/aws_lc/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
pub(crate) mod hmac;
2+
// pub(crate) mod rsa;

src/crypto/hmac.rs

-31
This file was deleted.

src/crypto/mod.rs

-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ use crate::algorithms::Algorithm;
66

77
#[cfg(feature = "aws_lc_rs")]
88
pub(crate) mod aws_lc;
9-
pub(crate) mod hmac;
109
#[cfg(feature = "rust_crypto")]
1110
pub(crate) mod rust_crypto;
1211

src/crypto/rust_crypto/hmac.rs

+69-28
Original file line numberDiff line numberDiff line change
@@ -6,25 +6,28 @@ use sha2::{Sha256, Sha384, Sha512};
66
use signature::{Signer, Verifier};
77

88
use crate::crypto::{JwtSigner, JwtVerifier};
9+
use crate::decoding::try_get_hmac_secret_from_decoding_key;
10+
use crate::encoding::try_get_hmac_secret_from_encoding_key;
911
use crate::errors::Result;
10-
use crate::{Algorithm, HmacSecret};
12+
use crate::{Algorithm, DecodingKey, EncodingKey};
1113

1214
type HmacSha256 = Hmac<Sha256>;
1315
type HmacSha384 = Hmac<Sha384>;
1416
type HmacSha512 = Hmac<Sha512>;
1517

16-
pub struct Hs256(HmacSha256);
18+
pub struct Hs256Signer(HmacSha256);
1719

18-
impl Hs256 {
19-
pub(crate) fn new(secret: HmacSecret) -> Result<Self> {
20-
let inner = HmacSha256::new_from_slice(&secret)
21-
.map_err(|_e| crate::errors::ErrorKind::InvalidKeyFormat)?;
20+
impl Hs256Signer {
21+
pub(crate) fn new(encoding_key: &EncodingKey) -> Result<Self> {
22+
let inner =
23+
HmacSha256::new_from_slice(try_get_hmac_secret_from_encoding_key(encoding_key)?)
24+
.map_err(|_e| crate::errors::ErrorKind::InvalidKeyFormat)?;
2225

2326
Ok(Self(inner))
2427
}
2528
}
2629

27-
impl Signer<Vec<u8>> for Hs256 {
30+
impl Signer<Vec<u8>> for Hs256Signer {
2831
fn try_sign(&self, msg: &[u8]) -> std::result::Result<Vec<u8>, signature::Error> {
2932
let mut signer = self.0.clone();
3033
signer.reset();
@@ -34,13 +37,25 @@ impl Signer<Vec<u8>> for Hs256 {
3437
}
3538
}
3639

37-
impl JwtSigner for Hs256 {
40+
impl JwtSigner for Hs256Signer {
3841
fn algorithm(&self) -> Algorithm {
3942
Algorithm::HS256
4043
}
4144
}
4245

43-
impl Verifier<Vec<u8>> for Hs256 {
46+
pub struct Hs256Verifier(HmacSha256);
47+
48+
impl Hs256Verifier {
49+
pub(crate) fn new(decoding_key: &DecodingKey) -> Result<Self> {
50+
let inner =
51+
HmacSha256::new_from_slice(&try_get_hmac_secret_from_decoding_key(decoding_key)?)
52+
.map_err(|_e| crate::errors::ErrorKind::InvalidKeyFormat)?;
53+
54+
Ok(Self(inner))
55+
}
56+
}
57+
58+
impl Verifier<Vec<u8>> for Hs256Verifier {
4459
fn verify(&self, msg: &[u8], signature: &Vec<u8>) -> std::result::Result<(), signature::Error> {
4560
let mut verifier = self.0.clone();
4661
verifier.reset();
@@ -50,24 +65,25 @@ impl Verifier<Vec<u8>> for Hs256 {
5065
}
5166
}
5267

53-
impl JwtVerifier for Hs256 {
68+
impl JwtVerifier for Hs256Verifier {
5469
fn algorithm(&self) -> Algorithm {
5570
Algorithm::HS256
5671
}
5772
}
5873

59-
pub(crate) struct Hs384(HmacSha384);
74+
pub struct Hs384Signer(HmacSha384);
6075

61-
impl Hs384 {
62-
pub(crate) fn new(secret: HmacSecret) -> Result<Self> {
63-
let inner = HmacSha384::new_from_slice(&secret)
64-
.map_err(|_e| crate::errors::ErrorKind::InvalidKeyFormat)?;
76+
impl Hs384Signer {
77+
pub(crate) fn new(encoding_key: &EncodingKey) -> Result<Self> {
78+
let inner =
79+
HmacSha384::new_from_slice(try_get_hmac_secret_from_encoding_key(encoding_key)?)
80+
.map_err(|_e| crate::errors::ErrorKind::InvalidKeyFormat)?;
6581

6682
Ok(Self(inner))
6783
}
6884
}
6985

70-
impl Signer<Vec<u8>> for Hs384 {
86+
impl Signer<Vec<u8>> for Hs384Signer {
7187
fn try_sign(&self, msg: &[u8]) -> std::result::Result<Vec<u8>, signature::Error> {
7288
let mut signer = self.0.clone();
7389
signer.reset();
@@ -77,13 +93,25 @@ impl Signer<Vec<u8>> for Hs384 {
7793
}
7894
}
7995

80-
impl JwtSigner for Hs384 {
96+
impl JwtSigner for Hs384Signer {
8197
fn algorithm(&self) -> Algorithm {
8298
Algorithm::HS384
8399
}
84100
}
85101

86-
impl Verifier<Vec<u8>> for Hs384 {
102+
pub struct Hs384Verifier(HmacSha384);
103+
104+
impl Hs384Verifier {
105+
pub(crate) fn new(decoding_key: &DecodingKey) -> Result<Self> {
106+
let inner =
107+
HmacSha384::new_from_slice(&try_get_hmac_secret_from_decoding_key(decoding_key)?)
108+
.map_err(|_e| crate::errors::ErrorKind::InvalidKeyFormat)?;
109+
110+
Ok(Self(inner))
111+
}
112+
}
113+
114+
impl Verifier<Vec<u8>> for Hs384Verifier {
87115
fn verify(&self, msg: &[u8], signature: &Vec<u8>) -> std::result::Result<(), signature::Error> {
88116
let mut verifier = self.0.clone();
89117
verifier.reset();
@@ -93,24 +121,25 @@ impl Verifier<Vec<u8>> for Hs384 {
93121
}
94122
}
95123

96-
impl JwtVerifier for Hs384 {
124+
impl JwtVerifier for Hs384Verifier {
97125
fn algorithm(&self) -> Algorithm {
98126
Algorithm::HS384
99127
}
100128
}
101129

102-
pub struct Hs512(HmacSha512);
130+
pub struct Hs512Signer(HmacSha512);
103131

104-
impl Hs512 {
105-
pub(crate) fn new(secret: HmacSecret) -> Result<Self> {
106-
let inner = HmacSha512::new_from_slice(&secret)
107-
.map_err(|_e| crate::errors::ErrorKind::InvalidKeyFormat)?;
132+
impl Hs512Signer {
133+
pub(crate) fn new(encoding_key: &EncodingKey) -> Result<Self> {
134+
let inner =
135+
HmacSha512::new_from_slice(try_get_hmac_secret_from_encoding_key(encoding_key)?)
136+
.map_err(|_e| crate::errors::ErrorKind::InvalidKeyFormat)?;
108137

109138
Ok(Self(inner))
110139
}
111140
}
112141

113-
impl Signer<Vec<u8>> for Hs512 {
142+
impl Signer<Vec<u8>> for Hs512Signer {
114143
fn try_sign(&self, msg: &[u8]) -> std::result::Result<Vec<u8>, signature::Error> {
115144
let mut signer = self.0.clone();
116145
signer.reset();
@@ -120,13 +149,25 @@ impl Signer<Vec<u8>> for Hs512 {
120149
}
121150
}
122151

123-
impl JwtSigner for Hs512 {
152+
impl JwtSigner for Hs512Signer {
124153
fn algorithm(&self) -> Algorithm {
125154
Algorithm::HS512
126155
}
127156
}
128157

129-
impl Verifier<Vec<u8>> for Hs512 {
158+
pub struct Hs512Verifier(HmacSha512);
159+
160+
impl Hs512Verifier {
161+
pub(crate) fn new(decoding_key: &DecodingKey) -> Result<Self> {
162+
let inner =
163+
HmacSha512::new_from_slice(&try_get_hmac_secret_from_decoding_key(decoding_key)?)
164+
.map_err(|_e| crate::errors::ErrorKind::InvalidKeyFormat)?;
165+
166+
Ok(Self(inner))
167+
}
168+
}
169+
170+
impl Verifier<Vec<u8>> for Hs512Verifier {
130171
fn verify(&self, msg: &[u8], signature: &Vec<u8>) -> std::result::Result<(), signature::Error> {
131172
let mut verifier = self.0.clone();
132173
verifier.reset();
@@ -136,7 +177,7 @@ impl Verifier<Vec<u8>> for Hs512 {
136177
}
137178
}
138179

139-
impl JwtVerifier for Hs512 {
180+
impl JwtVerifier for Hs512Verifier {
140181
fn algorithm(&self) -> Algorithm {
141182
Algorithm::HS512
142183
}

src/decoding.rs

+20-19
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ use base64::{engine::general_purpose::STANDARD, Engine};
22
use serde::de::DeserializeOwned;
33

44
use crate::algorithms::AlgorithmFamily;
5-
use crate::crypto::hmac::HmacSecret;
65
use crate::crypto::JwtVerifier;
76
use crate::errors::{new_error, Error, ErrorKind, Result};
87
use crate::header::Header;
@@ -17,7 +16,7 @@ use crate::Algorithm;
1716
#[cfg(feature = "aws_lc_rs")]
1817
use crate::crypto::aws_lc::hmac::{Hs256, Hs384, Hs512};
1918
#[cfg(feature = "rust_crypto")]
20-
use crate::crypto::rust_crypto::hmac::{Hs256, Hs384, Hs512};
19+
use crate::crypto::rust_crypto::hmac::{Hs256Verifier, Hs384Verifier, Hs512Verifier};
2120

2221
/// The return type of a successful call to [decode](fn.decode.html).
2322
#[derive(Debug)]
@@ -257,9 +256,9 @@ pub fn _decode<T: DeserializeOwned>(
257256
/// Return the correct [`JwtVerifier`] based on the `algorithm`.
258257
fn jwt_verifier_factory(algorithm: &Algorithm, key: &DecodingKey) -> Result<Box<dyn JwtVerifier>> {
259258
let jwt_encoder = match algorithm {
260-
Algorithm::HS256 => Box::new(Hs256::new(key.try_into()?)?) as Box<dyn JwtVerifier>,
261-
Algorithm::HS384 => Box::new(Hs384::new(key.try_into()?)?) as Box<dyn JwtVerifier>,
262-
Algorithm::HS512 => Box::new(Hs512::new(key.try_into()?)?) as Box<dyn JwtVerifier>,
259+
Algorithm::HS256 => Box::new(Hs256Verifier::new(key)?) as Box<dyn JwtVerifier>,
260+
Algorithm::HS384 => Box::new(Hs384Verifier::new(key)?) as Box<dyn JwtVerifier>,
261+
Algorithm::HS512 => Box::new(Hs512Verifier::new(key)?) as Box<dyn JwtVerifier>,
263262
Algorithm::ES256 => todo!(),
264263
Algorithm::ES384 => todo!(),
265264
Algorithm::RS256 => todo!(),
@@ -274,20 +273,6 @@ fn jwt_verifier_factory(algorithm: &Algorithm, key: &DecodingKey) -> Result<Box<
274273
Ok(jwt_encoder)
275274
}
276275

277-
/// Convert a [`&DecodingKey`] into an [`HmacSecret`]
278-
impl TryInto<HmacSecret> for &DecodingKey {
279-
type Error = Error;
280-
281-
fn try_into(self) -> std::result::Result<HmacSecret, Self::Error> {
282-
match self.kind.clone() {
283-
DecodingKeyKind::SecretOrDer(vec) => Ok(HmacSecret::from_secret(&vec)),
284-
DecodingKeyKind::RsaModulusExponent { .. } => {
285-
Err(new_error(crate::errors::ErrorKind::InvalidKeyFormat))
286-
}
287-
}
288-
}
289-
}
290-
291276
/// Decode a JWT without any signature verification/validations and return its [Header](struct.Header.html).
292277
///
293278
/// If the token has an invalid format (ie 3 parts separated by a `.`), it will return an error.
@@ -341,3 +326,19 @@ fn verify_signature<'a>(
341326

342327
Ok((header, payload))
343328
}
329+
330+
/// # Todo
331+
///
332+
/// - Try return a reference.
333+
pub(crate) fn try_get_hmac_secret_from_decoding_key(decoding_key: &DecodingKey) -> Result<Vec<u8>> {
334+
if decoding_key.family != AlgorithmFamily::Hmac {
335+
return Err(new_error(ErrorKind::InvalidKeyFormat));
336+
}
337+
338+
match decoding_key.kind.clone() {
339+
DecodingKeyKind::SecretOrDer(vec) => Ok(vec),
340+
DecodingKeyKind::RsaModulusExponent { .. } => {
341+
Err(new_error(crate::errors::ErrorKind::InvalidKeyFormat))
342+
}
343+
}
344+
}

src/encoding.rs

+12-10
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,19 @@ use base64::{engine::general_purpose::STANDARD, Engine};
22
use serde::ser::Serialize;
33

44
use crate::algorithms::AlgorithmFamily;
5-
use crate::crypto::hmac::HmacSecret;
65
use crate::crypto::JwtSigner;
76
use crate::errors::{new_error, ErrorKind, Result};
87
use crate::header::Header;
98
#[cfg(feature = "use_pem")]
109
use crate::pem::decoder::PemEncodedKey;
1110
use crate::serialization::{b64_encode, b64_encode_part};
12-
use crate::Algorithm;
11+
use crate::{Algorithm, DecodingKey};
1312

1413
// Crypto
1514
#[cfg(feature = "aws_lc_rs")]
1615
use crate::crypto::aws_lc::hmac::{Hs256, Hs384, Hs512};
1716
#[cfg(feature = "rust_crypto")]
18-
use crate::crypto::rust_crypto::hmac::{Hs256, Hs384, Hs512};
17+
use crate::crypto::rust_crypto::hmac::{Hs256Signer, Hs384Signer, Hs512Signer};
1918

2019
/// A key to encode a JWT with. Can be a secret, a PEM-encoded key or a DER-encoded key.
2120
/// This key can be re-used so make sure you only initialize it once if you can for better performance.
@@ -160,9 +159,9 @@ pub fn _encode<T: Serialize>(
160159
/// Return the correct [`JwtSigner`] based on the `algorithm`.
161160
fn jwt_signer_factory(algorithm: &Algorithm, key: &EncodingKey) -> Result<Box<dyn JwtSigner>> {
162161
let jwt_signer = match algorithm {
163-
Algorithm::HS256 => Box::new(Hs256::new(key.into())?) as Box<dyn JwtSigner>,
164-
Algorithm::HS384 => Box::new(Hs384::new(key.into())?) as Box<dyn JwtSigner>,
165-
Algorithm::HS512 => Box::new(Hs512::new(key.into())?) as Box<dyn JwtSigner>,
162+
Algorithm::HS256 => Box::new(Hs256Signer::new(key)?) as Box<dyn JwtSigner>,
163+
Algorithm::HS384 => Box::new(Hs384Signer::new(key)?) as Box<dyn JwtSigner>,
164+
Algorithm::HS512 => Box::new(Hs512Signer::new(key)?) as Box<dyn JwtSigner>,
166165
Algorithm::ES256 => todo!(),
167166
Algorithm::ES384 => todo!(),
168167
Algorithm::RS256 => todo!(),
@@ -177,9 +176,12 @@ fn jwt_signer_factory(algorithm: &Algorithm, key: &EncodingKey) -> Result<Box<dy
177176
Ok(jwt_signer)
178177
}
179178

180-
/// Convert an [`&EncodingKey`] to an [`HmacSecret`].
181-
impl From<&EncodingKey> for HmacSecret {
182-
fn from(key: &EncodingKey) -> Self {
183-
HmacSecret::from_secret(&key.content)
179+
pub(crate) fn try_get_hmac_secret_from_encoding_key(
180+
encoding_key: &EncodingKey,
181+
) -> Result<&Vec<u8>> {
182+
if encoding_key.family == AlgorithmFamily::Hmac {
183+
Ok(&encoding_key.content)
184+
} else {
185+
Err(new_error(ErrorKind::InvalidKeyFormat))
184186
}
185187
}

src/lib.rs

-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ compile_error!(
99
);
1010

1111
pub use algorithms::Algorithm;
12-
pub use crypto::hmac::HmacSecret;
1312
pub use decoding::{decode, decode_header, DecodingKey, TokenData, _decode};
1413
pub use encoding::{encode, EncodingKey, _encode};
1514
pub use header::Header;

0 commit comments

Comments
 (0)