ECB encryption mode in Swift

ECB encryption mode in Swift

Description

With the same key, ECB turns identical plaintext blocks into identical ciphertext blocks, revealing patterns in the data.

Potential impact

  • Disclosure of ciphertext patterns.
  • Identification of repeated data.
  • Increased likelihood of recovering sensitive information.

Remediation

  • Use authenticated encryption such as AES-GCM for sensitive data. Keep any ECB code needed for compatibility separate from this processing.
  • If you must keep CBC, use a fresh, unpredictable IV and encrypt-then-MAC with a separate MAC key. For CTR, use a unique nonce for each message under the same key and add separate integrity protection.

Examples

Before

The CryptoSwift example assumes a key and padding are ready. The CryptoKit example takes a SymmetricKey.

swift
let blockMode = ECB()
let aes = try AES(key: key, blockMode: blockMode, padding: padding)

After

swift
import Foundation
import CryptoKit

func encryptAuthenticated(
    data: Data,
    key: SymmetricKey
) throws -> AES.GCM.SealedBox {
    return try AES.GCM.seal(data, using: key)
}

AES.GCM.seal generates the nonce and returns the ciphertext and its authentication tag in a SealedBox.

References