Orientação gerada a partir de informações públicas. Apenas para referência.
Hashlib é um pacote Dart que fornece funções de hash seguras, geradores de checksum e algoritmos de derivação de chaves otimizados para desempenho e segurança. Ele suporta vários padrões criptográficos de hashing, como SHA-256, SHA-3 e BLAKE3, tornando-o adequado para verificação de integridade de dados, hash de senhas e geração de tokens seguros. Projetado para uso em múltiplas plataformas, funciona sem problemas em Android, iOS, Web, macOS, Windows e Linux. O pacote enfatiza segurança e eficiência, sendo ideal para aplicações que exigem operações criptográficas robustas sem dependências externas.
Casos de uso
Verificação de integridade de dados
Hash de senha
Geração segura de token
Derivação de chave criptográfica
Validação de soma de verificação de arquivo
Principais recursos
Suporta SHA-256, SHA-3 e BLAKE3
Compatibilidade multiplataforma
Otimizado para desempenho
Seguro por design
API simples para tarefas comuns de hash
Indicado para
Aplicações focadas em segurança
Sistemas de autenticação
Ferramentas de blockchain e cripto
Verificação de arquivos e dados
Criptografia de backend e frontend é necessária
Considerações
Garanta o uso adequado de sal na derivação de chaves
Evite usar hashes fracos para dados sensíveis
Revisar melhores práticas criptográficas
Teste em todas as plataformas-alvo
Monitore atualizações para manter a segurança
README original
Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.
hashlib
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.
hashlib is the middle layer of a three-package family:
→ →
It builds on convertlib for hex, Base32/Base64, and UTF-8 conversion, and
that is its only runtime dependency.
Highlights
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).
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: consistently outruns crypto, PointyCastle, and hash, see the
benchmarks below.
Codecs and secure random built in: companion codecs and random
libraries ship in the same package.
Install
dependencies:hashlib:^2.4.2
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:
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
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.
Quickstart
import'package:hashlib/hashlib.dart';
voidmain() {
// 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.
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.
Security notes
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.
Testing and reliability
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:
dart test# vm, node, and chrome
dart test -p vm # fast, VM-only iteration
Usage
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.
Hash text or bytes
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, explicitprint(digest.base64()); // Base64 encoding
digest.bytes; // raw bytes as a Uint8List
sha256.convert([1, 2, 3]); // hash a List<int> of bytes insteadsha256sum('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.
Hash a large file or stream
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();
Store and verify a password
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).
Authenticate a message with a key (HMAC)
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.
Fast checksum for accidental corruption
Cheap integrity checks against bit-rot and transfer errors — not attackers:
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)
Secure random values and UUIDs
import'package:hashlib/codecs.dart'; // for toHeximport'package:hashlib/random.dart';
randomBytes(16); // 16 cryptographically-secure bytes (great for a salt)toHex(randomBytes(16)); // the same, as a hex stringrandomString(32); // a random text token
uuid.v4(); // a random UUID (v1/v3/v5/v6/v7/v8 also available)