Logo for tanaschita.com

Cryptographic hash functions in CryptoKit for iOS

Use cases of cryptographic hash functions and how to implement them in iOS.

10 Jan 2022 · 3 min read

Cryptographic hash functions are a basic tool of modern cryptography. They map a message of arbitrary size to a fixed size hash value, also called a message digest.

Characteristics of a hash function

A cryptographic hash function is a:

  • one-way function - meaning that it's practically irreversible
  • deterministic - meaning that the same message always results in the same hash value
  • unique - meaning that it's practically not possible to find two different messages with the same hash value

Use cases of a hash function

Cryptographic hash functions have many security applications, for example in digital signatures, message authentication, password verification and more.

Let's look at the password verification example in more detail. When a user enters a password into our app to login, we hash the password and send it to the server for verification. The passwords stored on the server are also computed hash values of the original passwords. This way, we never store the original password or send it over the network but still are able to verify it.

Hash functions in CryptoKit

CryptoKit provides the Secure Hash Algorithm 2 (SHA-2) algorithms SHA-256, SHA-384 and SHA-512. The numbers indicate the digest size. Its Insecure container also provides SHA-1 and MD5 but those are considered to be insecure and available only for of backwards compatibility.

Let's look at how we can hash a password with the SHA-256 algorithm:

let hashedPassword = SHA512.hash(data: Data(password.utf8))

To use the other algorithms, just replace SHA512 with another algorithm. And that's basically it. CryptoKit makes it really easy to use and apply cryptographic hash functions.

Image of books
Further reading: Swift Power Pack
For further reading, check out the Swift Power Pack books by Paul Hudson. The bundle delivers six books from beginner to advanced around Swift topics.


Receive a monthly newsletter about the latest articles and tips.

Image of a reading marmot

Related tags

Written by

Articles with related topics

Latest articles and tips