Sample code for 30+ languages & platforms
Xbase++

Find a JWE Recipient by Header Value

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.FindRecipient, which searches the per-recipient unprotected headers for a member with a given name and string value, and returns the matching recipient index.

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. This locates the recipient that a particular key belongs to (for example by kid) before decrypting. The method returns -1 when no match is found.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oJwe
LOCAL oSbJwe
LOCAL nBLoaded
LOCAL nBCaseSensitive
LOCAL nIndex

nSuccess := 0

oJwe := CreateObject("Chilkat.Jwe")

//  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 a multi-recipient JWE (JSON serialization) from a file.
oSbJwe := CreateObject("Chilkat.StringBuilder")
nBLoaded := oSbJwe:LoadFile("qa_data/message.jwe", "utf-8")
IF (nBLoaded != 1)
    ? "Failed to load the JWE file."
    oJwe:destroy()
    oSbJwe:destroy()
    RETURN
ENDIF

nSuccess := oJwe:LoadJweSb(oSbJwe)
IF (nSuccess == 0)
    ? oJwe:LastErrorText
    oJwe:destroy()
    oSbJwe:destroy()
    RETURN
ENDIF

//  Search the per-recipient unprotected headers for a member named "kid" whose value equals the
//  given string.  Returns the recipient index, or -1 if not found.
nBCaseSensitive := 1
nIndex := oJwe:FindRecipient("kid", "recipient-key-1", nBCaseSensitive)
IF (nIndex < 0)
    ? "Recipient not found."
    oJwe:destroy()
    oSbJwe:destroy()
    RETURN
ENDIF

? "Found recipient at index " + Str(nIndex)

oJwe:destroy()
oSbJwe:destroy()