aranya-crypto 0.14.1

The Aranya Cryptography Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
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
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
//! [`Engine`] tests.

extern crate alloc;

use alloc::{collections::BTreeSet, vec, vec::Vec};
use core::ops::Add;

use spideroak_crypto::{
    aead::{Aead, OpenError},
    csprng::Random,
    default::Rng,
    generic_array::ArrayLength,
    hpke::HpkeError,
    typenum::{Sum, U64},
};

use super::{assert_ct_eq, assert_ct_ne};
use crate::{
    afc,
    apq::{
        EncryptedTopicKey, ReceiverSecretKey, Sender, SenderSecretKey, SenderSigningKey, Topic,
        TopicKey, Version,
    },
    aranya::{DeviceId, Encap, EncryptionKey, IdentityKey, SigningKey as DeviceSigningKey},
    ciphersuite::CipherSuite,
    engine::Engine,
    error::Error,
    groupkey::{Context, EncryptedGroupKey, GroupKey},
    id::{IdExt as _, Identified as _},
    policy::{CmdId, GroupId, LabelId, PolicyId},
    tls,
    util::cbor,
};

/// Invokes `callback` for each Engine test.
///
/// # Example
///
/// ```
/// use aranya_crypto::{
///     Rng,
///     default::{DefaultCipherSuite, DefaultEngine},
///     test_engine,
/// };
///
/// # aranya_crypto::__doctest_os_hardware_rand!();
/// macro_rules! run_test {
///     ($test:ident) => {
///         aranya_crypto::test_util::engine::$test(&mut {
///             let (eng, _) = DefaultEngine::<_, DefaultCipherSuite>::from_entropy(Rng);
///             eng
///         });
///     };
/// }
/// aranya_crypto::for_each_engine_test!(run_test);
/// ```
#[macro_export]
macro_rules! for_each_engine_test {
    ($callback:ident) => {
        $crate::__apply! {
            $callback,

            // Aranya

            test_simple_device_signing_key_sign,

            test_simple_seal_group_key,
            test_simple_wrap_group_key,
            test_simple_wrap_device_identity_key,
            test_simple_export_device_identity_key,
            test_simple_identity_key_sign,
            test_simple_wrap_device_signing_key,
            test_simple_export_device_signing_key,
            test_simple_wrap_device_encryption_key,
            test_simple_export_device_encryption_key,

            test_group_key_seal,
            test_group_key_open_wrong_key,
            test_group_key_open_wrong_context,
            test_group_key_open_bad_ciphertext,

            test_encrypted_group_key_encode,

            // APQ

            test_simple_sender_signing_key_sign,

            test_simple_seal_topic_key,
            test_simple_wrap_device_sender_secret_key,
            test_simple_wrap_device_sender_signing_key,
            test_simple_wrap_device_receiver_secret_key,

            test_topic_key_seal,
            test_topic_key_open_wrong_key,
            test_topic_key_open_wrong_context,
            test_topic_key_open_bad_ciphertext,

            // AFC

            test_afc_same_seal_key_open_key,
            test_afc_different_seal_key_open_key,
            test_afc_seal_key_monotonic_seq_number,
            test_afc_seal_key_seq_number_exhausted,
            test_afc_open_key_seq_number_exhausted,
            test_afc_open_key_wrong_seq_number,
            test_afc_open_key_wrong_auth_data,

            test_afc_derive_uni_key,
            test_afc_derive_uni_key_different_labels,
            test_afc_derive_uni_key_different_device_ids,
            test_afc_derive_uni_key_different_cmd_ids,
            test_afc_derive_uni_key_different_keys,
            test_afc_derive_uni_seal_key_same_device_id,
            test_afc_derive_uni_open_key_same_device_id,
            test_afc_wrap_uni_author_secret,

            // TLS

            test_tls_psk_different_suites,
            test_tls_psk_different_policy_ids,
            test_tls_psk_different_contexts,
            test_tls_psk_different_groups,
            test_tls_psk_seed_simple_wrap,
            test_tls_psk_seed_seal_open,
            test_tls_psk_seed_open_wrong_peer_pk,
            test_tls_psk_seed_open_wrong_sk,
            test_tls_psk_seed_open_wrong_group,
            test_tls_psk_seed_open_wrong_ciphertext,
            test_tls_psk_seed_open_wrong_tag,
        }
    };
}
pub use for_each_engine_test;

/// Performs all of the tests inside this module.
///
/// This macro expands into a bunch of individual `#[test]`
/// functions.
///
/// It also performs
/// [`test_ciphersuite`][super::test_ciphersuite].
///
/// # Example
///
/// ```
/// use aranya_crypto::{
///     Rng,
///     default::{DefaultCipherSuite, DefaultEngine},
///     test_engine,
/// };
///
/// test_engine!(default_engine, || -> DefaultEngine<_, _> {
///     let (eng, _) = DefaultEngine::<_, DefaultCipherSuite>::from_entropy(Rng);
///     eng
/// });
/// ```
#[macro_export]
macro_rules! test_engine {
    ($name:ident, || -> $engine:ty { $($args:tt)+ }) => {
        mod $name {
            #[allow(unused_imports)]
            use super::*;

            $crate::test_engine!(|| -> $engine { $($args)+ });
        }
    };
    (|| -> $engine:ty { $($args:tt)+ }) => {
        $crate::test_util::test_ciphersuite!(ciphersuite, <$engine as $crate::engine::Engine>::CS);

        macro_rules! __engine_test {
            ($test:ident) => {
                #[test]
                fn $test() {
                    $crate::test_util::engine::$test(&mut { $($args)+ });
                }
            };
        }
        $crate::for_each_engine_test!(__engine_test);
    };
}
pub use test_engine;

/// Simple test for [`DeviceSigningKey`].
pub fn test_simple_device_signing_key_sign<E: Engine>(eng: &E) {
    const MSG: &[u8] = b"hello, world!";
    const CONTEXT: &[u8] = b"test_simple_device_signing_key_sign";

    let sign_key = DeviceSigningKey::<E::CS>::new(eng);

    let sig = sign_key
        .sign(MSG, CONTEXT)
        .expect("unable to create signature");

    sign_key
        .public()
        .expect("sender signing key should be valid")
        .verify(MSG, CONTEXT, &sig)
        .expect("the signature should be valid");

    sign_key
        .public()
        .expect("sender signing key should be valid")
        .verify(MSG, b"wrong context", &sig)
        .expect_err("should fail with wrong context");

    let wrong_sig = sign_key
        .sign(b"different", b"signature")
        .expect("should not fail to create signature");

    sign_key
        .public()
        .expect("sender signing key should be valid")
        .verify(MSG, CONTEXT, &wrong_sig)
        .expect_err("should fail with wrong signature");
}

/// Simple positive test for encrypting/decrypting
/// [`GroupKey`]s.
pub fn test_simple_seal_group_key<E: Engine>(eng: &E) {
    let enc_key = EncryptionKey::<E::CS>::new(eng);

    let group = GroupId::default();
    let want = GroupKey::new(eng);
    let (enc, ciphertext) = enc_key
        .public()
        .expect("public encryption key should be valid")
        .seal_group_key(eng, &want, group)
        .expect("unable to encrypt `GroupKey`");
    let got = enc_key
        .open_group_key(&enc, ciphertext, group)
        .expect("unable to decrypt `GroupKey`");
    assert_eq!(want.id(), got.id());
}

/// Simple positive test for wrapping [`GroupKey`]s.
pub fn test_simple_wrap_group_key<E: Engine>(eng: &E) {
    let want = GroupKey::new(eng);
    let bytes = cbor::to_allocvec(
        &eng.wrap(want.clone())
            .expect("should be able to wrap `GroupKey`"),
    )
    .expect("should be able to encode wrapped `GroupKey`");
    let wrapped =
        cbor::from_bytes(&bytes).expect("should be able to decode encoded wrapped `GroupKey`");
    let got: GroupKey<E::CS> = eng
        .unwrap(&wrapped)
        .expect("should be able to unwrap `GroupKey`");
    assert_eq!(want.id(), got.id());
}

/// Simple positive test for wrapping [`IdentityKey`]s.
pub fn test_simple_wrap_device_identity_key<E: Engine>(eng: &E) {
    let want = IdentityKey::new(eng);
    let bytes = cbor::to_allocvec(
        &eng.wrap(want.clone())
            .expect("should be able to wrap `IdentityKey`"),
    )
    .expect("should be able to encode wrapped `IdentityKey`");
    let wrapped =
        cbor::from_bytes(&bytes).expect("should be able to decode encoded wrapped `IdentityKey`");
    let got: IdentityKey<E::CS> = eng
        .unwrap(&wrapped)
        .expect("should be able to unwrap `IdentityKey`");
    assert_eq!(want.id(), got.id());
}

/// Simple positive test for exporting the public half of
/// [`IdentityKey`]s.
pub fn test_simple_export_device_identity_key<E: Engine>(eng: &E) {
    let want = IdentityKey::<E::CS>::new(eng)
        .public()
        .expect("identity key should be valid");
    let bytes =
        cbor::to_allocvec(&want).expect("should be able to encode an `IdentityVerifyingKey`");
    let got = cbor::from_bytes(&bytes).expect("should be able to decode an `IdentityVerifyingKey`");
    assert_eq!(want, got);
}

/// Simple test for [`IdentityKey`].
/// Creates a signature over `msg` bound to some `context`.
/// `msg` must NOT be pre-hashed.
pub fn test_simple_identity_key_sign<E: Engine>(eng: &E) {
    let sign_key = IdentityKey::<E::CS>::new(eng);

    const MESSAGE: &[u8] = b"hello, world!";
    const CONTEXT: &[u8] = b"test_simple_identity_key_sign";

    let sig = sign_key
        .sign(MESSAGE, CONTEXT)
        .expect("should not fail to create signature");

    sign_key
        .public()
        .expect("sender signing key should be valid")
        .verify(MESSAGE, CONTEXT, &sig)
        .expect("should not fail with correct signature");

    sign_key
        .public()
        .expect("sender signing key should be valid")
        .verify(MESSAGE, b"wrong context", &sig)
        .expect_err("should fail with wrong context");

    let wrong_sig = sign_key
        .sign(b"different", b"signature")
        .expect("should not fail to create signature");

    sign_key
        .public()
        .expect("sender signing key should be valid")
        .verify(MESSAGE, CONTEXT, &wrong_sig)
        .expect_err("should fail with wrong signature");
}

/// Simple positive test for wrapping [`DeviceSigningKey`]s.
pub fn test_simple_wrap_device_signing_key<E: Engine>(eng: &E) {
    let want = DeviceSigningKey::new(eng);
    let bytes = cbor::to_allocvec(
        &eng.wrap(want.clone())
            .expect("should be able to wrap `DeviceSigningKey`"),
    )
    .expect("should be able to encode wrapped `DeviceSigningKey`");
    let wrapped = cbor::from_bytes(&bytes)
        .expect("should be able to decode encoded wrapped `DeviceSigningKey`");
    let got: DeviceSigningKey<E::CS> = eng
        .unwrap(&wrapped)
        .expect("should be able to unwrap `DeviceSigningKey`");
    assert_eq!(want.id(), got.id());
}

/// Simple positive test for exporting the public half of
/// [`DeviceSigningKey`]s.
pub fn test_simple_export_device_signing_key<E: Engine>(eng: &E) {
    let want = DeviceSigningKey::<E::CS>::new(eng)
        .public()
        .expect("device signing key should be valid");
    let bytes = cbor::to_allocvec(&want).expect("should be able to encode an `VerifyingKey`");
    let got = cbor::from_bytes(&bytes).expect("should be able to decode an `VerifyingKey`");
    assert_eq!(want, got);
}

/// Simple positive test for wrapping [`EncryptionKey`]s.
pub fn test_simple_wrap_device_encryption_key<E: Engine>(eng: &E) {
    let want = EncryptionKey::new(eng);
    let bytes = cbor::to_allocvec(
        &eng.wrap(want.clone())
            .expect("should be able to wrap `EncryptionKey`"),
    )
    .expect("should be able to encode wrapped `EncryptionKey`");
    let wrapped =
        cbor::from_bytes(&bytes).expect("should be able to decode encoded wrapped `EncryptionKey`");
    let got: EncryptionKey<E::CS> = eng
        .unwrap(&wrapped)
        .expect("should be able to unwrap `EncryptionKey`");
    assert_eq!(want.id(), got.id());
}

/// Simple positive test for exporting the public half of
/// [`EncryptionKey`]s.
pub fn test_simple_export_device_encryption_key<E: Engine>(eng: &E) {
    let want = EncryptionKey::<E::CS>::new(eng)
        .public()
        .expect("encryption public key should be valid");
    let bytes =
        cbor::to_allocvec(&want).expect("should be able to encode an `EncryptionPublicKey`");
    let got = cbor::from_bytes(&bytes).expect("should be able to decode an `EncryptionPublicKey`");
    assert_eq!(want, got);
}

/// Simple positive test for encryption using a [`GroupKey`].
pub fn test_group_key_seal<E: Engine>(eng: &E) {
    const INPUT: &[u8] = b"hello, world!";

    let author_sign_pk = DeviceSigningKey::<E::CS>::new(eng)
        .public()
        .expect("author signing key should be valid");

    let gk = GroupKey::new(eng);
    let ciphertext = {
        let mut dst = vec![0u8; INPUT.len() + gk.overhead()];
        gk.seal(
            eng,
            &mut dst,
            INPUT,
            Context {
                label: "test_group_key_seal",
                parent: CmdId::default(),
                author_sign_pk: &author_sign_pk,
            },
        )
        .expect("should succeed");
        dst
    };
    let plaintext = {
        let mut dst = vec![0u8; ciphertext.len() - gk.overhead()];
        gk.open(
            &mut dst,
            &ciphertext,
            Context {
                label: "test_group_key_seal",
                parent: CmdId::default(),
                author_sign_pk: &author_sign_pk,
            },
        )
        .expect("should succeed");
        dst
    };
    assert_eq!(&plaintext, INPUT);
}

/// Negative test for the wrong [`GroupKey`].
pub fn test_group_key_open_wrong_key<E: Engine>(eng: &E) {
    const INPUT: &[u8] = b"hello, world!";

    let author_sign_pk = DeviceSigningKey::<E::CS>::new(eng)
        .public()
        .expect("author signing key should be valid");

    let gk1 = GroupKey::new(eng);
    let gk2 = GroupKey::new(eng);

    let ciphertext = {
        let mut dst = vec![0u8; INPUT.len() + gk1.overhead()];
        gk1.seal(
            eng,
            &mut dst,
            INPUT,
            Context {
                label: "some label",
                parent: CmdId::default(),
                author_sign_pk: &author_sign_pk,
            },
        )
        .expect("should succeed");
        dst
    };
    let mut dst = vec![0u8; ciphertext.len() - gk2.overhead()];
    let err = gk2
        .open(
            &mut dst,
            &ciphertext,
            Context {
                label: "some label",
                parent: CmdId::default(),
                author_sign_pk: &author_sign_pk,
            },
        )
        .expect_err("should have failed");
    assert_eq!(err, Error::Open(OpenError::Authentication));
}

/// Negative test for the wrong [`Context`].
pub fn test_group_key_open_wrong_context<E: Engine>(eng: &E) {
    const INPUT: &[u8] = b"hello, world!";

    let author_pk1 = DeviceSigningKey::<E::CS>::new(eng)
        .public()
        .expect("author 1 signing key should be valid");
    let author_pk2 = DeviceSigningKey::<E::CS>::new(eng)
        .public()
        .expect("author 2 signing key should be valid");

    let gk = GroupKey::new(eng);
    let ciphertext = {
        let mut dst = vec![0u8; INPUT.len() + gk.overhead()];
        gk.seal(
            eng,
            &mut dst,
            INPUT,
            Context {
                label: "some label",
                parent: CmdId::default(),
                author_sign_pk: &author_pk1,
            },
        )
        .expect("should succeed");
        dst
    };

    macro_rules! should_fail {
        ($msg:expr, $ctx:expr) => {
            let mut dst = vec![0u8; ciphertext.len() - gk.overhead()];
            let err = gk
                .open(&mut dst, &ciphertext, $ctx)
                .expect_err("should have failed");
            assert_eq!(err, Error::Open(OpenError::Authentication), $msg);
        };
    }
    should_fail!(
        "wrong label",
        Context {
            label: "wrong label",
            parent: CmdId::default(),
            author_sign_pk: &author_pk1,
        }
    );
    should_fail!(
        "wrong `parent`",
        Context {
            label: "some label",
            parent: [1u8; 32].into(),
            author_sign_pk: &author_pk1,
        }
    );
    should_fail!(
        "wrong `author`",
        Context {
            label: "some label",
            parent: CmdId::default(),
            author_sign_pk: &author_pk2,
        }
    );
}

/// Negative test for a modified ciphertext.
pub fn test_group_key_open_bad_ciphertext<E: Engine>(eng: &E) {
    const INPUT: &[u8] = b"hello, world!";

    let author_sign_pk = DeviceSigningKey::<E::CS>::new(eng)
        .public()
        .expect("author signing key should be valid");

    let gk = GroupKey::new(eng);
    let mut ciphertext = {
        let mut dst = vec![0u8; INPUT.len() + gk.overhead()];
        gk.seal(
            eng,
            &mut dst,
            INPUT,
            Context {
                label: "some label",
                parent: CmdId::default(),
                author_sign_pk: &author_sign_pk,
            },
        )
        .expect("should succeed");
        dst
    };

    ciphertext[0] = ciphertext[0].wrapping_add(1);

    let mut dst = vec![0u8; ciphertext.len() - gk.overhead()];
    let err = gk
        .open(
            &mut dst,
            &ciphertext,
            Context {
                label: "some label",
                parent: CmdId::default(),
                author_sign_pk: &author_sign_pk,
            },
        )
        .expect_err("should have failed");
    assert_eq!(err, Error::Open(OpenError::Authentication));
}

/// Test encoding/decoding [`EncryptedGroupKey`].
pub fn test_encrypted_group_key_encode<E: Engine>(eng: &E)
where
    <<E::CS as CipherSuite>::Aead as Aead>::Overhead: Add<U64>,
    Sum<<<E::CS as CipherSuite>::Aead as Aead>::Overhead, U64>: ArrayLength,
{
    let enc_key = EncryptionKey::<E::CS>::new(eng);

    let group = GroupId::default();
    let want = GroupKey::new(eng);
    let (enc, ciphertext) = enc_key
        .public()
        .expect("encryption public key should be valid")
        .seal_group_key(eng, &want, group)
        .expect("unable to encrypt `GroupKey`");
    let enc = Encap::<E::CS>::from_bytes(enc.as_bytes()).expect("should be able to decode `Encap`");
    let ciphertext: EncryptedGroupKey<E::CS> = cbor::from_bytes(
        &cbor::to_allocvec(&ciphertext).expect("should be able to encode `EncryptedGroupKey`"),
    )
    .expect("should be able to decode `EncryptedGroupKey`");
    let got = enc_key
        .open_group_key(&enc, ciphertext, group)
        .expect("unable to decrypt `GroupKey`");
    assert_eq!(want.id(), got.id());
}

/// Simple test for [`SenderSigningKey`].
/// Creates a signature over an encoded record.
pub fn test_simple_sender_signing_key_sign<E: Engine>(eng: &E)
where
    <<E::CS as CipherSuite>::Aead as Aead>::Overhead: Add<U64>,
    Sum<<<E::CS as CipherSuite>::Aead as Aead>::Overhead, U64>: ArrayLength,
{
    const RECORD: &[u8] = b"some encoded record";

    const VERSION: Version = Version::new(1);
    let topic = Topic::new("SomeTopic");

    let sign_key = SenderSigningKey::<E::CS>::new(eng);
    let sig = sign_key
        .sign(VERSION, &topic, RECORD)
        .expect("unable to create signature");

    sign_key
        .public()
        .expect("sender signing key should be valid")
        .verify(VERSION, &topic, RECORD, &sig)
        .expect("the signature should be valid");

    sign_key
        .public()
        .expect("sender signing key should be valid")
        .verify(Version::new(VERSION.as_u32() + 1), &topic, RECORD, &sig)
        .expect_err("should fail: wrong version");

    sign_key
        .public()
        .expect("sender signing key should be valid")
        .verify(VERSION, &Topic::new("WrongTopic"), RECORD, &sig)
        .expect_err("should fail: wrong topic");

    sign_key
        .public()
        .expect("sender signing key should be valid")
        .verify(VERSION, &topic, b"wrong", &sig)
        .expect_err("should fail: wrong record");

    let wrong_sig = sign_key
        .sign(
            Version::new(VERSION.as_u32() + 1),
            &Topic::new("AnotherTopic"),
            b"encoded record",
        )
        .expect("should not fail to create signature");

    sign_key
        .public()
        .expect("sender signing key should be valid")
        .verify(VERSION, &topic, RECORD, &wrong_sig)
        .expect_err("should fail: wrong signature");
}

/// Simple positive test for encrypting/decrypting
/// [`TopicKey`]s.
pub fn test_simple_seal_topic_key<E: Engine>(eng: &E)
where
    <<E::CS as CipherSuite>::Aead as Aead>::Overhead: Add<U64>,
    Sum<<<E::CS as CipherSuite>::Aead as Aead>::Overhead, U64>: ArrayLength,
{
    let send_sk = SenderSecretKey::<E::CS>::new(eng);
    let send_pk = send_sk.public().expect("sender public key should be valid");
    let recv_sk = ReceiverSecretKey::<E::CS>::new(eng);
    let recv_pk = recv_sk
        .public()
        .expect("receiver public key should be valid");

    const VERSION: Version = Version::new(1);
    let topic = Topic::new("SomeTopic");

    let want = TopicKey::new(eng, VERSION, &topic).expect("unable to create new `TopicKey`");
    let (enc, ciphertext) = recv_pk
        .seal_topic_key(eng, VERSION, &topic, &send_sk, &want)
        .expect("unable to encrypt `TopicKey`");
    let enc = Encap::<E::CS>::from_bytes(enc.as_bytes()).expect("should be able to decode `Encap`");
    let ciphertext = EncryptedTopicKey::<E::CS>::from_bytes(ciphertext.as_bytes())
        .expect("should be able to decode `EncryptedTopicKey`");
    let got = recv_sk
        .open_topic_key(VERSION, &topic, &send_pk, &enc, &ciphertext)
        .expect("unable to decrypt `TopicKey`");
    assert_eq!(want.id(), got.id());
}

/// Simple positive test for wrapping [`SenderSecretKey`]s.
pub fn test_simple_wrap_device_sender_secret_key<E: Engine>(eng: &E) {
    let want = SenderSecretKey::new(eng);
    let bytes = cbor::to_allocvec(
        &eng.wrap(want.clone())
            .expect("should be able to wrap `SenderSecretKey`"),
    )
    .expect("should be able to encode wrapped `SenderSecretKey`");
    let wrapped = cbor::from_bytes(&bytes)
        .expect("should be able to decode encoded wrapped `SenderSecretKey`");
    let got: SenderSecretKey<E::CS> = eng
        .unwrap(&wrapped)
        .expect("should be able to unwrap `SenderSecretKey`");
    assert_eq!(want.id(), got.id());
}

/// Simple positive test for wrapping [`SenderSigningKey`]s.
pub fn test_simple_wrap_device_sender_signing_key<E: Engine>(eng: &E) {
    let want = SenderSigningKey::new(eng);
    let bytes = cbor::to_allocvec(
        &eng.wrap(want.clone())
            .expect("should be able to wrap `SenderSigningKey`"),
    )
    .expect("should be able to encode wrapped `SenderSigningKey`");
    let wrapped = cbor::from_bytes(&bytes)
        .expect("should be able to decode encoded wrapped `SenderSigningKey`");
    let got: SenderSigningKey<E::CS> = eng
        .unwrap(&wrapped)
        .expect("should be able to unwrap `SenderSigningKey`");
    assert_eq!(want.id(), got.id());
}

/// Simple positive test for wrapping [`ReceiverSecretKey`]s.
pub fn test_simple_wrap_device_receiver_secret_key<E: Engine>(eng: &E) {
    let want = ReceiverSecretKey::new(eng);
    let bytes = cbor::to_allocvec(
        &eng.wrap(want.clone())
            .expect("should be able to wrap `ReceiverSecretKey`"),
    )
    .expect("should be able to encode wrapped `ReceiverSecretKey`");
    let wrapped = cbor::from_bytes(&bytes)
        .expect("should be able to decode encoded wrapped `ReceiverSecretKey`");
    let got: ReceiverSecretKey<E::CS> = eng
        .unwrap(&wrapped)
        .expect("should be able to unwrap `ReceiverSecretKey`");
    assert_eq!(want.id(), got.id());
}

/// Simple positive test for encryption using a [`TopicKey`].
pub fn test_topic_key_seal<E: Engine>(eng: &E) {
    const INPUT: &[u8] = b"hello, world!";

    let ident = Sender {
        enc_key: &SenderSecretKey::<E::CS>::new(eng)
            .public()
            .expect("sender public encryption key should be valid"),
        sign_key: &SenderSigningKey::<E::CS>::new(eng)
            .public()
            .expect("sender public signing key should be valid"),
    };

    const VERSION: Version = Version::new(1);
    let topic = Topic::new("SomeTopic");

    let tk = TopicKey::new(eng, VERSION, &topic).expect("unable to create new `TopicKey`");
    let ciphertext = {
        let mut dst = vec![0u8; INPUT.len() + tk.overhead()];
        tk.seal_message(eng, &mut dst, INPUT, VERSION, &topic, &ident)
            .expect("should succeed");
        dst
    };
    let plaintext = {
        let mut dst = vec![0u8; ciphertext.len() - tk.overhead()];
        tk.open_message(&mut dst, &ciphertext, VERSION, &topic, &ident)
            .expect("should succeed");
        dst
    };
    assert_eq!(&plaintext, INPUT);
}

/// Negative test for the wrong [`TopicKey`].
pub fn test_topic_key_open_wrong_key<E: Engine>(eng: &E) {
    const INPUT: &[u8] = b"hello, world!";

    let ident = Sender {
        enc_key: &SenderSecretKey::<E::CS>::new(eng)
            .public()
            .expect("sender public encryption key should be valid"),
        sign_key: &SenderSigningKey::<E::CS>::new(eng)
            .public()
            .expect("sender public signing key should be valid"),
    };

    const VERSION: Version = Version::new(1);
    let topic = Topic::new("SomeTopic");

    let tk1 = TopicKey::new(eng, VERSION, &topic).expect("unable to create new `TopicKey`");
    let tk2 = TopicKey::new(eng, VERSION, &topic).expect("unable to create new `TopicKey`");

    let ciphertext = {
        let mut dst = vec![0u8; INPUT.len() + tk1.overhead()];
        tk1.seal_message(eng, &mut dst, INPUT, VERSION, &topic, &ident)
            .expect("should succeed");
        dst
    };
    let mut dst = vec![0u8; ciphertext.len() - tk2.overhead()];
    let err = tk2
        .open_message(&mut dst, &ciphertext, VERSION, &topic, &ident)
        .expect_err("should have failed");
    assert_eq!(err, Error::Open(OpenError::Authentication));
}

/// Negative test for the wrong [`Context`].
pub fn test_topic_key_open_wrong_context<E: Engine>(eng: &E) {
    const INPUT: &[u8] = b"hello, world!";

    let ident = Sender {
        enc_key: &SenderSecretKey::<E::CS>::new(eng)
            .public()
            .expect("sender public encryption key should be valid"),
        sign_key: &SenderSigningKey::<E::CS>::new(eng)
            .public()
            .expect("sender public signing key should be valid"),
    };
    let wrong_ident = Sender {
        enc_key: &SenderSecretKey::<E::CS>::new(eng)
            .public()
            .expect("sender public encryption key should be valid"),
        sign_key: &SenderSigningKey::<E::CS>::new(eng)
            .public()
            .expect("sender public signing key should be valid"),
    };

    const VERSION: Version = Version::new(1);
    let topic = Topic::new("SomeTopic");

    let tk = TopicKey::new(eng, VERSION, &topic).expect("unable to create `TopicKey`");
    let ciphertext = {
        let mut dst = vec![0u8; INPUT.len() + tk.overhead()];
        tk.seal_message(eng, &mut dst, INPUT, VERSION, &topic, &ident)
            .expect("should succeed");
        dst
    };

    macro_rules! should_fail {
        ($msg:expr, $version:expr, $topic:expr, $ident:expr) => {
            let mut dst = vec![0u8; ciphertext.len() - tk.overhead()];
            let err = tk
                .open_message(&mut dst, &ciphertext, $version, $topic, $ident)
                .expect_err("should have failed");
            assert_eq!(err, Error::Open(OpenError::Authentication), $msg);
        };
    }
    should_fail!(
        "wrong version",
        Version::new(VERSION.as_u32() + 1),
        &topic,
        &ident
    );
    should_fail!("wrong topic", VERSION, &Topic::new("WrongTopic"), &ident);
    should_fail!("wrong ident", VERSION, &topic, &wrong_ident);
}

/// Negative test for a modified ciphertext.
pub fn test_topic_key_open_bad_ciphertext<E: Engine>(eng: &E) {
    const INPUT: &[u8] = b"hello, world!";

    let ident = Sender {
        enc_key: &SenderSecretKey::<E::CS>::new(eng)
            .public()
            .expect("sender public encryption key should be valid"),
        sign_key: &SenderSigningKey::<E::CS>::new(eng)
            .public()
            .expect("sender public signing key should be valid"),
    };

    const VERSION: Version = Version::new(1);
    let topic = Topic::new("SomeTopic");

    let tk = TopicKey::new(eng, VERSION, &topic).expect("unable to create `TopicKey`");
    let mut ciphertext = {
        let mut dst = vec![0u8; INPUT.len() + tk.overhead()];
        tk.seal_message(eng, &mut dst, INPUT, VERSION, &topic, &ident)
            .expect("should succeed");
        dst
    };

    ciphertext[0] = ciphertext[0].wrapping_add(1);

    let mut dst = vec![0u8; ciphertext.len() - tk.overhead()];
    let err = tk
        .open_message(&mut dst, &ciphertext, VERSION, &topic, &ident)
        .expect_err("should have failed");
    assert_eq!(err, Error::Open(OpenError::Authentication));
}

/// Checks that `open` can decrypt ciphertexts from `seal`.
fn assert_same_afc_keys<CS: CipherSuite>(seal: &mut afc::SealKey<CS>, open: &afc::OpenKey<CS>) {
    const GOLDEN: &str = "hello, world!";
    let ad: afc::AuthData = afc::AuthData {
        version: 1,
        label_id: LabelId::random(Rng),
    };

    let (ciphertext, seq) = {
        let mut dst = vec![0u8; GOLDEN.len() + afc::SealKey::<CS>::OVERHEAD];
        let seq = seal
            .seal(&mut dst, GOLDEN.as_bytes(), &ad)
            .expect("should be able to encrypt plaintext");
        (dst, seq)
    };

    let mut plaintext = vec![0u8; ciphertext.len() - afc::OpenKey::<CS>::OVERHEAD];
    open.open(&mut plaintext, &ciphertext, &ad, seq)
        .expect("decryption failed; keys differ");

    assert_eq!(
        GOLDEN.as_bytes(),
        &plaintext,
        "`afc::OpenKey` produced incorrect plaintext"
    );
}

/// Checks that `open` cannot decrypt ciphertexts from
/// `seal`.
///
/// If `seal` is `None` then a random key will be used.
fn assert_different_afc_keys<E: Engine>(
    eng: &E,
    seal: Option<afc::SealKey<E::CS>>,
    open: &afc::OpenKey<E::CS>,
) {
    const GOLDEN: &str = "hello, world!";
    let ad: afc::AuthData = afc::AuthData {
        version: 1,
        label_id: LabelId::random(Rng),
    };

    let (ciphertext, seq) = {
        let mut dst = vec![0u8; GOLDEN.len() + afc::SealKey::<E::CS>::OVERHEAD];
        let seq = seal
            .unwrap_or_else(|| {
                afc::SealKey::from_raw(&Random::random(eng), afc::Seq::ZERO)
                    .expect("should be able to generate random `afc::SealKey`")
            })
            .seal(&mut dst, GOLDEN.as_bytes(), &ad)
            .expect("should be able to encrypt plaintext");
        (dst, seq)
    };

    let mut plaintext = vec![0u8; ciphertext.len() - afc::OpenKey::<E::CS>::OVERHEAD];
    let err = open
        .open(&mut plaintext, &ciphertext, &ad, seq)
        .expect_err("should not be able to decrypt ciphertext with mismatched keys");
    assert_eq!(
        err,
        afc::OpenError::Authentication,
        "should have received `Authentication` error"
    );
}

/// A simple positive test for [`afc::SealKey`] and [`afc::OpenKey`].
pub fn test_afc_same_seal_key_open_key<E: Engine>(eng: &E) {
    let raw: afc::RawSealKey<E::CS> = Random::random(eng);
    let mut seal = afc::SealKey::<E::CS>::from_raw(&raw, afc::Seq::ZERO)
        .expect("should be able to create `afc::SealKey`");
    let open = afc::OpenKey::<E::CS>::from_raw(&raw.into())
        .expect("should be able to create `afc::OpenKey`");
    assert_same_afc_keys(&mut seal, &open);
}

/// A simple negative test for [`afc::SealKey`] and [`afc::OpenKey`].
pub fn test_afc_different_seal_key_open_key<E: Engine>(eng: &E) {
    let seal = afc::SealKey::from_raw(&Random::random(eng), afc::Seq::ZERO)
        .expect("should be able to create `afc::SealKey`");
    let open = afc::OpenKey::from_raw(&Random::random(eng))
        .expect("should be able to create `afc::OpenKey`");
    assert_different_afc_keys(eng, Some(seal), &open);
    assert_different_afc_keys(eng, None, &open);
}

/// Tests that [`afc::SealKey`]'s sequence number monotonically
/// advances by one each time.
pub fn test_afc_seal_key_monotonic_seq_number<E: Engine>(eng: &E) {
    let mut seal = afc::SealKey::<E::CS>::from_raw(&Random::random(eng), afc::Seq::ZERO)
        .expect("should be able to create `afc::SealKey`");

    const GOLDEN: &str = "hello, world!";
    let ad: afc::AuthData = afc::AuthData {
        version: 1,
        label_id: LabelId::random(Rng),
    };
    let mut dst = vec![0u8; GOLDEN.len() + afc::SealKey::<E::CS>::OVERHEAD];
    // The upper bound is arbitrary. We obviously cannot test
    // all 2^61-1 integers.
    for idx in 0..u16::MAX {
        let seq = seal
            .seal(&mut dst, GOLDEN.as_bytes(), &ad)
            .expect("should be able to encrypt plaintext");
        assert_eq!(seq, afc::Seq::new(u64::from(idx)));
    }
}

/// Tests that [`afc::SealKey`] refuses to encrypt when its
/// sequence number has been exhausted.
pub fn test_afc_seal_key_seq_number_exhausted<E: Engine>(eng: &E) {
    let max = afc::Seq::max::<<<E::CS as CipherSuite>::Aead as Aead>::NonceSize>();
    // Start at one before the max.
    let start = afc::Seq::new(max - 1);
    let mut seal = afc::SealKey::<E::CS>::from_raw(&Random::random(eng), start)
        .expect("should be able to create `afc::SealKey`");

    const GOLDEN: &str = "hello, world!";
    let ad: afc::AuthData = afc::AuthData {
        version: 1,
        label_id: LabelId::random(Rng),
    };
    let mut dst = vec![0u8; GOLDEN.len() + afc::SealKey::<E::CS>::OVERHEAD];

    // The first encryption should succeed since seq < max.
    let seq = seal
        .seal(&mut dst, GOLDEN.as_bytes(), &ad)
        .expect("should be able to encrypt plaintext");
    assert_eq!(seq, afc::Seq::new(max - 1));

    // All encryptions afterward should fail since seq >=
    // max.
    let err = seal
        .seal(&mut dst, GOLDEN.as_bytes(), &ad)
        .expect_err("sequence counter should be exhausted");
    assert_eq!(err, afc::SealError::MessageLimitReached);
}

/// Tests that [`afc::OpenKey`] refuses to decrypt when the
/// sequence number has been exhausted.
pub fn test_afc_open_key_seq_number_exhausted<E: Engine>(eng: &E) {
    let raw: afc::RawSealKey<E::CS> = Random::random(eng);
    let mut seal = afc::SealKey::<E::CS>::from_raw(&raw, afc::Seq::ZERO)
        .expect("should be able to create `afc::SealKey`");
    let open =
        afc::OpenKey::from_raw(&raw.into()).expect("should be able to create `afc::OpenKey`");
    assert_same_afc_keys(&mut seal, &open);

    const GOLDEN: &str = "hello, world!";
    let ad: afc::AuthData = afc::AuthData {
        version: 1,
        label_id: LabelId::random(Rng),
    };
    let mut ciphertext = vec![0u8; GOLDEN.len() + afc::SealKey::<E::CS>::OVERHEAD];
    let mut plaintext = vec![0u8; ciphertext.len() - afc::OpenKey::<E::CS>::OVERHEAD];

    // `afc::OpenKey` should reject the sequence number before
    // attempting to decrypt the ciphertext, but start with
    // a valid ciphertext anyway.
    seal.seal(&mut ciphertext, GOLDEN.as_bytes(), &ad)
        .expect("should be able to encrypt plaintext");

    let exhausted_seq = afc::Seq::new(afc::Seq::max::<
        <<E::CS as CipherSuite>::Aead as Aead>::NonceSize,
    >());
    // Decryption should fail since seq >= max.
    let err = open
        .open(&mut plaintext, &ciphertext, &ad, exhausted_seq)
        .expect_err("should not be able to decrypt ciphertext with exhausted seq number");
    assert_eq!(
        err,
        afc::OpenError::MessageLimitReached,
        "should have received `MessageLimitReached` error"
    );
}

/// Tests that [`afc::OpenKey`]'s fails when the incorrect
/// sequence number is provided.
pub fn test_afc_open_key_wrong_seq_number<E: Engine>(eng: &E) {
    let raw: afc::RawSealKey<E::CS> = Random::random(eng);
    let mut seal = afc::SealKey::<E::CS>::from_raw(&raw, afc::Seq::ZERO)
        .expect("should be able to create `afc::SealKey`");
    let open =
        afc::OpenKey::from_raw(&raw.into()).expect("should be able to create `afc::OpenKey`");
    assert_same_afc_keys(&mut seal, &open);

    const GOLDEN: &str = "hello, world!";
    let ad: afc::AuthData = afc::AuthData {
        version: 1,
        label_id: LabelId::random(Rng),
    };
    let mut ciphertext = vec![0u8; GOLDEN.len() + afc::SealKey::<E::CS>::OVERHEAD];
    let mut plaintext = vec![0u8; ciphertext.len() - afc::OpenKey::<E::CS>::OVERHEAD];
    for _ in 0..100 {
        let seq = seal
            .seal(&mut ciphertext, GOLDEN.as_bytes(), &ad)
            .expect("should be able to encrypt plaintext");

        let wrong_seq = afc::Seq::new(seq.to_u64() + 1);
        let err = open
            .open(&mut plaintext, &ciphertext, &ad, wrong_seq)
            .expect_err("should not be able to decrypt ciphertext with the wrong seq number");
        assert_eq!(
            err,
            afc::OpenError::Authentication,
            "should have received `Authentication` error"
        );
    }
}

/// Tests that [`afc::OpenKey`]'s fails when the incorrect
/// [`afc::AuthData`] is provided.
pub fn test_afc_open_key_wrong_auth_data<E: Engine>(eng: &E) {
    let raw: afc::RawSealKey<E::CS> = Random::random(eng);
    let mut seal = afc::SealKey::<E::CS>::from_raw(&raw, afc::Seq::ZERO)
        .expect("should be able to create `afc::SealKey`");
    let open =
        afc::OpenKey::from_raw(&raw.into()).expect("should be able to create `afc::OpenKey`");
    assert_same_afc_keys(&mut seal, &open);

    const GOLDEN: &str = "hello, world!";
    let good_ad: afc::AuthData = afc::AuthData {
        version: 1,
        label_id: LabelId::random(Rng),
    };
    let bad_ad: afc::AuthData = afc::AuthData {
        version: 3,
        label_id: LabelId::random(Rng),
    };

    let mut ciphertext = vec![0u8; GOLDEN.len() + afc::SealKey::<E::CS>::OVERHEAD];
    let seq = seal
        .seal(&mut ciphertext, GOLDEN.as_bytes(), &good_ad)
        .expect("should be able to encrypt plaintext");

    let mut plaintext = vec![0u8; ciphertext.len() - afc::OpenKey::<E::CS>::OVERHEAD];
    let err = open
        .open(&mut plaintext, &ciphertext, &bad_ad, seq)
        .expect_err("should not be able to decrypt ciphertext with the wrong `afc::AuthData`");
    assert_eq!(
        err,
        afc::OpenError::Authentication,
        "should have received `Authentication` error"
    );
}

/// Checks that `seal` and `open` are the same key.
fn assert_same_afc_uni_key<CS: CipherSuite>(seal: afc::UniSealKey<CS>, open: afc::UniOpenKey<CS>) {
    // Simple test: they should have the same bytes.
    {
        let seal = seal.as_raw_key();
        let open = open.as_raw_key();
        assert_ct_eq!(seal.to_testing_key(), open.to_testing_key());
    }

    // Double check that the `to_testing_key` impls are
    // correct: actually perform encryption.
    let mut seal = seal.into_key().expect("should have got `afc::SealKey`");
    let open = open.into_key().expect("should have got `afc::OpenKey`");
    assert_same_afc_keys(&mut seal, &open);
}

/// Checks that `seal` and `open` are different keys.
fn assert_different_afc_uni_key<E: Engine>(
    eng: &E,
    seal: afc::UniSealKey<E::CS>,
    open: afc::UniOpenKey<E::CS>,
) {
    // Simple test: they should not have the same bytes.
    {
        let seal = seal.as_raw_key();
        let open = open.as_raw_key();
        assert_ct_ne!(seal.to_testing_key(), open.to_testing_key());
    }

    // Double check that the `to_testing_key` impls are
    // correct: actually perform encryption, which should
    // fail.
    //
    // First check with `open` with `seal`.
    let seal = seal.into_key().expect("should have got `afc::SealKey`");
    let open = open.into_key().expect("should have got `afc::OpenKey`");
    assert_different_afc_keys(eng, Some(seal), &open);

    // Then also check `open` with a randomly generated key.
    assert_different_afc_keys(eng, None, &open);
}

/// A simple positive test for deriving [`afc::UniSealKey`] and
/// [`afc::UniOpenKey`].
pub fn test_afc_derive_uni_key<E: Engine>(eng: &E) {
    let sk1 = EncryptionKey::<E::CS>::new(eng);
    let sk2 = EncryptionKey::<E::CS>::new(eng);
    let label_id = LabelId::random(eng);
    let ch1 = afc::UniChannel {
        parent_cmd_id: CmdId::random(eng),
        our_sk: &sk1,
        their_pk: &sk2
            .public()
            .expect("receiver public encryption key should be valid"),
        seal_id: IdentityKey::<E::CS>::new(eng)
            .id()
            .expect("seal id should be valid"),
        open_id: IdentityKey::<E::CS>::new(eng)
            .id()
            .expect("open id should be valid"),
        label_id,
    };
    let ch2 = afc::UniChannel {
        parent_cmd_id: ch1.parent_cmd_id,
        our_sk: &sk2,
        their_pk: &sk1
            .public()
            .expect("receiver public encryption key should be valid"),
        seal_id: ch1.seal_id,
        open_id: ch1.open_id,
        label_id,
    };
    assert_eq!(ch1.info(), ch2.info());

    let afc::UniSecrets { author, peer } =
        afc::UniSecrets::new(eng, &ch1).expect("unable to create `afc::UniSecrets`");
    let ck1 = afc::UniSealKey::from_author_secret(&ch1, author)
        .expect("unable to decrypt author `afc::UniSealKey`");
    let ck2 = afc::UniOpenKey::from_peer_encap(&ch2, peer)
        .expect("unable to decrypt peer `afc::UniOpenKey`");

    assert_same_afc_uni_key(ck1, ck2);
}

/// Different labels should create different [`afc::UniSealKey`]
/// and [`afc::UniOpenKey`]s.
pub fn test_afc_derive_uni_key_different_labels<E: Engine>(eng: &E) {
    let sk1 = EncryptionKey::<E::CS>::new(eng);
    let sk2 = EncryptionKey::<E::CS>::new(eng);
    let ch1 = afc::UniChannel {
        parent_cmd_id: CmdId::random(eng),
        our_sk: &sk1,
        their_pk: &sk2
            .public()
            .expect("receiver public encryption key should be valid"),
        seal_id: IdentityKey::<E::CS>::new(eng)
            .id()
            .expect("seal id should be valid"),
        open_id: IdentityKey::<E::CS>::new(eng)
            .id()
            .expect("open id should be valid"),
        label_id: LabelId::random(eng),
    };
    let ch2 = afc::UniChannel {
        parent_cmd_id: ch1.parent_cmd_id,
        our_sk: &sk2,
        their_pk: &sk1
            .public()
            .expect("receiver public encryption key should be valid"),
        seal_id: ch1.seal_id,
        open_id: ch1.open_id,
        label_id: LabelId::random(eng),
    };
    assert_ne!(ch1.info(), ch2.info());

    let afc::UniSecrets { author, peer } =
        afc::UniSecrets::new(eng, &ch1).expect("unable to create `afc::UniSecrets`");
    let ck1 = afc::UniSealKey::from_author_secret(&ch1, author)
        .expect("unable to decrypt author `afc::UniSealKey`");
    let ck2 = afc::UniOpenKey::from_peer_encap(&ch2, peer)
        .expect("unable to decrypt peer `afc::UniOpenKey`");

    assert_different_afc_uni_key(eng, ck1, ck2);
}

/// Different DeviceIDs should create different
/// [`afc::UniSealKey`] and [`afc::UniOpenKey`]s.
///
/// E.g., derive(label, u1, u2, c1) != derive(label, u2, u3, c1).
pub fn test_afc_derive_uni_key_different_device_ids<E: Engine>(eng: &E) {
    let label_id = LabelId::random(eng);
    let sk1 = EncryptionKey::<E::CS>::new(eng);
    let sk2 = EncryptionKey::<E::CS>::new(eng);
    let ch1 = afc::UniChannel {
        parent_cmd_id: CmdId::random(eng),
        our_sk: &sk1,
        their_pk: &sk2
            .public()
            .expect("receiver public encryption key should be valid"),
        seal_id: IdentityKey::<E::CS>::new(eng)
            .id()
            .expect("seal id should be valid"),
        open_id: IdentityKey::<E::CS>::new(eng)
            .id()
            .expect("open id should be valid"),
        label_id,
    };
    let ch2 = afc::UniChannel {
        parent_cmd_id: ch1.parent_cmd_id,
        our_sk: &sk2,
        their_pk: &sk1
            .public()
            .expect("receiver public encryption key should be valid"),
        seal_id: ch1.seal_id,
        open_id: DeviceId::random(eng),
        label_id,
    };
    assert_ne!(ch1.info(), ch2.info());

    let afc::UniSecrets { author, peer } =
        afc::UniSecrets::new(eng, &ch1).expect("unable to create `afc::UniSecrets`");
    let ck1 = afc::UniSealKey::from_author_secret(&ch1, author)
        .expect("unable to decrypt author `afc::UniSealKey`");
    let ck2 = afc::UniOpenKey::from_peer_encap(&ch2, peer)
        .expect("unable to decrypt peer `afc::UniOpenKey`");

    assert_different_afc_uni_key(eng, ck1, ck2);
}

/// Different command IDs should create different
/// [`afc::UniSealKey`] and [`afc::UniOpenKey`]s.
///
/// E.g., derive(label, u1, u2, c1) != derive(label, u2, u1, c2).
pub fn test_afc_derive_uni_key_different_cmd_ids<E: Engine>(eng: &E) {
    let label_id = LabelId::random(eng);
    let sk1 = EncryptionKey::<E::CS>::new(eng);
    let sk2 = EncryptionKey::<E::CS>::new(eng);
    let ch1 = afc::UniChannel {
        parent_cmd_id: CmdId::random(eng),
        our_sk: &sk1,
        their_pk: &sk2
            .public()
            .expect("receiver public encryption key should be valid"),
        seal_id: IdentityKey::<E::CS>::new(eng)
            .id()
            .expect("seal id should be valid"),
        open_id: IdentityKey::<E::CS>::new(eng)
            .id()
            .expect("open id should be valid"),
        label_id,
    };
    let ch2 = afc::UniChannel {
        parent_cmd_id: CmdId::random(eng),
        our_sk: &sk2,
        their_pk: &sk1
            .public()
            .expect("receiver public encryption key should be valid"),
        seal_id: ch1.seal_id,
        open_id: ch1.open_id,
        label_id,
    };
    assert_ne!(ch1.info(), ch2.info());

    let afc::UniSecrets { author, peer } =
        afc::UniSecrets::new(eng, &ch1).expect("unable to create `afc::UniSecrets`");
    let ck1 = afc::UniSealKey::from_author_secret(&ch1, author)
        .expect("unable to decrypt author `afc::UniSealKey`");
    let ck2 = afc::UniOpenKey::from_peer_encap(&ch2, peer)
        .expect("unable to decrypt peer `afc::UniOpenKey`");

    assert_different_afc_uni_key(eng, ck1, ck2);
}

/// Different encryption keys should create different
/// [`afc::UniSealKey`] and [`afc::UniOpenKey`]s.
///
/// E.g., derive(label, u1, u2, c1) != derive(label, u2, u1, c2).
pub fn test_afc_derive_uni_key_different_keys<E: Engine>(eng: &E) {
    let label_id = LabelId::random(eng);
    let sk1 = EncryptionKey::<E::CS>::new(eng);
    let sk2 = EncryptionKey::<E::CS>::new(eng);
    let ch1 = afc::UniChannel {
        parent_cmd_id: CmdId::random(eng),
        our_sk: &sk1,
        their_pk: &sk2
            .public()
            .expect("receiver public encryption key should be valid"),
        seal_id: IdentityKey::<E::CS>::new(eng)
            .id()
            .expect("seal id should be valid"),
        open_id: IdentityKey::<E::CS>::new(eng)
            .id()
            .expect("open id should be valid"),
        label_id,
    };
    let ch2 = afc::UniChannel {
        parent_cmd_id: ch1.parent_cmd_id,
        our_sk: &sk2,
        their_pk: &EncryptionKey::<E::CS>::new(eng)
            .public()
            .expect("receiver public encryption key should be valid"),
        seal_id: ch1.seal_id,
        open_id: ch1.open_id,
        label_id,
    };

    let afc::UniSecrets { author, peer } =
        afc::UniSecrets::new(eng, &ch1).expect("unable to create `afc::UniSecrets`");
    let ck1 = afc::UniSealKey::from_author_secret(&ch1, author)
        .expect("unable to decrypt author `afc::UniSealKey`");
    let ck2 = afc::UniOpenKey::from_peer_encap(&ch2, peer)
        .expect("unable to decrypt peer `afc::UniOpenKey`");

    assert_different_afc_uni_key(eng, ck1, ck2);
}

/// It is an error to use the same `DeviceId` when deriving
/// [`afc::UniSealKey`]s.
pub fn test_afc_derive_uni_seal_key_same_device_id<E: Engine>(eng: &E) {
    let label_id = LabelId::random(eng);
    let sk1 = EncryptionKey::<E::CS>::new(eng);
    let sk2 = EncryptionKey::<E::CS>::new(eng);
    let mut ch1 = afc::UniChannel {
        parent_cmd_id: CmdId::random(eng),
        our_sk: &sk1,
        their_pk: &sk2
            .public()
            .expect("receiver public encryption key should be valid"),
        seal_id: IdentityKey::<E::CS>::new(eng)
            .id()
            .expect("seal id should be valid"),
        open_id: IdentityKey::<E::CS>::new(eng)
            .id()
            .expect("open id should be valid"),
        label_id,
    };
    let mut ch2 = afc::UniChannel {
        parent_cmd_id: ch1.parent_cmd_id,
        our_sk: &sk2,
        their_pk: &EncryptionKey::<E::CS>::new(eng)
            .public()
            .expect("receiver public encryption key should be valid"),
        seal_id: ch1.seal_id,
        open_id: ch1.open_id,
        label_id,
    };
    assert_eq!(ch1.info(), ch2.info());

    let afc::UniSecrets { peer, .. } = {
        let prev = ch1.seal_id;
        ch1.seal_id = ch1.open_id;

        let err = afc::UniSecrets::new(eng, &ch1)
            .err()
            .expect("should not be able to create `afc::UniSecrets`");
        assert_eq!(err, Error::same_device_id());

        ch1.seal_id = prev;
        afc::UniSecrets::new(eng, &ch1).expect("unable to create `afc::UniSecrets`")
    };

    ch2.seal_id = ch2.open_id;
    let err = afc::UniSealKey::from_peer_encap(&ch2, peer)
        .err()
        .expect("should not be able to decrypt `afc::UniSealKey`");
    assert_eq!(err, Error::same_device_id());
}

/// It is an error to use the same `DeviceId` when deriving
/// [`afc::UniOpenKey`]s.
pub fn test_afc_derive_uni_open_key_same_device_id<E: Engine>(eng: &E) {
    let label_id = LabelId::random(eng);
    let sk1 = EncryptionKey::<E::CS>::new(eng);
    let sk2 = EncryptionKey::<E::CS>::new(eng);
    let mut ch1 = afc::UniChannel {
        parent_cmd_id: CmdId::random(eng),
        our_sk: &sk1,
        their_pk: &sk2
            .public()
            .expect("receiver public encryption key should be valid"),
        seal_id: IdentityKey::<E::CS>::new(eng)
            .id()
            .expect("seal id should be valid"),
        open_id: IdentityKey::<E::CS>::new(eng)
            .id()
            .expect("open id should be valid"),
        label_id,
    };
    let mut ch2 = afc::UniChannel {
        parent_cmd_id: ch1.parent_cmd_id,
        our_sk: &sk2,
        their_pk: &EncryptionKey::<E::CS>::new(eng)
            .public()
            .expect("receiver public encryption key should be valid"),
        seal_id: ch1.seal_id,
        open_id: ch1.open_id,
        label_id,
    };
    assert_eq!(ch1.info(), ch2.info());

    let afc::UniSecrets { peer, .. } = {
        let prev = ch1.seal_id;
        ch1.seal_id = ch1.open_id;

        let err = afc::UniSecrets::new(eng, &ch1)
            .err()
            .expect("should not be able to create `afc::UniSecrets`");
        assert_eq!(err, Error::same_device_id());

        ch1.seal_id = prev;
        afc::UniSecrets::new(eng, &ch1).expect("unable to create `afc::UniSecrets`")
    };

    ch2.seal_id = ch2.open_id;
    let err = afc::UniOpenKey::from_peer_encap(&ch2, peer)
        .err()
        .expect("should not be able to decrypt `afc::UniOpenKey`");
    assert_eq!(err, Error::same_device_id());
}

/// Simple positive test for wrapping [`afc::UniAuthorSecret`]s.
pub fn test_afc_wrap_uni_author_secret<E: Engine>(eng: &E) {
    let sk1 = EncryptionKey::new(eng);
    let sk2 = EncryptionKey::new(eng);
    let ch = afc::UniChannel {
        parent_cmd_id: CmdId::random(eng),
        our_sk: &sk1,
        their_pk: &sk2
            .public()
            .expect("receiver public encryption key should be valid"),
        seal_id: IdentityKey::<E::CS>::new(eng)
            .id()
            .expect("seal id should be valid"),
        open_id: IdentityKey::<E::CS>::new(eng)
            .id()
            .expect("open id should be valid"),
        label_id: LabelId::random(eng),
    };

    let afc::UniSecrets { author: want, .. } =
        afc::UniSecrets::new(eng, &ch).expect("unable to create `afc::UniSecrets`");
    let bytes = cbor::to_allocvec(
        &eng.wrap(want.clone())
            .expect("should be able to wrap `afc::UniAuthorSecret`"),
    )
    .expect("should be able to encode wrapped `afc::UniAuthorSecret`");
    let wrapped = cbor::from_bytes(&bytes)
        .expect("should be able to decode encoded wrapped `afc::UniAuthorSecret`");
    let got: afc::UniAuthorSecret<E::CS> = eng
        .unwrap(&wrapped)
        .expect("should be able to unwrap `afc::UniAuthorSecret`");
    assert_ct_eq!(want, got);
}

/// Test that [`tls::PskSeed`] generates different PSKs for
/// different cipher suites.
pub fn test_tls_psk_different_suites<E: Engine>(eng: &E) {
    let seed = tls::PskSeed::<E::CS>::new(eng, &GroupId::default());

    let mut ids = BTreeSet::new();
    let mut secrets = BTreeSet::new();

    let psks = seed
        .generate_psks(
            b"context",
            GroupId::default(),
            PolicyId::default(),
            tls::CipherSuiteId::all().iter().copied(),
        )
        .collect::<Result<Vec<_>, _>>()
        .unwrap();
    for psk in &psks {
        let ident = psk.identity();
        if !ids.insert(ident.as_bytes()) {
            let cs = ident.cipher_suite();
            panic!("duplicate PSK identity for {cs}: {ident}");
        }
        if !secrets.insert(psk.raw_secret_bytes().to_vec()) {
            panic!(
                "duplicate PSK secret for {}: {:?}",
                psk.identity().cipher_suite(),
                psk.raw_secret_bytes(),
            );
        }
    }
}

/// Test that [`tls::PskSeed`] generates different PSKs for
/// different contexts.
pub fn test_tls_psk_different_contexts<E: Engine>(eng: &E) {
    let seed = tls::PskSeed::<E::CS>::new(eng, &GroupId::default());

    let psks1 = seed
        .clone()
        .generate_psks(
            b"CONTEXT",
            GroupId::default(),
            PolicyId::default(),
            tls::CipherSuiteId::all().iter().copied(),
        )
        .collect::<Result<Vec<_>, _>>()
        .unwrap();
    let psks2 = seed
        .generate_psks(
            b"different context",
            GroupId::default(),
            PolicyId::default(),
            tls::CipherSuiteId::all().iter().copied(),
        )
        .collect::<Result<Vec<_>, _>>()
        .unwrap();

    assert_eq!(psks1.len(), psks2.len());
    for (i, (lhs, rhs)) in psks1.into_iter().zip(psks2).enumerate() {
        assert_ct_ne!(lhs, rhs, "#{i}");
    }
}

/// Test that [`tls::PskSeed`] generates different PSKs for
/// different groups.
pub fn test_tls_psk_different_groups<E: Engine>(eng: &E) {
    let seed = tls::PskSeed::<E::CS>::new(eng, &GroupId::default());

    let psks1 = seed
        .clone()
        .generate_psks(
            b"context",
            GroupId::random(eng),
            PolicyId::default(),
            tls::CipherSuiteId::all().iter().copied(),
        )
        .collect::<Result<Vec<_>, _>>()
        .unwrap();
    let psks2 = seed
        .generate_psks(
            b"context",
            GroupId::random(eng),
            PolicyId::default(),
            tls::CipherSuiteId::all().iter().copied(),
        )
        .collect::<Result<Vec<_>, _>>()
        .unwrap();

    assert_eq!(psks1.len(), psks2.len());
    for (i, (lhs, rhs)) in psks1.into_iter().zip(psks2).enumerate() {
        assert_ct_ne!(lhs, rhs, "#{i}");
    }
}

/// Test that [`tls::PskSeed`] generates different PSKs for
/// different policy IDs.
pub fn test_tls_psk_different_policy_ids<E: Engine>(eng: &E) {
    let seed = tls::PskSeed::<E::CS>::new(eng, &GroupId::default());

    let psks1 = seed
        .clone()
        .generate_psks(
            b"context",
            GroupId::default(),
            PolicyId::random(eng),
            tls::CipherSuiteId::all().iter().copied(),
        )
        .collect::<Result<Vec<_>, _>>()
        .unwrap();
    let psks2 = seed
        .generate_psks(
            b"context",
            GroupId::default(),
            PolicyId::random(eng),
            tls::CipherSuiteId::all().iter().copied(),
        )
        .collect::<Result<Vec<_>, _>>()
        .unwrap();

    assert_eq!(psks1.len(), psks2.len());
    for (i, (lhs, rhs)) in psks1.into_iter().zip(psks2).enumerate() {
        assert_ct_ne!(lhs, rhs, "#{i}");
    }
}

/// Simple positive test for wrapping [`tls::PskSeed`]s.
pub fn test_tls_psk_seed_simple_wrap<E: Engine>(eng: &E) {
    let want = tls::PskSeed::new(eng, &GroupId::default());
    let bytes = cbor::to_allocvec(
        &eng.wrap(want.clone())
            .expect("should be able to wrap `tls::PskSeed`"),
    )
    .expect("should be able to encode wrapped `tls::PskSeed`");
    let wrapped =
        cbor::from_bytes(&bytes).expect("should be able to decode encoded wrapped `tls::PskSeed`");
    let got: tls::PskSeed<E::CS> = eng
        .unwrap(&wrapped)
        .expect("should be able to unwrap `tls::PskSeed`");
    assert_eq!(want.id(), got.id());
}

/// Simple positive test for encrypting/decrypting
/// [`tls::PskSeed`]s.
pub fn test_tls_psk_seed_seal_open<E: Engine>(eng: &E) {
    let sk1 = EncryptionKey::<E::CS>::new(eng);
    let pk1 = sk1.public().expect("`sk1` public half should be valid");

    let sk2 = EncryptionKey::<E::CS>::new(eng);
    let pk2 = sk2.public().expect("`sk2` public half should be valid");

    let group = GroupId::default();
    let seed = tls::PskSeed::new(eng, &GroupId::default());

    let (enc, ct) = {
        let (enc, ct) = sk1
            .seal_psk_seed(eng, &seed, &pk2, &group)
            .expect("unable to encrypt `PskSeed`");

        // Make sure that we can encode and decode the encap and
        // ciphertext.
        let enc_buf = cbor::to_allocvec(&enc).expect("unable to encode `PskSeedEnc`");
        let ct_buf = cbor::to_allocvec(&ct).expect("unable to encode `PskSeedCt`");

        let enc = cbor::from_bytes(&enc_buf).expect("unable to decode `PskSeedEnc`");
        let ct = cbor::from_bytes(&ct_buf).expect("unable to decode `PskSeedCt`");
        (enc, ct)
    };

    let got = sk2
        .open_psk_seed(&enc, ct, &pk1, &group)
        .expect("unable to decrypt `PskSeed`");
    assert_ct_eq!(got, seed);
}

/// Negative test for decrypting a [`tls::PskSeed`] with the
/// wrong peer public key.
pub fn test_tls_psk_seed_open_wrong_peer_pk<E: Engine>(eng: &E) {
    let sk1 = EncryptionKey::<E::CS>::new(eng);

    let sk2 = EncryptionKey::<E::CS>::new(eng);
    let pk2 = sk2.public().expect("`sk2` public half should be valid");

    let sk3 = EncryptionKey::<E::CS>::new(eng);
    let pk3 = sk3.public().expect("`sk3` public half should be valid");

    assert_ne!(pk2, pk3); // pedantic

    let group = GroupId::default();
    let seed = tls::PskSeed::new(eng, &GroupId::default());
    let (enc, ct) = sk1
        .seal_psk_seed(eng, &seed, &pk2, &group)
        .expect("unable to encrypt `PskSeed`");
    // The peer is `pk1`, `pk3`.
    let err = sk2
        .open_psk_seed(&enc, ct, &pk3, &group)
        .expect_err("`PskSeed` decryption should fail");
    assert_eq!(err, Error::Hpke(HpkeError::Open(OpenError::Authentication)));
}

/// Negative test for decrypting a [`tls::PskSeed`] with the
/// wrong secret key (i.e., trying to open a PSK seed that was
/// encrypted for somebody else).
pub fn test_tls_psk_seed_open_wrong_sk<E: Engine>(eng: &E) {
    let sk1 = EncryptionKey::<E::CS>::new(eng);
    let pk1 = sk1.public().expect("`pk1` public half should be valid");

    let sk2 = EncryptionKey::<E::CS>::new(eng);
    let pk2 = sk2.public().expect("`sk2` public half should be valid");

    let sk3 = EncryptionKey::<E::CS>::new(eng);

    assert_ct_ne!(sk2.id().unwrap(), sk3.id().unwrap()); // pedantic

    let group = GroupId::default();
    let seed = tls::PskSeed::new(eng, &GroupId::default());
    let (enc, ct) = sk1
        .seal_psk_seed(eng, &seed, &pk2, &group)
        .expect("unable to encrypt `PskSeed`");
    // `(enc, ct)` are for `(sk2, pk2)`, not `(sk3, pk3)`.
    let err = sk3
        .open_psk_seed(&enc, ct, &pk1, &group)
        .expect_err("`PskSeed` decryption should fail");
    assert_eq!(err, Error::Hpke(HpkeError::Open(OpenError::Authentication)));
}

/// Negative test for decrypting a [`tls::PskSeed`] with the
/// wrong group ID.
pub fn test_tls_psk_seed_open_wrong_group<E: Engine>(eng: &E) {
    let sk1 = EncryptionKey::<E::CS>::new(eng);
    let pk1 = sk1.public().expect("`pk1` public half should be valid");

    let sk2 = EncryptionKey::<E::CS>::new(eng);
    let pk2 = sk2.public().expect("`sk2` public half should be valid");

    let group1 = GroupId::random(eng);
    let group2 = GroupId::random(eng);
    assert_ne!(group1, group2); // pedantic

    let seed = tls::PskSeed::new(eng, &GroupId::default());
    let (enc, ct) = sk1
        .seal_psk_seed(eng, &seed, &pk2, &group1)
        .expect("unable to encrypt `PskSeed`");
    let err = sk2
        .open_psk_seed(&enc, ct, &pk1, &group2)
        .expect_err("`PskSeed` decryption should fail");
    assert_eq!(err, Error::Hpke(HpkeError::Open(OpenError::Authentication)));
}

/// Negative test for decrypting a [`tls::PskSeed`] with
/// malformed ciphertext.
pub fn test_tls_psk_seed_open_wrong_ciphertext<E: Engine>(eng: &E) {
    let sk1 = EncryptionKey::<E::CS>::new(eng);
    let pk1 = sk1.public().expect("`pk1` public half should be valid");

    let sk2 = EncryptionKey::<E::CS>::new(eng);
    let pk2 = sk2.public().expect("`sk2` public half should be valid");

    let group = GroupId::default();

    let seed = tls::PskSeed::new(eng, &GroupId::default());
    let (enc, mut ct) = sk1
        .seal_psk_seed(eng, &seed, &pk2, &group)
        .expect("unable to encrypt `PskSeed`");

    ct.ciphertext[0] = ct.ciphertext[0].wrapping_add(1);

    let err = sk2
        .open_psk_seed(&enc, ct, &pk1, &group)
        .expect_err("`PskSeed` decryption should fail");
    assert_eq!(err, Error::Hpke(HpkeError::Open(OpenError::Authentication)));
}

/// Negative test for decrypting a [`tls::PskSeed`] with
/// malformed auth tag.
pub fn test_tls_psk_seed_open_wrong_tag<E: Engine>(eng: &E) {
    let sk1 = EncryptionKey::<E::CS>::new(eng);
    let pk1 = sk1.public().expect("`pk1` public half should be valid");

    let sk2 = EncryptionKey::<E::CS>::new(eng);
    let pk2 = sk2.public().expect("`sk2` public half should be valid");

    let group = GroupId::default();

    let seed = tls::PskSeed::new(eng, &GroupId::default());
    let (enc, mut ct) = sk1
        .seal_psk_seed(eng, &seed, &pk2, &group)
        .expect("unable to encrypt `PskSeed`");

    ct.tag[0] = ct.tag[0].wrapping_add(1);

    let err = sk2
        .open_psk_seed(&enc, ct, &pk1, &group)
        .expect_err("`PskSeed` decryption should fail");
    assert_eq!(err, Error::Hpke(HpkeError::Open(OpenError::Authentication)));
}