Sample code for 30+ languages & platforms
Swift

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 Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    let jws = CkoJws()!

    //  Set the protected header for signer 0, specifying the signature algorithm (alg).
    let header = CkoJsonObject()!
    header.updateString(jsonPath: "alg", value: "HS256")
    success = jws.setProtectedHeader(index: 0, json: header)
    if success == false {
        print("\(jws.lastErrorText!)")
        return
    }

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

    //  Provide the HMAC key (base64) for signer 0.  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
    }

    //  Create the JWS and write it into a StringBuilder.
    let sbJws = CkoStringBuilder()!
    success = jws.createSb(sbJws: sbJws)
    if success == false {
        print("\(jws.lastErrorText!)")
        return
    }

    print("\(sbJws.getAsString()!)")

}