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": "QC29aLrtYbeVaEFTzfAQpEFKSydC1dp5UUku8O1yQAo",
    "y": "_Y3_YYsmDJGGniHoAfek-7GGzrgoLBpjNIMyeDLxO7I",
    "d": "gKV9JOxtyuCK0eP9JcyhWF3xn1mJXEAOUtoKvj7ujLk"
}
 
# Use public key
pubkey <- as.list(key)$pubkey
json <- write_jwk(pubkey)
jsonlite::prettify(json)
{
    "kty": "EC",
    "crv": "P-256",
    "x": "QC29aLrtYbeVaEFTzfAQpEFKSydC1dp5UUku8O1yQAo",
    "y": "_Y3_YYsmDJGGniHoAfek-7GGzrgoLBpjNIMyeDLxO7I"
}
 
# Read JWK key
(out <- read_jwk(json))
[256-bit ecdsa public key]
md5: e63cd5bf06425d546cfd8ebb23517b59
sha256: c11f87dc1705c79db71e80a57fe21545c3498b8c19fc847e6d591575008c5808
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] 9f 06 0d fd 0a ef 8d f8 3b 3c 8d ee 8f 5f 99 d1
(jwk <- write_jwk(key))
{"kty":"oct","k":"nwYN_Qrvjfg7PI3uj1-Z0Q"} 
read_jwk(jwk)
 [1] 9f 06 0d fd 0a ef 8d f8 3b 3c 8d ee 8f 5f 99 d1