Cryptography

suggest change

Dart's core libraries don't include cryptographic algorithms beyond a secure random number generator (Random.secure() in dart:math). For everything else you use packages:

Add both to pubspec.yaml:

dependencies:
  crypto: ^3.0.7
  cryptography: ^2.9.0

Most examples print bytes as hex or Base64. See Base64 and hex encoding for details on those encodings.

Hashing with package:crypto

A cryptographic hash turns any amount of data into a fixed-size digest. The same input always gives the same digest, and it's infeasible to find a different input with the same digest. Hash functions work on bytes, so encode strings with utf8.encode() first:

import 'dart:convert';
import 'package:crypto/crypto.dart';

void main() {
  final bytes = utf8.encode('hello');

  print('md5:    ${md5.convert(bytes)}');
  print('sha1:   ${sha1.convert(bytes)}');
  print('sha256: ${sha256.convert(bytes)}');

  final digest = sha512.convert(bytes);
  print('sha512 has ${digest.bytes.length} bytes');
}

Output:

md5:    5d41402abc4b2a76b9719d911017c592
sha1:   aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d
sha256: 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
sha512 has 64 bytes

convert() returns a Digest. Its toString() gives lowercase hex and its bytes property gives the raw bytes. The package exports md5, sha1, sha224, sha256, sha384, sha512, sha512224 and sha512256 as constants.

Which hash to pick:

Hashing large data and files

You don't need the whole input in memory. Hash is a Converter, so bind() hashes a stream of byte chunks. This hashes a file of any size with constant memory:

import 'dart:io';
import 'package:crypto/crypto.dart';

Future<Digest> hashFile(String path) {
  return sha256.bind(File(path).openRead()).first;
}

Future<void> main(List<String> args) async {
  final digest = await hashFile(args.first);
  print('${digest}  ${args.first}');
}

The output has the same format as the sha256sum command, so you can compare results directly.

When data arrives in pieces from somewhere other than a stream, use chunked conversion. AccumulatorSink from the convert package collects the result:

import 'dart:convert';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';

void main() {
  final output = AccumulatorSink<Digest>();
  final input = sha256.startChunkedConversion(output);

  input.add(utf8.encode('hello'));
  input.add(utf8.encode(' '));
  input.add(utf8.encode('world'));
  input.close();

  final digest = output.events.single;
  print(digest);
  print(digest == sha256.convert(utf8.encode('hello world'))); // true
}

Output:

b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
true

HMAC: verifying who sent a message

A plain hash proves nothing about the sender, because anyone can compute it. An HMAC mixes a secret key into the hash, so only parties that know the key can produce or verify it. HMACs are used for webhook signatures, signed cookies, API request signing and JWTs with the HS256 algorithm.

import 'dart:convert';
import 'package:crypto/crypto.dart';

void main() {
  final key = utf8.encode('secret-key');
  final message = utf8.encode('hello');

  final hmac = Hmac(sha256, key);
  final mac = hmac.convert(message);

  print(mac); // hex
  print(base64Url.encode(mac.bytes).replaceAll('=', '')); // URL-safe Base64
}

Output:

98e7ffb964bb5a3f902db1fc101a5baa98b6f2cd56858210c9d70f26ac762fc7
mOf_uWS7Wj-QLbH8EBpbqpi28s1WhYIQydcPJqx2L8c

An Hmac object can be reused for many messages, and it supports bind() and startChunkedConversion() just like the hash constants.

Verifying a webhook signature

Services such as GitHub and Stripe sign each webhook request with an HMAC of the raw body, and send the result in a header. To verify it, compute the HMAC yourself and compare.

The comparison must take the same time no matter where the first difference is. A normal == on strings stops at the first mismatching character, which lets an attacker guess a valid signature byte by byte by measuring response times. Digest.operator== in package:crypto is constant-time, so compare Digest objects rather than hex strings:

import 'dart:convert';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';

/// Checks a GitHub-style "X-Hub-Signature-256: sha256=<hex>" header.
bool verifySignature(List<int> rawBody, String header, String secret) {
  const prefix = 'sha256=';
  if (!header.startsWith(prefix)) return false;

  final List<int> received;
  try {
    received = hex.decode(header.substring(prefix.length));
  } on FormatException {
    return false;
  }

  final expected = Hmac(sha256, utf8.encode(secret)).convert(rawBody);
  return expected == Digest(received); // constant-time comparison
}

void main() {
  const secret = 'webhook-secret';
  final body = utf8.encode('{"action":"opened"}');
  final good = 'sha256=${Hmac(sha256, utf8.encode(secret)).convert(body)}';

  print(verifySignature(body, good, secret)); // true
  print(verifySignature(body, 'sha256=${'0' * 64}', secret)); // false
  print(verifySignature(utf8.encode('{}'), good, secret)); // false
}

Always hash the raw request bytes. If you decode the JSON and encode it again, whitespace and key order may change and the signature won't match.

If you need to compare raw byte lists outside of Digest, write the loop yourself:

bool constantTimeEquals(List<int> a, List<int> b) {
  if (a.length != b.length) return false;
  var diff = 0;
  for (var i = 0; i < a.length; i++) {
    diff |= a[i] ^ b[i];
  }
  return diff == 0;
}

Generating keys, salts and tokens

Keys, salts, nonces and session tokens must come from a cryptographically secure generator. In Dart that's Random.secure(), which reads from the operating system's CSPRNG. Never use the default Random() for these, because its output is predictable.

import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';

final _rng = Random.secure();

Uint8List randomBytes(int length) {
  final bytes = Uint8List(length);
  for (var i = 0; i < length; i++) {
    bytes[i] = _rng.nextInt(256);
  }
  return bytes;
}

/// A URL-safe token with [byteLength] bytes of entropy.
String randomToken([int byteLength = 32]) =>
    base64Url.encode(randomBytes(byteLength)).replaceAll('=', '');

void main() {
  print(randomToken()); // e.g. 0vT3bq1x6zJ0bXzK9oQ2_4fQe8l3m1kYcJ7nW5sV2aE
  print(randomBytes(16).length); // 16
}

32 random bytes (256 bits) is plenty for API keys and session IDs. See Random numbers for more on Random.secure().

The cryptography package has a shortcut for keys: SecretKeyData.random(length: 32), and every cipher has newSecretKey() which returns a key of the right size.

Authenticated encryption with AES-GCM

To keep data secret, use an authenticated cipher such as AES-GCM or ChaCha20-Poly1305. Besides encrypting, they compute a MAC over the ciphertext, so any modification is detected during decryption. Avoid unauthenticated modes like AES-CBC or AES-CTR unless an existing format requires them.

Encryption takes the plaintext, a secret key and a nonce (a value that must never repeat for the same key). The result is a SecretBox holding the nonce, the ciphertext and the MAC:

import 'dart:convert';
import 'package:cryptography/cryptography.dart';

Future<void> main() async {
  final algorithm = AesGcm.with256bits();
  final secretKey = await algorithm.newSecretKey();

  final secretBox = await algorithm.encrypt(
    utf8.encode('Meet me at noon'),
    secretKey: secretKey,
  ); // a random 12-byte nonce is generated for you

  print('nonce:      ${secretBox.nonce.length} bytes');
  print('ciphertext: ${secretBox.cipherText.length} bytes');
  print('mac:        ${secretBox.mac.bytes.length} bytes');

  final clearText = await algorithm.decrypt(secretBox, secretKey: secretKey);
  print(utf8.decode(clearText));
}

Output:

nonce:      12 bytes
ciphertext: 15 bytes
mac:        16 bytes
Meet me at noon

GCM doesn't pad, so the ciphertext has the same length as the plaintext. Let the library generate nonces: with random 12-byte nonces you can safely encrypt billions of messages under one key. Reusing a nonce with the same key in GCM breaks both confidentiality and authentication.

encryptString() and decryptString() are shortcuts that do the UTF-8 conversion for you.

Storing and sending encrypted data

To store or transmit a SecretBox, join its parts with concatenation(), which produces nonce + ciphertext + mac. SecretBox.fromConcatenation() splits them again:

import 'dart:convert';
import 'package:cryptography/cryptography.dart';

final algorithm = AesGcm.with256bits();

Future<String> encryptToBase64(String text, SecretKey key) async {
  final box = await algorithm.encryptString(text, secretKey: key);
  return base64.encode(box.concatenation());
}

Future<String> decryptFromBase64(String encoded, SecretKey key) {
  final box = SecretBox.fromConcatenation(
    base64.decode(encoded),
    nonceLength: algorithm.nonceLength, // 12
    macLength: algorithm.macAlgorithm.macLength, // 16
  );
  return algorithm.decryptString(box, secretKey: key);
}

Future<void> main() async {
  final key = await algorithm.newSecretKey();

  final encoded = await encryptToBase64('card: 4111 1111 1111 1111', key);
  print(encoded.length); // 72: (12 + 25 + 16) bytes as Base64
  print(await decryptFromBase64(encoded, key));
}

Encrypting the same text twice gives different output each time, because the nonce is random.

To save a key, call await key.extractBytes() and store the 32 bytes somewhere safe, such as a secrets manager or an environment variable (Base64-encoded). Recreate it with SecretKey(bytes).

Detecting tampering

If the ciphertext, nonce or MAC is changed, or the wrong key is used, decrypt() throws SecretBoxAuthenticationError instead of returning garbage:

import 'package:cryptography/cryptography.dart';

Future<void> main() async {
  final algorithm = AesGcm.with256bits();
  final key = await algorithm.newSecretKey();
  final box = await algorithm.encryptString('transfer \$10', secretKey: key);

  // Flip one bit of the ciphertext.
  final tampered = SecretBox(
    [...box.cipherText]..[0] ^= 1,
    nonce: box.nonce,
    mac: box.mac,
  );

  try {
    await algorithm.decryptString(tampered, secretKey: key);
  } on SecretBoxAuthenticationError {
    print('message was modified');
  }

  try {
    await algorithm.decryptString(box, secretKey: await algorithm.newSecretKey());
  } on SecretBoxAuthenticationError {
    print('wrong key');
  }
}

Output:

message was modified
wrong key

Associated data

Sometimes data must stay readable but still be protected from modification, for example a user ID or a record version stored next to the ciphertext. Pass it as aad (additional authenticated data). It isn't encrypted or stored in the SecretBox, but decryption fails unless the exact same aad is supplied:

final aad = utf8.encode('user:42');
final box = await algorithm.encrypt(data, secretKey: key, aad: aad);
// ...
final clear = await algorithm.decrypt(box, secretKey: key, aad: aad);

This prevents an attacker from copying an encrypted field from one user's record into another's.

ChaCha20-Poly1305

Chacha20.poly1305Aead() is used the same way as AesGcm. It's fast on CPUs without AES hardware instructions and is what TLS uses on many mobile devices. Xchacha20.poly1305Aead() uses 24-byte nonces, so random nonces are safe even for an enormous number of messages:

final algorithm = Xchacha20.poly1305Aead();
final key = await algorithm.newSecretKey();
final box = await algorithm.encryptString('hello', secretKey: key);
print(box.nonce.length); // 24

Password hashing with Argon2id

Passwords must be stored with a deliberately slow, memory-hard function, so that an attacker who steals the database can test only a few guesses per second per CPU core. Argon2id is the current recommendation. Always use a unique random salt per password, and store the salt and parameters together with the hash.

This example stores hashes in the standard PHC string format used by other Argon2 libraries, so hashes stay portable between languages:

import 'dart:convert';
import 'dart:math';
import 'package:cryptography/cryptography.dart';

// OWASP minimum: 19 MiB of memory, 2 iterations, 1 degree of parallelism.
const _memoryKiB = 19456;
const _iterations = 2;
const _parallelism = 1;

String _b64(List<int> bytes) => base64.encode(bytes).replaceAll('=', '');
List<int> _unb64(String s) => base64.decode(base64.normalize(s));

Future<List<int>> _argon2(String password, List<int> salt,
    {required int m, required int t, required int p}) async {
  final algorithm =
      Argon2id(memory: m, iterations: t, parallelism: p, hashLength: 32);
  final key =
      await algorithm.deriveKeyFromPassword(password: password, nonce: salt);
  return key.extractBytes();
}

Future<String> hashPassword(String password) async {
  final rng = Random.secure();
  final salt = List<int>.generate(16, (_) => rng.nextInt(256));
  final hash = await _argon2(password, salt,
      m: _memoryKiB, t: _iterations, p: _parallelism);
  return '\$argon2id\$v=19\$m=$_memoryKiB,t=$_iterations,p=$_parallelism'
      '\$${_b64(salt)}\$${_b64(hash)}';
}

Future<bool> verifyPassword(String password, String stored) async {
  final parts = stored.split('\$'); // ['', 'argon2id', 'v=19', 'm=..', salt, hash]
  if (parts.length != 6 || parts[1] != 'argon2id') return false;
  final params = {
    for (final kv in parts[3].split(','))
      kv.split('=')[0]: int.parse(kv.split('=')[1]),
  };
  final expected = _unb64(parts[5]);
  final actual = await _argon2(password, _unb64(parts[4]),
      m: params['m']!, t: params['t']!, p: params['p']!);
  return Mac(actual) == Mac(expected); // constant-time comparison
}

Future<void> main() async {
  final stored = await hashPassword('correct horse battery staple');
  print(stored);
  print(await verifyPassword('correct horse battery staple', stored)); // true
  print(await verifyPassword('Tr0ub4dor&3', stored)); // false
}

Output (salt and hash differ on every run):

$argon2id$v=19$m=19456,t=2,p=1$pYp8yW4H2dKqQq1+o0b5Ig$Cq2bYV1o9cX0p0r3lE1Q2c7oV9yHnU0yJ3m6m3o1dZQ
true
false

Notes:

If you need PBKDF2 for compatibility (for example with existing hashes or FIPS requirements), use Pbkdf2.hmacSha256(iterations: 600000, bits: 256) with the same deriveKeyFromPassword() call. OWASP recommends at least 600,000 iterations for PBKDF2-HMAC-SHA256.

Encrypting with a password

The same key derivation turns a user's password into an encryption key. Store the salt next to the ciphertext so the key can be derived again when decrypting:

import 'dart:convert';
import 'dart:math';
import 'package:cryptography/cryptography.dart';

final _kdf =
    Argon2id(memory: 19456, iterations: 2, parallelism: 1, hashLength: 32);
final _cipher = AesGcm.with256bits();

Future<String> encryptWithPassword(String text, String password) async {
  final rng = Random.secure();
  final salt = List<int>.generate(16, (_) => rng.nextInt(256));
  final key = await _kdf.deriveKeyFromPassword(password: password, nonce: salt);
  final box = await _cipher.encryptString(text, secretKey: key);
  return base64.encode([...salt, ...box.concatenation()]);
}

Future<String> decryptWithPassword(String encoded, String password) async {
  final bytes = base64.decode(encoded);
  final salt = bytes.sublist(0, 16);
  final key = await _kdf.deriveKeyFromPassword(password: password, nonce: salt);
  final box = SecretBox.fromConcatenation(bytes.sublist(16),
      nonceLength: 12, macLength: 16);
  return _cipher.decryptString(box, secretKey: key); // throws on wrong password
}

Future<void> main() async {
  final encoded = await encryptWithPassword('my diary', 'pa55word');
  print(await decryptWithPassword(encoded, 'pa55word')); // my diary

  try {
    await decryptWithPassword(encoded, 'guess');
  } on SecretBoxAuthenticationError {
    print('wrong password');
  }
}

Deriving several keys with HKDF

When you have one strong secret (a master key or the result of a key exchange) and need separate keys for different purposes, use HKDF. Different info values produce independent keys, so compromising one doesn't reveal the others:

import 'dart:convert';
import 'package:convert/convert.dart';
import 'package:cryptography/cryptography.dart';

Future<void> main() async {
  final hkdf = Hkdf(hmac: Hmac.sha256(), outputLength: 32);
  final master = SecretKey(utf8.encode('master secret'));

  for (final purpose in ['encryption', 'authentication']) {
    final key = await hkdf.deriveKey(
      secretKey: master,
      nonce: utf8.encode('salt'),
      info: utf8.encode(purpose),
    );
    print('$purpose: ${hex.encode(await key.extractBytes())}');
  }
}

Output:

encryption: 220abf6eba12038cafab5f8c5df4b9862de89bd87f8820d603b489f02b4c1608
authentication: 12e8ccfb84ba54579e64960e0f2b01c439bea4e692506cce1f954ab3795e1837

HKDF is not a password hash. It's fast, so only use it on inputs that are already high-entropy.

Digital signatures with Ed25519

A signature lets anyone verify that a message was created by the holder of a private key, without being able to create signatures themselves. Typical uses are signing software updates, license files and tokens. Ed25519 is fast, has small keys (32 bytes) and signatures (64 bytes), and has no parameters to get wrong:

import 'dart:convert';
import 'package:cryptography/cryptography.dart';

Future<void> main() async {
  final algorithm = Ed25519();
  final keyPair = await algorithm.newKeyPair();

  final message = utf8.encode('license: pro, expires 2027-01-01');
  final signature = await algorithm.sign(message, keyPair: keyPair);
  print('signature: ${signature.bytes.length} bytes');

  // The verifier only needs the public key bytes.
  final publicKey = await keyPair.extractPublicKey();
  final publicBytes = publicKey.bytes; // 32 bytes, safe to publish

  final received = Signature(
    signature.bytes,
    publicKey: SimplePublicKey(publicBytes, type: KeyPairType.ed25519),
  );

  print(await algorithm.verify(message, signature: received)); // true
  print(await algorithm.verify(
    utf8.encode('license: pro, expires 2099-01-01'),
    signature: received,
  )); // false
}

Output:

signature: 64 bytes
true
false

To persist the private key, save the 32-byte seed from await keyPair.extractPrivateKeyBytes() and restore it with await Ed25519().newKeyPairFromSeed(seed). Ed25519 signatures are deterministic: signing the same message with the same key always gives the same signature.

Key exchange with X25519

X25519 lets two parties agree on a shared secret over an insecure channel. Each side generates a key pair and sends only its public key. Combining your private key with the other side's public key gives both sides the same secret:

import 'package:cryptography/cryptography.dart';

Future<void> main() async {
  final x25519 = X25519();

  final alice = await x25519.newKeyPair();
  final bob = await x25519.newKeyPair();

  // Public keys are exchanged over the network.
  final alicePublic = await alice.extractPublicKey();
  final bobPublic = await bob.extractPublicKey();

  final aliceShared = await x25519.sharedSecretKey(
      keyPair: alice, remotePublicKey: bobPublic);
  final bobShared = await x25519.sharedSecretKey(
      keyPair: bob, remotePublicKey: alicePublic);

  final a = await aliceShared.extractBytes();
  final b = await bobShared.extractBytes();
  print(a.length); // 32
  print(Mac(a) == Mac(b)); // true
}

Don't use the shared secret directly as an encryption key. Pass it through HKDF (as shown above) to derive the actual AES or ChaCha20 keys. Key exchange alone doesn't authenticate anyone, so in a real protocol the public keys must also be signed or verified out of band.

RSA, ECDSA and certificates

On the Dart VM, package:cryptography has no pure Dart implementation of RSA, ECDSA (Ecdsa.p256) or ECDH with NIST curves; these only work in browsers and with cryptography_flutter on mobile. If you need them on a server or in a CLI tool (for example to verify RS256 JWTs), use pointycastle, or a higher-level package built on it such as dart_jsonwebtoken (see JWT).

For TLS connections and certificates, use dart:io's SecureSocket and SecurityContext, which use the platform's TLS implementation. See TLS and HTTPS.

Rules of thumb

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents