Dart
Password hashing
Learn password hashing (bcrypt).
Password hashing with bcrypt
bcrypt is an algorithm designed to hash passwords securely. It adds a random salt to each hash; so the same password produces a different hash every time. It protects against rainbow tables. It is imported with import 'package:bcrypt/bcrypt.dart';.
Example: final hash = BCrypt.hashpw('pass123', BCrypt.gensalt());. This hashes 'pass123' with a salt. Verification: BCrypt.checkpw('pass123', hash). It returns true if the password is correct, false otherwise. bcrypt is intentionally slow; this makes brute force attacks harder.
The password storage pattern
An application never stores passwords as plain text. Instead at signup it produces a hash with BCrypt.hashpw(password, BCrypt.gensalt()) and stores the hash. At login it verifies the user's input with BCrypt.checkpw(password, storedHash).
This pattern ensures that even a database leak does not expose passwords. An attacker gets hashes but cannot recover the original passwords. The slowness of bcrypt also makes cracking leaked hashes harder. In this lesson we define hashPassword and verifyPassword functions.
Exercise Password functions
Add import 'package:bcrypt/bcrypt.dart';. Define hashPassword(String password) with return BCrypt.hashpw(password, BCrypt.gensalt()); inside. Define verifyPassword(String password, String hash) with return BCrypt.checkpw(password, hash); inside. In main add print('bcrypt: password hashing') and print('API: hashpw, checkpw').
Show example solution
import 'package:bcrypt/bcrypt.dart';
String hashPassword(String password) {
return BCrypt.hashpw(password, BCrypt.gensalt());
}
bool verifyPassword(String password, String hash) {
return BCrypt.checkpw(password, hash);
}
void main() {
print('bcrypt: password hashing');
print('API: hashpw, checkpw');
}
Test yourself
-
The bcrypt import
import 'package:____/bcrypt/bcrypt.dart';
Show answer
import 'package:bcrypt/bcrypt/bcrypt.dart';
-
Match the bcrypt parts
- bcrypt
- Password hashing
- hashpw
- Hashes
- checkpw
- Verifies
- gensalt
- Produces salt
-
What is bcrypt used for?
- File compression
- HTTP requests
- Password hashing
- Network management
Show answer
Password hashing — bcrypt is used for password hashing.
Next lesson: Summary - Security