Sample code for 30+ languages & platforms
Lianja

Encrypt a JWE with a Recipient Public Key

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.SetPublicKey, which sets the public key used to encrypt for a recipient. The example uses RSA-OAEP-256 key management with AES-256-GCM content encryption.

The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.

Background. In public-key JWE, the content-encryption key is wrapped for the recipient using their public key, so only the holder of the matching private key can decrypt.

Chilkat Lianja Downloads

Lianja
llSuccess = .F.

loJwe = createobject("CkJwe")

//  Protected header: RSA-OAEP-256 key management with AES-256-GCM content encryption.
loHeader = createobject("CkJsonObject")
loHeader.UpdateString("alg","RSA-OAEP-256")
loHeader.UpdateString("enc","A256GCM")
llSuccess = loJwe.SetProtectedHeader(loHeader)
if (llSuccess = .F.) then
    ? loJwe.LastErrorText
    release loJwe
    release loHeader
    return
endif

//  The file path is relative to the application's current working directory.  An absolute path
//  may also be used.  Supply the path appropriate to your own environment.
//  Load the recipient's public key.
loPubKey = createobject("CkPublicKey")
llSuccess = loPubKey.LoadFromFile("qa_data/recipient_pubkey.pem")
if (llSuccess = .F.) then
    ? loPubKey.LastErrorText
    release loJwe
    release loHeader
    release loPubKey
    return
endif

//  Set the public key used to encrypt for recipient 0.
llSuccess = loJwe.SetPublicKey(0,loPubKey)
if (llSuccess = .F.) then
    ? loJwe.LastErrorText
    release loJwe
    release loHeader
    release loPubKey
    return
endif

lcJweCompact = loJwe.Encrypt("This is the secret content.","utf-8")
if (loJwe.LastMethodSuccess = .F.) then
    ? loJwe.LastErrorText
    release loJwe
    release loHeader
    release loPubKey
    return
endif

? lcJweCompact


release loJwe
release loHeader
release loPubKey