Skip to content

hashlib guide

A pure-Dart library of secure hash functions, checksums, MACs, key-derivation functions, OTP generators, and secure random — a broad, fast, dependency-light toolbox that runs everywhere Dart does.

It builds on convertlib for hex, Base32/Base64, and UTF-8 conversion, and that is its only runtime dependency.

  • Runs on every platform: pure Dart with no native code or FFI, so the same library works everywhere Dart does — the VM, Flutter (Android, iOS, Windows, macOS, Linux), and the web (dart2js and dart2wasm).
  • Batteries included: ten hash families (MD, SHA-1, SHA-2, SHA-3, SHAKE, Keccak, BLAKE2, RIPEMD, SM3, xxHash), checksums (CRC, Adler-32), MACs (HMAC, Poly1305), password KDFs (Argon2, scrypt, bcrypt, PBKDF2), TOTP/HOTP, and RNG/UUID generators.
  • One-shot or streaming: hash a String or byte buffer in a single call, or feed data incrementally through a reusable sink for large or chunked input.
  • Password-grade KDFs: Argon2id, scrypt, bcrypt, and PBKDF2 with named security presets that make the cost/latency trade-off explicit.
  • Fast: outruns crypto, PointyCastle, and hash in most benchmarks (crypto stays slightly ahead on some 10-byte inputs), see the benchmarks below.
  • Codecs and secure random built in: companion codecs and random libraries ship in the same package.
dependencies:
hashlib: ^2.4.4

or run dart pub add hashlib. A single import exposes every algorithm:

import 'package:hashlib/hashlib.dart';

Two companion libraries pair well with it — codecs for hex/Base/UTF-8 conversion (re-exported from convertlib) and random for secure random bytes, numbers, and UUIDs:

import 'package:hashlib/codecs.dart'; // toHex, fromHex, toBase64, toUtf8
import 'package:hashlib/random.dart'; // randomBytes, uuid, HashlibRandom

Full API reference: hashlib library.

A hash turns any input — text, a file, bytes — into a short, fixed-size “fingerprint”. Different jobs need different tools. Here is the plain-English map:

Your goal Reach for Examples
Fingerprint data, detect changes, build a cache key a cryptographic hash sha256, blake2b256
Store a user password safely a password KDF (slow on purpose) argon2id, bcrypt
Prove a message came from someone who knows a secret key a MAC sha256.hmac, poly1305
Quickly catch accidental corruption (not attackers) a checksum crc32, adler32
Generate 2FA / one-time login codes an OTP generator TOTP, HOTP
Generate unguessable tokens, IDs, or salts secure random randomBytes, uuid

Three rules of thumb if you are new to this:

  • Never store a password as a plain hash — not even sha256. Use a KDF like argon2id; it is deliberately slow, which makes guessing passwords expensive.
  • Checksums are not security. crc32, adler32, and the xxHash family are fast but trivial to forge. Use them against accidents, never against an attacker.
  • Unsure which cryptographic hash? sha256 is the safe universal default; blake2b256 is faster. Avoid md5 and sha1 for anything security-related.
import 'package:hashlib/hashlib.dart';
void main() {
// A hex fingerprint of some text — that's the whole idea.
print(sha256.string('Happy Hashing!').hex());
}

Every algorithm follows the same shape: call it on a String, a List<int>, or a stream, then read the result as hex, Base64, raw bytes, or a BigInt. The Usage section below shows one short recipe per task.

Algorithm Available methods Source
MD2 md2, md2sum RFC-1319
MD4 md4, md4sum RFC-1320
MD5 md5, md5sum RFC-1321
SHA-1 sha1, sha1sum RFC-3174
SHA-2 sha224, sha256, sha384, sha512, sha512t224, sha512t256 RFC-6234
SHA-3 sha3_224, sha3_256, sha3_384, sha3_512 FIPS-202
SHAKE-128 Shake128, shake128, shake128_128, shake128_256 FIPS-202
SHAKE-256 Shake256, shake256, shake256_256, shake256_512 FIPS-202
Keccak keccak224, keccak256, keccak384, keccak512 Team Keccak
Blake2b blake2b160, blake2b256, blake2b384, blake2b512 RFC-7693
Blake2s blake2s128, blake2s160, blake2s224, blake2s256 RFC-7693
xxHash-32 XXHash32, xxh32, xxh32code Cyan4973
xxHash-64 XXHash64, xxh64, xxh64code Cyan4973
xxHash3-64 XXH3, xxh3, xxh3code Cyan4973
xxHash3-128 XXH128, xxh128, xxh128sum Cyan4973
RIPEMD ripemd128, ripemd256, ripemd160, ripemd320 ISO/IEC 10118-3:2018
SM3 sm3, sm3sum GB/T 32905-2016

Note: On the web, XXHash64, XXH3, and XXH128 run on 32-bit implementations with identical output. Seeds must fit in 53 bits there, and xxh64code/xxh3code may round results above 2^53; use the sum/hex variants for exact values.

Algorithm Available methods Source
Argon2 Argon2, argon2d, argon2i, argon2id, argon2Verify RFC-9106
PBKDF2 PBKDF2, pbkdf2, #.pbkdf2 RFC-8081
scrypt Scrypt, scrypt RFC-7914
bcrypt Bcrypt, bcrypt, bcryptSalt, bcryptVerify, bcryptDigest
Algorithm Available methods Source
HMAC HMAC, #.hmac RFC-2104
Poly1305 Poly1305, poly1305, poly1305auth RFC-8439
Algorithm Available methods Source
HOTP HOTP RFC-4226
TOTP TOTP RFC-6238
Algorithm Available methods Source
CRC crc16, crc32, crc64 Wikipedia
Adler-32 adler32 Wikipedia

The random library provides random number generators through HashlibRandom (secure, system, keccak, sha256, md5, xxh64, sm3), plus helpers like randomBytes, randomNumbers, and randomString. UUID versions v1, v3, v4, v5, v6, v7, and v8 are available through uuid.

  • Hash passwords with a KDF, not a bare hash. Store argon2id (or scrypt / bcrypt) output with an appropriate security preset — never a plain sha256 of a password — and check it with argon2Verify / bcryptVerify.
  • Compare digests in constant time. Use HashDigest.isEqual when verifying MACs and digests instead of == or a manual byte loop, to avoid leaking information through timing.
  • Legacy algorithms are for compatibility only. MD2, MD4, MD5, and SHA-1 are cryptographically broken; use them only for interop or non-security checksums, and prefer SHA-256, SHA-3, or BLAKE2 for new work.
  • Non-cryptographic hashes. CRC, Adler-32, and the xxHash family are fast integrity and lookup hashes, not secure against adversaries — do not use them where collision or preimage resistance matters.
  • Runtime timing. Pure-Dart execution (JIT, AOT, dart2js) is not guaranteed to run in constant time; weigh the deployment environment before relying on it in side-channel-sensitive settings.

Correctness is the first-order goal of this library, and the test suite is built to enforce it. There are 700 test cases across 60+ files that runs after every change and before each release across three platforms: the Dart VM, Node.js, and Chrome (WASM).

Every algorithm is checked in several independent ways:

  • Official known-answer vectors. Digests are pinned against the published test vectors from the relevant standard — RFCs, FIPS/NIST publications, and each algorithm’s reference implementation. Expected values are never invented; each vector cites its source in the test file.
  • Differential cross-validation. For every algorithm that a mature, independent Dart package also implements, the output is compared byte-for-byte against crypto and pointycastle over hundreds of random inputs. This currently covers MD2, MD4, MD5, SHA-1, SHA-224/256/384/512, SHA-512/224, SHA-512/256, SHA3 (224–512), Keccak (224–512), RIPEMD-128/160/256/320, BLAKE2b, SM3, and HMAC. A subtle divergence in padding, endianness, or a block boundary would fail these tests even if it slipped past a fixed vector.
  • Boundary and edge coverage. Inputs are exercised at the empty string, single bytes, and lengths straddling each algorithm’s internal block/rate size (e.g. block−1, block, block+1, and multi-block messages) - the exact places where length-encoding and padding bugs hide.
  • Streaming equals one-shot. Chunked/streamed input and the incremental Sink API (including reset(), double-close(), and use-after-close) are verified to produce identical digests to the one-shot path.
  • Argument validation. Invalid key, salt, digest, and parameter lengths are asserted to throw typed errors rather than silently producing weak output.

The algorithms compute exactly what their standards define, verified against official vectors and multiple independent implementations. Please still read the Security notes above: choose the right primitive for your threat model (a KDF for passwords, a cryptographic hash rather than a checksum where an adversary is involved), and note that pure-Dart execution makes no hard constant-time guarantee.

You can reproduce all of this locally:

Terminal window
dart test # vm, node, and chrome
dart test -p vm # fast, VM-only iteration

Short, focused snippets follow — one per task. Every algorithm listed in the tables above plugs into the same calls, and full runnable programs live in the example folder.

Turn any input into a fingerprint and read it in whatever format you need:

final digest = sha256.string('Happy Hashing!');
print(digest); // hex string (the default when printed)
print(digest.hex()); // "d8d0..." same value, explicit
print(digest.base64()); // Base64 encoding
digest.bytes; // raw bytes as a Uint8List
sha256.convert([1, 2, 3]); // hash a List<int> of bytes instead
sha256sum('Happy Hashing!'); // shortcut straight to a hex String

Swap sha256 for any hash — md5, sha3_256, blake2b512, sm3, and the rest all share this exact API.

Feed data in chunks instead of loading everything into memory. The result is identical to hashing it all at once:

final sink = sha256.createSink();
sink.add(firstChunk); // each chunk is a List<int>
sink.add(nextChunk);
final digest = sink.digest();

Hash the password with a slow KDF and a fresh random salt, then store only the encoded result. To check a login, verify against that string — nothing is ever decrypted:

import 'package:hashlib/hashlib.dart';
import 'package:hashlib/random.dart'; // for randomBytes
// Sign-up: hash and store.
final salt = randomBytes(16);
final stored = argon2id(password.codeUnits, salt).encoded();
// stored => "$argon2id$v=19$m=65536,t=3,p=4$..." safe to save in your database
// Login: check the password against the stored hash.
final ok = argon2Verify(stored, password.codeUnits); // true / false

bcrypt works the same way and generates its own salt:

final stored = bcrypt(password.codeUnits);
final ok = bcryptVerify(stored, password.codeUnits);

Both accept a security: preset (test, little, moderate, good, strong) that trades speed for resistance to guessing — pick the strongest your latency budget allows, e.g. argon2id(password.codeUnits, salt, security: Argon2Security.moderate).

A MAC proves a message was not tampered with by anyone who does not know the shared key. Attach .hmac to any hash:

final tag = sha256.hmac.byString('shared-secret-key').string('transfer 100 coins');
// The receiver recomputes the tag and compares it in constant time:
final valid = tag.isEqual(receivedTag);

Compare tags with isEqual() (constant-time), never with == on the hex string — a plain comparison can leak the answer through timing.

Cheap integrity checks against bit-rot and transfer errors — not attackers:

crc32code('Happy Hashing!'); // => 3003384410 (an int)
adler32code('Happy Hashing!'); // another fast, non-secure checksum
final secret = 'my-shared-secret'.codeUnits;
TOTP(secret).value(); // 6-digit code, rotates every 30 seconds
HOTP(secret, counter: counter).value(); // counter-based code (counter is bytes)
import 'package:hashlib/codecs.dart'; // for toHex
import 'package:hashlib/random.dart';
randomBytes(16); // 16 cryptographically-secure bytes (great for a salt)
toHex(randomBytes(16)); // the same, as a hex string
randomString(32); // a random text token
uuid.v4(); // a random UUID (v1/v3/v5/v6/v7/v8 also available)