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
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
//! [JSON Web Encryption](https://tools.ietf.org/html/rfc7516)
//!
//! This module contains code to implement JWE, the JOSE standard to encrypt arbitrary payloads.
//! Most commonly, JWE is used to encrypt a JWS payload, which is a signed JWT. For most common use,
//! you will want to look at the  [`Compact`](enum.Compact.html) enum.
use std::fmt;

use data_encoding::BASE64URL_NOPAD;

use serde::de::{self, DeserializeOwned};
use serde::{self, Deserialize, Deserializer, Serialize, Serializer};

use crate::errors::{DecodeError, Error, ValidationError};
use crate::jwa::{
    self, ContentEncryptionAlgorithm, EncryptionOptions, EncryptionResult, KeyManagementAlgorithm,
};
use crate::jwk;
use crate::{CompactJson, CompactPart, Empty};

#[derive(Debug, Eq, PartialEq, Clone)]
/// Compression algorithm applied to plaintext before encryption.
pub enum CompressionAlgorithm {
    /// DEFLATE algorithm defined in [RFC 1951](https://tools.ietf.org/html/rfc1951)
    Deflate,
    /// Other user-defined algorithm
    Other(String),
}

impl Serialize for CompressionAlgorithm {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let string = match *self {
            CompressionAlgorithm::Deflate => "DEF",
            CompressionAlgorithm::Other(ref other) => other,
        };

        serializer.serialize_str(string)
    }
}

impl<'de> Deserialize<'de> for CompressionAlgorithm {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct CompressionAlgorithmVisitor;
        impl<'de> de::Visitor<'de> for CompressionAlgorithmVisitor {
            type Value = CompressionAlgorithm;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                write!(formatter, "a string")
            }

            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(match v {
                    "DEF" => CompressionAlgorithm::Deflate,
                    other => CompressionAlgorithm::Other(other.to_string()),
                })
            }
        }

        deserializer.deserialize_string(CompressionAlgorithmVisitor)
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
/// Registered JWE header fields.
/// The fields are defined by [RFC 7516#4.1](https://tools.ietf.org/html/rfc7516#section-4.1)
pub struct RegisteredHeader {
    /// Algorithm used to encrypt or determine the value of the Content Encryption Key
    #[serde(rename = "alg")]
    pub cek_algorithm: KeyManagementAlgorithm,

    /// Content encryption algorithm used to perform authenticated encryption
    /// on the plaintext to produce the ciphertext and the Authentication Tag
    #[serde(rename = "enc")]
    pub enc_algorithm: ContentEncryptionAlgorithm,

    /// Compression algorithm applied to plaintext before encryption, if any.
    /// Compression is not supported at the moment.
    /// _Must only appear in integrity protected header._
    #[serde(rename = "zip", skip_serializing_if = "Option::is_none")]
    pub compression_algorithm: Option<CompressionAlgorithm>,

    /// Media type of the complete JWE. Serialized to `typ`.
    /// Defined in [RFC7519#5.1](https://tools.ietf.org/html/rfc7519#section-5.1) and additionally
    /// [RFC7515#4.1.9](https://tools.ietf.org/html/rfc7515#section-4.1.9).
    /// The "typ" value "JOSE" can be used by applications to indicate that
    /// this object is a JWS or JWE using the JWS Compact Serialization or
    /// the JWE Compact Serialization.  The "typ" value "JOSE+JSON" can be
    /// used by applications to indicate that this object is a JWS or JWE
    /// using the JWS JSON Serialization or the JWE JSON Serialization.
    /// Other type values can also be used by applications.
    #[serde(rename = "typ", skip_serializing_if = "Option::is_none")]
    pub media_type: Option<String>,

    /// Content Type of the secured payload.
    /// Typically used to indicate the presence of a nested JOSE object which is signed or encrypted.
    /// Serialized to `cty`.
    /// Defined in [RFC7519#5.2](https://tools.ietf.org/html/rfc7519#section-5.2) and additionally
    /// [RFC7515#4.1.10](https://tools.ietf.org/html/rfc7515#section-4.1.10).
    #[serde(rename = "cty", skip_serializing_if = "Option::is_none")]
    pub content_type: Option<String>,

    /// The JSON Web Key Set URL. This is currently not implemented (correctly).
    /// Serialized to `jku`.
    /// Defined in [RFC7515#4.1.2](https://tools.ietf.org/html/rfc7515#section-4.1.2).
    #[serde(rename = "jku", skip_serializing_if = "Option::is_none")]
    pub web_key_url: Option<String>,

    /// The JSON Web Key. This is currently not implemented (correctly).
    /// Serialized to `jwk`.
    /// Defined in [RFC7515#4.1.3](https://tools.ietf.org/html/rfc7515#section-4.1.3).
    #[serde(rename = "jwk", skip_serializing_if = "Option::is_none")]
    pub web_key: Option<String>,

    /// The Key ID. This is currently not implemented (correctly).
    /// Serialized to `kid`.
    /// Defined in [RFC7515#4.1.3](https://tools.ietf.org/html/rfc7515#section-4.1.3).
    #[serde(rename = "kid", skip_serializing_if = "Option::is_none")]
    pub key_id: Option<String>,

    /// X.509 Public key cerfificate URL. This is currently not implemented (correctly).
    /// Serialized to `x5u`.
    /// Defined in [RFC7515#4.1.5](https://tools.ietf.org/html/rfc7515#section-4.1.5).
    #[serde(rename = "x5u", skip_serializing_if = "Option::is_none")]
    pub x509_url: Option<String>,

    /// X.509 public key certificate chain. This is currently not implemented (correctly).
    /// Serialized to `x5c`.
    /// Defined in [RFC7515#4.1.6](https://tools.ietf.org/html/rfc7515#section-4.1.6).
    #[serde(rename = "x5c", skip_serializing_if = "Option::is_none")]
    pub x509_chain: Option<Vec<String>>,

    /// X.509 Certificate thumbprint. This is currently not implemented (correctly).
    /// Also not implemented, is the SHA-256 thumbprint variant of this header.
    /// Serialized to `x5t`.
    /// Defined in [RFC7515#4.1.7](https://tools.ietf.org/html/rfc7515#section-4.1.7).
    // TODO: How to make sure the headers are mutually exclusive?
    #[serde(rename = "x5t", skip_serializing_if = "Option::is_none")]
    pub x509_fingerprint: Option<String>,

    /// List of critical extended headers.
    /// This is currently not implemented (correctly).
    /// Serialized to `crit`.
    /// Defined in [RFC7515#4.1.11](https://tools.ietf.org/html/rfc7515#section-4.1.11).
    #[serde(rename = "crit", skip_serializing_if = "Option::is_none")]
    pub critical: Option<Vec<String>>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
/// Headers specific to the Key management algorithm used. Users should typically not construct these fields as they
/// will be filled in automatically when encrypting and stripped when decrypting
pub struct CekAlgorithmHeader {
    /// Header for AES GCM Keywrap algorithm.
    /// The initialization vector, or nonce used in the encryption
    #[serde(rename = "iv", skip_serializing_if = "Option::is_none")]
    pub nonce: Option<Vec<u8>>,

    /// Header for AES GCM Keywrap algorithm.
    /// The authentication tag resulting from the encryption
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tag: Option<Vec<u8>>,
}

/// JWE Header, consisting of the registered fields and other custom fields
#[derive(Debug, Eq, PartialEq, Clone, Default, Serialize, Deserialize)]
pub struct Header<T> {
    /// Registered header fields
    #[serde(flatten)]
    pub registered: RegisteredHeader,
    /// Key management algorithm specific headers
    #[serde(flatten)]
    pub cek_algorithm: CekAlgorithmHeader,
    /// Private header fields
    #[serde(flatten)]
    pub private: T,
}

impl<T: Serialize + DeserializeOwned> CompactJson for Header<T> {}

impl<T: Serialize + DeserializeOwned> Header<T> {
    /// Update CEK algorithm specific header fields based on a CEK encryption result
    fn update_cek_algorithm(&mut self, encrypted: &EncryptionResult) {
        if !encrypted.nonce.is_empty() {
            self.cek_algorithm.nonce = Some(encrypted.nonce.clone());
        }

        if !encrypted.tag.is_empty() {
            self.cek_algorithm.tag = Some(encrypted.tag.clone());
        }
    }

    /// Extract the relevant fields from the header to build an `EncryptionResult` and strip them from the header
    fn extract_cek_encryption_result(&mut self, encrypted_payload: &[u8]) -> EncryptionResult {
        let result = EncryptionResult {
            encrypted: encrypted_payload.to_vec(),
            nonce: self.cek_algorithm.nonce.clone().unwrap_or_default(),
            tag: self.cek_algorithm.tag.clone().unwrap_or_default(),
            ..Default::default()
        };

        self.cek_algorithm = Default::default();
        result
    }
}

impl Header<Empty> {
    /// Convenience function to create a header with only registered headers
    pub fn from_registered_header(registered: RegisteredHeader) -> Self {
        Self {
            registered,
            ..Default::default()
        }
    }
}

impl From<RegisteredHeader> for Header<Empty> {
    fn from(registered: RegisteredHeader) -> Self {
        Self::from_registered_header(registered)
    }
}

/// Compact representation of a JWE, or an encrypted JWT
///
/// This representation contains a payload of type `T` with custom headers provided by type `H`.
/// In general you should use a JWE with a JWS. That is, you should sign your JSON Web Token to
/// create a JWS, and then encrypt the signed JWS.
///
/// # Nonce/Initialization Vectors for AES GCM encryption
///
/// When encrypting tokens with AES GCM, you must take care _not to reuse_ the nonce for the same
/// key. You can keep track of this by simply treating the nonce as a 96 bit counter and
/// incrementing it every time you encrypt something new.
///
/// # Examples
/// ## Encrypting a JWS/JWT
/// See the example code in the [`biscuit::JWE`](../type.JWE.html) type alias.
///
/// ## Encrypting a string payload with A256GCMKW and A256GCM
/// ```
/// use std::str;
/// use biscuit::Empty;
/// use biscuit::jwk::JWK;
/// use biscuit::jwe;
/// use biscuit::jwa::{EncryptionOptions, KeyManagementAlgorithm, ContentEncryptionAlgorithm};
///
/// # #[allow(unused_assignments)]
/// # fn main() {
/// let payload = "The true sign of intelligence is not knowledge but imagination.";
/// // You would usually have your own AES key for this, but we will use a zeroed key as an example
/// let key: JWK<Empty> = JWK::new_octet_key(&vec![0; 256 / 8], Default::default());
///
/// // Construct the JWE
/// let jwe = jwe::Compact::new_decrypted(
///     From::from(jwe::RegisteredHeader {
///         cek_algorithm: KeyManagementAlgorithm::A256GCMKW,
///         enc_algorithm: ContentEncryptionAlgorithm::A256GCM,
///         ..Default::default()
///     }),
///     payload.as_bytes().to_vec(),
/// );
///
/// // We need to create an `EncryptionOptions` with a nonce for AES GCM encryption.
/// // You must take care NOT to reuse the nonce. You can simply treat the nonce as a 96 bit
/// // counter that is incremented after every use
/// let mut nonce_counter = num_bigint::BigUint::from_bytes_le(&vec![0; 96 / 8]);
/// // Make sure it's no more than 96 bits!
/// assert!(nonce_counter.bits() <= 96);
/// let mut nonce_bytes = nonce_counter.to_bytes_le();
/// // We need to ensure it is exactly 96 bits
/// nonce_bytes.resize(96/8, 0);
/// let options = EncryptionOptions::AES_GCM { nonce: nonce_bytes };
///
/// // Encrypt
/// let encrypted_jwe = jwe.encrypt(&key, &options).unwrap();
///
/// // Decrypt
/// let decrypted_jwe = encrypted_jwe
///     .decrypt(
///         &key,
///         KeyManagementAlgorithm::A256GCMKW,
///         ContentEncryptionAlgorithm::A256GCM,
///     )
///     .unwrap();
///
/// let decrypted_payload: &Vec<u8> = decrypted_jwe.payload().unwrap();
/// let decrypted_str = str::from_utf8(&*decrypted_payload).unwrap();
/// assert_eq!(decrypted_str, payload);
///
/// // Don't forget to increment the nonce!
/// nonce_counter = nonce_counter + 1u8;
/// # }
/// ```
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Compact<T, H> {
    /// Decrypted form of the JWE.
    /// This variant cannot be serialized or deserialized and will return an error.
    #[serde(skip_serializing)]
    #[serde(skip_deserializing)]
    Decrypted {
        /// Embedded header
        header: Header<H>,
        /// Payload, usually a signed/unsigned JWT
        payload: T,
    },
    /// Encrypted JWT. Use this form to send to your clients
    Encrypted(crate::Compact),
}

impl<T, H> Compact<T, H>
where
    T: CompactPart,
    H: Serialize + DeserializeOwned + Clone,
{
    /// Create a new encrypted JWE
    pub fn new_decrypted(header: Header<H>, payload: T) -> Self {
        Compact::Decrypted { header, payload }
    }

    /// Create a new encrypted JWE
    pub fn new_encrypted(token: &str) -> Self {
        Compact::Encrypted(crate::Compact::decode(token))
    }

    /// Consumes self and encrypt it. If the token is already encrypted, this is a no-op.
    ///
    /// You will need to provide a `jwa::EncryptionOptions` that will differ based on your chosen
    /// algorithms.
    ///
    /// If your `cek_algorithm` is not `dir` or direct, the options provided will be used to
    /// encrypt your content encryption key.
    ///
    /// If your `cek_algorithm` is `dir` or Direct, then the options will be used to encrypt
    /// your content directly.
    pub fn into_encrypted<K: Serialize + DeserializeOwned>(
        self,
        key: &jwk::JWK<K>,
        options: &EncryptionOptions,
    ) -> Result<Self, Error> {
        match self {
            Compact::Encrypted(_) => Ok(self),
            Compact::Decrypted { .. } => self.encrypt(key, options),
        }
    }

    /// Encrypt an Decrypted JWE.
    ///
    /// You will need to provide a `jwa::EncryptionOptions` that will differ based on your chosen
    /// algorithms.
    ///
    /// If your `cek_algorithm` is not `dir` or direct, the options provided will be used to
    /// encrypt your content encryption key.
    ///
    /// If your `cek_algorithm` is `dir` or Direct, then the options will be used to encrypt
    /// your content directly.
    pub fn encrypt<K: Serialize + DeserializeOwned>(
        &self,
        key: &jwk::JWK<K>,
        options: &EncryptionOptions,
    ) -> Result<Self, Error> {
        match *self {
            Compact::Encrypted(_) => Err(Error::UnsupportedOperation),
            Compact::Decrypted {
                ref header,
                ref payload,
            } => {
                use std::borrow::Cow;

                // Resolve encryption option
                let (key_option, content_option): (_, Cow<'_, _>) =
                    match header.registered.cek_algorithm {
                        KeyManagementAlgorithm::DirectSymmetricKey => {
                            (jwa::NONE_ENCRYPTION_OPTIONS, Cow::Borrowed(options))
                        }
                        _ => (
                            options,
                            Cow::Owned(
                                header
                                    .registered
                                    .enc_algorithm
                                    .random_encryption_options()?,
                            ),
                        ),
                    };

                // RFC 7516 Section 5.1 describes the steps involved in encryption.
                // From steps 1 to 8, we will first determine the CEK, and then encrypt the CEK.
                let cek = header
                    .registered
                    .cek_algorithm
                    .cek(header.registered.enc_algorithm, key)?;
                let encrypted_cek = header.registered.cek_algorithm.wrap_key(
                    cek.algorithm.octet_key()?,
                    key,
                    key_option,
                )?;
                // Update header
                let mut header = header.clone();
                header.update_cek_algorithm(&encrypted_cek);

                // Steps 9 and 10 involves calculating an initialization vector (nonce) for content encryption. We do
                // this as part of the encryption process later

                // Step 11 involves compressing the payload, which we do not support at the moment
                let payload = payload.to_bytes()?;
                if header.registered.compression_algorithm.is_some() {
                    Err(Error::UnsupportedOperation)?
                }

                // Steps 12 to 14 involves the calculation of `Additional Authenticated Data` for encryption. In
                // our compact example, our header is the AAD.
                let encoded_protected_header = BASE64URL_NOPAD.encode(&header.to_bytes()?);
                // Step 15 involves the actual encryption.
                let encrypted_payload = header.registered.enc_algorithm.encrypt(
                    &payload,
                    encoded_protected_header.as_bytes(),
                    &cek,
                    &content_option,
                )?;

                // Finally create the JWE
                let mut compact = crate::Compact::with_capacity(5);
                compact.push(&header)?;
                compact.push(&encrypted_cek.encrypted)?;
                compact.push(&encrypted_payload.nonce)?;
                compact.push(&encrypted_payload.encrypted)?;
                compact.push(&encrypted_payload.tag)?;

                Ok(Compact::Encrypted(compact))
            }
        }
    }

    /// Consumes self and decrypt it. If the token is already decrypted,
    /// this is a no-op.
    pub fn into_decrypted<K: Serialize + DeserializeOwned>(
        self,
        key: &jwk::JWK<K>,
        cek_alg: KeyManagementAlgorithm,
        enc_alg: ContentEncryptionAlgorithm,
    ) -> Result<Self, Error> {
        match self {
            Compact::Encrypted(_) => self.decrypt(key, cek_alg, enc_alg),
            Compact::Decrypted { .. } => Ok(self),
        }
    }

    /// Decrypt an encrypted JWE. Provide the expected algorithms to mitigate an attacker modifying the
    /// fields
    pub fn decrypt<K: Serialize + DeserializeOwned>(
        &self,
        key: &jwk::JWK<K>,
        cek_alg: KeyManagementAlgorithm,
        enc_alg: ContentEncryptionAlgorithm,
    ) -> Result<Self, Error> {
        match *self {
            Compact::Encrypted(ref encrypted) => {
                if encrypted.len() != 5 {
                    Err(DecodeError::PartsLengthError {
                        actual: encrypted.len(),
                        expected: 5,
                    })?
                }
                // RFC 7516 Section 5.2 describes the steps involved in decryption.
                // Steps 1-3
                let mut header: Header<H> = encrypted.part(0)?;
                let encrypted_cek: Vec<u8> = encrypted.part(1)?;
                let nonce: Vec<u8> = encrypted.part(2)?;
                let encrypted_payload: Vec<u8> = encrypted.part(3)?;
                let tag: Vec<u8> = encrypted.part(4)?;

                // Verify that the algorithms are expected
                if header.registered.cek_algorithm != cek_alg
                    || header.registered.enc_algorithm != enc_alg
                {
                    Err(Error::ValidationError(
                        ValidationError::WrongAlgorithmHeader,
                    ))?;
                }

                // TODO: Steps 4-5 not implemented at the moment.

                // Steps 6-13 involve the computation of the cek
                let cek_encryption_result = header.extract_cek_encryption_result(&encrypted_cek);
                let cek = header.registered.cek_algorithm.unwrap_key(
                    &cek_encryption_result,
                    header.registered.enc_algorithm,
                    key,
                )?;

                // Build encryption result as per steps 14-15
                let protected_header: Vec<u8> = encrypted.part(0)?;
                let encoded_protected_header = BASE64URL_NOPAD.encode(protected_header.as_ref());
                let encrypted_payload_result = EncryptionResult {
                    nonce,
                    tag,
                    encrypted: encrypted_payload,
                    additional_data: encoded_protected_header.as_bytes().to_vec(),
                };

                let payload = header
                    .registered
                    .enc_algorithm
                    .decrypt(&encrypted_payload_result, &cek)?;

                // Decompression is not supported at the moment
                if header.registered.compression_algorithm.is_some() {
                    Err(Error::UnsupportedOperation)?
                }

                let payload = T::from_bytes(&payload)?;

                Ok(Compact::new_decrypted(header, payload))
            }
            Compact::Decrypted { .. } => Err(Error::UnsupportedOperation),
        }
    }

    /// Convenience method to get a reference to the encrypted payload
    pub fn encrypted(&self) -> Result<&crate::Compact, Error> {
        match *self {
            Compact::Decrypted { .. } => Err(Error::UnsupportedOperation),
            Compact::Encrypted(ref encoded) => Ok(encoded),
        }
    }

    /// Convenience method to get a mutable reference to the encrypted payload
    pub fn encrypted_mut(&mut self) -> Result<&mut crate::Compact, Error> {
        match *self {
            Compact::Decrypted { .. } => Err(Error::UnsupportedOperation),
            Compact::Encrypted(ref mut encoded) => Ok(encoded),
        }
    }

    /// Convenience method to get a reference to the payload from an Decrypted JWE
    pub fn payload(&self) -> Result<&T, Error> {
        match *self {
            Compact::Decrypted { ref payload, .. } => Ok(payload),
            Compact::Encrypted(_) => Err(Error::UnsupportedOperation),
        }
    }

    /// Convenience method to get a mutable reference to the payload from an Decrypted JWE
    pub fn payload_mut(&mut self) -> Result<&mut T, Error> {
        match *self {
            Compact::Decrypted {
                ref mut payload, ..
            } => Ok(payload),
            Compact::Encrypted(_) => Err(Error::UnsupportedOperation),
        }
    }

    /// Convenience method to get a reference to the header from an Decrypted JWE
    pub fn header(&self) -> Result<&Header<H>, Error> {
        match *self {
            Compact::Decrypted { ref header, .. } => Ok(header),
            Compact::Encrypted(_) => Err(Error::UnsupportedOperation),
        }
    }

    /// Convenience method to get a reference to the header from an Decrypted JWE
    pub fn header_mut(&mut self) -> Result<&mut Header<H>, Error> {
        match *self {
            Compact::Decrypted { ref mut header, .. } => Ok(header),
            Compact::Encrypted(_) => Err(Error::UnsupportedOperation),
        }
    }

    /// Consumes self, and move the payload and header out and return them as a tuple
    ///
    /// # Panics
    /// Panics if the JWE is not decrypted
    pub fn unwrap_decrypted(self) -> (Header<H>, T) {
        match self {
            Compact::Decrypted { header, payload } => (header, payload),
            Compact::Encrypted(_) => panic!("JWE is encrypted"),
        }
    }

    /// Consumes self, and move the encrypted Compact serialization out and return it
    ///
    /// # Panics
    /// Panics if the JWE is not encrypted
    pub fn unwrap_encrypted(self) -> crate::Compact {
        match self {
            Compact::Decrypted { .. } => panic!("JWE is decrypted"),
            Compact::Encrypted(compact) => compact,
        }
    }
}

/// Convenience implementation for a Compact that contains a `ClaimsSet`
impl<P, H> Compact<crate::ClaimsSet<P>, H>
where
    crate::ClaimsSet<P>: CompactPart,
    H: Serialize + DeserializeOwned + Clone,
{
    /// Validate the temporal claims in the decoded token
    ///
    /// If `None` is provided for options, the defaults will apply.
    ///
    /// By default, no temporal claims (namely `iat`, `exp`, `nbf`)
    /// are required, and they will pass validation if they are missing.
    pub fn validate(&self, options: crate::ValidationOptions) -> Result<(), Error> {
        self.payload()?.registered.validate(options)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use ring::rand::SecureRandom;
    use serde_test::{assert_tokens, Token};

    use super::*;
    use crate::jwa::{self, random_aes_gcm_nonce, rng};
    use crate::jws;
    use crate::test::assert_serde_json;
    use crate::JWE;

    fn cek_oct_key(len: usize) -> jwk::JWK<Empty> {
        // Construct the encryption key
        let mut key: Vec<u8> = vec![0; len];
        not_err!(rng().fill(&mut key));
        jwk::JWK {
            common: Default::default(),
            additional: Default::default(),
            algorithm: jwk::AlgorithmParameters::OctetKey(jwk::OctetKeyParameters {
                key_type: Default::default(),
                value: key,
            }),
        }
    }

    #[test]
    fn compression_algorithm_serde_token() {
        #[derive(Debug, Eq, PartialEq, Serialize, Deserialize)]
        struct Test {
            test: CompressionAlgorithm,
        }

        let test_value = Test {
            test: CompressionAlgorithm::Deflate,
        };
        assert_tokens(
            &test_value,
            &[
                Token::Struct {
                    name: "Test",
                    len: 1,
                },
                Token::Str("test"),
                Token::Str("DEF"),
                Token::StructEnd,
            ],
        );

        let test_value = Test {
            test: CompressionAlgorithm::Other("xxx".to_string()),
        };
        assert_tokens(
            &test_value,
            &[
                Token::Struct {
                    name: "Test",
                    len: 1,
                },
                Token::Str("test"),
                Token::Str("xxx"),
                Token::StructEnd,
            ],
        );
    }

    #[test]
    fn compression_algorithm_json_serde() {
        #[derive(Debug, Eq, PartialEq, Serialize, Deserialize)]
        struct Test {
            test: CompressionAlgorithm,
        }

        let test_json = r#"{"test": "DEF"}"#;
        assert_serde_json(
            &Test {
                test: CompressionAlgorithm::Deflate,
            },
            Some(test_json),
        );

        let test_json = r#"{"test": "xxx"}"#;
        assert_serde_json(
            &Test {
                test: CompressionAlgorithm::Other("xxx".to_string()),
            },
            Some(test_json),
        );
    }

    #[test]
    fn jwe_interoperability_check() {
        // This test vector is created by using python-jwcrypto (https://jwcrypto.readthedocs.io/en/latest/)
        /*
          from jwcrypto import jwk, jwe
          from jwcrypto.common import json_encode
          key = jwk.JWK.generate(kty='oct', size=256)
          payload = "Encrypted"
          jwetoken = jwe.JWE(payload.encode('utf-8'),
                             json_encode({"alg": "dir",
                                          "enc": "A256GCM"}))
          jwetoken.add_recipient(key)
          jwetoken.serialize()
          key.export()
        */
        let external_token = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0..7-eXscPDD5DI4kTT.SUQuqkzIrp6j.QaNRHGYXtKC2lj11rgKDpw";
        let key_json = r#"{"k":"YKaiJrr6_-PY8DJelu3rWrxVQQ24tnE9XGIRdZTy9ys","kty":"oct"}"#;

        let key: jwk::JWK<Empty> = not_err!(serde_json::from_str(key_json));
        let token: Compact<Vec<u8>, Empty> = Compact::new_encrypted(external_token);

        let decrypted_jwe = not_err!(token.decrypt(
            &key,
            jwa::KeyManagementAlgorithm::DirectSymmetricKey,
            jwa::ContentEncryptionAlgorithm::A256GCM,
        ));

        let decrypted_payload: &Vec<u8> = not_err!(decrypted_jwe.payload());
        let decrypted_str = not_err!(std::str::from_utf8(decrypted_payload));
        assert_eq!(decrypted_str, "Encrypted");
    }

    #[test]
    fn jwe_header_round_trips() {
        let test_value: Header<Empty> = From::from(RegisteredHeader {
            cek_algorithm: KeyManagementAlgorithm::RSA_OAEP,
            enc_algorithm: ContentEncryptionAlgorithm::A256GCM,
            ..Default::default()
        });
        let test_json = r#"{"alg":"RSA-OAEP","enc":"A256GCM"}"#;
        assert_serde_json(&test_value, Some(test_json));

        let test_value: Header<Empty> = From::from(RegisteredHeader {
            cek_algorithm: KeyManagementAlgorithm::RSA1_5,
            enc_algorithm: ContentEncryptionAlgorithm::A128CBC_HS256,
            ..Default::default()
        });
        let test_json = r#"{"alg":"RSA1_5","enc":"A128CBC-HS256"}"#;
        assert_serde_json(&test_value, Some(test_json));

        let test_value: Header<Empty> = From::from(RegisteredHeader {
            cek_algorithm: KeyManagementAlgorithm::A128KW,
            enc_algorithm: ContentEncryptionAlgorithm::A128CBC_HS256,
            ..Default::default()
        });
        let test_json = r#"{"alg":"A128KW","enc":"A128CBC-HS256"}"#;
        assert_serde_json(&test_value, Some(test_json));
    }

    #[test]
    fn custom_jwe_header_round_trip() {
        #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
        struct CustomHeader {
            something: String,
        }

        let test_value = Header {
            registered: RegisteredHeader {
                cek_algorithm: KeyManagementAlgorithm::RSA_OAEP,
                enc_algorithm: ContentEncryptionAlgorithm::A256GCM,
                ..Default::default()
            },
            cek_algorithm: Default::default(),
            private: CustomHeader {
                something: "foobar".to_string(),
            },
        };
        let test_json = r#"{"alg":"RSA-OAEP","enc":"A256GCM","something":"foobar"}"#;
        assert_serde_json(&test_value, Some(test_json));
    }

    #[test]
    fn jwe_a256gcmkw_a256gcm_string_round_trip() {
        use std::str;

        // Construct the encryption key
        let key = cek_oct_key(256 / 8);

        // Construct the JWE
        let payload = "The true sign of intelligence is not knowledge but imagination.";
        let jwe = Compact::new_decrypted(
            From::from(RegisteredHeader {
                cek_algorithm: KeyManagementAlgorithm::A256GCMKW,
                enc_algorithm: ContentEncryptionAlgorithm::A256GCM,
                ..Default::default()
            }),
            payload.as_bytes().to_vec(),
        );
        let options = EncryptionOptions::AES_GCM {
            nonce: random_aes_gcm_nonce().unwrap(),
        };

        // Encrypt
        let encrypted_jwe = not_err!(jwe.encrypt(&key, &options));

        {
            // Check that new header values are added
            let compact = not_err!(encrypted_jwe.encrypted());
            let header: Header<Empty> = not_err!(compact.part(0));
            assert!(header.cek_algorithm.nonce.is_some());
            assert!(header.cek_algorithm.tag.is_some());

            // Check that the encrypted key part is not empty
            let cek: Vec<u8> = not_err!(compact.part(1));
            assert_eq!(256 / 8, cek.len());
        }

        // Serde test
        let json = not_err!(serde_json::to_string(&encrypted_jwe));
        let deserialized_json: Compact<Vec<u8>, Empty> = not_err!(serde_json::from_str(&json));
        assert_eq!(deserialized_json, encrypted_jwe);

        // Decrypt
        let decrypted_jwe = not_err!(encrypted_jwe.into_decrypted(
            &key,
            KeyManagementAlgorithm::A256GCMKW,
            ContentEncryptionAlgorithm::A256GCM
        ));
        assert_eq!(jwe, decrypted_jwe);

        let decrypted_payload: &Vec<u8> = not_err!(decrypted_jwe.payload());
        let decrypted_str = not_err!(str::from_utf8(decrypted_payload));
        assert_eq!(decrypted_str, payload);
    }

    #[test]
    fn jwe_a256gcmkw_a256gcm_jws_round_trip() {
        // Construct the JWS
        let claims = crate::ClaimsSet::<Empty> {
            registered: crate::RegisteredClaims {
                issuer: Some(not_err!(FromStr::from_str("https://www.acme.com"))),
                subject: Some(not_err!(FromStr::from_str("John Doe"))),
                audience: Some(crate::SingleOrMultiple::Single(not_err!(
                    FromStr::from_str("htts://acme-customer.com")
                ))),
                not_before: Some(1234.into()),
                ..Default::default()
            },
            private: Default::default(),
        };
        let jws = jws::Compact::new_decoded(
            From::from(jws::RegisteredHeader {
                algorithm: jwa::SignatureAlgorithm::HS256,
                ..Default::default()
            }),
            claims,
        );
        let jws =
            not_err!(jws.into_encoded(&jws::Secret::Bytes("secret".to_string().into_bytes())));

        // Construct the encryption key
        let key = cek_oct_key(256 / 8);

        // Construct the JWE
        let jwe = Compact::new_decrypted(
            From::from(RegisteredHeader {
                cek_algorithm: KeyManagementAlgorithm::A256GCMKW,
                enc_algorithm: ContentEncryptionAlgorithm::A256GCM,
                media_type: Some("JOSE".to_string()),
                content_type: Some("JOSE".to_string()),
                ..Default::default()
            }),
            jws.clone(),
        );
        let options = EncryptionOptions::AES_GCM {
            nonce: random_aes_gcm_nonce().unwrap(),
        };

        // Encrypt
        let encrypted_jwe = not_err!(jwe.encrypt(&key, &options));

        {
            // Check that new header values are added
            let compact = not_err!(encrypted_jwe.encrypted());
            let header: Header<Empty> = not_err!(compact.part(0));
            assert!(header.cek_algorithm.nonce.is_some());
            assert!(header.cek_algorithm.tag.is_some());

            // Check that the encrypted key part is not empty
            let cek: Vec<u8> = not_err!(compact.part(1));
            assert_eq!(256 / 8, cek.len());
        }

        // Serde test
        let json = not_err!(serde_json::to_string(&encrypted_jwe));
        let deserialized_json: JWE<Empty, Empty, Empty> = not_err!(serde_json::from_str(&json));
        assert_eq!(deserialized_json, encrypted_jwe);

        // Decrypt
        let decrypted_jwe = not_err!(encrypted_jwe.into_decrypted(
            &key,
            KeyManagementAlgorithm::A256GCMKW,
            ContentEncryptionAlgorithm::A256GCM
        ));
        assert_eq!(jwe, decrypted_jwe);

        let decrypted_jws = not_err!(decrypted_jwe.payload());
        assert_eq!(jws, *decrypted_jws);
    }

    #[test]
    fn jwe_dir_aes256gcm_jws_round_trip() {
        // Construct the JWS
        let claims = crate::ClaimsSet::<Empty> {
            registered: crate::RegisteredClaims {
                issuer: Some(not_err!(FromStr::from_str("https://www.acme.com"))),
                subject: Some(not_err!(FromStr::from_str("John Doe"))),
                audience: Some(crate::SingleOrMultiple::Single(not_err!(
                    FromStr::from_str("htts://acme-customer.com")
                ))),
                not_before: Some(1234.into()),
                ..Default::default()
            },
            private: Default::default(),
        };
        let jws = jws::Compact::new_decoded(
            From::from(jws::RegisteredHeader {
                algorithm: jwa::SignatureAlgorithm::HS256,
                ..Default::default()
            }),
            claims,
        );
        let jws =
            not_err!(jws.into_encoded(&jws::Secret::Bytes("secret".to_string().into_bytes())));

        // Construct the encryption key
        let key = cek_oct_key(256 / 8);

        // Construct the JWE
        let jwe = Compact::new_decrypted(
            From::from(RegisteredHeader {
                cek_algorithm: KeyManagementAlgorithm::DirectSymmetricKey,
                enc_algorithm: ContentEncryptionAlgorithm::A256GCM,
                media_type: Some("JOSE".to_string()),
                content_type: Some("JOSE".to_string()),
                ..Default::default()
            }),
            jws.clone(),
        );
        let options = EncryptionOptions::AES_GCM {
            nonce: random_aes_gcm_nonce().unwrap(),
        };

        // Encrypt
        let encrypted_jwe = not_err!(jwe.encrypt(&key, &options));

        {
            let compact = not_err!(encrypted_jwe.encrypted());
            // Check that new header values are empty
            let header: Header<Empty> = not_err!(compact.part(0));
            assert!(header.cek_algorithm.nonce.is_none());
            assert!(header.cek_algorithm.tag.is_none());

            // Check that the encrypted key part is empty
            let cek: Vec<u8> = not_err!(compact.part(1));
            assert!(cek.is_empty());
        }

        // Serde test
        let json = not_err!(serde_json::to_string(&encrypted_jwe));
        let deserialized_json: JWE<Empty, Empty, Empty> = not_err!(serde_json::from_str(&json));
        assert_eq!(deserialized_json, encrypted_jwe);

        // Decrypt
        let decrypted_jwe = not_err!(encrypted_jwe.into_decrypted(
            &key,
            KeyManagementAlgorithm::DirectSymmetricKey,
            ContentEncryptionAlgorithm::A256GCM
        ));
        assert_eq!(jwe, decrypted_jwe);

        let decrypted_jws = not_err!(decrypted_jwe.payload());
        assert_eq!(jws, *decrypted_jws);
    }

    #[test]
    #[should_panic(expected = "WrongAlgorithmHeader")]
    fn decrypt_with_mismatch_cek_algorithm() {
        // Construct the encryption key
        let key = cek_oct_key(256 / 8);

        // Construct the JWE
        let payload = "The true sign of intelligence is not knowledge but imagination.";
        let jwe = Compact::new_decrypted(
            From::from(RegisteredHeader {
                cek_algorithm: KeyManagementAlgorithm::A256GCMKW,
                enc_algorithm: ContentEncryptionAlgorithm::A256GCM,
                ..Default::default()
            }),
            payload.as_bytes().to_vec(),
        );
        let options = EncryptionOptions::AES_GCM {
            nonce: random_aes_gcm_nonce().unwrap(),
        };

        // Encrypt
        let encrypted_jwe = not_err!(jwe.encrypt(&key, &options));

        let _ = encrypted_jwe
            .into_decrypted(
                &key,
                KeyManagementAlgorithm::A128GCMKW,
                ContentEncryptionAlgorithm::A256GCM,
            )
            .unwrap();
    }

    #[test]
    #[should_panic(expected = "WrongAlgorithmHeader")]
    fn decrypt_with_mismatch_enc_algorithm() {
        // Construct the encryption key
        let key = cek_oct_key(256 / 8);

        // Construct the JWE
        let payload = "The true sign of intelligence is not knowledge but imagination.";
        let jwe = Compact::new_decrypted(
            From::from(RegisteredHeader {
                cek_algorithm: KeyManagementAlgorithm::A256GCMKW,
                enc_algorithm: ContentEncryptionAlgorithm::A256GCM,
                ..Default::default()
            }),
            payload.as_bytes().to_vec(),
        );

        let options = EncryptionOptions::AES_GCM {
            nonce: random_aes_gcm_nonce().unwrap(),
        };
        // Encrypt
        let encrypted_jwe = not_err!(jwe.encrypt(&key, &options));

        let _ = encrypted_jwe
            .into_decrypted(
                &key,
                KeyManagementAlgorithm::A256GCMKW,
                ContentEncryptionAlgorithm::A128GCM,
            )
            .unwrap();
    }

    #[test]
    #[should_panic(expected = "PartsLengthError")]
    fn decrypt_with_incorrect_length() {
        let key = cek_oct_key(256 / 8);
        let invalid = Compact::<Empty, Empty>::new_encrypted("INVALID");
        let _ = invalid
            .into_decrypted(
                &key,
                KeyManagementAlgorithm::A256GCMKW,
                ContentEncryptionAlgorithm::A128GCM,
            )
            .unwrap();
    }

    #[test]
    #[should_panic(expected = "UnspecifiedCryptographicError")]
    fn invalid_nonce_for_aes256gcmkw() {
        // Construct the encryption key
        let key = cek_oct_key(256 / 8);

        // Construct the JWE
        let payload = "The true sign of intelligence is not knowledge but imagination.";
        let jwe = Compact::new_decrypted(
            From::from(RegisteredHeader {
                cek_algorithm: KeyManagementAlgorithm::A256GCMKW,
                enc_algorithm: ContentEncryptionAlgorithm::A256GCM,
                ..Default::default()
            }),
            payload.as_bytes().to_vec(),
        );

        let options = EncryptionOptions::AES_GCM {
            nonce: random_aes_gcm_nonce().unwrap(),
        };
        // Encrypt
        let encrypted_jwe = not_err!(jwe.encrypt(&key, &options));

        // Modify the JWE
        let mut compact = encrypted_jwe.unwrap_encrypted();
        let mut header: Header<Empty> = not_err!(compact.part(0));
        header.cek_algorithm.nonce = Some(vec![0; 96 / 8]);
        compact.parts[0] = not_err!(header.to_base64());

        let encrypted_jwe = Compact::<Empty, Empty>::new_encrypted(&compact.to_string());
        let _ = encrypted_jwe
            .into_decrypted(
                &key,
                KeyManagementAlgorithm::A256GCMKW,
                ContentEncryptionAlgorithm::A256GCM,
            )
            .unwrap();
    }

    #[test]
    #[should_panic(expected = "UnspecifiedCryptographicError")]
    fn invalid_tag_for_aes256gcmkw() {
        // Construct the encryption key
        let key = cek_oct_key(256 / 8);

        // Construct the JWE
        let payload = "The true sign of intelligence is not knowledge but imagination.";
        let jwe = Compact::new_decrypted(
            From::from(RegisteredHeader {
                cek_algorithm: KeyManagementAlgorithm::A256GCMKW,
                enc_algorithm: ContentEncryptionAlgorithm::A256GCM,
                ..Default::default()
            }),
            payload.as_bytes().to_vec(),
        );

        let options = EncryptionOptions::AES_GCM {
            nonce: random_aes_gcm_nonce().unwrap(),
        };
        // Encrypt
        let encrypted_jwe = not_err!(jwe.encrypt(&key, &options));

        // Modify the JWE
        let mut compact = encrypted_jwe.unwrap_encrypted();
        let mut header: Header<Empty> = not_err!(compact.part(0));
        header.cek_algorithm.tag = Some(vec![0; 96 / 8]);
        compact.parts[0] = not_err!(header.to_base64());

        let encrypted_jwe = Compact::<Empty, Empty>::new_encrypted(&compact.to_string());
        let _ = encrypted_jwe
            .into_decrypted(
                &key,
                KeyManagementAlgorithm::A256GCMKW,
                ContentEncryptionAlgorithm::A256GCM,
            )
            .unwrap();
    }

    #[test]
    #[should_panic(expected = "UnspecifiedCryptographicError")]
    fn invalid_tag_for_aes256gcm() {
        // Construct the encryption key
        let key = cek_oct_key(256 / 8);

        // Construct the JWE
        let payload = "The true sign of intelligence is not knowledge but imagination.";
        let jwe = Compact::new_decrypted(
            From::from(RegisteredHeader {
                cek_algorithm: KeyManagementAlgorithm::A256GCMKW,
                enc_algorithm: ContentEncryptionAlgorithm::A256GCM,
                ..Default::default()
            }),
            payload.as_bytes().to_vec(),
        );

        let options = EncryptionOptions::AES_GCM {
            nonce: random_aes_gcm_nonce().unwrap(),
        };
        // Encrypt
        let encrypted_jwe = not_err!(jwe.encrypt(&key, &options));

        // Modify the JWE
        let mut compact = encrypted_jwe.unwrap_encrypted();
        compact.parts[4] = not_err!(vec![0u8; 1].to_base64());

        let encrypted_jwe = Compact::<Empty, Empty>::new_encrypted(&compact.to_string());
        let _ = encrypted_jwe
            .into_decrypted(
                &key,
                KeyManagementAlgorithm::A256GCMKW,
                ContentEncryptionAlgorithm::A256GCM,
            )
            .unwrap();
    }

    /// This test modifies the header so the tag (aad for the AES GCM) included becomes incorrect
    #[test]
    #[should_panic(expected = "UnspecifiedCryptographicError")]
    fn invalid_modified_header_for_aes256gcm() {
        // Construct the encryption key
        let key = cek_oct_key(256 / 8);

        // Construct the JWE
        let payload = "The true sign of intelligence is not knowledge but imagination.";
        let jwe = Compact::new_decrypted(
            From::from(RegisteredHeader {
                cek_algorithm: KeyManagementAlgorithm::A256GCMKW,
                enc_algorithm: ContentEncryptionAlgorithm::A256GCM,
                ..Default::default()
            }),
            payload.as_bytes().to_vec(),
        );
        let options = EncryptionOptions::AES_GCM {
            nonce: random_aes_gcm_nonce().unwrap(),
        };

        // Encrypt
        let encrypted_jwe = not_err!(jwe.encrypt(&key, &options));

        // Modify the JWE
        let mut compact = encrypted_jwe.unwrap_encrypted();
        let mut header: Header<Empty> = not_err!(compact.part(0));
        header.registered.media_type = Some("JOSE+JSON".to_string());
        compact.parts[0] = not_err!(header.to_base64());

        let encrypted_jwe = Compact::<Empty, Empty>::new_encrypted(&compact.to_string());
        let _ = encrypted_jwe
            .into_decrypted(
                &key,
                KeyManagementAlgorithm::A256GCMKW,
                ContentEncryptionAlgorithm::A256GCM,
            )
            .unwrap();
    }

    /// This test modifies the encrypted cek
    #[test]
    #[should_panic(expected = "UnspecifiedCryptographicError")]
    fn invalid_modified_encrypted_cek_for_aes256gcm() {
        // Construct the encryption key
        let key = cek_oct_key(256 / 8);

        // Construct the JWE
        let payload = "The true sign of intelligence is not knowledge but imagination.";
        let jwe = Compact::new_decrypted(
            From::from(RegisteredHeader {
                cek_algorithm: KeyManagementAlgorithm::A256GCMKW,
                enc_algorithm: ContentEncryptionAlgorithm::A256GCM,
                ..Default::default()
            }),
            payload.as_bytes().to_vec(),
        );

        let options = EncryptionOptions::AES_GCM {
            nonce: random_aes_gcm_nonce().unwrap(),
        };
        // Encrypt
        let encrypted_jwe = not_err!(jwe.encrypt(&key, &options));

        // Modify the JWE
        let mut compact = encrypted_jwe.unwrap_encrypted();
        compact.parts[1] = not_err!(vec![0u8; 256 / 8].to_base64());

        let encrypted_jwe = Compact::<Empty, Empty>::new_encrypted(&compact.to_string());
        let _ = encrypted_jwe
            .into_decrypted(
                &key,
                KeyManagementAlgorithm::A256GCMKW,
                ContentEncryptionAlgorithm::A256GCM,
            )
            .unwrap();
    }

    /// This test modifies the encrypted payload
    #[test]
    #[should_panic(expected = "UnspecifiedCryptographicError")]
    fn invalid_modified_encrypted_payload_for_aes256gcm() {
        // Construct the encryption key
        let key = cek_oct_key(256 / 8);

        // Construct the JWE
        let payload = "The true sign of intelligence is not knowledge but imagination.";
        let jwe = Compact::new_decrypted(
            From::from(RegisteredHeader {
                cek_algorithm: KeyManagementAlgorithm::A256GCMKW,
                enc_algorithm: ContentEncryptionAlgorithm::A256GCM,
                ..Default::default()
            }),
            payload.as_bytes().to_vec(),
        );
        let options = EncryptionOptions::AES_GCM {
            nonce: random_aes_gcm_nonce().unwrap(),
        };

        // Encrypt
        let encrypted_jwe = not_err!(jwe.encrypt(&key, &options));

        // Modify the JWE
        let mut compact = encrypted_jwe.unwrap_encrypted();
        let mut header: Header<Empty> = not_err!(compact.part(0));
        header.registered.media_type = Some("JOSE+JSON".to_string());
        compact.parts[3] = not_err!(vec![0u8; 32].to_base64());

        let encrypted_jwe = Compact::<Empty, Empty>::new_encrypted(&compact.to_string());
        let _ = encrypted_jwe
            .into_decrypted(
                &key,
                KeyManagementAlgorithm::A256GCMKW,
                ContentEncryptionAlgorithm::A256GCM,
            )
            .unwrap();
    }

    /// This test modifies the nonce
    #[test]
    #[should_panic(expected = "UnspecifiedCryptographicError")]
    fn invalid_modified_encrypted_nonce_for_aes256gcm() {
        // Construct the encryption key
        let key = cek_oct_key(256 / 8);

        // Construct the JWE
        let payload = "The true sign of intelligence is not knowledge but imagination.";
        let jwe = Compact::new_decrypted(
            From::from(RegisteredHeader {
                cek_algorithm: KeyManagementAlgorithm::A256GCMKW,
                enc_algorithm: ContentEncryptionAlgorithm::A256GCM,
                ..Default::default()
            }),
            payload.as_bytes().to_vec(),
        );
        let options = EncryptionOptions::AES_GCM {
            nonce: random_aes_gcm_nonce().unwrap(),
        };

        // Encrypt
        let encrypted_jwe = not_err!(jwe.encrypt(&key, &options));

        // Modify the JWE
        let mut compact = encrypted_jwe.unwrap_encrypted();
        let mut header: Header<Empty> = not_err!(compact.part(0));
        header.registered.media_type = Some("JOSE+JSON".to_string());
        compact.parts[2] = not_err!(vec![0u8; 96 / 8].to_base64());

        let encrypted_jwe = Compact::<Empty, Empty>::new_encrypted(&compact.to_string());
        let _ = encrypted_jwe
            .into_decrypted(
                &key,
                KeyManagementAlgorithm::A256GCMKW,
                ContentEncryptionAlgorithm::A256GCM,
            )
            .unwrap();
    }
}