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)
library(jose)

# Generate a ECDSA key
key <- openssl::ec_keygen()
jsonlite::prettify(write_jwk(key))
{
    "kty": "EC",
    "crv": "P-256",
    "x": "dKifrxVszoY3TmTGPoWnYMByynwfYsW2dbYhTUXH3PI",
    "y": "Mq0RXo5BcKmre8_PFwdUQutIUbqGm6KfRc67vLOcde8",
    "d": "2j9ayuKFjfxGzuxSu7fdGxs1HzOfrLgEfkhbdO6KT48"
}
 
# Use public key
pubkey <- as.list(key)$pubkey
json <- write_jwk(pubkey)
jsonlite::prettify(json)
{
    "kty": "EC",
    "crv": "P-256",
    "x": "dKifrxVszoY3TmTGPoWnYMByynwfYsW2dbYhTUXH3PI",
    "y": "Mq0RXo5BcKmre8_PFwdUQutIUbqGm6KfRc67vLOcde8"
}
 
# Read JWK key
(out <- read_jwk(json))
[256-bit ecdsa public key]
md5: e04d2eee9a19f3b7d1a6654b590cb06b
sha256: f7f01d943d3dff88e91743e5d97e3d577e02e29c979d8243da6d9819bb1273ea
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] a8 6c 4a ae 45 aa 0e 50 37 f3 84 79 48 66 a4 d5
(jwk <- write_jwk(key))
{"kty":"oct","k":"qGxKrkWqDlA384R5SGak1Q"} 
read_jwk(jwk)
 [1] a8 6c 4a ae 45 aa 0e 50 37 f3 84 79 48 66 a4 d5