How to generate secure Hash in Swift using algorithms like SHA256, SHA384, and SHA512

Mykhailo Moiseienko
3 min readMay 31, 2023

--

In Swift, you can use the CryptoKit framework to generate a hash from data. The CryptoKit framework provides cryptographic functionality, including hash functions. The CryptoKit framework is available starting from iOS 13.

Here's an example of how you can generate a hash string from data using the SHA256 algorithm:

import CryptoKit

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

// Usage Example
let inputData = "Hello, World!".data(using: .utf8)!
let hashString = hash(data: inputData)
print(hashString)
// Output: dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f

In case you want to pass a specific algorithm as a parameter, you can use the modified version:

import CryptoKit

func hash(data: Data, using
hashFunction: any HashFunction.Type) -> String {
let digest = hashFunction.hash(data: data)
let hashString = digest
.compactMap { String(format: "%02x", $0) }
.joined()
return hashString
}

// Usage Example
let inputData = "Hello, World!".data(using: .utf8)!
let hashStringSHA256 = hash(data: inputData, using: SHA256.self)
let hashStringSHA384 = hash(data: inputData, using: SHA384.self)
let hashStringSHA512 = hash(data: inputData, using: SHA512.self)

Comparing Hash Algorithms

The main difference between SHA-256, SHA-384, and SHA-512 lies in the output size and the number of internal rounds performed by each algorithm. Here’s a breakdown of the key differences:

SHA-256 (Secure Hash Algorithm 256-bit):

  • Output Size: 256 bits (32 bytes).
  • Internal Rounds: SHA-256 performs 64 rounds of computation on the input data.
  • Advantages: SHA-256 is widely adopted, computationally efficient, and provides a good balance between security and performance. It is resistant to known cryptographic vulnerabilities and is suitable for most cryptographic purposes.

SHA-384 (Secure Hash Algorithm 384-bit):

  • Output Size: 384 bits (48 bytes).
  • Internal Rounds: SHA-384 performs 80 rounds of computation on the input data.
  • Advantages: SHA-384 offers a larger output size compared to SHA-256, which can provide a higher level of security. It is suitable for applications that require stronger hash functions.

SHA-512 (Secure Hash Algorithm 512-bit):

  • Output Size: 512 bits (64 bytes).
  • Internal Rounds: SHA-512 performs 80 rounds of computation on the input data.
  • Advantages: SHA-512 provides the largest output size among the three, offering an even higher level of security. It is suitable for applications that require the highest level of cryptographic strength.

Usage

Hash functions have various use cases in computer science and information security. Here are some common scenarios where hash functions are needed:

  1. Data Integrity: Hash functions are often used to ensure the integrity of data. By calculating the hash value of a piece of data, such as a file or a message, you can later verify if the data has been tampered with by comparing the calculated hash with the original hash value. If the hashes match, the data has remained unchanged.
  2. Password Storage: Hash functions are widely used for secure password storage. Instead of storing user passwords in plaintext, they are hashed and stored. When a user logs in, their entered password is hashed and compared with the stored hash value. This way, even if the password database is compromised, the original passwords are not easily exposed.
  3. Digital Signatures: Hash functions play a crucial role in digital signatures. The hash of a document or a message is encrypted with the private key of the signer, creating a digital signature. Recipients can then verify the integrity and authenticity of the document by decrypting the signature using the signer’s public key and comparing the resulting hash with the recalculated hash of the received document.
  4. Data Deduplication: Hash functions are utilized in data deduplication scenarios where the goal is to eliminate duplicate data and store unique instances. By hashing the data, duplicate files or blocks can be identified quickly without the need for extensive comparisons, enabling efficient storage and retrieval of unique data.
  5. Data Indexing: Hash functions are employed in hash tables and hash-based data structures for efficient indexing and retrieval. Hashing allows for quick mapping of keys to their corresponding values, enabling fast access and lookup in large datasets.

--

--

Mykhailo Moiseienko
Mykhailo Moiseienko

Written by Mykhailo Moiseienko

📱 Senior iOS Software Engineer. ✍️ Writing about iOS Development, Swift, and SwiftUI.