Sample code for 30+ languages & platforms
Rust

Create JWT using a Brainpool EC Key

See more JSON Web Token (JWT) Examples

Demonstrates how to create a JWT using an EC private key. This is for JOSE headers having an "alg" member with any of the following values:
  • BP160R1
  • BP192R1
  • BP224R1
  • BP256R1
  • BP320R1
  • BP384R1
  • BP512R1

This example also demonstrates how to include time constraints:

  • nbf: Not Before Time
  • exp: Expiration Time
  • iat: Issue At Time

Chilkat Rust Downloads

Rust

// Demonstrates how to create a JWT using a brainpool EC private key.

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

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

// Load a brainpool EC key.
if priv_key.load_pem_file("c:/qa_data/pem/ec_brainpool_privKey.pem").is_err() {
    println!("{}", priv_key.last_error_text());
    return;
}

// You can examine the curve name of the key you just loaded by getting the private in XML format:
// <ECCKeyValue curve="CURVE_NAME">...</ECCKeyValue>
println!("{}", priv_key.get_xml().unwrap_or_default());

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

// Build the JOSE header
let jose = chilkat::JsonObject::new();
// Use the brainpool curve name matching the private key you just loaded.
// Use "BP256R1", or "BP384R1", etc.   
let _ = jose.append_string("alg", "BP256R1").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();

// 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();

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

// 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.  This is where the ECC signature is created.
let token = jwt.create_jwt_pk(&jose.emit().unwrap_or_default(), &claims.emit().unwrap_or_default(), &priv_key).unwrap_or_default();

println!("{}", token);