mdk-core 0.8.0

A simplified interface to build secure messaging apps on nostr with MLS.
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
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
//! Cryptographic operations for encrypted media
//!
//! This module handles all encryption and decryption operations for media files,
//! including key derivation, nonce generation, and ChaCha20-Poly1305 AEAD operations
//! according to the Marmot protocol specification.

use chacha20poly1305::{
    ChaCha20Poly1305, Nonce,
    aead::{Aead, KeyInit},
};
use hkdf::Hkdf;
use nostr::secp256k1::rand::{RngCore, rngs::OsRng};
use sha2::Sha256;

use mdk_storage_traits::{MdkStorageProvider, Secret};

use crate::encrypted_media::types::EncryptedMediaError;
use crate::{GroupId, MDK};

/// Default scheme version for MIP-04 encryption
pub const DEFAULT_SCHEME_VERSION: &str = "mip04-v2";

/// Check if a scheme version is supported for decryption
///
/// This function determines if the given version string corresponds to a supported
/// encryption scheme. Currently, "mip04-v2" is the standard supported version.
/// "mip04-v1" is NOT supported due to security vulnerabilities.
pub fn is_scheme_version_supported(version: &str) -> bool {
    match version {
        "mip04-v2" => true,
        // mip04-v1 is explicitly unsupported
        // Future versions can be added here
        _ => false,
    }
}

/// Get scheme label bytes from version string
///
/// This function maps version strings to their corresponding scheme labels
/// used in AAD and HKDF contexts. This allows for versioned encryption
/// schemes while maintaining backward compatibility.
fn get_scheme_label(version: &str) -> Result<&[u8], EncryptedMediaError> {
    match version {
        "mip04-v2" => Ok(b"mip04-v2"),
        // Future versions can be added here
        _ => Err(EncryptedMediaError::UnknownSchemeVersion(
            version.to_string(),
        )),
    }
}

/// Build HKDF context for key/nonce derivation with scheme label for domain separation
fn build_hkdf_context(
    scheme_label: &[u8],
    file_hash: &[u8; 32],
    mime_type: &str,
    filename: &str,
    suffix: &[u8],
) -> Vec<u8> {
    let mut context = Vec::new();
    context.extend_from_slice(scheme_label);
    context.push(0x00);
    context.extend_from_slice(file_hash);
    context.push(0x00);
    context.extend_from_slice(mime_type.as_bytes());
    context.push(0x00);
    context.extend_from_slice(filename.as_bytes());
    context.push(0x00);
    context.extend_from_slice(suffix);
    context
}

/// Build AAD (Associated Authenticated Data) for AEAD encryption with scheme label
fn build_aad(
    scheme_label: &[u8],
    file_hash: &[u8; 32],
    mime_type: &str,
    filename: &str,
) -> Vec<u8> {
    let mut aad = Vec::new();
    aad.extend_from_slice(scheme_label);
    aad.push(0x00);
    aad.extend_from_slice(file_hash);
    aad.push(0x00);
    aad.extend_from_slice(mime_type.as_bytes());
    aad.push(0x00);
    aad.extend_from_slice(filename.as_bytes());
    aad
}

/// Derive encryption key from the current epoch's MLS group secret for MIP-04.
///
/// Uses `MLS-Exporter("marmot", "encrypted-media", 32)` per MIP-04 and then derives
/// a per-file key via HKDF:
/// file_key = HKDF-Expand(exporter_secret, SCHEME_LABEL || 0x00 || file_hash_bytes || 0x00 || mime_type_bytes || 0x00 || filename_bytes || 0x00 || "key", 32)
pub fn derive_encryption_key<Storage>(
    mdk: &MDK<Storage>,
    group_id: &GroupId,
    scheme_version: &str,
    original_hash: &[u8; 32],
    mime_type: &str,
    filename: &str,
) -> Result<Secret<[u8; 32]>, EncryptedMediaError>
where
    Storage: MdkStorageProvider,
{
    let exporter_secret = mdk
        .mip04_exporter_secret(group_id)
        .map_err(|_| EncryptedMediaError::GroupNotFound)?;

    derive_encryption_key_with_secret(
        &exporter_secret.secret,
        scheme_version,
        original_hash,
        mime_type,
        filename,
    )
}

/// Derive encryption key from an explicit exporter secret
///
/// This variant accepts a raw exporter secret instead of looking it up.
/// Used by the epoch fallback logic in media decryption, which needs to try
/// multiple historical epoch secrets when the current epoch's key doesn't work.
pub(crate) fn derive_encryption_key_with_secret(
    exporter_secret: &Secret<[u8; 32]>,
    scheme_version: &str,
    original_hash: &[u8; 32],
    mime_type: &str,
    filename: &str,
) -> Result<Secret<[u8; 32]>, EncryptedMediaError> {
    let scheme_label = get_scheme_label(scheme_version)?;
    let context = build_hkdf_context(scheme_label, original_hash, mime_type, filename, b"key");

    let hk = Hkdf::<Sha256>::from_prk(exporter_secret.as_ref()).map_err(|e| {
        EncryptedMediaError::EncryptionFailed {
            reason: format!("Invalid HKDF PRK: {}", e),
        }
    })?;
    let mut key = [0u8; 32];
    hk.expand(&context, &mut key)
        .map_err(|e| EncryptedMediaError::EncryptionFailed {
            reason: format!("Key derivation failed: {}", e),
        })?;

    Ok(Secret::new(key))
}

/// Derive a compatibility-only pre-0.7.1 MIP-04 file key from an explicit exporter secret.
///
/// Unlike [`derive_encryption_key_with_secret`], this uses HKDF extract+expand
/// (`Hkdf::new(None, ...)`) to match the legacy media derivation. Callers should only
/// use this during the temporary migration window when attempting to read old media.
pub(crate) fn derive_legacy_encryption_key_with_secret(
    exporter_secret: &Secret<[u8; 32]>,
    scheme_version: &str,
    original_hash: &[u8; 32],
    mime_type: &str,
    filename: &str,
) -> Result<Secret<[u8; 32]>, EncryptedMediaError> {
    let scheme_label = get_scheme_label(scheme_version)?;
    let context = build_hkdf_context(scheme_label, original_hash, mime_type, filename, b"key");

    let hk = Hkdf::<Sha256>::new(None, exporter_secret.as_ref());
    let mut key = [0u8; 32];
    hk.expand(&context, &mut key)
        .map_err(|e| EncryptedMediaError::EncryptionFailed {
            reason: format!("Key derivation failed: {}", e),
        })?;

    Ok(Secret::new(key))
}

/// Generate a random encryption nonce
///
/// This function generates a cryptographically secure random 96-bit (12-byte) nonce
/// for ChaCha20-Poly1305 encryption. The nonce must be stored with the encrypted data
/// (e.g., in the IMETA tag) and provided during decryption.
pub fn generate_encryption_nonce() -> Secret<[u8; 12]> {
    let mut nonce = [0u8; 12];
    let mut rng = OsRng;
    rng.fill_bytes(&mut nonce);
    Secret::new(nonce)
}

/// Encrypt data using ChaCha20-Poly1305 AEAD with Associated Authenticated Data
///
/// As specified in MIP-04, the AAD includes:
/// aad = SCHEME_LABEL || 0x00 || file_hash_bytes || 0x00 || mime_type_bytes || 0x00 || filename_bytes
pub fn encrypt_data_with_aad(
    data: &[u8],
    key: &Secret<[u8; 32]>,
    nonce: &Secret<[u8; 12]>,
    scheme_version: &str,
    file_hash: &[u8; 32],
    mime_type: &str,
    filename: &str,
) -> Result<Vec<u8>, EncryptedMediaError> {
    let cipher = ChaCha20Poly1305::new_from_slice(key.as_ref()).map_err(|e| {
        EncryptedMediaError::EncryptionFailed {
            reason: format!("Failed to create cipher: {}", e),
        }
    })?;

    let nonce_arr = Nonce::from_slice(nonce.as_ref());

    let scheme_label = get_scheme_label(scheme_version)?;
    let aad = build_aad(scheme_label, file_hash, mime_type, filename);

    cipher
        .encrypt(
            nonce_arr,
            chacha20poly1305::aead::Payload {
                msg: data,
                aad: &aad,
            },
        )
        .map_err(|e| EncryptedMediaError::EncryptionFailed {
            reason: format!("Encryption failed: {}", e),
        })
}

/// Decrypt data using ChaCha20-Poly1305 AEAD with Associated Authenticated Data
///
/// As specified in MIP-04, the AAD includes:
/// aad = SCHEME_LABEL || 0x00 || file_hash_bytes || 0x00 || mime_type_bytes || 0x00 || filename_bytes
///
/// This function attempts decryption with the provided scheme version. If decryption
/// fails, it may be due to a version mismatch. The caller should ensure the correct
/// scheme_version is provided from the MediaReference parsed from the IMETA tag.
pub fn decrypt_data_with_aad(
    encrypted_data: &[u8],
    key: &Secret<[u8; 32]>,
    nonce: &Secret<[u8; 12]>,
    scheme_version: &str,
    file_hash: &[u8; 32],
    mime_type: &str,
    filename: &str,
) -> Result<Vec<u8>, EncryptedMediaError> {
    let cipher = ChaCha20Poly1305::new_from_slice(key.as_ref()).map_err(|e| {
        EncryptedMediaError::DecryptionFailed {
            reason: format!("Failed to create cipher: {}", e),
        }
    })?;

    let nonce_arr = Nonce::from_slice(nonce.as_ref());

    let scheme_label = get_scheme_label(scheme_version)?;
    let aad = build_aad(scheme_label, file_hash, mime_type, filename);

    cipher
        .decrypt(
            nonce_arr,
            chacha20poly1305::aead::Payload {
                msg: encrypted_data,
                aad: &aad,
            },
        )
        .map_err(|e| EncryptedMediaError::DecryptionFailed {
            reason: format!("Decryption failed: {}", e),
        })
}

#[cfg(test)]
mod tests {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    use sha2::Digest;

    use mdk_memory_storage::MdkMemoryStorage;

    use super::*;

    fn create_test_mdk() -> MDK<MdkMemoryStorage> {
        MDK::new(MdkMemoryStorage::default())
    }

    #[test]
    fn test_errors_without_group() {
        let mdk = create_test_mdk();
        let group_id = GroupId::from_slice(&[1, 2, 3, 4]);

        let original_data =
            b"This is test image data that should be encrypted and decrypted properly";
        let mime_type = "image/jpeg";
        let filename = "test.jpg";

        let original_hash: [u8; 32] = Sha256::digest(original_data).into();

        // Test key derivation (will fail without a proper group, but we can test the logic)
        let key_result = derive_encryption_key(
            &mdk,
            &group_id,
            DEFAULT_SCHEME_VERSION,
            &original_hash,
            mime_type,
            filename,
        );

        // Should fail gracefully since we don't have a real MLS group
        assert!(key_result.is_err());

        // Verify the error is the expected "GroupNotFound" error
        if let Err(EncryptedMediaError::GroupNotFound) = key_result {
            // Expected behavior
        } else {
            panic!("Expected GroupNotFound error for key derivation");
        }
    }

    #[test]
    fn test_encrypt_decrypt_with_known_key() {
        // Test encryption/decryption with a known key and nonce
        let key = Secret::new([0x42u8; 32]);
        let nonce = Secret::new([0x24u8; 12]);
        let original_data = b"Hello, encrypted world!";
        let file_hash = [0x01u8; 32];
        let mime_type = "image/jpeg";
        let filename = "test.jpg";

        // Encrypt the data
        let encrypted_result = encrypt_data_with_aad(
            original_data,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        );
        assert!(encrypted_result.is_ok());
        let encrypted_data = encrypted_result.unwrap();

        // Verify encrypted data is different from original
        assert_ne!(encrypted_data.as_slice(), original_data);
        assert!(encrypted_data.len() > original_data.len()); // Should include auth tag

        // Decrypt the data
        let decrypted_result = decrypt_data_with_aad(
            &encrypted_data,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        );
        assert!(decrypted_result.is_ok());
        let decrypted_data = decrypted_result.unwrap();

        // Verify decrypted data matches original
        assert_eq!(decrypted_data.as_slice(), original_data);
    }

    #[test]
    fn test_mip04_file_key_uses_hkdf_expand_with_exporter_secret_as_prk() {
        let exporter_secret = Secret::new([0x11u8; 32]);
        let file_hash = [0x22u8; 32];
        let mime_type = "image/jpeg";
        let filename = "photo.jpg";

        let derived = derive_encryption_key_with_secret(
            &exporter_secret,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        )
        .expect("MIP-04 key derivation should succeed");

        let scheme_label = get_scheme_label(DEFAULT_SCHEME_VERSION).unwrap();
        let context = build_hkdf_context(scheme_label, &file_hash, mime_type, filename, b"key");

        let hk_expand_only = Hkdf::<Sha256>::from_prk(exporter_secret.as_ref())
            .expect("32-byte exporter secret must be a valid HKDF PRK");
        let mut expected = [0u8; 32];
        hk_expand_only
            .expand(&context, &mut expected)
            .expect("HKDF expand-only should succeed");

        let hk_extract_then_expand = Hkdf::<Sha256>::new(None, exporter_secret.as_ref());
        let mut old_style = [0u8; 32];
        hk_extract_then_expand
            .expand(&context, &mut old_style)
            .expect("HKDF extract+expand should succeed");

        assert_eq!(*derived, expected);
        assert_ne!(expected, old_style);
    }

    #[test]
    fn test_encrypt_decrypt_with_different_aad() {
        // Test that changing AAD components causes decryption to fail
        let key = Secret::new([0x42u8; 32]);
        let nonce = Secret::new([0x24u8; 12]);
        let original_data = b"Hello, encrypted world!";
        let file_hash = [0x01u8; 32];
        let mime_type = "image/jpeg";
        let filename = "test.jpg";

        // Encrypt with original parameters
        let encrypted_data = encrypt_data_with_aad(
            original_data,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        )
        .unwrap();

        // Try to decrypt with different file hash (should fail)
        let different_hash = [0x02u8; 32];
        let result = decrypt_data_with_aad(
            &encrypted_data,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &different_hash,
            mime_type,
            filename,
        );
        assert!(result.is_err());

        // Try to decrypt with different MIME type (should fail)
        let result = decrypt_data_with_aad(
            &encrypted_data,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            "image/png",
            filename,
        );
        assert!(result.is_err());

        // Try to decrypt with different filename (should fail)
        let result = decrypt_data_with_aad(
            &encrypted_data,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            "different.jpg",
        );
        assert!(result.is_err());

        // Decrypt with correct parameters (should succeed)
        let result = decrypt_data_with_aad(
            &encrypted_data,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        );
        assert!(result.is_ok());
        assert_eq!(result.unwrap().as_slice(), original_data);
    }

    #[test]
    fn test_encrypt_decrypt_with_wrong_key() {
        // Test that using wrong key causes decryption to fail
        let key = Secret::new([0x42u8; 32]);
        let wrong_key = Secret::new([0x43u8; 32]);
        let nonce = Secret::new([0x24u8; 12]);
        let original_data = b"Hello, encrypted world!";
        let file_hash = [0x01u8; 32];
        let mime_type = "image/jpeg";
        let filename = "test.jpg";

        // Encrypt with original key
        let encrypted_data = encrypt_data_with_aad(
            original_data,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        )
        .unwrap();

        // Try to decrypt with wrong key (should fail)
        let result = decrypt_data_with_aad(
            &encrypted_data,
            &wrong_key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        );
        assert!(result.is_err());
        assert!(matches!(
            result,
            Err(EncryptedMediaError::DecryptionFailed { .. })
        ));
    }

    #[test]
    fn test_encrypt_decrypt_with_wrong_nonce() {
        // Test that using wrong nonce causes decryption to fail
        let key = Secret::new([0x42u8; 32]);
        let nonce = Secret::new([0x24u8; 12]);
        let wrong_nonce = Secret::new([0x25u8; 12]);
        let original_data = b"Hello, encrypted world!";
        let file_hash = [0x01u8; 32];
        let mime_type = "image/jpeg";
        let filename = "test.jpg";

        // Encrypt with original nonce
        let encrypted_data = encrypt_data_with_aad(
            original_data,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        )
        .unwrap();

        // Try to decrypt with wrong nonce (should fail)
        let result = decrypt_data_with_aad(
            &encrypted_data,
            &key,
            &wrong_nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        );
        assert!(result.is_err());
        assert!(matches!(
            result,
            Err(EncryptedMediaError::DecryptionFailed { .. })
        ));
    }

    #[test]
    fn test_encrypt_empty_data() {
        // Test encryption of empty data
        let key = Secret::new([0x42u8; 32]);
        let nonce = Secret::new([0x24u8; 12]);
        let empty_data = b"";
        let file_hash = [0x01u8; 32];
        let mime_type = "image/jpeg";
        let filename = "empty.jpg";

        // Encrypt empty data
        let encrypted_result = encrypt_data_with_aad(
            empty_data,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        );
        assert!(encrypted_result.is_ok());
        let encrypted_data = encrypted_result.unwrap();

        // Should still have auth tag even for empty data
        assert!(!encrypted_data.is_empty());

        // Decrypt and verify
        let decrypted_result = decrypt_data_with_aad(
            &encrypted_data,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        );
        assert!(decrypted_result.is_ok());
        assert_eq!(decrypted_result.unwrap().as_slice(), empty_data);
    }

    #[test]
    fn test_aad_construction() {
        // Test that AAD is constructed correctly by verifying different components
        // cause different encrypted outputs
        let key = Secret::new([0x42u8; 32]);
        let nonce = Secret::new([0x24u8; 12]);
        let data = b"test data";
        let file_hash = [0x01u8; 32];

        // Encrypt with first set of AAD components
        let encrypted1 = encrypt_data_with_aad(
            data,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            "image/jpeg",
            "photo.jpg",
        )
        .unwrap();

        // Encrypt with different MIME type
        let encrypted2 = encrypt_data_with_aad(
            data,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            "image/png",
            "photo.jpg",
        )
        .unwrap();

        // Encrypt with different filename
        let encrypted3 = encrypt_data_with_aad(
            data,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            "image/jpeg",
            "image.jpg",
        )
        .unwrap();

        // All encrypted outputs should be different due to different AAD
        assert_ne!(encrypted1, encrypted2);
        assert_ne!(encrypted1, encrypted3);
        assert_ne!(encrypted2, encrypted3);
    }

    #[test]
    fn test_secret_accessors() {
        // Test that Secret properly wraps values and can be accessed
        let original_key = [0xAAu8; 32];
        let secret_key = Secret::new(original_key);

        // Verify we can access the secret value
        assert_eq!(secret_key.as_ref(), &original_key);
        assert_eq!(*secret_key, original_key);

        // Test cloning preserves the value
        let cloned = secret_key.clone();
        assert_eq!(*cloned, original_key);
        assert_eq!(*secret_key, original_key);

        // Test mut access
        let mut mut_secret = Secret::new([0xBBu8; 32]);
        *mut_secret.as_mut() = [0xCCu8; 32];
        assert_eq!(*mut_secret, [0xCCu8; 32]);
    }

    #[test]
    fn test_secret_debug_format() {
        // Test that Debug formatting doesn't leak secrets
        let secret_key = Secret::new([0xAAu8; 32]);
        let debug_str = format!("{:?}", secret_key);
        assert_eq!(debug_str, "Secret(***)");
        assert!(!debug_str.contains("AA"));
    }

    #[test]
    fn test_decrypt_corrupted_data() {
        // Test decryption with corrupted encrypted data
        let key = Secret::new([0x42u8; 32]);
        let nonce = Secret::new([0x24u8; 12]);
        let original_data = b"Hello, encrypted world!";
        let file_hash = [0x01u8; 32];
        let mime_type = "image/jpeg";
        let filename = "test.jpg";

        // Encrypt valid data
        let mut encrypted_data = encrypt_data_with_aad(
            original_data,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        )
        .unwrap();

        // Corrupt the encrypted data (flip a bit)
        encrypted_data[0] ^= 0xFF;

        // Decryption should fail
        let result = decrypt_data_with_aad(
            &encrypted_data,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        );
        assert!(result.is_err());
        assert!(matches!(
            result,
            Err(EncryptedMediaError::DecryptionFailed { .. })
        ));
    }

    #[test]
    fn test_scheme_version_mismatch_causes_decryption_failure() {
        // Test that encrypting with one scheme version and decrypting with another fails
        let key = Secret::new([0x42u8; 32]);
        let nonce = Secret::new([0x24u8; 12]);
        let original_data = b"Test data for version mismatch";
        let file_hash = [0x01u8; 32];
        let mime_type = "image/jpeg";
        let filename = "test.jpg";

        // Encrypt with default scheme version
        let encrypted_data = encrypt_data_with_aad(
            original_data,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        )
        .unwrap();

        // Try to decrypt with a different scheme version ("mip04-v1")
        // This should produce different AAD and cause decryption failure
        let result = decrypt_data_with_aad(
            &encrypted_data,
            &key,
            &nonce,
            "mip04-v1", // Mismatched version
            &file_hash,
            mime_type,
            filename,
        );
        assert!(result.is_err());
        // mip04-v1 is no longer supported, so we expect UnknownSchemeVersion
        match result {
            Err(EncryptedMediaError::UnknownSchemeVersion(v)) => assert_eq!(v, "mip04-v1"),
            Err(e) => panic!("Expected UnknownSchemeVersion, got {:?}", e),
            Ok(_) => panic!("Should have failed"),
        }
    }

    #[test]
    fn test_decrypt_too_short_data() {
        // Test decryption with data that's too short to be valid
        let key = Secret::new([0x42u8; 32]);
        let nonce = Secret::new([0x24u8; 12]);
        let file_hash = [0x01u8; 32];
        let mime_type = "image/jpeg";
        let filename = "test.jpg";

        // Try to decrypt data that's too short (less than auth tag size)
        let too_short = vec![0u8; 5];

        let result = decrypt_data_with_aad(
            &too_short,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        );
        assert!(result.is_err());
        assert!(matches!(
            result,
            Err(EncryptedMediaError::DecryptionFailed { .. })
        ));
    }

    #[test]
    fn test_encrypt_large_data() {
        // Test encryption/decryption of large data
        let key = Secret::new([0x42u8; 32]);
        let nonce = Secret::new([0x24u8; 12]);
        let large_data = vec![0xABu8; 1024 * 1024]; // 1MB
        let file_hash = [0x01u8; 32];
        let mime_type = "application/octet-stream";
        let filename = "large.bin";

        // Encrypt large data
        let encrypted_result = encrypt_data_with_aad(
            &large_data,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        );
        assert!(encrypted_result.is_ok());
        let encrypted_data = encrypted_result.unwrap();

        // Verify encrypted data is larger (includes auth tag)
        assert!(encrypted_data.len() > large_data.len());

        // Decrypt and verify
        let decrypted_result = decrypt_data_with_aad(
            &encrypted_data,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        );
        assert!(decrypted_result.is_ok());
        assert_eq!(decrypted_result.unwrap(), large_data);
    }

    #[test]
    fn test_encrypt_special_characters() {
        // Test encryption with special characters in filename and MIME type
        let key = Secret::new([0x42u8; 32]);
        let nonce = Secret::new([0x24u8; 12]);
        let data = b"test data";
        let file_hash = [0x01u8; 32];

        // Test with special characters in filename
        let encrypted1 = encrypt_data_with_aad(
            data,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            "image/jpeg",
            "test file (1).jpg",
        )
        .unwrap();

        // Test with unicode characters
        let encrypted2 = encrypt_data_with_aad(
            data,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            "image/jpeg",
            "тест.jpg",
        )
        .unwrap();

        // Test with complex MIME type
        let encrypted3 = encrypt_data_with_aad(
            data,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            "document.docx",
        )
        .unwrap();

        // All should encrypt successfully
        assert!(!encrypted1.is_empty());
        assert!(!encrypted2.is_empty());
        assert!(!encrypted3.is_empty());

        // Verify decryption works
        let decrypted1 = decrypt_data_with_aad(
            &encrypted1,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            "image/jpeg",
            "test file (1).jpg",
        )
        .unwrap();
        assert_eq!(decrypted1, data);

        let decrypted2 = decrypt_data_with_aad(
            &encrypted2,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            "image/jpeg",
            "тест.jpg",
        )
        .unwrap();
        assert_eq!(decrypted2, data);
    }

    #[test]
    fn test_multiple_encryption_cycles() {
        // Test multiple encryption/decryption cycles (fresh nonce per encryption)
        let key = Secret::new([0x42u8; 32]);
        let file_hash = [0x01u8; 32];
        let mime_type = "image/jpeg";
        let filename = "test.jpg";

        let data1 = b"First encryption";
        let data2 = b"Second encryption";
        let data3 = b"Third encryption";

        let nonce1 = generate_encryption_nonce();
        let nonce2 = generate_encryption_nonce();
        let nonce3 = generate_encryption_nonce();

        let enc1 = encrypt_data_with_aad(
            data1,
            &key,
            &nonce1,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        )
        .unwrap();
        let enc2 = encrypt_data_with_aad(
            data2,
            &key,
            &nonce2,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        )
        .unwrap();
        let enc3 = encrypt_data_with_aad(
            data3,
            &key,
            &nonce3,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        )
        .unwrap();

        // All should decrypt correctly
        let dec1 = decrypt_data_with_aad(
            &enc1,
            &key,
            &nonce1,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        )
        .unwrap();
        let dec2 = decrypt_data_with_aad(
            &enc2,
            &key,
            &nonce2,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        )
        .unwrap();
        let dec3 = decrypt_data_with_aad(
            &enc3,
            &key,
            &nonce3,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            mime_type,
            filename,
        )
        .unwrap();

        assert_eq!(dec1, data1);
        assert_eq!(dec2, data2);
        assert_eq!(dec3, data3);
    }

    #[test]
    fn test_error_messages() {
        // Test that error messages are properly formatted
        let mdk = create_test_mdk();
        let group_id = GroupId::from_slice(&[1, 2, 3, 4]);
        let file_hash = [0x01u8; 32];

        // Test GroupNotFound error message
        let key_result = derive_encryption_key(
            &mdk,
            &group_id,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            "image/jpeg",
            "test.jpg",
        );
        assert!(matches!(
            key_result,
            Err(EncryptedMediaError::GroupNotFound)
        ));

        // Test DecryptionFailed error message format
        let key = Secret::new([0x42u8; 32]);
        let nonce = Secret::new([0x24u8; 12]);
        let corrupted = vec![0u8; 10];

        let result = decrypt_data_with_aad(
            &corrupted,
            &key,
            &nonce,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            "image/jpeg",
            "test.jpg",
        );
        match result {
            Err(EncryptedMediaError::DecryptionFailed { reason }) => {
                assert!(!reason.is_empty());
                assert!(reason.contains("Decryption failed"));
            }
            other => panic!("Expected DecryptionFailed, got {:?}", other),
        }
    }

    #[test]
    fn test_secret_access_methods() {
        // Test all Secret access methods (as_ref, as_mut, deref, deref_mut)
        let mut secret_key = Secret::new([0xAAu8; 32]);
        let original = [0xAAu8; 32];

        // Test as_ref
        assert_eq!(secret_key.as_ref(), &original);

        // Test deref
        assert_eq!(*secret_key, original);

        // Test as_mut
        *secret_key.as_mut() = [0xBBu8; 32];
        assert_eq!(*secret_key, [0xBBu8; 32]);

        // Test deref_mut
        *secret_key = [0xCCu8; 32];
        assert_eq!(*secret_key, [0xCCu8; 32]);
    }

    #[test]
    fn test_secret_equality() {
        // Test Secret equality and hashing
        let secret1 = Secret::new([0xAAu8; 32]);
        let secret2 = Secret::new([0xAAu8; 32]);
        let secret3 = Secret::new([0xBBu8; 32]);

        // Equal secrets should be equal
        assert_eq!(secret1, secret2);
        assert_ne!(secret1, secret3);

        // Test hashing (equal secrets should have same hash)
        let mut hasher1 = DefaultHasher::new();
        secret1.hash(&mut hasher1);
        let hash1 = hasher1.finish();

        let mut hasher2 = DefaultHasher::new();
        secret2.hash(&mut hasher2);
        let hash2 = hasher2.finish();

        assert_eq!(hash1, hash2);
    }

    #[test]
    fn test_key_derivation_error() {
        // Test key derivation error path
        let mdk = create_test_mdk();
        let group_id = GroupId::from_slice(&[1, 2, 3, 4]);
        let file_hash = [0x01u8; 32];

        let result = derive_encryption_key(
            &mdk,
            &group_id,
            DEFAULT_SCHEME_VERSION,
            &file_hash,
            "image/jpeg",
            "test.jpg",
        );
        assert!(result.is_err());
        assert!(matches!(result, Err(EncryptedMediaError::GroupNotFound)));
    }

    #[test]
    fn test_secret_ordering() {
        // Test Secret ordering (PartialOrd, Ord)
        let secret1 = Secret::new([0xAAu8; 32]);
        let secret2 = Secret::new([0xBBu8; 32]);
        let secret3 = Secret::new([0xAAu8; 32]);

        // Test PartialOrd
        assert!(secret1 < secret2);
        assert!(secret2 > secret1);
        assert!(secret1 <= secret3);
        assert!(secret1 >= secret3);
    }

    #[test]
    fn test_unknown_scheme_version() {
        let result = get_scheme_label("unknown-version");
        assert!(result.is_err());
        match result {
            Err(EncryptedMediaError::UnknownSchemeVersion(v)) => assert_eq!(v, "unknown-version"),
            _ => panic!("Expected UnknownSchemeVersion error"),
        }
    }
}