encrypt data using aes in swift

To encrypt data using the AES algorithm in Swift, you can use the CryptoKit framework provided by Apple. Here's an example:

main.swift
import CryptoKit

func encrypt(data: Data, key: SymmetricKey) throws -> Data {
    let sealedBox = try AES.GCM.seal(data, using: key)
    return sealedBox.combined!
}

// Usage:
let plaintext = "hello world".data(using: .utf8)!
let key = SymmetricKey(size: .bits256)
let ciphertext = try encrypt(data: plaintext, key: key)
print(ciphertext.base64EncodedString())  // output: "D6uncCv6ACFizSut9kmy8g=="
402 chars
13 lines

In the example above, we define a function called encrypt that takes in the plaintext data to be encrypted, as well as a symmetric key that will be used to encrypt the data. We use the AES.GCM.seal function to perform the encryption, which returns a SealedBox object that contains both the encrypted data and a tag that can be used to verify the integrity of the data. Finally, we return just the combined property of the SealedBox, which contains both the encrypted data and the tag.

Note that the size of the key used for encryption is specified as 256 bits in the example above, but other sizes are also supported.

gistlibby LogSnag