Encrypt or decrypt data or a JWT claim using JSON Web Encryption (JWE) in compact
serialization, see RFC7516.
The content is encrypted with a random content encryption key (CEK), which is in
turn encrypted for the recipient using the key management algorithm alg.
Usage
jwe_encrypt(payload, key, alg = NULL, enc = "A256GCM", header = NULL)
jwe_decrypt(jwe, key)
jwt_encrypt(
claim = jwt_claim(),
key,
alg = NULL,
enc = "A256GCM",
header = NULL
)
jwt_decrypt(jwt, key)Arguments
- payload
string or raw vector with the data to encrypt
- key
for encryption: path or object with the RSA or EC public key of the recipient, or a raw vector with a shared secret. For decryption: path or object with the RSA or EC private key, or a raw vector with the shared secret.
- alg
key management algorithm, see details.
- enc
content encryption algorithm, see details.
- header
named list with additional parameter fields to include in the protected header, for example
kid.- jwe
string containing the JWE in compact serialization
- claim
a named list with fields to include in the jwt payload, see jwt_claim
- jwt
string containing the encrypted JSON Web Token
Value
jwe_encrypt and jwt_encrypt return a string with the JWE.
jwe_decrypt returns a raw vector with the decrypted payload, and jwt_decrypt
returns the decrypted claim.
Details
Supported key management algorithms (alg) are:
RSA-OAEPandRSA-OAEP-256: for an RSA key.ECDH-ES,ECDH-ES+A128KW,ECDH-ES+A192KWandECDH-ES+A256KW: for an EC key (P-256, P-384, or P-521).A128KW,A192KWandA256KW: AES key wrap with a shared secret (raw vector) of 16, 24 or 32 bytes.dir: direct encryption with a shared secret (raw vector) that has the key size ofenc.
If alg is NULL, it defaults to RSA-OAEP-256 for RSA keys,
ECDH-ES for EC keys, and the AES key wrap of the matching size for raw keys.
Supported content encryption algorithms (enc) are A128GCM, A192GCM,
A256GCM, A128CBC-HS256, A192CBC-HS384 and A256CBC-HS512.
Examples
# Encrypt with RSA
key <- openssl::rsa_keygen()
pubkey <- as.list(key)$pubkey
token <- jwe_encrypt("Hello world", pubkey)
rawToChar(jwe_decrypt(token, key))
#> [1] "Hello world"
# Encrypt with EC
key <- openssl::ec_keygen()
pubkey <- as.list(key)$pubkey
token <- jwe_encrypt("Hello world", pubkey, enc = "A128CBC-HS256")
rawToChar(jwe_decrypt(token, key))
#> [1] "Hello world"
# Encrypt with a shared secret
secret <- openssl::rand_bytes(32)
token <- jwe_encrypt("Hello world", secret)
rawToChar(jwe_decrypt(token, secret))
#> [1] "Hello world"
# Encrypt a JWT
claim <- jwt_claim(name = "jeroen", session = 123456)
token <- jwt_encrypt(claim, pubkey)
jwt_decrypt(token, key)
#> $iat
#> [1] 1796090812
#>
#> $name
#> [1] "jeroen"
#>
#> $session
#> [1] 123456
#>