Skip to contents

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.

Linking to: OpenSSL 3.0.13 30 Jan 2024
library(jose)

# Generate a ECDSA key
key <- openssl::ec_keygen()
jsonlite::prettify(write_jwk(key))
{
    "kty": "EC",
    "crv": "P-256",
    "x": "iShdDlyD2aTyQCqd-LgFnozwbDnvlQ5vRRQVEdiWdy0",
    "y": "AbykS1h3XrvvEc756igyoP9KfkW6xIceNp4ZRcblgmA",
    "d": "Rbu2YWyR-EibAPAuvbmVjJ186ud16MdVVYbdkgnEr7A"
}
 
# Use public key
pubkey <- as.list(key)$pubkey
json <- write_jwk(pubkey)
jsonlite::prettify(json)
{
    "kty": "EC",
    "crv": "P-256",
    "x": "iShdDlyD2aTyQCqd-LgFnozwbDnvlQ5vRRQVEdiWdy0",
    "y": "AbykS1h3XrvvEc756igyoP9KfkW6xIceNp4ZRcblgmA"
}
 
# Read JWK key
(out <- read_jwk(json))
[256-bit ecdsa public key]
md5: f0b8e5af80b00e0b0160dad14f9c1c0d
sha256: eb35a28b63c75307161deee1c955eb62d072ed237d01398a6dcfabf3944a08c8
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] 7a 51 90 65 96 88 b6 b8 52 48 77 c8 51 cd f6 b8
(jwk <- write_jwk(key))
{"kty":"oct","k":"elGQZZaItrhSSHfIUc32uA"} 
 [1] 7a 51 90 65 96 88 b6 b8 52 48 77 c8 51 cd f6 b8