Posted in

Hashing vs Encoding vs Encryption in Swift: Beginner’s Guide

Encoding vs hashing vs encryption
Spread the love
Reading Time: 3 minutes

🔹 Hashing in Swift (Password Example)

Purpose:
Hashing is used to verify data without revealing it directly. For example, when you log in with a password:

  • The system never stores your real password.
  • Instead, it stores a hash of your password.
  • When you log in, the system hashes the entered password again and checks if the two hashes match.

Flow of password check with hashing:

  1. User registers → Password "MySecret123" is hashed (say with SHA256) → stored in database.
    Example stored: c9ef0d24d3... (hash string).
  2. User logs in → Enters "MySecret123".
  3. App hashes this input again with the same algorithm (SHA256).
  4. Compare the new hash with the stored hash.
    • ✅ If they match → Login success.
    • ❌ If not → Wrong password.

🔑 Notice:

  • Even if someone steals the database, they only get the hashes, not the original passwords.
  • Hashing is one-way — you can’t reverse it.

Swift Example (SHA256):

import CryptoKit

func hashPassword(_ password: String) -> String {
    let data = Data(password.utf8)
    let hash = SHA256.hash(data: data)
    return hash.compactMap { String(format: "%02x", $0) }.joined()
}

let storedHash = hashPassword("MySecret123")
// Save `storedHash` in DB

let loginHash = hashPassword("MySecret123")
// Compare `loginHash` == `storedHash`

Common Hashing Methods in Swift:

  • SHA-256 (Secure Hash Algorithm 256-bit)
    • Most commonly used cryptographic hash.
    • Secure, widely accepted.
  • SHA-512
    • Stronger variant of SHA-256, but produces larger hashes.
    • Used when extra security is needed.

🔹 Encoding in Swift

Purpose:
Encoding is about representation, not secrecy.

  • Example: If you want to send an image or text over the internet, you encode it (Base64, JSON, URL-safe text) so the other system can understand it.
  • Without encoding, data may break in transit (e.g., a special character might be misread).

If we didn’t use encoding:

  • Sending binary files (like an image) via text-based systems (like JSON or HTML) would fail.
  • Special characters (like &, ?, +) could be misinterpreted in URLs.

Swift Example (Base64):

let text = "Hello Swift!"
let data = text.data(using: .utf8)!
let encoded = data.base64EncodedString()  // "SGVsbG8gU3dpZnQh"
let decoded = String(data: Data(base64Encoded: encoded)!, encoding: .utf8)!
// decoded = "Hello Swift!"

Common Encoding Methods in Swift:

  • Base64 → Convert binary to text (for safe transmission).
  • URL Encoding → Replace unsafe characters in URLs (Hello Swift!Hello%20Swift%21).
  • JSON Encoding/Decoding → Convert objects ↔ JSON.

🔹 Encryption in Swift

Purpose:
Encryption ensures secrecy by scrambling data so only someone with the right key can read it.

  • Unlike encoding, encryption requires a key.
  • Unlike hashing, encryption is reversible (decrypt → original message).

Flow (e.g., chat message):

  1. User sends message "Hello".
  2. App encrypts with a key → "9a8b23...".
  3. Transmits encrypted text.
  4. Receiver decrypts with the same key → "Hello".

Swift Example (AES):

import CryptoKit

func encryptMessage(_ message: String, using key: SymmetricKey) -> Data {
    let data = message.data(using: .utf8)!
    let sealedBox = try! AES.GCM.seal(data, using: key)
    return sealedBox.combined!
}

func decryptMessage(_ encrypted: Data, using key: SymmetricKey) -> String {
    let sealedBox = try! AES.GCM.SealedBox(combined: encrypted)
    let decrypted = try! AES.GCM.open(sealedBox, using: key)
    return String(data: decrypted, encoding: .utf8)!
}

let key = SymmetricKey(size: .bits256)
let encrypted = encryptMessage("Hello Swift!", using: key)
let decrypted = decryptMessage(encrypted, using: key)
// decrypted = "Hello Swift!"

Common Encryption Methods in Swift:

  • AES (Advanced Encryption Standard) → Fast, widely used.
  • RSA (Asymmetric) → Public/Private key encryption.
  • ChaCha20 → Modern alternative to AES.

Summary Table

ConceptPurposeDirectionReversibleExample in Swift
EncodingFormat data for transmission/readingTwo-way✅ YesBase64, JSON, URL
HashingVerify integrity (e.g., passwords)One-way❌ NoSHA256, SHA512
EncryptionProtect secrecy with a keyTwo-way✅ Yes (with key)AES, RSA

So,

  • Encoding = Representation (safe transport)
  • Hashing = Integrity (verification, not secrecy)
  • Encryption = Secrecy (with keys)

I'm a passionate iOS Developer with over 8 years of experience building high-quality iOS apps using Objective-C, Swift, and SwiftUI. I created iostutor.com to share practical tips, tutorials, and insights for developers of all levels.

When I’m not coding, I enjoy exploring new technologies and writing content — from technical guides to stories and poems — with the hope that it might help or inspire someone, somewhere.

Leave a Reply

Your email address will not be published. Required fields are marked *