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 brower 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": "sxfiyf9fOjWfNlFz4sQqsTJbn2kK0CWxfx7HXE81NzI",
    "y": "Z9o3GOEe49c-wMuYYG0X4c0sTBnHkAJFijWoucC5DU8",
    "d": "_cMhREM1XWWDQfFivAbegR_PrhbI45h-nYTKY9j-vig"
}
 
# Use public key
pubkey <- as.list(key)$pubkey
json <- write_jwk(pubkey)
jsonlite::prettify(json)
{
    "kty": "EC",
    "crv": "P-256",
    "x": "sxfiyf9fOjWfNlFz4sQqsTJbn2kK0CWxfx7HXE81NzI",
    "y": "Z9o3GOEe49c-wMuYYG0X4c0sTBnHkAJFijWoucC5DU8"
}
 
# Read JWK key
(key2 <- read_jwk(json))
[256-bit ecdsa public key]
md5: e0:e0:12:60:40:44:83:cd:69:9f:10:aa:ff:4f:2f:f2
identical(key, key2)
[1] FALSE

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] af 70 8a 1b 12 1c 91 d8 47 6e a3 c4 ca 33 9b e8
(jwk <- write_jwk(key))
{"kty":"oct","k":"r3CKGxIckdhHbqPEyjOb6A"} 
read_jwk(jwk)
 [1] af 70 8a 1b 12 1c 91 d8 47 6e a3 c4 ca 33 9b e8