Reading/Writing JSON Web Keys (JWK) in R

RSA / ECDSA keys

JSON Web Keys (JWK) is a format specified in RFC7517 for storing RSA/EC/AES keys in a JSON based format. It can be used to import/export such keys in the browser using the new W3C WebCryptoAPI.

The jose package makes it easy to read/write such keys in R for use with JWT or any other functionality from the openssl package.

library(openssl)
Linking to: OpenSSL 3.5.5 27 Jan 2026
library(jose)

# Generate a ECDSA key
key <- openssl::ec_keygen()
jsonlite::prettify(write_jwk(key))
{
    "kty": "EC",
    "crv": "P-256",
    "x": "oFuozjNvwl32dxYFc8UBUu3s4J1AnorUs8vxHSQg0gQ",
    "y": "Hrk5RxYw1DLTnkCKErCnnkzwKej2FoxKexjvW8qWCfQ",
    "d": "yobiTfzzSzAnoYnO4QoA4LfqxJiIjO_LdT5mayE79vE"
}
 
# Use public key
pubkey <- as.list(key)$pubkey
json <- write_jwk(pubkey)
jsonlite::prettify(json)
{
    "kty": "EC",
    "crv": "P-256",
    "x": "oFuozjNvwl32dxYFc8UBUu3s4J1AnorUs8vxHSQg0gQ",
    "y": "Hrk5RxYw1DLTnkCKErCnnkzwKej2FoxKexjvW8qWCfQ"
}
 
# Read JWK key
(out <- read_jwk(json))
[256-bit ecdsa public key]
md5: b3be071977f5846288c76851176cf736
sha256: dd96558c64cda7dfd0e680fbf4f60d68ecf61bbe383133f8a81f0634730a0d85
identical(pubkey, out)
[1] TRUE

AES/HMAC keys

JWT also specifies a format for encoding AES/HMAC secrets. Such secret keys are simply raw bytes.

# Random secret
(key <- rand_bytes(16))
 [1] 13 4a 71 67 73 bf 3c 76 00 47 ff 74 54 27 f9 6f
(jwk <- write_jwk(key))
{"kty":"oct","k":"E0pxZ3O_PHYAR_90VCf5bw"} 
read_jwk(jwk)
 [1] 13 4a 71 67 73 bf 3c 76 00 47 ff 74 54 27 f9 6f