Sample code for 30+ languages & platforms
PureBasic

Validate a JWS with a Public Key

See more JSON Web Signatures (JWS) Examples

Demonstrates Jws.SetPublicKey, which sets the public key used to validate a signature of a loaded JWS.

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. The public key verifies a signature created with the corresponding private key. Validate returns 1 when valid, 0 when not, or a negative value on error.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkJws.pb"
IncludeFile "CkPublicKey.pb"

Procedure ChilkatExample()

    success.i = 0

    jws.i = CkJws::ckCreate()
    If jws.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    ;  Load the JWS compact serialization.
    jwsCompact.s = "eyJhbGciOiJIUzI1NiJ9.VGhpcyBpcyB0aGUgY29udGVudCB0byBzaWduLg.<signature>"
    success = CkJws::ckLoadJws(jws,jwsCompact)
    If success = 0
        Debug CkJws::ckLastErrorText(jws)
        CkJws::ckDispose(jws)
        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 signer's public key and set it for validating signature 0.
    pubKey.i = CkPublicKey::ckCreate()
    If pubKey.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkPublicKey::ckLoadFromFile(pubKey,"qa_data/signer_pubkey.pem")
    If success = 0
        Debug CkPublicKey::ckLastErrorText(pubKey)
        CkJws::ckDispose(jws)
        CkPublicKey::ckDispose(pubKey)
        ProcedureReturn
    EndIf

    success = CkJws::ckSetPublicKey(jws,0,pubKey)
    If success = 0
        Debug CkJws::ckLastErrorText(jws)
        CkJws::ckDispose(jws)
        CkPublicKey::ckDispose(pubKey)
        ProcedureReturn
    EndIf

    ;  Validate the signature.  Validate returns 1 when valid, 0 when not, or a negative value on error.
    v.i = CkJws::ckValidate(jws,0)
    If v < 0
        Debug CkJws::ckLastErrorText(jws)
        CkJws::ckDispose(jws)
        CkPublicKey::ckDispose(pubKey)
        ProcedureReturn
    EndIf

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

    Debug "The signature is valid."


    CkJws::ckDispose(jws)
    CkPublicKey::ckDispose(pubKey)


    ProcedureReturn
EndProcedure