Sha256 Hashes in Dart
Here’s the translation of the SHA256 Hashes example from Go to Dart, formatted in Markdown for Hugo:
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 Dart.
Dart implements several hash functions in the crypto
package. To use it, you need to add the crypto
package to your pubspec.yaml
file:
In this example, we start by importing the necessary libraries. The dart:convert
library is used for UTF-8 encoding, and the crypto
package provides the SHA256 implementation.
We create a string that we want to hash. Then, we use utf8.encode()
to convert the string to a list of bytes.
Next, we use sha256.convert()
to compute the hash of the bytes. This method returns a Digest
object.
Finally, we print the original string and the computed hash. The toString()
method of the Digest
object returns the hash in hexadecimal 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.convert()
instead of sha256.convert()
.
Note that if you need cryptographically secure hashes, you should carefully research hash strength!