JWK Library

A JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that represents a cryptographic key pair or individual public/private keys. The exact structure of JWK-JSON-objects is specified in RFC-7517.

JWKs are heavily used in a lot of web-based protocols such as Automatic Certificate Management Environment (ACME) or JSON Web Tokens (JWT).

File information

Filecommon/ilib/jwk.h

Overview
Classes jwk
Defines JSON_ID_ROOT
JSON_ID_NONE

Examples Encoding
Decoding

Overview

The jwk class can be used for encoding and decoding public/private keys to/from JSON messages in JWK format. A JWK typically looks like this:

{
    "kty": "EC,"
    "crv": "P-256,"
    "x":   "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU,"
    "y":   "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0,"
    "d":   "jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI,"
    "alg": "ES256"
}
In this case the P256 elliptic curve is used and 'd' is the private key, 'x' and 'y' compose the public key. The 'alg' attribute specifies the used algorithm and is optional.

Decoding is usually done like that:

// JWK encoded in JSON string
char msg[1000] = "<Insert JSON object from above>";

// Decode JWK object from JSON string
jwk keys;
keys.decode(msg);

// No we can access the elements
auto kty = keys.kty;
auto crv = keys.crv;
auto d   = keys.params.p256.d;

There are different ways to encode public/private keys to JWK-JSON-objects.

// Encode JWK to string
keys.encode(msg);               // Encode public and private key
keys.encode_public_key(msg);    // Encode public key only
keys.encode_private_key(msg);   // Encode private key only

For better integration with innovaphone's json_io library, there are also additional overloads for the encode/decode methods. This way JWKs can not only be (de-)serialized from strings, but also from/to json_io objects.

// Append JWK to existing json structure
json_io json(msg);
word json_parent_elem = json.get_object();
keys.encode(&json, json_parent_elem, "jwk");
keys.encode_public_key(&json, json_parent_elem, "jwk-pub");
keys.encode_private_key(&json, json_parent_elem, "jwk-priv");
json.encode();

JWK objects can be used to sign/verify messages.

// Sign message
const char* msg2 = "Hello World";
char* signature = (char*)alloca(keys.getSignatureSize()));
keys.sign(signature, msg2, strlen(msg2));                   // Requires private key to be set

// Verify message
bool valid = keys.verify(signature, msg2, strlen(msg2));    // Requires public key to be set

Additionally we can generate "random" key pairs

keys.gen_es256_keys(); // Initializes JWK object 'keys' with a set of ES256 public/private keys.

Classes

Public functions

TODO

Data types

TODO