Sample code for 30+ languages & platforms
Swift

Decrypt a JWE with a Private Key

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.SetPrivateKey, which sets the private key used to decrypt a recipient of a loaded JWE.

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 private key unwraps the content-encryption key that was wrapped with the corresponding public key during encryption.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    let jwe = CkoJwe()!

    //  Load the JWE compact serialization to be decrypted.
    var jweCompact: String? = "eyJhbGciOiJBMjU2S1ciLCJlbmMiOiJBMjU2R0NNIn0.<...>.<iv>.<ciphertext>.<tag>"
    success = jwe.load(jwe: jweCompact)
    if success == false {
        print("\(jwe.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 recipient's private key.
    let privKey = CkoPrivateKey()!
    success = privKey.loadPemFile(path: "qa_data/recipient_privkey.pem")
    if success == false {
        print("\(privKey.lastErrorText!)")
        return
    }

    //  Set the private key used to decrypt recipient 0.
    success = jwe.setPrivateKey(index: 0, privKey: privKey)
    if success == false {
        print("\(jwe.lastErrorText!)")
        return
    }

    var content: String? = jwe.decrypt(index: 0, charset: "utf-8")
    if jwe.lastMethodSuccess == false {
        print("\(jwe.lastErrorText!)")
        return
    }

    print("\(content!)")

}