Skip to main content

post_quantum_crypto 2.3.0 copy "post_quantum_crypto: ^2.3.0" to clipboard
post_quantum_crypto: ^2.3.0 copied to clipboard

Pure Dart post-quantum cryptography: ML-KEM envelopes and streaming encryption, ML-DSA and SLH-DSA signatures, X-Wing hybrid key exchange, Argon2id key protection.

post_quantum_crypto #

pub package Null Safety Dart CI codecov GitHub Tag Last Commits License

High-level post-quantum cryptography for Dart and Flutter, in pure Dart:

  • Encryption: ML-KEM-768 (FIPS 203) envelopes, with key wrapping by HPKE (RFC 9180) and AES-256-GCM, for one or many recipients, one-shot or streaming (bounded memory, publish-after-verify file decryption).
  • Signatures: ML-DSA-65 (FIPS 204), optional SLH-DSA (FIPS 205), detached signatures, signed artifacts and signed manifests.
  • Hybrid: X-Wing (ML-KEM-768 + X25519) recipients and key establishment.
  • Secure streams and channels: protected messages over any byte stream (files, sockets, pipes), and an authenticated two-way channel with forward secrecy, including over TCP.
  • Keys: seed-form keys, fingerprints, lifecycle metadata, SPKI/PKCS#8 (OpenSSL-compatible), Argon2id-protected exports, key stores, rotation.
  • Policies: allowed algorithms, minimum security category, hybrid-only, size limits, expiry/revocation/usage enforcement.

Runs on the Dart VM, Flutter (mobile/desktop), JavaScript and WebAssembly with no native libraries.

⚠️ No independent security review has been performed yet. Algorithms are checked against official test vectors and against OpenSSL, but that is not a design audit. Read doc/SECURITY.md before relying on this package.

API Documentation #

See the API Documentation for the full list of classes and APIs.

Runnable examples (dart run example/<name>.dart):

  • post_quantum_crypto_example.dart: quick tour (encryption, signatures, trust, PEM, X-Wing key establishment).
  • sharing_and_releases.dart: sharing with a changing group (add/remove recipients), authenticated context, password-based encryption, streaming with progress, signed release manifests and signed artifacts.
  • key_management.dart: key metadata, rotation, revocation, security policies, encrypted backup and restore, PEM export.
  • file_encryption.dart: streaming file encryption, a file-backed key store and password-protected key export.
  • secure_stream.dart: an append-style encrypted file to a recipient's key, truncation detection, and a live pipe with a shared key.
  • secure_socket.dart: an echo server over TCP with server and client authentication.

Installation #

dart pub add post_quantum_crypto
import 'package:post_quantum_crypto/post_quantum_crypto.dart';
// File helpers (VM / Flutter native only):
import 'package:post_quantum_crypto/post_quantum_crypto_io.dart';

Quick start #

final engine = PostQuantumCryptoEngine();

// Encryption keys (ML-KEM-768 by default).
final recipient = engine.generateEncryptionKeyPair();

final envelope = engine.encrypt(
  utf8.encode('hello, post-quantum world'),
  recipients: [recipient.publicKey],
);
final bytes = envelope.toBytes(); // store or send

final plaintext = engine.decryptBytes(bytes, privateKey: recipient.privateKey);

// Signatures (ML-DSA-65 by default).
final signer = engine.generateSigningKeyPair();
final signature = engine.sign(plaintext, privateKey: signer.privateKey);
final ok = engine.verify(
  plaintext,
  signature: signature,
  publicKey: signer.publicKey,
);

PostQuantumCrypto.encrypt(...), PostQuantumCrypto.sign(...) etc. are static shortcuts to a default engine.

All operations are synchronous and CPU-bound (microseconds to milliseconds; Argon2id up to seconds). In a Flutter UI isolate, wrap heavy calls in runInBackground, which uses Isolate.run on native platforms and runs inline on the web, where there are no isolates:

final keys = await runInBackground(engine.generateSigningKeyPair);

Encryption #

Authenticated context #

Bind an envelope to where it is meant to be used. The context is authenticated but not encrypted and is not proof of who encrypted it.

final env = engine.encrypt(
  data,
  recipients: [recipient.publicKey],
  context: {'tenant': 'acme', 'record': 'invoice-42'},
);

engine.decrypt(
  env,
  privateKey: recipient.privateKey,
  requiredContext: {'tenant': 'acme', 'record': 'invoice-42'},
); // ContextMismatchException if moved to another record

Multiple recipients #

The payload is encrypted once; every recipient gets its own encapsulation and wrapped key. Recipient entries are authenticated, and duplicates are rejected.

final env = engine.encrypt(
  data,
  recipients: [alice.publicKey, bob.publicKey, hybridCarol.publicKey],
);

// Re-encrypt for a new recipient set (fresh data key):
final updated = engine.addRecipients(
  env,
  privateKey: alice.privateKey,
  currentRecipients: [alice.publicKey, bob.publicKey, hybridCarol.publicKey],
  newRecipients: [dave.publicKey],
);

Removing a recipient produces a new envelope; it cannot revoke what that recipient already decrypted or copied.

Streams and files #

// Streams: bounded memory (about two chunks).
final encrypted = engine.encryptStream(
  File('big.iso').openRead(),
  recipients: [recipient.publicKey],
  chunkSize: 64 * 1024,
  onProgress: (bytes) => print(bytes),
  cancel: token,
);

// Files: decryptFile writes to a temporary file and renames it into place only
// after the final chunk is authenticated.
await engine.encryptFile('in.bin', 'in.bin.qc', recipients: [recipient.publicKey]);
await engine.decryptFile('in.bin.qc', 'out.bin', privateKey: recipient.privateKey);

Streams detect tampering, reordering, duplication, truncation and appended data. decryptStream emits each chunk once it authenticates, so treat output as unverified until the stream completes without error.

Algorithm choice #

engine.generateEncryptionKeyPair(algorithm: KemAlgorithm.mlKem1024);
engine.generateEncryptionKeyPair(algorithm: KemAlgorithm.xWing); // hybrid
engine.encrypt(data, recipients: [...], aead: AeadAlgorithm.chacha20Poly1305);

Signatures #

// Standard FIPS 204 signature with a context string (interoperable).
final sig = engine.sign(msg, privateKey: sk, context: utf8.encode('app/v1'));

// Detached signature over content + metadata (also streams/files).
final detached = engine.signDetached(
  content,
  privateKey: sk,
  metadata: {'name': 'app.tar.gz'},
);
final verified = engine.verifyDetached(
  content,
  signature: detached,
  publicKey: pk,
);

// Signed manifest of many files.
final manifest = engine.createSignedManifest([
  await engine.manifestEntryForFile(dir, 'bin/app'),
  await engine.manifestEntryForFile(dir, 'README.md'),
], privateKey: sk);
await engine.verifyManifestFiles(manifest, dir, publicKey: pk);

Verification is not trust. A valid signature shows that the holder of that key signed the bytes. Decide separately whether that key is a trusted, current signer:

// Expiry is judged by the engine's policy clock.
final trust = engine.createTrustStore([releaseKey]);
final key = trust.lookup(detached.signerKeyId);
if (key == null) throw 'unknown signer';
final v = engine.verifyDetached(content, signature: detached, publicKey: key);
assert(trust.evaluate(v) == TrustDecision.trusted);

SLH-DSA (SignatureAlgorithm.slhDsaShake128f, etc.) is available for hash-based signatures; the s sets sign slowly in pure Dart.

Hybrid key establishment (X-Wing) #

final server = engine.generateEncryptionKeyPair(algorithm: KemAlgorithm.xWing);
const t = HybridTranscript(
  protocol: 'myapp/sync/v1',
  initiatorId: 'client-7',
  responderId: 'server-1',
);

final init = engine.establishHybridKey(server.publicKey, transcript: t);
// send init.message ...
final key = engine.acceptHybridKey(
  init.message,
  privateKey: server.privateKey,
  transcript: t,
);
// key == init.sessionKey

The key stays secret if either ML-KEM-768 or X25519 is unbroken. Non-hybrid KEMs are rejected, which prevents downgrades. This is not TLS and not authenticated: obtain the responder's public key through a trusted channel.

For an authenticated connection, use a PQSecureChannel (below), which builds on this.

Secure streams and channels #

Three layers, each built on the one before. All are package-specific protocols, not TLS.

PQSecureStream: one direction of protected messages over any byte stream: a file, a socket, a pipe, a queue.

  • Messages are numbered AEAD records. They keep their boundaries and are written as soon as they are added.
  • Within a stream, tampering, replayed or reordered records, dropped records and truncation are all detected: the stream ends with an authenticated End record.
  • A one-way stream replayed whole (the same file or recording delivered twice) still decrypts. If that matters, put a message id or timestamp in your messages and reject repeats, or use a PQSecureChannel, whose keys are fresh for each connection.
// To a recipient's ML-KEM or X-Wing key; no round trip needed.
final writer = PQSecureStream.encryptTo(
  File('audit.log.pqs').openWrite(),
  recipient: auditor.publicKey,
);
writer.add(utf8.encode('login alice'));
await writer.close(); // writes the End record

final reader = await PQSecureStream.decryptFrom(
  File('audit.log.pqs').openRead(),
  privateKey: auditor.privateKey,
);
await for (final message in reader.messages) { /* ... */ }
// A file cut short throws PQSecureStreamException('... truncated').

encryptWithKey / decryptWithKey key a stream from a key both ends already share. Every stream gets a random salt, so the key can be reused.

PQSecureChannel: an authenticated, two-way channel over any byte stream.

  • The server signs a fresh X-Wing key, generated for each connection, with its identity key, which the client has pinned. This gives server authentication and forward secrecy, secure while either ML-KEM-768 or X25519 holds.
  • The server can require clients to authenticate with their own keys. The key and its proof travel encrypted; the clientId label is sent in the clear.
  • Each direction is a PQSecureStream.

PQSecureServer / PQSecureSocket (post_quantum_crypto_io): the channel over TCP.

Simple PQSecureSocket example #

An echo server and a client in one program:

import 'dart:convert';
import 'dart:io';

import 'package:post_quantum_crypto/post_quantum_crypto_io.dart';

Future<void> main() async {
  final engine = PostQuantumCryptoEngine();

  // The server's long-term identity; clients pin its public key.
  final identity = engine.generateSigningKeyPair();

  // Server: echo every message back.
  final server = await PQSecureServer.bind(
    InternetAddress.loopbackIPv4,
    4433,
    identity: identity,
    serverId: 'echo.example',
  );
  server.channels.listen((channel) async {
    try {
      await for (final message in channel.messages) {
        channel.send(message);
      }
      await channel.close();
    } on PQSecureStreamException {
      await channel.abort(); // a misbehaving client must not stop the server
    }
  });

  // Client: the handshake fails unless the server proves the pinned key.
  final channel = await PQSecureSocket.connect(
    InternetAddress.loopbackIPv4,
    4433,
    serverKey: identity.publicKey,
    serverId: 'echo.example',
  );
  channel.send(utf8.encode('hello, post-quantum world'));
  print(utf8.decode((await channel.receive())!)); // hello, post-quantum world

  await channel.close();
  await channel.receive(); // null: the server has closed its side too
  await server.close();
}

In a real deployment, the client gets the server's public key through a trusted channel: shipped with the app, or a pinned PEM. It never trusts a key the connection itself supplies.

To also authenticate clients, give the server an authorizeClient callback, and give each client its own SigningKeyPair:

final server = await PQSecureServer.bind(
  InternetAddress.anyIPv4, 4433,
  identity: identity,
  serverId: 'echo.example',
  authorizeClient: (clientKey, clientId) => allowedClients.contains(clientKey),
);

final channel = await PQSecureSocket.connect(
  'echo.example', 4433,
  serverKey: pinnedServerKey,
  serverId: 'echo.example',
  clientId: 'alice',
  clientIdentity: aliceKeyPair, // proves alice's key to the server
);

example/secure_socket.dart shows both, including refused connections.

PQSecureChannel.connect / accept run the same handshake over any Stream<List<int>> and StreamSink<List<int>>, for example a WebSocket. close() is a half-close. Where closing the sink ends both directions (a WebSocket), read until receive() returns null before closing.

PQSecureServer drops a client that does not send each handshake message within stepTimeout (10 s), whether it stalls before or after its ClientHello. It caps idle connections (maxIdleConnections) and handshakes in progress (maxPendingHandshakes) separately, so idle or stalled sockets cannot crowd out real clients for long.

Keys #

// Raw standard encodings and seeds.
final pk = engine.importEncryptionPublicKey(bytes);
final sk = engine.importEncryptionPrivateKeySeed(seed64);

// X.509 SPKI / PKCS#8 (seed, expanded or both): compatible with OpenSSL 3.5+
// and byte-identical to the RFC 9881 / RFC 9935 examples.
final pem = engine.exportPublicKeyPem(signer.publicKey);
final priv = engine.importPrivateKeyPem(File('key.pem').readAsStringSync());

// Package key record (keeps metadata: created, expires, usages, label, ...).
final record = engine.encodeKey(recipient.publicKey);
final again = engine.decodeEncryptionPublicKey(record);

// Fingerprint for display.
print(recipient.keyId.fingerprint); // e.g. f29b:f240:bb26:...

Imported private keys are checked before use. A seed is expanded and compared with any expanded key or public key that comes with it. An expanded key without its seed is checked for internal consistency:

  • ML-KEM: the FIPS 203 hash check, plus a pairwise-consistency test (an encapsulation must decapsulate).
  • ML-DSA: the public key is recomputed (FIPS 204 t = A·s1 + s2), which rejects out-of-range or inconsistent keys. An expanded-only ML-DSA key therefore imports on its own, without its public key.
  • SLH-DSA: PK.root is recomputed from SK.seed and PK.seed (FIPS 205 Algorithm 18). That costs a key generation: milliseconds for the "f" parameter sets, 1–2 s for the "s" sets, on every import and key-store load. Loading a key record your application wrote itself can skip it: decodeKey, importPrivateKeyWithPassword and KeyStore.get take verifySlhDsaKey: false.

Keys that fail raise InvalidKeyException; nothing is left half-imported.

Password-protected keys #

Argon2id (default 64 MiB, 3 passes) with AES-256-GCM, a fresh salt and nonce each time, and parameter bounds checked before any memory is allocated:

final blob = engine.exportPrivateKeyWithPassword(sk, 'correct horse battery');
final restored = engine.importPrivateKeyWithPassword(blob, 'correct horse battery');
final rotated = engine.changeKeyPassword(
  blob,
  oldPassword: 'correct horse battery',
  newPassword: 'new passphrase',
);

encryptWithPassword and decryptWithPassword encrypt application data under a password. That is symmetric encryption, as strong as the password, and is not post-quantum public-key encryption.

Key store, rotation, backup #

final store = KeyStore(
  engine,
  FileKeyStorage(Directory('keys')), // or InMemoryKeyStorage, or your own
  password: 'store passphrase',      // encrypts private keys at rest
);
await store.putPair(keys);
final next = await store.rotateEncryptionKey(keys.keyId); // old key: decrypt-only
await store.revoke(oldSigningKeyId, reason: 'compromised');
final backup = await store.backup('backup passphrase');

Implement KeyStorage to use platform secure storage (Keychain, Android Keystore, DPAPI, a KMS). FileKeyStorage is not hardware-backed.

Security policies #

final engine = PostQuantumCryptoEngine(
  policy: SecurityPolicy(
    minimumSecurityCategory: 3,              // no ML-KEM-512 / ML-DSA-44
    requireHybridKem: true,                  // X-Wing only
    allowedAeads: {AeadAlgorithm.aes256Gcm},
    limits: ResourceLimits(maxEnvelopePayloadBytes: 16 << 20),
    password: PasswordPolicy(minMemoryKiB: 64 * 1024),
  ),
);

Prohibited algorithms are rejected before any expensive work. Expired, revoked or usage-restricted keys are refused by default.

Errors #

Every error is a PostQuantumCryptoException: InvalidInputException, MalformedDataException, UnsupportedAlgorithmException, UnsupportedFormatException, InvalidKeyException, DecryptionFailedException, SignatureVerificationException, SecureRandomUnavailableException, UnsupportedPlatformException, ResourceLimitExceededException, PolicyViolationException, KeyNotFoundException, ContextMismatchException, OperationCancelledException, PQSecureStreamException and its subclass PQSecureChannelException (handshake failures). For envelopes, streaming encryption and password containers, every authentication failure after parsing is the same DecryptionFailedException, so errors cannot be used as an oracle. Secure streams and channels report failures as PQSecureStreamException. Their messages name the cause ("Record failed authentication", "Stream is not for this key"), and any such failure ends the stream, so there is nothing to probe a second time. Messages never contain key material.

Two kinds of error pass through unchanged: I/O errors from the file APIs (encryptFile, decryptFile, signFile, FileKeyStorage, …) surface as FileSystemException, and an error raised by a caller-supplied input stream reaches the caller of encryptStream/decryptStream as is.

Architecture: swappable backends #

The library depends only on package-owned interfaces (KemPrimitive, SignaturePrimitive, AeadCipher, Kdf, HashFunction, X25519Primitive, Argon2idPrimitive, ...). The third-party libraries live in single adapter files under lib/src/providers/. The one exception is the ML-DSA private-key check, which validates key structure rather than perform a pluggable cryptographic operation and uses pqcrypto's SHAKE128 directly. The SLH-DSA check is part of the backend (SignaturePrimitive.publicKeyFromSecretKey).

Provider Library Primitives
PqcryptoProvider, PqcryptoKeccak pqcrypto ML-KEM, ML-DSA, SLH-DSA, SHA-3/SHAKE
CryptographyAesGcm, CryptographyChaCha20Poly1305, CryptographySha2, CryptographyX25519 cryptography AES-GCM, ChaCha20-Poly1305, SHA-2, X25519
PointyCastleSymmetricProvider pointycastle HMAC, HKDF, Argon2id (and alternative AES-GCM/SHA-2/ChaCha)

To swap a library, for example a native AES or a platform keystore, write a provider and build a CryptoBackend:

final engine = PostQuantumCryptoEngine(
  backend: standardCryptoBackend.copyWith(symmetric: MyNativeSymmetricProvider()),
);

The known-answer suite in test/vectors/ runs against the configured providers; a replacement should pass it unchanged. Its third-party vector files live in the repository and are not included in the published package.

Supported platforms #

Platform Status
Dart VM, Linux ✔ full suite (CI)
Dart VM, macOS / Windows ✔ platform-sensitive tests (CI): files, permissions, processes, isolates; the rest is pure Dart, identical on every OS
Flutter Android / iOS / desktop ✔ pure Dart, same code as the VM (not separately CI-tested)
Web, dart2js ✔ test/browser in Chrome (CI)
Web, dart2wasm ✔ test/browser in Chrome (CI)
post_quantum_crypto_io.dart (files, FileKeyStorage) VM / Flutter native only
runInBackground real isolate on native; inline on the web

Secure randomness is Random.secure() (OS CSPRNG on native, crypto.getRandomValues in browsers). If it is unavailable, operations fail with SecureRandomUnavailableException; there is no fallback.

Performance #

Pure Dart. On an Apple M-series machine (AOT): ML-KEM-768 envelope encrypt/decrypt about 0.9 ms; ML-DSA-65 sign 3.2 ms, verify 1.0 ms; AES-256-GCM about 20 MiB/s; streaming files at about 19 MiB/s, with memory bounded independent of file size. JavaScript and WebAssembly are 1–3× slower for the PQ operations, and Argon2id is much slower on the web. Full table: doc/BENCHMARKS.md.

Formats and interoperability #

  • doc/FORMATS.md specifies every binary format. All are versioned (PQCR + version + type), strictly parsed and bounded. The current format is version 2: envelopes, streams and password objects are key-committing, so every recipient decrypts the same plaintext (doc/FORMAT_V2.md). Objects from package 1.x (format 1) are not read.

  • Standard and interoperable: FIPS 203/204/205 raw keys and signatures, SPKI/PKCS#8 DER/PEM (tested against OpenSSL 3.6), and HPKE key wrapping (verified with draft-ietf-hpke-pq vectors).

  • Conformance tests:

    Standard Vectors
    FIPS 203 (ML-KEM) NIST ACVP; Wycheproof (incl. CCTV edge cases)
    FIPS 204 (ML-DSA) NIST ACVP; Wycheproof (sign, verify, invalid keys)
    FIPS 205 (SLH-DSA) NIST ACVP (keyGen, sigGen, sigVer)
    RFC 9935 / RFC 9881 (ML-KEM / ML-DSA keys in X.509) Appendix C example and inconsistent keys, byte for byte
    RFC 9180 + draft-ietf-hpke-pq (HPKE) hpke-pq vectors
    X-Wing (draft-connolly-cfrg-xwing-kem) draft vectors
    Symmetric (AES-GCM, ChaCha20-Poly1305, HKDF, HMAC, X25519, Argon2id) Wycheproof, RFC 7748, RFC 9106
  • Package-specific: envelope, stream, signed-object, key-record and password containers, and the secure stream and channel protocols.

  • Test vectors and their provenance are in test/vectors.

Security #

What is and isn't protected, assumptions and limitations (side channels, memory erasure, storage, review status): doc/SECURITY.md.

In short:

  • Confidentiality (encryption) is not authentication (who sent it). Signatures prove possession of a key; trust in that key is a separate decision.
  • Post-quantum algorithms do not protect against compromised endpoints, stolen keys, malicious applications or implementation side channels.
  • No constant-time guarantee is claimed on any Dart platform.
  • pqcrypto provides the post-quantum primitives used here.
  • pqforge is a different application layer over pqcrypto. Its formats are not compatible with this package's.

Author #

Graciliano M. Passos: gmpassos@GitHub.

License #

Apache License - Version 2.0

1
likes
160
points
1.3k
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Pure Dart post-quantum cryptography: ML-KEM envelopes and streaming encryption, ML-DSA and SLH-DSA signatures, X-Wing hybrid key exchange, Argon2id key protection.

Repository (GitHub)
View/report issues

Topics

#cryptography #post-quantum #encryption #signatures #security

License

Apache-2.0 (license)

Dependencies

cryptography, meta, pointycastle, pqcrypto

More

Packages that depend on post_quantum_crypto