Hashlib은 성능과 보안을 최적화한 안전한 해시 함수, 체크섬 생성기 및 키 유도 알고리즘을 제공하는 Dart 패키지입니다. SHA-256, SHA-3, BLAKE3 등의 다양한 암호 해시 표준을 지원하여 데이터 무결성 검증, 비밀번호 해시, 안전한 토큰 생성에 적합합니다. 크로스플랫폼 사용을 위해 설계되어 Android, iOS, Web, macOS, Windows, Linux에서 원활하게 작동합니다. 외부 종속성이 없이 강력한 암호 연산이 필요한 애플리케이션에 이상적입니다.
사용 사례
데이터 무결성 검사
비밀번호 해싱
보안 토큰 생성
암호학적 키 파생
파일 체크섬 검증
주요 기능
SHA-256, SHA-3 및 BLAKE3 지원
크로스 플랫폼 호환성
성능 최적화
디자인을 통한 보안
일반적인 해싱 작업을 위한 간단한 API
적합한 대상
보안 중심 애플리케이션
인증 시스템
블록체인 및 암호 도구
파일 및 데이터 검증
백엔드 및 프론트엔드 암호화 필요
고려 사항
키 유도에서 적절한 솔트 사용을 보장하십시오
민감한 데이터에 약한 해시를 사용하지 마십시오
암호화 최선의 실천 방안 검토
모든 대상 플랫폼에서 테스트하기
보안을 유지하기 위해 업데이트를 모니터링하세요
원본 README
연결된 소스 저장소의 README 원문 스냅샷입니다. 최신 내용은 저장소에서 확인하세요.
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)