Sha256 Hashes in Swift

Here’s the translation of the Go SHA256 hashes example to Swift:

Our first program demonstrates how to compute SHA256 hashes. SHA256 hashes are frequently used to compute short identities for binary or text blobs. For example, TLS/SSL certificates use SHA256 to compute a certificate’s signature. Here’s how to compute SHA256 hashes in Swift.

import Foundation
import CryptoKit

func main() {
    let s = "sha256 this string"

    // Here we start with a new hash.
    let h = SHA256.hash(data: s.data(using: .utf8)!)

    // Convert the hash to a byte array
    let bs = h.compactMap { $0 }

    print(s)
    print(bs.map { String(format: "%02x", $0) }.joined())
}

main()

Swift implements several hash functions in the CryptoKit framework.

In this example, we create a string s that we want to hash. Then we use the SHA256.hash(data:) method to compute the hash of the string’s UTF-8 representation.

The compactMap is used to convert the SHA256.Digest to an array of bytes. Finally, we print the original string and the hash in a human-readable hex format.

Running the program computes the hash and prints it in a human-readable hex format.

$ swift sha256-hashes.swift
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...

You can compute other hashes using a similar pattern to the one shown above. For example, to compute SHA512 hashes, you can use SHA512.hash(data:) from the CryptoKit framework.

Note that if you need cryptographically secure hashes, you should carefully research hash strength!