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.0.13 30 Jan 2024
library(jose)

# Generate a ECDSA key
key <- openssl::ec_keygen()
jsonlite::prettify(write_jwk(key))
{
    "kty": "EC",
    "crv": "P-256",
    "x": "Qne5tNnj22-B4QILG3LD31ZpaGO2YW113tOgjAXZfis",
    "y": "Vybe2_vApL29QKECgPfUMRSG0yxy-qdItD6yExZHo2E",
    "d": "XKLctLms9jgbThIYwNluO1fdRKVE8C-PkaHzdBvvsXI"
}
 
# Use public key
pubkey <- as.list(key)$pubkey
json <- write_jwk(pubkey)
jsonlite::prettify(json)
{
    "kty": "EC",
    "crv": "P-256",
    "x": "Qne5tNnj22-B4QILG3LD31ZpaGO2YW113tOgjAXZfis",
    "y": "Vybe2_vApL29QKECgPfUMRSG0yxy-qdItD6yExZHo2E"
}
 
# Read JWK key
(out <- read_jwk(json))
[256-bit ecdsa public key]
md5: dc0f2d2de942a9228c17ed7ba389a7b7
sha256: 775d6f4a9cfa21000c8c8a165c59f421c69f0fcdbccc5d90c511f6074466926c
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] 92 3b 20 b5 7c 89 aa fa cd ae e1 95 f1 3e 53 ec
(jwk <- write_jwk(key))
{"kty":"oct","k":"kjsgtXyJqvrNruGV8T5T7A"} 
read_jwk(jwk)
 [1] 92 3b 20 b5 7c 89 aa fa cd ae e1 95 f1 3e 53 ec