Skip to content

Commit

Permalink
chore: use different hex/base64 crates
Browse files Browse the repository at this point in the history
Signed-off-by: Henry Gressmann <[email protected]>
  • Loading branch information
explodingcamera committed Aug 22, 2023
1 parent d5aa520 commit 0b539b7
Show file tree
Hide file tree
Showing 9 changed files with 44 additions and 45 deletions.
9 changes: 2 additions & 7 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ version = "1.4.1"

[dependencies]
coarsetime = "0.1"
ct-codecs = "1.1"
base64ct = "1.6"
hex = "0.4"

# ecdsa
k256 = {version = "0.13", features = ["ecdsa", "std", "pkcs8", "pem"], optional = true}
Expand All @@ -35,10 +36,4 @@ ecdsa = ["dep:k256", "dep:p256", "dep:p384", "dep:rand"]
eddsa = ["dep:ed25519-compact"]

[profile.release]
codegen-units = 1
incremental = false
lto = "fat"
panic = "abort"

[profile.bench]
codegen-units = 1
10 changes: 5 additions & 5 deletions src/algorithms/eddsa.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use ct_codecs::{Base64UrlSafeNoPadding, Encoder};
use base64ct::Base64UrlUnpadded;
use base64ct::Encoding;
use serde::{de::DeserializeOwned, Serialize};
use sha2::Digest;

Expand Down Expand Up @@ -177,7 +178,7 @@ pub trait EdDSAPublicKeyLike {
fn create_key_id(&mut self) -> Result<String, JWTError> {
let mut hasher = sha2::Sha256::new();
hasher.update(self.public_key().to_bytes());
let key_id = Base64UrlSafeNoPadding::encode_to_string(hasher.finalize())?;
let key_id = Base64UrlUnpadded::encode_string(&hasher.finalize());
self.set_key_id(key_id.clone());
Ok(key_id)
}
Expand Down Expand Up @@ -332,8 +333,7 @@ impl Ed25519PublicKey {
pub fn sha256_thumbprint(&self) -> Result<String, JWTError> {
let mut hasher = sha2::Sha256::new();
hasher.update(self.to_der());
Ok(Base64UrlSafeNoPadding::encode_to_string(
hasher.finalize().as_slice(),
)?)

Ok(Base64UrlUnpadded::encode_string(&hasher.finalize()))
}
}
4 changes: 2 additions & 2 deletions src/algorithms/es256.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::convert::TryFrom;

use ct_codecs::{Base64UrlSafeNoPadding, Encoder};
use base64ct::{Base64UrlUnpadded, Encoding};
use p256::ecdsa::{self, signature::DigestVerifier as _, signature::RandomizedDigestSigner as _};
use p256::pkcs8::{DecodePrivateKey, DecodePublicKey, EncodePrivateKey, EncodePublicKey};
use p256::NonZeroScalar;
Expand Down Expand Up @@ -212,7 +212,7 @@ pub trait ECDSAP256PublicKeyLike {
fn create_key_id(&mut self) -> Result<String, JWTError> {
let mut hasher = sha2::Sha256::new();
hasher.update(self.public_key().to_bytes());
let key_id = Base64UrlSafeNoPadding::encode_to_string(hasher.finalize())?;
let key_id = Base64UrlUnpadded::encode_string(&hasher.finalize());
self.set_key_id(key_id.clone());
Ok(key_id)
}
Expand Down
4 changes: 2 additions & 2 deletions src/algorithms/es256k.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::convert::TryFrom;

use ct_codecs::{Base64UrlSafeNoPadding, Encoder};
use base64ct::{Base64UrlUnpadded, Encoding};
use k256::ecdsa::{self, signature::DigestVerifier as _, signature::RandomizedDigestSigner as _};
use k256::pkcs8::{DecodePrivateKey, DecodePublicKey, EncodePrivateKey, EncodePublicKey};
use serde::{de::DeserializeOwned, Serialize};
Expand Down Expand Up @@ -196,7 +196,7 @@ pub trait ECDSAP256kPublicKeyLike {
fn create_key_id(&mut self) -> Result<String, JWTError> {
let mut hasher = sha2::Sha256::new();
hasher.update(self.public_key().to_bytes());
let key_id = Base64UrlSafeNoPadding::encode_to_string(hasher.finalize())?;
let key_id = Base64UrlUnpadded::encode_string(&hasher.finalize());
self.set_key_id(key_id.clone());
Ok(key_id)
}
Expand Down
4 changes: 2 additions & 2 deletions src/algorithms/es384.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::convert::TryFrom;

use ct_codecs::{Base64UrlSafeNoPadding, Encoder};
use base64ct::{Base64UrlUnpadded, Encoding};
use p384::ecdsa::{self, signature::DigestVerifier as _, signature::RandomizedDigestSigner as _};
use p384::pkcs8::{DecodePrivateKey, DecodePublicKey, EncodePrivateKey, EncodePublicKey};
use p384::NonZeroScalar;
Expand Down Expand Up @@ -211,7 +211,7 @@ pub trait ECDSAP384PublicKeyLike {
fn create_key_id(&mut self) -> Result<String, JWTError> {
let mut hasher = sha2::Sha256::new();
hasher.update(self.public_key().to_bytes());
let key_id = Base64UrlSafeNoPadding::encode_to_string(hasher.finalize())?;
let key_id = Base64UrlUnpadded::encode_string(&hasher.finalize());
self.set_key_id(key_id.clone());
Ok(key_id)
}
Expand Down
11 changes: 4 additions & 7 deletions src/common.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::collections::HashSet;

use base64ct::{Base64UrlUnpadded, Encoding};
use coarsetime::{Duration, UnixTimeStamp};
use ct_codecs::{Base64UrlSafeNoPadding, Decoder, Encoder, Hex};

use crate::{claims::DEFAULT_TIME_TOLERANCE_SECS, ensure, JWTError};

Expand Down Expand Up @@ -109,16 +109,13 @@ impl KeyMetadata {
let thumbprint = certificate_sha256_thumbprint.to_string();
let mut bin = [0u8; 32];
if thumbprint.len() == 64 {
ensure!(
Hex::decode(&mut bin, &thumbprint, None)?.len() == bin.len(),
JWTError::InvalidCertThumprint
);
let thumbprint = Base64UrlSafeNoPadding::encode_to_string(bin)?;
hex::decode_to_slice(&thumbprint, &mut bin)?;
let thumbprint = Base64UrlUnpadded::encode_string(&bin);
self.certificate_sha256_thumbprint = Some(thumbprint);
return Ok(self);
}
ensure!(
Base64UrlSafeNoPadding::decode(&mut bin, &thumbprint, None)?.len() == bin.len(),
Base64UrlUnpadded::decode(&thumbprint, &mut bin)?.len() == bin.len(),
JWTError::InvalidCertThumprint
);
self.certificate_sha256_thumbprint = Some(thumbprint);
Expand Down
16 changes: 14 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ pub enum JWTError {
#[error("Token is too long")]
TokenTooLong,

#[error(transparent)]
Codec(#[from] ct_codecs::Error),
#[error("codec error: {0}")]
Codec(String),

#[error(transparent)]
Serde(#[from] serde_json::Error),
Expand All @@ -81,6 +81,18 @@ pub enum JWTError {
Ed25519(#[from] ed25519_compact::Error),
}

impl From<base64ct::Error> for JWTError {
fn from(e: base64ct::Error) -> JWTError {
JWTError::Codec(e.to_string())
}
}

impl From<hex::FromHexError> for JWTError {
fn from(e: hex::FromHexError) -> JWTError {
JWTError::Codec(e.to_string())
}
}

impl From<&str> for JWTError {
fn from(e: &str) -> JWTError {
JWTError::InternalError(e.into())
Expand Down
3 changes: 0 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,6 @@ pub mod prelude {
pub use std::collections::HashSet;

pub use coarsetime::{self, Clock, Duration, UnixTimeStamp};
pub use ct_codecs::{
Base64, Base64NoPadding, Base64UrlSafe, Base64UrlSafeNoPadding, Decoder as _, Encoder as _,
};
pub use serde::{Deserialize, Serialize};

pub use crate::algorithms::*;
Expand Down
28 changes: 13 additions & 15 deletions src/token.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use ct_codecs::{Base64UrlSafeNoPadding, Decoder, Encoder};
use base64ct::Base64UrlUnpadded;
use base64ct::Encoding;
use serde::{de::DeserializeOwned, Serialize};

use crate::claims::*;
Expand Down Expand Up @@ -100,15 +101,15 @@ impl Token {
let claims_json = serde_json::to_string(&claims)?;
let authenticated = format!(
"{}.{}",
Base64UrlSafeNoPadding::encode_to_string(jwt_header_json)?,
Base64UrlSafeNoPadding::encode_to_string(claims_json)?
Base64UrlUnpadded::encode_string(jwt_header_json.as_bytes()),
Base64UrlUnpadded::encode_string(claims_json.as_bytes())
);
let authentication_tag_or_signature = authentication_or_signature_fn(&authenticated)?;
let mut token = authenticated;
token.push('.');
token.push_str(&Base64UrlSafeNoPadding::encode_to_string(
authentication_tag_or_signature,
)?);
token.push_str(&Base64UrlUnpadded::encode_string(
&authentication_tag_or_signature,
));
Ok(token)
}

Expand Down Expand Up @@ -136,9 +137,8 @@ impl Token {
let claims_b64 = parts.next().ok_or(JWTError::CompactEncodingError)?;
let authentication_tag_b64 = parts.next().ok_or(JWTError::CompactEncodingError)?;
ensure!(parts.next().is_none(), JWTError::CompactEncodingError);
let jwt_header: JWTHeader = serde_json::from_slice(
&Base64UrlSafeNoPadding::decode_to_vec(jwt_header_b64, None)?,
)?;
let jwt_header: JWTHeader =
serde_json::from_slice(&Base64UrlUnpadded::decode_vec(jwt_header_b64)?)?;
if let Some(signature_type) = &jwt_header.signature_type {
let signature_type_uc = signature_type.to_uppercase();
ensure!(
Expand All @@ -157,12 +157,11 @@ impl Token {
return Err(JWTError::MissingJWTKeyIdentifier);
}
}
let authentication_tag =
Base64UrlSafeNoPadding::decode_to_vec(authentication_tag_b64, None)?;
let authentication_tag = Base64UrlUnpadded::decode_vec(authentication_tag_b64)?;
let authenticated = &token[..jwt_header_b64.len() + 1 + claims_b64.len()];
authentication_or_signature_fn(authenticated, &authentication_tag)?;
let claims: JWTClaims<CustomClaims> =
serde_json::from_slice(&Base64UrlSafeNoPadding::decode_to_vec(claims_b64, None)?)?;
serde_json::from_slice(&Base64UrlUnpadded::decode_vec(claims_b64)?)?;
claims.validate(&options)?;
Ok(claims)
}
Expand All @@ -176,9 +175,8 @@ impl Token {
jwt_header_b64.len() <= MAX_HEADER_LENGTH,
JWTError::HeaderTooLarge
);
let jwt_header: JWTHeader = serde_json::from_slice(
&Base64UrlSafeNoPadding::decode_to_vec(jwt_header_b64, None)?,
)?;
let jwt_header: JWTHeader =
serde_json::from_slice(&Base64UrlUnpadded::decode_vec(jwt_header_b64)?)?;
Ok(TokenMetadata { jwt_header })
}
}
Expand Down

0 comments on commit 0b539b7

Please sign in to comment.