Sample code for 30+ languages & platforms
Rust

Create JWT Using Ed25519 Private Key (EdDSA)

See more JSON Web Token (JWT) Examples

Demonstrates how to create a JWT using an Ed25519 private key. If the private key is Ed25519, which is an EdDSA algorithm, the JOSE header's "alg" member should be set to "EdDSA".

Note: This example requires Chilkat v9.5.0.95 or greater.

Chilkat Rust Downloads

Rust

// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

// Demonstrates how to create a JWT using an Ed25519 private key.

let priv_key = chilkat::PrivateKey::new();

// Load an Ed25519 (EdDSA) private key from a PEM file.
if priv_key.load_pem_file("qa_data/eddsa/ed25519.pem").is_err() {
    println!("{}", priv_key.last_error_text());
    return;
}

let jwt = chilkat::Jwt::new();

// Build the JOSE header
let jose = chilkat::JsonObject::new();

// -----------------------------------------------------------------
// Note: This example requires Chilkat v9.5.0.95 or greater.
// -----------------------------------------------------------------
let _ = jose.append_string("alg", "EdDSA").is_ok();
let _ = jose.append_string("typ", "JWT").is_ok();

// Now build the JWT claims (also known as the payload)
let claims = chilkat::JsonObject::new();
let _ = claims.append_string("iss", "http://example.org").is_ok();
let _ = claims.append_string("sub", "John").is_ok();
let _ = claims.append_string("aud", "http://example.com").is_ok();

// (optional) Set the timestamp of when the JWT was created to now.
let cur_date_time = jwt.gen_numeric_date(0);
let _ = claims.add_int_at(-1, "iat", cur_date_time).is_ok();

// (optional)  Set the "not process before" timestamp to now.
let _ = claims.add_int_at(-1, "nbf", cur_date_time).is_ok();

// (optional)  Set the timestamp defining an expiration time (end time) for the token
// to be now + 1 hour (3600 seconds)
let _ = claims.add_int_at(-1, "exp", cur_date_time + 3600).is_ok();

// Produce the smallest possible JWT:
jwt.set_auto_compact(true);

// Create the JWT token.
let token = jwt.create_jwt_pk(&jose.emit().unwrap_or_default(), &claims.emit().unwrap_or_default(), &priv_key).unwrap_or_default();

println!("{}", token);

// Example output:
// eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwOi8vZXhhbXBsZS5vcmciLCJzdWIiOiJKb2huIiwiYXVkIjoiaHR0cDovL2V4YW1wbGUuY29tIiwiaWF0IjoxNjg3OTcwNjgyLCJuYmYiOjE2ODc5NzA2ODIsImV4cCI6MTY4Nzk3NDI4Mn0.eyfrDJfuWJSJVJPfAUYb_p_c-LF_YULHGRaZx82MLLjMLCCFEEGckp8icuayf5bLW9ah20LzYYt0JgOBIB0RDg