PureBasic
PureBasic
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 PureBasic Downloads
IncludeFile "CkJws.pb"
IncludeFile "CkJsonObject.pb"
Procedure ChilkatExample()
success.i = 0
jws.i = CkJws::ckCreate()
If jws.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
; Protected header specifying HMAC-SHA256.
header.i = CkJsonObject::ckCreate()
If header.i = 0
Debug "Failed to create object."
ProcedureReturn
EndIf
CkJsonObject::ckUpdateString(header,"alg","HS256")
success = CkJws::ckSetProtectedHeader(jws,0,header)
If success = 0
Debug CkJws::ckLastErrorText(jws)
CkJws::ckDispose(jws)
CkJsonObject::ckDispose(header)
ProcedureReturn
EndIf
bIncludeBom.i = 0
success = CkJws::ckSetPayload(jws,"This is the content to sign.","utf-8",bIncludeBom)
If success = 0
Debug CkJws::ckLastErrorText(jws)
CkJws::ckDispose(jws)
CkJsonObject::ckDispose(header)
ProcedureReturn
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.
base64Key.s = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU="
success = CkJws::ckSetMacKey(jws,0,base64Key,"base64")
If success = 0
Debug CkJws::ckLastErrorText(jws)
CkJws::ckDispose(jws)
CkJsonObject::ckDispose(header)
ProcedureReturn
EndIf
jwsCompact.s = CkJws::ckCreateJws(jws)
If CkJws::ckLastMethodSuccess(jws) = 0
Debug CkJws::ckLastErrorText(jws)
CkJws::ckDispose(jws)
CkJsonObject::ckDispose(header)
ProcedureReturn
EndIf
Debug jwsCompact
CkJws::ckDispose(jws)
CkJsonObject::ckDispose(header)
ProcedureReturn
EndProcedure