Sample code for 30+ languages & platforms
DataFlex

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

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoJws
    String sJwsCompact
    Variant vPubKey
    Handle hoPubKey
    Integer v
    String sTemp1

    Move False To iSuccess

    Get Create (RefClass(cComChilkatJws)) To hoJws
    If (Not(IsComObjectCreated(hoJws))) Begin
        Send CreateComObject of hoJws
    End

    //  Load the JWS compact serialization.
    Move "eyJhbGciOiJIUzI1NiJ9.VGhpcyBpcyB0aGUgY29udGVudCB0byBzaWduLg.<signature>" To sJwsCompact
    Get ComLoadJws Of hoJws sJwsCompact To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoJws To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  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.
    Get Create (RefClass(cComChilkatPublicKey)) To hoPubKey
    If (Not(IsComObjectCreated(hoPubKey))) Begin
        Send CreateComObject of hoPubKey
    End
    Get ComLoadFromFile Of hoPubKey "qa_data/signer_pubkey.pem" To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoPubKey To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get pvComObject of hoPubKey to vPubKey
    Get ComSetPublicKey Of hoJws 0 vPubKey To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoJws To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  Validate the signature.  Validate returns 1 when valid, 0 when not, or a negative value on error.
    Get ComValidate Of hoJws 0 To v
    If (v < 0) Begin
        Get ComLastErrorText Of hoJws To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    If (v <> 1) Begin
        Showln "The signature is not valid."
        Procedure_Return
    End

    Showln "The signature is valid."


End_Procedure