CodeBlanks Logo Icon CodeBlanks

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.

Practice 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').

Starter code

main.dart
// import the bcrypt package
// define hashPassword and verifyPassword functions

void main() {
  // print bcrypt info
}

Sample solution

main.dart
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');
}

Expected output

bcrypt: password hashing
API: hashpw, checkpw

Questions and answers

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

1 The bcrypt import

Question
import 'package:____/bcrypt/bcrypt.dart';
Answer
import 'package:bcrypt/bcrypt/bcrypt.dart';

Explanation: bcrypt is imported via package:bcrypt/bcrypt.dart.

2 Match the bcrypt parts

Term Meaning
bcrypt Password hashing
hashpw Hashes
checkpw Verifies
gensalt Produces salt

3 What is bcrypt used for?

  • File compression
  • HTTP requests
  • Password hashing Correct answer
  • Network management

Explanation: bcrypt is used for password hashing.

All lessons in Advanced