Summary - Security
- Dart course
- Advanced
- Lesson 72/83
- 5 min
Combine crypto, HMAC and encrypt to write an encryptor.
Summary - Security
In this group we learned Dart's security tools. crypto provides hash functions (sha256); HMAC produces keyed signatures; encrypt does AES symmetric encryption; Random.secure produces cryptographic random; bcrypt offers password hashing.
In this summary we will write a small program that brings crypto and HMAC together. The program computes the SHA-256 hash of data and the HMAC-SHA256 signature of the same data. This is a small example of an application's data integrity and authentication layer.
Practice Hash and HMAC summary
Add import 'dart:convert'; and import 'package:crypto/crypto.dart';. In main add final data = utf8.encode('test');. Compute the hash with final hash = sha256.convert(data);. Create the HMAC with final key = utf8.encode('anahtar'); and final hmac = Hmac(sha256, key);, compute the signature with final digest = hmac.convert(data);. Print with print('Hash: $hash') and print('HMAC: $digest').
Starter code
// import dart:convert and the crypto package
void main() {
// compute sha256 hash and HMAC-SHA256 signature of 'test' and print
}Sample solution
import 'dart:convert';
import 'package:crypto/crypto.dart';
void main() {
final data = utf8.encode('test');
final hash = sha256.convert(data);
final key = utf8.encode('anahtar');
final hmac = Hmac(sha256, key);
final digest = hmac.convert(data);
print('Hash: $hash');
print('HMAC: $digest');
}Expected output
Hash: 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08 HMAC: 6370f34eedacadc33452b4fc825abafc6aa7ae86d29e7b36fe1b76f0ffbad0fa
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is the password hashing algorithm?
- jaspr
- crypto
- encrypt
- bcrypt Correct answer
Explanation: bcrypt is the password hashing algorithm.
2 Match the security tools
| Term | Meaning |
|---|---|
sha256 |
Hash |
Hmac |
Signed hash |
AES |
Encryption |
bcrypt |
Password |
3 The sha256 call
final hash = ____.convert(utf8.encode('test'));
final hash = sha256.convert(utf8.encode('test'));
Explanation: sha256.convert(...) computes the SHA-256 digest.