---
title: Không để credential mặc định hoặc hardcode mật khẩu trong app
impact: HIGH
impactDescription: Credential mặc định hoặc mật khẩu hardcode trong source code có thể bị phát hiện qua reverse engineering hoặc static analysis, cho phép truy cập trái phép.
tags: swift, ios, credentials, hardcode, default-password, security
---

## Không để credential mặc định hoặc hardcode mật khẩu trong app

Không hardcode username/password, API key hoặc encryption key dưới dạng string literals trong code Swift. Đây là lỗi phổ biến nhất trong mobile app security. Dùng Keychain hoặc load từ server sau khi authenticate.

**Incorrect (hardcode credential):**

```swift
// !! Credential hardcode trong code
struct AuthService {
    private let adminUsername = "admin"
    private let adminPassword = "admin123"  // Hardcode!

    func loginAdmin() {
        let credentials = "\(adminUsername):\(adminPassword)"
            .data(using: .utf8)!
            .base64EncodedString()
        // Bất kỳ ai có binary app đều đọc được qua strings command
    }
}

// !! API key hardcode
class AnalyticsService {
    private let apiKey = "AIzaSyD-hardcoded-key-abc123"  // Lộ sau khi decompile!
    private let encryptionKey = "mySecretKey1234"  // Nguy hiểm!
}

// !! Default profile cho testing còn sót lại production
let defaultPIN = "1234"
let testAccountPassword = "Test@123"
```

**Correct (load từ secure source):**

```swift
// SAFE: Load API key từ xcconfig / remote config
class AnalyticsService {
    private let apiKey: String

    init() {
        // Load từ Info.plist (giá trị inject qua xcconfig trong CI/CD)
        guard let key = Bundle.main.infoDictionary?["ANALYTICS_API_KEY"] as? String,
              !key.isEmpty else {
            fatalError("ANALYTICS_API_KEY not configured")
        }
        self.apiKey = key
    }
}

// SAFE: Encryption key sinh ngẫu nhiên và lưu Keychain
class EncryptionKeyManager {
    private let keychainKey = "com.app.encryptionKey"

    func getOrCreateKey() throws -> SymmetricKey {
        if let keyData = try KeychainHelper.read(key: keychainKey) {
            return SymmetricKey(data: keyData)
        }
        // Sinh key ngẫu nhiên, không hardcode
        let newKey = SymmetricKey(size: .bits256)
        let keyData = newKey.withUnsafeBytes { Data($0) }
        try KeychainHelper.save(key: keychainKey, data: keyData)
        return newKey
    }
}

// Test credentials phải dùng environment variable trong CI
// Không commit file chứa test password vào Git
```

**Tools:** SwiftLint (no_hardcoded_strings custom rule), `strings` binary analysis, OWASP MASVS-STORAGE-2, detect-secrets
