Sample code for 30+ languages & platforms
Swift

Encrypt a JWE with a Password (PBES2)

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.SetPassword, which sets the PBES2 password for a recipient. The example uses PBES2-HS256+A128KW key management with AES-128-GCM content encryption.

Background. PBES2 derives a key-wrapping key from a password using a salt and iteration count, allowing password-based JWE encryption. The password should come from a secure source.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    let jwe = CkoJwe()!

    //  Protected header: PBES2 password-based key management with AES-128-GCM content encryption.
    let header = CkoJsonObject()!
    header.updateString(jsonPath: "alg", value: "PBES2-HS256+A128KW")
    header.updateString(jsonPath: "enc", value: "A128GCM")
    success = jwe.setProtectedHeader(json: header)
    if success == false {
        print("\(jwe.lastErrorText!)")
        return
    }

    //  Set the PBES2 password for recipient 0.  The password should come from a secure source rather than
    //  being hard-coded.
    var password: String? = "myPassword"
    success = jwe.setPassword(index: 0, password: password)
    if success == false {
        print("\(jwe.lastErrorText!)")
        return
    }

    var jweCompact: String? = jwe.encrypt(content: "This is the secret content.", charset: "utf-8")
    if jwe.lastMethodSuccess == false {
        print("\(jwe.lastErrorText!)")
        return
    }

    print("\(jweCompact!)")

}