anubis-age 1.4.0

Post-quantum secure encryption library with hybrid X25519+ML-KEM-1024 mode (internal dependency for anubis-rage)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
//! # Anubis Rage - Post-Quantum Secure File Encryption
//!
//! **Quantum-resistant file encryption using ML-KEM-1024 (NIST FIPS 203)**
//!
//! Anubis Rage is a modern, simple, and secure file encryption tool and library that implements
//! **post-quantum cryptography** to protect your files against both current and future threats,
//! including attacks from quantum computers.
//!
//! ## Table of Contents
//!
//! - [Quick Start](#quick-start)
//! - [What is Anubis Rage?](#what-is-anubis-rage)
//! - [Security Guarantees](#security-guarantees)
//! - [Installation](#installation)
//! - [Library Usage](#library-usage)
//! - [Command-Line Usage](#command-line-usage)
//! - [File Format](#file-format)
//! - [Cryptographic Stack](#cryptographic-stack)
//! - [Performance](#performance)
//! - [Examples](#examples)
//!
//! ## Quick Start
//!
//! ### Library Usage
//!
//! ```rust
//! use std::io::{Read, Write};
//!
//! # fn run_main() -> Result<(), Box<dyn std::error::Error>> {
//! // Generate Hybrid keypair (X25519 + ML-KEM-1024) - RECOMMENDED
//! let identity = age::pqc::hybrid::Identity::generate();
//! let recipient = identity.to_public();
//!
//! // Encrypt (uses both X25519 and ML-KEM-1024)
//! let plaintext = b"Secret message with defense-in-depth security!";
//! let encryptor = age::Encryptor::with_recipients(vec![&recipient as _])?;
//! let mut ciphertext = vec![];
//! let mut writer = encryptor.wrap_output(&mut ciphertext)?;
//! writer.write_all(plaintext)?;
//! writer.finish()?;
//!
//! // Decrypt (both X25519 and ML-KEM-1024 must succeed)
//! let decryptor = age::Decryptor::new(&ciphertext[..])?;
//! let mut decrypted = vec![];
//! let mut reader = decryptor.decrypt(vec![&identity as _])?;
//! reader.read_to_end(&mut decrypted)?;
//!
//! assert_eq!(decrypted, plaintext);
//! # Ok(())
//! # }
//! # run_main().unwrap();
//! ```
//!
//! ### CLI Tool
//!
//! ```bash
//! # Install
//! cargo install anubis-rage
//!
//! # Generate a key
//! anubis-rage-keygen -o key.txt
//!
//! # Encrypt a file
//! anubis-rage -r $(grep -o 'anubis1[^"]*' key.txt) -o secret.txt.anubis secret.txt
//!
//! # Decrypt a file
//! anubis-rage -d -i key.txt -o decrypted.txt secret.txt.anubis
//! ```
//!
//! ## What is Anubis Rage?
//!
//! Anubis Rage is a **post-quantum secure** file encryption tool based on **ML-KEM-1024**
//! (Module-Lattice-Based Key-Encapsulation Mechanism), standardized as **NIST FIPS 203**.
//!
//! ### Key Features
//!
//! - ✅ **Post-Quantum Security**: NIST Category 5 (maximum security level)
//! - ✅ **Simple & Modern**: Small explicit keys, no config files, UNIX-style composability
//! - ✅ **Streaming Encryption**: Handles files of any size with constant memory usage
//! - ✅ **Authenticated Encryption**: AES-256-GCM-SIV or ChaCha20-Poly1305 AEAD
//! - ✅ **Forward Secrecy**: Ephemeral key encapsulation per recipient
//! - ✅ **Standards Compliant**: NIST FIPS 203, FIPS 198-1, SP 800-56C
//!
//! ### Why Post-Quantum Cryptography?
//!
//! Quantum computers (when built at sufficient scale) will break current public-key cryptography:
//!
//! - **Shor's Algorithm**: Breaks RSA, ECDSA, ECDH in polynomial time
//! - **Grover's Algorithm**: Halves symmetric key security (256-bit → 128-bit effective)
//!
//! Anubis Rage uses **lattice-based cryptography** (ML-KEM-1024) which resists both classical
//! and quantum attacks, ensuring your encrypted files remain secure for decades to come.
//!
//! ## Security Guarantees
//!
//! ### Cryptographic Security
//!
//! | Property | Status |
//! |----------|--------|
//! | **Confidentiality** | ✅ IND-CCA2 secure (ML-KEM-1024) |
//! | **Integrity** | ✅ Authenticated encryption (AEAD) |
//! | **Forward Secrecy** | ✅ Ephemeral key wrapping |
//! | **Post-Quantum** | ✅ NIST Category 5 (256-bit quantum security) |
//! | **Classical Security** | ✅ 256-bit equivalent (AES-256) |
//!
//! ### NIST Category 5 Security Level
//!
//! Anubis Rage achieves **NIST Category 5** - the highest security classification:
//!
//! - **Classical Attack Cost**: 2^256 operations (equivalent to AES-256)
//! - **Quantum Attack Cost**: > 2^170 quantum gates (exceeds NIST requirement)
//! - **Public Key Size**: 2592 bytes
//! - **Secret Key Size**: 4736 bytes
//! - **Ciphertext Overhead**: 1568 bytes + 64-byte SHA-512 MAC
//!
//! ## Installation
//!
//! ### As a Library
//!
//! Add to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! anubis-rage = "1.0"
//! ```
//!
//! ### As a CLI Tool
//!
//! ```bash
//! cargo install anubis-rage
//! ```
//!
//! This installs three binaries:
//! - **`anubis-rage`**: Encryption/decryption tool
//! - **`anubis-rage-keygen`**: Key generation utility
//! - **`anubis-rage-sign`**: Digital signature tool (ML-DSA-87)
//!
//! ## Library Usage
//!
//! ### Basic Encryption/Decryption
//!
//! ```rust
//! use anubis_rage::{pqc::mlkem, Encryptor, Decryptor};
//! use std::io::{Read, Write};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Generate keypair
//! let identity = mlkem::Identity::generate();
//! let recipient = identity.to_public();
//!
//! // Encrypt data
//! let plaintext = b"Top secret quantum-safe data";
//! let encryptor = Encryptor::with_recipients(vec![&recipient as _])?;
//! let mut ciphertext = vec![];
//! let mut writer = encryptor.wrap_output(&mut ciphertext)?;
//! writer.write_all(plaintext)?;
//! writer.finish()?;
//!
//! // Decrypt data
//! let decryptor = Decryptor::new(&ciphertext[..])?;
//! let mut decrypted = vec![];
//! let mut reader = decryptor.decrypt(vec![&identity as _])?;
//! reader.read_to_end(&mut decrypted)?;
//!
//! assert_eq!(decrypted, plaintext);
//! # Ok(())
//! # }
//! ```
//!
//! ### Multi-Recipient Encryption
//!
//! ```rust,no_run
//! use anubis_rage::{pqc::mlkem, Encryptor};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Generate keys for multiple recipients
//! let alice = mlkem::Identity::generate();
//! let bob = mlkem::Identity::generate();
//! let carol = mlkem::Identity::generate();
//!
//! let recipients = vec![
//!     &alice.to_public() as &dyn anubis_rage::Recipient,
//!     &bob.to_public() as &dyn anubis_rage::Recipient,
//!     &carol.to_public() as &dyn anubis_rage::Recipient,
//! ];
//!
//! // Encrypt to all recipients (any can decrypt)
//! let encryptor = Encryptor::with_recipients(recipients)?;
//! // ... encrypt data ...
//! # Ok(())
//! # }
//! ```
//!
//! ### Async I/O Support
//!
//! ```rust,no_run
//! use anubis_rage::{pqc::mlkem, Encryptor};
//! use futures::io::AsyncWriteExt;
//!
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let identity = mlkem::Identity::generate();
//! let recipient = identity.to_public();
//!
//! let encryptor = Encryptor::with_recipients(vec![&recipient as _])?;
//! let mut encrypted = vec![];
//! let mut writer = encryptor.wrap_async_output(&mut encrypted).await?;
//! writer.write_all(b"Async quantum-safe encryption!").await?;
//! writer.close().await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Command-Line Usage
//!
//! ### Key Generation
//!
//! ```bash
//! # Generate new ML-KEM-1024 keypair
//! anubis-rage-keygen -o identity.txt
//! chmod 600 identity.txt
//!
//! # Extract public key
//! grep "public key:" identity.txt
//! ```
//!
//! ### Encryption
//!
//! ```bash
//! # Encrypt to a recipient
//! anubis-rage -r RECIPIENT_PUBLIC_KEY -o file.anubis file.txt
//!
//! # Encrypt to multiple recipients
//! anubis-rage -r alice.pub -r bob.pub -o file.anubis file.txt
//!
//! # Encrypt with ASCII armor
//! anubis-rage -r RECIPIENT --armor -o file.anubis file.txt
//!
//! # Pipe encryption
//! cat file.txt | anubis-rage -r RECIPIENT > file.anubis
//! ```
//!
//! ### Decryption
//!
//! ```bash
//! # Decrypt with identity file
//! anubis-rage -d -i identity.txt -o output.txt file.anubis
//!
//! # Pipe decryption
//! cat file.anubis | anubis-rage -d -i identity.txt > output.txt
//! ```
//!
//! ## File Format
//!
//! Anubis Rage uses the `anubis-encryption.org/v1` file format:
//!
//! ```text
//! anubis-encryption.org/v1
//! -> MLKEM-1024
//! [2144-char base64: ML-KEM-1024 encapsulated key (1568 bytes)]
//! [76-char base64: wrapped file key with ChaCha20-Poly1305 (44 bytes)]
//! --- [86-char base64: SHA-512 HMAC header MAC (64 bytes)]
//! [encrypted payload with AES-256-GCM-SIV or ChaCha20-Poly1305]
//! ```
//!
//! ### Size Overhead
//!
//! - **Fixed header**: ~2.4 KB
//! - **Per recipient**: ~2.1 KB
//! - **Total**: ~2.4 KB + (num_recipients × 2.1 KB)
//!
//! For files >100 KB, overhead is <2%. For files >1 MB, overhead is <0.2%.
//!
//! ## Cryptographic Stack
//!
//! Anubis Rage uses **NIST Category 5** (maximum strength) cryptography throughout:
//!
//! | Component | Algorithm | Security Level | Standard |
//! |-----------|-----------|----------------|----------|
//! | **Key Encapsulation** | ML-KEM-1024 | Cat. 5 (256-bit) | NIST FIPS 203 |
//! | **Key Derivation** | HKDF-SHA512 | 256-bit | SP 800-56C Rev. 2 |
//! | **Message Auth** | HMAC-SHA512 | 256-bit | FIPS 198-1 |
//! | **AEAD (Default)** | AES-256-GCM-SIV | 256-bit | RFC 8452 |
//! | **AEAD (Alt)** | ChaCha20-Poly1305 | 256-bit | RFC 8439 |
//! | **Random Generation** | OS CSPRNG | System | `/dev/urandom` |
//!
//! ### Key Derivation Process
//!
//! ```text
//! 1. ML-KEM-1024.Encapsulate(recipient_pk) → (ciphertext, shared_secret)
//! 2. wrap_key = HKDF-SHA512-Expand(
//!      HKDF-SHA512-Extract(
//!        salt: recipient_pk || ciphertext,
//!        IKM: shared_secret
//!      ),
//!      info: "anubis-encryption.org/v1/MLKEM-1024",
//!      L: 32 bytes
//!    )
//! 3. encrypted_file_key = ChaCha20-Poly1305.Encrypt(wrap_key, file_key)
//! 4. payload = AES-256-GCM-SIV.Encrypt(file_key, plaintext)
//! ```
//!
//! ## Performance
//!
//! Benchmarks on Apple M1 with 2.0 GB video file:
//!
//! | Operation | Throughput | Time |
//! |-----------|------------|------|
//! | **Encryption** | ~187 MB/s | 10.97s |
//! | **Decryption** | ~159 MB/s | 12.89s |
//! | **Key Generation** | N/A | ~2ms |
//!
//! ### Cryptographic Operation Timing
//!
//! - **ML-KEM-1024 KeyGen**: ~2ms
//! - **ML-KEM-1024 Encapsulate**: ~0.5ms
//! - **ML-KEM-1024 Decapsulate**: ~0.6ms
//! - **HKDF-SHA512 Derive**: <0.1ms
//! - **File Encryption**: I/O-bound (~170 MB/s)
//!
//! ### Memory Usage
//!
//! - **Encryption**: ~64 KB constant (streaming)
//! - **Decryption**: ~64 KB constant (streaming)
//! - **Key Storage**: ~5 KB per identity
//!
//! Files of any size can be encrypted with constant memory usage.
//!
//! ## Examples
//!
//! ### File Encryption
//!
//! ```rust,no_run
//! use anubis_rage::{pqc::mlkem, Encryptor};
//! use std::fs::File;
//! use std::io::{copy, Write};
//!
//! fn encrypt_file(
//!     input_path: &str,
//!     output_path: &str,
//!     recipient: &mlkem::Recipient
//! ) -> Result<(), Box<dyn std::error::Error>> {
//!     let encryptor = Encryptor::with_recipients(vec![recipient as _])?;
//!
//!     let mut input = File::open(input_path)?;
//!     let output = File::create(output_path)?;
//!     let mut writer = encryptor.wrap_output(output)?;
//!
//!     copy(&mut input, &mut writer)?;
//!     writer.finish()?;
//!
//!     Ok(())
//! }
//! ```
//!
//! ### Streaming Large Files
//!
//! ```rust,no_run
//! use anubis_rage::{pqc::mlkem, Encryptor, Decryptor};
//! use std::io::{Read, Write, copy};
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let identity = mlkem::Identity::generate();
//! let recipient = identity.to_public();
//!
//! // Encrypt a large file with constant memory
//! let encryptor = Encryptor::with_recipients(vec![&recipient as _])?;
//! let input = std::fs::File::open("large-file.bin")?;
//! let output = std::fs::File::create("large-file.bin.anubis")?;
//! let mut writer = encryptor.wrap_output(output)?;
//! std::io::copy(&mut input.take(u64::MAX), &mut writer)?;
//! writer.finish()?;
//!
//! // Decrypt with constant memory
//! let encrypted = std::fs::File::open("large-file.bin.anubis")?;
//! let decryptor = Decryptor::new(encrypted)?;
//! let mut reader = decryptor.decrypt(vec![&identity as _])?;
//! let mut output = std::fs::File::create("large-file-decrypted.bin")?;
//! std::io::copy(&mut reader, &mut output)?;
//! # Ok(())
//! # }
//! ```
//!
//! ### Identity File Management
//!
//! ```rust,no_run
//! use anubis_rage::{IdentityFile, pqc::mlkem};
//! use std::fs::File;
//! use std::io::Write;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Generate and save identity
//! let identity = mlkem::Identity::generate();
//! let recipient = identity.to_public();
//!
//! let identity_file = format!(
//!     "# Anubis Rage ML-KEM-1024 identity\n\
//!      # public key: {}\n\
//!      {}",
//!     recipient.to_string(),
//!     identity.to_string()
//! );
//!
//! let mut file = File::create("identity.txt")?;
//! file.write_all(identity_file.as_bytes())?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Module Organization
//!
//! - [`pqc`]: Post-quantum cryptography (ML-KEM-1024, ML-DSA-87)
//! - [`Encryptor`]: Encryption API
//! - [`Decryptor`]: Decryption API
//! - [`armor`]: ASCII armoring support
//! - [`stream`]: Low-level streaming encryption primitives
//! - [`fips`]: FIPS 140-3 compliance and self-tests
//!
//! ## Platform Support
//!
//! Anubis Rage runs on all platforms supported by Rust and liboqs:
//!
//! - ✅ Linux (x86_64, aarch64)
//! - ✅ macOS (Intel, Apple Silicon)
//! - ✅ Windows (x86_64)
//! - ✅ BSD (FreeBSD, OpenBSD, NetBSD)
//! - ✅ Android / iOS (via FFI)
//!
//! ## Standards Compliance
//!
//! - **NIST FIPS 203**: ML-KEM (Module-Lattice-Based KEM)
//! - **NIST FIPS 204**: ML-DSA (Module-Lattice-Based Digital Signature Algorithm)
//! - **NIST FIPS 198-1**: HMAC (Keyed-Hash Message Authentication Code)
//! - **NIST SP 800-56C Rev. 2**: Key Derivation (HKDF)
//! - **RFC 8452**: AES-GCM-SIV (Authenticated Encryption)
//! - **RFC 8439**: ChaCha20-Poly1305 (Authenticated Encryption)
//! - **RFC 4648**: Base64 Encoding
//!
//! ## License
//!
//! Licensed under either of:
//!
//! - Apache License, Version 2.0 ([LICENSE-APACHE](../LICENSE-APACHE))
//! - MIT License ([LICENSE-MIT](../LICENSE-MIT))
//!
//! at your option.
//!
//! ## Contributing
//!
//! Contributions are welcome! Please see [CONTRIBUTING.md](../CONTRIBUTING.md).
//!
//! For security issues, see [SECURITY.md](../SECURITY.md) or email security@anubis-rage.org.
//!

#![cfg_attr(docsrs, feature(doc_cfg))]
#![forbid(unsafe_code)]
// Catch documentation errors caused by code changes.
#![deny(rustdoc::broken_intra_doc_links)]
#![deny(missing_docs)]

use std::collections::HashSet;

// Re-export crates that are used in our public API.
pub use anubis_core::secrecy;

mod error;
mod format;
mod identity;
mod keys;
mod primitives;
mod protocol;
mod util;

pub use error::{DecryptError, EncryptError, IdentityFileConvertError};
pub use identity::IdentityFile;
pub use primitives::stream;
pub use protocol::{Decryptor, Encryptor};

#[cfg(feature = "armor")]
#[cfg_attr(docsrs, doc(cfg(feature = "armor")))]
pub use primitives::armor;

#[cfg(feature = "cli-common")]
#[cfg_attr(docsrs, doc(cfg(feature = "cli-common")))]
pub mod cli_common;

mod i18n;
pub use i18n::localizer;

//
// Simple interface
//

mod simple;
pub use simple::{decrypt, encrypt};

#[cfg(feature = "armor")]
#[cfg_attr(docsrs, doc(cfg(feature = "armor")))]
pub use simple::encrypt_and_armor;

//
// Identity types
//

/// Post-quantum cryptography (PQC) using ML-KEM (formerly Kyber).
///
/// This module provides Level-5 post-quantum secure encryption using ML-KEM-1024.
#[cfg(feature = "pqc-mlkem")]
#[cfg_attr(docsrs, doc(cfg(feature = "pqc-mlkem")))]
pub mod pqc;

/// FIPS 140-3 compliance module
///
/// This module implements:
/// - Module integrity verification
/// - Power-up self-tests (POST)
/// - Conditional self-tests
///
/// Required for FIPS 140-3 Level 1 certification.
pub mod fips;

//
// Core traits
//

use anubis_core::{
    format::{FileKey, Stanza},
    secrecy::SecretString,
};

/// A private key or other value that can unwrap an opaque file key from a recipient
/// stanza.
///
/// # Implementation notes
///
/// The canonical entry point for this trait is [`Identity::unwrap_stanzas`]. The default
/// implementation of that method is:
/// ```ignore
/// stanzas.iter().find_map(|stanza| self.unwrap_stanza(stanza))
/// ```
///
/// The `age` crate otherwise does not call [`Identity::unwrap_stanza`] directly. As such,
/// if you want to add file-level stanza checks, override [`Identity::unwrap_stanzas`].
pub trait Identity {
    /// Attempts to unwrap the given stanza with this identity.
    ///
    /// This method is part of the `Identity` trait to expose age's [one joint] for
    /// external implementations. You should not need to call this directly; instead, pass
    /// identities to [`Decryptor::decrypt`].
    ///
    /// The `age` crate only calls this method via [`Identity::unwrap_stanzas`].
    ///
    /// Returns:
    /// - `Some(Ok(file_key))` on success.
    /// - `Some(Err(e))` if a decryption error occurs.
    /// - `None` if the recipient stanza does not match this key.
    ///
    /// [one joint]: https://www.imperialviolet.org/2016/05/16/agility.html
    fn unwrap_stanza(&self, stanza: &Stanza) -> Option<Result<FileKey, DecryptError>>;

    /// Attempts to unwrap any of the given stanzas, which are assumed to come from the
    /// same age file header, and therefore contain the same file key.
    ///
    /// This method is part of the `Identity` trait to expose age's [one joint] for
    /// external implementations. You should not need to call this directly; instead, pass
    /// identities to [`Decryptor::decrypt`].
    ///
    /// Returns:
    /// - `Some(Ok(file_key))` on success.
    /// - `Some(Err(e))` if a decryption error occurs.
    /// - `None` if none of the recipient stanzas match this identity.
    ///
    /// [one joint]: https://www.imperialviolet.org/2016/05/16/agility.html
    fn unwrap_stanzas(&self, stanzas: &[Stanza]) -> Option<Result<FileKey, DecryptError>> {
        stanzas.iter().find_map(|stanza| self.unwrap_stanza(stanza))
    }
}

/// A public key or other value that can wrap an opaque file key to a recipient stanza.
///
/// Implementations of this trait might represent more than one recipient.
pub trait Recipient {
    /// Wraps the given file key, returning stanzas to be placed in an age file header,
    /// and labels that constrain how the stanzas may be combined with those from other
    /// recipients.
    ///
    /// Implementations may return more than one stanza per "actual recipient", e.g. to
    /// support multiple formats, to build group aliases, or to act as a proxy.
    ///
    /// This method is part of the `Recipient` trait to expose age's [one joint] for
    /// external implementations. You should not need to call this directly; instead, pass
    /// recipients to [`Encryptor::with_recipients`].
    ///
    /// [one joint]: https://www.imperialviolet.org/2016/05/16/agility.html
    ///
    /// # Labels
    ///
    /// [`Encryptor`] will succeed at encrypting only if every recipient returns the same
    /// set of labels. Subsets or partial overlapping sets are not allowed; all sets must
    /// be identical. Labels are compared exactly, and are case-sensitive.
    ///
    /// Label sets can be used to ensure a recipient is only encrypted to alongside other
    /// recipients with equivalent properties, or to ensure a recipient is always used
    /// alone. A recipient with no particular properties to enforce should return an empty
    /// label set.
    ///
    /// Labels can have any value that is a valid arbitrary string (`1*VCHAR` in ABNF),
    /// but usually take one of several forms:
    ///   - *Common public label* - used by multiple recipients to permit their stanzas to
    ///     be used only together. Examples include:
    ///     - `postquantum` - indicates that the recipient stanzas being generated are
    ///       postquantum-secure, and that they can only be combined with other stanzas
    ///       that are also postquantum-secure.
    ///   - *Common private label* - used by recipients created by the same private entity
    ///     to permit their recipient stanzas to be used only together. For example,
    ///     private recipients used in a corporate environment could all send the same
    ///     private label in order to prevent compliant age clients from simultaneously
    ///     wrapping file keys with other recipients.
    ///   - *Random label* - used by recipients that want to ensure their stanzas are not
    ///     used with any other recipient stanzas. This can be used to produce a file key
    ///     that is only encrypted to a single recipient stanza, for example to preserve
    ///     its authentication properties.
    fn wrap_file_key(
        &self,
        file_key: &FileKey,
    ) -> Result<(Vec<Stanza>, HashSet<String>), EncryptError>;
}

/// Callbacks that might be triggered during encryption or decryption.
///
/// Structs that implement this trait should be given directly to the individual
/// `Recipient` or `Identity` implementations that require them.
pub trait Callbacks: Clone + Send + Sync + 'static {
    /// Shows a message to the user.
    ///
    /// This can be used to prompt the user to take some physical action, such as
    /// inserting a hardware key.
    ///
    /// No guarantee is provided that the user sees this message (for example, if there is
    /// no UI for displaying messages).
    fn display_message(&self, message: &str);

    /// Requests that the user provides confirmation for some action.
    ///
    /// This can be used to, for example, request that a hardware key the plugin wants to
    /// try either be plugged in, or skipped.
    ///
    /// - `message` is the request or call-to-action to be displayed to the user.
    /// - `yes_string` and (optionally) `no_string` will be displayed on buttons or next
    ///   to selection options in the user's UI.
    ///
    /// Returns:
    /// - `Some(true)` if the user selected the option marked with `yes_string`.
    /// - `Some(false)` if the user selected the option marked with `no_string` (or the
    ///   default negative confirmation label).
    /// - `None` if the confirmation request could not be given to the user (for example,
    ///   if there is no UI for displaying messages).
    fn confirm(&self, message: &str, yes_string: &str, no_string: Option<&str>) -> Option<bool>;

    /// Requests non-private input from the user.
    ///
    /// To request private inputs, use [`Callbacks::request_passphrase`].
    ///
    /// Returns:
    /// - `Some(input)` with the user-provided input.
    /// - `None` if no input could be requested from the user (for example, if there is no
    ///   UI for displaying messages or typing inputs).
    fn request_public_string(&self, description: &str) -> Option<String>;

    /// Requests a passphrase to decrypt a key.
    ///
    /// Returns:
    /// - `Some(passphrase)` with the user-provided passphrase.
    /// - `None` if no passphrase could be requested from the user (for example, if there
    ///   is no UI for displaying messages or typing inputs).
    fn request_passphrase(&self, description: &str) -> Option<SecretString>;
}

/// An implementation of [`Callbacks`] that does not allow callbacks.
///
/// No user interaction will occur; [`Recipient`] or [`Identity`] implementations will
/// receive `None` from the callbacks that return responses, and will act accordingly.
#[derive(Clone, Copy, Debug)]
pub struct NoCallbacks;

impl Callbacks for NoCallbacks {
    fn display_message(&self, _: &str) {}

    fn confirm(&self, _: &str, _: &str, _: Option<&str>) -> Option<bool> {
        None
    }

    fn request_public_string(&self, _: &str) -> Option<String> {
        None
    }

    fn request_passphrase(&self, _: &str) -> Option<SecretString> {
        None
    }
}

//
// Fuzzing APIs
//

/// Helper for fuzzing the Header parser and serializer.
#[cfg(fuzzing)]
pub fn fuzz_header(data: &[u8]) {
    if let Ok(header) = format::Header::read(data) {
        let mut buf = Vec::with_capacity(data.len());
        header.write(&mut buf).expect("can write header");
        assert_eq!(&buf[..], &data[..buf.len()]);
    }
}