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": "dn5AXxAielCQbw9R9ISoadR1CHO9uolEna92_QdgHZw",
    "y": "2NWFH6fYB6oVUZoKl5e-sFN55tS5gbn5PKQ-7IVM-Eg",
    "d": "uh1uqdLLTi3qfciyF7OC-ERF-8Rx-5IEd1Jc1G0SYbA"
}

# Use public key
pubkey <- as.list(key)$pubkey
json <- write_jwk(pubkey)
jsonlite::prettify(json)
{
    "kty": "EC",
    "crv": "P-256",
    "x": "dn5AXxAielCQbw9R9ISoadR1CHO9uolEna92_QdgHZw",
    "y": "2NWFH6fYB6oVUZoKl5e-sFN55tS5gbn5PKQ-7IVM-Eg"
}

# Read JWK key
(out <- read_jwk(json))
[256-bit ecdsa public key]
md5: fa5030b109ef81161d30dff7ccf62cd9
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] 54 37 c2 33 d0 6a e4 e9 f5 f4 80 32 f5 09 e0 f0
(jwk <- write_jwk(key))
{"kty":"oct","k":"VDfCM9Bq5On19IAy9Qng8A"} 
read_jwk(jwk)
 [1] 54 37 c2 33 d0 6a e4 e9 f5 f4 80 32 f5 09 e0 f0