Skip to content

Commit

Permalink
Add the JwtHmacKey type with the support for SM3
Browse files Browse the repository at this point in the history
  • Loading branch information
photino committed Oct 11, 2023
1 parent ab91000 commit 6bfa301
Show file tree
Hide file tree
Showing 11 changed files with 145 additions and 10 deletions.
5 changes: 4 additions & 1 deletion zino-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ version = "0.9.1"
features = ["macros"]

[dependencies.utoipa]
version = "3.5.0"
version = "4.0.0"
features = [
"non_strict_integers",
"preserve_order",
Expand All @@ -259,7 +259,10 @@ features = [
anyhow = "1.0.75"
base64-simd = "0.8.0"
criterion = "0.5.1"
data-encoding = "2.4.0"
libsm = "0.5.1"
ryu = "1.0.15"
sm3 = "0.4.2"
tinyvec = { version = "1.6.0", features = ["alloc"] }
uuid-simd = "0.8.0"

Expand Down
12 changes: 12 additions & 0 deletions zino-core/benches/base64_simd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ pub fn bench(c: &mut criterion::Criterion) {
base64_simd::STANDARD_NO_PAD.encode_to_string(bytes)
})
});
c.bench_function("data_encoding_base64_encode", |b| {
b.iter(|| {
let bytes = b"hello world";
data_encoding::BASE64_NOPAD.encode(bytes)
})
});
c.bench_function("base64_decode", |b| {
b.iter(|| {
let encoded = "Er/DkSLyeOsUiHXHK4hO7E8fdl1g8Qwy2Ef8mR1/4BQ";
Expand All @@ -31,4 +37,10 @@ pub fn bench(c: &mut criterion::Criterion) {
base64_simd::forgiving_decode_to_vec(encoded.as_bytes())
})
});
c.bench_function("data_encoding_base64_decode", |b| {
b.iter(|| {
let encoded = "Er/DkSLyeOsUiHXHK4hO7E8fdl1g8Qwy2Ef8mR1/4BQ";
data_encoding::BASE64_NOPAD.decode(encoded.as_bytes())
})
});
}
2 changes: 2 additions & 0 deletions zino-core/benches/criterion_main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ mod format_duration;
mod hashmap_vec;
mod json_raw_value;
mod serde_map;
mod sha256_sm3;
mod str_join;
mod uuid_simd;

Expand All @@ -15,6 +16,7 @@ criterion::criterion_group!(
hashmap_vec::bench,
json_raw_value::bench,
serde_map::bench,
sha256_sm3::bench,
str_join::bench,
uuid_simd::bench,
);
Expand Down
30 changes: 30 additions & 0 deletions zino-core/benches/sha256_sm3.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
pub fn bench(c: &mut criterion::Criterion) {
c.bench_function("sha256_digest", |b| {
b.iter(|| {
use sha2::{Digest, Sha256};

let data = b"Hellow, world!";
let mut hasher = Sha256::new();
hasher.update(data);
hasher.finalize()
})
});
c.bench_function("sm3_digest", |b| {
b.iter(|| {
use sm3::{Digest, Sm3};

let data = b"Hellow, world!";
let mut hasher = Sm3::new();
hasher.update(data);
hasher.finalize()
})
});
c.bench_function("libsm_digest", |b| {
b.iter(|| {
use libsm::sm3::hash::Sm3Hash;

let data = b"Hellow, world!";
Sm3Hash::new(data).get_hash()
})
});
}
2 changes: 1 addition & 1 deletion zino-core/benches/uuid_simd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use uuid::Uuid;
use uuid_simd::UuidExt;

pub fn bench(c: &mut criterion::Criterion) {
c.bench_function("formt_uuid", |b| {
c.bench_function("format_uuid", |b| {
b.iter(|| {
let value = Uuid::new_v4();
value.to_string()
Expand Down
97 changes: 91 additions & 6 deletions zino-core/src/auth/jwt_claims.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::{
JsonValue, Map,
};
use jwt_simple::{
algorithms::{HS256Key, MACLike},
algorithms::MACLike,
claims::{self, Claims, JWTClaims},
common::VerificationOptions,
};
Expand Down Expand Up @@ -130,9 +130,9 @@ impl JwtClaims<Map> {
}

impl JwtClaims<()> {
/// Returns the shared secret access key for the `HS256` JWT algorithm.
/// Returns the shared secret access key for the HMAC algorithm.
#[inline]
pub fn shared_key() -> &'static HS256Key {
pub fn shared_key() -> &'static JwtHmacKey {
LazyLock::force(&SECRET_KEY)
}
}
Expand Down Expand Up @@ -190,8 +190,8 @@ static DEFAULT_REFRESH_INTERVAL: LazyLock<Duration> = LazyLock::new(|| {
.unwrap_or_else(|| Duration::from_secs(60 * 60 * 24 * 30))
});

/// Shared secret access key for the `HS256` JWT algorithm.
static SECRET_KEY: LazyLock<HS256Key> = LazyLock::new(|| {
/// Shared secret access key for the HMAC algorithm.
static SECRET_KEY: LazyLock<JwtHmacKey> = LazyLock::new(|| {
let config = State::shared().config();
let checksum: [u8; 32] = config
.get_table("jwt")
Expand All @@ -210,5 +210,90 @@ static SECRET_KEY: LazyLock<HS256Key> = LazyLock::new(|| {
crypto::digest(app_name.as_bytes())
});
let secret_key = crypto::derive_key("ZINO:JWT", &checksum);
HS256Key::from_bytes(&secret_key)
JwtHmacKey::from_bytes(&secret_key)
});

cfg_if::cfg_if! {
if #[cfg(feature = "crypto-sm")] {
use hmac::{Hmac, Mac};
use jwt_simple::{algorithms::HMACKey, common::KeyMetadata};
use sm3::Sm3;

/// HMAC-SM3 key type.
#[derive(Debug, Clone)]
pub struct HSm3Key {
/// key.
key: HMACKey,
/// Key ID.
key_id: Option<String>,
}

impl HSm3Key {
/// Creates a new instance from bytes.
pub fn from_bytes(raw_key: &[u8]) -> Self {
Self {
key: HMACKey::from_bytes(raw_key),
key_id: None,
}
}

/// Returns the bytes.
pub fn to_bytes(&self) -> Vec<u8> {
self.key.to_bytes()
}

/// Generates a new instance with random bytes.
pub fn generate() -> Self {
Self {
key: HMACKey::generate(),
key_id: None,
}
}

/// Set the key ID.
pub fn with_key_id(mut self, key_id: &str) -> Self {
self.key_id = Some(key_id.to_owned());
self
}
}

impl MACLike for HSm3Key {
fn jwt_alg_name() -> &'static str {
"HSM3"
}

fn key(&self) -> &HMACKey {
&self.key
}

fn key_id(&self) -> &Option<String> {
&self.key_id
}

fn set_key_id(&mut self, key_id: String) {
self.key_id = Some(key_id);
}

fn metadata(&self) -> &Option<KeyMetadata> {
&None
}

fn attach_metadata(&mut self, _metadata: KeyMetadata) -> Result<(), jwt_simple::Error> {
Ok(())
}

fn authentication_tag(&self, authenticated: &str) -> Vec<u8> {
let mut mac = Hmac::<Sm3>::new_from_slice(self.key().as_ref())
.expect("HMAC can take key of any size");
mac.update(authenticated.as_bytes());
mac.finalize().into_bytes().to_vec()
}
}

/// HMAC key type for JWT.
pub type JwtHmacKey = HSm3Key;
} else {
/// HMAC key type for JWT.
pub type JwtHmacKey = jwt_simple::algorithms::HS256Key;
}
}
2 changes: 1 addition & 1 deletion zino-core/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub use access_key::{AccessKeyId, SecretAccessKey};
pub use authentication::Authentication;
pub use authorization_provider::AuthorizationProvider;
pub use client_credentials::ClientCredentials;
pub use jwt_claims::JwtClaims;
pub use jwt_claims::{JwtClaims, JwtHmacKey};
pub use security_token::SecurityToken;
pub use session_id::SessionId;
pub use user_session::UserSession;
1 change: 1 addition & 0 deletions zino-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
//!
//! [`zino`]: https://github.com/photino/zino

#![allow(async_fn_in_trait)]
#![doc(html_favicon_url = "https://photino.github.io/zino-docs-zh/assets/zino-logo.png")]
#![doc(html_logo_url = "https://photino.github.io/zino-docs-zh/assets/zino-logo.svg")]
#![feature(associated_type_defaults)]
Expand Down
1 change: 1 addition & 0 deletions zino-model/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
//!
//! [`zino`]: https://github.com/photino/zino

#![allow(async_fn_in_trait)]
#![doc(html_favicon_url = "https://photino.github.io/zino-docs-zh/assets/zino-logo.png")]
#![doc(html_logo_url = "https://photino.github.io/zino-docs-zh/assets/zino-logo.svg")]
#![feature(async_fn_in_trait)]
Expand Down
2 changes: 1 addition & 1 deletion zino/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ version = "3.5.0"
optional = true

[dependencies.utoipa-rapidoc]
version = "0.1.0"
version = "1.0.0"
optional = true

[dependencies.zino-core]
Expand Down
1 change: 1 addition & 0 deletions zino/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
//! [`axum-app`]: https://github.com/photino/zino/tree/main/examples/axum-app
//! [`dioxus-desktop`]: https://github.com/photino/zino/tree/main/examples/dioxus-desktop

#![allow(async_fn_in_trait)]
#![doc(html_favicon_url = "https://photino.github.io/zino-docs-zh/assets/zino-logo.png")]
#![doc(html_logo_url = "https://photino.github.io/zino-docs-zh/assets/zino-logo.svg")]
#![feature(async_fn_in_trait)]
Expand Down

0 comments on commit 6bfa301

Please sign in to comment.