Zig
Zig
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 Zig Downloads
const std = @import("std");
const chilkat = @import("chilkat");
pub fn main(init: std.process.Init) !void {
const alloc = init.arena.allocator();
// 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.
const priv_key = try chilkat.PrivateKey.init();
defer priv_key.deinit();
// Load a brainpool EC key.
priv_key.loadPemFile("c:/qa_data/pem/ec_brainpool_privKey.pem") catch {
std.debug.print("{s}\n", .{try priv_key.getLastErrorText(alloc)});
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>
std.debug.print("{s}\n", .{try priv_key.getXml(alloc)});
const jwt = try chilkat.Jwt.init();
defer jwt.deinit();
// Build the JOSE header
const jose = try chilkat.JsonObject.init();
defer jose.deinit();
// Use the brainpool curve name matching the private key you just loaded.
// Use "BP256R1", or "BP384R1", etc.
try jose.appendString("alg", "BP256R1");
try jose.appendString("typ", "JWT");
// Now build the JWT claims (also known as the payload)
const claims = try chilkat.JsonObject.init();
defer claims.deinit();
try claims.appendString("iss", "http://example.org");
try claims.appendString("sub", "John");
try claims.appendString("aud", "http://example.com");
// Set the timestamp of when the JWT was created to now.
const cur_date_time = jwt.genNumericDate(0);
try claims.addIntAt(-1, "iat", cur_date_time);
// Set the "not process before" timestamp to now.
try claims.addIntAt(-1, "nbf", cur_date_time);
// Set the timestamp defining an expiration time (end time) for the token
// to be now + 1 hour (3600 seconds)
try claims.addIntAt(-1, "exp", cur_date_time + 3600);
// Produce the smallest possible JWT:
jwt.setAutoCompact(true);
// Create the JWT token. This is where the ECC signature is created.
const token = try jwt.createJwtPk(alloc, try jose.emit(alloc), try claims.emit(alloc), priv_key);
std.debug.print("{s}\n", .{token});
}