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": "rVhpeKLE3DNr_Z_OxyunraCoa2466BjE5LKLzn1AsMY",
    "y": "Jzzl0SvxJihJxA_jDxRXeNFHJkMXvoLTGX3hosmS_-c",
    "d": "jfNbam3-_CslkYd-X5HChCBFIJJ55MqpWNum30rGO4s"
}
 
# Use public key
pubkey <- as.list(key)$pubkey
json <- write_jwk(pubkey)
jsonlite::prettify(json)
{
    "kty": "EC",
    "crv": "P-256",
    "x": "rVhpeKLE3DNr_Z_OxyunraCoa2466BjE5LKLzn1AsMY",
    "y": "Jzzl0SvxJihJxA_jDxRXeNFHJkMXvoLTGX3hosmS_-c"
}
 
# Read JWK key
(out <- read_jwk(json))
[256-bit ecdsa public key]
md5: 7ec47b33b53602b2151aa57e33b930d1
sha256: 5fbb923ba3732885e0e23067f9a36d5a3fc271c8d250229e1544a4c4067aacb5
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] aa 09 ea 7e f2 09 91 68 15 9c bd 5a ab 15 84 95
(jwk <- write_jwk(key))
{"kty":"oct","k":"qgnqfvIJkWgVnL1aqxWElQ"} 
read_jwk(jwk)
 [1] aa 09 ea 7e f2 09 91 68 15 9c bd 5a ab 15 84 95