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": "NXZGuL1wOvtflOLft16-qphINd8KjLMQm-yY3eFzLYs",
"y": "3B1vMkCcFtYHo9dwiOKtsCbHMlELyY4Pe7qI_XCezdQ",
"d": "6UrT9SC3YtNY-tI8EU1sj_zNO-vqwaEVUdRVklzu940"
}
# Use public key
pubkey <- as.list(key)$pubkey
json <- write_jwk(pubkey)
jsonlite::prettify(json)
{
"kty": "EC",
"crv": "P-256",
"x": "NXZGuL1wOvtflOLft16-qphINd8KjLMQm-yY3eFzLYs",
"y": "3B1vMkCcFtYHo9dwiOKtsCbHMlELyY4Pe7qI_XCezdQ"
}
# Read JWK key
(out <- read_jwk(json))
[256-bit ecdsa public key]
md5: 24fa905f7b589f852da4fd12c3c933f5
sha256: 5bb0a17ba47932505a658eabe02e5016402a693cc6b8e75f9b32346585094ea8
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] 8a 67 1a 2a 2e dd f2 07 44 b7 61 93 22 dc ce b5
(jwk <- write_jwk(key))
{"kty":"oct","k":"imcaKi7d8gdEt2GTItzOtQ"}
read_jwk(jwk)
[1] 8a 67 1a 2a 2e dd f2 07 44 b7 61 93 22 dc ce b5