M5: Insufficient Cryptography
M5: Insufficient Cryptography
Using weak encryption algorithms or implementing cryptography incorrectly leaves data vulnerable to decryption.
// iOS - Proper cryptographic implementation
class CryptographyManager {
// VULNERABLE: Common cryptographic mistakes
class WeakCryptography {
func demonstrateMistakes() {
// Bad: Using deprecated algorithms
let key = "weak_key_123"
let iv = "1234567890123456"
// Bad: ECB mode (patterns preserved)
// Bad: Hard-coded keys
// Bad: Predictable IVs
// Bad: Using MD5 for hashing
}
}
// SECURE: Strong cryptographic implementation
class StrongCryptography {
// Generate cryptographically secure keys
func generateKey() -> SymmetricKey {
return SymmetricKey(size: .bits256)
}
// Encrypt data with authenticated encryption
func encryptData(_ plaintext: Data, using key: SymmetricKey) throws -> EncryptedData {
// Use AES-GCM for authenticated encryption
let sealedBox = try AES.GCM.seal(plaintext, using: key)
return EncryptedData(
ciphertext: sealedBox.ciphertext,
nonce: sealedBox.nonce,
tag: sealedBox.tag
)
}
// Key derivation from password
func deriveKey(from password: String, salt: Data) throws -> SymmetricKey {
// Use Argon2 or PBKDF2 with proper parameters
let keyData = try self.pbkdf2(
password: password,
salt: salt,
keyByteCount: 32,
rounds: 100_000
)
return SymmetricKey(data: keyData)
}
// Secure random number generation
func generateSecureRandom(bytes: Int) -> Data? {
var randomData = Data(count: bytes)
let result = randomData.withUnsafeMutableBytes { buffer in
SecRandomCopyBytes(kSecRandomDefault, bytes, buffer.baseAddress!)
}
return result == errSecSuccess ? randomData : nil
}
// Digital signature implementation
func signData(_ data: Data, with privateKey: SecKey) throws -> Data {
var error: Unmanaged<CFError>?
guard let signature = SecKeyCreateSignature(
privateKey,
.rsaSignatureMessagePSSSHA256,
data as CFData,
&error
) else {
throw error?.takeRetainedValue() ?? CryptoError.signingFailed
}
return signature as Data
}
struct EncryptedData {
let ciphertext: Data
let nonce: AES.GCM.Nonce
let tag: Data
var combined: Data {
var data = Data()
data.append(nonce)
data.append(tag)
data.append(ciphertext)
return data
}
}
}
}