File: test_algorithms.py

package info (click to toggle)
pyjwt 2.11.0-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 864 kB
  • sloc: python: 5,151; makefile: 141
file content (1587 lines) | stat: -rw-r--r-- 59,438 bytes parent folder | download
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
import base64
import json
from typing import Any, cast

import pytest

from jwt.algorithms import HMACAlgorithm, NoneAlgorithm, has_crypto
from jwt.exceptions import InvalidKeyError
from jwt.utils import base64url_decode

from .keys import load_ec_pub_key_p_521, load_hmac_key, load_rsa_pub_key
from .utils import crypto_required, key_path

if has_crypto:
    from cryptography.hazmat.primitives.asymmetric.ec import (
        EllipticCurvePrivateKey,
        EllipticCurvePublicKey,
    )
    from cryptography.hazmat.primitives.asymmetric.ed448 import (
        Ed448PrivateKey,
        Ed448PublicKey,
    )
    from cryptography.hazmat.primitives.asymmetric.ed25519 import (
        Ed25519PrivateKey,
        Ed25519PublicKey,
    )
    from cryptography.hazmat.primitives.asymmetric.rsa import (
        RSAPrivateKey,
        RSAPublicKey,
    )

    from jwt.algorithms import ECAlgorithm, OKPAlgorithm, RSAAlgorithm, RSAPSSAlgorithm


class TestAlgorithms:
    def test_check_crypto_key_type_should_fail_when_not_using_crypto(self):
        """If has_crypto is False, or if _crypto_key_types is None, then this method should throw."""

        algo = NoneAlgorithm()
        with pytest.raises(ValueError):
            algo.check_crypto_key_type("key")  # type: ignore[arg-type]

    def test_none_algorithm_should_throw_exception_if_key_is_not_none(self):
        algo = NoneAlgorithm()

        with pytest.raises(InvalidKeyError):
            algo.prepare_key("123")

    def test_none_algorithm_should_throw_exception_on_to_jwk(self):
        algo = NoneAlgorithm()

        with pytest.raises(NotImplementedError):
            algo.to_jwk("dummy")  # Using a dummy argument as is it not relevant

    def test_none_algorithm_should_throw_exception_on_from_jwk(self):
        algo = NoneAlgorithm()

        with pytest.raises(NotImplementedError):
            algo.from_jwk({})  # Using a dummy argument as is it not relevant

    def test_hmac_should_reject_nonstring_key(self):
        algo = HMACAlgorithm(HMACAlgorithm.SHA256)

        with pytest.raises(TypeError) as context:
            algo.prepare_key(object())  # type: ignore[arg-type]

        exception = context.value
        assert str(exception) == "Expected a string value"

    def test_hmac_should_accept_unicode_key(self):
        algo = HMACAlgorithm(HMACAlgorithm.SHA256)

        algo.prepare_key("awesome")

    @pytest.mark.parametrize(
        "key",
        [
            "testkey2_rsa.pub.pem",
            "testkey2_rsa.pub.pem",
            "testkey_pkcs1.pub.pem",
            "testkey_rsa.cer",
            "testkey_rsa.pub",
        ],
    )
    def test_hmac_should_throw_exception(self, key):
        algo = HMACAlgorithm(HMACAlgorithm.SHA256)

        with pytest.raises(InvalidKeyError):
            with open(key_path(key)) as keyfile:
                algo.prepare_key(keyfile.read())

    def test_hmac_jwk_should_parse_and_verify(self):
        algo = HMACAlgorithm(HMACAlgorithm.SHA256)

        with open(key_path("jwk_hmac.json")) as keyfile:
            key = algo.from_jwk(keyfile.read())

        signature = algo.sign(b"Hello World!", key)
        assert algo.verify(b"Hello World!", key, signature)

    @pytest.mark.parametrize("as_dict", (False, True))
    def test_hmac_to_jwk_returns_correct_values(self, as_dict):
        algo = HMACAlgorithm(HMACAlgorithm.SHA256)
        key: Any = algo.to_jwk("secret", as_dict=as_dict)

        if not as_dict:
            key = json.loads(key)

        assert key == {"kty": "oct", "k": "c2VjcmV0"}

    def test_hmac_from_jwk_should_raise_exception_if_not_hmac_key(self):
        algo = HMACAlgorithm(HMACAlgorithm.SHA256)

        with open(key_path("jwk_rsa_pub.json")) as keyfile:
            with pytest.raises(InvalidKeyError):
                algo.from_jwk(keyfile.read())

    def test_hmac_from_jwk_should_raise_exception_if_empty_json(self):
        algo = HMACAlgorithm(HMACAlgorithm.SHA256)

        with open(key_path("jwk_empty.json")) as keyfile:
            with pytest.raises(InvalidKeyError):
                algo.from_jwk(keyfile.read())

    @crypto_required
    def test_rsa_should_parse_pem_public_key(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with open(key_path("testkey2_rsa.pub.pem")) as pem_key:
            algo.prepare_key(pem_key.read())

    @crypto_required
    def test_rsa_should_accept_pem_private_key_bytes(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with open(key_path("testkey_rsa.priv"), "rb") as pem_key:
            algo.prepare_key(pem_key.read())

    @crypto_required
    def test_rsa_should_accept_unicode_key(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with open(key_path("testkey_rsa.priv")) as rsa_key:
            algo.prepare_key(rsa_key.read())

    @crypto_required
    def test_rsa_should_reject_non_string_key(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with pytest.raises(TypeError):
            algo.prepare_key(None)  # type: ignore[arg-type]

    @crypto_required
    def test_rsa_verify_should_return_false_if_signature_invalid(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        message = b"Hello World!"

        sig = base64.b64decode(
            b"yS6zk9DBkuGTtcBzLUzSpo9gGJxJFOGvUqN01iLhWHrzBQ9ZEz3+Ae38AXp"
            b"10RWwscp42ySC85Z6zoN67yGkLNWnfmCZSEv+xqELGEvBJvciOKsrhiObUl"
            b"2mveSc1oeO/2ujkGDkkkJ2epn0YliacVjZF5+/uDmImUfAAj8lzjnHlzYix"
            b"sn5jGz1H07jYYbi9diixN8IUhXeTafwFg02IcONhum29V40Wu6O5tAKWlJX"
            b"fHJnNUzAEUOXS0WahHVb57D30pcgIji9z923q90p5c7E2cU8V+E1qe8NdCA"
            b"APCDzZZ9zQ/dgcMVaBrGrgimrcLbPjueOKFgSO+SSjIElKA=="
        )

        sig += b"123"  # Signature is now invalid

        with open(key_path("testkey_rsa.pub")) as keyfile:
            pub_key = cast(RSAPublicKey, algo.prepare_key(keyfile.read()))

        result = algo.verify(message, pub_key, sig)
        assert not result

    @crypto_required
    def test_ec_jwk_public_and_private_keys_should_parse_and_verify(self):
        tests = {
            "P-256": ECAlgorithm.SHA256,
            "P-384": ECAlgorithm.SHA384,
            "P-521": ECAlgorithm.SHA512,
            "secp256k1": ECAlgorithm.SHA256,
        }
        for curve, hash in tests.items():
            algo = ECAlgorithm(hash)

            with open(key_path(f"jwk_ec_pub_{curve}.json")) as keyfile:
                pub_key = cast(EllipticCurvePublicKey, algo.from_jwk(keyfile.read()))

            with open(key_path(f"jwk_ec_key_{curve}.json")) as keyfile:
                priv_key = cast(EllipticCurvePrivateKey, algo.from_jwk(keyfile.read()))

            signature = algo.sign(b"Hello World!", priv_key)
            assert algo.verify(b"Hello World!", pub_key, signature)

    @crypto_required
    def test_ec_jwk_fails_on_invalid_json(self):
        algo = ECAlgorithm(ECAlgorithm.SHA512)

        valid_points = {
            "P-256": {
                "x": "PTTjIY84aLtaZCxLTrG_d8I0G6YKCV7lg8M4xkKfwQ4",
                "y": "ank6KA34vv24HZLXlChVs85NEGlpg2sbqNmR_BcgyJU",
            },
            "P-384": {
                "x": "IDC-5s6FERlbC4Nc_4JhKW8sd51AhixtMdNUtPxhRFP323QY6cwWeIA3leyZhz-J",
                "y": "eovmN9ocANS8IJxDAGSuC1FehTq5ZFLJU7XSPg36zHpv4H2byKGEcCBiwT4sFJsy",
            },
            "P-521": {
                "x": "AHKZLLOsCOzz5cY97ewNUajB957y-C-U88c3v13nmGZx6sYl_oJXu9A5RkTKqjqvjyekWF-7ytDyRXYgCF5cj0Kt",
                "y": "AdymlHvOiLxXkEhayXQnNCvDX4h9htZaCJN34kfmC6pV5OhQHiraVySsUdaQkAgDPrwQrJmbnX9cwlGfP-HqHZR1",
            },
            "secp256k1": {
                "x": "MLnVyPDPQpNm0KaaO4iEh0i8JItHXJE0NcIe8GK1SYs",
                "y": "7r8d-xF7QAgT5kSRdly6M8xeg4Jz83Gs_CQPQRH65QI",
            },
        }

        # Invalid JSON
        with pytest.raises(InvalidKeyError):
            algo.from_jwk("<this isn't json>")

        # Bad key type
        with pytest.raises(InvalidKeyError):
            algo.from_jwk('{"kty": "RSA"}')

        # Missing data
        with pytest.raises(InvalidKeyError):
            algo.from_jwk('{"kty": "EC"}')
        with pytest.raises(InvalidKeyError):
            algo.from_jwk('{"kty": "EC", "x": "1"}')
        with pytest.raises(InvalidKeyError):
            algo.from_jwk('{"kty": "EC", "y": "1"}')

        # Missing curve
        with pytest.raises(InvalidKeyError):
            algo.from_jwk('{"kty": "EC", "x": "dGVzdA==", "y": "dGVzdA=="}')

        # EC coordinates not equally long
        with pytest.raises(InvalidKeyError):
            algo.from_jwk('{"kty": "EC", "x": "dGVzdHRlc3Q=", "y": "dGVzdA=="}')

        # EC coordinates length invalid
        for curve in ("P-256", "P-384", "P-521", "secp256k1"):
            with pytest.raises(InvalidKeyError):
                algo.from_jwk(
                    f'{{"kty": "EC", "crv": "{curve}", "x": "dGVzdA==", "y": "dGVzdA=="}}'
                )

        # EC private key length invalid
        for curve, point in valid_points.items():
            with pytest.raises(InvalidKeyError):
                algo.from_jwk(
                    f'{{"kty": "EC", "crv": "{curve}", "x": "{point["x"]}", "y": "{point["y"]}", "d": "dGVzdA=="}}'
                )

    @crypto_required
    def test_ec_private_key_to_jwk_works_with_from_jwk(self):
        algo = ECAlgorithm(ECAlgorithm.SHA256)

        with open(key_path("testkey_ec.priv")) as ec_key:
            orig_key = cast(EllipticCurvePrivateKey, algo.prepare_key(ec_key.read()))

        parsed_key = cast(EllipticCurvePrivateKey, algo.from_jwk(algo.to_jwk(orig_key)))
        assert parsed_key.private_numbers() == orig_key.private_numbers()
        assert (
            parsed_key.private_numbers().public_numbers
            == orig_key.private_numbers().public_numbers
        )

    @crypto_required
    def test_ec_public_key_to_jwk_works_with_from_jwk(self):
        algo = ECAlgorithm(ECAlgorithm.SHA256)

        with open(key_path("testkey_ec.pub")) as ec_key:
            orig_key = cast(EllipticCurvePublicKey, algo.prepare_key(ec_key.read()))

        parsed_key = cast(EllipticCurvePublicKey, algo.from_jwk(algo.to_jwk(orig_key)))
        assert parsed_key.public_numbers() == orig_key.public_numbers()

    @crypto_required
    @pytest.mark.parametrize("as_dict", (False, True))
    def test_ec_to_jwk_returns_correct_values_for_public_key(self, as_dict):
        algo = ECAlgorithm(ECAlgorithm.SHA256)

        with open(key_path("testkey_ec.pub")) as keyfile:
            pub_key = algo.prepare_key(keyfile.read())

        key: Any = algo.to_jwk(pub_key, as_dict=as_dict)

        if not as_dict:
            key = json.loads(key)

        expected = {
            "kty": "EC",
            "crv": "P-256",
            "x": "HzAcUWSlGBHcuf3y3RiNrWI-pE6-dD2T7fIzg9t6wEc",
            "y": "t2G02kbWiOqimYfQAfnARdp2CTycsJPhwA8rn1Cn0SQ",
        }

        assert key == expected

    @crypto_required
    @pytest.mark.parametrize("as_dict", (False, True))
    def test_ec_to_jwk_returns_correct_values_for_private_key(self, as_dict):
        algo = ECAlgorithm(ECAlgorithm.SHA256)

        with open(key_path("testkey_ec.priv")) as keyfile:
            priv_key = algo.prepare_key(keyfile.read())

        key: Any = algo.to_jwk(priv_key, as_dict=as_dict)

        if not as_dict:
            key = json.loads(key)

        expected = {
            "kty": "EC",
            "crv": "P-256",
            "x": "HzAcUWSlGBHcuf3y3RiNrWI-pE6-dD2T7fIzg9t6wEc",
            "y": "t2G02kbWiOqimYfQAfnARdp2CTycsJPhwA8rn1Cn0SQ",
            "d": "2nninfu2jMHDwAbn9oERUhRADS6duQaJEadybLaa0YQ",
        }

        assert key == expected

    @crypto_required
    def test_ec_to_jwk_raises_exception_on_invalid_key(self):
        algo = ECAlgorithm(ECAlgorithm.SHA256)

        with pytest.raises(InvalidKeyError):
            algo.to_jwk({"not": "a valid key"})  # type: ignore[call-overload]

    @crypto_required
    @pytest.mark.parametrize("as_dict", (False, True))
    def test_ec_to_jwk_with_valid_curves(self, as_dict):
        tests = {
            "P-256": ECAlgorithm.SHA256,
            "P-384": ECAlgorithm.SHA384,
            "P-521": ECAlgorithm.SHA512,
            "secp256k1": ECAlgorithm.SHA256,
        }
        for curve, hash in tests.items():
            algo = ECAlgorithm(hash)

            with open(key_path(f"jwk_ec_pub_{curve}.json")) as keyfile:
                pub_key = algo.from_jwk(keyfile.read())
                jwk: Any = algo.to_jwk(pub_key, as_dict=as_dict)

                if not as_dict:
                    jwk = json.loads(jwk)

                assert jwk["crv"] == curve

            with open(key_path(f"jwk_ec_key_{curve}.json")) as keyfile:
                priv_key = algo.from_jwk(keyfile.read())
                jwk = algo.to_jwk(priv_key, as_dict=as_dict)

                if not as_dict:
                    jwk = json.loads(jwk)

                assert jwk["crv"] == curve

    @crypto_required
    def test_ec_to_jwk_with_invalid_curve(self):
        algo = ECAlgorithm(ECAlgorithm.SHA256)

        with open(key_path("testkey_ec_secp192r1.priv")) as keyfile:
            priv_key = algo.prepare_key(keyfile.read())

        with pytest.raises(InvalidKeyError):
            algo.to_jwk(priv_key)

    @crypto_required
    def test_rsa_jwk_public_and_private_keys_should_parse_and_verify(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with open(key_path("jwk_rsa_pub.json")) as keyfile:
            pub_key = cast(RSAPublicKey, algo.from_jwk(keyfile.read()))

        with open(key_path("jwk_rsa_key.json")) as keyfile:
            priv_key = cast(RSAPrivateKey, algo.from_jwk(keyfile.read()))

        signature = algo.sign(b"Hello World!", priv_key)
        assert algo.verify(b"Hello World!", pub_key, signature)

    @crypto_required
    def test_rsa_private_key_to_jwk_works_with_from_jwk(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with open(key_path("testkey_rsa.priv")) as rsa_key:
            orig_key = cast(RSAPrivateKey, algo.prepare_key(rsa_key.read()))

        parsed_key = cast(RSAPrivateKey, algo.from_jwk(algo.to_jwk(orig_key)))
        assert parsed_key.private_numbers() == orig_key.private_numbers()
        assert (
            parsed_key.private_numbers().public_numbers
            == orig_key.private_numbers().public_numbers
        )

    @crypto_required
    def test_rsa_public_key_to_jwk_works_with_from_jwk(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with open(key_path("testkey_rsa.pub")) as rsa_key:
            orig_key = cast(RSAPublicKey, algo.prepare_key(rsa_key.read()))

        parsed_key = cast(RSAPublicKey, algo.from_jwk(algo.to_jwk(orig_key)))
        assert parsed_key.public_numbers() == orig_key.public_numbers()

    @crypto_required
    def test_rsa_jwk_private_key_with_other_primes_is_invalid(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with open(key_path("jwk_rsa_key.json")) as keyfile:
            with pytest.raises(InvalidKeyError):
                keydata = json.loads(keyfile.read())
                keydata["oth"] = []

                algo.from_jwk(json.dumps(keydata))

    @crypto_required
    def test_rsa_jwk_private_key_with_missing_values_is_invalid(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with open(key_path("jwk_rsa_key.json")) as keyfile:
            with pytest.raises(InvalidKeyError):
                keydata = json.loads(keyfile.read())
                del keydata["p"]

                algo.from_jwk(json.dumps(keydata))

    @crypto_required
    def test_rsa_jwk_private_key_can_recover_prime_factors(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with open(key_path("jwk_rsa_key.json")) as keyfile:
            keybytes = keyfile.read()
            control_key = cast(RSAPrivateKey, algo.from_jwk(keybytes)).private_numbers()

            keydata = json.loads(keybytes)
            delete_these = ["p", "q", "dp", "dq", "qi"]
            for field in delete_these:
                del keydata[field]

            parsed_key = cast(
                RSAPrivateKey, algo.from_jwk(json.dumps(keydata))
            ).private_numbers()

        assert control_key.d == parsed_key.d
        assert control_key.p == parsed_key.p
        assert control_key.q == parsed_key.q
        assert control_key.dmp1 == parsed_key.dmp1
        assert control_key.dmq1 == parsed_key.dmq1
        assert control_key.iqmp == parsed_key.iqmp

    @crypto_required
    def test_rsa_jwk_private_key_with_missing_required_values_is_invalid(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with open(key_path("jwk_rsa_key.json")) as keyfile:
            with pytest.raises(InvalidKeyError):
                keydata = json.loads(keyfile.read())
                del keydata["p"]

                algo.from_jwk(json.dumps(keydata))

    @crypto_required
    def test_rsa_jwk_raises_exception_if_not_a_valid_key(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        # Invalid JSON
        with pytest.raises(InvalidKeyError):
            algo.from_jwk("{not-a-real-key")

        # Missing key parts
        with pytest.raises(InvalidKeyError):
            algo.from_jwk('{"kty": "RSA"}')

    @crypto_required
    @pytest.mark.parametrize("as_dict", (False, True))
    def test_rsa_to_jwk_returns_correct_values_for_public_key(self, as_dict):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with open(key_path("testkey_rsa.pub")) as keyfile:
            pub_key = algo.prepare_key(keyfile.read())

        key: Any = algo.to_jwk(pub_key, as_dict=as_dict)

        if not as_dict:
            key = json.loads(key)

        expected = {
            "e": "AQAB",
            "key_ops": ["verify"],
            "kty": "RSA",
            "n": (
                "1HgzBfJv2cOjQryCwe8NEelriOTNFWKZUivevUrRhlqcmZJdCvuCJRr-xCN-"
                "OmO8qwgJJR98feNujxVg-J9Ls3_UOA4HcF9nYH6aqVXELAE8Hk_ALvxi96ms"
                "1DDuAvQGaYZ-lANxlvxeQFOZSbjkz_9mh8aLeGKwqJLp3p-OhUBQpwvAUAPg"
                "82-OUtgTW3nSljjeFr14B8qAneGSc_wl0ni--1SRZUXFSovzcqQOkla3W27r"
                "rLfrD6LXgj_TsDs4vD1PnIm1zcVenKT7TfYI17bsG_O_Wecwz2Nl19pL7gDo"
                "sNruF3ogJWNq1Lyn_ijPQnkPLpZHyhvuiycYcI3DiQ"
            ),
        }
        assert key == expected

    @crypto_required
    @pytest.mark.parametrize("as_dict", (False, True))
    def test_rsa_to_jwk_returns_correct_values_for_private_key(self, as_dict):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with open(key_path("testkey_rsa.priv")) as keyfile:
            priv_key = algo.prepare_key(keyfile.read())

        key: Any = algo.to_jwk(priv_key, as_dict=as_dict)

        if not as_dict:
            key = json.loads(key)

        expected = {
            "key_ops": ["sign"],
            "kty": "RSA",
            "e": "AQAB",
            "n": (
                "1HgzBfJv2cOjQryCwe8NEelriOTNFWKZUivevUrRhlqcmZJdCvuCJRr-xCN-"
                "OmO8qwgJJR98feNujxVg-J9Ls3_UOA4HcF9nYH6aqVXELAE8Hk_ALvxi96ms"
                "1DDuAvQGaYZ-lANxlvxeQFOZSbjkz_9mh8aLeGKwqJLp3p-OhUBQpwvAUAPg"
                "82-OUtgTW3nSljjeFr14B8qAneGSc_wl0ni--1SRZUXFSovzcqQOkla3W27r"
                "rLfrD6LXgj_TsDs4vD1PnIm1zcVenKT7TfYI17bsG_O_Wecwz2Nl19pL7gDo"
                "sNruF3ogJWNq1Lyn_ijPQnkPLpZHyhvuiycYcI3DiQ"
            ),
            "d": (
                "rfbs8AWdB1RkLJRlC51LukrAvYl5UfU1TE6XRa4o-DTg2-03OXLNEMyVpMr"
                "a47weEnu14StypzC8qXL7vxXOyd30SSFTffLfleaTg-qxgMZSDw-Fb_M-pU"
                "HMPMEDYG-lgGma4l4fd1yTX2ATtoUo9BVOQgWS1LMZqi0ASEOkUfzlBgL04"
                "UoaLhPSuDdLygdlDzgruVPnec0t1uOEObmrcWIkhwU2CGQzeLtuzX6OVgPh"
                "k7xcnjbDurTTVpWH0R0gbZ5ukmQ2P-YuCX8T9iWNMGjPNSkb7h02s2Oe9ZR"
                "zP007xQ0VF-Z7xyLuxk6ASmoX1S39ujSbk2WF0eXNPRgFwQ"
            ),
            "q": (
                "47hlW2f1ARuWYJf9Dl6MieXjdj2dGx9PL2UH0unVzJYInd56nqXNPrQrc5k"
                "ZU65KApC9n9oKUwIxuqwAAbh8oGNEQDqnuTj-powCkdC6bwA8KH1Y-wotpq"
                "_GSjxkNzjWRm2GArJSzZc6Fb8EuObOrAavKJ285-zMPCEfus1WZG0"
            ),
            "p": (
                "7tr0z929Lp4OHIRJjIKM_rDrWMPtRgnV-51pgWsN6qdpDzns_PgFwrHcoyY"
                "sWIO-4yCdVWPxFOgEZ8xXTM_uwOe4VEmdZhw55Tx7axYZtmZYZbO_RIP4CG"
                "mlJlOFTiYnxpr-2Cx6kIeQmd-hf7fA3tL018aEzwYMbFMcnAGnEg0"
            ),
            "qi": (
                "djo95mB0LVYikNPa-NgyDwLotLqrueb9IviMmn6zKHCwiOXReqXDX9slB8"
                "RA15uv56bmN04O__NyVFcgJ2ef169GZHiRFIgIy0Pl8LYkMhCYKKhyqM7g"
                "xN-SqGqDTKDC22j00S7jcvCaa1qadn1qbdfukZ4NXv7E2d_LO0Y2Kkc"
            ),
            "dp": (
                "tgZ2-tJpEdWxu1m1EzeKa644LHVjpTRptk7H0LDc8i6SieADEuWQvkb9df"
                "fpY6tDFaQNQr3fQ6dtdAztmsP7l1b_ynwvT1nDZUcqZvl4ruBgDWFmKbjI"
                "lOCt0v9jX6MEPP5xqBx9axdkw18BnGtUuHrbzHSlUX-yh_rumpVH1SE"
            ),
            "dq": (
                "xxCIuhD0YlWFbUcwFgGdBWcLIm_WCMGj7SB6aGu1VDTLr4Wu10TFWM0TNu"
                "hc9YPker2gpj5qzAmdAzwcfWSSvXpJTYR43jfulBTMoj8-2o3wCM0anclW"
                "AuKhin-kc4mh9ssDXRQZwlMymZP0QtaxUDw_nlfVrUCZgO7L1_ZsUTk"
            ),
        }
        assert key == expected

    @crypto_required
    def test_rsa_to_jwk_raises_exception_on_invalid_key(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with pytest.raises(InvalidKeyError):
            algo.to_jwk({"not": "a valid key"})  # type: ignore[call-overload]

    @crypto_required
    def test_rsa_from_jwk_raises_exception_on_invalid_key(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)

        with open(key_path("jwk_hmac.json")) as keyfile:
            with pytest.raises(InvalidKeyError):
                algo.from_jwk(keyfile.read())

    @crypto_required
    def test_ec_should_reject_non_string_key(self):
        algo = ECAlgorithm(ECAlgorithm.SHA256)

        with pytest.raises(TypeError):
            algo.prepare_key(None)  # type: ignore[arg-type]

    @crypto_required
    def test_ec_should_accept_pem_private_key_bytes(self):
        algo = ECAlgorithm(ECAlgorithm.SHA256)

        with open(key_path("testkey_ec.priv"), "rb") as ec_key:
            algo.prepare_key(ec_key.read())

    @crypto_required
    def test_ec_should_accept_ssh_public_key_bytes(self):
        algo = ECAlgorithm(ECAlgorithm.SHA256)

        with open(key_path("testkey_ec_ssh.pub")) as ec_key:
            algo.prepare_key(ec_key.read())

    @crypto_required
    def test_ec_verify_should_return_false_if_signature_invalid(self):
        algo = ECAlgorithm(ECAlgorithm.SHA256)

        message = b"Hello World!"

        # Mess up the signature by replacing a known byte
        sig = base64.b64decode(
            b"AC+m4Jf/xI3guAC6w0w37t5zRpSCF6F4udEz5LiMiTIjCS4vcVe6dDOxK+M"
            b"mvkF8PxJuvqxP2CO3TR3okDPCl/NjATTO1jE+qBZ966CRQSSzcCM+tzcHzw"
            b"LZS5kbvKu0Acd/K6Ol2/W3B1NeV5F/gjvZn/jOwaLgWEUYsg0o4XVrAg65".replace(
                b"r", b"s"
            )
        )

        with open(key_path("testkey_ec.pub")) as keyfile:
            pub_key = algo.prepare_key(keyfile.read())

        result = algo.verify(message, pub_key, sig)
        assert not result

    @crypto_required
    def test_ec_verify_should_return_false_if_signature_wrong_length(self):
        algo = ECAlgorithm(ECAlgorithm.SHA256)

        message = b"Hello World!"

        sig = base64.b64decode(b"AC+m4Jf/xI3guAC6w0w3")

        with open(key_path("testkey_ec.pub")) as keyfile:
            pub_key = algo.prepare_key(keyfile.read())

        result = algo.verify(message, pub_key, sig)
        assert not result

    @crypto_required
    def test_ec_should_throw_exception_on_wrong_key(self):
        algo = ECAlgorithm(ECAlgorithm.SHA256)

        with pytest.raises(InvalidKeyError):
            with open(key_path("testkey_rsa.priv")) as keyfile:
                algo.prepare_key(keyfile.read())

        with pytest.raises(InvalidKeyError):
            with open(key_path("testkey2_rsa.pub.pem")) as pem_key:
                algo.prepare_key(pem_key.read())

    @crypto_required
    def test_rsa_pss_sign_then_verify_should_return_true(self):
        algo = RSAPSSAlgorithm(RSAPSSAlgorithm.SHA256)

        message = b"Hello World!"

        with open(key_path("testkey_rsa.priv")) as keyfile:
            priv_key = cast(RSAPrivateKey, algo.prepare_key(keyfile.read()))
            sig = algo.sign(message, priv_key)

        with open(key_path("testkey_rsa.pub")) as keyfile:
            pub_key = cast(RSAPublicKey, algo.prepare_key(keyfile.read()))

        result = algo.verify(message, pub_key, sig)
        assert result

    @crypto_required
    def test_rsa_pss_verify_should_return_false_if_signature_invalid(self):
        algo = RSAPSSAlgorithm(RSAPSSAlgorithm.SHA256)

        jwt_message = b"Hello World!"

        jwt_sig = base64.b64decode(
            b"ywKAUGRIDC//6X+tjvZA96yEtMqpOrSppCNfYI7NKyon3P7doud5v65oWNu"
            b"vQsz0fzPGfF7mQFGo9Cm9Vn0nljm4G6PtqZRbz5fXNQBH9k10gq34AtM02c"
            b"/cveqACQ8gF3zxWh6qr9jVqIpeMEaEBIkvqG954E0HT9s9ybHShgHX9mlWk"
            b"186/LopP4xe5c/hxOQjwhv6yDlTiwJFiqjNCvj0GyBKsc4iECLGIIO+4mC4"
            b"daOCWqbpZDuLb1imKpmm8Nsm56kAxijMLZnpCcnPgyb7CqG+B93W9GHglA5"
            b"drUeR1gRtO7vqbZMsCAQ4bpjXxwbYyjQlEVuMl73UL6sOWg=="
        )

        jwt_sig += b"123"  # Signature is now invalid

        with open(key_path("testkey_rsa.pub")) as keyfile:
            jwt_pub_key = cast(RSAPublicKey, algo.prepare_key(keyfile.read()))

        result = algo.verify(jwt_message, jwt_pub_key, jwt_sig)
        assert not result


class TestAlgorithmsRFC7520:
    """
    These test vectors were taken from RFC 7520
    (https://tools.ietf.org/html/rfc7520)
    """

    def test_hmac_verify_should_return_true_for_test_vector(self):
        """
        This test verifies that HMAC verification works with a known good
        signature and key.

        Reference: https://tools.ietf.org/html/rfc7520#section-4.4
        """
        signing_input = (
            b"eyJhbGciOiJIUzI1NiIsImtpZCI6IjAxOGMwYWU1LTRkOWItNDcxYi1iZmQ2LWVlZ"
            b"jMxNGJjNzAzNyJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ"
            b"29pbmcgb3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIG"
            b"lmIHlvdSBkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmc"
            b"gd2hlcmUgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4"
        )

        signature = base64url_decode(b"s0h6KThzkfBBBkLspW1h84VsJZFTsPPqMDA7g1Md7p0")

        algo = HMACAlgorithm(HMACAlgorithm.SHA256)
        key = algo.prepare_key(load_hmac_key())

        result = algo.verify(signing_input, key, signature)
        assert result

    @crypto_required
    def test_rsa_verify_should_return_true_for_test_vector(self):
        """
        This test verifies that RSA PKCS v1.5 verification works with a known
        good signature and key.

        Reference: https://tools.ietf.org/html/rfc7520#section-4.1
        """
        signing_input = (
            b"eyJhbGciOiJSUzI1NiIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhb"
            b"XBsZSJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb"
            b"3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdS"
            b"Bkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmU"
            b"geW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4"
        )

        signature = base64url_decode(
            b"MRjdkly7_-oTPTS3AXP41iQIGKa80A0ZmTuV5MEaHoxnW2e5CZ5NlKtainoFmKZop"
            b"dHM1O2U4mwzJdQx996ivp83xuglII7PNDi84wnB-BDkoBwA78185hX-Es4JIwmDLJ"
            b"K3lfWRa-XtL0RnltuYv746iYTh_qHRD68BNt1uSNCrUCTJDt5aAE6x8wW1Kt9eRo4"
            b"QPocSadnHXFxnt8Is9UzpERV0ePPQdLuW3IS_de3xyIrDaLGdjluPxUAhb6L2aXic"
            b"1U12podGU0KLUQSE_oI-ZnmKJ3F4uOZDnd6QZWJushZ41Axf_fcIe8u9ipH84ogor"
            b"ee7vjbU5y18kDquDg"
        )

        algo = RSAAlgorithm(RSAAlgorithm.SHA256)
        key = cast(RSAPublicKey, algo.prepare_key(load_rsa_pub_key()))

        result = algo.verify(signing_input, key, signature)
        assert result

    @crypto_required
    def test_rsapss_verify_should_return_true_for_test_vector(self):
        """
        This test verifies that RSA-PSS verification works with a known good
        signature and key.

        Reference: https://tools.ietf.org/html/rfc7520#section-4.2
        """
        signing_input = (
            b"eyJhbGciOiJQUzM4NCIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhb"
            b"XBsZSJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb"
            b"3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdS"
            b"Bkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmU"
            b"geW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4"
        )

        signature = base64url_decode(
            b"cu22eBqkYDKgIlTpzDXGvaFfz6WGoz7fUDcfT0kkOy42miAh2qyBzk1xEsnk2IpN6"
            b"-tPid6VrklHkqsGqDqHCdP6O8TTB5dDDItllVo6_1OLPpcbUrhiUSMxbbXUvdvWXz"
            b"g-UD8biiReQFlfz28zGWVsdiNAUf8ZnyPEgVFn442ZdNqiVJRmBqrYRXe8P_ijQ7p"
            b"8Vdz0TTrxUeT3lm8d9shnr2lfJT8ImUjvAA2Xez2Mlp8cBE5awDzT0qI0n6uiP1aC"
            b"N_2_jLAeQTlqRHtfa64QQSUmFAAjVKPbByi7xho0uTOcbH510a6GYmJUAfmWjwZ6o"
            b"D4ifKo8DYM-X72Eaw"
        )

        algo = RSAPSSAlgorithm(RSAPSSAlgorithm.SHA384)
        key = cast(RSAPublicKey, algo.prepare_key(load_rsa_pub_key()))

        result = algo.verify(signing_input, key, signature)
        assert result

    @crypto_required
    def test_ec_verify_should_return_true_for_test_vector(self):
        """
        This test verifies that ECDSA verification works with a known good
        signature and key.

        Reference: https://tools.ietf.org/html/rfc7520#section-4.3
        """
        signing_input = (
            b"eyJhbGciOiJFUzUxMiIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZXhhb"
            b"XBsZSJ9.SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb"
            b"3V0IHlvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdS"
            b"Bkb24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcmU"
            b"geW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4"
        )

        signature = base64url_decode(
            b"AE_R_YZCChjn4791jSQCrdPZCNYqHXCTZH0-JZGYNlaAjP2kqaluUIIUnC9qvbu9P"
            b"lon7KRTzoNEuT4Va2cmL1eJAQy3mtPBu_u_sDDyYjnAMDxXPn7XrT0lw-kvAD890j"
            b"l8e2puQens_IEKBpHABlsbEPX6sFY8OcGDqoRuBomu9xQ2"
        )

        algo = ECAlgorithm(ECAlgorithm.SHA512)
        key = algo.prepare_key(load_ec_pub_key_p_521())

        result = algo.verify(signing_input, key, signature)
        assert result

        # private key can also be used.
        with open(key_path("jwk_ec_key_P-521.json")) as keyfile:
            private_key = algo.from_jwk(keyfile.read())

        result = algo.verify(signing_input, private_key, signature)
        assert result


@crypto_required
class TestOKPAlgorithms:
    hello_world_sig = b"Qxa47mk/azzUgmY2StAOguAd4P7YBLpyCfU3JdbaiWnXM4o4WibXwmIHvNYgN3frtE2fcyd8OYEaOiD/KiwkCg=="
    hello_world_sig_pem = b"9ueQE7PT8uudHIQb2zZZ7tB7k1X3jeTnIfOVvGCINZejrqQbru1EXPeuMlGcQEZrGkLVcfMmr99W/+byxfppAg=="
    hello_world = b"Hello World!"

    def test_okp_ed25519_should_reject_non_string_key(self):
        algo = OKPAlgorithm()

        with pytest.raises(InvalidKeyError):
            algo.prepare_key(None)  # type: ignore[arg-type]

        with open(key_path("testkey_ed25519")) as keyfile:
            algo.prepare_key(keyfile.read())

        with open(key_path("testkey_ed25519.pub")) as keyfile:
            algo.prepare_key(keyfile.read())

    @pytest.mark.parametrize(
        "private_key_file,public_key_file,sig_attr",
        [
            ("testkey_ed25519", "testkey_ed25519.pub", "hello_world_sig"),
            ("testkey_ed25519.pem", "testkey_ed25519.pub.pem", "hello_world_sig_pem"),
        ],
    )
    def test_okp_ed25519_sign_should_generate_correct_signature_value(
        self, private_key_file, public_key_file, sig_attr
    ):
        algo = OKPAlgorithm()

        jwt_message = self.hello_world

        expected_sig = base64.b64decode(getattr(self, sig_attr))

        with open(key_path(private_key_file)) as keyfile:
            jwt_key = cast(Ed25519PrivateKey, algo.prepare_key(keyfile.read()))

        with open(key_path(public_key_file)) as keyfile:
            jwt_pub_key = cast(Ed25519PublicKey, algo.prepare_key(keyfile.read()))

        algo.sign(jwt_message, jwt_key)
        result = algo.verify(jwt_message, jwt_pub_key, expected_sig)
        assert result

    @pytest.mark.parametrize(
        "public_key_file,sig_attr",
        [
            ("testkey_ed25519.pub", "hello_world_sig"),
            ("testkey_ed25519.pub.pem", "hello_world_sig_pem"),
        ],
    )
    def test_okp_ed25519_verify_should_return_false_if_signature_invalid(
        self, public_key_file, sig_attr
    ):
        algo = OKPAlgorithm()

        jwt_message = self.hello_world
        jwt_sig = base64.b64decode(getattr(self, sig_attr))

        jwt_sig += b"123"  # Signature is now invalid

        with open(key_path(public_key_file)) as keyfile:
            jwt_pub_key = algo.prepare_key(keyfile.read())

        result = algo.verify(jwt_message, jwt_pub_key, jwt_sig)
        assert not result

    @pytest.mark.parametrize(
        "public_key_file,sig_attr",
        [
            ("testkey_ed25519.pub", "hello_world_sig"),
            ("testkey_ed25519.pub.pem", "hello_world_sig_pem"),
        ],
    )
    def test_okp_ed25519_verify_should_return_true_if_signature_valid(
        self, public_key_file, sig_attr
    ):
        algo = OKPAlgorithm()

        jwt_message = self.hello_world
        jwt_sig = base64.b64decode(getattr(self, sig_attr))

        with open(key_path(public_key_file)) as keyfile:
            jwt_pub_key = algo.prepare_key(keyfile.read())

        result = algo.verify(jwt_message, jwt_pub_key, jwt_sig)
        assert result

    @pytest.mark.parametrize(
        "public_key_file", ("testkey_ed25519.pub", "testkey_ed25519.pub.pem")
    )
    def test_okp_ed25519_prepare_key_should_be_idempotent(self, public_key_file):
        algo = OKPAlgorithm()

        with open(key_path(public_key_file)) as keyfile:
            jwt_pub_key_first = algo.prepare_key(keyfile.read())
            jwt_pub_key_second = algo.prepare_key(jwt_pub_key_first)

        assert jwt_pub_key_first == jwt_pub_key_second

    def test_okp_ed25519_prepare_key_should_reject_invalid_key(self):
        algo = OKPAlgorithm()

        with pytest.raises(InvalidKeyError):
            algo.prepare_key("not a valid key")

    def test_okp_ed25519_jwk_private_key_should_parse_and_verify(self):
        algo = OKPAlgorithm()

        with open(key_path("jwk_okp_key_Ed25519.json")) as keyfile:
            key = cast(Ed25519PrivateKey, algo.from_jwk(keyfile.read()))

        signature = algo.sign(b"Hello World!", key)
        assert algo.verify(b"Hello World!", key.public_key(), signature)

    def test_okp_ed25519_jwk_private_key_should_parse_and_verify_with_private_key_as_is(
        self,
    ):
        algo = OKPAlgorithm()

        with open(key_path("jwk_okp_key_Ed25519.json")) as keyfile:
            key = cast(Ed25519PrivateKey, algo.from_jwk(keyfile.read()))

        signature = algo.sign(b"Hello World!", key)
        assert algo.verify(b"Hello World!", key, signature)

    def test_okp_ed25519_jwk_public_key_should_parse_and_verify(self):
        algo = OKPAlgorithm()

        with open(key_path("jwk_okp_key_Ed25519.json")) as keyfile:
            priv_key = cast(Ed25519PrivateKey, algo.from_jwk(keyfile.read()))

        with open(key_path("jwk_okp_pub_Ed25519.json")) as keyfile:
            pub_key = cast(Ed25519PublicKey, algo.from_jwk(keyfile.read()))

        signature = algo.sign(b"Hello World!", priv_key)
        assert algo.verify(b"Hello World!", pub_key, signature)

    def test_okp_ed25519_jwk_fails_on_invalid_json(self):
        algo = OKPAlgorithm()

        with open(key_path("jwk_okp_pub_Ed25519.json")) as keyfile:
            valid_pub = json.loads(keyfile.read())
        with open(key_path("jwk_okp_key_Ed25519.json")) as keyfile:
            valid_key = json.loads(keyfile.read())

        # Invalid instance type
        with pytest.raises(InvalidKeyError):
            algo.from_jwk(123)  # type: ignore[arg-type]

        # Invalid JSON
        with pytest.raises(InvalidKeyError):
            algo.from_jwk("<this isn't json>")

        # Invalid kty, not "OKP"
        v = valid_pub.copy()
        v["kty"] = "oct"
        with pytest.raises(InvalidKeyError):
            algo.from_jwk(v)

        # Invalid crv, not "Ed25519"
        v = valid_pub.copy()
        v["crv"] = "P-256"
        with pytest.raises(InvalidKeyError):
            algo.from_jwk(v)

        # Invalid crv, "Ed448"
        v = valid_pub.copy()
        v["crv"] = "Ed448"
        with pytest.raises(InvalidKeyError):
            algo.from_jwk(v)

        # Missing x
        v = valid_pub.copy()
        del v["x"]
        with pytest.raises(InvalidKeyError):
            algo.from_jwk(v)

        # Invalid x
        v = valid_pub.copy()
        v["x"] = "123"
        with pytest.raises(InvalidKeyError):
            algo.from_jwk(v)

        # Invalid d
        v = valid_key.copy()
        v["d"] = "123"
        with pytest.raises(InvalidKeyError):
            algo.from_jwk(v)

    @pytest.mark.parametrize("as_dict", (False, True))
    def test_okp_ed25519_to_jwk_works_with_from_jwk(self, as_dict):
        algo = OKPAlgorithm()

        with open(key_path("jwk_okp_key_Ed25519.json")) as keyfile:
            priv_key_1 = cast(Ed25519PrivateKey, algo.from_jwk(keyfile.read()))

        with open(key_path("jwk_okp_pub_Ed25519.json")) as keyfile:
            pub_key_1 = cast(Ed25519PublicKey, algo.from_jwk(keyfile.read()))

        pub = algo.to_jwk(pub_key_1, as_dict=as_dict)
        pub_key_2 = algo.from_jwk(pub)
        pri = algo.to_jwk(priv_key_1, as_dict=as_dict)
        priv_key_2 = cast(Ed25519PrivateKey, algo.from_jwk(pri))

        signature_1 = algo.sign(b"Hello World!", priv_key_1)
        signature_2 = algo.sign(b"Hello World!", priv_key_2)
        assert algo.verify(b"Hello World!", pub_key_2, signature_1)
        assert algo.verify(b"Hello World!", pub_key_2, signature_2)

    def test_okp_to_jwk_raises_exception_on_invalid_key(self):
        algo = OKPAlgorithm()

        with pytest.raises(InvalidKeyError):
            algo.to_jwk({"not": "a valid key"})  # type: ignore[call-overload]

    def test_okp_ed448_jwk_private_key_should_parse_and_verify(self):
        algo = OKPAlgorithm()

        with open(key_path("jwk_okp_key_Ed448.json")) as keyfile:
            key = cast(Ed448PrivateKey, algo.from_jwk(keyfile.read()))

        signature = algo.sign(b"Hello World!", key)
        assert algo.verify(b"Hello World!", key.public_key(), signature)

    def test_okp_ed448_jwk_private_key_should_parse_and_verify_with_private_key_as_is(
        self,
    ):
        algo = OKPAlgorithm()

        with open(key_path("jwk_okp_key_Ed448.json")) as keyfile:
            key = cast(Ed448PrivateKey, algo.from_jwk(keyfile.read()))

        signature = algo.sign(b"Hello World!", key)
        assert algo.verify(b"Hello World!", key, signature)

    def test_okp_ed448_jwk_public_key_should_parse_and_verify(self):
        algo = OKPAlgorithm()

        with open(key_path("jwk_okp_key_Ed448.json")) as keyfile:
            priv_key = cast(Ed448PrivateKey, algo.from_jwk(keyfile.read()))

        with open(key_path("jwk_okp_pub_Ed448.json")) as keyfile:
            pub_key = cast(Ed448PublicKey, algo.from_jwk(keyfile.read()))

        signature = algo.sign(b"Hello World!", priv_key)
        assert algo.verify(b"Hello World!", pub_key, signature)

    def test_okp_ed448_jwk_fails_on_invalid_json(self):
        algo = OKPAlgorithm()

        with open(key_path("jwk_okp_pub_Ed448.json")) as keyfile:
            valid_pub = json.loads(keyfile.read())
        with open(key_path("jwk_okp_key_Ed448.json")) as keyfile:
            valid_key = json.loads(keyfile.read())

        # Invalid instance type
        with pytest.raises(InvalidKeyError):
            algo.from_jwk(123)  # type: ignore[arg-type]

        # Invalid JSON
        with pytest.raises(InvalidKeyError):
            algo.from_jwk("<this isn't json>")

        # Invalid kty, not "OKP"
        v = valid_pub.copy()
        v["kty"] = "oct"
        with pytest.raises(InvalidKeyError):
            algo.from_jwk(v)

        # Invalid crv, not "Ed448"
        v = valid_pub.copy()
        v["crv"] = "P-256"
        with pytest.raises(InvalidKeyError):
            algo.from_jwk(v)

        # Invalid crv, "Ed25519"
        v = valid_pub.copy()
        v["crv"] = "Ed25519"
        with pytest.raises(InvalidKeyError):
            algo.from_jwk(v)

        # Missing x
        v = valid_pub.copy()
        del v["x"]
        with pytest.raises(InvalidKeyError):
            algo.from_jwk(v)

        # Invalid x
        v = valid_pub.copy()
        v["x"] = "123"
        with pytest.raises(InvalidKeyError):
            algo.from_jwk(v)

        # Invalid d
        v = valid_key.copy()
        v["d"] = "123"
        with pytest.raises(InvalidKeyError):
            algo.from_jwk(v)

    @pytest.mark.parametrize("as_dict", (False, True))
    def test_okp_ed448_to_jwk_works_with_from_jwk(self, as_dict):
        algo = OKPAlgorithm()

        with open(key_path("jwk_okp_key_Ed448.json")) as keyfile:
            priv_key_1 = cast(Ed448PrivateKey, algo.from_jwk(keyfile.read()))

        with open(key_path("jwk_okp_pub_Ed448.json")) as keyfile:
            pub_key_1 = cast(Ed448PublicKey, algo.from_jwk(keyfile.read()))

        pub = algo.to_jwk(pub_key_1, as_dict=as_dict)
        pub_key_2 = algo.from_jwk(pub)
        pri = algo.to_jwk(priv_key_1, as_dict=as_dict)
        priv_key_2 = cast(Ed448PrivateKey, algo.from_jwk(pri))

        signature_1 = algo.sign(b"Hello World!", priv_key_1)
        signature_2 = algo.sign(b"Hello World!", priv_key_2)
        assert algo.verify(b"Hello World!", pub_key_2, signature_1)
        assert algo.verify(b"Hello World!", pub_key_2, signature_2)

    @crypto_required
    def test_rsa_can_compute_digest(self):
        # this is the well-known sha256 hash of "foo"
        foo_hash = base64.b64decode(b"LCa0a2j/xo/5m0U8HTBBNBNCLXBkg7+g+YpeiGJm564=")

        algo = RSAAlgorithm(RSAAlgorithm.SHA256)
        computed_hash = algo.compute_hash_digest(b"foo")
        assert computed_hash == foo_hash

    def test_hmac_can_compute_digest(self):
        # this is the well-known sha256 hash of "foo"
        foo_hash = base64.b64decode(b"LCa0a2j/xo/5m0U8HTBBNBNCLXBkg7+g+YpeiGJm564=")

        algo = HMACAlgorithm(HMACAlgorithm.SHA256)
        computed_hash = algo.compute_hash_digest(b"foo")
        assert computed_hash == foo_hash

    @crypto_required
    def test_rsa_prepare_key_raises_invalid_key_error_on_invalid_pem(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)
        invalid_key = "invalid key"

        with pytest.raises(InvalidKeyError) as excinfo:
            algo.prepare_key(invalid_key)

        # Check that the exception message is correct
        assert "Could not parse the provided public key." in str(excinfo.value)


@crypto_required
class TestECCurveValidation:
    """Tests for ECDSA curve validation per RFC 7518 Section 3.4."""

    def test_ec_curve_validation_rejects_wrong_curve_for_es256(self):
        """ES256 should reject keys that are not P-256."""
        from cryptography.hazmat.primitives.asymmetric.ec import SECP256R1

        algo = ECAlgorithm(ECAlgorithm.SHA256, SECP256R1)

        # P-384 key should be rejected
        with open(key_path("jwk_ec_key_P-384.json")) as keyfile:
            p384_key = ECAlgorithm.from_jwk(keyfile.read())

        with pytest.raises(InvalidKeyError) as excinfo:
            algo.prepare_key(p384_key)
        assert "secp384r1" in str(excinfo.value)
        assert "secp256r1" in str(excinfo.value)

    def test_ec_curve_validation_rejects_wrong_curve_for_es384(self):
        """ES384 should reject keys that are not P-384."""
        from cryptography.hazmat.primitives.asymmetric.ec import SECP384R1

        algo = ECAlgorithm(ECAlgorithm.SHA384, SECP384R1)

        # P-256 key should be rejected
        with open(key_path("jwk_ec_key_P-256.json")) as keyfile:
            p256_key = ECAlgorithm.from_jwk(keyfile.read())

        with pytest.raises(InvalidKeyError) as excinfo:
            algo.prepare_key(p256_key)
        assert "secp256r1" in str(excinfo.value)
        assert "secp384r1" in str(excinfo.value)

    def test_ec_curve_validation_rejects_wrong_curve_for_es512(self):
        """ES512 should reject keys that are not P-521."""
        from cryptography.hazmat.primitives.asymmetric.ec import SECP521R1

        algo = ECAlgorithm(ECAlgorithm.SHA512, SECP521R1)

        # P-256 key should be rejected
        with open(key_path("jwk_ec_key_P-256.json")) as keyfile:
            p256_key = ECAlgorithm.from_jwk(keyfile.read())

        with pytest.raises(InvalidKeyError) as excinfo:
            algo.prepare_key(p256_key)
        assert "secp256r1" in str(excinfo.value)
        assert "secp521r1" in str(excinfo.value)

    def test_ec_curve_validation_rejects_wrong_curve_for_es256k(self):
        """ES256K should reject keys that are not secp256k1."""
        from cryptography.hazmat.primitives.asymmetric.ec import SECP256K1

        algo = ECAlgorithm(ECAlgorithm.SHA256, SECP256K1)

        # P-256 key should be rejected
        with open(key_path("jwk_ec_key_P-256.json")) as keyfile:
            p256_key = ECAlgorithm.from_jwk(keyfile.read())

        with pytest.raises(InvalidKeyError) as excinfo:
            algo.prepare_key(p256_key)
        assert "secp256r1" in str(excinfo.value)
        assert "secp256k1" in str(excinfo.value)

    def test_ec_curve_validation_accepts_correct_curve_for_es256(self):
        """ES256 should accept P-256 keys."""
        from cryptography.hazmat.primitives.asymmetric.ec import SECP256R1

        algo = ECAlgorithm(ECAlgorithm.SHA256, SECP256R1)

        with open(key_path("jwk_ec_key_P-256.json")) as keyfile:
            key = algo.from_jwk(keyfile.read())
            prepared = algo.prepare_key(key)
            assert prepared is key

    def test_ec_curve_validation_accepts_correct_curve_for_es384(self):
        """ES384 should accept P-384 keys."""
        from cryptography.hazmat.primitives.asymmetric.ec import SECP384R1

        algo = ECAlgorithm(ECAlgorithm.SHA384, SECP384R1)

        with open(key_path("jwk_ec_key_P-384.json")) as keyfile:
            key = algo.from_jwk(keyfile.read())
            prepared = algo.prepare_key(key)
            assert prepared is key

    def test_ec_curve_validation_accepts_correct_curve_for_es512(self):
        """ES512 should accept P-521 keys."""
        from cryptography.hazmat.primitives.asymmetric.ec import SECP521R1

        algo = ECAlgorithm(ECAlgorithm.SHA512, SECP521R1)

        with open(key_path("jwk_ec_key_P-521.json")) as keyfile:
            key = algo.from_jwk(keyfile.read())
            prepared = algo.prepare_key(key)
            assert prepared is key

    def test_ec_curve_validation_accepts_correct_curve_for_es256k(self):
        """ES256K should accept secp256k1 keys."""
        from cryptography.hazmat.primitives.asymmetric.ec import SECP256K1

        algo = ECAlgorithm(ECAlgorithm.SHA256, SECP256K1)

        with open(key_path("jwk_ec_key_secp256k1.json")) as keyfile:
            key = algo.from_jwk(keyfile.read())
            prepared = algo.prepare_key(key)
            assert prepared is key

    def test_ec_curve_validation_rejects_p192_for_es256(self):
        """ES256 should reject P-192 keys (weaker than P-256)."""
        from cryptography.hazmat.primitives.asymmetric.ec import SECP256R1

        algo = ECAlgorithm(ECAlgorithm.SHA256, SECP256R1)

        with open(key_path("testkey_ec_secp192r1.priv")) as keyfile:
            with pytest.raises(InvalidKeyError) as excinfo:
                algo.prepare_key(keyfile.read())
            assert "secp192r1" in str(excinfo.value)
            assert "secp256r1" in str(excinfo.value)

    def test_ec_algorithm_without_expected_curve_accepts_any_curve(self):
        """ECAlgorithm without expected_curve should accept any curve (backwards compat)."""
        algo = ECAlgorithm(ECAlgorithm.SHA256)

        # Should accept P-256
        with open(key_path("jwk_ec_key_P-256.json")) as keyfile:
            p256_key = algo.from_jwk(keyfile.read())
            algo.prepare_key(p256_key)

        # Should accept P-384
        with open(key_path("jwk_ec_key_P-384.json")) as keyfile:
            p384_key = algo.from_jwk(keyfile.read())
            algo.prepare_key(p384_key)

        # Should accept P-521
        with open(key_path("jwk_ec_key_P-521.json")) as keyfile:
            p521_key = algo.from_jwk(keyfile.read())
            algo.prepare_key(p521_key)

        # Should accept secp256k1
        with open(key_path("jwk_ec_key_secp256k1.json")) as keyfile:
            secp256k1_key = algo.from_jwk(keyfile.read())
            algo.prepare_key(secp256k1_key)

    def test_default_algorithms_have_correct_expected_curve(self):
        """Default algorithms returned by get_default_algorithms should have expected_curve set."""
        from cryptography.hazmat.primitives.asymmetric.ec import (
            SECP256K1,
            SECP256R1,
            SECP384R1,
            SECP521R1,
        )

        from jwt.algorithms import get_default_algorithms

        algorithms = get_default_algorithms()

        es256 = algorithms["ES256"]
        assert isinstance(es256, ECAlgorithm)
        assert es256.expected_curve == SECP256R1

        es256k = algorithms["ES256K"]
        assert isinstance(es256k, ECAlgorithm)
        assert es256k.expected_curve == SECP256K1

        es384 = algorithms["ES384"]
        assert isinstance(es384, ECAlgorithm)
        assert es384.expected_curve == SECP384R1

        es521 = algorithms["ES521"]
        assert isinstance(es521, ECAlgorithm)
        assert es521.expected_curve == SECP521R1

        es512 = algorithms["ES512"]
        assert isinstance(es512, ECAlgorithm)
        assert es512.expected_curve == SECP521R1

    def test_ec_curve_validation_with_pem_key(self):
        """Curve validation should work with PEM-formatted keys."""
        from cryptography.hazmat.primitives.asymmetric.ec import SECP256R1

        algo = ECAlgorithm(ECAlgorithm.SHA256, SECP256R1)

        # P-256 PEM key should be accepted
        with open(key_path("testkey_ec.priv")) as keyfile:
            algo.prepare_key(keyfile.read())

        # P-192 PEM key should be rejected
        with open(key_path("testkey_ec_secp192r1.priv")) as keyfile:
            with pytest.raises(InvalidKeyError):
                algo.prepare_key(keyfile.read())

    def test_jwt_encode_decode_rejects_wrong_curve(self):
        """Integration test: jwt.encode/decode should reject wrong curve keys."""
        import jwt

        # Use P-384 key with ES256 algorithm (expects P-256)
        with open(key_path("jwk_ec_key_P-384.json")) as keyfile:
            p384_key = ECAlgorithm.from_jwk(keyfile.read())

        # Encoding should fail
        with pytest.raises(InvalidKeyError):
            jwt.encode({"hello": "world"}, p384_key, algorithm="ES256")

        # Create a valid token with P-256 key
        with open(key_path("jwk_ec_key_P-256.json")) as keyfile:
            p256_key = ECAlgorithm.from_jwk(keyfile.read())

        token = jwt.encode({"hello": "world"}, p256_key, algorithm="ES256")

        # Decoding with wrong curve key should fail
        with open(key_path("jwk_ec_pub_P-384.json")) as keyfile:
            p384_pub_key = ECAlgorithm.from_jwk(keyfile.read())

        with pytest.raises(InvalidKeyError):
            jwt.decode(token, p384_pub_key, algorithms=["ES256"])

        # Decoding with correct curve key should succeed
        with open(key_path("jwk_ec_pub_P-256.json")) as keyfile:
            p256_pub_key = ECAlgorithm.from_jwk(keyfile.read())

        decoded = jwt.decode(token, p256_pub_key, algorithms=["ES256"])
        assert decoded == {"hello": "world"}


class TestKeyLengthValidation:
    """Tests for minimum key length validation (CWE-326)."""

    # --- HMAC tests ---

    def test_hmac_short_key_warns_by_default_hs256(self):
        algo = HMACAlgorithm(HMACAlgorithm.SHA256)
        key = algo.prepare_key(b"short")
        msg = algo.check_key_length(key)
        assert msg is not None
        assert "below" in msg
        assert "32" in msg

    def test_hmac_short_key_warns_by_default_hs384(self):
        algo = HMACAlgorithm(HMACAlgorithm.SHA384)
        key = algo.prepare_key(b"a" * 47)
        msg = algo.check_key_length(key)
        assert msg is not None
        assert "48" in msg

    def test_hmac_short_key_warns_by_default_hs512(self):
        algo = HMACAlgorithm(HMACAlgorithm.SHA512)
        key = algo.prepare_key(b"a" * 63)
        msg = algo.check_key_length(key)
        assert msg is not None
        assert "64" in msg

    def test_hmac_empty_key_returns_warning_message(self):
        algo = HMACAlgorithm(HMACAlgorithm.SHA256)
        key = algo.prepare_key(b"")
        msg = algo.check_key_length(key)
        assert msg is not None

    def test_hmac_exact_minimum_no_warning(self):
        algo = HMACAlgorithm(HMACAlgorithm.SHA256)
        key = algo.prepare_key(b"a" * 32)
        assert algo.check_key_length(key) is None

    def test_hmac_above_minimum_no_warning(self):
        algo = HMACAlgorithm(HMACAlgorithm.SHA512)
        key = algo.prepare_key(b"a" * 128)
        assert algo.check_key_length(key) is None

    def test_hmac_exact_minimum_hs384(self):
        algo = HMACAlgorithm(HMACAlgorithm.SHA384)
        key = algo.prepare_key(b"a" * 48)
        assert algo.check_key_length(key) is None

    def test_hmac_exact_minimum_hs512(self):
        algo = HMACAlgorithm(HMACAlgorithm.SHA512)
        key = algo.prepare_key(b"a" * 64)
        assert algo.check_key_length(key) is None

    # --- RSA tests ---

    @crypto_required
    def test_rsa_small_key_returns_warning_message(self):
        from cryptography.hazmat.primitives.asymmetric import rsa as rsa_module

        small_key = rsa_module.generate_private_key(
            public_exponent=65537,
            key_size=1024,
        )
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)
        msg = algo.check_key_length(small_key)
        assert msg is not None
        assert "1024" in msg
        assert "2048" in msg

    @crypto_required
    def test_rsa_small_public_key_returns_warning_message(self):
        from cryptography.hazmat.primitives.asymmetric import rsa as rsa_module

        small_key = rsa_module.generate_private_key(
            public_exponent=65537,
            key_size=1024,
        )
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)
        msg = algo.check_key_length(small_key.public_key())
        assert msg is not None

    @crypto_required
    def test_rsa_2048_key_no_warning(self):
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)
        with open(key_path("testkey_rsa.priv")) as f:
            key = algo.prepare_key(f.read())
        assert algo.check_key_length(key) is None

    @crypto_required
    def test_rsa_pss_inherits_validation(self):
        from cryptography.hazmat.primitives.asymmetric import rsa as rsa_module

        small_key = rsa_module.generate_private_key(
            public_exponent=65537,
            key_size=1024,
        )
        algo = RSAPSSAlgorithm(RSAPSSAlgorithm.SHA256)
        msg = algo.check_key_length(small_key)
        assert msg is not None

    @crypto_required
    def test_rsa_pem_weak_key_validated(self):
        from cryptography.hazmat.primitives.asymmetric import rsa as rsa_module
        from cryptography.hazmat.primitives.serialization import (
            Encoding,
            NoEncryption,
            PrivateFormat,
        )

        small_key = rsa_module.generate_private_key(
            public_exponent=65537,
            key_size=1024,
        )
        pem = small_key.private_bytes(
            Encoding.PEM, PrivateFormat.TraditionalOpenSSL, NoEncryption()
        )
        algo = RSAAlgorithm(RSAAlgorithm.SHA256)
        prepared = algo.prepare_key(pem)
        msg = algo.check_key_length(prepared)
        assert msg is not None

    # --- PyJWS integration tests ---

    def test_pyjws_encode_warns_short_hmac_key(self):
        import jwt

        jws = jwt.PyJWS()
        with pytest.warns(jwt.InsecureKeyLengthWarning, match="below"):
            jws.encode(b'{"test":"payload"}', b"short", algorithm="HS256")

    def test_pyjws_encode_enforces_short_hmac_key(self):
        import jwt

        jws = jwt.PyJWS(options={"enforce_minimum_key_length": True})
        with pytest.raises(InvalidKeyError, match="below"):
            jws.encode(b'{"test":"payload"}', b"short", algorithm="HS256")

    def test_pyjws_encode_no_warning_adequate_key(self):
        import warnings

        import jwt

        jws = jwt.PyJWS()
        with warnings.catch_warnings():
            warnings.simplefilter("error", jwt.InsecureKeyLengthWarning)
            jws.encode(b'{"test":"payload"}', b"a" * 32, algorithm="HS256")

    # --- PyJWT integration tests ---

    def test_pyjwt_encode_warns_short_hmac_key(self):
        import jwt

        with pytest.warns(jwt.InsecureKeyLengthWarning):
            jwt.encode({"hello": "world"}, "short", algorithm="HS256")

    def test_pyjwt_encode_enforces_short_hmac_key(self):
        import jwt

        pyjwt = jwt.PyJWT(options={"enforce_minimum_key_length": True})
        with pytest.raises(InvalidKeyError, match="below"):
            pyjwt.encode({"hello": "world"}, "short", algorithm="HS256")

    def test_pyjwt_decode_enforces_short_hmac_key(self):
        import jwt

        adequate_key = "a" * 32
        token = jwt.encode({"hello": "world"}, adequate_key, algorithm="HS256")

        pyjwt = jwt.PyJWT(options={"enforce_minimum_key_length": True})
        # Decoding with adequate key should work
        result = pyjwt.decode(token, adequate_key, algorithms=["HS256"])
        assert result == {"hello": "world"}

        # Decoding with short key should raise
        pyjwt_enforce = jwt.PyJWT(options={"enforce_minimum_key_length": True})
        with pytest.raises(InvalidKeyError):
            pyjwt_enforce.decode(token, "short", algorithms=["HS256"])

    def test_pyjwt_encode_no_warning_adequate_key(self):
        import warnings

        import jwt

        with warnings.catch_warnings():
            warnings.simplefilter("error", jwt.InsecureKeyLengthWarning)
            jwt.encode({"hello": "world"}, "a" * 32, algorithm="HS256")

    def test_global_register_algorithm_works_with_encode(self):
        """Backward compat: jwt.register_algorithm + jwt.encode use the same JWS."""
        import jwt

        # This test just verifies the global path still works
        # (register_algorithm and encode share the same JWS instance)
        token = jwt.encode({"hello": "world"}, "a" * 32, algorithm="HS256")
        decoded = jwt.decode(token, "a" * 32, algorithms=["HS256"])
        assert decoded == {"hello": "world"}