Issue #925

Use AES.GCM method with 128 bits key

import CryptoKit

public extension Optional {
    func tryUnwrap() throws -> Wrapped {
        if let value = self {
            return value
        } else {
            throw NSError(domain: "", code: 0)
        }
    }
}

public struct Crypto {
    static func encrypt(input: Data, key: String) -> Data {
        do {
            let keyData = Data(key.data(using: .utf8)!.prefix(32))
            let key = SymmetricKey(data: keyData)

            let sealed = try AES.GCM.seal(input, using: key)
            return try sealed.combined.tryUnwrap()
        } catch {
            return input
        }
    }
    
    static func decrypt(input: Data, key: String) -> Data {
        do {
            let keyData = Data(key.data(using: .utf8)!.prefix(32))
            let key = SymmetricKey(data: keyData)

            let box = try AES.GCM.SealedBox(combined: input)
            let opened = try AES.GCM.open(box, using: key)
            return opened
        } catch {
            return input
        }
    }
}

How to use

let key = "a secret key"
let input = "hello world".data(using: .utf8)!

let encrypted = Crypto.encrypt(input: input, key: key)
let decrypted = Crypto.decrypt(input: encrypted, key: key)
print(String(data: decrypted, encoding: .utf8)) // hello world