Sample code for 30+ languages & platforms
DataFlex

Create a JWS into a StringBuilder

See more JSON Web Signatures (JWS) Examples

Demonstrates Jws.CreateJwsSb, which creates a JWS and writes it into a StringBuilder.

Background. JWS (JSON Web Signature) integrity-protects a payload with a signature or MAC. The header alg names the algorithm; this example uses HMAC-SHA256 (HS256) with a symmetric MAC key.

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoJws
    Variant vHeader
    Handle hoHeader
    Boolean iBIncludeBom
    String sBase64Key
    Variant vSbJws
    Handle hoSbJws
    String sTemp1

    Move False To iSuccess

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

    //  Set the protected header for signer 0, specifying the signature algorithm (alg).
    Get Create (RefClass(cComChilkatJsonObject)) To hoHeader
    If (Not(IsComObjectCreated(hoHeader))) Begin
        Send CreateComObject of hoHeader
    End
    Get ComUpdateString Of hoHeader "alg" "HS256" 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

    //  Set the payload to be signed.
    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

    //  Provide the HMAC key (base64) for signer 0.  In production, obtain the key from a secure source
    //  rather than hard-coding it.
    Move "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU=" To sBase64Key
    Get ComSetMacKey Of hoJws 0 sBase64Key "base64" To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoJws To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  Create the JWS and write it into a StringBuilder.
    Get Create (RefClass(cComChilkatStringBuilder)) To hoSbJws
    If (Not(IsComObjectCreated(hoSbJws))) Begin
        Send CreateComObject of hoSbJws
    End
    Get pvComObject of hoSbJws to vSbJws
    Get ComCreateJwsSb Of hoJws vSbJws To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoJws To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get ComGetAsString Of hoSbJws To sTemp1
    Showln sTemp1


End_Procedure