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)
Linking to: OpenSSL 3.2.2 4 Jun 2024
library(jose)

# Generate a ECDSA key
key <- openssl::ec_keygen()
jsonlite::prettify(write_jwk(key))
{
    "kty": "EC",
    "crv": "P-256",
    "x": "mB9ah0WWsUKwXhC4jkKvdVVFB2UdmcpwSFsLMkL7TAg",
    "y": "TpTBOPbO8NA_Mp50MWU_VU3NSvoibf1QoxFk45C15C8",
    "d": "RX1cejC9Xj75_8ZOQgzDD9WPbcw6w01nPDZLDo9SSxE"
}
 
# Use public key
pubkey <- as.list(key)$pubkey
json <- write_jwk(pubkey)
jsonlite::prettify(json)
{
    "kty": "EC",
    "crv": "P-256",
    "x": "mB9ah0WWsUKwXhC4jkKvdVVFB2UdmcpwSFsLMkL7TAg",
    "y": "TpTBOPbO8NA_Mp50MWU_VU3NSvoibf1QoxFk45C15C8"
}
 
# Read JWK key
(out <- read_jwk(json))
[256-bit ecdsa public key]
md5: 555bb282c3da12ae0c2136759e2113ed
sha256: 1e4ac62c80fca13d8123430556c5d1a846d46435c5696452006b7086385a45d8
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] 31 a7 0c fa 58 a0 c2 89 b4 8b 4f e0 9f ae 01 cf
(jwk <- write_jwk(key))
{"kty":"oct","k":"MacM-ligwom0i0_gn64Bzw"} 
read_jwk(jwk)
 [1] 31 a7 0c fa 58 a0 c2 89 b4 8b 4f e0 9f ae 01 cf