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, it is often used to:
- Protect sensitive information in a non-reversible way
- Store passwords securely
- Verify data integrity
Hashing in iOS with CryptoKit
Starting from iOS 13, you can hash data using CryptoKit. Here’s a basic example:
import CryptoKit
func hash(_ input: String) -> String {
let inputData = Data(input.utf8) // Line 1
let hashed = SHA256.hash(data: inputData) // Line 2
return hashed.map { String(format: "%02x", $0) }.joined() // Line 3
}
let originalPassword = "MySecret123"
let hashedPassword = hash(originalPassword)
storeInDB(hashedPassword) // store this in database
Lets crack the hashing method!
Line 1: let inputData = Data(input.utf8)
- Converts the
input
string into a sequence of bytes (UTF-8 encoded). - This is necessary because the SHA256 function works on binary data — not text.
Example :"hello"
becomes:[104, 101, 108, 108, 111]
Line 2: let hashed = SHA256.hash(data: inputData)
- Uses Swift’s
CryptoKit
framework to compute the SHA-256 hash of the input data. SHA256.hash(...)
returns aDigest
object containing the hashed bytes.
Line 3: hashed.map { String(format: "%02x", $0) }.joined()
- Then each byte of the hash converts into a 2-digit hex string (e.g.,
185 → "b9"
). - The
map
transforms each byte, andjoined()
combines them into one long string.
Hurray! And the final result would look like :
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
Example: Verifying a Password Using Hashing
Step 1: Hash the original password and store it
let originalPassword = "MySecret123"
let hashedPassword = hash(originalPassword) // The above hash() method
storeInDB(hashedPassword) // Save to database
Step 2: When user logs in, hash their input and compare
let enteredPassword = "MySecret123"
let enteredHash = hash(enteredPassword) // The above hash() method
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 |
Hope you’ve enjoyed!
2 thoughts on “Hashing in iOS – Understand the basic concept”