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

JWE using "dir" Direct use of Shared Symmetric Key

See more JSON Web Encryption (JWE) Examples

Demonstrates how to create a JWE using the "dir" alg -- which is to directly use a shared symmetric key.

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.

local plaintext = "Live long and prosper."

local jwe = chilkat.Jwe.new()

-- First build the JWE Protected Header..
local jweProtHdr = chilkat.JsonObject.new()
jweProtHdr:append_string("alg", "dir")
jweProtHdr:append_string("enc", "A128GCM")

-- Don't forget to actually provide the protected header to the JWE object:
jwe:set_protected_header(jweProtHdr)

-- The JWE is to use 128-bit AES GCM encryption as specified by the "enc" parameter.
-- Given that the "alg" = "dir", we are to directly specify the AES GCM key.
-- (It is assumed that the decrypting side also has knowledge of the direct key to be used..)

-- Our key will be these 16 hex bytes: 000102030405060708090A0B0C0D0E0F

-- The SetWrappingKey method is also used for "dir" direct keys.
-- However, if there are multiple recipients, they must all share the same CEK (Content Encryption Key),
-- which is specified by calling SetWrappingKey with an index of 0.

local recipientIndex = 0
jwe:set_wrapping_key(recipientIndex, "000102030405060708090A0B0C0D0E0F", "hex")

-- Encrypt and return the JWE:
local strJwe = jwe:encrypt(plaintext, "utf-8")
if not jwe.last_method_success then
    print(jwe.last_error_text)
    return
end

-- Show the JWE we just created:
print(strJwe)

-- Decrypt the JWE.
local jwe2 = chilkat.Jwe.new()
local success = jwe2:load_jwe(strJwe)
if not success then
    print(jwe2.last_error_text)
    return
end

jwe2:set_wrapping_key(0, "000102030405060708090A0B0C0D0E0F", "hex")

-- Decrypt.
local originalPlaintext = jwe2:decrypt(0, "utf-8")
if not jwe2.last_method_success then
    print(jwe2.last_error_text)
    return
end

print("original text: ")
print(originalPlaintext)

-- Sample output:
-- eyJhbGciOiJkaXIiLCJlbmMiOiJBMTI4R0NNIn0..20HX5Huc7f1nQC4pBUtiCQ.axFZIxtZy5j0ifJQUzGXLKIpsBuxJA.eBrOC-NrsreN6JeGuOPk1g
-- original text:
-- Live long and prosper.