Sample code for 30+ languages & platforms
DataFlex

Sign a JWS with an HMAC Key

See more JSON Web Signatures (JWS) Examples

Demonstrates Jws.SetMacKey, which sets the symmetric MAC key for a signature. The key bytes are supplied in a named encoding such as hex or base64.

Background. HMAC-based JWS (for example HS256) authenticates the payload with a shared symmetric key that both signer and verifier possess.

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoJws
    Variant vHeader
    Handle hoHeader
    Boolean iBIncludeBom
    String sBase64Key
    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 HMAC-SHA256.
    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

    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

    //  Set the symmetric MAC key for signature 0.  The key bytes are provided in the named encoding (here
    //  base64).  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

    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