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 1.1.1h 22 Sep 2020
library(jose)
# Generate a ECDSA key
key <- openssl::ec_keygen()
jsonlite::prettify(write_jwk(key))
{
"kty": "EC",
"crv": "P-256",
"x": "4mRfH_XLZK3kDAgKcsUWrowDVwMbJu1cLe4Lp2qG4vk",
"y": "V8lFNwC6XPL9HWla-IT1Tea_dQKJXVsDYe0ezfv_RCI",
"d": "x9VXjILw4gNU9LID1pKNkvGXKq8tCS0m4asW5rbsCe0"
}
# Use public key
pubkey <- as.list(key)$pubkey
json <- write_jwk(pubkey)
jsonlite::prettify(json)
{
"kty": "EC",
"crv": "P-256",
"x": "4mRfH_XLZK3kDAgKcsUWrowDVwMbJu1cLe4Lp2qG4vk",
"y": "V8lFNwC6XPL9HWla-IT1Tea_dQKJXVsDYe0ezfv_RCI"
}
# Read JWK key
(out <- read_jwk(json))
[256-bit ecdsa public key]
md5: 01965264c60f4a699503498ab348735c
identical(pubkey, out)
[1] TRUE
JWT also specifies a format for encoding AES/HMAC secrets. Such secret keys are simply raw bytes.
# Random secret
(key <- rand_bytes(16))
[1] 1a a9 b7 c3 e1 f7 cc eb 60 1b f6 fe 4c f5 5d 91
(jwk <- write_jwk(key))
{"kty":"oct","k":"Gqm3w-H3zOtgG_b-TPVdkQ"}
read_jwk(jwk)
[1] 1a a9 b7 c3 e1 f7 cc eb 60 1b f6 fe 4c f5 5d 91