#json-web #key #jwt-json #deserialize #key-type #jwk #conversion

jsonwebkey

JSON Web Key (JWK) (de)serialization, generation, and conversion

10 releases

0.3.5 Apr 21, 2022
0.3.4 Jul 28, 2021
0.3.2 Apr 28, 2021
0.3.1 Jan 26, 2021
0.0.3 Jul 13, 2020

#193 in Web programming

Download history 16065/week @ 2023-11-24 17955/week @ 2023-12-01 15873/week @ 2023-12-08 13074/week @ 2023-12-15 4514/week @ 2023-12-22 11505/week @ 2023-12-29 17309/week @ 2024-01-05 18076/week @ 2024-01-12 21848/week @ 2024-01-19 22074/week @ 2024-01-26 15504/week @ 2024-02-02 24384/week @ 2024-02-09 22135/week @ 2024-02-16 30317/week @ 2024-02-23 26344/week @ 2024-03-01 14341/week @ 2024-03-08

96,973 downloads per month
Used in 18 crates (10 directly)

MIT license

53KB
1K SLoC

jsonwebkey

crates.io docs.rs codecov

JSON Web Key (JWK) (de)serialization, generation, and conversion.

Goals

tl;dr: get keys into a format that can be used by other crates; be as safe as possible while doing so.

  • Serialization and deserialization of Required and Recommended key types (HS256, RS256, ES256)
  • Conversion to PEM for interop with existing JWT libraries (e.g., jsonwebtoken)
  • Key generation (particularly useful for testing)

Non-goals

  • be a fully-featured JOSE framework

Examples

Deserializing from JSON

extern crate jsonwebkey as jwk;
// Generated using https://mkjwk.org/.
let jwt_str = r#"{
   "kty": "oct",
   "use": "sig",
   "kid": "my signing key",
   "k": "Wpj30SfkzM_m0Sa_B2NqNw",
   "alg": "HS256"
}"#;
let the_jwk: jwk::JsonWebKey = jwt_str.parse().unwrap();
println!("{:#?}", the_jwk); // looks like `jwt_str` but with reordered fields.

Using with other crates

#[cfg(all(feature = "generate", feature = "jwt-convert"))] {
extern crate jsonwebtoken as jwt;
extern crate jsonwebkey as jwk;

#[derive(serde::Serialize, serde::Deserialize)]
struct TokenClaims {
   exp: usize
}

let mut my_jwk = jwk::JsonWebKey::new(jwk::Key::generate_p256());
my_jwk.set_algorithm(jwk::Algorithm::ES256);

let alg: jwt::Algorithm = my_jwk.algorithm.unwrap().into();
let token = jwt::encode(
    &jwt::Header::new(alg),
    &TokenClaims { exp: 1492 },
    &my_jwk.key.to_encoding_key(),
).unwrap();

let mut validation = jwt::Validation::new(alg);
validation.validate_exp = false;
jwt::decode::<TokenClaims>(&token, &my_jwk.key.to_decoding_key(), &validation).unwrap();
}

Features

  • pkcs-convert - enables Key::{to_der, to_pem}. This pulls in the yasna crate.
  • generate - enables Key::{generate_p256, generate_symmetric}. This pulls in the p256 and rand crates.
  • jwt-convert - enables conversions to types in the jsonwebtoken crate.

Dependencies

~1.2–4.5MB
~107K SLoC