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.
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.
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!