-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
test_rsa.py
2606 lines (2422 loc) · 92.7 KB
/
test_rsa.py
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
# This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
import binascii
import itertools
import os
import pytest
from cryptography.exceptions import (
InvalidSignature,
UnsupportedAlgorithm,
_Reasons,
)
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import (
padding,
rsa,
utils as asym_utils,
)
from cryptography.hazmat.primitives.asymmetric.rsa import (
RSAPrivateNumbers,
RSAPublicNumbers,
)
from .fixtures_rsa import (
RSA_KEY_1024,
RSA_KEY_1025,
RSA_KEY_1026,
RSA_KEY_1027,
RSA_KEY_1028,
RSA_KEY_1029,
RSA_KEY_1030,
RSA_KEY_1031,
RSA_KEY_1536,
RSA_KEY_2048,
RSA_KEY_2048_ALT,
RSA_KEY_512,
RSA_KEY_522,
RSA_KEY_599,
RSA_KEY_745,
RSA_KEY_CORRUPTED,
)
from .utils import (
_check_rsa_private_numbers,
generate_rsa_verification_test,
skip_fips_traditional_openssl,
)
from ...doubles import (
DummyAsymmetricPadding,
DummyHashAlgorithm,
DummyKeySerializationEncryption,
)
from ...utils import (
load_nist_vectors,
load_pkcs1_vectors,
load_rsa_nist_vectors,
load_vectors_from_file,
raises_unsupported_algorithm,
)
class DummyMGF(padding.MGF):
_salt_length = 0
_algorithm = hashes.SHA1()
def _check_fips_key_length(backend, private_key):
if (
backend._fips_enabled
and private_key.key_size < backend._fips_rsa_min_key_size
):
pytest.skip(
"Key size not FIPS compliant: {}".format(private_key.key_size)
)
def _check_rsa_private_numbers_if_serializable(key):
if isinstance(key, rsa.RSAPrivateKey):
_check_rsa_private_numbers(key.private_numbers())
def test_check_rsa_private_numbers_if_serializable():
_check_rsa_private_numbers_if_serializable("notserializable")
def _flatten_pkcs1_examples(vectors):
flattened_vectors = []
for vector in vectors:
examples = vector[0].pop("examples")
for example in examples:
merged_vector = (vector[0], vector[1], example)
flattened_vectors.append(merged_vector)
return flattened_vectors
def _build_oaep_sha2_vectors():
base_path = os.path.join("asymmetric", "RSA", "oaep-custom")
vectors = []
hashalgs = [
hashes.SHA1(),
hashes.SHA224(),
hashes.SHA256(),
hashes.SHA384(),
hashes.SHA512(),
]
for mgf1alg, oaepalg in itertools.product(hashalgs, hashalgs):
if mgf1alg.name == "sha1" and oaepalg.name == "sha1":
# We need to generate the cartesian product of the permutations
# of all the SHAs above, but SHA1/SHA1 is something we already
# tested previously and thus did not generate custom vectors for.
continue
examples = _flatten_pkcs1_examples(
load_vectors_from_file(
os.path.join(
base_path,
"oaep-{}-{}.txt".format(mgf1alg.name, oaepalg.name),
),
load_pkcs1_vectors,
)
)
# We've loaded the files, but the loaders don't give us any information
# about the mgf1 or oaep hash algorithms. We know this info so we'll
# just add that to the end of the tuple
for private, public, vector in examples:
vectors.append((private, public, vector, mgf1alg, oaepalg))
return vectors
def _skip_pss_hash_algorithm_unsupported(backend, hash_alg):
if not backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hash_alg), salt_length=padding.PSS.MAX_LENGTH
)
):
pytest.skip(
"Does not support {} in MGF1 using PSS.".format(hash_alg.name)
)
def test_skip_pss_hash_algorithm_unsupported(backend):
with pytest.raises(pytest.skip.Exception):
_skip_pss_hash_algorithm_unsupported(backend, DummyHashAlgorithm())
def test_modular_inverse():
p = int(
"d1f9f6c09fd3d38987f7970247b85a6da84907753d42ec52bc23b745093f4fff5cff3"
"617ce43d00121a9accc0051f519c76e08cf02fc18acfe4c9e6aea18da470a2b611d2e"
"56a7b35caa2c0239bc041a53cc5875ca0b668ae6377d4b23e932d8c995fd1e58ecfd8"
"c4b73259c0d8a54d691cca3f6fb85c8a5c1baf588e898d481",
16,
)
q = int(
"d1519255eb8f678c86cfd06802d1fbef8b664441ac46b73d33d13a8404580a33a8e74"
"cb2ea2e2963125b3d454d7a922cef24dd13e55f989cbabf64255a736671f4629a47b5"
"b2347cfcd669133088d1c159518531025297c2d67c9da856a12e80222cd03b4c6ec0f"
"86c957cb7bb8de7a127b645ec9e820aa94581e4762e209f01",
16,
)
assert rsa._modinv(q, p) == int(
"0275e06afa722999315f8f322275483e15e2fb46d827b17800f99110b269a6732748f"
"624a382fa2ed1ec68c99f7fc56fb60e76eea51614881f497ba7034c17dde955f92f15"
"772f8b2b41f3e56d88b1e096cdd293eba4eae1e82db815e0fadea0c4ec971bc6fd875"
"c20e67e48c31a611e98d32c6213ae4c4d7b53023b2f80c538",
16,
)
class TestRSA:
@pytest.mark.parametrize(
("public_exponent", "key_size"),
itertools.product(
(3, 65537),
(1024, 1536, 2048),
),
)
def test_generate_rsa_keys(self, backend, public_exponent, key_size):
if backend._fips_enabled:
if key_size < backend._fips_rsa_min_key_size:
pytest.skip("Key size not FIPS compliant: {}".format(key_size))
if public_exponent < backend._fips_rsa_min_public_exponent:
pytest.skip(
"Exponent not FIPS compliant: {}".format(public_exponent)
)
skey = rsa.generate_private_key(public_exponent, key_size, backend)
assert skey.key_size == key_size
_check_rsa_private_numbers_if_serializable(skey)
pkey = skey.public_key()
assert isinstance(pkey.public_numbers(), rsa.RSAPublicNumbers)
def test_generate_bad_public_exponent(self, backend):
with pytest.raises(ValueError):
rsa.generate_private_key(
public_exponent=1, key_size=2048, backend=backend
)
with pytest.raises(ValueError):
rsa.generate_private_key(
public_exponent=4, key_size=2048, backend=backend
)
with pytest.raises(ValueError):
rsa.generate_private_key(
public_exponent=65535, key_size=2048, backend=backend
)
def test_cant_generate_insecure_tiny_key(self, backend):
with pytest.raises(ValueError):
rsa.generate_private_key(
public_exponent=65537, key_size=511, backend=backend
)
with pytest.raises(ValueError):
rsa.generate_private_key(
public_exponent=65537, key_size=256, backend=backend
)
@pytest.mark.parametrize(
"pkcs1_example",
load_vectors_from_file(
os.path.join(
"asymmetric", "RSA", "pkcs-1v2-1d2-vec", "pss-vect.txt"
),
load_pkcs1_vectors,
),
)
def test_load_pss_vect_example_keys(self, pkcs1_example):
secret, public = pkcs1_example
private_num = rsa.RSAPrivateNumbers(
p=secret["p"],
q=secret["q"],
d=secret["private_exponent"],
dmp1=secret["dmp1"],
dmq1=secret["dmq1"],
iqmp=secret["iqmp"],
public_numbers=rsa.RSAPublicNumbers(
e=secret["public_exponent"], n=secret["modulus"]
),
)
_check_rsa_private_numbers(private_num)
public_num = rsa.RSAPublicNumbers(
e=public["public_exponent"], n=public["modulus"]
)
assert public_num
public_num2 = private_num.public_numbers
assert public_num2
assert public_num.n == public_num2.n
assert public_num.e == public_num2.e
@pytest.mark.supported(
only_if=lambda backend: (
not backend._lib.CRYPTOGRAPHY_IS_LIBRESSL
and not backend._lib.CRYPTOGRAPHY_IS_BORINGSSL
and not backend._lib.CRYPTOGRAPHY_OPENSSL_LESS_THAN_111E
),
skip_message="Does not support RSA PSS loading",
)
@pytest.mark.parametrize(
"path",
[
os.path.join("asymmetric", "PKCS8", "rsa_pss_2048.pem"),
os.path.join("asymmetric", "PKCS8", "rsa_pss_2048_hash.pem"),
os.path.join("asymmetric", "PKCS8", "rsa_pss_2048_hash_mask.pem"),
os.path.join(
"asymmetric", "PKCS8", "rsa_pss_2048_hash_mask_diff.pem"
),
os.path.join(
"asymmetric", "PKCS8", "rsa_pss_2048_hash_mask_salt.pem"
),
],
)
def test_load_pss_keys_strips_constraints(self, path, backend):
key = load_vectors_from_file(
filename=path,
loader=lambda p: serialization.load_pem_private_key(
p.read(), password=None
),
mode="rb",
)
# These keys have constraints that prohibit PKCS1v15 signing,
# but for now we load them without the constraint and test that
# it's truly removed by performing a disallowed signature.
assert isinstance(key, rsa.RSAPrivateKey)
signature = key.sign(b"whatever", padding.PKCS1v15(), hashes.SHA224())
key.public_key().verify(
signature, b"whatever", padding.PKCS1v15(), hashes.SHA224()
)
@pytest.mark.supported(
only_if=lambda backend: (
backend._lib.CRYPTOGRAPHY_IS_LIBRESSL
or backend._lib.CRYPTOGRAPHY_IS_BORINGSSL
or backend._lib.CRYPTOGRAPHY_OPENSSL_LESS_THAN_111E
),
skip_message="Test requires a backend without RSA-PSS key support",
)
def test_load_pss_unsupported(self, backend):
# Key loading errors unfortunately have multiple paths so
# we need to allow ValueError and UnsupportedAlgorithm
with pytest.raises((UnsupportedAlgorithm, ValueError)):
load_vectors_from_file(
filename=os.path.join(
"asymmetric", "PKCS8", "rsa_pss_2048.pem"
),
loader=lambda p: serialization.load_pem_private_key(
p.read(), password=None
),
mode="rb",
)
@pytest.mark.parametrize(
"vector",
load_vectors_from_file(
os.path.join("asymmetric", "RSA", "oaep-label.txt"),
load_nist_vectors,
),
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=b"label",
)
),
skip_message="Does not support RSA OAEP labels",
)
def test_oaep_label_decrypt(self, vector, backend):
private_key = serialization.load_der_private_key(
binascii.unhexlify(vector["key"]), None, backend
)
assert isinstance(private_key, rsa.RSAPrivateKey)
assert vector["oaepdigest"] == b"SHA512"
decrypted = private_key.decrypt(
binascii.unhexlify(vector["input"]),
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA512()),
algorithm=hashes.SHA512(),
label=binascii.unhexlify(vector["oaeplabel"]),
),
)
assert vector["output"][1:-1] == decrypted
@pytest.mark.parametrize(
("msg", "label"),
[
(b"amazing encrypted msg", b"some label"),
(b"amazing encrypted msg", b""),
],
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=b"label",
)
),
skip_message="Does not support RSA OAEP labels",
)
def test_oaep_label_roundtrip(self, msg, label, backend):
private_key = RSA_KEY_2048.private_key(backend)
ct = private_key.public_key().encrypt(
msg,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=label,
),
)
pt = private_key.decrypt(
ct,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=label,
),
)
assert pt == msg
@pytest.mark.parametrize(
("enclabel", "declabel"),
[(b"label1", b"label2"), (b"label3", b""), (b"", b"label4")],
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=b"label",
)
),
skip_message="Does not support RSA OAEP labels",
)
def test_oaep_wrong_label(self, enclabel, declabel, backend):
private_key = RSA_KEY_2048.private_key(backend)
msg = b"test"
ct = private_key.public_key().encrypt(
msg,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=enclabel,
),
)
with pytest.raises(ValueError):
private_key.decrypt(
ct,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=declabel,
),
)
class TestRSASignature:
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
skip_message="Does not support PKCS1v1.5.",
)
@pytest.mark.supported(
only_if=lambda backend: backend.signature_hash_supported(
hashes.SHA1()
),
skip_message="Does not support SHA1 signature.",
)
def test_pkcs1v15_signing(self, backend, disable_rsa_checks, subtests):
vectors = _flatten_pkcs1_examples(
load_vectors_from_file(
os.path.join("asymmetric", "RSA", "pkcs1v15sign-vectors.txt"),
load_pkcs1_vectors,
)
)
for private, public, example in vectors:
with subtests.test():
private_key = rsa.RSAPrivateNumbers(
p=private["p"],
q=private["q"],
d=private["private_exponent"],
dmp1=private["dmp1"],
dmq1=private["dmq1"],
iqmp=private["iqmp"],
public_numbers=rsa.RSAPublicNumbers(
e=private["public_exponent"], n=private["modulus"]
),
).private_key(backend)
signature = private_key.sign(
binascii.unhexlify(example["message"]),
padding.PKCS1v15(),
hashes.SHA1(),
)
assert binascii.hexlify(signature) == example["signature"]
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH,
)
),
skip_message="Does not support PSS.",
)
@pytest.mark.supported(
only_if=lambda backend: backend.signature_hash_supported(
hashes.SHA1()
),
skip_message="Does not support SHA1 signature.",
)
def test_pss_signing(self, subtests, backend):
for private, public, example in _flatten_pkcs1_examples(
load_vectors_from_file(
os.path.join(
"asymmetric", "RSA", "pkcs-1v2-1d2-vec", "pss-vect.txt"
),
load_pkcs1_vectors,
)
):
with subtests.test():
private_key = rsa.RSAPrivateNumbers(
p=private["p"],
q=private["q"],
d=private["private_exponent"],
dmp1=private["dmp1"],
dmq1=private["dmq1"],
iqmp=private["iqmp"],
public_numbers=rsa.RSAPublicNumbers(
e=private["public_exponent"], n=private["modulus"]
),
).private_key(backend)
public_key = rsa.RSAPublicNumbers(
e=public["public_exponent"], n=public["modulus"]
).public_key(backend)
signature = private_key.sign(
binascii.unhexlify(example["message"]),
padding.PSS(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH,
),
hashes.SHA1(),
)
assert len(signature) == (private_key.key_size + 7) // 8
# PSS signatures contain randomness so we can't do an exact
# signature check. Instead we'll verify that the signature
# created successfully verifies.
public_key.verify(
signature,
binascii.unhexlify(example["message"]),
padding.PSS(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH,
),
hashes.SHA1(),
)
@pytest.mark.parametrize(
"hash_alg",
[hashes.SHA224(), hashes.SHA256(), hashes.SHA384(), hashes.SHA512()],
)
def test_pss_signing_sha2(self, hash_alg, backend):
_skip_pss_hash_algorithm_unsupported(backend, hash_alg)
private_key = RSA_KEY_2048.private_key(backend)
public_key = private_key.public_key()
pss = padding.PSS(
mgf=padding.MGF1(hash_alg), salt_length=padding.PSS.MAX_LENGTH
)
msg = b"testing signature"
signature = private_key.sign(msg, pss, hash_alg)
public_key.verify(signature, msg, pss, hash_alg)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.DIGEST_LENGTH,
)
),
skip_message="Does not support PSS.",
)
def test_pss_digest_length(self, backend):
private_key = RSA_KEY_2048.private_key()
signature = private_key.sign(
b"some data",
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.DIGEST_LENGTH,
),
hashes.SHA256(),
)
public = private_key.public_key()
public.verify(
signature,
b"some data",
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.DIGEST_LENGTH,
),
hashes.SHA256(),
)
public.verify(
signature,
b"some data",
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=32,
),
hashes.SHA256(),
)
@pytest.mark.supported(
only_if=lambda backend: (
backend.hash_supported(hashes.SHA512())
and backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH,
)
)
),
skip_message="Does not support SHA512.",
)
@pytest.mark.skip_fips(reason="Unsupported key size in FIPS mode.")
def test_pss_minimum_key_size_for_digest(self, backend):
private_key = RSA_KEY_522.private_key(backend)
private_key.sign(
b"no failure",
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH,
),
hashes.SHA512(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH,
)
),
skip_message="Does not support PSS.",
)
@pytest.mark.supported(
only_if=lambda backend: backend.hash_supported(hashes.SHA512()),
skip_message="Does not support SHA512.",
)
@pytest.mark.skip_fips(reason="Unsupported key size in FIPS mode.")
def test_pss_signing_digest_too_large_for_key_size(self, backend):
private_key = RSA_KEY_512.private_key(backend)
with pytest.raises(ValueError):
private_key.sign(
b"msg",
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH,
),
hashes.SHA512(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()),
salt_length=padding.PSS.MAX_LENGTH,
)
),
skip_message="Does not support PSS.",
)
def test_pss_signing_salt_length_too_long(self, backend):
private_key = RSA_KEY_2048.private_key(backend)
with pytest.raises(ValueError):
private_key.sign(
b"failure coming",
padding.PSS(
mgf=padding.MGF1(hashes.SHA1()), salt_length=1000000
),
hashes.SHA256(),
)
def test_unsupported_padding(self, backend):
private_key = RSA_KEY_2048.private_key(backend)
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_PADDING):
private_key.sign(b"msg", DummyAsymmetricPadding(), hashes.SHA1())
def test_padding_incorrect_type(self, backend):
private_key = RSA_KEY_2048.private_key(backend)
with pytest.raises(TypeError):
private_key.sign(
b"msg",
"notpadding", # type: ignore[arg-type]
hashes.SHA256(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=0)
),
skip_message="Does not support PSS.",
)
def test_unsupported_pss_mgf(self, backend):
private_key = RSA_KEY_512.private_key(backend)
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_MGF):
private_key.sign(
b"msg",
padding.PSS(
mgf=DummyMGF(),
salt_length=padding.PSS.MAX_LENGTH,
),
hashes.SHA1(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.AUTO,
)
),
skip_message="Does not support PSS.",
)
def test_pss_sign_unsupported_auto(self, backend):
private_key = RSA_KEY_2048.private_key()
with pytest.raises(ValueError):
private_key.sign(
b"some data",
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.AUTO,
),
hashes.SHA256(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
skip_message="Does not support PKCS1v1.5.",
)
@pytest.mark.skip_fips(reason="Unsupported key size in FIPS mode.")
def test_pkcs1_digest_too_large_for_key_size(self, backend):
private_key = RSA_KEY_599.private_key(backend)
with pytest.raises(ValueError):
private_key.sign(
b"failure coming", padding.PKCS1v15(), hashes.SHA512()
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
skip_message="Does not support PKCS1v1.5.",
)
@pytest.mark.skip_fips(reason="Unsupported key size in FIPS mode.")
def test_pkcs1_minimum_key_size(self, backend):
private_key = RSA_KEY_745.private_key(backend)
private_key.sign(b"no failure", padding.PKCS1v15(), hashes.SHA512())
def test_sign(self, backend):
private_key = RSA_KEY_2048.private_key(backend)
message = b"one little message"
pkcs = padding.PKCS1v15()
algorithm = hashes.SHA256()
signature = private_key.sign(message, pkcs, algorithm)
public_key = private_key.public_key()
public_key.verify(signature, message, pkcs, algorithm)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=0)
),
skip_message="Does not support PSS.",
)
def test_prehashed_sign(self, backend):
private_key = RSA_KEY_2048.private_key(backend)
message = b"one little message"
h = hashes.Hash(hashes.SHA256(), backend)
h.update(message)
digest = h.finalize()
pss = padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=0)
prehashed_alg = asym_utils.Prehashed(hashes.SHA256())
signature = private_key.sign(digest, pss, prehashed_alg)
public_key = private_key.public_key()
public_key.verify(signature, message, pss, hashes.SHA256())
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.DIGEST_LENGTH,
)
),
skip_message="Does not support PSS.",
)
def test_prehashed_digest_length(self, backend):
private_key = RSA_KEY_2048.private_key(backend)
message = b"one little message"
h = hashes.Hash(hashes.SHA256(), backend)
h.update(message)
digest = h.finalize()
pss = padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.DIGEST_LENGTH,
)
prehashed_alg = asym_utils.Prehashed(hashes.SHA256())
signature = private_key.sign(digest, pss, prehashed_alg)
public_key = private_key.public_key()
public_key.verify(signature, message, pss, hashes.SHA256())
@pytest.mark.supported(
only_if=lambda backend: backend.hash_supported(
hashes.BLAKE2s(digest_size=32)
),
skip_message="Does not support BLAKE2s",
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=0)
),
skip_message="Does not support PSS.",
)
def test_unsupported_hash(self, backend):
private_key = RSA_KEY_512.private_key(backend)
message = b"one little message"
pss = padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=0)
with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_HASH):
private_key.sign(message, pss, hashes.BLAKE2s(32))
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=0)
),
skip_message="Does not support PSS.",
)
def test_prehashed_digest_mismatch(self, backend):
private_key = RSA_KEY_512.private_key(backend)
message = b"one little message"
h = hashes.Hash(hashes.SHA512(), backend)
h.update(message)
digest = h.finalize()
pss = padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=0)
prehashed_alg = asym_utils.Prehashed(hashes.SHA1())
with pytest.raises(ValueError):
private_key.sign(digest, pss, prehashed_alg)
def test_prehashed_unsupported_in_signature_recover(self, backend):
private_key = RSA_KEY_2048.private_key(backend)
public_key = private_key.public_key()
signature = private_key.sign(
b"sign me", padding.PKCS1v15(), hashes.SHA256()
)
prehashed_alg = asym_utils.Prehashed(hashes.SHA256())
with pytest.raises(TypeError):
public_key.recover_data_from_signature(
signature,
padding.PKCS1v15(),
prehashed_alg, # type: ignore[arg-type]
)
def test_corrupted_private_key(self, backend):
with pytest.raises(ValueError):
serialization.load_pem_private_key(
RSA_KEY_CORRUPTED, password=None, backend=backend
)
class TestRSAVerification:
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
skip_message="Does not support PKCS1v1.5.",
)
@pytest.mark.supported(
only_if=lambda backend: backend.signature_hash_supported(
hashes.SHA1()
),
skip_message="Does not support SHA1 signature.",
)
def test_pkcs1v15_verification(self, backend, subtests):
vectors = _flatten_pkcs1_examples(
load_vectors_from_file(
os.path.join("asymmetric", "RSA", "pkcs1v15sign-vectors.txt"),
load_pkcs1_vectors,
)
)
for private, public, example in vectors:
with subtests.test():
public_key = rsa.RSAPublicNumbers(
e=public["public_exponent"], n=public["modulus"]
).public_key(backend)
signature = binascii.unhexlify(example["signature"])
message = binascii.unhexlify(example["message"])
public_key.verify(
signature, message, padding.PKCS1v15(), hashes.SHA1()
)
# Test digest recovery by providing hash
digest = hashes.Hash(hashes.SHA1())
digest.update(message)
msg_digest = digest.finalize()
rec_msg_digest = public_key.recover_data_from_signature(
signature, padding.PKCS1v15(), hashes.SHA1()
)
assert msg_digest == rec_msg_digest
# Test recovery of all data (full DigestInfo) with hash alg. as
# None
rec_sig_data = public_key.recover_data_from_signature(
signature, padding.PKCS1v15(), None
)
assert len(rec_sig_data) > len(msg_digest)
assert msg_digest == rec_sig_data[-len(msg_digest) :]
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
skip_message="Does not support PKCS1v1.5.",
)
def test_invalid_pkcs1v15_signature_wrong_data(self, backend):
private_key = RSA_KEY_2048.private_key(backend)
public_key = private_key.public_key()
signature = private_key.sign(
b"sign me", padding.PKCS1v15(), hashes.SHA256()
)
with pytest.raises(InvalidSignature):
public_key.verify(
signature,
b"incorrect data",
padding.PKCS1v15(),
hashes.SHA256(),
)
def test_invalid_pkcs1v15_signature_recover_wrong_hash_alg(self, backend):
private_key = RSA_KEY_2048.private_key(backend)
public_key = private_key.public_key()
signature = private_key.sign(
b"sign me", padding.PKCS1v15(), hashes.SHA256()
)
with pytest.raises(InvalidSignature):
public_key.recover_data_from_signature(
signature, padding.PKCS1v15(), hashes.SHA512()
)
def test_invalid_signature_sequence_removed(self, backend):
"""
This test comes from wycheproof
"""
key_der = binascii.unhexlify(
b"30820122300d06092a864886f70d01010105000382010f003082010a02820101"
b"00a2b451a07d0aa5f96e455671513550514a8a5b462ebef717094fa1fee82224"
b"e637f9746d3f7cafd31878d80325b6ef5a1700f65903b469429e89d6eac88450"
b"97b5ab393189db92512ed8a7711a1253facd20f79c15e8247f3d3e42e46e48c9"
b"8e254a2fe9765313a03eff8f17e1a029397a1fa26a8dce26f490ed81299615d9"
b"814c22da610428e09c7d9658594266f5c021d0fceca08d945a12be82de4d1ece"
b"6b4c03145b5d3495d4ed5411eb878daf05fd7afc3e09ada0f1126422f590975a"
b"1969816f48698bcbba1b4d9cae79d460d8f9f85e7975005d9bc22c4e5ac0f7c1"
b"a45d12569a62807d3b9a02e5a530e773066f453d1f5b4c2e9cf7820283f742b9"
b"d50203010001"
)
sig = binascii.unhexlify(
b"498209f59a0679a1f926eccf3056da2cba553d7ab3064e7c41ad1d739f038249"
b"f02f5ad12ee246073d101bc3cdb563e8b6be61562056422b7e6c16ad53deb12a"
b"f5de744197753a35859833f41bb59c6597f3980132b7478fd0b95fd27dfad64a"
b"20fd5c25312bbd41a85286cd2a83c8df5efa0779158d01b0747ff165b055eb28"
b"80ea27095700a295593196d8c5922cf6aa9d7e29b5056db5ded5eb20aeb31b89"
b"42e26b15a5188a4934cd7e39cfe379a197f49a204343a493452deebca436ee61"
b"4f4daf989e355544489f7e69ffa8ccc6a1e81cf0ab33c3e6d7591091485a6a31"
b"bda3b33946490057b9a3003d3fd9daf7c4778b43fd46144d945d815f12628ff4"
)
public_key = serialization.load_der_public_key(key_der, backend)
assert isinstance(public_key, rsa.RSAPublicKey)
with pytest.raises(InvalidSignature):
public_key.verify(
sig,
binascii.unhexlify(b"313233343030"),
padding.PKCS1v15(),
hashes.SHA256(),
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PKCS1v15()
),
skip_message="Does not support PKCS1v1.5.",
)
def test_invalid_pkcs1v15_signature_wrong_key(self, backend):
private_key = RSA_KEY_2048.private_key(backend)
private_key2 = RSA_KEY_2048_ALT.private_key(backend)
public_key = private_key2.public_key()
msg = b"sign me"
signature = private_key.sign(msg, padding.PKCS1v15(), hashes.SHA256())
with pytest.raises(InvalidSignature):
public_key.verify(
signature, msg, padding.PKCS1v15(), hashes.SHA256()
)
@pytest.mark.supported(
only_if=lambda backend: backend.rsa_padding_supported(
padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=20)
),
skip_message="Does not support PSS.",
)
@pytest.mark.supported(
only_if=lambda backend: backend.signature_hash_supported(
hashes.SHA1()
),
skip_message="Does not support SHA1 signature.",
)
def test_pss_verification(self, subtests, backend):
for private, public, example in _flatten_pkcs1_examples(
load_vectors_from_file(
os.path.join(
"asymmetric", "RSA", "pkcs-1v2-1d2-vec", "pss-vect.txt"
),
load_pkcs1_vectors,
)
):
with subtests.test():
public_key = rsa.RSAPublicNumbers(
e=public["public_exponent"], n=public["modulus"]
).public_key(backend)
public_key.verify(
binascii.unhexlify(example["signature"]),
binascii.unhexlify(example["message"]),
padding.PSS(
mgf=padding.MGF1(algorithm=hashes.SHA1()),
salt_length=20,