Cipher Algorithms

Ciphers allow you to encrypt plaintext data with a key yielding ciphertext. This ciphertext can be later decrypted by the same cipher using the same key.

Read more about ciphers on Wikipedia.

Encrypt

Use the global convenience variables for encrypting data with common algorithms.

  1. let ciphertext = try AES128.encrypt("vapor", key: "secret")
  2. print(ciphertext) /// Data

Decrypt

Decryption works very similarly to encryption. The following snippet shows how to decrypt the ciphertext from our previous example.

  1. let plaintext = try AES128.decrypt(ciphertext, key: "secret")
  2. print(plaintext) /// "vapor"

See the Crypto module’s global variables for a list of all available cipher algorithms.

Streaming

Both encryption and decryption can work in a streaming mode that allows data to be chunked. This is useful for controlling memory usage while encrypting large amounts of data.

  1. let key: Data // 16-bytes
  2. let aes128 = Cipher(algorithm: .aes128ecb)
  3. try aes128.reset(key: key, mode: .encrypt)
  4. var buffer = Data()
  5. try aes128.update(data: "hello", into: &buffer)
  6. try aes128.update(data: "world", into: &buffer)
  7. try aes128.finish(into: &buffer)
  8. print(buffer) // Completed ciphertext