### Sign and Verify JWT with RSA-SHA256 in Rust Source: https://context7.com/hidekatsu-izuno/josekit-rs/llms.txt Illustrates signing and verifying a JWT using the RS256 RSA algorithm in Rust. This method employs asymmetric cryptography, requiring a private key for signing and a public key for verification. Keys can be loaded from PEM, DER, or JWK formats. The example shows setting custom claims. ```rust use josekit::{JoseError, jws::{JwsHeader, RS256}, jwt::{self, JwtPayload}}; use std::fs; fn main() -> Result<(), JoseError> { let mut header = JwsHeader::new(); header.set_token_type("JWT"); header.set_key_id("my-key-id"); let mut payload = JwtPayload::new(); payload.set_subject("user@example.com"); payload.set_claim("role", Some(serde_json::json!("admin")))?; // Load RSA keys from PEM files let private_key = fs::read("private.pem").expect("Failed to read private key"); let public_key = fs::read("public.pem").expect("Failed to read public key"); // Sign with private key let signer = RS256.signer_from_pem(&private_key)?; let jwt = jwt::encode_with_signer(&payload, &header, &signer)?; println!("JWT: {}", jwt); // Verify with public key let verifier = RS256.verifier_from_pem(&public_key)?; let (payload, header) = jwt::decode_with_verifier(&jwt, &verifier)?; println!("Algorithm: {:?}", header.algorithm()); println!("Custom claim: {:?}", payload.claim("role")); Ok(()) } ``` -------------------------------- ### JWT Encryption with Password-Based Encryption (PBES2) in Rust Source: https://context7.com/hidekatsu-izuno/josekit-rs/llms.txt Encrypts and decrypts JWTs using PBES2 algorithms, which derive encryption keys from passwords. This is useful for creating password-protected JWTs. The example uses `PBES2_HS256_A128KW` and requires the `josekit` crate. It demonstrates setting up headers, payloads, and using password-derived encrypters and decrypters. ```rust use josekit::{JoseError, jwe::{JweHeader, PBES2_HS256_A128KW}, jwt::{self, JwtPayload}}; fn main() -> Result<(), JoseError> { let mut header = JweHeader::new(); header.set_token_type("JWT"); header.set_content_encryption("A128GCM"); let mut payload = JwtPayload::new(); payload.set_subject("password-protected-user"); // Password can be any length (recommended: 16+ bytes) let password = b"my-secure-password"; let encrypter = PBES2_HS256_A128KW.encrypter_from_bytes(password)?; let jwt = jwt::encode_with_encrypter(&payload, &header, &encrypter)?; let decrypter = PBES2_HS256_A128KW.decrypter_from_bytes(password)?; let (payload, _) = jwt::decode_with_decrypter(&jwt, &decrypter)?; println!("Subject: {:?}", payload.subject()); Ok(()) } ``` -------------------------------- ### Sign and Verify JWT with ECDSA-P256 in Rust Source: https://context7.com/hidekatsu-izuno/josekit-rs/llms.txt Demonstrates signing and verifying a JWT using the ES256 ECDSA algorithm in Rust, which utilizes the P-256 elliptic curve. This method offers strong security with compact signatures. The example shows loading EC keys from PEM files and setting standard JWT claims. ```rust use josekit::{JoseError, jws::{JwsHeader, ES256}, jwt::{self, JwtPayload}}; use std::fs; fn main() -> Result<(), JoseError> { let mut header = JwsHeader::new(); header.set_token_type("JWT"); let mut payload = JwtPayload::new(); payload.set_subject("device-001"); payload.set_issuer("iot-gateway"); // Load EC keys (P-256 curve for ES256) let private_key = fs::read("ec_private.pem").expect("Failed to read key"); let public_key = fs::read("ec_public.pem").expect("Failed to read key"); // Sign JWT let signer = ES256.signer_from_pem(&private_key)?; let jwt = jwt::encode_with_signer(&payload, &header, &signer)?; // Verify JWT let verifier = ES256.verifier_from_pem(&public_key)?; let (payload, _) = jwt::decode_with_verifier(&jwt, &verifier)?; println!("Subject: {:?}", payload.subject()); Ok(()) } ``` -------------------------------- ### JWT Payload Validation with JwtPayloadValidator in Rust Source: https://context7.com/hidekatsu-izuno/josekit-rs/llms.txt Validates JWT payloads using the `JwtPayloadValidator` from the `josekit` crate. This validator supports both time-based claims (exp, nbf, iat) and value-based claims (iss, sub, aud, jti). The example shows how to configure the validator with specific issuer, audience, JWT ID, and time constraints, and then use it to validate a `JwtPayload` object. ```rust use josekit::{JoseError, jwt::{JwtPayload, JwtPayloadValidator}}; use std::time::{Duration, SystemTime}; fn main() -> Result<(), JoseError> { // Create a payload to validate let mut payload = JwtPayload::new(); payload.set_issuer("https://auth.example.com"); payload.set_subject("user123"); payload.set_audience(vec!["https://api.example.com"]); payload.set_expires_at(&(SystemTime::now() + Duration::from_secs(3600))); payload.set_not_before(&(SystemTime::now() - Duration::from_secs(60))); payload.set_issued_at(&SystemTime::now()); payload.set_jwt_id("token-id-12345"); // Configure validator let mut validator = JwtPayloadValidator::new(); // Value-based validation validator.set_issuer("https://auth.example.com"); validator.set_audience("https://api.example.com"); validator.set_jwt_id("token-id-12345"); // Time-based validation: nbf <= base_time < exp validator.set_base_time(SystemTime::now()); // Issued time validation: min <= iat <= max validator.set_min_issued_time(SystemTime::now() - Duration::from_secs(300)); validator.set_max_issued_time(SystemTime::now() + Duration::from_secs(60)); // Validate the payload match validator.validate(&payload) { Ok(()) => println!("Token is valid!"), Err(e) => println!("Validation failed: {}", e), } Ok(()) } ``` -------------------------------- ### Handle Unsecured JWT Source: https://github.com/hidekatsu-izuno/josekit-rs/blob/master/README.md Demonstrates how to encode and decode unsecured JWTs, which do not require cryptographic keys for signing or encryption. ```rust use josekit::{JoseError, jws::JwsHeader, jwt::{self, JwtPayload}}; fn main() -> Result<(), JoseError> { let mut header = JwsHeader::new(); header.set_token_type("JWT"); let mut payload = JwtPayload::new(); payload.set_subject("subject"); let jwt = jwt::encode_unsecured(&payload, &header)?; let (payload, header) = jwt::decode_unsecured(&jwt)?; Ok(()) } ``` -------------------------------- ### Encrypt and Decrypt JWT using RSAES Source: https://github.com/hidekatsu-izuno/josekit-rs/blob/master/README.md Demonstrates asymmetric JWT encryption using RSA-OAEP. Includes OpenSSL commands for key generation and Rust code for PEM-based encryption/decryption. ```sh # Generate a new private key. Keygen bits must be 2048 or more. openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out private.pem # Generate a public key from the private key. openssl pkey -in private.pem -pubout -out public.pem ``` ```rust use josekit::{JoseError, jwe::{JweHeader, RSA_OAEP}, jwt::{self, JwtPayload}}; const PRIVATE_KEY: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/data/pem/RSA_2048bit_private.pem"); const PUBLIC_KEY: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/data/pem/RSA_2048bit_public.pem"); fn main() -> Result<(), JoseError> { let mut header = JweHeader::new(); header.set_token_type("JWT"); header.set_content_encryption("A128CBC-HS256"); let mut payload = JwtPayload::new(); payload.set_subject("subject"); // Encrypting JWT let public_key = std::fs::read(PUBLIC_KEY).unwrap(); let encrypter = RSA_OAEP.encrypter_from_pem(&public_key)?; let jwt = jwt::encode_with_encrypter(&payload, &header, &encrypter)?; // Decrypting JWT let private_key = std::fs::read(PRIVATE_KEY).unwrap(); let decrypter = RSA_OAEP.decrypter_from_pem(&private_key)?; let (payload, header) = jwt::decode_with_decrypter(&jwt, &decrypter)?; Ok(()) } ``` -------------------------------- ### JWS Compact Serialization in Rust Source: https://context7.com/hidekatsu-izuno/josekit-rs/llms.txt Demonstrates creating and verifying a JWS using compact serialization in Rust. This format is suitable for HTTP headers and URL parameters. It requires private and public keys for signing and verification respectively. ```rust use josekit::{JoseError, jws::{self, JwsHeader, RS256}}; use std::fs; fn main() -> Result<(), JoseError> { let mut header = JwsHeader::new(); header.set_token_type("JWT"); header.set_key_id("signing-key-001"); let payload = b"This is the message to sign"; let private_key = fs::read("rsa_private.pem").expect("Failed to read key"); let public_key = fs::read("rsa_public.pem").expect("Failed to read key"); // Create compact JWS let signer = RS256.signer_from_pem(&private_key)?; let jws_compact = jws::serialize_compact(payload, &header, &signer)?; println!("JWS: {}", jws_compact); // Verify and deserialize let verifier = RS256.verifier_from_pem(&public_key)?; let (decoded_payload, decoded_header) = jws::deserialize_compact(&jws_compact, &verifier)?; println!("Payload: {}", String::from_utf8_lossy(&decoded_payload)); println!("Key ID: {:?}", decoded_header.key_id()); Ok(()) } ``` -------------------------------- ### Generate Public Key from Private Key using OpenSSL Source: https://github.com/hidekatsu-izuno/josekit-rs/blob/master/README.md This command generates a public key file from a given private key file using the OpenSSL command-line tool. It takes the private key as input and outputs the corresponding public key. ```shell openssl pkey -in private.pem -pubout -out public.pem ``` -------------------------------- ### Sign and Verify JWT with RSASSA in Rust Source: https://github.com/hidekatsu-izuno/josekit-rs/blob/master/README.md Illustrates signing and verifying a JWT using RSASSA algorithms (RS256, RS384, RS512) with RSA public/private key pairs. Requires the `josekit` crate and OpenSSL for key generation. Keys are loaded from PEM files. ```rust use josekit::{JoseError, jws::{JwsHeader, RS256}, jwt::{self, JwtPayload}}; const PRIVATE_KEY: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/data/pem/RSA_2048bit_private.pem"); const PUBLIC_KEY: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/data/pem/RSA_2048bit_public.pem"); fn main() -> Result<(), JoseError> { let mut header = JwsHeader::new(); header.set_token_type("JWT"); let mut payload = JwtPayload::new(); payload.set_subject("subject"); // Signing JWT let private_key = std::fs::read(PRIVATE_KEY).unwrap(); let signer = RS256.signer_from_pem(&private_key)?; let jwt = jwt::encode_with_signer(&payload, &header, &signer)?; // Verifing JWT let public_key = std::fs::read(PUBLIC_KEY).unwrap(); let verifier = RS256.verifier_from_pem(&public_key)?; let (payload, header) = jwt::decode_with_verifier(&jwt, &verifier)?; Ok(()) } ``` -------------------------------- ### Load and use JWK for signing and verification in Rust Source: https://context7.com/hidekatsu-izuno/josekit-rs/llms.txt Illustrates loading JSON Web Keys (JWK) from files and utilizing them to create signers or verifiers. This is essential for secure token handling using asymmetric algorithms like RS256. ```rust use josekit::{JoseError, jwk::Jwk, jws::RS256, jwt::{self, JwtPayload}}; use std::fs; fn main() -> Result<(), JoseError> { // Load JWK from file let jwk_bytes = fs::read("key.jwk").expect("Failed to read JWK file"); let jwk = Jwk::from_bytes(&jwk_bytes)?; // Check key properties println!("Key Type: {}", jwk.key_type()); println!("Key ID: {:?}", jwk.key_id()); println!("Algorithm: {:?}", jwk.algorithm()); println!("Key Use: {:?}", jwk.key_use()); // Create verifier from JWK let verifier = RS256.verifier_from_jwk(&jwk)?; // Create signer from JWK (if it contains private key) let signer = RS256.signer_from_jwk(&jwk)?; let mut payload = JwtPayload::new(); payload.set_subject("from-jwk"); let mut header = josekit::jws::JwsHeader::new(); header.set_token_type("JWT"); let jwt = jwt::encode_with_signer(&payload, &header, &signer)?; println!("Signed JWT: {}", jwt); Ok(()) } ``` -------------------------------- ### Sign and Verify JWT with RSA-PSS in Rust Source: https://github.com/hidekatsu-izuno/josekit-rs/blob/master/README.md This Rust code snippet demonstrates signing a JWT using the RSA-PSS algorithm with a private key and then verifying the signature using the corresponding public key. It utilizes the josekit library for JWT operations and file system operations to read key files. ```rust use josekit::{JoseError, jws::{JwsHeader, PS256}, jwt::{self, JwtPayload}}; const PRIVATE_KEY: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/data/pem/RSA-PSS_2048bit_SHA-256_private.pem"); const PUBLIC_KEY: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/data/pem/RSA-PSS_2048bit_SHA-256_public.pem"); fn main() -> Result<(), JoseError> { let mut header = JwsHeader::new(); header.set_token_type("JWT"); let mut payload = JwtPayload::new(); payload.set_subject("subject"); // Signing JWT let private_key = std::fs::read(PRIVATE_KEY).unwrap(); let signer = PS256.signer_from_pem(&private_key)?; let jwt = jwt::encode_with_signer(&payload, &header, &signer)?; // Verifing JWT let public_key = std::fs::read(PUBLIC_KEY).unwrap(); let verifier = PS256.verifier_from_pem(&public_key)?; let (payload, header) = jwt::decode_with_verifier(&jwt, &verifier)?; Ok(()) } ``` -------------------------------- ### JWK Generation and Management in Rust Source: https://context7.com/hidekatsu-izuno/josekit-rs/llms.txt Demonstrates generating and managing cryptographic keys in JWK (JSON Web Key) format using the `Jwk` struct from the `josekit` crate. It covers generating various key types (symmetric, RSA, EC, Ed, ECX) and curves, extracting public keys, and loading JWKs from JSON. Metadata like key ID, use, and algorithm can also be set. ```rust use josekit::{JoseError, jwk::{Jwk, P_256, Ed25519, X25519}}; fn main() -> Result<(), JoseError> { // Generate symmetric key (oct type) let oct_key = Jwk::generate_oct_key(32)?; println!("OCT key: {}", oct_key); // Generate RSA key pair let rsa_key = Jwk::generate_rsa_key(2048)?; println!("RSA key type: {}", rsa_key.key_type()); // Generate EC key pair (P-256 curve) let ec_key = Jwk::generate_ec_key(P_256)?; println!("EC curve: {:?}", ec_key.curve()); // Generate Ed key pair (Ed25519) let ed_key = Jwk::generate_ed_key(Ed25519)?; println!("Ed curve: {:?}", ed_key.curve()); // Generate ECX key pair (X25519 for key agreement) let ecx_key = Jwk::generate_ecx_key(X25519)?; println!("ECX curve: {:?}", ecx_key.curve()); // Extract public key from key pair let public_key = ec_key.to_public_key()?; println!("Public key: {}", public_key); // Load JWK from JSON let jwk_json = r#"{"kty":"oct","k":"AyM32w-8kLL5T0qBLSnFZ1-TN3zfpnpVxX2J5Rn_Lk8"}"#; let loaded_jwk = Jwk::from_bytes(jwk_json)?; println!("Loaded key type: {}", loaded_jwk.key_type()); // Set JWK metadata let mut jwk = Jwk::generate_ec_key(P_256)?; jwk.set_key_id("my-key-2024"); jwk.set_key_use("sig"); jwk.set_algorithm("ES256"); Ok(()) } ``` -------------------------------- ### Generate RSASSA-PSS Keys using OpenSSL Source: https://github.com/hidekatsu-izuno/josekit-rs/blob/master/README.md Shows OpenSSL commands for generating RSA private keys specifically for RSASSA-PSS signing with different hash and salt length options. Requires keygen bits to be 2048 or more. ```sh # Generate a new private key # for PS256 openssl genpkey -algorithm RSA-PSS -pkeyopt rsa_keygen_bits:2048 -pkeyopt rsa_pss_keygen_md:sha256 -pkeyopt rsa_pss_keygen_mgf1_md:sha256 -pkeyopt rsa_pss_keygen_saltlen:32 -out private.pem # for PS384 openssl genpkey -algorithm RSA-PSS -pkeyopt rsa_keygen_bits:2048 -pkeyopt rsa_pss_keygen_md:sha384 -pkeyopt rsa_pss_keygen_mgf1_md:sha384 -pkeyopt rsa_pss_keygen_saltlen:48 -out private.pem # for PS512 openssl genpkey -algorithm RSA-PSS -pkeyopt rsa_keygen_bits:2048 -pkeyopt rsa_pss_keygen_md:sha512 -pkeyopt rsa_pss_keygen_mgf1_md:sha512 -pkeyopt rsa_pss_keygen_saltlen:64 -out private.pem ``` -------------------------------- ### Sign and Verify JWT with HMAC in Rust Source: https://github.com/hidekatsu-izuno/josekit-rs/blob/master/README.md Demonstrates signing and verifying a JWT using HMAC algorithms (HS256, HS384, HS512) with a shared secret key. Requires the `josekit` crate. The key must be at least as long as the output hash size. ```rust use josekit::{JoseError, jws::{JwsHeader, HS256}, jwt::{self, JwtPayload}}; fn main() -> Result<(), JoseError> { let mut header = JwsHeader::new(); header.set_token_type("JWT"); let mut payload = JwtPayload::new(); payload.set_subject("subject"); let key = b"0123456789ABCDEF0123456789ABCDEF"; // Signing JWT let signer = HS256.signer_from_bytes(key)?; let jwt = jwt::encode_with_signer(&payload, &header, &signer)?; // Verifing JWT let verifier = HS256.verifier_from_bytes(key)?; let (payload, header) = jwt::decode_with_verifier(&jwt, &verifier)?; Ok(()) } ``` -------------------------------- ### Encrypt and Decrypt JWT using PBES2-HMAC+AESKW Source: https://github.com/hidekatsu-izuno/josekit-rs/blob/master/README.md Demonstrates JWT encryption and decryption using PBES2-HMAC+AES key wrapping. Uses a password-based key derivation approach. ```rust use josekit::{JoseError, jwe::{JweHeader, PBES2_HS256_A128KW}, jwt::{self, JwtPayload}}; fn main() -> Result<(), JoseError> { let mut header = JweHeader::new(); header.set_token_type("JWT"); header.set_content_encryption("A128CBC-HS256"); let mut payload = JwtPayload::new(); payload.set_subject("subject"); let key = b"01234567"; // Encrypting JWT let encrypter = PBES2_HS256_A128KW.encrypter_from_bytes(key)?; let jwt = jwt::encode_with_encrypter(&payload, &header, &encrypter)?; // Decrypting JWT let decrypter = PBES2_HS256_A128KW.decrypter_from_bytes(key)?; let (payload, header) = jwt::decode_with_decrypter(&jwt, &decrypter)?; Ok(()) } ``` -------------------------------- ### Create and decode unsecured JWTs with Rust Source: https://context7.com/hidekatsu-izuno/josekit-rs/llms.txt Demonstrates how to encode and decode JWTs using the 'none' algorithm. This approach lacks cryptographic protection and is intended only for testing or trusted environments. ```rust use josekit::{JoseError, jws::JwsHeader, jwt::{self, JwtPayload}}; fn main() -> Result<(), JoseError> { let mut header = JwsHeader::new(); header.set_token_type("JWT"); let mut payload = JwtPayload::new(); payload.set_subject("test-user"); payload.set_claim("debug", Some(serde_json::json!(true)))?; // Encode unsecured JWT (no signature) let jwt = jwt::encode_unsecured(&payload, &header)?; println!("Unsecured JWT: {}", jwt); // Decode unsecured JWT let (decoded_payload, decoded_header) = jwt::decode_unsecured(&jwt)?; println!("Algorithm: {:?}", decoded_header.algorithm()); // "none" println!("Subject: {:?}", decoded_payload.subject()); Ok(()) } ``` -------------------------------- ### Generate and export RSA keys with Web Crypto API Source: https://github.com/hidekatsu-izuno/josekit-rs/blob/master/data/memo.md Demonstrates generating an RSA-OAEP key pair using the browser's Web Crypto API and exporting the private key in PKCS#8 format or public key in SPKI format. The exported keys are base64 encoded for storage or transmission. ```javascript const key_pair = await window.crypto.subtle.generateKey( { name: "RSA-OAEP", modulusLength: 2048, publicExponent: new Uint8Array([0x01, 0x00, 0x01]), hash: {name: "SHA-256"} }, true, ["encrypt", "decrypt"] ); btoa(String.fromCharCode(...new Uint8Array(await window.crypto.subtle.exportKey("pkcs8", key_pair.privateKey)))); btoa(String.fromCharCode(...new Uint8Array(await window.crypto.subtle.exportKey("spki", result.publicKey)))); ``` -------------------------------- ### Generate RSA Private and Public Keys using OpenSSL Source: https://github.com/hidekatsu-izuno/josekit-rs/blob/master/README.md Provides OpenSSL commands to generate RSA private and public key pairs for use with RSASSA and RSASSA-PSS signing algorithms. Keygen bits must be 2048 or more. ```sh # Generate a new private key. Keygen bits must be 2048 or more. openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out private.pem # Generate a public key from the private key. openssl pkey -in private.pem -pubout -out public.pem ``` -------------------------------- ### Sign and Verify JWT with EdDSA in Rust Source: https://github.com/hidekatsu-izuno/josekit-rs/blob/master/README.md This Rust code snippet demonstrates signing a JWT using the EdDSA algorithm with a private key and subsequently verifying it using the public key. It leverages the josekit library for cryptographic functions and standard library features for file handling. ```rust use josekit::{JoseError, jws::{JwsHeader, EdDSA}, jwt::{self, JwtPayload}}; const PRIVATE_KEY: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/data/pem/ED25519_private.pem"); const PUBLIC_KEY: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/data/pem/ED25519_public.pem"); fn main() -> Result<(), JoseError> { let mut header = JwsHeader::new(); header.set_token_type("JWT"); let mut payload = JwtPayload::new(); payload.set_subject("subject"); // Signing JWT let private_key = std::fs::read(PRIVATE_KEY).unwrap(); let signer = EdDSA.signer_from_pem(&private_key)?; let jwt = jwt::encode_with_signer(&payload, &header, &signer)?; // Verifing JWT let public_key = std::fs::read(PUBLIC_KEY).unwrap(); let verifier = EdDSA.verifier_from_pem(&public_key)?; let (payload, header) = jwt::decode_with_verifier(&jwt, &verifier)?; Ok(()) } ``` -------------------------------- ### Manage RSA Keypairs with OpenSSL Source: https://github.com/hidekatsu-izuno/josekit-rs/blob/master/data/memo.md Commands for generating RSA 2048-bit keys and converting between PKCS#8 and PKCS#1 formats in both PEM and DER encodings. ```bash openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out rsa_2048_private.pem openssl pkey -in rsa_2048_private.pem -pubout -outform PEM -out rsa_2048_public.pem openssl pkcs8 -nocrypt -in rsa_2048_private.pem -topk8 -outform DER -out rsa_2048_private.der openssl pkey -in rsa_2048_private.pem -pubout -outform DER -out rsa_2048_public.der openssl pkey -inform DER -in rsa_2048_private.der -out rsa_2048_private.pem openssl pkcs8 -nocrypt -in rsa_2048_private.pem -traditional -out rsa_2048_pk1_private.pem openssl pkey -in rsa_2048_private.pem -outform DER -out rsa_2048_pk1_private.der openssl pkcs8 -nocrypt -in rsa_2048_pk1_private.pem -topk8 -out rsa_2048_private.pem openssl rsa -in rsa_2048_private.pem -RSAPublicKey_out -out rsa_2048_pk1_public.pem openssl rsa -in rsa_2048_private.pem -RSAPublicKey_out -outform DER -out rsa_2048_pk1_public.der ``` -------------------------------- ### Encrypt and Decrypt JWT using AES-GCM Source: https://github.com/hidekatsu-izuno/josekit-rs/blob/master/README.md Demonstrates JWT encryption and decryption using AES-GCM key wrapping algorithms (A128GCMKW). Requires a symmetric key of appropriate size. ```rust use josekit::{JoseError, jwe::{JweHeader, A128GCMKW}, jwt::{self, JwtPayload}}; fn main() -> Result<(), JoseError> { let mut header = JweHeader::new(); header.set_token_type("JWT"); header.set_content_encryption("A128CBC-HS256"); let mut payload = JwtPayload::new(); payload.set_subject("subject"); let key = b"0123456789ABCDEF"; // Encrypting JWT let encrypter = A128GCMKW.encrypter_from_bytes(key)?; let jwt = jwt::encode_with_encrypter(&payload, &header, &encrypter)?; // Decrypting JWT let decrypter = A128GCMKW.decrypter_from_bytes(key)?; let (payload, header) = jwt::decode_with_decrypter(&jwt, &decrypter)?; Ok(()) } ``` -------------------------------- ### Sign and Verify JWT with EdDSA in Rust Source: https://context7.com/hidekatsu-izuno/josekit-rs/llms.txt Demonstrates how to sign and verify a JWT using the EdDSA algorithm with Ed25519 keys. It loads PEM-encoded keys from the filesystem and uses the josekit library to perform cryptographic operations. ```rust use josekit::{JoseError, jws::{JwsHeader, EdDSA}, jwt::{self, JwtPayload}}; use std::fs; fn main() -> Result<(), JoseError> { let mut header = JwsHeader::new(); header.set_token_type("JWT"); let mut payload = JwtPayload::new(); payload.set_subject("user123"); // Load Ed25519 keys let private_key = fs::read("ed25519_private.pem").expect("Failed to read key"); let public_key = fs::read("ed25519_public.pem").expect("Failed to read key"); // Sign with EdDSA let signer = EdDSA.signer_from_pem(&private_key)?; let jwt = jwt::encode_with_signer(&payload, &header, &signer)?; // Verify with EdDSA let verifier = EdDSA.verifier_from_pem(&public_key)?; let (payload, _) = jwt::decode_with_verifier(&jwt, &verifier)?; println!("Verified subject: {:?}", payload.subject()); Ok(()) } ``` -------------------------------- ### Sign and Verify JWT with ECDSA in Rust Source: https://github.com/hidekatsu-izuno/josekit-rs/blob/master/README.md This Rust code snippet demonstrates signing a JWT using the ECDSA ES256 algorithm with a private key and then verifying the signature using the corresponding public key. It relies on the josekit library for cryptographic operations and standard file I/O for key management. ```rust use josekit::{JoseError, jws::{JwsHeader, ES256}, jwt::{self, JwtPayload}}; const PRIVATE_KEY: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/data/pem/EC_P-256_private.pem"); const PUBLIC_KEY: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/data/pem/EC_P-256_public.pem"); fn main() -> Result<(), JoseError> { let mut header = JwsHeader::new(); header.set_token_type("JWT"); let mut payload = JwtPayload::new(); payload.set_subject("subject"); // Signing JWT let private_key = std::fs::read(PRIVATE_KEY).unwrap(); let signer = ES256.signer_from_pem(&private_key)?; let jwt = jwt::encode_with_signer(&payload, &header, &signer)?; // Verifing JWT let public_key = std::fs::read(PUBLIC_KEY).unwrap(); let verifier = ES256.verifier_from_pem(&public_key)?; let (payload, header) = jwt::decode_with_verifier(&jwt, &verifier)?; Ok(()) } ``` -------------------------------- ### Manage RSA-PSS Keypairs with OpenSSL Source: https://github.com/hidekatsu-izuno/josekit-rs/blob/master/data/memo.md Commands for generating RSA-PSS keys with specific digest and salt lengths, and converting them between PKCS#8 PEM and DER formats. ```bash openssl genpkey -algorithm RSA-PSS -pkeyopt rsa_keygen_bits:2048 -pkeyopt rsa_pss_keygen_md:sha256 -pkeyopt rsa_pss_keygen_mgf1_md:sha256 -pkeyopt rsa_pss_keygen_saltlen:32 -out rsapss_2048_sha256_pkcs8_private.pem openssl pkey -in rsapss_2048_sha256_pkcs8_private.pem -pubout -outform PEM -out rsapss_2048_sha256_spki_public.pem openssl pkcs8 -nocrypt -in rsapss_2048_sha256_pkcs8_private.pem -topk8 -outform DER -out rsapss_2048_sha256_pkcs8_private.der ``` -------------------------------- ### Encrypt and Decrypt JWT with RSA-OAEP in Rust Source: https://context7.com/hidekatsu-izuno/josekit-rs/llms.txt Demonstrates asymmetric encryption for JWTs using the RSA-OAEP algorithm. The public key is used for encryption, while the corresponding private key is used for decryption. ```rust use josekit::{JoseError, jwe::{JweHeader, RSA_OAEP}, jwt::{self, JwtPayload}}; use std::fs; fn main() -> Result<(), JoseError> { let mut header = JweHeader::new(); header.set_token_type("JWT"); header.set_content_encryption("A256GCM"); let mut payload = JwtPayload::new(); payload.set_subject("secure-user"); let public_key = fs::read("rsa_public.pem").expect("Failed to read key"); let private_key = fs::read("rsa_private.pem").expect("Failed to read key"); // Encrypt with public key let encrypter = RSA_OAEP.encrypter_from_pem(&public_key)?; let jwt = jwt::encode_with_encrypter(&payload, &header, &encrypter)?; // Decrypt with private key let decrypter = RSA_OAEP.decrypter_from_pem(&private_key)?; let (payload, _) = jwt::decode_with_decrypter(&jwt, &decrypter)?; println!("Subject: {:?}", payload.subject()); Ok(()) } ``` -------------------------------- ### Encrypt JWT using Direct Method (Rust) Source: https://github.com/hidekatsu-izuno/josekit-rs/blob/master/README.md Encrypts and decrypts a JWT using the 'dir' (Direct) encryption method. This method uses a Content Encryption Key (CEK) directly, requiring the key length to match the CEK length. It's suitable when the CEK can be securely shared out-of-band. ```rust use josekit::{JoseError, jwe::{JweHeader, Dir}, jwt::{self, JwtPayload}}; fn main() -> Result<(), JoseError> { let mut header = JweHeader::new(); header.set_token_type("JWT"); header.set_content_encryption("A128CBC-HS256"); let mut payload = JwtPayload::new(); payload.set_subject("subject"); let key = b"0123456789ABCDEF0123456789ABCDEF"; // Encrypting JWT let encrypter = Dir.encrypter_from_bytes(key)?; let jwt = jwt::encode_with_encrypter(&payload, &header, &encrypter)?; // Decrypting JWT let decrypter = Dir.decrypter_from_bytes(key)?; let (payload, header) = jwt::decode_with_decrypter(&jwt, &decrypter)?; Ok(()) } ``` -------------------------------- ### Encrypt JWT using AESKW Method (Rust) Source: https://github.com/hidekatsu-izuno/josekit-rs/blob/master/README.md Encrypts and decrypts a JWT using an AES Key Wrap (AESKW) algorithm. This method encrypts the message with a CEK and then wraps the CEK using a common secret key. The key length must match the AES key size (e.g., 16 bytes for A128KW). ```rust use josekit::{JoseError, jwe::{JweHeader, A128KW}, jwt::{self, JwtPayload}}; fn main() -> Result<(), JoseError> { let mut header = JweHeader::new(); header.set_token_type("JWT"); header.set_content_encryption("A128CBC-HS256"); let mut payload = JwtPayload::new(); payload.set_subject("subject"); let key = b"0123456789ABCDEF"; // Encrypting JWT let encrypter = A128KW.encrypter_from_bytes(key)?; let jwt = jwt::encode_with_encrypter(&payload, &header, &encrypter)?; // Decrypting JWT let decrypter = A128KW.decrypter_from_bytes(key)?; let (payload, header) = jwt::decode_with_decrypter(&jwt, &decrypter)?; Ok(()) } ``` -------------------------------- ### Generate Private Key for ECDSA using OpenSSL Source: https://github.com/hidekatsu-izuno/josekit-rs/blob/master/README.md These OpenSSL commands generate private keys for different ECDSA algorithms (ES256, ES384, ES512, ES256K). Each command specifies the elliptic curve to be used for key generation. ```shell # for ES256 openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out private.pem # for ES384 openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-384 -out private.pem # for ES512 openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-521 -out private.pem # for ES256K openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:secp256k1 -out private.pem ``` -------------------------------- ### Encrypt and Decrypt JWT with Direct Symmetric Encryption in Rust Source: https://context7.com/hidekatsu-izuno/josekit-rs/llms.txt Shows how to perform direct encryption (dir) on a JWT using a shared symmetric key. The key size must be compatible with the chosen content encryption algorithm, such as A128CBC-HS256. ```rust use josekit::{JoseError, jwe::{JweHeader, Dir}, jwt::{self, JwtPayload}}; fn main() -> Result<(), JoseError> { let mut header = JweHeader::new(); header.set_token_type("JWT"); header.set_content_encryption("A128CBC-HS256"); // Requires 32-byte key let mut payload = JwtPayload::new(); payload.set_subject("sensitive-data"); payload.set_claim("secret", Some(serde_json::json!("classified")))?; let key = b"0123456789ABCDEF0123456789ABCDEF"; // Encrypt JWT let encrypter = Dir.encrypter_from_bytes(key)?; let jwt = jwt::encode_with_encrypter(&payload, &header, &encrypter)?; println!("Encrypted JWT: {}", jwt); // Decrypt JWT let decrypter = Dir.decrypter_from_bytes(key)?; let (payload, header) = jwt::decode_with_decrypter(&jwt, &decrypter)?; println!("Algorithm: {:?}", header.algorithm()); println!("Content Encryption: {:?}", header.content_encryption()); println!("Secret: {:?}", payload.claim("secret")); Ok(()) } ``` -------------------------------- ### Manage ECDSA Keypairs with OpenSSL Source: https://github.com/hidekatsu-izuno/josekit-rs/blob/master/data/memo.md Commands for generating ECDSA keys using various curves (P-256, P-384, P-521, secp256k1) and performing format conversions. ```bash openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -outform PEM -out ecdsa_p256_private.pem openssl pkey -in ecdsa_p256_private.pem -pubout -outform PEM -out ecdsa_p256_public.pem openssl pkcs8 -nocrypt -in ecdsa_p256_private.pem -topk8 -outform DER -out ecdsa_p256_private.der openssl pkey -in ecdsa_p256_private.pem -pubout -outform DER -out ecdsa_p256_public.der openssl pkey -inform DER -in ecdsa_p256_private.der -out ecdsa_p256_private.pem openssl pkcs8 -nocrypt -in ecdsa_p256_private.pem -traditional -out ecdsa_p256_pk1_private.pem openssl pkey -in ecdsa_p256_private.pem -outform DER -out ecdsa_p256_pk1_private.der openssl pkcs8 -nocrypt -in ecdsa_p256_pk1_private.pem -topk8 -out ecdsa_p256_private.pem ``` -------------------------------- ### Sign and Verify JWT with HMAC-SHA256 in Rust Source: https://context7.com/hidekatsu-izuno/josekit-rs/llms.txt Demonstrates signing and verifying a JWT using the HS256 HMAC algorithm in Rust. This method requires a shared secret key of at least 32 bytes. The code includes setting standard JWT claims like issuer, subject, audience, and expiration time. ```rust use josekit::{JoseError, jws::{JwsHeader, HS256}, jwt::{self, JwtPayload}}; use std::time::{Duration, SystemTime}; fn main() -> Result<(), JoseError> { // Create JWT header let mut header = JwsHeader::new(); header.set_token_type("JWT"); // Create JWT payload with standard claims let mut payload = JwtPayload::new(); payload.set_issuer("https://example.com"); payload.set_subject("user123"); payload.set_audience(vec!["https://api.example.com"]); payload.set_expires_at(&(SystemTime::now() + Duration::from_secs(3600))); payload.set_issued_at(&SystemTime::now()); payload.set_jwt_id("unique-token-id"); // Secret key (must be at least 32 bytes for HS256) let key = b"0123456789ABCDEF0123456789ABCDEF"; // Sign JWT let signer = HS256.signer_from_bytes(key)?; let jwt = jwt::encode_with_signer(&payload, &header, &signer)?; println!("Signed JWT: {}", jwt); // Verify JWT let verifier = HS256.verifier_from_bytes(key)?; let (verified_payload, verified_header) = jwt::decode_with_verifier(&jwt, &verifier)?; println!("Issuer: {:?}", verified_payload.issuer()); println!("Subject: {:?}", verified_payload.subject()); Ok(()) } ``` -------------------------------- ### JWS JSON Serialization with Multiple Signatures in Rust Source: https://context7.com/hidekatsu-izuno/josekit-rs/llms.txt Illustrates JWS JSON serialization in Rust, enabling multiple signatures and separate protected/unprotected headers for complex scenarios. This requires multiple private keys for signing and corresponding public keys for verification. ```rust use josekit::{JoseError, jws::{self, JwsHeaderSet, RS256, ES256}}; use std::fs; fn main() -> Result<(), JoseError> { let payload = b"Message with multiple signatures"; // First signer (RSA) let rsa_private = fs::read("rsa_private.pem").expect("Failed to read key"); let mut header1 = JwsHeaderSet::new(); header1.set_key_id("rsa-key", true); // true = protected header header1.set_token_type("JWT", false); // false = unprotected header let signer1 = RS256.signer_from_pem(&rsa_private)?; // Second signer (ECDSA) let ec_private = fs::read("ec_private.pem").expect("Failed to read key"); let mut header2 = JwsHeaderSet::new(); header2.set_key_id("ec-key", true); let signer2 = ES256.signer_from_pem(&ec_private)?; // Create JWS with multiple signatures let jws_json = jws::serialize_general_json( payload, &vec![(&header1, &*signer1), (&header2, &*signer2)], )?; println!("JWS JSON: {}", jws_json); // Verify with one of the keys let ec_public = fs::read("ec_public.pem").expect("Failed to read key"); let verifier = ES256.verifier_from_pem(&ec_public)?; let (decoded_payload, _) = jws::deserialize_json(&jws_json, &verifier)?; println!("Verified payload: {}", String::from_utf8_lossy(&decoded_payload)); Ok(()) } ``` -------------------------------- ### JWT Encryption with AES Key Wrap (A128KW, A192KW, A256KW) in Rust Source: https://context7.com/hidekatsu-izuno/josekit-rs/llms.txt Encrypts and decrypts JWTs using AES Key Wrap algorithms (A128KW, A192KW, A256KW). This method uses a symmetric key to wrap the Content Encryption Key (CEK), suitable for efficient key management in symmetric encryption scenarios. It requires the `josekit` crate and demonstrates the process of creating headers, payloads, encrypters, and decrypters. ```rust use josekit::{JoseError, jwe::{JweHeader, A256KW}, jwt::{self, JwtPayload}}; fn main() -> Result<(), JoseError> { let mut header = JweHeader::new(); header.set_token_type("JWT"); header.set_content_encryption("A128GCM"); let mut payload = JwtPayload::new(); payload.set_subject("wrapped-key-user"); // A128KW: 16 bytes, A192KW: 24 bytes, A256KW: 32 bytes let key = b"0123456789ABCDEF0123456789ABCDEF"; let encrypter = A256KW.encrypter_from_bytes(key)?; let jwt = jwt::encode_with_encrypter(&payload, &header, &encrypter)?; let decrypter = A256KW.decrypter_from_bytes(key)?; let (payload, _) = jwt::decode_with_decrypter(&jwt, &decrypter)?; println!("Subject: {:?}", payload.subject()); Ok(()) } ``` -------------------------------- ### Convert EC private keys using OpenSSL Source: https://github.com/hidekatsu-izuno/josekit-rs/blob/master/data/memo.md Converts EC private keys from PKCS#8 PEM format to PKCS#8 Traditional PEM format. This is useful for compatibility with legacy systems that do not support the standard PKCS#8 structure. ```bash openssl pkcs8 -nocrypt -in X25519_pkcs8_private.pem -traditional -out X25519_pkcs8_private_traditional.pem openssl pkcs8 -nocrypt -in X448_pkcs8_private.pem -traditional -out X448_pkcs8_private_traditional.pem ``` -------------------------------- ### Generate Private Key for EdDSA using OpenSSL Source: https://github.com/hidekatsu-izuno/josekit-rs/blob/master/README.md These OpenSSL commands generate private keys for EdDSA algorithms, specifically Ed25519 and Ed448. The generated private key can then be used to derive the corresponding public key. ```shell # for Ed25519 openssl genpkey -algorithm ED25519 -out private.pem # for Ed448 openssl genpkey -algorithm ED448 -out private.pem ``` -------------------------------- ### Parse JWT header without verification in Rust Source: https://context7.com/hidekatsu-izuno/josekit-rs/llms.txt Shows how to extract metadata from a JWT header before performing full signature verification. Useful for determining the required algorithm or key ID. ```rust use josekit::{JoseError, jwt, jws::JwsHeader, JoseHeader}; fn main() -> Result<(), JoseError> { let jwt_string = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6Im15LWtleS1pZCJ9.eyJzdWIiOiJ1c2VyMTIzIn0.signature"; // Decode header without verification let header = jwt::decode_header(&jwt_string)?; println!("Algorithm: {:?}", header.claim("alg")); println!("Token Type: {:?}", header.claim("typ")); println!("Key ID: {:?}", header.claim("kid")); // Downcast to JwsHeader for type-safe access if let Some(jws_header) = header.as_any().downcast_ref::() { println!("JWS Algorithm: {:?}", jws_header.algorithm()); println!("JWS Key ID: {:?}", jws_header.key_id()); } Ok(()) } ```