CodeBlanks Logo Icon CodeBlanks

HMAC

Learn message authentication with Hmac.

HMAC

HMAC (Hash-based Message Authentication Code) is a keyed hash. It provides not just a hash but message integrity and authentication together. It is used as Hmac(sha256, key).convert(data).

Example: final key = utf8.encode('anahtar'); final data = utf8.encode('mesaj'); final hmac = Hmac(sha256, key); final digest = hmac.convert(data);. Here the key and data are turned into bytes and HMAC-SHA256 is computed. The result is again 64 hex characters. The receiver computes the same HMAC with the same key and compares; if equal the message is unchanged and the sender is authenticated.

HMAC verification

HMAC works with a key shared by two parties. The sender produces an HMAC from the message and the key and sends it with the message. The receiver computes its own HMAC with the same key and compares. If equal the message is unchanged and from the correct sender.

This is a common method to sign API requests. For example a web service gives each user a key; requests are signed with this key. The server verifies the signature and confirms the request comes from an authorized source. In this lesson we learn HMAC computation.

Practice Compute an HMAC-SHA256

Add import 'dart:convert'; and import 'package:crypto/crypto.dart';. In main add final key = utf8.encode('anahtar'); and final data = utf8.encode('mesaj');. Compute the HMAC with final hmac = Hmac(sha256, key); and final digest = hmac.convert(data);. Print with print(digest).

Starter code

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

void main() {
  // compute HMAC-SHA256 of 'mesaj' with key 'anahtar' and print
}

Sample solution

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

void main() {
  final key = utf8.encode('anahtar');
  final data = utf8.encode('mesaj');
  final hmac = Hmac(sha256, key);
  final digest = hmac.convert(data);
  print(digest);
}

Expected output

4efc48e22c0421d2f0be62f9369b7930b6b69d9e71ee42a02f25ceb35c441b9c

Questions and answers

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

1 Creating an Hmac

Question
final hmac = ____(sha256, key);
Answer
final hmac = Hmac(sha256, key);

Explanation: Hmac(sha256, key) creates a keyed hash.

2 What does HMAC add?

  • Storage
  • Compression
  • Encryption
  • Authentication with a key Correct answer

Explanation: HMAC adds authentication with a key.

3 Match the HMAC parts

Term Meaning
Hmac Signed hash
sha256 Hash algorithm
key Key
convert Computes

All lessons in Advanced