Sample code for 30+ languages & platforms
PureBasic

Load and Validate a JWS from a StringBuilder

See more JSON Web Signatures (JWS) Examples

Demonstrates Jws.LoadJwsSb, which loads a JWS from a StringBuilder (here read from a file). The example then supplies the MAC key and validates the signature.

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. Validate returns 1 when the signature or MAC is cryptographically valid, 0 when it is not, or a negative value on error.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkJws.pb"
IncludeFile "CkStringBuilder.pb"

Procedure ChilkatExample()

    success.i = 0

    jws.i = CkJws::ckCreate()
    If jws.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 the JWS text from a file into a StringBuilder.
    sbJws.i = CkStringBuilder::ckCreate()
    If sbJws.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    bLoaded.i = CkStringBuilder::ckLoadFile(sbJws,"qa_data/message.jws","utf-8")
    If bLoaded <> 1
        Debug "Failed to load the JWS file."
        CkJws::ckDispose(jws)
        CkStringBuilder::ckDispose(sbJws)
        ProcedureReturn
    EndIf

    ;  Load the JWS from the StringBuilder.
    success = CkJws::ckLoadJwsSb(jws,sbJws)
    If success = 0
        Debug CkJws::ckLastErrorText(jws)
        CkJws::ckDispose(jws)
        CkStringBuilder::ckDispose(sbJws)
        ProcedureReturn
    EndIf

    base64Key.s = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU="
    success = CkJws::ckSetMacKey(jws,0,base64Key,"base64")
    If success = 0
        Debug CkJws::ckLastErrorText(jws)
        CkJws::ckDispose(jws)
        CkStringBuilder::ckDispose(sbJws)
        ProcedureReturn
    EndIf

    v.i = CkJws::ckValidate(jws,0)
    If v < 0
        Debug CkJws::ckLastErrorText(jws)
        CkJws::ckDispose(jws)
        CkStringBuilder::ckDispose(sbJws)
        ProcedureReturn
    EndIf

    If v <> 1
        Debug "The signature is not valid."
        CkJws::ckDispose(jws)
        CkStringBuilder::ckDispose(sbJws)
        ProcedureReturn
    EndIf

    Debug "The signature is valid."


    CkJws::ckDispose(jws)
    CkStringBuilder::ckDispose(sbJws)


    ProcedureReturn
EndProcedure