pqfile 4.2.1

Quantum-resistant file encryption: ML-KEM (512/768/1024), hybrid X25519+ML-KEM-768, ML-DSA-65 signing, multi-recipient, Shamir sharing
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
use aes_gcm::{
    aead::{Aead, KeyInit},
    Aes256Gcm, Key, Nonce,
};
use argon2::{Argon2, Params};
use zeroize::Zeroizing;

use crate::error::PqfileError;

// Current Argon2id parameters (pqfile >= 4.0): m=64 MiB, t=3, p=4.
//
// p=4 (four lanes) forces each brute-force attempt to occupy 4× the memory
// bandwidth compared to p=1, hampering parallel GPU attacks. OWASP 2023
// recommends p=4 for the same m/t values.
const ARGON2_M_COST: u32 = 65536; // 64 MiB
const ARGON2_T_COST: u32 = 3;
const ARGON2_P_COST: u32 = 4;

// Legacy Argon2id p-cost (pqfile < 4.0). Used only to detect and migrate old keys.
const ARGON2_P_COST_LEGACY: u32 = 1;

const SALT_LEN: usize = 16;
const NONCE_LEN: usize = 12;
const SEED_LEN: usize = 64;
const HYBRID_SEED_LEN: usize = 96;

// Layout of the encrypted private key PEM body (108 bytes total):
//   0..16   salt
//   16..28  AES-GCM nonce
//   28..108 AES-256-GCM ciphertext (64-byte seed + 16-byte tag)
/// Byte length of an encrypted ML-KEM private key PEM body (108 bytes: salt + nonce + ciphertext).
pub const ENCRYPTED_BODY_LEN: usize = SALT_LEN + NONCE_LEN + SEED_LEN + 16;

// Layout of the encrypted hybrid private key PEM body (140 bytes total):
//   0..16   salt
//   16..28  AES-GCM nonce
//   28..140 AES-256-GCM ciphertext (96-byte hybrid seed + 16-byte tag)
/// Byte length of an encrypted hybrid X25519+ML-KEM-768 private key PEM body (140 bytes).
pub const ENCRYPTED_HYBRID_BODY_LEN: usize = SALT_LEN + NONCE_LEN + HYBRID_SEED_LEN + 16;

/// Encrypts a 64-byte ML-KEM seed under `passphrase`. Returns the 108-byte
/// payload that is stored as the PEM body of an encrypted private key.
pub fn encrypt_seed(seed: &[u8; SEED_LEN], passphrase: &str) -> Result<Vec<u8>, PqfileError> {
    let mut salt = [0u8; SALT_LEN];
    getrandom::fill(&mut salt).map_err(|_| PqfileError::EncryptionFailure)?;

    let key = derive_key(passphrase, &salt)?;
    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key.as_ref()));

    let mut nonce_bytes = [0u8; NONCE_LEN];
    getrandom::fill(&mut nonce_bytes).map_err(|_| PqfileError::EncryptionFailure)?;
    let nonce = Nonce::from_slice(&nonce_bytes);

    let ciphertext = cipher
        .encrypt(nonce, seed.as_slice())
        .map_err(|_| PqfileError::EncryptionFailure)?;

    let mut out = Vec::with_capacity(ENCRYPTED_BODY_LEN);
    out.extend_from_slice(&salt);
    out.extend_from_slice(&nonce_bytes);
    out.extend_from_slice(&ciphertext);
    Ok(out)
}

/// Decrypts the 108-byte payload from an encrypted private key PEM body using
/// current (p=4) Argon2id parameters.
///
/// Returns `LegacyKeyFormat` if the body decrypts correctly only with the old
/// p=1 parameters (pqfile < 4.0 key). Use `pqfile repassphrase --from-legacy`
/// to upgrade such keys before use.
pub fn decrypt_seed(
    body: &[u8],
    passphrase: &str,
) -> Result<Zeroizing<[u8; SEED_LEN]>, PqfileError> {
    if body.len() != ENCRYPTED_BODY_LEN {
        return Err(PqfileError::InvalidKeyLength {
            expected: ENCRYPTED_BODY_LEN,
            got: body.len(),
        });
    }
    // Try current params first.
    if let Ok(seed) = try_decrypt_seed(body, passphrase, ARGON2_P_COST) {
        return Ok(seed);
    }
    // If p=1 succeeds, the key is valid but needs migration.
    if try_decrypt_seed(body, passphrase, ARGON2_P_COST_LEGACY).is_ok() {
        return Err(PqfileError::LegacyKeyFormat);
    }
    Err(PqfileError::WrongPassphrase)
}

/// Decrypts a 108-byte body using the legacy p=1 Argon2id parameters.
/// Only called by the `repassphrase --from-legacy` migration path.
pub(crate) fn decrypt_seed_legacy(
    body: &[u8],
    passphrase: &str,
) -> Result<Zeroizing<[u8; SEED_LEN]>, PqfileError> {
    if body.len() != ENCRYPTED_BODY_LEN {
        return Err(PqfileError::InvalidKeyLength {
            expected: ENCRYPTED_BODY_LEN,
            got: body.len(),
        });
    }
    try_decrypt_seed(body, passphrase, ARGON2_P_COST_LEGACY)
        .map_err(|_| PqfileError::WrongPassphrase)
}

fn try_decrypt_seed(
    body: &[u8],
    passphrase: &str,
    p_cost: u32,
) -> Result<Zeroizing<[u8; SEED_LEN]>, PqfileError> {
    let salt = &body[..SALT_LEN];
    let nonce_bytes = &body[SALT_LEN..SALT_LEN + NONCE_LEN];
    let ciphertext = &body[SALT_LEN + NONCE_LEN..];

    let key = derive_key_with_pcost(passphrase, salt, p_cost)?;
    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key.as_ref()));
    let nonce = Nonce::from_slice(nonce_bytes);

    let plaintext = Zeroizing::new(
        cipher
            .decrypt(nonce, ciphertext)
            .map_err(|_| PqfileError::WrongPassphrase)?,
    );

    if plaintext.len() != SEED_LEN {
        return Err(PqfileError::WrongPassphrase);
    }

    let mut seed = Zeroizing::new([0u8; SEED_LEN]);
    seed.copy_from_slice(&plaintext);
    Ok(seed)
}

/// Encrypts a 96-byte hybrid seed (X25519 scalar || ML-KEM seed) under `passphrase`.
pub fn encrypt_hybrid_seed(
    seed: &[u8; HYBRID_SEED_LEN],
    passphrase: &str,
) -> Result<Vec<u8>, PqfileError> {
    let mut salt = [0u8; SALT_LEN];
    getrandom::fill(&mut salt).map_err(|_| PqfileError::EncryptionFailure)?;

    let key = derive_key(passphrase, &salt)?;
    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key.as_ref()));

    let mut nonce_bytes = [0u8; NONCE_LEN];
    getrandom::fill(&mut nonce_bytes).map_err(|_| PqfileError::EncryptionFailure)?;
    let nonce = Nonce::from_slice(&nonce_bytes);

    let ciphertext = cipher
        .encrypt(nonce, seed.as_slice())
        .map_err(|_| PqfileError::EncryptionFailure)?;

    let mut out = Vec::with_capacity(ENCRYPTED_HYBRID_BODY_LEN);
    out.extend_from_slice(&salt);
    out.extend_from_slice(&nonce_bytes);
    out.extend_from_slice(&ciphertext);
    Ok(out)
}

/// Decrypts the 140-byte payload from an encrypted hybrid private key PEM body.
///
/// Returns `LegacyKeyFormat` if the body was encrypted with legacy p=1 parameters.
pub fn decrypt_hybrid_seed(
    body: &[u8],
    passphrase: &str,
) -> Result<Zeroizing<[u8; HYBRID_SEED_LEN]>, PqfileError> {
    if body.len() != ENCRYPTED_HYBRID_BODY_LEN {
        return Err(PqfileError::InvalidKeyLength {
            expected: ENCRYPTED_HYBRID_BODY_LEN,
            got: body.len(),
        });
    }
    if let Ok(seed) = try_decrypt_hybrid_seed(body, passphrase, ARGON2_P_COST) {
        return Ok(seed);
    }
    if try_decrypt_hybrid_seed(body, passphrase, ARGON2_P_COST_LEGACY).is_ok() {
        return Err(PqfileError::LegacyKeyFormat);
    }
    Err(PqfileError::WrongPassphrase)
}

/// Decrypts a 140-byte hybrid body using legacy p=1 parameters.
/// Only called by the `repassphrase --from-legacy` migration path.
pub(crate) fn decrypt_hybrid_seed_legacy(
    body: &[u8],
    passphrase: &str,
) -> Result<Zeroizing<[u8; HYBRID_SEED_LEN]>, PqfileError> {
    if body.len() != ENCRYPTED_HYBRID_BODY_LEN {
        return Err(PqfileError::InvalidKeyLength {
            expected: ENCRYPTED_HYBRID_BODY_LEN,
            got: body.len(),
        });
    }
    try_decrypt_hybrid_seed(body, passphrase, ARGON2_P_COST_LEGACY)
        .map_err(|_| PqfileError::WrongPassphrase)
}

fn try_decrypt_hybrid_seed(
    body: &[u8],
    passphrase: &str,
    p_cost: u32,
) -> Result<Zeroizing<[u8; HYBRID_SEED_LEN]>, PqfileError> {
    let salt = &body[..SALT_LEN];
    let nonce_bytes = &body[SALT_LEN..SALT_LEN + NONCE_LEN];
    let ciphertext = &body[SALT_LEN + NONCE_LEN..];

    let key = derive_key_with_pcost(passphrase, salt, p_cost)?;
    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key.as_ref()));
    let nonce = Nonce::from_slice(nonce_bytes);

    let plaintext = Zeroizing::new(
        cipher
            .decrypt(nonce, ciphertext)
            .map_err(|_| PqfileError::WrongPassphrase)?,
    );

    if plaintext.len() != HYBRID_SEED_LEN {
        return Err(PqfileError::WrongPassphrase);
    }

    let mut seed = Zeroizing::new([0u8; HYBRID_SEED_LEN]);
    seed.copy_from_slice(&plaintext);
    Ok(seed)
}

const SIGNING_SEED_LEN: usize = 32;

/// Layout of the encrypted ML-DSA-65 signing key PEM body (76 bytes total):
///   0..16   salt
///   16..28  AES-GCM nonce
///   28..76  AES-256-GCM ciphertext (32-byte signing seed + 16-byte tag)
pub const ENCRYPTED_SIGNING_BODY_LEN: usize = SALT_LEN + NONCE_LEN + SIGNING_SEED_LEN + 16;

/// Encrypts a 32-byte ML-DSA-65 signing seed under `passphrase`. Returns the 76-byte
/// payload stored as the PEM body of an encrypted signing key.
pub fn encrypt_signing_seed(
    seed: &[u8; SIGNING_SEED_LEN],
    passphrase: &str,
) -> Result<Vec<u8>, PqfileError> {
    let mut salt = [0u8; SALT_LEN];
    getrandom::fill(&mut salt).map_err(|_| PqfileError::EncryptionFailure)?;

    let key = derive_key(passphrase, &salt)?;
    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key.as_ref()));

    let mut nonce_bytes = [0u8; NONCE_LEN];
    getrandom::fill(&mut nonce_bytes).map_err(|_| PqfileError::EncryptionFailure)?;
    let nonce = Nonce::from_slice(&nonce_bytes);

    let ciphertext = cipher
        .encrypt(nonce, seed.as_slice())
        .map_err(|_| PqfileError::EncryptionFailure)?;

    let mut out = Vec::with_capacity(ENCRYPTED_SIGNING_BODY_LEN);
    out.extend_from_slice(&salt);
    out.extend_from_slice(&nonce_bytes);
    out.extend_from_slice(&ciphertext);
    Ok(out)
}

/// Decrypts the 76-byte payload from an encrypted ML-DSA-65 signing key PEM body.
///
/// Returns `LegacyKeyFormat` if the body was encrypted with legacy p=1 parameters.
pub fn decrypt_signing_seed(
    body: &[u8],
    passphrase: &str,
) -> Result<Zeroizing<[u8; SIGNING_SEED_LEN]>, PqfileError> {
    if body.len() != ENCRYPTED_SIGNING_BODY_LEN {
        return Err(PqfileError::InvalidKeyLength {
            expected: ENCRYPTED_SIGNING_BODY_LEN,
            got: body.len(),
        });
    }
    if let Ok(seed) = try_decrypt_signing_seed(body, passphrase, ARGON2_P_COST) {
        return Ok(seed);
    }
    if try_decrypt_signing_seed(body, passphrase, ARGON2_P_COST_LEGACY).is_ok() {
        return Err(PqfileError::LegacyKeyFormat);
    }
    Err(PqfileError::WrongPassphrase)
}

/// Decrypts a 76-byte signing body using legacy p=1 parameters.
/// Only called by the `repassphrase --from-legacy` migration path.
pub(crate) fn decrypt_signing_seed_legacy(
    body: &[u8],
    passphrase: &str,
) -> Result<Zeroizing<[u8; SIGNING_SEED_LEN]>, PqfileError> {
    if body.len() != ENCRYPTED_SIGNING_BODY_LEN {
        return Err(PqfileError::InvalidKeyLength {
            expected: ENCRYPTED_SIGNING_BODY_LEN,
            got: body.len(),
        });
    }
    try_decrypt_signing_seed(body, passphrase, ARGON2_P_COST_LEGACY)
        .map_err(|_| PqfileError::WrongPassphrase)
}

fn try_decrypt_signing_seed(
    body: &[u8],
    passphrase: &str,
    p_cost: u32,
) -> Result<Zeroizing<[u8; SIGNING_SEED_LEN]>, PqfileError> {
    let salt = &body[..SALT_LEN];
    let nonce_bytes = &body[SALT_LEN..SALT_LEN + NONCE_LEN];
    let ciphertext = &body[SALT_LEN + NONCE_LEN..];

    let key = derive_key_with_pcost(passphrase, salt, p_cost)?;
    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key.as_ref()));
    let nonce = Nonce::from_slice(nonce_bytes);

    let plaintext = Zeroizing::new(
        cipher
            .decrypt(nonce, ciphertext)
            .map_err(|_| PqfileError::WrongPassphrase)?,
    );

    if plaintext.len() != SIGNING_SEED_LEN {
        return Err(PqfileError::WrongPassphrase);
    }

    let mut seed = Zeroizing::new([0u8; SIGNING_SEED_LEN]);
    seed.copy_from_slice(&plaintext);
    Ok(seed)
}

fn derive_key(passphrase: &str, salt: &[u8]) -> Result<Zeroizing<[u8; 32]>, PqfileError> {
    derive_key_with_pcost(passphrase, salt, ARGON2_P_COST)
}

fn derive_key_with_pcost(
    passphrase: &str,
    salt: &[u8],
    p_cost: u32,
) -> Result<Zeroizing<[u8; 32]>, PqfileError> {
    let params = Params::new(ARGON2_M_COST, ARGON2_T_COST, p_cost, Some(32))
        .map_err(|_| PqfileError::EncryptionFailure)?;
    let argon2 = Argon2::new(argon2::Algorithm::Argon2id, argon2::Version::V0x13, params);
    let mut key = Zeroizing::new([0u8; 32]);
    argon2
        .hash_password_into(passphrase.as_bytes(), salt, key.as_mut())
        .map_err(|_| PqfileError::EncryptionFailure)?;
    Ok(key)
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── Helpers that produce legacy (p=1) bodies for migration tests ──────────

    fn encrypt_seed_legacy(seed: &[u8; SEED_LEN], passphrase: &str) -> Vec<u8> {
        let mut salt = [0u8; SALT_LEN];
        getrandom::fill(&mut salt).unwrap();
        let key = derive_key_with_pcost(passphrase, &salt, ARGON2_P_COST_LEGACY).unwrap();
        let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key.as_ref()));
        let mut nonce_bytes = [0u8; NONCE_LEN];
        getrandom::fill(&mut nonce_bytes).unwrap();
        let ct = cipher
            .encrypt(Nonce::from_slice(&nonce_bytes), seed.as_slice())
            .unwrap();
        let mut out = Vec::new();
        out.extend_from_slice(&salt);
        out.extend_from_slice(&nonce_bytes);
        out.extend_from_slice(&ct);
        out
    }

    fn encrypt_signing_seed_legacy(seed: &[u8; SIGNING_SEED_LEN], passphrase: &str) -> Vec<u8> {
        let mut salt = [0u8; SALT_LEN];
        getrandom::fill(&mut salt).unwrap();
        let key = derive_key_with_pcost(passphrase, &salt, ARGON2_P_COST_LEGACY).unwrap();
        let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key.as_ref()));
        let mut nonce_bytes = [0u8; NONCE_LEN];
        getrandom::fill(&mut nonce_bytes).unwrap();
        let ct = cipher
            .encrypt(Nonce::from_slice(&nonce_bytes), seed.as_slice())
            .unwrap();
        let mut out = Vec::new();
        out.extend_from_slice(&salt);
        out.extend_from_slice(&nonce_bytes);
        out.extend_from_slice(&ct);
        out
    }

    fn encrypt_hybrid_seed_legacy(seed: &[u8; HYBRID_SEED_LEN], passphrase: &str) -> Vec<u8> {
        let mut salt = [0u8; SALT_LEN];
        getrandom::fill(&mut salt).unwrap();
        let key = derive_key_with_pcost(passphrase, &salt, ARGON2_P_COST_LEGACY).unwrap();
        let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key.as_ref()));
        let mut nonce_bytes = [0u8; NONCE_LEN];
        getrandom::fill(&mut nonce_bytes).unwrap();
        let ct = cipher
            .encrypt(Nonce::from_slice(&nonce_bytes), seed.as_slice())
            .unwrap();
        let mut out = Vec::new();
        out.extend_from_slice(&salt);
        out.extend_from_slice(&nonce_bytes);
        out.extend_from_slice(&ct);
        out
    }

    // ── Current (p=4) round-trips ─────────────────────────────────────────────

    #[test]
    fn roundtrip_correct_passphrase() {
        let seed = [0x42u8; SEED_LEN];
        let body = encrypt_seed(&seed, "hunter2").unwrap();
        assert_eq!(body.len(), ENCRYPTED_BODY_LEN);
        let recovered = decrypt_seed(&body, "hunter2").unwrap();
        assert_eq!(*recovered, seed);
    }

    #[test]
    fn wrong_passphrase_returns_error() {
        let seed = [0x99u8; SEED_LEN];
        let body = encrypt_seed(&seed, "correct").unwrap();
        assert!(matches!(
            decrypt_seed(&body, "wrong"),
            Err(PqfileError::WrongPassphrase)
        ));
    }

    #[test]
    fn different_encryptions_produce_different_bodies() {
        let seed = [0x01u8; SEED_LEN];
        let a = encrypt_seed(&seed, "pass").unwrap();
        let b = encrypt_seed(&seed, "pass").unwrap();
        assert_ne!(a, b);
    }

    #[test]
    fn wrong_body_length_returns_error() {
        assert!(matches!(
            decrypt_seed(&[0u8; 10], "pass"),
            Err(PqfileError::InvalidKeyLength { .. })
        ));
    }

    // ── Legacy detection ──────────────────────────────────────────────────────

    #[test]
    fn legacy_key_returns_legacy_key_format_error() {
        let seed = [0x11u8; SEED_LEN];
        let legacy_body = encrypt_seed_legacy(&seed, "correct");
        assert!(matches!(
            decrypt_seed(&legacy_body, "correct"),
            Err(PqfileError::LegacyKeyFormat)
        ));
    }

    #[test]
    fn legacy_key_wrong_passphrase_returns_wrong_passphrase() {
        let seed = [0x22u8; SEED_LEN];
        let legacy_body = encrypt_seed_legacy(&seed, "correct");
        assert!(matches!(
            decrypt_seed(&legacy_body, "wrong"),
            Err(PqfileError::WrongPassphrase)
        ));
    }

    #[test]
    fn decrypt_seed_legacy_roundtrip() {
        let seed = [0x33u8; SEED_LEN];
        let legacy_body = encrypt_seed_legacy(&seed, "migrate-me");
        let recovered = decrypt_seed_legacy(&legacy_body, "migrate-me").unwrap();
        assert_eq!(*recovered, seed);
    }

    #[test]
    fn decrypt_seed_legacy_wrong_passphrase() {
        let seed = [0x44u8; SEED_LEN];
        let legacy_body = encrypt_seed_legacy(&seed, "correct");
        assert!(matches!(
            decrypt_seed_legacy(&legacy_body, "wrong"),
            Err(PqfileError::WrongPassphrase)
        ));
    }

    // ── Hybrid (p=4) ──────────────────────────────────────────────────────────

    #[test]
    fn hybrid_roundtrip_correct_passphrase() {
        let seed = [0x77u8; HYBRID_SEED_LEN];
        let body = encrypt_hybrid_seed(&seed, "hybrid-pass").unwrap();
        assert_eq!(body.len(), ENCRYPTED_HYBRID_BODY_LEN);
        let recovered = decrypt_hybrid_seed(&body, "hybrid-pass").unwrap();
        assert_eq!(*recovered, seed);
    }

    #[test]
    fn hybrid_wrong_passphrase_returns_error() {
        let seed = [0xABu8; HYBRID_SEED_LEN];
        let body = encrypt_hybrid_seed(&seed, "correct").unwrap();
        assert!(matches!(
            decrypt_hybrid_seed(&body, "wrong"),
            Err(PqfileError::WrongPassphrase)
        ));
    }

    #[test]
    fn hybrid_wrong_body_length_returns_error() {
        assert!(matches!(
            decrypt_hybrid_seed(&[0u8; 10], "pass"),
            Err(PqfileError::InvalidKeyLength { .. })
        ));
    }

    #[test]
    fn hybrid_different_encryptions_produce_different_bodies() {
        let seed = [0x55u8; HYBRID_SEED_LEN];
        let a = encrypt_hybrid_seed(&seed, "pass").unwrap();
        let b = encrypt_hybrid_seed(&seed, "pass").unwrap();
        assert_ne!(a, b);
    }

    #[test]
    fn hybrid_legacy_key_returns_legacy_key_format_error() {
        let seed = [0xCCu8; HYBRID_SEED_LEN];
        let legacy_body = encrypt_hybrid_seed_legacy(&seed, "correct");
        assert!(matches!(
            decrypt_hybrid_seed(&legacy_body, "correct"),
            Err(PqfileError::LegacyKeyFormat)
        ));
    }

    #[test]
    fn decrypt_hybrid_seed_legacy_roundtrip() {
        let seed = [0xDDu8; HYBRID_SEED_LEN];
        let legacy_body = encrypt_hybrid_seed_legacy(&seed, "migrate-me");
        let recovered = decrypt_hybrid_seed_legacy(&legacy_body, "migrate-me").unwrap();
        assert_eq!(*recovered, seed);
    }

    // ── Signing (p=4) ─────────────────────────────────────────────────────────

    #[test]
    fn signing_roundtrip_correct_passphrase() {
        let seed = [0x11u8; SIGNING_SEED_LEN];
        let body = encrypt_signing_seed(&seed, "signpass").unwrap();
        assert_eq!(body.len(), ENCRYPTED_SIGNING_BODY_LEN);
        let recovered = decrypt_signing_seed(&body, "signpass").unwrap();
        assert_eq!(*recovered, seed);
    }

    #[test]
    fn signing_wrong_passphrase_returns_error() {
        let seed = [0x22u8; SIGNING_SEED_LEN];
        let body = encrypt_signing_seed(&seed, "correct").unwrap();
        assert!(matches!(
            decrypt_signing_seed(&body, "wrong"),
            Err(PqfileError::WrongPassphrase)
        ));
    }

    #[test]
    fn signing_wrong_body_length_returns_error() {
        assert!(matches!(
            decrypt_signing_seed(&[0u8; 10], "pass"),
            Err(PqfileError::InvalidKeyLength { .. })
        ));
    }

    #[test]
    fn signing_different_encryptions_produce_different_bodies() {
        let seed = [0x33u8; SIGNING_SEED_LEN];
        let a = encrypt_signing_seed(&seed, "pass").unwrap();
        let b = encrypt_signing_seed(&seed, "pass").unwrap();
        assert_ne!(a, b);
    }

    #[test]
    fn signing_legacy_key_returns_legacy_key_format_error() {
        let seed = [0x55u8; SIGNING_SEED_LEN];
        let legacy_body = encrypt_signing_seed_legacy(&seed, "correct");
        assert!(matches!(
            decrypt_signing_seed(&legacy_body, "correct"),
            Err(PqfileError::LegacyKeyFormat)
        ));
    }

    #[test]
    fn decrypt_signing_seed_legacy_roundtrip() {
        let seed = [0x66u8; SIGNING_SEED_LEN];
        let legacy_body = encrypt_signing_seed_legacy(&seed, "migrate-me");
        let recovered = decrypt_signing_seed_legacy(&legacy_body, "migrate-me").unwrap();
        assert_eq!(*recovered, seed);
    }
}