## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(comment = "")

## -----------------------------------------------------------------------------
library(openssl)
library(jose)

# Recipient generates a keypair
key <- ec_keygen()
pubkey <- as.list(key)$pubkey

# Encrypt a message for the recipient
(jwe <- jwe_encrypt("This is a secret message", pubkey))

# The recipient decrypts it with the private key
rawToChar(jwe_decrypt(jwe, key))

## ----error=TRUE---------------------------------------------------------------
try({
wrong_key <- ec_keygen()
jwe_decrypt(jwe, wrong_key)
})

## -----------------------------------------------------------------------------
claim <- jwt_claim(user = "jeroen", session_key = 123456)

# Encrypt for the recipient
(jwt <- jwt_encrypt(claim, pubkey))

# Decrypt and get the claim
jwt_decrypt(jwt, key)

## -----------------------------------------------------------------------------
secret <- rand_bytes(32)
jwe <- jwe_encrypt("This is a secret message", secret)
rawToChar(jwe_decrypt(jwe, secret))

## -----------------------------------------------------------------------------
rsa_key <- rsa_keygen()
jwe <- jwe_encrypt("Hello", as.list(rsa_key)$pubkey, alg = "RSA-OAEP", enc = "A128CBC-HS256")
rawToChar(jwe_decrypt(jwe, rsa_key))

## -----------------------------------------------------------------------------
strings <- strsplit(jwe, ".", fixed = TRUE)[[1]]
cat(rawToChar(base64url_decode(strings[1])))

## -----------------------------------------------------------------------------
# Sender signs with own key, then encrypts for the recipient
sender_key <- ec_keygen()
signed <- jwt_encode_sig(claim, key = sender_key)
jwe <- jwe_encrypt(signed, pubkey, header = list(cty = "JWT"))

# Recipient decrypts, then verifies the signature of the sender
signed <- rawToChar(jwe_decrypt(jwe, key))
jwt_decode_sig(signed, pubkey = as.list(sender_key)$pubkey)

