Sample code for 30+ languages & platforms
Lua Requires Chilkat v9.5.0.66+

JWE with Binary Data

See more JSON Web Encryption (JWE) Examples

Demonstrates how to create a JWE that contains a binary payload (such as a JPG image).

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- This requires the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.

-- Load a JPG file that will be the JWE payload.
local jpgBytes = chilkat.BinData.new()
local success = jpgBytes:load_file("qa_data/jpg/starfish.jpg")
-- Make sure your app checks the success/failure of the call to LoadFile..
print("Original JPG size = " .. jpgBytes.num_bytes)

local jwe = chilkat.Jwe.new()

local jweProtHdr = chilkat.JsonObject.new()
jweProtHdr:append_string("alg", "A128KW")
jweProtHdr:append_string("enc", "A128CBC-HS256")
jwe:set_protected_header(jweProtHdr)

local aesWrappingKey = "GawgguFyGrWKav7AX4VKUg"
jwe:set_wrapping_key(0, aesWrappingKey, "base64url")

-- Encrypt and return the JWE in sbJwe:
local sbJwe = chilkat.StringBuilder.new()
success = jwe:encrypt_bd(jpgBytes, sbJwe)
if not success then
    print(jwe.last_error_text)
    return
end

-- Show the JWE:
print(sbJwe:get_as_string())
print("size of JWE: " .. sbJwe.length)

-- ---------------------------------------------------------
-- Decrypt to get the original JPG file..

local jwe2 = chilkat.Jwe.new()
success = jwe2:load_jwe_sb(sbJwe)
if not success then
    print(jwe2.last_error_text)
    return
end

-- Set the AES wrap key.
jwe2:set_wrapping_key(0, aesWrappingKey, "base64url")

-- Decrypt.
local jpgOriginal = chilkat.BinData.new()
success = jwe2:decrypt_bd(0, jpgOriginal)
if not success then
    print(jwe2.last_error_text)
    return
end

print("Decrypted JPG size = " .. jpgOriginal.num_bytes)

-- Save the decrypted JPG to a file.
success = jpgOriginal:write_file("qa_output/jwe_decrypted_starfish.jpg")

print("success = " .. tostring(success))

-- The output of this program, when tested, was:
-- Original JPG size = 6229
-- eyJhbGciOiJBMTI4S1ciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.9YFz_wteV ... 7Et3hKhpxnKEXw
-- size of JWE: 8473
-- Decrypted JPG size = 6229
-- success = True