Swift
Swift
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 Swift Downloads
func chilkatTest() {
var success: Bool = false
let jws = CkoJws()!
// Protected header specifying HMAC-SHA256.
let header = CkoJsonObject()!
header.updateString(jsonPath: "alg", value: "HS256")
success = jws.setProtectedHeader(index: 0, json: header)
if success == false {
print("\(jws.lastErrorText!)")
return
}
var bIncludeBom: Bool = false
success = jws.setPayload(payload: "This is the content to sign.", charset: "utf-8", includeBom: bIncludeBom)
if success == false {
print("\(jws.lastErrorText!)")
return
}
// 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.
var base64Key: String? = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU="
success = jws.setMacKey(index: 0, key: base64Key, encoding: "base64")
if success == false {
print("\(jws.lastErrorText!)")
return
}
var jwsCompact: String? = jws.create()
if jws.lastMethodSuccess == false {
print("\(jws.lastErrorText!)")
return
}
print("\(jwsCompact!)")
}