Xbase++
Xbase++
JWE using A256GCMKW
See more JSON Web Encryption (JWE) Examples
This example demonstrates creating a JCE with AES GCM key wrap.Chilkat Xbase++ Downloads
LOCAL nSuccess
LOCAL cPlaintext
LOCAL oJwe
LOCAL oJweProtHdr
LOCAL oPrng
LOCAL cAesWrappingKey
LOCAL cStrJwe
LOCAL oJwe2
LOCAL cOriginalPlaintext
nSuccess := 0
// This requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
cPlaintext := "My text to enrypt"
oJwe := CreateObject("Chilkat.Jwe")
// First build the JWE Protected Header:
// {
// "alg": "A256GCMKW",
// "kid": "18ec08e1-bfa9-4d95-b205-2b4dd1d4321d",
// "tag": "kfPduVQ3T3H6vnewt--ksw",
// "iv": "KkYT0GX_2jHlfqN_",
// "enc": "A128CBC-HS256"
// }
oJweProtHdr := CreateObject("Chilkat.JsonObject")
oJweProtHdr:AppendString("alg", "A256GCMKW")
// kid is optional
oJweProtHdr:AppendString("kid", "18ec08e1-bfa9-4d95-b205-2b4dd1d4321d")
// tag is optional
oJweProtHdr:AppendString("tag", "kfPduVQ3T3H6vnewt--ksw")
oJweProtHdr:AppendString("enc", "A256GCM")
// the iv should be 16 random chars.
oPrng := CreateObject("Chilkat.Prng")
oJweProtHdr:AppendString("iv", oPrng:RandomString(16, 1, 1, 1))
oJwe:SetProtectedHeader(oJweProtHdr)
? "JWE Protected Header: " + oJweProtHdr:Emit()
? "--"
// Given that we have 256-bit AES, our key should be 32 bytes.
// The ascii string here is 32 bytes, therefore the 2nd arg is "ascii" to use these
// ascii chars directly as the key.
cAesWrappingKey := "2baf4f730f5e4542b428593ef9cceb0e"
oJwe:SetWrappingKey(0, cAesWrappingKey, "ascii")
// Encrypt and return the JWE:
cStrJwe := oJwe:Encrypt(cPlaintext, "utf-8")
IF (oJwe:LastMethodSuccess != 1)
? oJwe:LastErrorText
oJwe:destroy()
oJweProtHdr:destroy()
oPrng:destroy()
RETURN
ENDIF
// Show the JWE we just created:
? cStrJwe
// Decrypt the JWE that was just produced.
// 1) Load the JWE.
// 2) Set the AES wrapping key.
// 3) Decrypt.
oJwe2 := CreateObject("Chilkat.Jwe")
nSuccess := oJwe2:LoadJwe(cStrJwe)
IF (nSuccess != 1)
? oJwe2:LastErrorText
oJwe:destroy()
oJweProtHdr:destroy()
oPrng:destroy()
oJwe2:destroy()
RETURN
ENDIF
// Set the AES wrap key. Important to use "ascii"
oJwe2:SetWrappingKey(0, cAesWrappingKey, "ascii")
// Decrypt.
cOriginalPlaintext := oJwe2:Decrypt(0, "utf-8")
IF (oJwe2:LastMethodSuccess != 1)
? oJwe2:LastErrorText
oJwe:destroy()
oJweProtHdr:destroy()
oPrng:destroy()
oJwe2:destroy()
RETURN
ENDIF
? "original text: "
? cOriginalPlaintext
oJwe:destroy()
oJweProtHdr:destroy()
oPrng:destroy()
oJwe2:destroy()