Sample code for 30+ languages & platforms
Swift

Validate a JWS with a Public Key

See more JSON Web Signatures (JWS) Examples

Demonstrates Jws.SetPublicKey, which sets the public key used to validate a signature of a loaded JWS.

The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.

Background. The public key verifies a signature created with the corresponding private key. Validate returns 1 when valid, 0 when not, or a negative value on error.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    let jws = CkoJws()!

    //  Load the JWS compact serialization.
    var jwsCompact: String? = "eyJhbGciOiJIUzI1NiJ9.VGhpcyBpcyB0aGUgY29udGVudCB0byBzaWduLg.<signature>"
    success = jws.load(jwsStr: jwsCompact)
    if success == false {
        print("\(jws.lastErrorText!)")
        return
    }

    //  The file path is relative to the application's current working directory.  An absolute path
    //  may also be used.  Supply the path appropriate to your own environment.
    //  Load the signer's public key and set it for validating signature 0.
    let pubKey = CkoPublicKey()!
    success = pubKey.load(fromFile: "qa_data/signer_pubkey.pem")
    if success == false {
        print("\(pubKey.lastErrorText!)")
        return
    }

    success = jws.setPublicKey(index: 0, pubKey: pubKey)
    if success == false {
        print("\(jws.lastErrorText!)")
        return
    }

    //  Validate the signature.  Validate returns 1 when valid, 0 when not, or a negative value on error.
    var v: Int = jws.validate(index: 0).intValue
    if v < 0 {
        print("\(jws.lastErrorText!)")
        return
    }

    if v != 1 {
        print("The signature is not valid.")
        return
    }

    print("The signature is valid.")

}