Sample code for 30+ languages & platforms
DataFlex

Sign a JWS with a Private Key

See more JSON Web Signatures (JWS) Examples

Demonstrates Jws.SetPrivateKey, which sets the private key used to create a signature. The example uses RS256 (RSASSA-PKCS1-v1_5 with SHA-256).

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. Public-key JWS signs with a private key so that anyone holding the corresponding public key can verify the signature.

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoJws
    Variant vHeader
    Handle hoHeader
    Boolean iBIncludeBom
    Variant vPrivKey
    Handle hoPrivKey
    String sJwsCompact
    String sTemp1
    Boolean bTemp1

    Move False To iSuccess

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

    //  Protected header specifying RSASSA-PKCS1-v1_5 with SHA-256 (RS256).
    Get Create (RefClass(cComChilkatJsonObject)) To hoHeader
    If (Not(IsComObjectCreated(hoHeader))) Begin
        Send CreateComObject of hoHeader
    End
    Get ComUpdateString Of hoHeader "alg" "RS256" To iSuccess
    Get pvComObject of hoHeader to vHeader
    Get ComSetProtectedHeader Of hoJws 0 vHeader To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoJws To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Move False To iBIncludeBom
    Get ComSetPayload Of hoJws "This is the content to sign." "utf-8" iBIncludeBom 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 private key and set it for signature 0.
    Get Create (RefClass(cComChilkatPrivateKey)) To hoPrivKey
    If (Not(IsComObjectCreated(hoPrivKey))) Begin
        Send CreateComObject of hoPrivKey
    End
    Get ComLoadPemFile Of hoPrivKey "qa_data/signer_privkey.pem" To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoPrivKey To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get pvComObject of hoPrivKey to vPrivKey
    Get ComSetPrivateKey Of hoJws 0 vPrivKey To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoJws To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get ComCreateJws Of hoJws To sJwsCompact
    Get ComLastMethodSuccess Of hoJws To bTemp1
    If (bTemp1 = False) Begin
        Get ComLastErrorText Of hoJws To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Showln sJwsCompact


End_Procedure