Sample code for 30+ languages & platforms
PureBasic

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 PureBasic Downloads

PureBasic
IncludeFile "CkStringBuilder.pb"
IncludeFile "CkJwe.pb"

Procedure ChilkatExample()

    success.i = 0

    jwe.i = CkJwe::ckCreate()
    If jwe.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    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 a multi-recipient JWE (JSON serialization) from a file.
    sbJwe.i = CkStringBuilder::ckCreate()
    If sbJwe.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    bLoaded.i = CkStringBuilder::ckLoadFile(sbJwe,"qa_data/message.jwe","utf-8")
    If bLoaded <> 1
        Debug "Failed to load the JWE file."
        CkJwe::ckDispose(jwe)
        CkStringBuilder::ckDispose(sbJwe)
        ProcedureReturn
    EndIf

    success = CkJwe::ckLoadJweSb(jwe,sbJwe)
    If success = 0
        Debug CkJwe::ckLastErrorText(jwe)
        CkJwe::ckDispose(jwe)
        CkStringBuilder::ckDispose(sbJwe)
        ProcedureReturn
    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.
    bCaseSensitive.i = 1
    index.i = CkJwe::ckFindRecipient(jwe,"kid","recipient-key-1",bCaseSensitive)
    If index < 0
        Debug "Recipient not found."
        CkJwe::ckDispose(jwe)
        CkStringBuilder::ckDispose(sbJwe)
        ProcedureReturn
    EndIf

    Debug "Found recipient at index " + Str(index)


    CkJwe::ckDispose(jwe)
    CkStringBuilder::ckDispose(sbJwe)


    ProcedureReturn
EndProcedure