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.

import 'dart:convert';
import 'package:crypto/crypto.dart';

void main() {
  String s = "sha256 this string";

  // Create a SHA256 hash object
  var bytes = utf8.encode(s);
  var digest = sha256.convert(bytes);

  print(s);
  print(digest.toString());
}

Dart implements several hash functions in the crypto package. To use it, you need to add the crypto package to your pubspec.yaml file:

dependencies:
  crypto: ^3.0.1

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:

$ dart run sha256_hashes.dart
sha256 this string
d3b4ddb7e093445b0d83d8240afae0a5f8622bec7f1c0dc6f984c3a28d43d548

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!