paserk 0.4.0

Platform-Agnostic Serialized Keys (PASERK) for PASETO
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
//! PIE (Platform-Independent Encryption) protocol implementation.
//!
//! This module implements the PIE key wrapping protocol for PASERK.
//! - For K2/K4: Uses `XChaCha20` + `BLAKE2b`
//! - For K1/K3: Uses AES-256-CTR + HMAC-SHA384

#[cfg(any(
    feature = "k1-insecure",
    feature = "k2",
    feature = "k3",
    feature = "k4"
))]
use crate::core::error::{PaserkError, PaserkResult};

/// Nonce size for PIE protocol (32 bytes).
pub const PIE_NONCE_SIZE: usize = 32;

/// Tag size for PIE protocol (32 bytes).
pub const PIE_TAG_SIZE: usize = 32;

/// Domain separation byte for PIE encryption key derivation (0x80).
#[cfg(any(
    feature = "k1-insecure",
    feature = "k2",
    feature = "k3",
    feature = "k4"
))]
const PIE_ENCRYPTION_KEY_DOMAIN: u8 = 0x80;

/// Domain separation byte for PIE authentication key derivation (0x81).
#[cfg(any(
    feature = "k1-insecure",
    feature = "k2",
    feature = "k3",
    feature = "k4"
))]
const PIE_AUTH_KEY_DOMAIN: u8 = 0x81;

/// Wraps a local (symmetric) key using the PIE protocol for K2/K4.
///
/// # Arguments
///
/// * `wrapping_key` - The 32-byte symmetric key used for wrapping
/// * `plaintext_key` - The 32-byte key to wrap
/// * `header` - The PASERK header (e.g., "k4.local-wrap.pie.")
///
/// # Returns
///
/// A tuple of (nonce, ciphertext, tag) where:
/// - nonce is 32 bytes
/// - ciphertext is 32 bytes (same size as plaintext)
/// - tag is 32 bytes
#[cfg(any(feature = "k2", feature = "k4"))]
pub fn pie_wrap_local_k2k4(
    wrapping_key: &[u8; 32],
    plaintext_key: &[u8; 32],
    header: &str,
) -> PaserkResult<([u8; PIE_NONCE_SIZE], [u8; 32], [u8; PIE_TAG_SIZE])> {
    use blake2::digest::{FixedOutput, KeyInit, Update};
    use blake2::Blake2bMac;
    use chacha20::cipher::{KeyIvInit, StreamCipher};
    use chacha20::XChaCha20;
    use rand_core::{OsRng, TryRngCore};

    // Type aliases for BLAKE2b variants
    type Blake2bMac56 = Blake2bMac<blake2::digest::consts::U56>;
    type Blake2bMac32 = Blake2bMac<blake2::digest::consts::U32>;

    // Generate random nonce
    let mut nonce = [0u8; PIE_NONCE_SIZE];
    OsRng
        .try_fill_bytes(&mut nonce)
        .map_err(|_| PaserkError::CryptoError)?;

    // Derive encryption key and XChaCha20 nonce
    // x = BLAKE2b-MAC(key=wrapping_key, msg=0x80 || nonce, len=56)
    // Ek = x[0:32], n2 = x[32:56]
    let mut kdf_mac = <Blake2bMac56 as KeyInit>::new_from_slice(wrapping_key)
        .map_err(|_| PaserkError::CryptoError)?;
    <Blake2bMac56 as Update>::update(&mut kdf_mac, &[PIE_ENCRYPTION_KEY_DOMAIN]);
    <Blake2bMac56 as Update>::update(&mut kdf_mac, &nonce);
    let tmp = <Blake2bMac56 as FixedOutput>::finalize_fixed(kdf_mac);

    let mut encryption_key = [0u8; 32];
    encryption_key.copy_from_slice(&tmp[..32]);

    let mut xchacha_nonce = [0u8; 24];
    xchacha_nonce.copy_from_slice(&tmp[32..56]);

    // Derive authentication key
    // Ak = BLAKE2b-MAC(key=wrapping_key, msg=0x81 || nonce, len=32)
    let mut auth_mac = <Blake2bMac32 as KeyInit>::new_from_slice(wrapping_key)
        .map_err(|_| PaserkError::CryptoError)?;
    <Blake2bMac32 as Update>::update(&mut auth_mac, &[PIE_AUTH_KEY_DOMAIN]);
    <Blake2bMac32 as Update>::update(&mut auth_mac, &nonce);
    let mut auth_key: [u8; 32] = <Blake2bMac32 as FixedOutput>::finalize_fixed(auth_mac).into();

    // Encrypt the plaintext key
    // c = XChaCha20(key=Ek, nonce=n2, plaintext=ptk)
    let mut ciphertext = *plaintext_key;
    let mut cipher = XChaCha20::new(&encryption_key.into(), &xchacha_nonce.into());
    cipher.apply_keystream(&mut ciphertext);

    // Compute authentication tag
    // t = BLAKE2b-MAC(key=Ak, msg=header || nonce || ciphertext, len=32)
    let mut tag_mac = <Blake2bMac32 as KeyInit>::new_from_slice(&auth_key)
        .map_err(|_| PaserkError::CryptoError)?;
    <Blake2bMac32 as Update>::update(&mut tag_mac, header.as_bytes());
    <Blake2bMac32 as Update>::update(&mut tag_mac, &nonce);
    <Blake2bMac32 as Update>::update(&mut tag_mac, &ciphertext);
    let tag: [u8; PIE_TAG_SIZE] = <Blake2bMac32 as FixedOutput>::finalize_fixed(tag_mac).into();

    // Zeroize sensitive key material
    zeroize::Zeroize::zeroize(&mut encryption_key);
    zeroize::Zeroize::zeroize(&mut xchacha_nonce);
    zeroize::Zeroize::zeroize(&mut auth_key);

    Ok((nonce, ciphertext, tag))
}

/// Unwraps a local (symmetric) key using the PIE protocol for K2/K4.
///
/// # Arguments
///
/// * `wrapping_key` - The 32-byte symmetric key used for unwrapping
/// * `nonce` - The 32-byte nonce from the wrapped key
/// * `ciphertext` - The 32-byte encrypted key
/// * `tag` - The 32-byte authentication tag
/// * `header` - The PASERK header (e.g., "k4.local-wrap.pie.")
///
/// # Returns
///
/// The unwrapped 32-byte plaintext key.
#[cfg(any(feature = "k2", feature = "k4"))]
pub fn pie_unwrap_local_k2k4(
    wrapping_key: &[u8; 32],
    nonce: &[u8; PIE_NONCE_SIZE],
    ciphertext: &[u8; 32],
    tag: &[u8; PIE_TAG_SIZE],
    header: &str,
) -> PaserkResult<[u8; 32]> {
    use blake2::digest::{FixedOutput, KeyInit, Update};
    use blake2::Blake2bMac;
    use chacha20::cipher::{KeyIvInit, StreamCipher};
    use chacha20::XChaCha20;
    use subtle::ConstantTimeEq;

    // Type aliases for BLAKE2b variants
    type Blake2bMac56 = Blake2bMac<blake2::digest::consts::U56>;
    type Blake2bMac32 = Blake2bMac<blake2::digest::consts::U32>;

    // Derive encryption key and XChaCha20 nonce
    // x = BLAKE2b-MAC(key=wrapping_key, msg=0x80 || nonce, len=56)
    let mut kdf_mac = <Blake2bMac56 as KeyInit>::new_from_slice(wrapping_key)
        .map_err(|_| PaserkError::CryptoError)?;
    <Blake2bMac56 as Update>::update(&mut kdf_mac, &[PIE_ENCRYPTION_KEY_DOMAIN]);
    <Blake2bMac56 as Update>::update(&mut kdf_mac, nonce);
    let tmp = <Blake2bMac56 as FixedOutput>::finalize_fixed(kdf_mac);

    let mut encryption_key = [0u8; 32];
    encryption_key.copy_from_slice(&tmp[..32]);

    let mut xchacha_nonce = [0u8; 24];
    xchacha_nonce.copy_from_slice(&tmp[32..56]);

    // Derive authentication key
    // Ak = BLAKE2b-MAC(key=wrapping_key, msg=0x81 || nonce, len=32)
    let mut auth_mac = <Blake2bMac32 as KeyInit>::new_from_slice(wrapping_key)
        .map_err(|_| PaserkError::CryptoError)?;
    <Blake2bMac32 as Update>::update(&mut auth_mac, &[PIE_AUTH_KEY_DOMAIN]);
    <Blake2bMac32 as Update>::update(&mut auth_mac, nonce);
    let mut auth_key: [u8; 32] = <Blake2bMac32 as FixedOutput>::finalize_fixed(auth_mac).into();

    // Verify authentication tag
    // t2 = BLAKE2b-MAC(key=Ak, msg=header || nonce || ciphertext, len=32)
    let mut tag_mac = <Blake2bMac32 as KeyInit>::new_from_slice(&auth_key)
        .map_err(|_| PaserkError::CryptoError)?;
    <Blake2bMac32 as Update>::update(&mut tag_mac, header.as_bytes());
    <Blake2bMac32 as Update>::update(&mut tag_mac, nonce);
    <Blake2bMac32 as Update>::update(&mut tag_mac, ciphertext);
    let computed_tag: [u8; PIE_TAG_SIZE] =
        <Blake2bMac32 as FixedOutput>::finalize_fixed(tag_mac).into();

    // Constant-time tag comparison
    if computed_tag.ct_eq(tag).into() {
        // Decrypt the ciphertext
        let mut plaintext = *ciphertext;
        let mut cipher = XChaCha20::new(&encryption_key.into(), &xchacha_nonce.into());
        cipher.apply_keystream(&mut plaintext);

        // Zeroize sensitive key material
        zeroize::Zeroize::zeroize(&mut encryption_key);
        zeroize::Zeroize::zeroize(&mut xchacha_nonce);
        zeroize::Zeroize::zeroize(&mut auth_key);

        Ok(plaintext)
    } else {
        // Zeroize sensitive key material even on error path
        zeroize::Zeroize::zeroize(&mut encryption_key);
        zeroize::Zeroize::zeroize(&mut xchacha_nonce);
        zeroize::Zeroize::zeroize(&mut auth_key);

        Err(PaserkError::AuthenticationFailed)
    }
}

/// Wraps a secret (signing) key using the PIE protocol for K2/K4.
///
/// # Arguments
///
/// * `wrapping_key` - The 32-byte symmetric key used for wrapping
/// * `plaintext_key` - The 64-byte Ed25519 secret key to wrap
/// * `header` - The PASERK header (e.g., "k4.secret-wrap.pie.")
///
/// # Returns
///
/// A tuple of (nonce, ciphertext, tag) where:
/// - nonce is 32 bytes
/// - ciphertext is 64 bytes (same size as plaintext)
/// - tag is 32 bytes
#[cfg(any(feature = "k2", feature = "k4"))]
pub fn pie_wrap_secret_k2k4(
    wrapping_key: &[u8; 32],
    plaintext_key: &[u8; 64],
    header: &str,
) -> PaserkResult<([u8; PIE_NONCE_SIZE], [u8; 64], [u8; PIE_TAG_SIZE])> {
    use blake2::digest::{FixedOutput, KeyInit, Update};
    use blake2::Blake2bMac;
    use chacha20::cipher::{KeyIvInit, StreamCipher};
    use chacha20::XChaCha20;
    use rand_core::{OsRng, TryRngCore};

    // Type aliases for BLAKE2b variants
    type Blake2bMac56 = Blake2bMac<blake2::digest::consts::U56>;
    type Blake2bMac32 = Blake2bMac<blake2::digest::consts::U32>;

    // Generate random nonce
    let mut nonce = [0u8; PIE_NONCE_SIZE];
    OsRng
        .try_fill_bytes(&mut nonce)
        .map_err(|_| PaserkError::CryptoError)?;

    // Derive encryption key and XChaCha20 nonce
    // x = BLAKE2b-MAC(key=wrapping_key, msg=0x80 || nonce, len=56)
    let mut kdf_mac = <Blake2bMac56 as KeyInit>::new_from_slice(wrapping_key)
        .map_err(|_| PaserkError::CryptoError)?;
    <Blake2bMac56 as Update>::update(&mut kdf_mac, &[PIE_ENCRYPTION_KEY_DOMAIN]);
    <Blake2bMac56 as Update>::update(&mut kdf_mac, &nonce);
    let tmp = <Blake2bMac56 as FixedOutput>::finalize_fixed(kdf_mac);

    let mut encryption_key = [0u8; 32];
    encryption_key.copy_from_slice(&tmp[..32]);

    let mut xchacha_nonce = [0u8; 24];
    xchacha_nonce.copy_from_slice(&tmp[32..56]);

    // Derive authentication key
    // Ak = BLAKE2b-MAC(key=wrapping_key, msg=0x81 || nonce, len=32)
    let mut auth_mac = <Blake2bMac32 as KeyInit>::new_from_slice(wrapping_key)
        .map_err(|_| PaserkError::CryptoError)?;
    <Blake2bMac32 as Update>::update(&mut auth_mac, &[PIE_AUTH_KEY_DOMAIN]);
    <Blake2bMac32 as Update>::update(&mut auth_mac, &nonce);
    let mut auth_key: [u8; 32] = <Blake2bMac32 as FixedOutput>::finalize_fixed(auth_mac).into();

    // Encrypt the plaintext key
    let mut ciphertext = *plaintext_key;
    let mut cipher = XChaCha20::new(&encryption_key.into(), &xchacha_nonce.into());
    cipher.apply_keystream(&mut ciphertext);

    // Compute authentication tag
    // t = BLAKE2b-MAC(key=Ak, msg=header || nonce || ciphertext, len=32)
    let mut tag_mac = <Blake2bMac32 as KeyInit>::new_from_slice(&auth_key)
        .map_err(|_| PaserkError::CryptoError)?;
    <Blake2bMac32 as Update>::update(&mut tag_mac, header.as_bytes());
    <Blake2bMac32 as Update>::update(&mut tag_mac, &nonce);
    <Blake2bMac32 as Update>::update(&mut tag_mac, &ciphertext);
    let tag: [u8; PIE_TAG_SIZE] = <Blake2bMac32 as FixedOutput>::finalize_fixed(tag_mac).into();

    // Zeroize sensitive key material
    zeroize::Zeroize::zeroize(&mut encryption_key);
    zeroize::Zeroize::zeroize(&mut xchacha_nonce);
    zeroize::Zeroize::zeroize(&mut auth_key);

    Ok((nonce, ciphertext, tag))
}

/// Unwraps a secret (signing) key using the PIE protocol for K2/K4.
///
/// # Arguments
///
/// * `wrapping_key` - The 32-byte symmetric key used for unwrapping
/// * `nonce` - The 32-byte nonce from the wrapped key
/// * `ciphertext` - The 64-byte encrypted key
/// * `tag` - The 32-byte authentication tag
/// * `header` - The PASERK header (e.g., "k4.secret-wrap.pie.")
///
/// # Returns
///
/// The unwrapped 64-byte plaintext secret key.
#[cfg(any(feature = "k2", feature = "k4"))]
pub fn pie_unwrap_secret_k2k4(
    wrapping_key: &[u8; 32],
    nonce: &[u8; PIE_NONCE_SIZE],
    ciphertext: &[u8; 64],
    tag: &[u8; PIE_TAG_SIZE],
    header: &str,
) -> PaserkResult<[u8; 64]> {
    use blake2::digest::{FixedOutput, KeyInit, Update};
    use blake2::Blake2bMac;
    use chacha20::cipher::{KeyIvInit, StreamCipher};
    use chacha20::XChaCha20;
    use subtle::ConstantTimeEq;

    // Type aliases for BLAKE2b variants
    type Blake2bMac56 = Blake2bMac<blake2::digest::consts::U56>;
    type Blake2bMac32 = Blake2bMac<blake2::digest::consts::U32>;

    // Derive encryption key and XChaCha20 nonce
    // x = BLAKE2b-MAC(key=wrapping_key, msg=0x80 || nonce, len=56)
    let mut kdf_mac = <Blake2bMac56 as KeyInit>::new_from_slice(wrapping_key)
        .map_err(|_| PaserkError::CryptoError)?;
    <Blake2bMac56 as Update>::update(&mut kdf_mac, &[PIE_ENCRYPTION_KEY_DOMAIN]);
    <Blake2bMac56 as Update>::update(&mut kdf_mac, nonce);
    let tmp = <Blake2bMac56 as FixedOutput>::finalize_fixed(kdf_mac);

    let mut encryption_key = [0u8; 32];
    encryption_key.copy_from_slice(&tmp[..32]);

    let mut xchacha_nonce = [0u8; 24];
    xchacha_nonce.copy_from_slice(&tmp[32..56]);

    // Derive authentication key
    // Ak = BLAKE2b-MAC(key=wrapping_key, msg=0x81 || nonce, len=32)
    let mut auth_mac = <Blake2bMac32 as KeyInit>::new_from_slice(wrapping_key)
        .map_err(|_| PaserkError::CryptoError)?;
    <Blake2bMac32 as Update>::update(&mut auth_mac, &[PIE_AUTH_KEY_DOMAIN]);
    <Blake2bMac32 as Update>::update(&mut auth_mac, nonce);
    let mut auth_key: [u8; 32] = <Blake2bMac32 as FixedOutput>::finalize_fixed(auth_mac).into();

    // Verify authentication tag
    // t2 = BLAKE2b-MAC(key=Ak, msg=header || nonce || ciphertext, len=32)
    let mut tag_mac = <Blake2bMac32 as KeyInit>::new_from_slice(&auth_key)
        .map_err(|_| PaserkError::CryptoError)?;
    <Blake2bMac32 as Update>::update(&mut tag_mac, header.as_bytes());
    <Blake2bMac32 as Update>::update(&mut tag_mac, nonce);
    <Blake2bMac32 as Update>::update(&mut tag_mac, ciphertext);
    let computed_tag: [u8; PIE_TAG_SIZE] =
        <Blake2bMac32 as FixedOutput>::finalize_fixed(tag_mac).into();

    // Constant-time tag comparison
    if computed_tag.ct_eq(tag).into() {
        // Decrypt the ciphertext
        let mut plaintext = *ciphertext;
        let mut cipher = XChaCha20::new(&encryption_key.into(), &xchacha_nonce.into());
        cipher.apply_keystream(&mut plaintext);

        // Zeroize sensitive key material
        zeroize::Zeroize::zeroize(&mut encryption_key);
        zeroize::Zeroize::zeroize(&mut xchacha_nonce);
        zeroize::Zeroize::zeroize(&mut auth_key);

        Ok(plaintext)
    } else {
        // Zeroize sensitive key material even on error path
        zeroize::Zeroize::zeroize(&mut encryption_key);
        zeroize::Zeroize::zeroize(&mut xchacha_nonce);
        zeroize::Zeroize::zeroize(&mut auth_key);

        Err(PaserkError::AuthenticationFailed)
    }
}

// =============================================================================
// K1/K3 PIE Protocol Implementation (AES-256-CTR + HMAC-SHA384)
// =============================================================================

/// Nonce size for K1/K3 PIE protocol (32 bytes).
#[cfg(any(feature = "k1-insecure", feature = "k3"))]
pub const PIE_K1K3_NONCE_SIZE: usize = 32;

/// Tag size for K1/K3 PIE protocol (48 bytes - HMAC-SHA384).
#[cfg(any(feature = "k1-insecure", feature = "k3"))]
pub const PIE_K1K3_TAG_SIZE: usize = 48;

/// Domain separation byte for K1/K3 PIE encryption key derivation (0x80).
#[cfg(any(feature = "k1-insecure", feature = "k3"))]
const PIE_K1K3_ENCRYPTION_KEY_DOMAIN: u8 = 0x80;

/// Domain separation byte for K1/K3 PIE authentication key derivation (0x81).
#[cfg(any(feature = "k1-insecure", feature = "k3"))]
const PIE_K1K3_AUTH_KEY_DOMAIN: u8 = 0x81;

/// Derives encryption and authentication keys for K1/K3 PIE using HMAC-SHA384.
///
/// # Arguments
///
/// * `wrapping_key` - The 32-byte symmetric wrapping key
/// * `nonce` - The 32-byte random nonce
///
/// # Returns
///
/// A tuple of (`encryption_key`, `aes_nonce`, `auth_key`) where:
/// - `encryption_key` is 32 bytes
/// - `aes_nonce` is 16 bytes
/// - `auth_key` is 48 bytes (full HMAC-SHA384 output)
#[cfg(any(feature = "k1-insecure", feature = "k3"))]
fn derive_pie_keys_k1k3(
    wrapping_key: &[u8; 32],
    nonce: &[u8; PIE_K1K3_NONCE_SIZE],
) -> PaserkResult<([u8; 32], [u8; 16], [u8; 48])> {
    use hmac::{Hmac, Mac};
    use sha2::Sha384;

    // Derive tmp = HMAC-SHA384(key=wrapping_key, msg=0x80 || nonce)
    // Use first 32 bytes as Ek, next 16 bytes as AES-CTR nonce
    let mut kdf_mac = <Hmac<Sha384> as Mac>::new_from_slice(wrapping_key)
        .map_err(|_| PaserkError::CryptoError)?;
    kdf_mac.update(&[PIE_K1K3_ENCRYPTION_KEY_DOMAIN]);
    kdf_mac.update(nonce);
    let tmp = kdf_mac.finalize().into_bytes();

    let mut encryption_key = [0u8; 32];
    encryption_key.copy_from_slice(&tmp[..32]);

    let mut aes_nonce = [0u8; 16];
    aes_nonce.copy_from_slice(&tmp[32..48]);

    // Derive authentication key
    // Ak = HMAC-SHA384(key=wrapping_key, msg=0x81 || nonce)
    let mut auth_mac = <Hmac<Sha384> as Mac>::new_from_slice(wrapping_key)
        .map_err(|_| PaserkError::CryptoError)?;
    auth_mac.update(&[PIE_K1K3_AUTH_KEY_DOMAIN]);
    auth_mac.update(nonce);
    let auth_key: [u8; 48] = auth_mac.finalize().into_bytes().into();

    Ok((encryption_key, aes_nonce, auth_key))
}

/// Computes the authentication tag for K1/K3 PIE using HMAC-SHA384.
#[cfg(any(feature = "k1-insecure", feature = "k3"))]
fn compute_pie_tag_k1k3(
    auth_key: &[u8; 48],
    header: &str,
    nonce: &[u8],
    ciphertext: &[u8],
) -> PaserkResult<[u8; PIE_K1K3_TAG_SIZE]> {
    use hmac::{Hmac, Mac};
    use sha2::Sha384;

    let mut tag_mac =
        <Hmac<Sha384> as Mac>::new_from_slice(auth_key).map_err(|_| PaserkError::CryptoError)?;
    tag_mac.update(header.as_bytes());
    tag_mac.update(nonce);
    tag_mac.update(ciphertext);
    Ok(tag_mac.finalize().into_bytes().into())
}

/// Encrypts/decrypts data using AES-256-CTR for PIE.
#[cfg(any(feature = "k1-insecure", feature = "k3"))]
fn aes_ctr_apply(key: &[u8; 32], nonce: &[u8; 16], data: &mut [u8]) {
    use aes::cipher::{KeyIvInit, StreamCipher};
    use ctr::Ctr128BE;

    type Aes256Ctr = Ctr128BE<aes::Aes256>;
    let mut cipher = Aes256Ctr::new(key.into(), nonce.into());
    cipher.apply_keystream(data);
}

/// Wraps a local (symmetric) key using the PIE protocol for K1/K3.
///
/// # Arguments
///
/// * `wrapping_key` - The 32-byte symmetric key used for wrapping
/// * `plaintext_key` - The 32-byte key to wrap
/// * `header` - The PASERK header (e.g., "k3.local-wrap.pie.")
///
/// # Returns
///
/// A tuple of (nonce, ciphertext, tag) where:
/// - nonce is 32 bytes
/// - ciphertext is 32 bytes
/// - tag is 48 bytes (HMAC-SHA384)
#[cfg(any(feature = "k1-insecure", feature = "k3"))]
pub fn pie_wrap_local_k1k3(
    wrapping_key: &[u8; 32],
    plaintext_key: &[u8; 32],
    header: &str,
) -> PaserkResult<([u8; PIE_K1K3_NONCE_SIZE], [u8; 32], [u8; PIE_K1K3_TAG_SIZE])> {
    use rand_core::{OsRng, TryRngCore};

    // Generate random nonce
    let mut nonce = [0u8; PIE_K1K3_NONCE_SIZE];
    OsRng
        .try_fill_bytes(&mut nonce)
        .map_err(|_| PaserkError::CryptoError)?;

    // Derive keys
    let (mut encryption_key, mut aes_nonce, mut auth_key) =
        derive_pie_keys_k1k3(wrapping_key, &nonce)?;

    // Encrypt the plaintext key
    let mut ciphertext = *plaintext_key;
    aes_ctr_apply(&encryption_key, &aes_nonce, &mut ciphertext);

    // Compute authentication tag
    let tag = compute_pie_tag_k1k3(&auth_key, header, &nonce, &ciphertext)?;

    // Zeroize sensitive key material
    zeroize::Zeroize::zeroize(&mut encryption_key);
    zeroize::Zeroize::zeroize(&mut aes_nonce);
    zeroize::Zeroize::zeroize(&mut auth_key);

    Ok((nonce, ciphertext, tag))
}

/// Unwraps a local (symmetric) key using the PIE protocol for K1/K3.
///
/// # Arguments
///
/// * `wrapping_key` - The 32-byte symmetric key used for unwrapping
/// * `nonce` - The 32-byte nonce from the wrapped key
/// * `ciphertext` - The 32-byte encrypted key
/// * `tag` - The 48-byte authentication tag
/// * `header` - The PASERK header (e.g., "k3.local-wrap.pie.")
///
/// # Returns
///
/// The unwrapped 32-byte plaintext key.
#[cfg(any(feature = "k1-insecure", feature = "k3"))]
pub fn pie_unwrap_local_k1k3(
    wrapping_key: &[u8; 32],
    nonce: &[u8; PIE_K1K3_NONCE_SIZE],
    ciphertext: &[u8; 32],
    tag: &[u8; PIE_K1K3_TAG_SIZE],
    header: &str,
) -> PaserkResult<[u8; 32]> {
    use subtle::ConstantTimeEq;

    // Derive keys
    let (mut encryption_key, mut aes_nonce, mut auth_key) =
        derive_pie_keys_k1k3(wrapping_key, nonce)?;

    // Verify authentication tag
    let computed_tag = compute_pie_tag_k1k3(&auth_key, header, nonce, ciphertext)?;

    // Constant-time tag comparison
    if computed_tag.ct_eq(tag).into() {
        // Decrypt the ciphertext
        let mut plaintext = *ciphertext;
        aes_ctr_apply(&encryption_key, &aes_nonce, &mut plaintext);

        // Zeroize sensitive key material
        zeroize::Zeroize::zeroize(&mut encryption_key);
        zeroize::Zeroize::zeroize(&mut aes_nonce);
        zeroize::Zeroize::zeroize(&mut auth_key);

        Ok(plaintext)
    } else {
        // Zeroize sensitive key material even on error path
        zeroize::Zeroize::zeroize(&mut encryption_key);
        zeroize::Zeroize::zeroize(&mut aes_nonce);
        zeroize::Zeroize::zeroize(&mut auth_key);

        Err(PaserkError::AuthenticationFailed)
    }
}

/// Wraps a P-384 secret key using the PIE protocol for K3.
///
/// # Arguments
///
/// * `wrapping_key` - The 32-byte symmetric key used for wrapping
/// * `plaintext_key` - The 48-byte P-384 secret key to wrap
/// * `header` - The PASERK header (e.g., "k3.secret-wrap.pie.")
///
/// # Returns
///
/// A tuple of (nonce, ciphertext, tag) where:
/// - nonce is 32 bytes
/// - ciphertext is 48 bytes
/// - tag is 48 bytes (HMAC-SHA384)
#[cfg(feature = "k3")]
pub fn pie_wrap_secret_k3(
    wrapping_key: &[u8; 32],
    plaintext_key: &[u8; 48],
    header: &str,
) -> PaserkResult<([u8; PIE_K1K3_NONCE_SIZE], [u8; 48], [u8; PIE_K1K3_TAG_SIZE])> {
    use rand_core::{OsRng, TryRngCore};

    // Generate random nonce
    let mut nonce = [0u8; PIE_K1K3_NONCE_SIZE];
    OsRng
        .try_fill_bytes(&mut nonce)
        .map_err(|_| PaserkError::CryptoError)?;

    // Derive keys
    let (mut encryption_key, mut aes_nonce, mut auth_key) =
        derive_pie_keys_k1k3(wrapping_key, &nonce)?;

    // Encrypt the plaintext key
    let mut ciphertext = *plaintext_key;
    aes_ctr_apply(&encryption_key, &aes_nonce, &mut ciphertext);

    // Compute authentication tag
    let tag = compute_pie_tag_k1k3(&auth_key, header, &nonce, &ciphertext)?;

    // Zeroize sensitive key material
    zeroize::Zeroize::zeroize(&mut encryption_key);
    zeroize::Zeroize::zeroize(&mut aes_nonce);
    zeroize::Zeroize::zeroize(&mut auth_key);

    Ok((nonce, ciphertext, tag))
}

/// Unwraps a P-384 secret key using the PIE protocol for K3.
///
/// # Arguments
///
/// * `wrapping_key` - The 32-byte symmetric key used for unwrapping
/// * `nonce` - The 32-byte nonce from the wrapped key
/// * `ciphertext` - The 48-byte encrypted key
/// * `tag` - The 48-byte authentication tag
/// * `header` - The PASERK header (e.g., "k3.secret-wrap.pie.")
///
/// # Returns
///
/// The unwrapped 48-byte P-384 secret key.
#[cfg(feature = "k3")]
pub fn pie_unwrap_secret_k3(
    wrapping_key: &[u8; 32],
    nonce: &[u8; PIE_K1K3_NONCE_SIZE],
    ciphertext: &[u8; 48],
    tag: &[u8; PIE_K1K3_TAG_SIZE],
    header: &str,
) -> PaserkResult<[u8; 48]> {
    use subtle::ConstantTimeEq;

    // Derive keys
    let (mut encryption_key, mut aes_nonce, mut auth_key) =
        derive_pie_keys_k1k3(wrapping_key, nonce)?;

    // Verify authentication tag
    let computed_tag = compute_pie_tag_k1k3(&auth_key, header, nonce, ciphertext)?;

    // Constant-time tag comparison
    if computed_tag.ct_eq(tag).into() {
        // Decrypt the ciphertext
        let mut plaintext = *ciphertext;
        aes_ctr_apply(&encryption_key, &aes_nonce, &mut plaintext);

        // Zeroize sensitive key material
        zeroize::Zeroize::zeroize(&mut encryption_key);
        zeroize::Zeroize::zeroize(&mut aes_nonce);
        zeroize::Zeroize::zeroize(&mut auth_key);

        Ok(plaintext)
    } else {
        // Zeroize sensitive key material even on error path
        zeroize::Zeroize::zeroize(&mut encryption_key);
        zeroize::Zeroize::zeroize(&mut aes_nonce);
        zeroize::Zeroize::zeroize(&mut auth_key);

        Err(PaserkError::AuthenticationFailed)
    }
}

#[cfg(test)]
#[cfg(any(
    feature = "k1-insecure",
    feature = "k2",
    feature = "k3",
    feature = "k4"
))]
#[allow(deprecated)]
mod tests {
    use super::*;

    #[test]
    #[cfg(feature = "k4")]
    fn test_pie_wrap_unwrap_local_k4_roundtrip() -> PaserkResult<()> {
        let wrapping_key = [0x42u8; 32];
        let plaintext_key = [0x13u8; 32];
        let header = "k4.local-wrap.pie.";

        let (nonce, ciphertext, tag) = pie_wrap_local_k2k4(&wrapping_key, &plaintext_key, header)?;

        // Ciphertext should be different from plaintext
        assert_ne!(ciphertext, plaintext_key);

        let unwrapped = pie_unwrap_local_k2k4(&wrapping_key, &nonce, &ciphertext, &tag, header)?;

        assert_eq!(unwrapped, plaintext_key);
        Ok(())
    }

    #[test]
    #[cfg(feature = "k4")]
    fn test_pie_wrap_unwrap_secret_k4_roundtrip() -> PaserkResult<()> {
        let wrapping_key = [0x42u8; 32];
        let plaintext_key = [0x13u8; 64];
        let header = "k4.secret-wrap.pie.";

        let (nonce, ciphertext, tag) = pie_wrap_secret_k2k4(&wrapping_key, &plaintext_key, header)?;

        // Ciphertext should be different from plaintext
        assert_ne!(ciphertext, plaintext_key);

        let unwrapped = pie_unwrap_secret_k2k4(&wrapping_key, &nonce, &ciphertext, &tag, header)?;

        assert_eq!(unwrapped, plaintext_key);
        Ok(())
    }

    #[test]
    #[cfg(feature = "k4")]
    fn test_pie_unwrap_local_wrong_key() -> PaserkResult<()> {
        let wrapping_key = [0x42u8; 32];
        let wrong_key = [0x43u8; 32];
        let plaintext_key = [0x13u8; 32];
        let header = "k4.local-wrap.pie.";

        let (nonce, ciphertext, tag) = pie_wrap_local_k2k4(&wrapping_key, &plaintext_key, header)?;

        let result = pie_unwrap_local_k2k4(&wrong_key, &nonce, &ciphertext, &tag, header);

        assert!(matches!(result, Err(PaserkError::AuthenticationFailed)));
        Ok(())
    }

    #[test]
    #[cfg(feature = "k4")]
    fn test_pie_unwrap_local_modified_ciphertext() -> PaserkResult<()> {
        let wrapping_key = [0x42u8; 32];
        let plaintext_key = [0x13u8; 32];
        let header = "k4.local-wrap.pie.";

        let (nonce, mut ciphertext, tag) =
            pie_wrap_local_k2k4(&wrapping_key, &plaintext_key, header)?;

        // Modify ciphertext
        ciphertext[0] ^= 0xff;

        let result = pie_unwrap_local_k2k4(&wrapping_key, &nonce, &ciphertext, &tag, header);

        assert!(matches!(result, Err(PaserkError::AuthenticationFailed)));
        Ok(())
    }

    #[test]
    #[cfg(feature = "k4")]
    fn test_pie_unwrap_local_modified_tag() -> PaserkResult<()> {
        let wrapping_key = [0x42u8; 32];
        let plaintext_key = [0x13u8; 32];
        let header = "k4.local-wrap.pie.";

        let (nonce, ciphertext, mut tag) =
            pie_wrap_local_k2k4(&wrapping_key, &plaintext_key, header)?;

        // Modify tag
        tag[0] ^= 0xff;

        let result = pie_unwrap_local_k2k4(&wrapping_key, &nonce, &ciphertext, &tag, header);

        assert!(matches!(result, Err(PaserkError::AuthenticationFailed)));
        Ok(())
    }

    #[test]
    #[cfg(feature = "k4")]
    fn test_pie_unwrap_local_wrong_header() -> PaserkResult<()> {
        let wrapping_key = [0x42u8; 32];
        let plaintext_key = [0x13u8; 32];
        let header = "k4.local-wrap.pie.";
        let wrong_header = "k4.secret-wrap.pie.";

        let (nonce, ciphertext, tag) = pie_wrap_local_k2k4(&wrapping_key, &plaintext_key, header)?;

        let result = pie_unwrap_local_k2k4(&wrapping_key, &nonce, &ciphertext, &tag, wrong_header);

        assert!(matches!(result, Err(PaserkError::AuthenticationFailed)));
        Ok(())
    }

    #[test]
    #[cfg(feature = "k4")]
    fn test_pie_wrap_produces_different_nonces() -> PaserkResult<()> {
        let wrapping_key = [0x42u8; 32];
        let plaintext_key = [0x13u8; 32];
        let header = "k4.local-wrap.pie.";

        let (nonce1, _, _) = pie_wrap_local_k2k4(&wrapping_key, &plaintext_key, header)?;
        let (nonce2, _, _) = pie_wrap_local_k2k4(&wrapping_key, &plaintext_key, header)?;

        // Nonces should be different (probabilistically)
        assert_ne!(nonce1, nonce2);
        Ok(())
    }

    // =========================================================================
    // K1/K3 PIE Tests
    // =========================================================================

    #[test]
    #[cfg(feature = "k3")]
    fn test_pie_wrap_unwrap_local_k3_roundtrip() -> PaserkResult<()> {
        let wrapping_key = [0x42u8; 32];
        let plaintext_key = [0x13u8; 32];
        let header = "k3.local-wrap.pie.";

        let (nonce, ciphertext, tag) = pie_wrap_local_k1k3(&wrapping_key, &plaintext_key, header)?;

        // Ciphertext should be different from plaintext
        assert_ne!(ciphertext, plaintext_key);

        let unwrapped = pie_unwrap_local_k1k3(&wrapping_key, &nonce, &ciphertext, &tag, header)?;

        assert_eq!(unwrapped, plaintext_key);
        Ok(())
    }

    #[test]
    #[cfg(feature = "k1-insecure")]
    fn test_pie_wrap_unwrap_local_k1_roundtrip() -> PaserkResult<()> {
        let wrapping_key = [0x42u8; 32];
        let plaintext_key = [0x13u8; 32];
        let header = "k1.local-wrap.pie.";

        let (nonce, ciphertext, tag) = pie_wrap_local_k1k3(&wrapping_key, &plaintext_key, header)?;

        // Ciphertext should be different from plaintext
        assert_ne!(ciphertext, plaintext_key);

        let unwrapped = pie_unwrap_local_k1k3(&wrapping_key, &nonce, &ciphertext, &tag, header)?;

        assert_eq!(unwrapped, plaintext_key);
        Ok(())
    }

    #[test]
    #[cfg(feature = "k3")]
    fn test_pie_wrap_unwrap_secret_k3_roundtrip() -> PaserkResult<()> {
        let wrapping_key = [0x42u8; 32];
        let plaintext_key = [0x13u8; 48];
        let header = "k3.secret-wrap.pie.";

        let (nonce, ciphertext, tag) = pie_wrap_secret_k3(&wrapping_key, &plaintext_key, header)?;

        // Ciphertext should be different from plaintext
        assert_ne!(ciphertext, plaintext_key);

        let unwrapped = pie_unwrap_secret_k3(&wrapping_key, &nonce, &ciphertext, &tag, header)?;

        assert_eq!(unwrapped, plaintext_key);
        Ok(())
    }

    #[test]
    #[cfg(feature = "k3")]
    fn test_pie_k1k3_unwrap_wrong_key() -> PaserkResult<()> {
        let wrapping_key = [0x42u8; 32];
        let wrong_key = [0x43u8; 32];
        let plaintext_key = [0x13u8; 32];
        let header = "k3.local-wrap.pie.";

        let (nonce, ciphertext, tag) = pie_wrap_local_k1k3(&wrapping_key, &plaintext_key, header)?;

        let result = pie_unwrap_local_k1k3(&wrong_key, &nonce, &ciphertext, &tag, header);

        assert!(matches!(result, Err(PaserkError::AuthenticationFailed)));
        Ok(())
    }

    #[test]
    #[cfg(feature = "k3")]
    fn test_pie_k1k3_unwrap_modified_tag() -> PaserkResult<()> {
        let wrapping_key = [0x42u8; 32];
        let plaintext_key = [0x13u8; 32];
        let header = "k3.local-wrap.pie.";

        let (nonce, ciphertext, mut tag) =
            pie_wrap_local_k1k3(&wrapping_key, &plaintext_key, header)?;

        // Modify tag
        tag[0] ^= 0xff;

        let result = pie_unwrap_local_k1k3(&wrapping_key, &nonce, &ciphertext, &tag, header);

        assert!(matches!(result, Err(PaserkError::AuthenticationFailed)));
        Ok(())
    }

    #[test]
    #[cfg(feature = "k3")]
    fn test_pie_k1k3_tag_size() {
        // K1/K3 uses HMAC-SHA384 with 48-byte tags
        assert_eq!(PIE_K1K3_TAG_SIZE, 48);
    }

    #[test]
    #[cfg(feature = "k3")]
    fn test_pie_k1k3_produces_different_nonces() -> PaserkResult<()> {
        let wrapping_key = [0x42u8; 32];
        let plaintext_key = [0x13u8; 32];
        let header = "k3.local-wrap.pie.";

        let (nonce1, _, _) = pie_wrap_local_k1k3(&wrapping_key, &plaintext_key, header)?;
        let (nonce2, _, _) = pie_wrap_local_k1k3(&wrapping_key, &plaintext_key, header)?;

        // Nonces should be different (probabilistically)
        assert_ne!(nonce1, nonce2);
        Ok(())
    }
}