Hashing is a one-way process that transforms data into a fixed-length string that represents the original input. Unlike encryption, hashing is irreversible — you can’t decode the hashed result back to the original data.
In iOS, hashing is often used to:
- Protect sensitive information in a non-reversible way
- Store passwords securely
- Verify data integrity
Hashing in Swift with CryptoKit
You can hash data in Swift using CryptoKit (available in iOS 13+). Here’s how:
import CryptoKit
func hash(_ input: String) -> String {
let inputData = Data(input.utf8)
let hashed = SHA256.hash(data: inputData)
return hashed.map { String(format: "%02x", $0) }.joined()
}
let originalPassword = "MySecret123"
let hashedPassword = hash(originalPassword)
storeInDB(hashedPassword) // store this in database
Example: Verifying a Password Using Hashing
Step 1: Hash the original password and store it
let originalPassword = "MySecret123"
let hashedPassword = hash(originalPassword)
storeInDB(hashedPassword) // Save to database
Step 2: When user logs in, hash their input and compare
let enteredPassword = "MySecret123"
let enteredHash = hash(enteredPassword)
let storedHash = getHashFromDB()
if enteredHash == storedHash {
print("✅ Password matched")
} else {
print("❌ Incorrect password")
}
❗ Hashing ≠ Encryption
Feature | Hashing | Encryption |
---|---|---|
Direction | One-way | Two-way (can decrypt) |
Purpose | Verification | Privacy/Confidentiality |
Reversible? | No | Yes |
Example Use | Password checking | Storing secure data |
For Real-World Authentication
While SHA256 is okay for learning, never use plain SHA256 in production for password storage.
Instead, use:
- PBKDF2
- bcrypt
- Argon2
Also, always add a salt to prevent rainbow table attacks.
Thank you!