Swift
Swift
Encrypt a JWE with a Recipient Public Key
See more JSON Web Encryption (JWE) Examples
Demonstrates Jwe.SetPublicKey, which sets the public key used to encrypt for a recipient. The example uses RSA-OAEP-256 key management with AES-256-GCM content encryption.
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. In public-key JWE, the content-encryption key is wrapped for the recipient using their public key, so only the holder of the matching private key can decrypt.
Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
let jwe = CkoJwe()!
// Protected header: RSA-OAEP-256 key management with AES-256-GCM content encryption.
let header = CkoJsonObject()!
header.updateString(jsonPath: "alg", value: "RSA-OAEP-256")
header.updateString(jsonPath: "enc", value: "A256GCM")
success = jwe.setProtectedHeader(json: header)
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 public key.
let pubKey = CkoPublicKey()!
success = pubKey.load(fromFile: "qa_data/recipient_pubkey.pem")
if success == false {
print("\(pubKey.lastErrorText!)")
return
}
// Set the public key used to encrypt for recipient 0.
success = jwe.setPublicKey(index: 0, pubKey: pubKey)
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!)")
}