Sample code for 30+ languages & platforms
Xbase++

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 Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oJws
LOCAL oHeader
LOCAL nBIncludeBom
LOCAL cBase64Key
LOCAL cJwsCompact

nSuccess := 0

oJws := CreateObject("Chilkat.Jws")

//  Protected header specifying HMAC-SHA256.
oHeader := CreateObject("Chilkat.JsonObject")
oHeader:UpdateString("alg", "HS256")
nSuccess := oJws:SetProtectedHeader(0, oHeader)
IF (nSuccess == 0)
    ? oJws:LastErrorText
    oJws:destroy()
    oHeader:destroy()
    RETURN
ENDIF

nBIncludeBom := 0
nSuccess := oJws:SetPayload("This is the content to sign.", "utf-8", nBIncludeBom)
IF (nSuccess == 0)
    ? oJws:LastErrorText
    oJws:destroy()
    oHeader:destroy()
    RETURN
ENDIF

//  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.
cBase64Key := "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU="
nSuccess := oJws:SetMacKey(0, cBase64Key, "base64")
IF (nSuccess == 0)
    ? oJws:LastErrorText
    oJws:destroy()
    oHeader:destroy()
    RETURN
ENDIF

cJwsCompact := oJws:CreateJws()
IF (oJws:LastMethodSuccess == 0)
    ? oJws:LastErrorText
    oJws:destroy()
    oHeader:destroy()
    RETURN
ENDIF

? cJwsCompact

oJws:destroy()
oHeader:destroy()