CodeBlanks Logo Icon CodeBlanks

crypto

Learn hashing with the crypto package.

The crypto package

crypto is Dart's hash function package. It is imported with import 'package:crypto/crypto.dart';. It offers SHA-256, SHA-512 and MD5 algorithms. It turns data into a fixed-length hash digest.

Example: final hash = sha256.convert(utf8.encode('Merhaba'));. Here utf8.encode turns the text into bytes; sha256.convert computes the SHA-256 digest of those bytes. The result is a 64-character hexadecimal string. A hash is one-way; you produce a hash from data but cannot recover data from the hash.

Using SHA-256

SHA-256 produces a 256-bit (32-byte) hash. It is shown as a 64-character hexadecimal string. The same input always gives the same hash; so it is used for file integrity and fingerprinting.

Usage: import 'dart:convert'; import 'package:crypto/crypto.dart';. Then final hash = sha256.convert(utf8.encode('Merhaba')); print(hash);. The hash variable is a Digest object; toString() or direct print gives the hex string. Hash computation is deterministic; the same input always produces the same output.

Practice Compute a SHA-256 hash

Add import 'dart:convert'; and import 'package:crypto/crypto.dart';. In main compute the hash with final hash = sha256.convert(utf8.encode('Merhaba')); and print with print(hash).

Starter code

main.dart
// import dart:convert and the crypto package

void main() {
  // compute the sha256 hash of 'Merhaba' and print it
}

Sample solution

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

void main() {
  final hash = sha256.convert(utf8.encode('Merhaba'));
  print(hash);
}

Expected output

7fdc9f4717c5fe66df286c700fab969b4d6209d03aa84624c5f8f58c17c9c058

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does the crypto package provide?

  • HTTP client
  • Database
  • Hash functions Correct answer
  • DOM manipulation

Explanation: the crypto package provides hash functions.

2 The sha256 call

Question
final hash = ____.convert(utf8.encode('Merhaba'));
Answer
final hash = sha256.convert(utf8.encode('Merhaba'));

Explanation: sha256.convert(...) computes the SHA-256 digest.

3 Match the crypto parts

Term Meaning
crypto Hash package
sha256 256 bit
utf8.encode Turns to bytes
convert Computes

All lessons in Advanced