blob: 5214052ec6614db1cf3f695ab9e09f6ee4d28153 [file] [log] [blame]
Alex Gaynorc574e752018-07-17 09:20:13 -04001# This file is dual licensed under the terms of the Apache License, Version
2# 2.0, and the BSD License. See the LICENSE file in the root of this repository
3# for complete details.
4
5from __future__ import absolute_import, division, print_function
6
7import binascii
8
9import pytest
10
11from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm
12from cryptography.hazmat.backends.interfaces import EllipticCurveBackend
13from cryptography.hazmat.primitives import hashes, serialization
14from cryptography.hazmat.primitives.asymmetric import ec
15
16
17_DIGESTS = {
18 "SHA-1": hashes.SHA1(),
19 "SHA-224": hashes.SHA224(),
20 "SHA-256": hashes.SHA256(),
21 "SHA-384": hashes.SHA384(),
22 "SHA-512": hashes.SHA512(),
23}
24
25
26@pytest.mark.requires_backend_interface(interface=EllipticCurveBackend)
27@pytest.mark.wycheproof_tests(
28 "ecdsa_test.json",
29 "ecdsa_brainpoolP224r1_sha224_test.json",
30 "ecdsa_brainpoolP256r1_sha256_test.json",
31 "ecdsa_brainpoolP320r1_sha384_test.json",
32 "ecdsa_brainpoolP384r1_sha384_test.json",
33 "ecdsa_brainpoolP512r1_sha512_test.json",
34 "ecdsa_secp224r1_sha224_test.json",
35 "ecdsa_secp224r1_sha256_test.json",
36 "ecdsa_secp224r1_sha512_test.json",
37 "ecdsa_secp256k1_sha256_test.json",
38 "ecdsa_secp256k1_sha512_test.json",
39 "ecdsa_secp256r1_sha256_test.json",
40 "ecdsa_secp256r1_sha512_test.json",
41 "ecdsa_secp384r1_sha384_test.json",
42 "ecdsa_secp384r1_sha512_test.json",
43 "ecdsa_secp521r1_sha512_test.json",
44)
45def test_ecdsa_signature(backend, wycheproof):
46 try:
47 key = serialization.load_der_public_key(
48 binascii.unhexlify(wycheproof.testgroup["keyDer"]), backend
49 )
50 except (UnsupportedAlgorithm, ValueError):
51 # In OpenSSL 1.0.1, some keys fail to load with ValueError, instead of
52 # Unsupported Algorithm. We can remove handling for that exception
53 # when we drop support.
54 pytest.skip(
55 "unable to load key (curve {})".format(
56 wycheproof.testgroup["key"]["curve"]
57 )
58 )
59 digest = _DIGESTS[wycheproof.testgroup["sha"]]
60
61 if (
62 wycheproof.valid or
63 (wycheproof.acceptable and not wycheproof.has_flag("MissingZero"))
64 ):
65 key.verify(
66 binascii.unhexlify(wycheproof.testcase["sig"]),
67 binascii.unhexlify(wycheproof.testcase["msg"]),
68 ec.ECDSA(digest),
69 )
70 else:
71 with pytest.raises(InvalidSignature):
72 key.verify(
73 binascii.unhexlify(wycheproof.testcase["sig"]),
74 binascii.unhexlify(wycheproof.testcase["msg"]),
75 ec.ECDSA(digest),
76 )