Skip to content

Generate JWK

The jwk.Key type

Key managers are built around the jwk.Key format. This is a special struct that can hold both JSON and concrete key data.

To use the key encoded in a given jwk.Key object, just call its Key() method. The object can also be directly marshalled into valid JSON, using the standard encoding/json package - or any compatible package.

go
var jsonKey jwk.Key[T]

// The concrete key, that can be directly used for cryptographic operations.
key := jsonKey.Key()

// Produces a valid JSON out-of-the-box, given it was generated by
// the library.
serialized, _ := json.Marshal(jsonKey)

Each JSON Web Algorithm has requirements regarding the key used. Some are strict, and some other more loose. Nonetheless, each has optimal parameters that are baked into the library, so you almost don't need to think about it.

Symmetric keys

go
package main

import (
	"github.com/a-novel-kit/jwt/jwk"
)

func main() {
	// Uses the Key format described above.
	key, _ := jwk.GenerateAES(jwk.A128CBC)
}

Available presets for use as Content-Encryption Keys (CEK) are:

PresetTarget "enc"
jwk.A128CBCA128CBC-HS256
jwk.A192CBCA192CBC-HS384
jwk.A256CBCA256CBC-HS512
jwk.A128GCMA128GCM
jwk.A192GCMA192GCM
jwk.A256GCMA256GCM

Asymmetric keys

go
package main

import (
	"github.com/a-novel-kit/jwt/jwk"
)

func main() {
	// Uses the Key format described above.
	privateKey, publicKey, _ := jwk.GenerateECDH()
}