DEV Community

João Matheus
João Matheus

Posted on

Advanced Encryption Standard with Swift

This blog I show my way of how to Advanced Encryption Standard with Swift Language.

I will use framework CryptoKit and your resource AES.

To perform the cryptography is necessary a key and message.

I use message "AES Cryptography" and aleatory key that received by SymmetricKey of bits 256.

let key = SymmetricKey(size: .bits256)<br>
let message = "AES Cryptography".data(using: .utf8)!<br>
let sealedBox = try! AES.GCM.seal(message, using: key)<br>
print(sealedBox.combined?.base64EncodedString() ?? "")<br>
let decryptedData = try? AES.GCM.open(sealedBox, using: key)<br>
print(String(data: decryptedData ?? Data(), encoding: .utf8) ?? "")

So, whats happening in this code?

Firstly, created a aleatory key using SymmetricKey and defines the message data that we want encrypt.

And next, use AES.GCM to storaged in SealedBox.

Right, your message has encrypt!

To decrypt this message, use AES.GCM.open passing your sealedBox and key.

Case need encrypt message with definitive key, change .init of SymmetricKey for this:

let key = SymmetricKey(data: "{YOUR_KEY}".data(using: .utf8)!)

Top comments (0)