ECB encryption mode in Swift

ECB encryption mode in Swift

Description

With the same key, ECB encrypts identical plaintext blocks into identical ciphertext blocks, revealing data patterns. Using it for sensitive data increases the risk of block reuse, pattern analysis, and precomputed attacks.

Potential impact

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

Remediation

  1. Use authenticated encryption such as AES-GCM instead of ECB.
  2. If legacy CBC must remain, use a fresh unpredictable IV and encrypt-then-MAC with a separate key. CTR needs a unique nonce for each message under the same key and separate integrity protection.
  3. Isolate legacy ECB compatibility from security-sensitive processing.

Examples

Before

The CryptoSwift excerpt assumes that the key and padding are prepared. The after example uses the separate CryptoKit API and its SymmetricKey type.

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)
}

Explanation:

  • Before: ECB under the same key maps identical plaintext blocks to identical ciphertext blocks, exposing patterns.
  • After: CryptoKit AES-GCM protects confidentiality and integrity, with nonce generation handled by the cryptographic API.

References