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": "6mMYB9-kH0vZhpG00_D2Zyc0C1viClLfJQwvf01PjcY",
    "y": "Rqe4ilfSkflJUP6cw1EYOTRSI6OrEggpd_1P72tchjc",
    "d": "NttlnK4puyUzPD-j7y6F23MbHMjZxk8JyQ4Nldba4A0"
}
 
# Use public key
pubkey <- as.list(key)$pubkey
json <- write_jwk(pubkey)
jsonlite::prettify(json)
{
    "kty": "EC",
    "crv": "P-256",
    "x": "6mMYB9-kH0vZhpG00_D2Zyc0C1viClLfJQwvf01PjcY",
    "y": "Rqe4ilfSkflJUP6cw1EYOTRSI6OrEggpd_1P72tchjc"
}
 
# Read JWK key
(out <- read_jwk(json))
[256-bit ecdsa public key]
md5: 18148ba83bfedbdc8c0da7e8f7c8f009
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] fa 9f 55 be 47 e9 78 82 68 0a 98 78 b5 1e 85 f7
(jwk <- write_jwk(key))
{"kty":"oct","k":"-p9VvkfpeIJoCph4tR6F9w"} 
read_jwk(jwk)
 [1] fa 9f 55 be 47 e9 78 82 68 0a 98 78 b5 1e 85 f7