Fixed salts in Swift

Fixed salts in Swift

Description

A fixed salt in password hashing or key derivation makes identical inputs produce identical results under the same algorithm and settings. An attacker can reuse the computation for a password candidate across multiple users.

Potential impact

  • Lower cost for dictionary attacks.
  • Easier identification of users with the same password.
  • Greater chance of recovering passwords from stolen hashes.

Remediation

Generate a fresh salt for each password hash using a vetted library's cryptographically secure random generator. Store it with the hash for verification. Choose the password-hashing algorithm and work factor separately.

Examples

Before

swift
try PKCS5.PBKDF2(
    password: password,
    salt: Array<UInt8>("staticSalt".utf8),
    iterations: 600000,
    keyLength: 32).calculate()

After

swift
import CryptoSwift

func derivePasswordKey(
    password: [UInt8]
) throws -> (salt: [UInt8], derivedKey: [UInt8]) {
    let salt = (0..<16).map { _ in UInt8.random(in: 0...UInt8.max) }
    let derivedKey = try PKCS5.PBKDF2(
        password: password, salt: salt, iterations: 600000, keyLength: 32
    ).calculate()
    return (salt, derivedKey)
}

derivePasswordKey generates a new 16-byte salt on each call and returns it with the PBKDF2-derived key.

References