From dd88e1cbe701fb286e856f96a020922ec6cf643b Mon Sep 17 00:00:00 2001 From: Alex Gaynor Date: Sun, 19 Jul 2020 17:11:25 -0400 Subject: [PATCH] Paint it Black by the Rolling Stones --- .github/workflows/download_openssl.py | 10 +- docs/conf.py | 72 +- .../custom-vectors/arc4/generate_arc4.py | 51 +- .../custom-vectors/cast5/generate_cast5.py | 8 +- .../custom-vectors/hkdf/generate_hkdf.py | 16 +- .../custom-vectors/idea/generate_idea.py | 8 +- .../custom-vectors/idea/verify_idea.py | 17 +- .../rsa-oaep-sha2/generate_rsa_oaep_sha2.py | 20 +- .../secp256k1/generate_secp256k1.py | 21 +- .../secp256k1/verify_secp256k1.py | 29 +- .../custom-vectors/seed/generate_seed.py | 8 +- .../custom-vectors/seed/verify_seed.py | 17 +- pyproject.toml | 4 + release.py | 65 +- setup.py | 138 +- src/_cffi_src/build_openssl.py | 19 +- src/_cffi_src/build_padding.py | 12 +- src/_cffi_src/utils.py | 33 +- src/cryptography/__about__.py | 16 +- src/cryptography/__init__.py | 22 +- src/cryptography/fernet.py | 2 +- src/cryptography/hazmat/_der.py | 4 +- src/cryptography/hazmat/_oid.py | 29 +- src/cryptography/hazmat/backends/__init__.py | 1 + .../hazmat/backends/interfaces.py | 5 +- .../hazmat/backends/openssl/aead.py | 26 +- .../hazmat/backends/openssl/backend.py | 528 ++- .../hazmat/backends/openssl/ciphers.py | 74 +- .../hazmat/backends/openssl/cmac.py | 29 +- .../hazmat/backends/openssl/decode_asn1.py | 101 +- .../hazmat/backends/openssl/dh.py | 102 +- .../hazmat/backends/openssl/dsa.py | 31 +- .../hazmat/backends/openssl/ec.py | 69 +- .../hazmat/backends/openssl/ed25519.py | 39 +- .../hazmat/backends/openssl/ed448.py | 37 +- .../hazmat/backends/openssl/encode_asn1.py | 58 +- .../hazmat/backends/openssl/hashes.py | 24 +- .../hazmat/backends/openssl/hmac.py | 16 +- .../hazmat/backends/openssl/ocsp.py | 53 +- .../hazmat/backends/openssl/poly1305.py | 13 +- .../hazmat/backends/openssl/rsa.py | 140 +- .../hazmat/backends/openssl/utils.py | 10 +- .../hazmat/backends/openssl/x25519.py | 37 +- .../hazmat/backends/openssl/x448.py | 27 +- .../hazmat/backends/openssl/x509.py | 60 +- .../hazmat/bindings/openssl/_conditional.py | 20 +- .../hazmat/bindings/openssl/binding.py | 9 +- .../hazmat/primitives/asymmetric/dh.py | 25 +- .../hazmat/primitives/asymmetric/dsa.py | 15 +- .../hazmat/primitives/asymmetric/ec.py | 37 +- .../hazmat/primitives/asymmetric/ed25519.py | 9 +- .../hazmat/primitives/asymmetric/ed448.py | 9 +- .../hazmat/primitives/asymmetric/padding.py | 6 +- .../hazmat/primitives/asymmetric/rsa.py | 62 +- .../hazmat/primitives/asymmetric/utils.py | 6 +- .../hazmat/primitives/asymmetric/x25519.py | 9 +- .../hazmat/primitives/asymmetric/x448.py | 9 +- .../hazmat/primitives/ciphers/__init__.py | 9 +- .../hazmat/primitives/ciphers/aead.py | 18 +- .../hazmat/primitives/ciphers/algorithms.py | 11 +- .../hazmat/primitives/ciphers/base.py | 14 +- .../hazmat/primitives/ciphers/modes.py | 19 +- src/cryptography/hazmat/primitives/cmac.py | 14 +- src/cryptography/hazmat/primitives/hashes.py | 6 +- src/cryptography/hazmat/primitives/hmac.py | 8 +- .../hazmat/primitives/kdf/concatkdf.py | 28 +- .../hazmat/primitives/kdf/hkdf.py | 16 +- .../hazmat/primitives/kdf/kbkdf.py | 43 +- .../hazmat/primitives/kdf/pbkdf2.py | 14 +- .../hazmat/primitives/kdf/scrypt.py | 7 +- .../hazmat/primitives/kdf/x963kdf.py | 14 +- src/cryptography/hazmat/primitives/keywrap.py | 24 +- src/cryptography/hazmat/primitives/padding.py | 36 +- .../hazmat/primitives/poly1305.py | 7 +- .../primitives/serialization/__init__.py | 39 +- .../hazmat/primitives/serialization/pkcs12.py | 14 +- .../hazmat/primitives/serialization/ssh.py | 21 +- .../hazmat/primitives/twofactor/hotp.py | 21 +- .../hazmat/primitives/twofactor/totp.py | 27 +- .../hazmat/primitives/twofactor/utils.py | 7 +- src/cryptography/utils.py | 18 +- src/cryptography/x509/__init__.py | 105 +- src/cryptography/x509/base.py | 286 +- src/cryptography/x509/extensions.py | 342 +- src/cryptography/x509/general_name.py | 34 +- src/cryptography/x509/name.py | 70 +- src/cryptography/x509/ocsp.py | 102 +- src/cryptography/x509/oid.py | 25 +- tests/conftest.py | 14 +- tests/hazmat/backends/test_openssl.py | 265 +- tests/hazmat/backends/test_openssl_memleak.py | 160 +- tests/hazmat/bindings/test_openssl.py | 9 +- tests/hazmat/primitives/fixtures_dh.py | 6 +- tests/hazmat/primitives/fixtures_dsa.py | 217 +- tests/hazmat/primitives/fixtures_ec.py | 266 +- tests/hazmat/primitives/fixtures_rsa.py | 447 +- tests/hazmat/primitives/test_3des.py | 30 +- tests/hazmat/primitives/test_aead.py | 65 +- tests/hazmat/primitives/test_aes.py | 68 +- tests/hazmat/primitives/test_arc4.py | 2 +- tests/hazmat/primitives/test_asym_utils.py | 8 +- tests/hazmat/primitives/test_block.py | 58 +- tests/hazmat/primitives/test_camellia.py | 6 +- tests/hazmat/primitives/test_cast5.py | 6 +- tests/hazmat/primitives/test_chacha20.py | 8 +- tests/hazmat/primitives/test_ciphers.py | 83 +- tests/hazmat/primitives/test_cmac.py | 78 +- tests/hazmat/primitives/test_concatkdf.py | 73 +- tests/hazmat/primitives/test_dh.py | 440 +- tests/hazmat/primitives/test_dsa.py | 318 +- tests/hazmat/primitives/test_ec.py | 543 ++- tests/hazmat/primitives/test_ed25519.py | 82 +- tests/hazmat/primitives/test_ed448.py | 101 +- tests/hazmat/primitives/test_hash_vectors.py | 113 +- tests/hazmat/primitives/test_hashes.py | 52 +- tests/hazmat/primitives/test_hkdf.py | 123 +- tests/hazmat/primitives/test_hkdf_vectors.py | 8 +- tests/hazmat/primitives/test_hmac.py | 24 +- tests/hazmat/primitives/test_hmac_vectors.py | 48 +- tests/hazmat/primitives/test_idea.py | 6 +- tests/hazmat/primitives/test_kbkdf.py | 327 +- tests/hazmat/primitives/test_kbkdf_vectors.py | 2 +- tests/hazmat/primitives/test_keywrap.py | 38 +- tests/hazmat/primitives/test_padding.py | 156 +- tests/hazmat/primitives/test_pbkdf2hmac.py | 4 +- .../primitives/test_pbkdf2hmac_vectors.py | 7 +- tests/hazmat/primitives/test_pkcs12.py | 129 +- tests/hazmat/primitives/test_poly1305.py | 22 +- tests/hazmat/primitives/test_rsa.py | 1199 ++--- tests/hazmat/primitives/test_scrypt.py | 105 +- tests/hazmat/primitives/test_seed.py | 6 +- tests/hazmat/primitives/test_serialization.py | 850 ++-- tests/hazmat/primitives/test_x25519.py | 100 +- tests/hazmat/primitives/test_x448.py | 96 +- tests/hazmat/primitives/test_x963_vectors.py | 25 +- tests/hazmat/primitives/test_x963kdf.py | 34 +- .../hazmat/primitives/twofactor/test_hotp.py | 17 +- .../hazmat/primitives/twofactor/test_totp.py | 45 +- tests/hazmat/primitives/utils.py | 153 +- tests/hazmat/test_der.py | 39 +- tests/hazmat/test_oid.py | 16 +- tests/test_fernet.py | 18 +- tests/test_interfaces.py | 4 +- tests/test_utils.py | 3342 ++++++++------ tests/test_warnings.py | 4 +- tests/utils.py | 161 +- tests/wycheproof/test_aes.py | 17 +- tests/wycheproof/test_chacha20poly1305.py | 2 +- tests/wycheproof/test_dsa.py | 6 +- tests/wycheproof/test_ecdsa.py | 5 +- tests/wycheproof/test_eddsa.py | 12 +- tests/wycheproof/test_hkdf.py | 4 +- tests/wycheproof/test_keywrap.py | 8 +- tests/wycheproof/test_rsa.py | 37 +- tests/wycheproof/test_x25519.py | 8 +- tests/wycheproof/test_x448.py | 8 +- tests/x509/test_ocsp.py | 492 ++- tests/x509/test_x509.py | 3897 +++++++++-------- tests/x509/test_x509_crlbuilder.py | 660 +-- tests/x509/test_x509_ext.py | 3523 ++++++++------- tests/x509/test_x509_revokedcertbuilder.py | 72 +- tox.ini | 3 +- vectors/cryptography_vectors/__about__.py | 10 +- vectors/cryptography_vectors/__init__.py | 20 +- vectors/setup.py | 6 +- 165 files changed, 12847 insertions(+), 10285 deletions(-) diff --git a/.github/workflows/download_openssl.py b/.github/workflows/download_openssl.py index 559e68192b07..cb3a494cb1f8 100644 --- a/.github/workflows/download_openssl.py +++ b/.github/workflows/download_openssl.py @@ -11,9 +11,9 @@ def get_response(session, url, token): response = session.get(url, headers={"Authorization": "token " + token}) if response.status_code != 200: - raise ValueError("Got HTTP {} fetching {}: ".format( - response.status_code, url - )) + raise ValueError( + "Got HTTP {} fetching {}: ".format(response.status_code, url) + ) return response @@ -28,9 +28,7 @@ def main(platform, target): raise ValueError("Invalid platform") session = requests.Session() - adapter = requests.adapters.HTTPAdapter( - max_retries=Retry() - ) + adapter = requests.adapters.HTTPAdapter(max_retries=Retry()) session.mount("https://", adapter) session.mount("http://", adapter) diff --git a/docs/conf.py b/docs/conf.py index fc0079ac0f7b..91bdf25f135c 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -35,7 +35,7 @@ # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath('.')) +sys.path.insert(0, os.path.abspath(".")) # -- General configuration ---------------------------------------------------- @@ -45,33 +45,33 @@ # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ - 'sphinx.ext.autodoc', - 'sphinx.ext.doctest', - 'sphinx.ext.intersphinx', - 'sphinx.ext.viewcode', - 'cryptography-docs', + "sphinx.ext.autodoc", + "sphinx.ext.doctest", + "sphinx.ext.intersphinx", + "sphinx.ext.viewcode", + "cryptography-docs", ] if spelling is not None: - extensions.append('sphinxcontrib.spelling') + extensions.append("sphinxcontrib.spelling") # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] nitpicky = True # The suffix of source filenames. -source_suffix = '.rst' +source_suffix = ".rst" # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. -project = 'Cryptography' -copyright = '2013-2017, Individual Contributors' +project = "Cryptography" +copyright = "2013-2017, Individual Contributors" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -81,7 +81,7 @@ base_dir = os.path.join(os.path.dirname(__file__), os.pardir) about = {} with open(os.path.join(base_dir, "src", "cryptography", "__about__.py")) as f: - exec(f.read(), about) + exec (f.read(), about) version = release = about["__version__"] @@ -97,7 +97,7 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ['_build'] +exclude_patterns = ["_build"] # The reST default role (used for this markup: `text`) to use for all documents # default_role = None @@ -114,7 +114,7 @@ # show_authors = False # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # -- Options for HTML output -------------------------------------------------- @@ -130,22 +130,26 @@ # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] +html_static_path = ["_static"] # Output file base name for HTML help builder. -htmlhelp_basename = 'Cryptographydoc' +htmlhelp_basename = "Cryptographydoc" # -- Options for LaTeX output ------------------------------------------------- -latex_elements = { -} +latex_elements = {} # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]) latex_documents = [ - ('index', 'Cryptography.tex', 'Cryptography Documentation', - 'Individual Contributors', 'manual'), + ( + "index", + "Cryptography.tex", + "Cryptography Documentation", + "Individual Contributors", + "manual", + ), ] # -- Options for manual page output ------------------------------------------- @@ -153,8 +157,13 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - ('index', 'cryptography', 'Cryptography Documentation', - ['Individual Contributors'], 1) + ( + "index", + "cryptography", + "Cryptography Documentation", + ["Individual Contributors"], + 1, + ) ] # -- Options for Texinfo output ----------------------------------------------- @@ -163,16 +172,21 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - ('index', 'Cryptography', 'Cryptography Documentation', - 'Individual Contributors', 'Cryptography', - 'One line description of project.', - 'Miscellaneous'), + ( + "index", + "Cryptography", + "Cryptography Documentation", + "Individual Contributors", + "Cryptography", + "One line description of project.", + "Miscellaneous", + ), ] # Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {'https://docs.python.org/3': None} +intersphinx_mapping = {"https://docs.python.org/3": None} -epub_theme = 'epub' +epub_theme = "epub" # Retry requests in the linkcheck builder so that we're resillient against # transient network errors. diff --git a/docs/development/custom-vectors/arc4/generate_arc4.py b/docs/development/custom-vectors/arc4/generate_arc4.py index 3dee44a305a4..2ca85c98dbe7 100644 --- a/docs/development/custom-vectors/arc4/generate_arc4.py +++ b/docs/development/custom-vectors/arc4/generate_arc4.py @@ -12,10 +12,14 @@ _RFC6229_KEY_MATERIALS = [ - (True, - 8 * '0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20'), - (False, - 8 * '1ada31d5cf688221c109163908ebe51debb46227c6cc8b37641910833222772a') + ( + True, + 8 * "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20", + ), + ( + False, + 8 * "1ada31d5cf688221c109163908ebe51debb46227c6cc8b37641910833222772a", + ), ] @@ -37,42 +41,43 @@ 3056, 3072, 4080, - 4096 + 4096, ] -_SIZES_TO_GENERATE = [ - 160 -] +_SIZES_TO_GENERATE = [160] def _key_for_size(size, keyinfo): msb, key = keyinfo if msb: - return key[:size // 4] + return key[: size // 4] else: - return key[-size // 4:] + return key[-size // 4 :] def _build_vectors(): count = 0 output = [] key = None - plaintext = binascii.unhexlify(32 * '0') + plaintext = binascii.unhexlify(32 * "0") for size in _SIZES_TO_GENERATE: for keyinfo in _RFC6229_KEY_MATERIALS: key = _key_for_size(size, keyinfo) cipher = ciphers.Cipher( algorithms.ARC4(binascii.unhexlify(key)), None, - default_backend()) + default_backend(), + ) encryptor = cipher.encryptor() current_offset = 0 for offset in _RFC6229_OFFSETS: if offset % 16 != 0: raise ValueError( - "Offset {} is not evenly divisible by 16" - .format(offset)) + "Offset {} is not evenly divisible by 16".format( + offset + ) + ) while current_offset < offset: encryptor.update(plaintext) current_offset += len(plaintext) @@ -80,19 +85,23 @@ def _build_vectors(): count += 1 output.append("KEY = {}".format(key)) output.append("OFFSET = {}".format(offset)) - output.append("PLAINTEXT = {}".format( - binascii.hexlify(plaintext))) - output.append("CIPHERTEXT = {}".format( - binascii.hexlify(encryptor.update(plaintext)))) + output.append( + "PLAINTEXT = {}".format(binascii.hexlify(plaintext)) + ) + output.append( + "CIPHERTEXT = {}".format( + binascii.hexlify(encryptor.update(plaintext)) + ) + ) current_offset += len(plaintext) assert not encryptor.finalize() return "\n".join(output) def _write_file(data, filename): - with open(filename, 'w') as f: + with open(filename, "w") as f: f.write(data) -if __name__ == '__main__': - _write_file(_build_vectors(), 'arc4.txt') +if __name__ == "__main__": + _write_file(_build_vectors(), "arc4.txt") diff --git a/docs/development/custom-vectors/cast5/generate_cast5.py b/docs/development/custom-vectors/cast5/generate_cast5.py index ce046b0f01f3..5208b90d8440 100644 --- a/docs/development/custom-vectors/cast5/generate_cast5.py +++ b/docs/development/custom-vectors/cast5/generate_cast5.py @@ -14,7 +14,7 @@ def encrypt(mode, key, iv, plaintext): cipher = base.Cipher( algorithms.CAST5(binascii.unhexlify(key)), mode(binascii.unhexlify(iv)), - default_backend() + default_backend(), ) encryptor = cipher.encryptor() ct = encryptor.update(binascii.unhexlify(plaintext)) @@ -34,8 +34,10 @@ def build_vectors(mode, filename): line = line.strip() if line.startswith("KEY"): if count != 0: - output.append("CIPHERTEXT = {}".format( - encrypt(mode, key, iv, plaintext)) + output.append( + "CIPHERTEXT = {}".format( + encrypt(mode, key, iv, plaintext) + ) ) output.append("\nCOUNT = {}".format(count)) count += 1 diff --git a/docs/development/custom-vectors/hkdf/generate_hkdf.py b/docs/development/custom-vectors/hkdf/generate_hkdf.py index 8976effdd7e2..aa2fc274f9ae 100644 --- a/docs/development/custom-vectors/hkdf/generate_hkdf.py +++ b/docs/development/custom-vectors/hkdf/generate_hkdf.py @@ -13,8 +13,11 @@ IKM = binascii.unhexlify(b"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b") L = 1200 OKM = HKDF( - algorithm=hashes.SHA256(), length=L, salt=None, info=None, - backend=default_backend() + algorithm=hashes.SHA256(), + length=L, + salt=None, + info=None, + backend=default_backend(), ).derive(IKM) @@ -23,7 +26,8 @@ def _build_vectors(): "COUNT = 0", "Hash = SHA-256", "IKM = " + binascii.hexlify(IKM).decode("ascii"), - "salt = ", "info = ", + "salt = ", + "info = ", "L = {}".format(L), "OKM = " + binascii.hexlify(OKM).decode("ascii"), ] @@ -31,9 +35,9 @@ def _build_vectors(): def _write_file(data, filename): - with open(filename, 'w') as f: + with open(filename, "w") as f: f.write(data) -if __name__ == '__main__': - _write_file(_build_vectors(), 'hkdf.txt') +if __name__ == "__main__": + _write_file(_build_vectors(), "hkdf.txt") diff --git a/docs/development/custom-vectors/idea/generate_idea.py b/docs/development/custom-vectors/idea/generate_idea.py index 2eb6996ef651..00309567b959 100644 --- a/docs/development/custom-vectors/idea/generate_idea.py +++ b/docs/development/custom-vectors/idea/generate_idea.py @@ -8,7 +8,7 @@ def encrypt(mode, key, iv, plaintext): cipher = base.Cipher( algorithms.IDEA(binascii.unhexlify(key)), mode(binascii.unhexlify(iv)), - backend + backend, ) encryptor = cipher.encryptor() ct = encryptor.update(binascii.unhexlify(plaintext)) @@ -29,8 +29,10 @@ def build_vectors(mode, filename): line = line.strip() if line.startswith("KEY"): if count != 0: - output.append("CIPHERTEXT = {0}".format( - encrypt(mode, key, iv, plaintext)) + output.append( + "CIPHERTEXT = {0}".format( + encrypt(mode, key, iv, plaintext) + ) ) output.append("\nCOUNT = {0}".format(count)) count += 1 diff --git a/docs/development/custom-vectors/idea/verify_idea.py b/docs/development/custom-vectors/idea/verify_idea.py index 89713c801dba..d356de0ba7f3 100644 --- a/docs/development/custom-vectors/idea/verify_idea.py +++ b/docs/development/custom-vectors/idea/verify_idea.py @@ -8,11 +8,13 @@ def encrypt(mode, key, iv, plaintext): - encryptor = botan.Cipher("IDEA/{0}/NoPadding".format(mode), "encrypt", - binascii.unhexlify(key)) + encryptor = botan.Cipher( + "IDEA/{0}/NoPadding".format(mode), "encrypt", binascii.unhexlify(key) + ) - cipher_text = encryptor.cipher(binascii.unhexlify(plaintext), - binascii.unhexlify(iv)) + cipher_text = encryptor.cipher( + binascii.unhexlify(plaintext), binascii.unhexlify(iv) + ) return binascii.hexlify(cipher_text) @@ -22,12 +24,7 @@ def verify_vectors(mode, filename): vectors = load_nist_vectors(vector_file) for vector in vectors: - ct = encrypt( - mode, - vector["key"], - vector["iv"], - vector["plaintext"] - ) + ct = encrypt(mode, vector["key"], vector["iv"], vector["plaintext"]) assert ct == vector["ciphertext"] diff --git a/docs/development/custom-vectors/rsa-oaep-sha2/generate_rsa_oaep_sha2.py b/docs/development/custom-vectors/rsa-oaep-sha2/generate_rsa_oaep_sha2.py index bd5148f54cbd..a43e1506d53d 100644 --- a/docs/development/custom-vectors/rsa-oaep-sha2/generate_rsa_oaep_sha2.py +++ b/docs/development/custom-vectors/rsa-oaep-sha2/generate_rsa_oaep_sha2.py @@ -62,9 +62,8 @@ def build_vectors(mgf1alg, hashalg, filename): dmq1=private["dmq1"], iqmp=private["iqmp"], public_numbers=rsa.RSAPublicNumbers( - e=private["public_exponent"], - n=private["modulus"] - ) + e=private["public_exponent"], n=private["modulus"] + ), ).private_key(backend) count = 1 @@ -74,8 +73,8 @@ def build_vectors(mgf1alg, hashalg, filename): padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), - label=None - ) + label=None, + ), ) assert message == binascii.unhexlify(example["message"]) ct = pkey.encrypt( @@ -83,8 +82,8 @@ def build_vectors(mgf1alg, hashalg, filename): padding.OAEP( mgf=padding.MGF1(algorithm=mgf1alg), algorithm=hashalg, - label=None - ) + label=None, + ), ) output.append( b"# OAEP Example {0} alg={1} mgf1={2}".format( @@ -116,13 +115,12 @@ def write_file(data, filename): hashes.SHA512(), ] for hashtuple in itertools.product(hashalgs, hashalgs): - if ( - isinstance(hashtuple[0], hashes.SHA1) and - isinstance(hashtuple[1], hashes.SHA1) + if isinstance(hashtuple[0], hashes.SHA1) and isinstance( + hashtuple[1], hashes.SHA1 ): continue write_file( build_vectors(hashtuple[0], hashtuple[1], oaep_path), - "oaep-{0}-{1}.txt".format(hashtuple[0].name, hashtuple[1].name) + "oaep-{0}-{1}.txt".format(hashtuple[0].name, hashtuple[1].name), ) diff --git a/docs/development/custom-vectors/secp256k1/generate_secp256k1.py b/docs/development/custom-vectors/secp256k1/generate_secp256k1.py index d6a2071ac22c..bfb150ba6fcc 100644 --- a/docs/development/custom-vectors/secp256k1/generate_secp256k1.py +++ b/docs/development/custom-vectors/secp256k1/generate_secp256k1.py @@ -10,9 +10,7 @@ from cryptography_vectors import open_vector_file -from tests.utils import ( - load_fips_ecdsa_signing_vectors, load_vectors_from_file -) +from tests.utils import load_fips_ecdsa_signing_vectors, load_vectors_from_file HASHLIB_HASH_TYPES = { "SHA-1": hashlib.sha1, @@ -32,13 +30,13 @@ def __call__(self, data): return self def digest(self): - return self.hasher.digest()[:256 // 8] + return self.hasher.digest()[: 256 // 8] def build_vectors(fips_vectors): vectors = defaultdict(list) for vector in fips_vectors: - vectors[vector['digest_algorithm']].append(vector['message']) + vectors[vector["digest_algorithm"]].append(vector["message"]) for digest_algorithm, messages in vectors.items(): if digest_algorithm not in HASHLIB_HASH_TYPES: @@ -55,8 +53,9 @@ def build_vectors(fips_vectors): # Sign the message using warner/ecdsa secret_key = SigningKey.generate(curve=SECP256k1) public_key = secret_key.get_verifying_key() - signature = secret_key.sign(message, hashfunc=hash_func, - sigencode=sigencode_der) + signature = secret_key.sign( + message, hashfunc=hash_func, sigencode=sigencode_der + ) r, s = sigdecode_der(signature, None) @@ -79,12 +78,8 @@ def write_file(lines, dest): dest_path = os.path.join("asymmetric", "ECDSA", "SECP256K1", "SigGen.txt") fips_vectors = load_vectors_from_file( - source_path, - load_fips_ecdsa_signing_vectors + source_path, load_fips_ecdsa_signing_vectors ) with open_vector_file(dest_path, "w") as dest_file: - write_file( - build_vectors(fips_vectors), - dest_file - ) + write_file(build_vectors(fips_vectors), dest_file) diff --git a/docs/development/custom-vectors/secp256k1/verify_secp256k1.py b/docs/development/custom-vectors/secp256k1/verify_secp256k1.py index b236d77fcf07..485f0718bc02 100644 --- a/docs/development/custom-vectors/secp256k1/verify_secp256k1.py +++ b/docs/development/custom-vectors/secp256k1/verify_secp256k1.py @@ -6,12 +6,10 @@ from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.asymmetric.utils import ( - encode_dss_signature + encode_dss_signature, ) -from tests.utils import ( - load_fips_ecdsa_signing_vectors, load_vectors_from_file -) +from tests.utils import load_fips_ecdsa_signing_vectors, load_vectors_from_file CRYPTOGRAPHY_HASH_TYPES = { "SHA-1": hashes.SHA1, @@ -23,22 +21,18 @@ def verify_one_vector(vector): - digest_algorithm = vector['digest_algorithm'] - message = vector['message'] - x = vector['x'] - y = vector['y'] - signature = encode_dss_signature(vector['r'], vector['s']) - - numbers = ec.EllipticCurvePublicNumbers( - x, y, - ec.SECP256K1() - ) + digest_algorithm = vector["digest_algorithm"] + message = vector["message"] + x = vector["x"] + y = vector["y"] + signature = encode_dss_signature(vector["r"], vector["s"]) + + numbers = ec.EllipticCurvePublicNumbers(x, y, ec.SECP256K1()) key = numbers.public_key(default_backend()) verifier = key.verifier( - signature, - ec.ECDSA(CRYPTOGRAPHY_HASH_TYPES[digest_algorithm]()) + signature, ec.ECDSA(CRYPTOGRAPHY_HASH_TYPES[digest_algorithm]()) ) verifier.update(message) return verifier.verify() @@ -52,8 +46,7 @@ def verify_vectors(vectors): vector_path = os.path.join("asymmetric", "ECDSA", "SECP256K1", "SigGen.txt") secp256k1_vectors = load_vectors_from_file( - vector_path, - load_fips_ecdsa_signing_vectors + vector_path, load_fips_ecdsa_signing_vectors ) verify_vectors(secp256k1_vectors) diff --git a/docs/development/custom-vectors/seed/generate_seed.py b/docs/development/custom-vectors/seed/generate_seed.py index 5c62d6713398..046fcfb87b48 100644 --- a/docs/development/custom-vectors/seed/generate_seed.py +++ b/docs/development/custom-vectors/seed/generate_seed.py @@ -8,7 +8,7 @@ def encrypt(mode, key, iv, plaintext): cipher = base.Cipher( algorithms.SEED(binascii.unhexlify(key)), mode(binascii.unhexlify(iv)), - backend + backend, ) encryptor = cipher.encryptor() ct = encryptor.update(binascii.unhexlify(plaintext)) @@ -29,8 +29,10 @@ def build_vectors(mode, filename): line = line.strip() if line.startswith("KEY"): if count != 0: - output.append("CIPHERTEXT = {0}".format( - encrypt(mode, key, iv, plaintext)) + output.append( + "CIPHERTEXT = {0}".format( + encrypt(mode, key, iv, plaintext) + ) ) output.append("\nCOUNT = {0}".format(count)) count += 1 diff --git a/docs/development/custom-vectors/seed/verify_seed.py b/docs/development/custom-vectors/seed/verify_seed.py index e626428cb0c2..252088d083e1 100644 --- a/docs/development/custom-vectors/seed/verify_seed.py +++ b/docs/development/custom-vectors/seed/verify_seed.py @@ -6,11 +6,13 @@ def encrypt(mode, key, iv, plaintext): - encryptor = botan.Cipher("SEED/{0}/NoPadding".format(mode), "encrypt", - binascii.unhexlify(key)) + encryptor = botan.Cipher( + "SEED/{0}/NoPadding".format(mode), "encrypt", binascii.unhexlify(key) + ) - cipher_text = encryptor.cipher(binascii.unhexlify(plaintext), - binascii.unhexlify(iv)) + cipher_text = encryptor.cipher( + binascii.unhexlify(plaintext), binascii.unhexlify(iv) + ) return binascii.hexlify(cipher_text) @@ -20,12 +22,7 @@ def verify_vectors(mode, filename): vectors = load_nist_vectors(vector_file) for vector in vectors: - ct = encrypt( - mode, - vector["key"], - vector["iv"], - vector["plaintext"] - ) + ct = encrypt(mode, vector["key"], vector["iv"], vector["plaintext"]) assert ct == vector["ciphertext"] diff --git a/pyproject.toml b/pyproject.toml index e4d893fcba8b..957b1fd04bb0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -8,3 +8,7 @@ requires = [ "cffi>=1.8,!=1.11.3; platform_python_implementation != 'PyPy'", ] build-backend = "setuptools.build_meta" + +[tool.black] +line-length = 79 +target-version = ["py27"] diff --git a/release.py b/release.py index fdde7d680c8b..a5eea848e0b0 100644 --- a/release.py +++ b/release.py @@ -25,10 +25,13 @@ def run(*args, **kwargs): def wait_for_build_complete_github_actions(session, token, run_url): while True: - response = session.get(run_url, headers={ - "Content-Type": "application/json", - "Authorization": "token {}".format(token), - }) + response = session.get( + run_url, + headers={ + "Content-Type": "application/json", + "Authorization": "token {}".format(token), + }, + ) response.raise_for_status() if response.json()["conclusion"] is not None: break @@ -36,32 +39,39 @@ def wait_for_build_complete_github_actions(session, token, run_url): def download_artifacts_github_actions(session, token, run_url): - response = session.get(run_url, headers={ - "Content-Type": "application/json", - "Authorization": "token {}".format(token), - }) + response = session.get( + run_url, + headers={ + "Content-Type": "application/json", + "Authorization": "token {}".format(token), + }, + ) response.raise_for_status() - response = session.get(response.json()["artifacts_url"], headers={ - "Content-Type": "application/json", - "Authorization": "token {}".format(token), - }) + response = session.get( + response.json()["artifacts_url"], + headers={ + "Content-Type": "application/json", + "Authorization": "token {}".format(token), + }, + ) response.raise_for_status() paths = [] for artifact in response.json()["artifacts"]: - response = session.get(artifact["archive_download_url"], headers={ - "Content-Type": "application/json", - "Authorization": "token {}".format(token), - }) + response = session.get( + artifact["archive_download_url"], + headers={ + "Content-Type": "application/json", + "Authorization": "token {}".format(token), + }, + ) with zipfile.ZipFile(io.BytesIO(response.content)) as z: for name in z.namelist(): if not name.endswith(".whl"): continue p = z.open(name) out_path = os.path.join( - os.path.dirname(__file__), - "dist", - os.path.basename(name), + os.path.dirname(__file__), "dist", os.path.basename(name), ) with open(out_path, "wb") as f: f.write(p.read()) @@ -79,12 +89,12 @@ def build_github_actions_wheels(token, version): "Accept": "application/vnd.github.everest-preview+json", "Authorization": "token {}".format(token), }, - data=json.dumps({ - "event_type": "wheel-builder", - "client_payload": { - "BUILD_VERSION": version, - }, - }), + data=json.dumps( + { + "event_type": "wheel-builder", + "client_payload": {"BUILD_VERSION": version}, + } + ), ) response.raise_for_status() @@ -120,9 +130,8 @@ def release(version): run("python", "setup.py", "sdist") run("python", "setup.py", "sdist", "bdist_wheel", cwd="vectors/") - packages = ( - glob.glob("dist/cryptography-{0}*".format(version)) + - glob.glob("vectors/dist/cryptography_vectors-{0}*".format(version)) + packages = glob.glob("dist/cryptography-{0}*".format(version)) + glob.glob( + "vectors/dist/cryptography_vectors-{0}*".format(version) ) run("twine", "upload", "-s", *packages) diff --git a/setup.py b/setup.py index acefbbf930b4..450279142e3d 100644 --- a/setup.py +++ b/setup.py @@ -18,10 +18,9 @@ from setuptools.command.install import install -if ( - pkg_resources.parse_version(setuptools.__version__) < - pkg_resources.parse_version("18.5") -): +if pkg_resources.parse_version( + setuptools.__version__ +) < pkg_resources.parse_version("18.5"): raise RuntimeError( "cryptography requires setuptools 18.5 or newer, please upgrade to a " "newer version of setuptools" @@ -36,7 +35,7 @@ about = {} with open(os.path.join(src_dir, "cryptography", "__about__.py")) as f: - exec(f.read(), about) + exec (f.read(), about) # `setup_requirements` must be kept in sync with `pyproject.toml` @@ -76,47 +75,52 @@ def keywords_with_side_effects(argv): .. _setup.py script: https://github.com/scipy/scipy/blob/master/setup.py """ no_setup_requires_arguments = ( - '-h', '--help', - '-n', '--dry-run', - '-q', '--quiet', - '-v', '--verbose', - '-V', '--version', - '--author', - '--author-email', - '--classifiers', - '--contact', - '--contact-email', - '--description', - '--egg-base', - '--fullname', - '--help-commands', - '--keywords', - '--licence', - '--license', - '--long-description', - '--maintainer', - '--maintainer-email', - '--name', - '--no-user-cfg', - '--obsoletes', - '--platforms', - '--provides', - '--requires', - '--url', - 'clean', - 'egg_info', - 'register', - 'sdist', - 'upload', + "-h", + "--help", + "-n", + "--dry-run", + "-q", + "--quiet", + "-v", + "--verbose", + "-V", + "--version", + "--author", + "--author-email", + "--classifiers", + "--contact", + "--contact-email", + "--description", + "--egg-base", + "--fullname", + "--help-commands", + "--keywords", + "--licence", + "--license", + "--long-description", + "--maintainer", + "--maintainer-email", + "--name", + "--no-user-cfg", + "--obsoletes", + "--platforms", + "--provides", + "--requires", + "--url", + "clean", + "egg_info", + "register", + "sdist", + "upload", ) def is_short_option(argument): """Check whether a command line argument is a short option.""" - return len(argument) >= 2 and argument[0] == '-' and argument[1] != '-' + return len(argument) >= 2 and argument[0] == "-" and argument[1] != "-" def expand_short_options(argument): """Expand combined short options into canonical short options.""" - return ('-' + char for char in argument[1:]) + return ("-" + char for char in argument[1:]) def argument_without_setup_requirements(argv, i): """Check whether a command line argument needs setup requirements.""" @@ -124,27 +128,25 @@ def argument_without_setup_requirements(argv, i): # Simple case: An argument which is either an option or a command # which doesn't need setup requirements. return True - elif (is_short_option(argv[i]) and - all(option in no_setup_requires_arguments - for option in expand_short_options(argv[i]))): + elif is_short_option(argv[i]) and all( + option in no_setup_requires_arguments + for option in expand_short_options(argv[i]) + ): # Not so simple case: Combined short options none of which need # setup requirements. return True - elif argv[i - 1:i] == ['--egg-base']: + elif argv[i - 1 : i] == ["--egg-base"]: # Tricky case: --egg-info takes an argument which should not make # us use setup_requires (defeating the purpose of this code). return True else: return False - if all(argument_without_setup_requirements(argv, i) - for i in range(1, len(argv))): - return { - "cmdclass": { - "build": DummyBuild, - "install": DummyInstall, - } - } + if all( + argument_without_setup_requirements(argv, i) + for i in range(1, len(argv)) + ): + return {"cmdclass": {"build": DummyBuild, "install": DummyInstall}} else: cffi_modules = [ "src/_cffi_src/build_openssl.py:ffi", @@ -153,13 +155,15 @@ def argument_without_setup_requirements(argv, i): return { "setup_requires": setup_requirements, - "cffi_modules": cffi_modules + "cffi_modules": cffi_modules, } -setup_requires_error = ("Requested setup command that needs 'setup_requires' " - "while command line arguments implied a side effect " - "free command or option.") +setup_requires_error = ( + "Requested setup command that needs 'setup_requires' " + "while command line arguments implied a side effect " + "free command or option." +) class DummyBuild(build): @@ -191,16 +195,13 @@ def run(self): setup( name=about["__title__"], version=about["__version__"], - description=about["__summary__"], long_description=long_description, long_description_content_type="text/x-rst", license=about["__license__"], url=about["__uri__"], - author=about["__author__"], author_email=about["__email__"], - classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", @@ -224,19 +225,13 @@ def run(self): "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Security :: Cryptography", ], - package_dir={"": "src"}, packages=find_packages(where="src", exclude=["_cffi_src", "_cffi_src.*"]), include_package_data=True, - - python_requires='>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*', - - install_requires=[ - "six >= 1.4.1", - ] + setup_requirements, + python_requires=">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*", + install_requires=["six >= 1.4.1"] + setup_requirements, extras_require={ ":python_version < '3'": ["enum34", "ipaddress"], - "test": [ "pytest>=3.6.0,!=3.9.0,!=3.9.1,!=3.9.2", "pretend", @@ -254,22 +249,15 @@ def run(self): "twine >= 1.12.0", "sphinxcontrib-spelling >= 4.0.1", ], - "pep8test": [ - "flake8", - "flake8-import-order", - "pep8-naming", - ], + "pep8test": ["black", "flake8", "flake8-import-order", "pep8-naming"], # This extra is for OpenSSH private keys that use bcrypt KDF # Versions: v3.1.3 - ignore_few_rounds, v3.1.5 - abi3 "ssh": ["bcrypt >= 3.1.5"], # This extra is for the U-label support that was deprecated in # cryptography 2.1. If you need this deprecated path install with # pip install cryptography[idna] - "idna": [ - "idna >= 2.1", - ] + "idna": ["idna >= 2.1"], }, - # for cffi zip_safe=False, ext_package="cryptography.hazmat.bindings", diff --git a/src/_cffi_src/build_openssl.py b/src/_cffi_src/build_openssl.py index 8cc1066ad338..35ccd6b9be0a 100644 --- a/src/_cffi_src/build_openssl.py +++ b/src/_cffi_src/build_openssl.py @@ -11,7 +11,9 @@ from distutils.command.config import config from _cffi_src.utils import ( - build_ffi_for_binding, compiler_type, extra_link_args + build_ffi_for_binding, + compiler_type, + extra_link_args, ) @@ -40,7 +42,7 @@ def _get_openssl_libraries(platform): # -lpthread required due to usage of pthread an potential # existance of a static part containing e.g. pthread_atfork # (https://github.com/pyca/cryptography/issues/5084) - if sys.platform == 'zos': + if sys.platform == "zos": return ["ssl", "crypto"] else: return ["ssl", "crypto", "pthread"] @@ -62,10 +64,14 @@ def _extra_compile_args(platform): d = dist.Distribution() cmd = config(d) cmd._check_compiler() - is_gcc = ("gcc" in cmd.compiler.compiler[0] or - "clang" in cmd.compiler.compiler[0]) - if is_gcc or not (platform in ["win32", "hp-ux11", "sunos5"] or - platform.startswith("aix")): + is_gcc = ( + "gcc" in cmd.compiler.compiler[0] + or "clang" in cmd.compiler.compiler[0] + ) + if is_gcc or not ( + platform in ["win32", "hp-ux11", "sunos5"] + or platform.startswith("aix") + ): return ["-Wconversion", "-Wno-error=sign-conversion"] else: return [] @@ -77,7 +83,6 @@ def _extra_compile_args(platform): modules=[ # This goes first so we can define some cryptography-wide symbols. "cryptography", - "aes", "asn1", "bignum", diff --git a/src/_cffi_src/build_padding.py b/src/_cffi_src/build_padding.py index 4c5096a19435..207f4a658ea2 100644 --- a/src/_cffi_src/build_padding.py +++ b/src/_cffi_src/build_padding.py @@ -9,14 +9,14 @@ from _cffi_src.utils import build_ffi, compiler_type, extra_link_args -with open(os.path.join( - os.path.dirname(__file__), "hazmat_src/padding.h" -)) as f: +with open( + os.path.join(os.path.dirname(__file__), "hazmat_src/padding.h") +) as f: types = f.read() -with open(os.path.join( - os.path.dirname(__file__), "hazmat_src/padding.c" -)) as f: +with open( + os.path.join(os.path.dirname(__file__), "hazmat_src/padding.c") +) as f: functions = f.read() ffi = build_ffi( diff --git a/src/_cffi_src/utils.py b/src/_cffi_src/utils.py index eecd6ea12367..56745a3e5b2e 100644 --- a/src/_cffi_src/utils.py +++ b/src/_cffi_src/utils.py @@ -16,11 +16,17 @@ base_src = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) about = {} with open(os.path.join(base_src, "cryptography", "__about__.py")) as f: - exec(f.read(), about) + exec (f.read(), about) -def build_ffi_for_binding(module_name, module_prefix, modules, libraries=[], - extra_compile_args=[], extra_link_args=[]): +def build_ffi_for_binding( + module_name, + module_prefix, + modules, + libraries=[], + extra_compile_args=[], + extra_link_args=[], +): """ Modules listed in ``modules`` should have the following attributes: @@ -44,10 +50,7 @@ def build_ffi_for_binding(module_name, module_prefix, modules, libraries=[], includes.append(module.INCLUDES) customizations.append(module.CUSTOMIZATIONS) - verify_source = "\n".join( - includes + - customizations - ) + verify_source = "\n".join(includes + customizations) ffi = build_ffi( module_name, cdef_source="\n".join(types + functions), @@ -60,8 +63,14 @@ def build_ffi_for_binding(module_name, module_prefix, modules, libraries=[], return ffi -def build_ffi(module_name, cdef_source, verify_source, libraries=[], - extra_compile_args=[], extra_link_args=[]): +def build_ffi( + module_name, + cdef_source, + verify_source, + libraries=[], + extra_compile_args=[], + extra_link_args=[], +): ffi = FFI() # Always add the CRYPTOGRAPHY_PACKAGE_VERSION to the shared object cdef_source += "\nstatic const char *const CRYPTOGRAPHY_PACKAGE_VERSION;" @@ -80,10 +89,10 @@ def build_ffi(module_name, cdef_source, verify_source, libraries=[], def extra_link_args(compiler_type): - if compiler_type == 'msvc': + if compiler_type == "msvc": # Enable NX and ASLR for Windows builds on MSVC. These are enabled by # default on Python 3.3+ but not on 2.x. - return ['/NXCOMPAT', '/DYNAMICBASE'] + return ["/NXCOMPAT", "/DYNAMICBASE"] else: return [] @@ -95,7 +104,7 @@ def compiler_type(): """ dist = Distribution() dist.parse_config_files() - cmd = dist.get_command_obj('build') + cmd = dist.get_command_obj("build") cmd.ensure_finalized() compiler = new_compiler(compiler=cmd.compiler) return compiler.compiler_type diff --git a/src/cryptography/__about__.py b/src/cryptography/__about__.py index 92d5042e5a3d..54292526a831 100644 --- a/src/cryptography/__about__.py +++ b/src/cryptography/__about__.py @@ -5,13 +5,21 @@ from __future__ import absolute_import, division, print_function __all__ = [ - "__title__", "__summary__", "__uri__", "__version__", "__author__", - "__email__", "__license__", "__copyright__", + "__title__", + "__summary__", + "__uri__", + "__version__", + "__author__", + "__email__", + "__license__", + "__copyright__", ] __title__ = "cryptography" -__summary__ = ("cryptography is a package which provides cryptographic recipes" - " and primitives to Python developers.") +__summary__ = ( + "cryptography is a package which provides cryptographic recipes" + " and primitives to Python developers." +) __uri__ = "https://github.com/pyca/cryptography" __version__ = "3.0.dev1" diff --git a/src/cryptography/__init__.py b/src/cryptography/__init__.py index bd2a8102f9a9..b666506386b1 100644 --- a/src/cryptography/__init__.py +++ b/src/cryptography/__init__.py @@ -8,15 +8,27 @@ import warnings from cryptography.__about__ import ( - __author__, __copyright__, __email__, __license__, __summary__, __title__, - __uri__, __version__ + __author__, + __copyright__, + __email__, + __license__, + __summary__, + __title__, + __uri__, + __version__, ) from cryptography.utils import CryptographyDeprecationWarning __all__ = [ - "__title__", "__summary__", "__uri__", "__version__", "__author__", - "__email__", "__license__", "__copyright__", + "__title__", + "__summary__", + "__uri__", + "__version__", + "__author__", + "__email__", + "__license__", + "__copyright__", ] if sys.version_info[0] == 2: @@ -24,5 +36,5 @@ "Python 2 is no longer supported by the Python core team. Support for " "it is now deprecated in cryptography, and will be removed in a " "future release.", - CryptographyDeprecationWarning + CryptographyDeprecationWarning, ) diff --git a/src/cryptography/fernet.py b/src/cryptography/fernet.py index 8528d85a91a5..b5641965913e 100644 --- a/src/cryptography/fernet.py +++ b/src/cryptography/fernet.py @@ -102,7 +102,7 @@ def _get_unverified_token_data(token): raise InvalidToken try: - timestamp, = struct.unpack(">Q", data[1:9]) + (timestamp,) = struct.unpack(">Q", data[1:9]) except struct.error: raise InvalidToken return timestamp, data diff --git a/src/cryptography/hazmat/_der.py b/src/cryptography/hazmat/_der.py index 51518d641ff5..462b911b4532 100644 --- a/src/cryptography/hazmat/_der.py +++ b/src/cryptography/hazmat/_der.py @@ -68,7 +68,7 @@ def read_any_element(self): tag = self.read_byte() # Tag numbers 31 or higher are stored in multiple bytes. No supported # ASN.1 types use such tags, so reject these. - if tag & 0x1f == 0x1f: + if tag & 0x1F == 0x1F: raise ValueError("Invalid DER input: unexpected high tag number") length_byte = self.read_byte() if length_byte & 0x80 == 0: @@ -77,7 +77,7 @@ def read_any_element(self): else: # If the high bit is set, the first length byte encodes the length # of the length. - length_byte &= 0x7f + length_byte &= 0x7F if length_byte == 0: raise ValueError( "Invalid DER input: indefinite length form is not allowed " diff --git a/src/cryptography/hazmat/_oid.py b/src/cryptography/hazmat/_oid.py index f98912f96285..de2771a7379a 100644 --- a/src/cryptography/hazmat/_oid.py +++ b/src/cryptography/hazmat/_oid.py @@ -22,28 +22,33 @@ def __init__(self, dotted_string): node_value = int(node, 10) except ValueError: raise ValueError( - "Malformed OID: %s (non-integer nodes)" % ( - self._dotted_string)) + "Malformed OID: %s (non-integer nodes)" + % (self._dotted_string) + ) if node_value < 0: raise ValueError( - "Malformed OID: %s (negative-integer nodes)" % ( - self._dotted_string)) + "Malformed OID: %s (negative-integer nodes)" + % (self._dotted_string) + ) intnodes.append(node_value) if len(nodes) < 2: raise ValueError( - "Malformed OID: %s (insufficient number of nodes)" % ( - self._dotted_string)) + "Malformed OID: %s (insufficient number of nodes)" + % (self._dotted_string) + ) if intnodes[0] > 2: raise ValueError( - "Malformed OID: %s (first node outside valid range)" % ( - self._dotted_string)) + "Malformed OID: %s (first node outside valid range)" + % (self._dotted_string) + ) if intnodes[0] < 2 and intnodes[1] >= 40: raise ValueError( - "Malformed OID: %s (second node outside valid range)" % ( - self._dotted_string)) + "Malformed OID: %s (second node outside valid range)" + % (self._dotted_string) + ) def __eq__(self, other): if not isinstance(other, ObjectIdentifier): @@ -56,8 +61,7 @@ def __ne__(self, other): def __repr__(self): return "".format( - self.dotted_string, - self._name + self.dotted_string, self._name ) def __hash__(self): @@ -67,6 +71,7 @@ def __hash__(self): def _name(self): # Lazy import to avoid an import cycle from cryptography.x509.oid import _OID_NAMES + return _OID_NAMES.get(self, "Unknown OID") dotted_string = utils.read_only_property("_dotted_string") diff --git a/src/cryptography/hazmat/backends/__init__.py b/src/cryptography/hazmat/backends/__init__.py index 565bde788bab..50af41a8c598 100644 --- a/src/cryptography/hazmat/backends/__init__.py +++ b/src/cryptography/hazmat/backends/__init__.py @@ -13,6 +13,7 @@ def default_backend(): if _default_backend is None: from cryptography.hazmat.backends.openssl.backend import backend + _default_backend = backend return _default_backend diff --git a/src/cryptography/hazmat/backends/interfaces.py b/src/cryptography/hazmat/backends/interfaces.py index 20f4164ea850..418980a34e0d 100644 --- a/src/cryptography/hazmat/backends/interfaces.py +++ b/src/cryptography/hazmat/backends/interfaces.py @@ -86,8 +86,9 @@ def pbkdf2_hmac_supported(self, algorithm): """ @abc.abstractmethod - def derive_pbkdf2_hmac(self, algorithm, length, salt, iterations, - key_material): + def derive_pbkdf2_hmac( + self, algorithm, length, salt, iterations, key_material + ): """ Return length bytes derived from provided PBKDF2 parameters. """ diff --git a/src/cryptography/hazmat/backends/openssl/aead.py b/src/cryptography/hazmat/backends/openssl/aead.py index 0cad15ccd7cc..4494916852ae 100644 --- a/src/cryptography/hazmat/backends/openssl/aead.py +++ b/src/cryptography/hazmat/backends/openssl/aead.py @@ -13,8 +13,11 @@ def _aead_cipher_name(cipher): from cryptography.hazmat.primitives.ciphers.aead import ( - AESCCM, AESGCM, ChaCha20Poly1305 + AESCCM, + AESGCM, + ChaCha20Poly1305, ) + if isinstance(cipher, ChaCha20Poly1305): return b"chacha20-poly1305" elif isinstance(cipher, AESCCM): @@ -30,18 +33,21 @@ def _aead_setup(backend, cipher_name, key, nonce, tag, tag_len, operation): ctx = backend._lib.EVP_CIPHER_CTX_new() ctx = backend._ffi.gc(ctx, backend._lib.EVP_CIPHER_CTX_free) res = backend._lib.EVP_CipherInit_ex( - ctx, evp_cipher, + ctx, + evp_cipher, backend._ffi.NULL, backend._ffi.NULL, backend._ffi.NULL, - int(operation == _ENCRYPT) + int(operation == _ENCRYPT), ) backend.openssl_assert(res != 0) res = backend._lib.EVP_CIPHER_CTX_set_key_length(ctx, len(key)) backend.openssl_assert(res != 0) res = backend._lib.EVP_CIPHER_CTX_ctrl( - ctx, backend._lib.EVP_CTRL_AEAD_SET_IVLEN, len(nonce), - backend._ffi.NULL + ctx, + backend._lib.EVP_CTRL_AEAD_SET_IVLEN, + len(nonce), + backend._ffi.NULL, ) backend.openssl_assert(res != 0) if operation == _DECRYPT: @@ -63,7 +69,7 @@ def _aead_setup(backend, cipher_name, key, nonce, tag, tag_len, operation): backend._ffi.NULL, key_ptr, nonce_ptr, - int(operation == _ENCRYPT) + int(operation == _ENCRYPT), ) backend.openssl_assert(res != 0) return ctx @@ -72,11 +78,7 @@ def _aead_setup(backend, cipher_name, key, nonce, tag, tag_len, operation): def _set_length(backend, ctx, data_len): intptr = backend._ffi.new("int *") res = backend._lib.EVP_CipherUpdate( - ctx, - backend._ffi.NULL, - intptr, - backend._ffi.NULL, - data_len + ctx, backend._ffi.NULL, intptr, backend._ffi.NULL, data_len ) backend.openssl_assert(res != 0) @@ -99,6 +101,7 @@ def _process_data(backend, ctx, data): def _encrypt(backend, cipher, nonce, data, associated_data, tag_length): from cryptography.hazmat.primitives.ciphers.aead import AESCCM + cipher_name = _aead_cipher_name(cipher) ctx = _aead_setup( backend, cipher_name, cipher._key, nonce, None, tag_length, _ENCRYPT @@ -126,6 +129,7 @@ def _encrypt(backend, cipher, nonce, data, associated_data, tag_length): def _decrypt(backend, cipher, nonce, data, associated_data, tag_length): from cryptography.hazmat.primitives.ciphers.aead import AESCCM + if len(data) < tag_length: raise InvalidTag tag = data[-tag_length:] diff --git a/src/cryptography/hazmat/backends/openssl/backend.py b/src/cryptography/hazmat/backends/openssl/backend.py index 0daea2d27468..a98d3e26f5b9 100644 --- a/src/cryptography/hazmat/backends/openssl/backend.py +++ b/src/cryptography/hazmat/backends/openssl/backend.py @@ -16,75 +16,131 @@ from cryptography import utils, x509 from cryptography.exceptions import UnsupportedAlgorithm, _Reasons from cryptography.hazmat._der import ( - INTEGER, NULL, SEQUENCE, encode_der, encode_der_integer + INTEGER, + NULL, + SEQUENCE, + encode_der, + encode_der_integer, ) from cryptography.hazmat.backends.interfaces import ( - CMACBackend, CipherBackend, DERSerializationBackend, DHBackend, DSABackend, - EllipticCurveBackend, HMACBackend, HashBackend, PBKDF2HMACBackend, - PEMSerializationBackend, RSABackend, ScryptBackend, X509Backend + CMACBackend, + CipherBackend, + DERSerializationBackend, + DHBackend, + DSABackend, + EllipticCurveBackend, + HMACBackend, + HashBackend, + PBKDF2HMACBackend, + PEMSerializationBackend, + RSABackend, + ScryptBackend, + X509Backend, ) from cryptography.hazmat.backends.openssl import aead from cryptography.hazmat.backends.openssl.ciphers import _CipherContext from cryptography.hazmat.backends.openssl.cmac import _CMACContext from cryptography.hazmat.backends.openssl.decode_asn1 import ( - _CRL_ENTRY_REASON_ENUM_TO_CODE + _CRL_ENTRY_REASON_ENUM_TO_CODE, ) from cryptography.hazmat.backends.openssl.dh import ( - _DHParameters, _DHPrivateKey, _DHPublicKey, _dh_params_dup + _DHParameters, + _DHPrivateKey, + _DHPublicKey, + _dh_params_dup, ) from cryptography.hazmat.backends.openssl.dsa import ( - _DSAParameters, _DSAPrivateKey, _DSAPublicKey + _DSAParameters, + _DSAPrivateKey, + _DSAPublicKey, ) from cryptography.hazmat.backends.openssl.ec import ( - _EllipticCurvePrivateKey, _EllipticCurvePublicKey + _EllipticCurvePrivateKey, + _EllipticCurvePublicKey, ) from cryptography.hazmat.backends.openssl.ed25519 import ( - _Ed25519PrivateKey, _Ed25519PublicKey + _Ed25519PrivateKey, + _Ed25519PublicKey, ) from cryptography.hazmat.backends.openssl.ed448 import ( - _ED448_KEY_SIZE, _Ed448PrivateKey, _Ed448PublicKey + _ED448_KEY_SIZE, + _Ed448PrivateKey, + _Ed448PublicKey, ) from cryptography.hazmat.backends.openssl.encode_asn1 import ( _CRL_ENTRY_EXTENSION_ENCODE_HANDLERS, - _CRL_EXTENSION_ENCODE_HANDLERS, _EXTENSION_ENCODE_HANDLERS, + _CRL_EXTENSION_ENCODE_HANDLERS, + _EXTENSION_ENCODE_HANDLERS, _OCSP_BASICRESP_EXTENSION_ENCODE_HANDLERS, _OCSP_REQUEST_EXTENSION_ENCODE_HANDLERS, - _encode_asn1_int_gc, _encode_asn1_str_gc, _encode_name_gc, _txt2obj_gc, + _encode_asn1_int_gc, + _encode_asn1_str_gc, + _encode_name_gc, + _txt2obj_gc, ) from cryptography.hazmat.backends.openssl.hashes import _HashContext from cryptography.hazmat.backends.openssl.hmac import _HMACContext from cryptography.hazmat.backends.openssl.ocsp import ( - _OCSPRequest, _OCSPResponse + _OCSPRequest, + _OCSPResponse, ) from cryptography.hazmat.backends.openssl.poly1305 import ( - _POLY1305_KEY_SIZE, _Poly1305Context + _POLY1305_KEY_SIZE, + _Poly1305Context, ) from cryptography.hazmat.backends.openssl.rsa import ( - _RSAPrivateKey, _RSAPublicKey + _RSAPrivateKey, + _RSAPublicKey, ) from cryptography.hazmat.backends.openssl.x25519 import ( - _X25519PrivateKey, _X25519PublicKey + _X25519PrivateKey, + _X25519PublicKey, ) from cryptography.hazmat.backends.openssl.x448 import ( - _X448PrivateKey, _X448PublicKey + _X448PrivateKey, + _X448PublicKey, ) from cryptography.hazmat.backends.openssl.x509 import ( - _Certificate, _CertificateRevocationList, - _CertificateSigningRequest, _RevokedCertificate + _Certificate, + _CertificateRevocationList, + _CertificateSigningRequest, + _RevokedCertificate, ) from cryptography.hazmat.bindings.openssl import binding from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import ( - dsa, ec, ed25519, ed448, rsa + dsa, + ec, + ed25519, + ed448, + rsa, ) from cryptography.hazmat.primitives.asymmetric.padding import ( - MGF1, OAEP, PKCS1v15, PSS + MGF1, + OAEP, + PKCS1v15, + PSS, ) from cryptography.hazmat.primitives.ciphers.algorithms import ( - AES, ARC4, Blowfish, CAST5, Camellia, ChaCha20, IDEA, SEED, TripleDES + AES, + ARC4, + Blowfish, + CAST5, + Camellia, + ChaCha20, + IDEA, + SEED, + TripleDES, ) from cryptography.hazmat.primitives.ciphers.modes import ( - CBC, CFB, CFB8, CTR, ECB, GCM, OFB, XTS + CBC, + CFB, + CFB8, + CTR, + ECB, + GCM, + OFB, + XTS, ) from cryptography.hazmat.primitives.kdf import scrypt from cryptography.hazmat.primitives.serialization import ssh @@ -118,6 +174,7 @@ class Backend(object): """ OpenSSL API binding interfaces. """ + name = "openssl" # FIPS has opinions about acceptable algorithms and key sizes, but the @@ -125,16 +182,27 @@ class Backend(object): # you try to use them. To avoid that we allowlist the algorithms in # FIPS 140-3. This isn't ideal, but FIPS 140-3 is trash so here we are. _fips_aead = { - b'aes-128-ccm', b'aes-192-ccm', b'aes-256-ccm', - b'aes-128-gcm', b'aes-192-gcm', b'aes-256-gcm', + b"aes-128-ccm", + b"aes-192-ccm", + b"aes-256-ccm", + b"aes-128-gcm", + b"aes-192-gcm", + b"aes-256-gcm", } - _fips_ciphers = ( - AES, TripleDES - ) + _fips_ciphers = (AES, TripleDES) _fips_hashes = ( - hashes.SHA1, hashes.SHA224, hashes.SHA256, hashes.SHA384, - hashes.SHA512, hashes.SHA512_224, hashes.SHA512_256, hashes.SHA3_224, - hashes.SHA3_256, hashes.SHA3_384, hashes.SHA3_512, hashes.SHAKE128, + hashes.SHA1, + hashes.SHA224, + hashes.SHA256, + hashes.SHA384, + hashes.SHA512, + hashes.SHA512_224, + hashes.SHA512_256, + hashes.SHA3_224, + hashes.SHA3_256, + hashes.SHA3_384, + hashes.SHA3_512, + hashes.SHAKE128, hashes.SHAKE256, ) _fips_rsa_min_key_size = 2048 @@ -154,7 +222,7 @@ def __init__(self): if self._fips_enabled and self._lib.CRYPTOGRAPHY_NEEDS_OSRANDOM_ENGINE: warnings.warn( "OpenSSL FIPS mode is enabled. Can't enable DRBG fork safety.", - UserWarning + UserWarning, ) else: self.activate_osrandom_engine() @@ -221,11 +289,11 @@ def activate_osrandom_engine(self): def osrandom_engine_implementation(self): buf = self._ffi.new("char[]", 64) with self._get_osurandom_engine() as e: - res = self._lib.ENGINE_ctrl_cmd(e, b"get_implementation", - len(buf), buf, - self._ffi.NULL, 0) + res = self._lib.ENGINE_ctrl_cmd( + e, b"get_implementation", len(buf), buf, self._ffi.NULL, 0 + ) self.openssl_assert(res > 0) - return self._ffi.string(buf).decode('ascii') + return self._ffi.string(buf).decode("ascii") def openssl_version_text(self): """ @@ -285,8 +353,10 @@ def cipher_supported(self, cipher, mode): def register_cipher_adapter(self, cipher_cls, mode_cls, adapter): if (cipher_cls, mode_cls) in self._cipher_registry: - raise ValueError("Duplicate registration for: {} {}.".format( - cipher_cls, mode_cls) + raise ValueError( + "Duplicate registration for: {} {}.".format( + cipher_cls, mode_cls + ) ) self._cipher_registry[cipher_cls, mode_cls] = adapter @@ -295,59 +365,42 @@ def _register_default_ciphers(self): self.register_cipher_adapter( AES, mode_cls, - GetCipherByName("{cipher.name}-{cipher.key_size}-{mode.name}") + GetCipherByName("{cipher.name}-{cipher.key_size}-{mode.name}"), ) for mode_cls in [CBC, CTR, ECB, OFB, CFB]: self.register_cipher_adapter( Camellia, mode_cls, - GetCipherByName("{cipher.name}-{cipher.key_size}-{mode.name}") + GetCipherByName("{cipher.name}-{cipher.key_size}-{mode.name}"), ) for mode_cls in [CBC, CFB, CFB8, OFB]: self.register_cipher_adapter( - TripleDES, - mode_cls, - GetCipherByName("des-ede3-{mode.name}") + TripleDES, mode_cls, GetCipherByName("des-ede3-{mode.name}") ) self.register_cipher_adapter( - TripleDES, - ECB, - GetCipherByName("des-ede3") + TripleDES, ECB, GetCipherByName("des-ede3") ) for mode_cls in [CBC, CFB, OFB, ECB]: self.register_cipher_adapter( - Blowfish, - mode_cls, - GetCipherByName("bf-{mode.name}") + Blowfish, mode_cls, GetCipherByName("bf-{mode.name}") ) for mode_cls in [CBC, CFB, OFB, ECB]: self.register_cipher_adapter( - SEED, - mode_cls, - GetCipherByName("seed-{mode.name}") + SEED, mode_cls, GetCipherByName("seed-{mode.name}") ) for cipher_cls, mode_cls in itertools.product( - [CAST5, IDEA], - [CBC, OFB, CFB, ECB], + [CAST5, IDEA], [CBC, OFB, CFB, ECB], ): self.register_cipher_adapter( cipher_cls, mode_cls, - GetCipherByName("{cipher.name}-{mode.name}") + GetCipherByName("{cipher.name}-{mode.name}"), ) - self.register_cipher_adapter( - ARC4, - type(None), - GetCipherByName("rc4") - ) + self.register_cipher_adapter(ARC4, type(None), GetCipherByName("rc4")) # We don't actually support RC2, this is just used by some tests. + self.register_cipher_adapter(_RC2, type(None), GetCipherByName("rc2")) self.register_cipher_adapter( - _RC2, type(None), GetCipherByName("rc2") - ) - self.register_cipher_adapter( - ChaCha20, - type(None), - GetCipherByName("chacha20") + ChaCha20, type(None), GetCipherByName("chacha20") ) self.register_cipher_adapter(AES, XTS, _get_xts_cipher) @@ -360,8 +413,9 @@ def create_symmetric_decryption_ctx(self, cipher, mode): def pbkdf2_hmac_supported(self, algorithm): return self.hmac_supported(algorithm) - def derive_pbkdf2_hmac(self, algorithm, length, salt, iterations, - key_material): + def derive_pbkdf2_hmac( + self, algorithm, length, salt, iterations, key_material + ): buf = self._ffi.new("unsigned char[]", length) evp_md = self._evp_md_non_null_from_algorithm(algorithm) key_material_ptr = self._ffi.from_buffer(key_material) @@ -373,7 +427,7 @@ def derive_pbkdf2_hmac(self, algorithm, length, salt, iterations, iterations, evp_md, length, - buf + buf, ) self.openssl_assert(res == 1) return self._ffi.buffer(buf)[:] @@ -453,8 +507,11 @@ def generate_rsa_private_key(self, public_exponent, key_size): return _RSAPrivateKey(self, rsa_cdata, evp_pkey) def generate_rsa_parameters_supported(self, public_exponent, key_size): - return (public_exponent >= 3 and public_exponent & 1 != 0 and - key_size >= 512) + return ( + public_exponent >= 3 + and public_exponent & 1 != 0 + and key_size >= 512 + ) def load_rsa_private_numbers(self, numbers): rsa._check_private_key_components( @@ -465,7 +522,7 @@ def load_rsa_private_numbers(self, numbers): numbers.dmq1, numbers.iqmp, numbers.public_numbers.e, - numbers.public_numbers.n + numbers.public_numbers.n, ) rsa_cdata = self._lib.RSA_new() self.openssl_assert(rsa_cdata != self._ffi.NULL) @@ -523,9 +580,7 @@ def _bytes_to_bio(self, data): BIO is finished with. """ data_ptr = self._ffi.from_buffer(data) - bio = self._lib.BIO_new_mem_buf( - data_ptr, len(data) - ) + bio = self._lib.BIO_new_mem_buf(data_ptr, len(data)) self.openssl_assert(bio != self._ffi.NULL) return _MemoryBIO(self._ffi.gc(bio, self._lib.BIO_free), data_ptr) @@ -641,13 +696,14 @@ def _evp_pkey_to_public_key(self, evp_pkey): def _oaep_hash_supported(self, algorithm): if self._lib.Cryptography_HAS_RSA_OAEP_MD: return isinstance( - algorithm, ( + algorithm, + ( hashes.SHA1, hashes.SHA224, hashes.SHA256, hashes.SHA384, hashes.SHA512, - ) + ), ) else: return isinstance(algorithm, hashes.SHA1) @@ -659,11 +715,11 @@ def rsa_padding_supported(self, padding): return self.hash_supported(padding._mgf._algorithm) elif isinstance(padding, OAEP) and isinstance(padding._mgf, MGF1): return ( - self._oaep_hash_supported(padding._mgf._algorithm) and - self._oaep_hash_supported(padding._algorithm) and - ( - (padding._label is None or len(padding._label) == 0) or - self._lib.Cryptography_HAS_RSA_OAEP_LABEL == 1 + self._oaep_hash_supported(padding._mgf._algorithm) + and self._oaep_hash_supported(padding._algorithm) + and ( + (padding._label is None or len(padding._label) == 0) + or self._lib.Cryptography_HAS_RSA_OAEP_LABEL == 1 ) ) else: @@ -680,8 +736,13 @@ def generate_dsa_parameters(self, key_size): ctx = self._ffi.gc(ctx, self._lib.DSA_free) res = self._lib.DSA_generate_parameters_ex( - ctx, key_size, self._ffi.NULL, 0, - self._ffi.NULL, self._ffi.NULL, self._ffi.NULL + ctx, + key_size, + self._ffi.NULL, + 0, + self._ffi.NULL, + self._ffi.NULL, + self._ffi.NULL, ) self.openssl_assert(res == 1) @@ -778,22 +839,24 @@ def create_cmac_ctx(self, algorithm): return _CMACContext(self, algorithm) def _x509_check_signature_params(self, private_key, algorithm): - if isinstance(private_key, - (ed25519.Ed25519PrivateKey, ed448.Ed448PrivateKey)): + if isinstance( + private_key, (ed25519.Ed25519PrivateKey, ed448.Ed448PrivateKey) + ): if algorithm is not None: raise ValueError( "algorithm must be None when signing via ed25519 or ed448" ) - elif not isinstance(private_key, (rsa.RSAPrivateKey, dsa.DSAPrivateKey, - ec.EllipticCurvePrivateKey)): + elif not isinstance( + private_key, + (rsa.RSAPrivateKey, dsa.DSAPrivateKey, ec.EllipticCurvePrivateKey), + ): raise TypeError( "Key must be an rsa, dsa, ec, ed25519, or ed448 private key." ) elif not isinstance(algorithm, hashes.HashAlgorithm): raise TypeError("Algorithm must be a registered hash algorithm.") - elif ( - isinstance(algorithm, hashes.MD5) and not - isinstance(private_key, rsa.RSAPrivateKey) + elif isinstance(algorithm, hashes.MD5) and not isinstance( + private_key, rsa.RSAPrivateKey ): raise ValueError( "MD5 hash algorithm is only supported with RSA keys" @@ -801,7 +864,7 @@ def _x509_check_signature_params(self, private_key, algorithm): def create_x509_csr(self, builder, private_key, algorithm): if not isinstance(builder, x509.CertificateSigningRequestBuilder): - raise TypeError('Builder type mismatch.') + raise TypeError("Builder type mismatch.") self._x509_check_signature_params(private_key, algorithm) # Resolve the signature algorithm. @@ -824,9 +887,7 @@ def create_x509_csr(self, builder, private_key, algorithm): # Set subject public key. public_key = private_key.public_key() - res = self._lib.X509_REQ_set_pubkey( - x509_req, public_key._evp_pkey - ) + res = self._lib.X509_REQ_set_pubkey(x509_req, public_key._evp_pkey) self.openssl_assert(res == 1) # Add extensions. @@ -835,10 +896,11 @@ def create_x509_csr(self, builder, private_key, algorithm): sk_extension = self._ffi.gc( sk_extension, lambda x: self._lib.sk_X509_EXTENSION_pop_free( - x, self._ffi.addressof( + x, + self._ffi.addressof( self._lib._original_lib, "X509_EXTENSION_free" - ) - ) + ), + ), ) # Don't GC individual extensions because the memory is owned by # sk_extensions and will be freed along with it. @@ -847,7 +909,7 @@ def create_x509_csr(self, builder, private_key, algorithm): handlers=_EXTENSION_ENCODE_HANDLERS, x509_obj=sk_extension, add_func=self._lib.sk_X509_EXTENSION_insert, - gc=False + gc=False, ) res = self._lib.X509_REQ_add_extensions(x509_req, sk_extension) self.openssl_assert(res == 1) @@ -856,20 +918,22 @@ def create_x509_csr(self, builder, private_key, algorithm): for attr_oid, attr_val in builder._attributes: obj = _txt2obj_gc(self, attr_oid.dotted_string) res = self._lib.X509_REQ_add1_attr_by_OBJ( - x509_req, obj, x509.name._ASN1Type.UTF8String.value, - attr_val, len(attr_val)) + x509_req, + obj, + x509.name._ASN1Type.UTF8String.value, + attr_val, + len(attr_val), + ) self.openssl_assert(res == 1) # Sign the request using the requester's private key. - res = self._lib.X509_REQ_sign( - x509_req, private_key._evp_pkey, evp_md - ) + res = self._lib.X509_REQ_sign(x509_req, private_key._evp_pkey, evp_md) if res == 0: errors = self._consume_errors() self.openssl_assert( errors[0]._lib_reason_match( self._lib.ERR_LIB_RSA, - self._lib.RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY + self._lib.RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY, ) ) @@ -879,7 +943,7 @@ def create_x509_csr(self, builder, private_key, algorithm): def create_x509_certificate(self, builder, private_key, algorithm): if not isinstance(builder, x509.CertificateBuilder): - raise TypeError('Builder type mismatch.') + raise TypeError("Builder type mismatch.") self._x509_check_signature_params(private_key, algorithm) # Resolve the signature algorithm. @@ -926,7 +990,7 @@ def create_x509_certificate(self, builder, private_key, algorithm): handlers=_EXTENSION_ENCODE_HANDLERS, x509_obj=x509_cert, add_func=self._lib.X509_add_ext, - gc=True + gc=True, ) # Set the issuer name. @@ -936,15 +1000,13 @@ def create_x509_certificate(self, builder, private_key, algorithm): self.openssl_assert(res == 1) # Sign the certificate with the issuer's private key. - res = self._lib.X509_sign( - x509_cert, private_key._evp_pkey, evp_md - ) + res = self._lib.X509_sign(x509_cert, private_key._evp_pkey, evp_md) if res == 0: errors = self._consume_errors() self.openssl_assert( errors[0]._lib_reason_match( self._lib.ERR_LIB_RSA, - self._lib.RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY + self._lib.RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY, ) ) raise ValueError("Digest too big for RSA key") @@ -952,8 +1014,9 @@ def create_x509_certificate(self, builder, private_key, algorithm): return _Certificate(self, x509_cert) def _evp_md_x509_null_if_eddsa(self, private_key, algorithm): - if isinstance(private_key, - (ed25519.Ed25519PrivateKey, ed448.Ed448PrivateKey)): + if isinstance( + private_key, (ed25519.Ed25519PrivateKey, ed448.Ed448PrivateKey) + ): # OpenSSL requires us to pass NULL for EVP_MD for ed25519/ed448 return self._ffi.NULL else: @@ -961,9 +1024,9 @@ def _evp_md_x509_null_if_eddsa(self, private_key, algorithm): def _set_asn1_time(self, asn1_time, time): if time.year >= 2050: - asn1_str = time.strftime('%Y%m%d%H%M%SZ').encode('ascii') + asn1_str = time.strftime("%Y%m%d%H%M%SZ").encode("ascii") else: - asn1_str = time.strftime('%y%m%d%H%M%SZ').encode('ascii') + asn1_str = time.strftime("%y%m%d%H%M%SZ").encode("ascii") res = self._lib.ASN1_TIME_set_string(asn1_time, asn1_str) self.openssl_assert(res == 1) @@ -976,7 +1039,7 @@ def _create_asn1_time(self, time): def create_x509_crl(self, builder, private_key, algorithm): if not isinstance(builder, x509.CertificateRevocationListBuilder): - raise TypeError('Builder type mismatch.') + raise TypeError("Builder type mismatch.") self._x509_check_signature_params(private_key, algorithm) evp_md = self._evp_md_x509_null_if_eddsa(private_key, algorithm) @@ -1011,7 +1074,7 @@ def create_x509_crl(self, builder, private_key, algorithm): handlers=_CRL_EXTENSION_ENCODE_HANDLERS, x509_obj=x509_crl, add_func=self._lib.X509_CRL_add_ext, - gc=True + gc=True, ) # add revoked certificates @@ -1023,27 +1086,24 @@ def create_x509_crl(self, builder, private_key, algorithm): res = self._lib.X509_CRL_add0_revoked(x509_crl, revoked) self.openssl_assert(res == 1) - res = self._lib.X509_CRL_sign( - x509_crl, private_key._evp_pkey, evp_md - ) + res = self._lib.X509_CRL_sign(x509_crl, private_key._evp_pkey, evp_md) if res == 0: errors = self._consume_errors() self.openssl_assert( errors[0]._lib_reason_match( self._lib.ERR_LIB_RSA, - self._lib.RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY + self._lib.RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY, ) ) raise ValueError("Digest too big for RSA key") return _CertificateRevocationList(self, x509_crl) - def _create_x509_extensions(self, extensions, handlers, x509_obj, - add_func, gc): + def _create_x509_extensions( + self, extensions, handlers, x509_obj, add_func, gc + ): for i, extension in enumerate(extensions): - x509_extension = self._create_x509_extension( - handlers, extension - ) + x509_extension = self._create_x509_extension(handlers, extension) self.openssl_assert(x509_extension != self._ffi.NULL) if gc: @@ -1081,7 +1141,7 @@ def _create_x509_extension(self, handlers, extension): encode = handlers[extension.oid] except KeyError: raise NotImplementedError( - 'Extension not supported: {}'.format(extension.oid) + "Extension not supported: {}".format(extension.oid) ) ext_struct = encode(self, extension.value) @@ -1095,7 +1155,7 @@ def _create_x509_extension(self, handlers, extension): def create_x509_revoked_certificate(self, builder): if not isinstance(builder, x509.RevokedCertificateBuilder): - raise TypeError('Builder type mismatch.') + raise TypeError("Builder type mismatch.") x509_revoked = self._lib.X509_REVOKED_new() self.openssl_assert(x509_revoked != self._ffi.NULL) @@ -1114,7 +1174,7 @@ def create_x509_revoked_certificate(self, builder): handlers=_CRL_ENTRY_EXTENSION_ENCODE_HANDLERS, x509_obj=x509_revoked, add_func=self._lib.X509_REVOKED_add_ext, - gc=True + gc=True, ) return _RevokedCertificate(self, None, x509_revoked) @@ -1155,7 +1215,8 @@ def load_pem_parameters(self, data): mem_bio = self._bytes_to_bio(data) # only DH is supported currently dh_cdata = self._lib.PEM_read_bio_DHparams( - mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL) + mem_bio.bio, self._ffi.NULL, self._ffi.NULL, self._ffi.NULL + ) if dh_cdata != self._ffi.NULL: dh_cdata = self._ffi.gc(dh_cdata, self._lib.DH_free) return _DHParameters(self, dh_cdata) @@ -1220,9 +1281,7 @@ def load_der_public_key(self, data): def load_der_parameters(self, data): mem_bio = self._bytes_to_bio(data) - dh_cdata = self._lib.d2i_DHparams_bio( - mem_bio.bio, self._ffi.NULL - ) + dh_cdata = self._lib.d2i_DHparams_bio(mem_bio.bio, self._ffi.NULL) if dh_cdata != self._ffi.NULL: dh_cdata = self._ffi.gc(dh_cdata, self._lib.DH_free) return _DHParameters(self, dh_cdata) @@ -1355,12 +1414,12 @@ def _load_key(self, openssl_read_func, convert_func, data, password): if password is not None and userdata.called == 0: raise TypeError( - "Password was given but private key is not encrypted.") + "Password was given but private key is not encrypted." + ) assert ( - (password is not None and userdata.called == 1) or - password is None - ) + password is not None and userdata.called == 1 + ) or password is None return convert_func(evp_pkey) @@ -1370,32 +1429,28 @@ def _handle_key_loading_error(self): if not errors: raise ValueError("Could not deserialize key data.") - elif ( - errors[0]._lib_reason_match( - self._lib.ERR_LIB_EVP, self._lib.EVP_R_BAD_DECRYPT - ) or errors[0]._lib_reason_match( - self._lib.ERR_LIB_PKCS12, - self._lib.PKCS12_R_PKCS12_CIPHERFINAL_ERROR - ) + elif errors[0]._lib_reason_match( + self._lib.ERR_LIB_EVP, self._lib.EVP_R_BAD_DECRYPT + ) or errors[0]._lib_reason_match( + self._lib.ERR_LIB_PKCS12, + self._lib.PKCS12_R_PKCS12_CIPHERFINAL_ERROR, ): raise ValueError("Bad decrypt. Incorrect password?") - elif ( - errors[0]._lib_reason_match( - self._lib.ERR_LIB_EVP, self._lib.EVP_R_UNKNOWN_PBE_ALGORITHM - ) or errors[0]._lib_reason_match( - self._lib.ERR_LIB_PEM, self._lib.PEM_R_UNSUPPORTED_ENCRYPTION - ) + elif errors[0]._lib_reason_match( + self._lib.ERR_LIB_EVP, self._lib.EVP_R_UNKNOWN_PBE_ALGORITHM + ) or errors[0]._lib_reason_match( + self._lib.ERR_LIB_PEM, self._lib.PEM_R_UNSUPPORTED_ENCRYPTION ): raise UnsupportedAlgorithm( "PEM data is encrypted with an unsupported cipher", - _Reasons.UNSUPPORTED_CIPHER + _Reasons.UNSUPPORTED_CIPHER, ) elif any( error._lib_reason_match( self._lib.ERR_LIB_EVP, - self._lib.EVP_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM + self._lib.EVP_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM, ) for error in errors ): @@ -1420,15 +1475,14 @@ def elliptic_curve_supported(self, curve): if group == self._ffi.NULL: errors = self._consume_errors() self.openssl_assert( - curve_nid == self._lib.NID_undef or - errors[0]._lib_reason_match( - self._lib.ERR_LIB_EC, - self._lib.EC_R_UNKNOWN_GROUP - ) or + curve_nid == self._lib.NID_undef + or errors[0]._lib_reason_match( + self._lib.ERR_LIB_EC, self._lib.EC_R_UNKNOWN_GROUP + ) + or # This occurs in FIPS mode for unsupported curves on RHEL errors[0]._lib_reason_match( - self._lib.ERR_LIB_EC, - self._lib.EC_R_NOT_A_NIST_PRIME + self._lib.ERR_LIB_EC, self._lib.EC_R_NOT_A_NIST_PRIME ) ) return False @@ -1463,7 +1517,7 @@ def generate_elliptic_curve_private_key(self, curve): else: raise UnsupportedAlgorithm( "Backend object does not support {}.".format(curve.name), - _Reasons.UNSUPPORTED_ELLIPTIC_CURVE + _Reasons.UNSUPPORTED_ELLIPTIC_CURVE, ) def load_elliptic_curve_private_numbers(self, numbers): @@ -1478,7 +1532,8 @@ def load_elliptic_curve_private_numbers(self, numbers): self.openssl_assert(res == 1) ec_cdata = self._ec_key_set_public_key_affine_coordinates( - ec_cdata, public.x, public.y) + ec_cdata, public.x, public.y + ) evp_pkey = self._ec_cdata_to_evp_pkey(ec_cdata) @@ -1487,7 +1542,8 @@ def load_elliptic_curve_private_numbers(self, numbers): def load_elliptic_curve_public_numbers(self, numbers): ec_cdata = self._ec_key_new_by_curve(numbers.curve) ec_cdata = self._ec_key_set_public_key_affine_coordinates( - ec_cdata, numbers.x, numbers.y) + ec_cdata, numbers.x, numbers.y + ) evp_pkey = self._ec_cdata_to_evp_pkey(ec_cdata) return _EllipticCurvePublicKey(self, ec_cdata, evp_pkey) @@ -1525,8 +1581,9 @@ def derive_elliptic_curve_private_key(self, private_value, curve): value = self._ffi.gc(value, self._lib.BN_clear_free) with self._tmp_bn_ctx() as bn_ctx: - res = self._lib.EC_POINT_mul(group, point, value, self._ffi.NULL, - self._ffi.NULL, bn_ctx) + res = self._lib.EC_POINT_mul( + group, point, value, self._ffi.NULL, self._ffi.NULL, bn_ctx + ) self.openssl_assert(res == 1) bn_x = self._lib.BN_CTX_get(bn_ctx) @@ -1578,9 +1635,7 @@ def create_ocsp_request(self, builder): ocsp_req = self._ffi.gc(ocsp_req, self._lib.OCSP_REQUEST_free) cert, issuer, algorithm = builder._request evp_md = self._evp_md_non_null_from_algorithm(algorithm) - certid = self._lib.OCSP_cert_to_id( - evp_md, cert._x509, issuer._x509 - ) + certid = self._lib.OCSP_cert_to_id(evp_md, cert._x509, issuer._x509) self.openssl_assert(certid != self._ffi.NULL) onereq = self._lib.OCSP_request_add0_id(ocsp_req, certid) self.openssl_assert(onereq != self._ffi.NULL) @@ -1603,8 +1658,9 @@ def _create_ocsp_basic_response(self, builder, private_key, algorithm): builder._response._algorithm ) certid = self._lib.OCSP_cert_to_id( - evp_md, builder._response._cert._x509, - builder._response._issuer._x509 + evp_md, + builder._response._cert._x509, + builder._response._issuer._x509, ) self.openssl_assert(certid != self._ffi.NULL) certid = self._ffi.gc(certid, self._lib.OCSP_CERTID_free) @@ -1636,7 +1692,7 @@ def _create_ocsp_basic_response(self, builder, private_key, algorithm): reason, rev_time, this_update, - next_update + next_update, ) self.openssl_assert(res != self._ffi.NULL) # okay, now sign the basic structure @@ -1660,23 +1716,28 @@ def _create_ocsp_basic_response(self, builder, private_key, algorithm): ) res = self._lib.OCSP_basic_sign( - basic, responder_cert._x509, private_key._evp_pkey, - evp_md, self._ffi.NULL, flags + basic, + responder_cert._x509, + private_key._evp_pkey, + evp_md, + self._ffi.NULL, + flags, ) if res != 1: errors = self._consume_errors() self.openssl_assert( errors[0]._lib_reason_match( self._lib.ERR_LIB_X509, - self._lib.X509_R_KEY_VALUES_MISMATCH + self._lib.X509_R_KEY_VALUES_MISMATCH, ) ) raise ValueError("responder_cert must be signed by private_key") return basic - def create_ocsp_response(self, response_status, builder, private_key, - algorithm): + def create_ocsp_response( + self, response_status, builder, private_key, algorithm + ): if response_status is ocsp.OCSPResponseStatus.SUCCESSFUL: basic = self._create_ocsp_basic_response( builder, private_key, algorithm @@ -1692,9 +1753,8 @@ def create_ocsp_response(self, response_status, builder, private_key, return _OCSPResponse(self, ocsp_resp) def elliptic_curve_exchange_algorithm_supported(self, algorithm, curve): - return ( - self.elliptic_curve_supported(curve) and - isinstance(algorithm, ec.ECDH) + return self.elliptic_curve_supported(curve) and isinstance( + algorithm, ec.ECDH ) def _ec_cdata_to_evp_pkey(self, ec_cdata): @@ -1708,10 +1768,7 @@ def _elliptic_curve_to_nid(self, curve): Get the NID for a curve name. """ - curve_aliases = { - "secp192r1": "prime192v1", - "secp256r1": "prime256v1" - } + curve_aliases = {"secp192r1": "prime192v1", "secp256r1": "prime256v1"} curve_name = curve_aliases.get(curve.name, curve.name) @@ -1719,7 +1776,7 @@ def _elliptic_curve_to_nid(self, curve): if curve_nid == self._lib.NID_undef: raise UnsupportedAlgorithm( "{} is not a supported elliptic curve".format(curve.name), - _Reasons.UNSUPPORTED_ELLIPTIC_CURVE + _Reasons.UNSUPPORTED_ELLIPTIC_CURVE, ) return curve_nid @@ -1782,8 +1839,9 @@ def _ec_key_set_public_key_affine_coordinates(self, ctx, x, y): return ctx - def _private_key_bytes(self, encoding, format, encryption_algorithm, - key, evp_pkey, cdata): + def _private_key_bytes( + self, encoding, format, encryption_algorithm, key, evp_pkey, cdata + ): # validate argument types if not isinstance(encoding, serialization.Encoding): raise TypeError("encoding must be an item from the Encoding enum") @@ -1791,8 +1849,9 @@ def _private_key_bytes(self, encoding, format, encryption_algorithm, raise TypeError( "format must be an item from the PrivateFormat enum" ) - if not isinstance(encryption_algorithm, - serialization.KeySerializationEncryption): + if not isinstance( + encryption_algorithm, serialization.KeySerializationEncryption + ): raise TypeError( "Encryption algorithm must be a KeySerializationEncryption " "instance" @@ -1801,8 +1860,9 @@ def _private_key_bytes(self, encoding, format, encryption_algorithm, # validate password if isinstance(encryption_algorithm, serialization.NoEncryption): password = b"" - elif isinstance(encryption_algorithm, - serialization.BestAvailableEncryption): + elif isinstance( + encryption_algorithm, serialization.BestAvailableEncryption + ): password = encryption_algorithm.password if len(password) > 1023: raise ValueError( @@ -1826,11 +1886,8 @@ def _private_key_bytes(self, encoding, format, encryption_algorithm, # TraditionalOpenSSL + PEM/DER if format is serialization.PrivateFormat.TraditionalOpenSSL: - if ( - self._fips_enabled and - not isinstance( - encryption_algorithm, serialization.NoEncryption - ) + if self._fips_enabled and not isinstance( + encryption_algorithm, serialization.NoEncryption ): raise ValueError( "Encrypted traditional OpenSSL format is not " @@ -1871,9 +1928,7 @@ def _private_key_bytes(self, encoding, format, encryption_algorithm, ) return self._bio_func_output(write_bio, cdata) - raise ValueError( - "Unsupported encoding for TraditionalOpenSSL" - ) + raise ValueError("Unsupported encoding for TraditionalOpenSSL") # OpenSSH + PEM if format is serialization.PrivateFormat.OpenSSH: @@ -1903,7 +1958,7 @@ def _private_key_bytes_via_bio(self, write_bio, evp_pkey, password): password, len(password), self._ffi.NULL, - self._ffi.NULL + self._ffi.NULL, ) def _bio_func_output(self, write_bio, *args): @@ -1944,9 +1999,7 @@ def _public_key_bytes(self, encoding, format, key, evp_pkey, cdata): elif encoding is serialization.Encoding.DER: write_bio = self._lib.i2d_RSAPublicKey_bio else: - raise ValueError( - "PKCS1 works only with PEM or DER encoding" - ) + raise ValueError("PKCS1 works only with PEM or DER encoding") return self._bio_func_output(write_bio, cdata) # OpenSSH + OpenSSH @@ -1964,16 +2017,11 @@ def _public_key_bytes(self, encoding, format, key, evp_pkey, cdata): def _parameter_bytes(self, encoding, format, cdata): if encoding is serialization.Encoding.OpenSSH: - raise TypeError( - "OpenSSH encoding is not supported" - ) + raise TypeError("OpenSSH encoding is not supported") # Only DH is supported here currently. q = self._ffi.new("BIGNUM **") - self._lib.DH_get0_pqg(cdata, - self._ffi.NULL, - q, - self._ffi.NULL) + self._lib.DH_get0_pqg(cdata, self._ffi.NULL, q, self._ffi.NULL) if encoding is serialization.Encoding.PEM: if q[0] != self._ffi.NULL: write_bio = self._lib.PEM_write_bio_DHxparams @@ -2004,10 +2052,7 @@ def generate_dh_parameters(self, generator, key_size): dh_param_cdata = self._ffi.gc(dh_param_cdata, self._lib.DH_free) res = self._lib.DH_generate_parameters_ex( - dh_param_cdata, - key_size, - generator, - self._ffi.NULL + dh_param_cdata, key_size, generator, self._ffi.NULL ) self.openssl_assert(res == 1) @@ -2031,7 +2076,8 @@ def generate_dh_private_key(self, parameters): def generate_dh_private_key_and_parameters(self, generator, key_size): return self.generate_dh_private_key( - self.generate_dh_parameters(generator, key_size)) + self.generate_dh_parameters(generator, key_size) + ) def load_dh_private_numbers(self, numbers): parameter_numbers = numbers.public_numbers.parameter_numbers @@ -2070,12 +2116,10 @@ def load_dh_private_numbers(self, numbers): # the key to the attacker in exchange for having the full key space # available. See: https://crypto.stackexchange.com/questions/12961 if codes[0] != 0 and not ( - parameter_numbers.g == 2 and - codes[0] ^ self._lib.DH_NOT_SUITABLE_GENERATOR == 0 + parameter_numbers.g == 2 + and codes[0] ^ self._lib.DH_NOT_SUITABLE_GENERATOR == 0 ): - raise ValueError( - "DH private numbers did not pass safety checks." - ) + raise ValueError("DH private numbers did not pass safety checks.") evp_pkey = self._dh_cdata_to_evp_pkey(dh_cdata) @@ -2342,8 +2386,16 @@ def derive_scrypt(self, key_material, salt, length, n, r, p): buf = self._ffi.new("unsigned char[]", length) key_material_ptr = self._ffi.from_buffer(key_material) res = self._lib.EVP_PBE_scrypt( - key_material_ptr, len(key_material), salt, len(salt), n, r, p, - scrypt._MEM_LIMIT, buf, length + key_material_ptr, + len(key_material), + salt, + len(salt), + n, + r, + p, + scrypt._MEM_LIMIT, + buf, + length, ) if res != 1: errors = self._consume_errors() @@ -2351,18 +2403,17 @@ def derive_scrypt(self, key_material, salt, length, n, r, p): # This error is only added to the stack in 1.1.1+ self.openssl_assert( errors[0]._lib_reason_match( + self._lib.ERR_LIB_EVP, self._lib.ERR_R_MALLOC_FAILURE + ) + or errors[0]._lib_reason_match( self._lib.ERR_LIB_EVP, - self._lib.ERR_R_MALLOC_FAILURE - ) or - errors[0]._lib_reason_match( - self._lib.ERR_LIB_EVP, - self._lib.EVP_R_MEMORY_LIMIT_EXCEEDED + self._lib.EVP_R_MEMORY_LIMIT_EXCEEDED, ) ) # memory required formula explained here: # https://blog.filippo.io/the-scrypt-parameters/ - min_memory = 128 * n * r // (1024**2) + min_memory = 128 * n * r // (1024 ** 2) raise MemoryError( "Not enough memory to derive key. These parameters require" " {} MB of memory.".format(min_memory) @@ -2373,9 +2424,7 @@ def aead_cipher_supported(self, cipher): cipher_name = aead._aead_cipher_name(cipher) if self._fips_enabled and cipher_name not in self._fips_aead: return False - return ( - self._lib.EVP_get_cipherbyname(cipher_name) != self._ffi.NULL - ) + return self._lib.EVP_get_cipherbyname(cipher_name) != self._ffi.NULL @contextlib.contextmanager def _zeroed_bytearray(self, length): @@ -2466,8 +2515,9 @@ def load_key_and_certificates_from_pkcs12(self, data, password): return (key, cert, additional_certificates) - def serialize_key_and_certificates_to_pkcs12(self, name, key, cert, cas, - encryption_algorithm): + def serialize_key_and_certificates_to_pkcs12( + self, name, key, cert, cas, encryption_algorithm + ): password = None if name is not None: utils._check_bytes("name", name) @@ -2477,8 +2527,9 @@ def serialize_key_and_certificates_to_pkcs12(self, name, key, cert, cas, nid_key = -1 pkcs12_iter = 0 mac_iter = 0 - elif isinstance(encryption_algorithm, - serialization.BestAvailableEncryption): + elif isinstance( + encryption_algorithm, serialization.BestAvailableEncryption + ): # PKCS12 encryption is hopeless trash and can never be fixed. # This is the least terrible option. nid_cert = self._lib.NID_pbe_WithSHA1And3_Key_TripleDES_CBC @@ -2508,10 +2559,17 @@ def serialize_key_and_certificates_to_pkcs12(self, name, key, cert, cas, with self._zeroed_null_terminated_buf(password) as password_buf: with self._zeroed_null_terminated_buf(name) as name_buf: p12 = self._lib.PKCS12_create( - password_buf, name_buf, + password_buf, + name_buf, key._evp_pkey if key else self._ffi.NULL, cert._x509 if cert else self._ffi.NULL, - sk_x509, nid_key, nid_cert, pkcs12_iter, mac_iter, 0) + sk_x509, + nid_key, + nid_cert, + pkcs12_iter, + mac_iter, + 0, + ) self.openssl_assert(p12 != self._ffi.NULL) p12 = self._ffi.gc(p12, self._lib.PKCS12_free) diff --git a/src/cryptography/hazmat/backends/openssl/ciphers.py b/src/cryptography/hazmat/backends/openssl/ciphers.py index 1de814193455..8e9b58cd2a4f 100644 --- a/src/cryptography/hazmat/backends/openssl/ciphers.py +++ b/src/cryptography/hazmat/backends/openssl/ciphers.py @@ -42,8 +42,9 @@ def __init__(self, backend, cipher, mode, operation): raise UnsupportedAlgorithm( "cipher {} in {} mode is not supported " "by this backend.".format( - cipher.name, mode.name if mode else mode), - _Reasons.UNSUPPORTED_CIPHER + cipher.name, mode.name if mode else mode + ), + _Reasons.UNSUPPORTED_CIPHER, ) evp_cipher = adapter(self._backend, cipher, mode) @@ -70,11 +71,14 @@ def __init__(self, backend, cipher, mode, operation): else: iv_nonce = self._backend._ffi.NULL # begin init with cipher and operation type - res = self._backend._lib.EVP_CipherInit_ex(ctx, evp_cipher, - self._backend._ffi.NULL, - self._backend._ffi.NULL, - self._backend._ffi.NULL, - operation) + res = self._backend._lib.EVP_CipherInit_ex( + ctx, + evp_cipher, + self._backend._ffi.NULL, + self._backend._ffi.NULL, + self._backend._ffi.NULL, + operation, + ) self._backend.openssl_assert(res != 0) # set the key length to handle variable key ciphers res = self._backend._lib.EVP_CIPHER_CTX_set_key_length( @@ -83,14 +87,18 @@ def __init__(self, backend, cipher, mode, operation): self._backend.openssl_assert(res != 0) if isinstance(mode, modes.GCM): res = self._backend._lib.EVP_CIPHER_CTX_ctrl( - ctx, self._backend._lib.EVP_CTRL_AEAD_SET_IVLEN, - len(iv_nonce), self._backend._ffi.NULL + ctx, + self._backend._lib.EVP_CTRL_AEAD_SET_IVLEN, + len(iv_nonce), + self._backend._ffi.NULL, ) self._backend.openssl_assert(res != 0) if mode.tag is not None: res = self._backend._lib.EVP_CIPHER_CTX_ctrl( - ctx, self._backend._lib.EVP_CTRL_AEAD_SET_TAG, - len(mode.tag), mode.tag + ctx, + self._backend._lib.EVP_CTRL_AEAD_SET_TAG, + len(mode.tag), + mode.tag, ) self._backend.openssl_assert(res != 0) self._tag = mode.tag @@ -102,7 +110,7 @@ def __init__(self, backend, cipher, mode, operation): self._backend._ffi.NULL, self._backend._ffi.from_buffer(cipher.key), iv_nonce, - operation + operation, ) self._backend.openssl_assert(res != 0) # We purposely disable padding here as it's handled higher up in the @@ -127,17 +135,20 @@ def update_into(self, data, buf): ) outlen = self._backend._ffi.new("int *") res = self._backend._lib.EVP_CipherUpdate( - self._ctx, buf, outlen, - self._backend._ffi.from_buffer(data), len(data) + self._ctx, + buf, + outlen, + self._backend._ffi.from_buffer(data), + len(data), ) self._backend.openssl_assert(res != 0) return outlen[0] def finalize(self): if ( - self._operation == self._DECRYPT and - isinstance(self._mode, modes.ModeWithAuthenticationTag) and - self.tag is None + self._operation == self._DECRYPT + and isinstance(self._mode, modes.ModeWithAuthenticationTag) + and self.tag is None ): raise ValueError( "Authentication tag must be provided when decrypting." @@ -155,7 +166,7 @@ def finalize(self): self._backend.openssl_assert( errors[0]._lib_reason_match( self._backend._lib.ERR_LIB_EVP, - self._backend._lib.EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH + self._backend._lib.EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH, ) ) raise ValueError( @@ -163,31 +174,35 @@ def finalize(self): "the block length." ) - if (isinstance(self._mode, modes.GCM) and - self._operation == self._ENCRYPT): + if ( + isinstance(self._mode, modes.GCM) + and self._operation == self._ENCRYPT + ): tag_buf = self._backend._ffi.new( "unsigned char[]", self._block_size_bytes ) res = self._backend._lib.EVP_CIPHER_CTX_ctrl( - self._ctx, self._backend._lib.EVP_CTRL_AEAD_GET_TAG, - self._block_size_bytes, tag_buf + self._ctx, + self._backend._lib.EVP_CTRL_AEAD_GET_TAG, + self._block_size_bytes, + tag_buf, ) self._backend.openssl_assert(res != 0) self._tag = self._backend._ffi.buffer(tag_buf)[:] res = self._backend._lib.EVP_CIPHER_CTX_cleanup(self._ctx) self._backend.openssl_assert(res == 1) - return self._backend._ffi.buffer(buf)[:outlen[0]] + return self._backend._ffi.buffer(buf)[: outlen[0]] def finalize_with_tag(self, tag): if len(tag) < self._mode._min_tag_length: raise ValueError( "Authentication tag must be {} bytes or longer.".format( - self._mode._min_tag_length) + self._mode._min_tag_length + ) ) res = self._backend._lib.EVP_CIPHER_CTX_ctrl( - self._ctx, self._backend._lib.EVP_CTRL_AEAD_SET_TAG, - len(tag), tag + self._ctx, self._backend._lib.EVP_CTRL_AEAD_SET_TAG, len(tag), tag ) self._backend.openssl_assert(res != 0) self._tag = tag @@ -196,8 +211,11 @@ def finalize_with_tag(self, tag): def authenticate_additional_data(self, data): outlen = self._backend._ffi.new("int *") res = self._backend._lib.EVP_CipherUpdate( - self._ctx, self._backend._ffi.NULL, outlen, - self._backend._ffi.from_buffer(data), len(data) + self._ctx, + self._backend._ffi.NULL, + outlen, + self._backend._ffi.from_buffer(data), + len(data), ) self._backend.openssl_assert(res != 0) diff --git a/src/cryptography/hazmat/backends/openssl/cmac.py b/src/cryptography/hazmat/backends/openssl/cmac.py index d4d46f55f3cb..195fc230f2b2 100644 --- a/src/cryptography/hazmat/backends/openssl/cmac.py +++ b/src/cryptography/hazmat/backends/openssl/cmac.py @@ -7,7 +7,9 @@ from cryptography import utils from cryptography.exceptions import ( - InvalidSignature, UnsupportedAlgorithm, _Reasons + InvalidSignature, + UnsupportedAlgorithm, + _Reasons, ) from cryptography.hazmat.primitives import constant_time from cryptography.hazmat.primitives.ciphers.modes import CBC @@ -16,8 +18,10 @@ class _CMACContext(object): def __init__(self, backend, algorithm, ctx=None): if not backend.cmac_algorithm_supported(algorithm): - raise UnsupportedAlgorithm("This backend does not support CMAC.", - _Reasons.UNSUPPORTED_CIPHER) + raise UnsupportedAlgorithm( + "This backend does not support CMAC.", + _Reasons.UNSUPPORTED_CIPHER, + ) self._backend = backend self._key = algorithm.key @@ -37,8 +41,11 @@ def __init__(self, backend, algorithm, ctx=None): key_ptr = self._backend._ffi.from_buffer(self._key) res = self._backend._lib.CMAC_Init( - ctx, key_ptr, len(self._key), - evp_cipher, self._backend._ffi.NULL + ctx, + key_ptr, + len(self._key), + evp_cipher, + self._backend._ffi.NULL, ) self._backend.openssl_assert(res == 1) @@ -53,9 +60,7 @@ def update(self, data): def finalize(self): buf = self._backend._ffi.new("unsigned char[]", self._output_length) length = self._backend._ffi.new("size_t *", self._output_length) - res = self._backend._lib.CMAC_Final( - self._ctx, buf, length - ) + res = self._backend._lib.CMAC_Final(self._ctx, buf, length) self._backend.openssl_assert(res == 1) self._ctx = None @@ -67,13 +72,9 @@ def copy(self): copied_ctx = self._backend._ffi.gc( copied_ctx, self._backend._lib.CMAC_CTX_free ) - res = self._backend._lib.CMAC_CTX_copy( - copied_ctx, self._ctx - ) + res = self._backend._lib.CMAC_CTX_copy(copied_ctx, self._ctx) self._backend.openssl_assert(res == 1) - return _CMACContext( - self._backend, self._algorithm, ctx=copied_ctx - ) + return _CMACContext(self._backend, self._algorithm, ctx=copied_ctx) def verify(self, signature): digest = self.finalize() diff --git a/src/cryptography/hazmat/backends/openssl/decode_asn1.py b/src/cryptography/hazmat/backends/openssl/decode_asn1.py index 5543b57a4871..56dcf26c1b54 100644 --- a/src/cryptography/hazmat/backends/openssl/decode_asn1.py +++ b/src/cryptography/hazmat/backends/openssl/decode_asn1.py @@ -14,7 +14,9 @@ from cryptography.x509.extensions import _TLS_FEATURE_TYPE_TO_ENUM from cryptography.x509.name import _ASN1_TYPE_TO_ENUM from cryptography.x509.oid import ( - CRLEntryExtensionOID, CertificatePoliciesOID, ExtensionOID, + CRLEntryExtensionOID, + CertificatePoliciesOID, + ExtensionOID, OCSPExtensionOID, ) @@ -119,10 +121,10 @@ def _decode_general_name(backend, gn): # netmask. To handle this we convert the netmask to integer, then # find the first 0 bit, which will be the prefix. If another 1 # bit is present after that the netmask is invalid. - base = ipaddress.ip_address(data[:data_len // 2]) - netmask = ipaddress.ip_address(data[data_len // 2:]) + base = ipaddress.ip_address(data[: data_len // 2]) + netmask = ipaddress.ip_address(data[data_len // 2 :]) bits = bin(int(netmask))[2:] - prefix = bits.find('0') + prefix = bits.find("0") # If no 0 bits are found it is a /32 or /128 if prefix == -1: prefix = len(bits) @@ -158,7 +160,7 @@ def _decode_general_name(backend, gn): "{} is not a supported type".format( x509._GENERAL_NAMES.get(gn.type, gn.type) ), - gn.type + gn.type, ) @@ -223,9 +225,9 @@ def parse(self, backend, x509_obj): # The contents of the extension must be an ASN.1 NULL. reader = DERReader(_asn1_string_to_bytes(backend, data)) reader.read_single_element(NULL).check_empty() - extensions.append(x509.Extension( - oid, critical, x509.PrecertPoison() - )) + extensions.append( + x509.Extension(oid, critical, x509.PrecertPoison()) + ) seen_oids.add(oid) continue @@ -237,9 +239,7 @@ def parse(self, backend, x509_obj): backend.openssl_assert(data != backend._ffi.NULL) der = backend._ffi.buffer(data.data, data.length)[:] unrecognized = x509.UnrecognizedExtension(oid, der) - extensions.append( - x509.Extension(oid, critical, unrecognized) - ) + extensions.append(x509.Extension(oid, critical, unrecognized)) else: ext_data = backend._lib.X509V3_EXT_d2i(ext) if ext_data == backend._ffi.NULL: @@ -271,16 +271,12 @@ def _decode_certificate_policies(backend, cp): qnum = backend._lib.sk_POLICYQUALINFO_num(pi.qualifiers) qualifiers = [] for j in range(qnum): - pqi = backend._lib.sk_POLICYQUALINFO_value( - pi.qualifiers, j - ) - pqualid = x509.ObjectIdentifier( - _obj2txt(backend, pqi.pqualid) - ) + pqi = backend._lib.sk_POLICYQUALINFO_value(pi.qualifiers, j) + pqualid = x509.ObjectIdentifier(_obj2txt(backend, pqi.pqualid)) if pqualid == CertificatePoliciesOID.CPS_QUALIFIER: cpsuri = backend._ffi.buffer( pqi.d.cpsuri.data, pqi.d.cpsuri.length - )[:].decode('ascii') + )[:].decode("ascii") qualifiers.append(cpsuri) else: assert pqualid == CertificatePoliciesOID.CPS_USER_NOTICE @@ -289,9 +285,7 @@ def _decode_certificate_policies(backend, cp): ) qualifiers.append(user_notice) - certificate_policies.append( - x509.PolicyInformation(oid, qualifiers) - ) + certificate_policies.append(x509.PolicyInformation(oid, qualifiers)) return x509.CertificatePolicies(certificate_policies) @@ -304,13 +298,9 @@ def _decode_user_notice(backend, un): explicit_text = _asn1_string_to_utf8(backend, un.exptext) if un.noticeref != backend._ffi.NULL: - organization = _asn1_string_to_utf8( - backend, un.noticeref.organization - ) + organization = _asn1_string_to_utf8(backend, un.noticeref.organization) - num = backend._lib.sk_ASN1_INTEGER_num( - un.noticeref.noticenos - ) + num = backend._lib.sk_ASN1_INTEGER_num(un.noticeref.noticenos) notice_numbers = [] for i in range(num): asn1_int = backend._lib.sk_ASN1_INTEGER_value( @@ -319,9 +309,7 @@ def _decode_user_notice(backend, un): notice_num = _asn1_integer_to_int(backend, asn1_int) notice_numbers.append(notice_num) - notice_reference = x509.NoticeReference( - organization, notice_numbers - ) + notice_reference = x509.NoticeReference(organization, notice_numbers) return x509.UserNotice(notice_reference, explicit_text) @@ -364,9 +352,7 @@ def _decode_authority_key_identifier(backend, akid): )[:] if akid.issuer != backend._ffi.NULL: - authority_cert_issuer = _decode_general_names( - backend, akid.issuer - ) + authority_cert_issuer = _decode_general_names(backend, akid.issuer) authority_cert_serial_number = _asn1_integer_to_int_or_none( backend, akid.serial @@ -382,10 +368,11 @@ def _decode_information_access(backend, ia): ia = backend._ffi.gc( ia, lambda x: backend._lib.sk_ACCESS_DESCRIPTION_pop_free( - x, backend._ffi.addressof( + x, + backend._ffi.addressof( backend._lib._original_lib, "ACCESS_DESCRIPTION_free" - ) - ) + ), + ), ) num = backend._lib.sk_ACCESS_DESCRIPTION_num(ia) access_descriptions = [] @@ -432,7 +419,7 @@ def _decode_key_usage(backend, bit_string): key_cert_sign, crl_sign, encipher_only, - decipher_only + decipher_only, ) @@ -500,8 +487,13 @@ def _decode_issuing_dist_point(backend, idp): only_some_reasons = None return x509.IssuingDistributionPoint( - full_name, relative_name, only_user, only_ca, only_some_reasons, - indirect_crl, only_attr + full_name, + relative_name, + only_user, + only_ca, + only_some_reasons, + indirect_crl, + only_attr, ) @@ -622,13 +614,9 @@ def _decode_distpoint(backend, distpoint): rnum = backend._lib.sk_X509_NAME_ENTRY_num(rns) attributes = set() for i in range(rnum): - rn = backend._lib.sk_X509_NAME_ENTRY_value( - rns, i - ) + rn = backend._lib.sk_X509_NAME_ENTRY_value(rns, i) backend.openssl_assert(rn != backend._ffi.NULL) - attributes.add( - _decode_x509_name_entry(backend, rn) - ) + attributes.add(_decode_x509_name_entry(backend, rn)) relative_name = x509.RelativeDistinguishedName(attributes) @@ -654,8 +642,9 @@ def _decode_inhibit_any_policy(backend, asn1_int): def _decode_scts(backend, asn1_scts): from cryptography.hazmat.backends.openssl.x509 import ( - _SignedCertificateTimestamp + _SignedCertificateTimestamp, ) + asn1_scts = backend._ffi.cast("Cryptography_STACK_OF_SCT *", asn1_scts) asn1_scts = backend._ffi.gc(asn1_scts, backend._lib.SCT_LIST_free) @@ -674,9 +663,7 @@ def _decode_precert_signed_certificate_timestamps(backend, asn1_scts): def _decode_signed_certificate_timestamps(backend, asn1_scts): - return x509.SignedCertificateTimestamps( - _decode_scts(backend, asn1_scts) - ) + return x509.SignedCertificateTimestamps(_decode_scts(backend, asn1_scts)) # CRLReason ::= ENUMERATED { @@ -715,7 +702,7 @@ def _decode_signed_certificate_timestamps(backend, asn1_scts): x509.ReasonFlags.certificate_hold: 6, x509.ReasonFlags.remove_from_crl: 8, x509.ReasonFlags.privilege_withdrawn: 9, - x509.ReasonFlags.aa_compromise: 10 + x509.ReasonFlags.aa_compromise: 10, } @@ -731,9 +718,7 @@ def _decode_crl_reason(backend, enum): def _decode_invalidity_date(backend, inv_date): - generalized_time = backend._ffi.cast( - "ASN1_GENERALIZEDTIME *", inv_date - ) + generalized_time = backend._ffi.cast("ASN1_GENERALIZEDTIME *", inv_date) generalized_time = backend._ffi.gc( generalized_time, backend._lib.ASN1_GENERALIZEDTIME_free ) @@ -794,7 +779,7 @@ def _asn1_string_to_utf8(backend, asn1_string): buf = backend._ffi.gc( buf, lambda buffer: backend._lib.OPENSSL_free(buffer[0]) ) - return backend._ffi.buffer(buf[0], res)[:].decode('utf8') + return backend._ffi.buffer(buf[0], res)[:].decode("utf8") def _parse_asn1_time(backend, asn1_time): @@ -895,19 +880,19 @@ def _decode_nonce(backend, nonce): _CERTIFICATE_EXTENSION_PARSER_NO_SCT = _X509ExtensionParser( ext_count=lambda backend, x: backend._lib.X509_get_ext_count(x), get_ext=lambda backend, x, i: backend._lib.X509_get_ext(x, i), - handlers=_EXTENSION_HANDLERS_NO_SCT + handlers=_EXTENSION_HANDLERS_NO_SCT, ) _CERTIFICATE_EXTENSION_PARSER = _X509ExtensionParser( ext_count=lambda backend, x: backend._lib.X509_get_ext_count(x), get_ext=lambda backend, x, i: backend._lib.X509_get_ext(x, i), - handlers=_EXTENSION_HANDLERS + handlers=_EXTENSION_HANDLERS, ) _CSR_EXTENSION_PARSER = _X509ExtensionParser( ext_count=lambda backend, x: backend._lib.sk_X509_EXTENSION_num(x), get_ext=lambda backend, x, i: backend._lib.sk_X509_EXTENSION_value(x, i), - handlers=_EXTENSION_HANDLERS + handlers=_EXTENSION_HANDLERS, ) _REVOKED_CERTIFICATE_EXTENSION_PARSER = _X509ExtensionParser( @@ -943,5 +928,5 @@ def _decode_nonce(backend, nonce): _OCSP_SINGLERESP_EXT_PARSER_NO_SCT = _X509ExtensionParser( ext_count=lambda backend, x: backend._lib.OCSP_SINGLERESP_get_ext_count(x), get_ext=lambda backend, x, i: backend._lib.OCSP_SINGLERESP_get_ext(x, i), - handlers=_OCSP_SINGLERESP_EXTENSION_HANDLERS_NO_SCT + handlers=_OCSP_SINGLERESP_EXTENSION_HANDLERS_NO_SCT, ) diff --git a/src/cryptography/hazmat/backends/openssl/dh.py b/src/cryptography/hazmat/backends/openssl/dh.py index 1d5065c26bec..95179d374e4c 100644 --- a/src/cryptography/hazmat/backends/openssl/dh.py +++ b/src/cryptography/hazmat/backends/openssl/dh.py @@ -53,7 +53,7 @@ def parameter_numbers(self): return dh.DHParameterNumbers( p=self._backend._bn_to_int(p[0]), g=self._backend._bn_to_int(g[0]), - q=q_val + q=q_val, ) def generate_private_key(self): @@ -61,34 +61,29 @@ def generate_private_key(self): def parameter_bytes(self, encoding, format): if format is not serialization.ParameterFormat.PKCS3: - raise ValueError( - "Only PKCS3 serialization is supported" - ) + raise ValueError("Only PKCS3 serialization is supported") if not self._backend._lib.Cryptography_HAS_EVP_PKEY_DHX: q = self._backend._ffi.new("BIGNUM **") - self._backend._lib.DH_get0_pqg(self._dh_cdata, - self._backend._ffi.NULL, - q, - self._backend._ffi.NULL) + self._backend._lib.DH_get0_pqg( + self._dh_cdata, + self._backend._ffi.NULL, + q, + self._backend._ffi.NULL, + ) if q[0] != self._backend._ffi.NULL: raise UnsupportedAlgorithm( "DH X9.42 serialization is not supported", - _Reasons.UNSUPPORTED_SERIALIZATION) + _Reasons.UNSUPPORTED_SERIALIZATION, + ) - return self._backend._parameter_bytes( - encoding, - format, - self._dh_cdata - ) + return self._backend._parameter_bytes(encoding, format, self._dh_cdata) def _handle_dh_compute_key_error(errors, backend): lib = backend._lib backend.openssl_assert( - errors[0]._lib_reason_match( - lib.ERR_LIB_DH, lib.DH_R_INVALID_PUBKEY - ) + errors[0]._lib_reason_match(lib.ERR_LIB_DH, lib.DH_R_INVALID_PUBKEY) ) raise ValueError("Public key value is invalid for this exchange.") @@ -96,9 +91,7 @@ def _handle_dh_compute_key_error(errors, backend): def _get_dh_num_bits(backend, dh_cdata): p = backend._ffi.new("BIGNUM **") - backend._lib.DH_get0_pqg(dh_cdata, p, - backend._ffi.NULL, - backend._ffi.NULL) + backend._lib.DH_get0_pqg(dh_cdata, p, backend._ffi.NULL, backend._ffi.NULL) backend.openssl_assert(p[0] != backend._ffi.NULL) return backend._lib.BN_num_bits(p[0]) @@ -136,24 +129,23 @@ def private_numbers(self): parameter_numbers=dh.DHParameterNumbers( p=self._backend._bn_to_int(p[0]), g=self._backend._bn_to_int(g[0]), - q=q_val + q=q_val, ), - y=self._backend._bn_to_int(pub_key[0]) + y=self._backend._bn_to_int(pub_key[0]), ), - x=self._backend._bn_to_int(priv_key[0]) + x=self._backend._bn_to_int(priv_key[0]), ) def exchange(self, peer_public_key): buf = self._backend._ffi.new("unsigned char[]", self._key_size_bytes) pub_key = self._backend._ffi.new("BIGNUM **") - self._backend._lib.DH_get0_key(peer_public_key._dh_cdata, pub_key, - self._backend._ffi.NULL) + self._backend._lib.DH_get0_key( + peer_public_key._dh_cdata, pub_key, self._backend._ffi.NULL + ) self._backend.openssl_assert(pub_key[0] != self._backend._ffi.NULL) res = self._backend._lib.DH_compute_key( - buf, - pub_key[0], - self._dh_cdata + buf, pub_key[0], self._dh_cdata ) if res == -1: @@ -173,15 +165,16 @@ def exchange(self, peer_public_key): def public_key(self): dh_cdata = _dh_params_dup(self._dh_cdata, self._backend) pub_key = self._backend._ffi.new("BIGNUM **") - self._backend._lib.DH_get0_key(self._dh_cdata, - pub_key, self._backend._ffi.NULL) + self._backend._lib.DH_get0_key( + self._dh_cdata, pub_key, self._backend._ffi.NULL + ) self._backend.openssl_assert(pub_key[0] != self._backend._ffi.NULL) pub_key_dup = self._backend._lib.BN_dup(pub_key[0]) self._backend.openssl_assert(pub_key_dup != self._backend._ffi.NULL) - res = self._backend._lib.DH_set0_key(dh_cdata, - pub_key_dup, - self._backend._ffi.NULL) + res = self._backend._lib.DH_set0_key( + dh_cdata, pub_key_dup, self._backend._ffi.NULL + ) self._backend.openssl_assert(res == 1) evp_pkey = self._backend._dh_cdata_to_evp_pkey(dh_cdata) return _DHPublicKey(self._backend, dh_cdata, evp_pkey) @@ -196,14 +189,17 @@ def private_bytes(self, encoding, format, encryption_algorithm): ) if not self._backend._lib.Cryptography_HAS_EVP_PKEY_DHX: q = self._backend._ffi.new("BIGNUM **") - self._backend._lib.DH_get0_pqg(self._dh_cdata, - self._backend._ffi.NULL, - q, - self._backend._ffi.NULL) + self._backend._lib.DH_get0_pqg( + self._dh_cdata, + self._backend._ffi.NULL, + q, + self._backend._ffi.NULL, + ) if q[0] != self._backend._ffi.NULL: raise UnsupportedAlgorithm( "DH X9.42 serialization is not supported", - _Reasons.UNSUPPORTED_SERIALIZATION) + _Reasons.UNSUPPORTED_SERIALIZATION, + ) return self._backend._private_key_bytes( encoding, @@ -211,7 +207,7 @@ def private_bytes(self, encoding, format, encryption_algorithm): encryption_algorithm, self, self._evp_pkey, - self._dh_cdata + self._dh_cdata, ) @@ -239,16 +235,17 @@ def public_numbers(self): else: q_val = self._backend._bn_to_int(q[0]) pub_key = self._backend._ffi.new("BIGNUM **") - self._backend._lib.DH_get0_key(self._dh_cdata, - pub_key, self._backend._ffi.NULL) + self._backend._lib.DH_get0_key( + self._dh_cdata, pub_key, self._backend._ffi.NULL + ) self._backend.openssl_assert(pub_key[0] != self._backend._ffi.NULL) return dh.DHPublicNumbers( parameter_numbers=dh.DHParameterNumbers( p=self._backend._bn_to_int(p[0]), g=self._backend._bn_to_int(g[0]), - q=q_val + q=q_val, ), - y=self._backend._bn_to_int(pub_key[0]) + y=self._backend._bn_to_int(pub_key[0]), ) def parameters(self): @@ -263,19 +260,18 @@ def public_bytes(self, encoding, format): if not self._backend._lib.Cryptography_HAS_EVP_PKEY_DHX: q = self._backend._ffi.new("BIGNUM **") - self._backend._lib.DH_get0_pqg(self._dh_cdata, - self._backend._ffi.NULL, - q, - self._backend._ffi.NULL) + self._backend._lib.DH_get0_pqg( + self._dh_cdata, + self._backend._ffi.NULL, + q, + self._backend._ffi.NULL, + ) if q[0] != self._backend._ffi.NULL: raise UnsupportedAlgorithm( "DH X9.42 serialization is not supported", - _Reasons.UNSUPPORTED_SERIALIZATION) + _Reasons.UNSUPPORTED_SERIALIZATION, + ) return self._backend._public_key_bytes( - encoding, - format, - self, - self._evp_pkey, - None + encoding, format, self, self._evp_pkey, None ) diff --git a/src/cryptography/hazmat/backends/openssl/dsa.py b/src/cryptography/hazmat/backends/openssl/dsa.py index 79142bf6fa68..0c5faba18ac9 100644 --- a/src/cryptography/hazmat/backends/openssl/dsa.py +++ b/src/cryptography/hazmat/backends/openssl/dsa.py @@ -7,12 +7,15 @@ from cryptography import utils from cryptography.exceptions import InvalidSignature from cryptography.hazmat.backends.openssl.utils import ( - _calculate_digest_and_algorithm, _check_not_prehashed, - _warn_sign_verify_deprecated + _calculate_digest_and_algorithm, + _check_not_prehashed, + _warn_sign_verify_deprecated, ) from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import ( - AsymmetricSignatureContext, AsymmetricVerificationContext, dsa + AsymmetricSignatureContext, + AsymmetricVerificationContext, + dsa, ) @@ -29,7 +32,7 @@ def _dsa_sig_sign(backend, private_key, data): backend.openssl_assert(res == 1) backend.openssl_assert(buflen[0]) - return backend._ffi.buffer(sig_buf)[:buflen[0]] + return backend._ffi.buffer(sig_buf)[: buflen[0]] def _dsa_sig_verify(backend, public_key, signature, data): @@ -98,7 +101,7 @@ def parameter_numbers(self): return dsa.DSAParameterNumbers( p=self._backend._bn_to_int(p[0]), q=self._backend._bn_to_int(q[0]), - g=self._backend._bn_to_int(g[0]) + g=self._backend._bn_to_int(g[0]), ) def generate_private_key(self): @@ -144,11 +147,11 @@ def private_numbers(self): parameter_numbers=dsa.DSAParameterNumbers( p=self._backend._bn_to_int(p[0]), q=self._backend._bn_to_int(q[0]), - g=self._backend._bn_to_int(g[0]) + g=self._backend._bn_to_int(g[0]), ), - y=self._backend._bn_to_int(pub_key[0]) + y=self._backend._bn_to_int(pub_key[0]), ), - x=self._backend._bn_to_int(priv_key[0]) + x=self._backend._bn_to_int(priv_key[0]), ) def public_key(self): @@ -185,7 +188,7 @@ def private_bytes(self, encoding, format, encryption_algorithm): encryption_algorithm, self, self._evp_pkey, - self._dsa_cdata + self._dsa_cdata, ) def sign(self, data, algorithm): @@ -236,9 +239,9 @@ def public_numbers(self): parameter_numbers=dsa.DSAParameterNumbers( p=self._backend._bn_to_int(p[0]), q=self._backend._bn_to_int(q[0]), - g=self._backend._bn_to_int(g[0]) + g=self._backend._bn_to_int(g[0]), ), - y=self._backend._bn_to_int(pub_key[0]) + y=self._backend._bn_to_int(pub_key[0]), ) def parameters(self): @@ -250,11 +253,7 @@ def parameters(self): def public_bytes(self, encoding, format): return self._backend._public_key_bytes( - encoding, - format, - self, - self._evp_pkey, - None + encoding, format, self, self._evp_pkey, None ) def verify(self, signature, data, algorithm): diff --git a/src/cryptography/hazmat/backends/openssl/ec.py b/src/cryptography/hazmat/backends/openssl/ec.py index e70a3410548a..3ecec0da2009 100644 --- a/src/cryptography/hazmat/backends/openssl/ec.py +++ b/src/cryptography/hazmat/backends/openssl/ec.py @@ -6,15 +6,20 @@ from cryptography import utils from cryptography.exceptions import ( - InvalidSignature, UnsupportedAlgorithm, _Reasons + InvalidSignature, + UnsupportedAlgorithm, + _Reasons, ) from cryptography.hazmat.backends.openssl.utils import ( - _calculate_digest_and_algorithm, _check_not_prehashed, - _warn_sign_verify_deprecated + _calculate_digest_and_algorithm, + _check_not_prehashed, + _warn_sign_verify_deprecated, ) from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import ( - AsymmetricSignatureContext, AsymmetricVerificationContext, ec + AsymmetricSignatureContext, + AsymmetricVerificationContext, + ec, ) @@ -22,7 +27,8 @@ def _check_signature_algorithm(signature_algorithm): if not isinstance(signature_algorithm, ec.ECDSA): raise UnsupportedAlgorithm( "Unsupported elliptic curve signature algorithm.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM) + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) def _ec_key_curve_sn(backend, ec_key): @@ -34,26 +40,24 @@ def _ec_key_curve_sn(backend, ec_key): # an error for now. if nid == backend._lib.NID_undef: raise NotImplementedError( - "ECDSA keys with unnamed curves are unsupported " - "at this time" + "ECDSA keys with unnamed curves are unsupported " "at this time" ) # This is like the above check, but it also catches the case where you # explicitly encoded a curve with the same parameters as a named curve. # Don't do that. if ( - backend._lib.CRYPTOGRAPHY_OPENSSL_110_OR_GREATER and - backend._lib.EC_GROUP_get_asn1_flag(group) == 0 + backend._lib.CRYPTOGRAPHY_OPENSSL_110_OR_GREATER + and backend._lib.EC_GROUP_get_asn1_flag(group) == 0 ): raise NotImplementedError( - "ECDSA keys with unnamed curves are unsupported " - "at this time" + "ECDSA keys with unnamed curves are unsupported " "at this time" ) curve_name = backend._lib.OBJ_nid2sn(nid) backend.openssl_assert(curve_name != backend._ffi.NULL) - sn = backend._ffi.string(curve_name).decode('ascii') + sn = backend._ffi.string(curve_name).decode("ascii") return sn @@ -75,7 +79,7 @@ def _sn_to_elliptic_curve(backend, sn): except KeyError: raise UnsupportedAlgorithm( "{} is not a supported elliptic curve".format(sn), - _Reasons.UNSUPPORTED_ELLIPTIC_CURVE + _Reasons.UNSUPPORTED_ELLIPTIC_CURVE, ) @@ -89,7 +93,7 @@ def _ecdsa_sig_sign(backend, private_key, data): 0, data, len(data), sigbuf, siglen_ptr, private_key._ec_key ) backend.openssl_assert(res == 1) - return backend._ffi.buffer(sigbuf)[:siglen_ptr[0]] + return backend._ffi.buffer(sigbuf)[: siglen_ptr[0]] def _ecdsa_sig_verify(backend, public_key, signature, data): @@ -168,7 +172,7 @@ def exchange(self, algorithm, peer_public_key): ): raise UnsupportedAlgorithm( "This backend does not support the ECDH algorithm.", - _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, ) if peer_public_key.curve.name != self.curve.name: @@ -217,7 +221,7 @@ def private_numbers(self): private_value = self._backend._bn_to_int(bn) return ec.EllipticCurvePrivateNumbers( private_value=private_value, - public_numbers=self.public_key().public_numbers() + public_numbers=self.public_key().public_numbers(), ) def private_bytes(self, encoding, format, encryption_algorithm): @@ -227,7 +231,7 @@ def private_bytes(self, encoding, format, encryption_algorithm): encryption_algorithm, self, self._evp_pkey, - self._ec_key + self._ec_key, ) def sign(self, data, signature_algorithm): @@ -266,8 +270,8 @@ def verifier(self, signature, signature_algorithm): ) def public_numbers(self): - get_func, group = ( - self._backend._ec_key_determine_group_get_func(self._ec_key) + get_func, group = self._backend._ec_key_determine_group_get_func( + self._ec_key ) point = self._backend._lib.EC_KEY_get0_public_key(self._ec_key) self._backend.openssl_assert(point != self._backend._ffi.NULL) @@ -282,11 +286,7 @@ def public_numbers(self): x = self._backend._bn_to_int(bn_x) y = self._backend._bn_to_int(bn_y) - return ec.EllipticCurvePublicNumbers( - x=x, - y=y, - curve=self._curve - ) + return ec.EllipticCurvePublicNumbers(x=x, y=y, curve=self._curve) def _encode_point(self, format): if format is serialization.PublicFormat.CompressedPoint: @@ -315,16 +315,13 @@ def _encode_point(self, format): def public_bytes(self, encoding, format): if ( - encoding is serialization.Encoding.X962 or - format is serialization.PublicFormat.CompressedPoint or - format is serialization.PublicFormat.UncompressedPoint + encoding is serialization.Encoding.X962 + or format is serialization.PublicFormat.CompressedPoint + or format is serialization.PublicFormat.UncompressedPoint ): - if ( - encoding is not serialization.Encoding.X962 or - format not in ( - serialization.PublicFormat.CompressedPoint, - serialization.PublicFormat.UncompressedPoint - ) + if encoding is not serialization.Encoding.X962 or format not in ( + serialization.PublicFormat.CompressedPoint, + serialization.PublicFormat.UncompressedPoint, ): raise ValueError( "X962 encoding must be used with CompressedPoint or " @@ -334,11 +331,7 @@ def public_bytes(self, encoding, format): return self._encode_point(format) else: return self._backend._public_key_bytes( - encoding, - format, - self, - self._evp_pkey, - None + encoding, format, self, self._evp_pkey, None ) def verify(self, signature, data, signature_algorithm): diff --git a/src/cryptography/hazmat/backends/openssl/ed25519.py b/src/cryptography/hazmat/backends/openssl/ed25519.py index 1632ec371eaa..75653373b3cf 100644 --- a/src/cryptography/hazmat/backends/openssl/ed25519.py +++ b/src/cryptography/hazmat/backends/openssl/ed25519.py @@ -7,7 +7,10 @@ from cryptography import exceptions, utils from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric.ed25519 import ( - Ed25519PrivateKey, Ed25519PublicKey, _ED25519_KEY_SIZE, _ED25519_SIG_SIZE + Ed25519PrivateKey, + Ed25519PublicKey, + _ED25519_KEY_SIZE, + _ED25519_SIG_SIZE, ) @@ -19,12 +22,12 @@ def __init__(self, backend, evp_pkey): def public_bytes(self, encoding, format): if ( - encoding is serialization.Encoding.Raw or - format is serialization.PublicFormat.Raw + encoding is serialization.Encoding.Raw + or format is serialization.PublicFormat.Raw ): if ( - encoding is not serialization.Encoding.Raw or - format is not serialization.PublicFormat.Raw + encoding is not serialization.Encoding.Raw + or format is not serialization.PublicFormat.Raw ): raise ValueError( "When using Raw both encoding and format must be Raw" @@ -53,8 +56,11 @@ def verify(self, signature, data): evp_md_ctx, self._backend._lib.Cryptography_EVP_MD_CTX_free ) res = self._backend._lib.EVP_DigestVerifyInit( - evp_md_ctx, self._backend._ffi.NULL, self._backend._ffi.NULL, - self._backend._ffi.NULL, self._evp_pkey + evp_md_ctx, + self._backend._ffi.NULL, + self._backend._ffi.NULL, + self._backend._ffi.NULL, + self._evp_pkey, ) self._backend.openssl_assert(res == 1) res = self._backend._lib.EVP_DigestVerify( @@ -89,8 +95,11 @@ def sign(self, data): evp_md_ctx, self._backend._lib.Cryptography_EVP_MD_CTX_free ) res = self._backend._lib.EVP_DigestSignInit( - evp_md_ctx, self._backend._ffi.NULL, self._backend._ffi.NULL, - self._backend._ffi.NULL, self._evp_pkey + evp_md_ctx, + self._backend._ffi.NULL, + self._backend._ffi.NULL, + self._backend._ffi.NULL, + self._evp_pkey, ) self._backend.openssl_assert(res == 1) buf = self._backend._ffi.new("unsigned char[]", _ED25519_SIG_SIZE) @@ -104,13 +113,15 @@ def sign(self, data): def private_bytes(self, encoding, format, encryption_algorithm): if ( - encoding is serialization.Encoding.Raw or - format is serialization.PublicFormat.Raw + encoding is serialization.Encoding.Raw + or format is serialization.PublicFormat.Raw ): if ( - format is not serialization.PrivateFormat.Raw or - encoding is not serialization.Encoding.Raw or not - isinstance(encryption_algorithm, serialization.NoEncryption) + format is not serialization.PrivateFormat.Raw + or encoding is not serialization.Encoding.Raw + or not isinstance( + encryption_algorithm, serialization.NoEncryption + ) ): raise ValueError( "When using Raw both encoding and format must be Raw " diff --git a/src/cryptography/hazmat/backends/openssl/ed448.py b/src/cryptography/hazmat/backends/openssl/ed448.py index 4845a1f2d2b8..4a8dab1a8115 100644 --- a/src/cryptography/hazmat/backends/openssl/ed448.py +++ b/src/cryptography/hazmat/backends/openssl/ed448.py @@ -7,7 +7,8 @@ from cryptography import exceptions, utils from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric.ed448 import ( - Ed448PrivateKey, Ed448PublicKey + Ed448PrivateKey, + Ed448PublicKey, ) _ED448_KEY_SIZE = 57 @@ -22,12 +23,12 @@ def __init__(self, backend, evp_pkey): def public_bytes(self, encoding, format): if ( - encoding is serialization.Encoding.Raw or - format is serialization.PublicFormat.Raw + encoding is serialization.Encoding.Raw + or format is serialization.PublicFormat.Raw ): if ( - encoding is not serialization.Encoding.Raw or - format is not serialization.PublicFormat.Raw + encoding is not serialization.Encoding.Raw + or format is not serialization.PublicFormat.Raw ): raise ValueError( "When using Raw both encoding and format must be Raw" @@ -56,8 +57,11 @@ def verify(self, signature, data): evp_md_ctx, self._backend._lib.Cryptography_EVP_MD_CTX_free ) res = self._backend._lib.EVP_DigestVerifyInit( - evp_md_ctx, self._backend._ffi.NULL, self._backend._ffi.NULL, - self._backend._ffi.NULL, self._evp_pkey + evp_md_ctx, + self._backend._ffi.NULL, + self._backend._ffi.NULL, + self._backend._ffi.NULL, + self._evp_pkey, ) self._backend.openssl_assert(res == 1) res = self._backend._lib.EVP_DigestVerify( @@ -92,8 +96,11 @@ def sign(self, data): evp_md_ctx, self._backend._lib.Cryptography_EVP_MD_CTX_free ) res = self._backend._lib.EVP_DigestSignInit( - evp_md_ctx, self._backend._ffi.NULL, self._backend._ffi.NULL, - self._backend._ffi.NULL, self._evp_pkey + evp_md_ctx, + self._backend._ffi.NULL, + self._backend._ffi.NULL, + self._backend._ffi.NULL, + self._evp_pkey, ) self._backend.openssl_assert(res == 1) buf = self._backend._ffi.new("unsigned char[]", _ED448_SIG_SIZE) @@ -107,13 +114,15 @@ def sign(self, data): def private_bytes(self, encoding, format, encryption_algorithm): if ( - encoding is serialization.Encoding.Raw or - format is serialization.PublicFormat.Raw + encoding is serialization.Encoding.Raw + or format is serialization.PublicFormat.Raw ): if ( - format is not serialization.PrivateFormat.Raw or - encoding is not serialization.Encoding.Raw or not - isinstance(encryption_algorithm, serialization.NoEncryption) + format is not serialization.PrivateFormat.Raw + or encoding is not serialization.Encoding.Raw + or not isinstance( + encryption_algorithm, serialization.NoEncryption + ) ): raise ValueError( "When using Raw both encoding and format must be Raw " diff --git a/src/cryptography/hazmat/backends/openssl/encode_asn1.py b/src/cryptography/hazmat/backends/openssl/encode_asn1.py index e12431cfc626..154f6764cad8 100644 --- a/src/cryptography/hazmat/backends/openssl/encode_asn1.py +++ b/src/cryptography/hazmat/backends/openssl/encode_asn1.py @@ -11,12 +11,15 @@ from cryptography import utils, x509 from cryptography.hazmat.backends.openssl.decode_asn1 import ( - _CRL_ENTRY_REASON_ENUM_TO_CODE, _DISTPOINT_TYPE_FULLNAME, - _DISTPOINT_TYPE_RELATIVENAME + _CRL_ENTRY_REASON_ENUM_TO_CODE, + _DISTPOINT_TYPE_FULLNAME, + _DISTPOINT_TYPE_RELATIVENAME, ) from cryptography.x509.name import _ASN1Type from cryptography.x509.oid import ( - CRLEntryExtensionOID, ExtensionOID, OCSPExtensionOID, + CRLEntryExtensionOID, + ExtensionOID, + OCSPExtensionOID, ) @@ -94,7 +97,8 @@ def _encode_name(backend, name): name_entry, backend._lib.X509_NAME_ENTRY_free ) res = backend._lib.X509_NAME_add_entry( - subject, name_entry, -1, set_flag) + subject, name_entry, -1, set_flag + ) backend.openssl_assert(res == 1) set_flag = -1 return subject @@ -120,11 +124,11 @@ def _encode_sk_name_entry(backend, attributes): def _encode_name_entry(backend, attribute): if attribute._type is _ASN1Type.BMPString: - value = attribute.value.encode('utf_16_be') + value = attribute.value.encode("utf_16_be") elif attribute._type is _ASN1Type.UniversalString: - value = attribute.value.encode('utf_32_be') + value = attribute.value.encode("utf_32_be") else: - value = attribute.value.encode('utf8') + value = attribute.value.encode("utf8") obj = _txt2obj_gc(backend, attribute.oid.dotted_string) @@ -174,9 +178,8 @@ def _encode_crl_reason(backend, crl_reason): def _encode_invalidity_date(backend, invalidity_date): time = backend._lib.ASN1_GENERALIZEDTIME_set( - backend._ffi.NULL, calendar.timegm( - invalidity_date.invalidity_date.timetuple() - ) + backend._ffi.NULL, + calendar.timegm(invalidity_date.invalidity_date.timetuple()), ) backend.openssl_assert(time != backend._ffi.NULL) time = backend._ffi.gc(time, backend._lib.ASN1_GENERALIZEDTIME_free) @@ -208,8 +211,7 @@ def _encode_certificate_policies(backend, certificate_policies): backend, x509.OID_CPS_QUALIFIER.dotted_string ) pqi.d.cpsuri = _encode_asn1_str( - backend, - qualifier.encode("ascii"), + backend, qualifier.encode("ascii"), ) else: assert isinstance(qualifier, x509.UserNotice) @@ -257,7 +259,7 @@ def _txt2obj(backend, name): Converts a Python string with an ASN.1 object ID in dotted form to a ASN1_OBJECT. """ - name = name.encode('ascii') + name = name.encode("ascii") obj = backend._lib.OBJ_txt2obj(name, 1) backend.openssl_assert(obj != backend._ffi.NULL) return obj @@ -311,10 +313,7 @@ def _encode_authority_key_identifier(backend, authority_keyid): backend.openssl_assert(akid != backend._ffi.NULL) akid = backend._ffi.gc(akid, backend._lib.AUTHORITY_KEYID_free) if authority_keyid.key_identifier is not None: - akid.keyid = _encode_asn1_str( - backend, - authority_keyid.key_identifier, - ) + akid.keyid = _encode_asn1_str(backend, authority_keyid.key_identifier,) if authority_keyid.authority_cert_issuer is not None: akid.issuer = _encode_general_names( @@ -349,10 +348,11 @@ def _encode_information_access(backend, info_access): aia = backend._ffi.gc( aia, lambda x: backend._lib.sk_ACCESS_DESCRIPTION_pop_free( - x, backend._ffi.addressof( + x, + backend._ffi.addressof( backend._lib._original_lib, "ACCESS_DESCRIPTION_free" - ) - ) + ), + ), ) for access_description in info_access: ad = backend._lib.ACCESS_DESCRIPTION_new() @@ -416,7 +416,7 @@ def _encode_general_name_preallocated(backend, name, gn): backend.openssl_assert(gn != backend._ffi.NULL) gn.type = backend._lib.GEN_RID obj = backend._lib.OBJ_txt2obj( - name.value.dotted_string.encode('ascii'), 1 + name.value.dotted_string.encode("ascii"), 1 ) backend.openssl_assert(obj != backend._ffi.NULL) gn.d.registeredID = obj @@ -428,14 +428,12 @@ def _encode_general_name_preallocated(backend, name, gn): elif isinstance(name, x509.IPAddress): backend.openssl_assert(gn != backend._ffi.NULL) if isinstance(name.value, ipaddress.IPv4Network): - packed = ( - name.value.network_address.packed + - utils.int_to_bytes(((1 << 32) - name.value.num_addresses), 4) + packed = name.value.network_address.packed + utils.int_to_bytes( + ((1 << 32) - name.value.num_addresses), 4 ) elif isinstance(name.value, ipaddress.IPv6Network): - packed = ( - name.value.network_address.packed + - utils.int_to_bytes((1 << 128) - name.value.num_addresses, 16) + packed = name.value.network_address.packed + utils.int_to_bytes( + (1 << 128) - name.value.num_addresses, 16 ) else: packed = name.value.packed @@ -448,7 +446,7 @@ def _encode_general_name_preallocated(backend, name, gn): backend.openssl_assert(other_name != backend._ffi.NULL) type_id = backend._lib.OBJ_txt2obj( - name.type_id.dotted_string.encode('ascii'), 1 + name.type_id.dotted_string.encode("ascii"), 1 ) backend.openssl_assert(type_id != backend._ffi.NULL) data = backend._ffi.new("unsigned char[]", name.value) @@ -481,9 +479,7 @@ def _encode_general_name_preallocated(backend, name, gn): gn.type = backend._lib.GEN_URI gn.d.uniformResourceIdentifier = asn1_str else: - raise ValueError( - "{} is an unknown GeneralName type".format(name) - ) + raise ValueError("{} is an unknown GeneralName type".format(name)) def _encode_extended_key_usage(backend, extended_key_usage): diff --git a/src/cryptography/hazmat/backends/openssl/hashes.py b/src/cryptography/hazmat/backends/openssl/hashes.py index 7f9d840b3809..44033993e166 100644 --- a/src/cryptography/hazmat/backends/openssl/hashes.py +++ b/src/cryptography/hazmat/backends/openssl/hashes.py @@ -26,11 +26,13 @@ def __init__(self, backend, algorithm, ctx=None): if evp_md == self._backend._ffi.NULL: raise UnsupportedAlgorithm( "{} is not a supported hash on this backend.".format( - algorithm.name), - _Reasons.UNSUPPORTED_HASH + algorithm.name + ), + _Reasons.UNSUPPORTED_HASH, ) - res = self._backend._lib.EVP_DigestInit_ex(ctx, evp_md, - self._backend._ffi.NULL) + res = self._backend._lib.EVP_DigestInit_ex( + ctx, evp_md, self._backend._ffi.NULL + ) self._backend.openssl_assert(res != 0) self._ctx = ctx @@ -58,21 +60,23 @@ def finalize(self): # extendable output functions use a different finalize return self._finalize_xof() else: - buf = self._backend._ffi.new("unsigned char[]", - self._backend._lib.EVP_MAX_MD_SIZE) + buf = self._backend._ffi.new( + "unsigned char[]", self._backend._lib.EVP_MAX_MD_SIZE + ) outlen = self._backend._ffi.new("unsigned int *") res = self._backend._lib.EVP_DigestFinal_ex(self._ctx, buf, outlen) self._backend.openssl_assert(res != 0) self._backend.openssl_assert( outlen[0] == self.algorithm.digest_size ) - return self._backend._ffi.buffer(buf)[:outlen[0]] + return self._backend._ffi.buffer(buf)[: outlen[0]] def _finalize_xof(self): - buf = self._backend._ffi.new("unsigned char[]", - self.algorithm.digest_size) + buf = self._backend._ffi.new( + "unsigned char[]", self.algorithm.digest_size + ) res = self._backend._lib.EVP_DigestFinalXOF( self._ctx, buf, self.algorithm.digest_size ) self._backend.openssl_assert(res != 0) - return self._backend._ffi.buffer(buf)[:self.algorithm.digest_size] + return self._backend._ffi.buffer(buf)[: self.algorithm.digest_size] diff --git a/src/cryptography/hazmat/backends/openssl/hmac.py b/src/cryptography/hazmat/backends/openssl/hmac.py index 2e09cbc8a98f..5024223b219b 100644 --- a/src/cryptography/hazmat/backends/openssl/hmac.py +++ b/src/cryptography/hazmat/backends/openssl/hmac.py @@ -7,7 +7,9 @@ from cryptography import utils from cryptography.exceptions import ( - InvalidSignature, UnsupportedAlgorithm, _Reasons + InvalidSignature, + UnsupportedAlgorithm, + _Reasons, ) from cryptography.hazmat.primitives import constant_time, hashes @@ -28,8 +30,9 @@ def __init__(self, backend, key, algorithm, ctx=None): if evp_md == self._backend._ffi.NULL: raise UnsupportedAlgorithm( "{} is not a supported hash on this backend".format( - algorithm.name), - _Reasons.UNSUPPORTED_HASH + algorithm.name + ), + _Reasons.UNSUPPORTED_HASH, ) key_ptr = self._backend._ffi.from_buffer(key) res = self._backend._lib.HMAC_Init_ex( @@ -60,13 +63,14 @@ def update(self, data): self._backend.openssl_assert(res != 0) def finalize(self): - buf = self._backend._ffi.new("unsigned char[]", - self._backend._lib.EVP_MAX_MD_SIZE) + buf = self._backend._ffi.new( + "unsigned char[]", self._backend._lib.EVP_MAX_MD_SIZE + ) outlen = self._backend._ffi.new("unsigned int *") res = self._backend._lib.HMAC_Final(self._ctx, buf, outlen) self._backend.openssl_assert(res != 0) self._backend.openssl_assert(outlen[0] == self.algorithm.digest_size) - return self._backend._ffi.buffer(buf)[:outlen[0]] + return self._backend._ffi.buffer(buf)[: outlen[0]] def verify(self, signature): digest = self.finalize() diff --git a/src/cryptography/hazmat/backends/openssl/ocsp.py b/src/cryptography/hazmat/backends/openssl/ocsp.py index 3b5528929cb5..1de75a26ca64 100644 --- a/src/cryptography/hazmat/backends/openssl/ocsp.py +++ b/src/cryptography/hazmat/backends/openssl/ocsp.py @@ -9,18 +9,27 @@ from cryptography import utils, x509 from cryptography.exceptions import UnsupportedAlgorithm from cryptography.hazmat.backends.openssl.decode_asn1 import ( - _CRL_ENTRY_REASON_CODE_TO_ENUM, _OCSP_BASICRESP_EXT_PARSER, - _OCSP_REQ_EXT_PARSER, _OCSP_SINGLERESP_EXT_PARSER, + _CRL_ENTRY_REASON_CODE_TO_ENUM, + _OCSP_BASICRESP_EXT_PARSER, + _OCSP_REQ_EXT_PARSER, + _OCSP_SINGLERESP_EXT_PARSER, _OCSP_SINGLERESP_EXT_PARSER_NO_SCT, _asn1_integer_to_int, - _asn1_string_to_bytes, _decode_x509_name, _obj2txt, + _asn1_string_to_bytes, + _decode_x509_name, + _obj2txt, _parse_asn1_generalized_time, ) from cryptography.hazmat.backends.openssl.x509 import _Certificate from cryptography.hazmat.primitives import serialization from cryptography.x509.ocsp import ( - OCSPCertStatus, OCSPRequest, OCSPResponse, OCSPResponseStatus, - _CERT_STATUS_TO_ENUM, _OIDS_TO_HASH, _RESPONSE_STATUS_TO_ENUM, + OCSPCertStatus, + OCSPRequest, + OCSPResponse, + OCSPResponseStatus, + _CERT_STATUS_TO_ENUM, + _OIDS_TO_HASH, + _RESPONSE_STATUS_TO_ENUM, ) @@ -41,8 +50,11 @@ def wrapper(self, *args): def _issuer_key_hash(backend, cert_id): key_hash = backend._ffi.new("ASN1_OCTET_STRING **") res = backend._lib.OCSP_id_get0_info( - backend._ffi.NULL, backend._ffi.NULL, - key_hash, backend._ffi.NULL, cert_id + backend._ffi.NULL, + backend._ffi.NULL, + key_hash, + backend._ffi.NULL, + cert_id, ) backend.openssl_assert(res == 1) backend.openssl_assert(key_hash[0] != backend._ffi.NULL) @@ -52,8 +64,11 @@ def _issuer_key_hash(backend, cert_id): def _issuer_name_hash(backend, cert_id): name_hash = backend._ffi.new("ASN1_OCTET_STRING **") res = backend._lib.OCSP_id_get0_info( - name_hash, backend._ffi.NULL, - backend._ffi.NULL, backend._ffi.NULL, cert_id + name_hash, + backend._ffi.NULL, + backend._ffi.NULL, + backend._ffi.NULL, + cert_id, ) backend.openssl_assert(res == 1) backend.openssl_assert(name_hash[0] != backend._ffi.NULL) @@ -63,8 +78,7 @@ def _issuer_name_hash(backend, cert_id): def _serial_number(backend, cert_id): num = backend._ffi.new("ASN1_INTEGER **") res = backend._lib.OCSP_id_get0_info( - backend._ffi.NULL, backend._ffi.NULL, - backend._ffi.NULL, num, cert_id + backend._ffi.NULL, backend._ffi.NULL, backend._ffi.NULL, num, cert_id ) backend.openssl_assert(res == 1) backend.openssl_assert(num[0] != backend._ffi.NULL) @@ -74,8 +88,11 @@ def _serial_number(backend, cert_id): def _hash_algorithm(backend, cert_id): asn1obj = backend._ffi.new("ASN1_OBJECT **") res = backend._lib.OCSP_id_get0_info( - backend._ffi.NULL, asn1obj, - backend._ffi.NULL, backend._ffi.NULL, cert_id + backend._ffi.NULL, + asn1obj, + backend._ffi.NULL, + backend._ffi.NULL, + cert_id, ) backend.openssl_assert(res == 1) backend.openssl_assert(asn1obj[0] != backend._ffi.NULL) @@ -339,9 +356,7 @@ def single_extensions(self): def public_bytes(self, encoding): if encoding is not serialization.Encoding.DER: - raise ValueError( - "The only allowed encoding value is Encoding.DER" - ) + raise ValueError("The only allowed encoding value is Encoding.DER") bio = self._backend._create_mem_bio_gc() res = self._backend._lib.i2d_OCSP_RESPONSE_bio( @@ -356,7 +371,7 @@ class _OCSPRequest(object): def __init__(self, backend, ocsp_request): if backend._lib.OCSP_request_onereq_count(ocsp_request) > 1: raise NotImplementedError( - 'OCSP request contains more than one request' + "OCSP request contains more than one request" ) self._backend = backend self._ocsp_request = ocsp_request @@ -389,9 +404,7 @@ def extensions(self): def public_bytes(self, encoding): if encoding is not serialization.Encoding.DER: - raise ValueError( - "The only allowed encoding value is Encoding.DER" - ) + raise ValueError("The only allowed encoding value is Encoding.DER") bio = self._backend._create_mem_bio_gc() res = self._backend._lib.i2d_OCSP_REQUEST_bio(bio, self._ocsp_request) diff --git a/src/cryptography/hazmat/backends/openssl/poly1305.py b/src/cryptography/hazmat/backends/openssl/poly1305.py index 25448dd02597..17493ca60ce8 100644 --- a/src/cryptography/hazmat/backends/openssl/poly1305.py +++ b/src/cryptography/hazmat/backends/openssl/poly1305.py @@ -22,7 +22,9 @@ def __init__(self, backend, key): # need to retain it ourselves evp_pkey = self._backend._lib.EVP_PKEY_new_raw_private_key( self._backend._lib.NID_poly1305, - self._backend._ffi.NULL, key_ptr, len(key) + self._backend._ffi.NULL, + key_ptr, + len(key), ) self._backend.openssl_assert(evp_pkey != self._backend._ffi.NULL) self._evp_pkey = self._backend._ffi.gc( @@ -34,8 +36,11 @@ def __init__(self, backend, key): ctx, self._backend._lib.Cryptography_EVP_MD_CTX_free ) res = self._backend._lib.EVP_DigestSignInit( - self._ctx, self._backend._ffi.NULL, self._backend._ffi.NULL, - self._backend._ffi.NULL, self._evp_pkey + self._ctx, + self._backend._ffi.NULL, + self._backend._ffi.NULL, + self._backend._ffi.NULL, + self._evp_pkey, ) self._backend.openssl_assert(res == 1) @@ -52,7 +57,7 @@ def finalize(self): res = self._backend._lib.EVP_DigestSignFinal(self._ctx, buf, outlen) self._backend.openssl_assert(res != 0) self._backend.openssl_assert(outlen[0] == _POLY1305_TAG_SIZE) - return self._backend._ffi.buffer(buf)[:outlen[0]] + return self._backend._ffi.buffer(buf)[: outlen[0]] def verify(self, tag): mac = self.finalize() diff --git a/src/cryptography/hazmat/backends/openssl/rsa.py b/src/cryptography/hazmat/backends/openssl/rsa.py index a9e07b52fb97..5c1fda51749d 100644 --- a/src/cryptography/hazmat/backends/openssl/rsa.py +++ b/src/cryptography/hazmat/backends/openssl/rsa.py @@ -6,21 +6,32 @@ from cryptography import utils from cryptography.exceptions import ( - InvalidSignature, UnsupportedAlgorithm, _Reasons + InvalidSignature, + UnsupportedAlgorithm, + _Reasons, ) from cryptography.hazmat.backends.openssl.utils import ( - _calculate_digest_and_algorithm, _check_not_prehashed, - _warn_sign_verify_deprecated + _calculate_digest_and_algorithm, + _check_not_prehashed, + _warn_sign_verify_deprecated, ) from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import ( - AsymmetricSignatureContext, AsymmetricVerificationContext, rsa + AsymmetricSignatureContext, + AsymmetricVerificationContext, + rsa, ) from cryptography.hazmat.primitives.asymmetric.padding import ( - AsymmetricPadding, MGF1, OAEP, PKCS1v15, PSS, calculate_max_pss_salt_length + AsymmetricPadding, + MGF1, + OAEP, + PKCS1v15, + PSS, + calculate_max_pss_salt_length, ) from cryptography.hazmat.primitives.asymmetric.rsa import ( - RSAPrivateKeyWithSerialization, RSAPublicKeyWithSerialization + RSAPrivateKeyWithSerialization, + RSAPublicKeyWithSerialization, ) @@ -45,22 +56,20 @@ def _enc_dec_rsa(backend, key, data, padding): if not isinstance(padding._mgf, MGF1): raise UnsupportedAlgorithm( "Only MGF1 is supported by this backend.", - _Reasons.UNSUPPORTED_MGF + _Reasons.UNSUPPORTED_MGF, ) if not backend.rsa_padding_supported(padding): raise UnsupportedAlgorithm( "This combination of padding and hash algorithm is not " "supported by this backend.", - _Reasons.UNSUPPORTED_PADDING + _Reasons.UNSUPPORTED_PADDING, ) else: raise UnsupportedAlgorithm( - "{} is not supported by this backend.".format( - padding.name - ), - _Reasons.UNSUPPORTED_PADDING + "{} is not supported by this backend.".format(padding.name), + _Reasons.UNSUPPORTED_PADDING, ) return _enc_dec_rsa_pkey_ctx(backend, key, data, padding_enum, padding) @@ -74,24 +83,19 @@ def _enc_dec_rsa_pkey_ctx(backend, key, data, padding_enum, padding): init = backend._lib.EVP_PKEY_decrypt_init crypt = backend._lib.EVP_PKEY_decrypt - pkey_ctx = backend._lib.EVP_PKEY_CTX_new( - key._evp_pkey, backend._ffi.NULL - ) + pkey_ctx = backend._lib.EVP_PKEY_CTX_new(key._evp_pkey, backend._ffi.NULL) backend.openssl_assert(pkey_ctx != backend._ffi.NULL) pkey_ctx = backend._ffi.gc(pkey_ctx, backend._lib.EVP_PKEY_CTX_free) res = init(pkey_ctx) backend.openssl_assert(res == 1) - res = backend._lib.EVP_PKEY_CTX_set_rsa_padding( - pkey_ctx, padding_enum) + res = backend._lib.EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, padding_enum) backend.openssl_assert(res > 0) buf_size = backend._lib.EVP_PKEY_size(key._evp_pkey) backend.openssl_assert(buf_size > 0) - if ( - isinstance(padding, OAEP) and - backend._lib.Cryptography_HAS_RSA_OAEP_MD - ): + if isinstance(padding, OAEP) and backend._lib.Cryptography_HAS_RSA_OAEP_MD: mgf1_md = backend._evp_md_non_null_from_algorithm( - padding._mgf._algorithm) + padding._mgf._algorithm + ) res = backend._lib.EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, mgf1_md) backend.openssl_assert(res > 0) oaep_md = backend._evp_md_non_null_from_algorithm(padding._algorithm) @@ -99,9 +103,9 @@ def _enc_dec_rsa_pkey_ctx(backend, key, data, padding_enum, padding): backend.openssl_assert(res > 0) if ( - isinstance(padding, OAEP) and - padding._label is not None and - len(padding._label) > 0 + isinstance(padding, OAEP) + and padding._label is not None + and len(padding._label) > 0 ): # set0_rsa_oaep_label takes ownership of the char * so we need to # copy it into some new memory @@ -119,7 +123,7 @@ def _enc_dec_rsa_pkey_ctx(backend, key, data, padding_enum, padding): if res <= 0: _handle_rsa_enc_dec_error(backend, key) - return backend._ffi.buffer(buf)[:outlen[0]] + return backend._ffi.buffer(buf)[: outlen[0]] def _handle_rsa_enc_dec_error(backend, key): @@ -165,20 +169,22 @@ def _rsa_sig_determine_padding(backend, key, padding, algorithm): if not isinstance(padding._mgf, MGF1): raise UnsupportedAlgorithm( "Only MGF1 is supported by this backend.", - _Reasons.UNSUPPORTED_MGF + _Reasons.UNSUPPORTED_MGF, ) # Size of key in bytes - 2 is the maximum # PSS signature length (salt length is checked later) if pkey_size - algorithm.digest_size - 2 < 0: - raise ValueError("Digest too large for key size. Use a larger " - "key or different digest.") + raise ValueError( + "Digest too large for key size. Use a larger " + "key or different digest." + ) padding_enum = backend._lib.RSA_PKCS1_PSS_PADDING else: raise UnsupportedAlgorithm( "{} is not supported by this backend.".format(padding.name), - _Reasons.UNSUPPORTED_PADDING + _Reasons.UNSUPPORTED_PADDING, ) return padding_enum @@ -199,7 +205,7 @@ def _rsa_sig_setup(backend, padding, algorithm, key, data, init_func): "{} is not supported by this backend for RSA signing.".format( algorithm.name ), - _Reasons.UNSUPPORTED_HASH + _Reasons.UNSUPPORTED_HASH, ) res = backend._lib.EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, padding_enum) backend.openssl_assert(res > 0) @@ -210,7 +216,8 @@ def _rsa_sig_setup(backend, padding, algorithm, key, data, init_func): backend.openssl_assert(res > 0) mgf1_md = backend._evp_md_non_null_from_algorithm( - padding._mgf._algorithm) + padding._mgf._algorithm + ) res = backend._lib.EVP_PKEY_CTX_set_rsa_mgf1_md(pkey_ctx, mgf1_md) backend.openssl_assert(res > 0) @@ -219,34 +226,32 @@ def _rsa_sig_setup(backend, padding, algorithm, key, data, init_func): def _rsa_sig_sign(backend, padding, algorithm, private_key, data): pkey_ctx = _rsa_sig_setup( - backend, padding, algorithm, private_key, data, - backend._lib.EVP_PKEY_sign_init + backend, + padding, + algorithm, + private_key, + data, + backend._lib.EVP_PKEY_sign_init, ) buflen = backend._ffi.new("size_t *") res = backend._lib.EVP_PKEY_sign( - pkey_ctx, - backend._ffi.NULL, - buflen, - data, - len(data) + pkey_ctx, backend._ffi.NULL, buflen, data, len(data) ) backend.openssl_assert(res == 1) buf = backend._ffi.new("unsigned char[]", buflen[0]) - res = backend._lib.EVP_PKEY_sign( - pkey_ctx, buf, buflen, data, len(data)) + res = backend._lib.EVP_PKEY_sign(pkey_ctx, buf, buflen, data, len(data)) if res != 1: errors = backend._consume_errors() backend.openssl_assert(errors[0].lib == backend._lib.ERR_LIB_RSA) - if ( - errors[0].reason == - backend._lib.RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE - ): - reason = ("Salt length too long for key size. Try using " - "MAX_LENGTH instead.") + if errors[0].reason == backend._lib.RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE: + reason = ( + "Salt length too long for key size. Try using " + "MAX_LENGTH instead." + ) else: backend.openssl_assert( - errors[0].reason == - backend._lib.RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY + errors[0].reason + == backend._lib.RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY ) reason = "Digest too large for key size. Use a larger key." raise ValueError(reason) @@ -256,8 +261,12 @@ def _rsa_sig_sign(backend, padding, algorithm, private_key, data): def _rsa_sig_verify(backend, padding, algorithm, public_key, signature, data): pkey_ctx = _rsa_sig_setup( - backend, padding, algorithm, public_key, data, - backend._lib.EVP_PKEY_verify_init + backend, + padding, + algorithm, + public_key, + data, + backend._lib.EVP_PKEY_verify_init, ) res = backend._lib.EVP_PKEY_verify( pkey_ctx, signature, len(signature), data, len(data) @@ -294,7 +303,7 @@ def finalize(self): self._padding, self._algorithm, self._private_key, - self._hash_ctx.finalize() + self._hash_ctx.finalize(), ) @@ -324,7 +333,7 @@ def verify(self): self._algorithm, self._public_key, self._signature, - self._hash_ctx.finalize() + self._hash_ctx.finalize(), ) @@ -337,8 +346,10 @@ def __init__(self, backend, rsa_cdata, evp_pkey): n = self._backend._ffi.new("BIGNUM **") self._backend._lib.RSA_get0_key( - self._rsa_cdata, n, self._backend._ffi.NULL, - self._backend._ffi.NULL + self._rsa_cdata, + n, + self._backend._ffi.NULL, + self._backend._ffi.NULL, ) self._backend.openssl_assert(n[0] != self._backend._ffi.NULL) self._key_size = self._backend._lib.BN_num_bits(n[0]) @@ -398,7 +409,7 @@ def private_numbers(self): public_numbers=rsa.RSAPublicNumbers( e=self._backend._bn_to_int(e[0]), n=self._backend._bn_to_int(n[0]), - ) + ), ) def private_bytes(self, encoding, format, encryption_algorithm): @@ -408,7 +419,7 @@ def private_bytes(self, encoding, format, encryption_algorithm): encryption_algorithm, self, self._evp_pkey, - self._rsa_cdata + self._rsa_cdata, ) def sign(self, data, padding, algorithm): @@ -427,8 +438,10 @@ def __init__(self, backend, rsa_cdata, evp_pkey): n = self._backend._ffi.new("BIGNUM **") self._backend._lib.RSA_get0_key( - self._rsa_cdata, n, self._backend._ffi.NULL, - self._backend._ffi.NULL + self._rsa_cdata, + n, + self._backend._ffi.NULL, + self._backend._ffi.NULL, ) self._backend.openssl_assert(n[0] != self._backend._ffi.NULL) self._key_size = self._backend._lib.BN_num_bits(n[0]) @@ -456,17 +469,12 @@ def public_numbers(self): self._backend.openssl_assert(n[0] != self._backend._ffi.NULL) self._backend.openssl_assert(e[0] != self._backend._ffi.NULL) return rsa.RSAPublicNumbers( - e=self._backend._bn_to_int(e[0]), - n=self._backend._bn_to_int(n[0]), + e=self._backend._bn_to_int(e[0]), n=self._backend._bn_to_int(n[0]), ) def public_bytes(self, encoding, format): return self._backend._public_key_bytes( - encoding, - format, - self, - self._evp_pkey, - self._rsa_cdata + encoding, format, self, self._evp_pkey, self._rsa_cdata ) def verify(self, signature, data, padding, algorithm): diff --git a/src/cryptography/hazmat/backends/openssl/utils.py b/src/cryptography/hazmat/backends/openssl/utils.py index ee472c0e665c..ec0b947a44c6 100644 --- a/src/cryptography/hazmat/backends/openssl/utils.py +++ b/src/cryptography/hazmat/backends/openssl/utils.py @@ -17,9 +17,7 @@ def _evp_pkey_derive(backend, evp_pkey, peer_public_key): ctx = backend._ffi.gc(ctx, backend._lib.EVP_PKEY_CTX_free) res = backend._lib.EVP_PKEY_derive_init(ctx) backend.openssl_assert(res == 1) - res = backend._lib.EVP_PKEY_derive_set_peer( - ctx, peer_public_key._evp_pkey - ) + res = backend._lib.EVP_PKEY_derive_set_peer(ctx, peer_public_key._evp_pkey) backend.openssl_assert(res == 1) keylen = backend._ffi.new("size_t *") res = backend._lib.EVP_PKEY_derive(ctx, backend._ffi.NULL, keylen) @@ -28,9 +26,7 @@ def _evp_pkey_derive(backend, evp_pkey, peer_public_key): buf = backend._ffi.new("unsigned char[]", keylen[0]) res = backend._lib.EVP_PKEY_derive(ctx, buf, keylen) if res != 1: - raise ValueError( - "Null shared key derived from public/private pair." - ) + raise ValueError("Null shared key derived from public/private pair.") return backend._ffi.buffer(buf, keylen[0])[:] @@ -65,5 +61,5 @@ def _warn_sign_verify_deprecated(): "signer and verifier have been deprecated. Please use sign " "and verify instead.", utils.PersistentlyDeprecated2017, - stacklevel=3 + stacklevel=3, ) diff --git a/src/cryptography/hazmat/backends/openssl/x25519.py b/src/cryptography/hazmat/backends/openssl/x25519.py index 665acf2fffc8..4971c5481402 100644 --- a/src/cryptography/hazmat/backends/openssl/x25519.py +++ b/src/cryptography/hazmat/backends/openssl/x25519.py @@ -8,7 +8,8 @@ from cryptography.hazmat.backends.openssl.utils import _evp_pkey_derive from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric.x25519 import ( - X25519PrivateKey, X25519PublicKey + X25519PrivateKey, + X25519PublicKey, ) @@ -23,12 +24,12 @@ def __init__(self, backend, evp_pkey): def public_bytes(self, encoding, format): if ( - encoding is serialization.Encoding.Raw or - format is serialization.PublicFormat.Raw + encoding is serialization.Encoding.Raw + or format is serialization.PublicFormat.Raw ): if ( - encoding is not serialization.Encoding.Raw or - format is not serialization.PublicFormat.Raw + encoding is not serialization.Encoding.Raw + or format is not serialization.PublicFormat.Raw ): raise ValueError( "When using Raw both encoding and format must be Raw" @@ -76,19 +77,19 @@ def exchange(self, peer_public_key): if not isinstance(peer_public_key, X25519PublicKey): raise TypeError("peer_public_key must be X25519PublicKey.") - return _evp_pkey_derive( - self._backend, self._evp_pkey, peer_public_key - ) + return _evp_pkey_derive(self._backend, self._evp_pkey, peer_public_key) def private_bytes(self, encoding, format, encryption_algorithm): if ( - encoding is serialization.Encoding.Raw or - format is serialization.PublicFormat.Raw + encoding is serialization.Encoding.Raw + or format is serialization.PublicFormat.Raw ): if ( - format is not serialization.PrivateFormat.Raw or - encoding is not serialization.Encoding.Raw or not - isinstance(encryption_algorithm, serialization.NoEncryption) + format is not serialization.PrivateFormat.Raw + or encoding is not serialization.Encoding.Raw + or not isinstance( + encryption_algorithm, serialization.NoEncryption + ) ): raise ValueError( "When using Raw both encoding and format must be Raw " @@ -108,9 +109,13 @@ def _raw_private_bytes(self): # using the last 32 bytes, which is the key itself. bio = self._backend._create_mem_bio_gc() res = self._backend._lib.i2d_PKCS8PrivateKey_bio( - bio, self._evp_pkey, - self._backend._ffi.NULL, self._backend._ffi.NULL, - 0, self._backend._ffi.NULL, self._backend._ffi.NULL + bio, + self._evp_pkey, + self._backend._ffi.NULL, + self._backend._ffi.NULL, + 0, + self._backend._ffi.NULL, + self._backend._ffi.NULL, ) self._backend.openssl_assert(res == 1) pkcs8 = self._backend._read_mem_bio(bio) diff --git a/src/cryptography/hazmat/backends/openssl/x448.py b/src/cryptography/hazmat/backends/openssl/x448.py index 3de35b433493..7ebcdf84bcc2 100644 --- a/src/cryptography/hazmat/backends/openssl/x448.py +++ b/src/cryptography/hazmat/backends/openssl/x448.py @@ -8,7 +8,8 @@ from cryptography.hazmat.backends.openssl.utils import _evp_pkey_derive from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric.x448 import ( - X448PrivateKey, X448PublicKey + X448PrivateKey, + X448PublicKey, ) _X448_KEY_SIZE = 56 @@ -22,12 +23,12 @@ def __init__(self, backend, evp_pkey): def public_bytes(self, encoding, format): if ( - encoding is serialization.Encoding.Raw or - format is serialization.PublicFormat.Raw + encoding is serialization.Encoding.Raw + or format is serialization.PublicFormat.Raw ): if ( - encoding is not serialization.Encoding.Raw or - format is not serialization.PublicFormat.Raw + encoding is not serialization.Encoding.Raw + or format is not serialization.PublicFormat.Raw ): raise ValueError( "When using Raw both encoding and format must be Raw" @@ -70,19 +71,19 @@ def exchange(self, peer_public_key): if not isinstance(peer_public_key, X448PublicKey): raise TypeError("peer_public_key must be X448PublicKey.") - return _evp_pkey_derive( - self._backend, self._evp_pkey, peer_public_key - ) + return _evp_pkey_derive(self._backend, self._evp_pkey, peer_public_key) def private_bytes(self, encoding, format, encryption_algorithm): if ( - encoding is serialization.Encoding.Raw or - format is serialization.PublicFormat.Raw + encoding is serialization.Encoding.Raw + or format is serialization.PublicFormat.Raw ): if ( - format is not serialization.PrivateFormat.Raw or - encoding is not serialization.Encoding.Raw or not - isinstance(encryption_algorithm, serialization.NoEncryption) + format is not serialization.PrivateFormat.Raw + or encoding is not serialization.Encoding.Raw + or not isinstance( + encryption_algorithm, serialization.NoEncryption + ) ): raise ValueError( "When using Raw both encoding and format must be Raw " diff --git a/src/cryptography/hazmat/backends/openssl/x509.py b/src/cryptography/hazmat/backends/openssl/x509.py index 9b3982707856..ce643254f2a6 100644 --- a/src/cryptography/hazmat/backends/openssl/x509.py +++ b/src/cryptography/hazmat/backends/openssl/x509.py @@ -10,13 +10,20 @@ from cryptography import utils, x509 from cryptography.exceptions import UnsupportedAlgorithm from cryptography.hazmat.backends.openssl.decode_asn1 import ( - _CERTIFICATE_EXTENSION_PARSER, _CERTIFICATE_EXTENSION_PARSER_NO_SCT, - _CRL_EXTENSION_PARSER, _CSR_EXTENSION_PARSER, - _REVOKED_CERTIFICATE_EXTENSION_PARSER, _asn1_integer_to_int, - _asn1_string_to_bytes, _decode_x509_name, _obj2txt, _parse_asn1_time + _CERTIFICATE_EXTENSION_PARSER, + _CERTIFICATE_EXTENSION_PARSER_NO_SCT, + _CRL_EXTENSION_PARSER, + _CSR_EXTENSION_PARSER, + _REVOKED_CERTIFICATE_EXTENSION_PARSER, + _asn1_integer_to_int, + _asn1_string_to_bytes, + _decode_x509_name, + _obj2txt, + _parse_asn1_time, ) from cryptography.hazmat.backends.openssl.encode_asn1 import ( - _encode_asn1_int_gc, _txt2obj_gc + _encode_asn1_int_gc, + _txt2obj_gc, ) from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import dsa, ec, rsa @@ -195,7 +202,7 @@ def revocation_date(self): self._backend, self._backend._lib.X509_REVOKED_get0_revocationDate( self._x509_revoked - ) + ), ) @utils.cached_property @@ -224,9 +231,7 @@ def __ne__(self, other): def fingerprint(self, algorithm): h = hashes.Hash(algorithm, self._backend) bio = self._backend._create_mem_bio_gc() - res = self._backend._lib.i2d_X509_CRL_bio( - bio, self._x509_crl - ) + res = self._backend._lib.i2d_X509_CRL_bio(bio, self._x509_crl) self._backend.openssl_assert(res == 1) der = self._backend._read_mem_bio(bio) h.update(der) @@ -251,9 +256,7 @@ def get_revoked_certificate_by_serial_number(self, serial_number): if res == 0: return None else: - self._backend.openssl_assert( - revoked[0] != self._backend._ffi.NULL - ) + self._backend.openssl_assert(revoked[0] != self._backend._ffi.NULL) return _RevokedCertificate( self._backend, self._sorted_crl, revoked[0] ) @@ -363,10 +366,14 @@ def extensions(self): return _CRL_EXTENSION_PARSER.parse(self._backend, self._x509_crl) def is_signature_valid(self, public_key): - if not isinstance(public_key, (dsa.DSAPublicKey, rsa.RSAPublicKey, - ec.EllipticCurvePublicKey)): - raise TypeError('Expecting one of DSAPublicKey, RSAPublicKey,' - ' or EllipticCurvePublicKey.') + if not isinstance( + public_key, + (dsa.DSAPublicKey, rsa.RSAPublicKey, ec.EllipticCurvePublicKey), + ): + raise TypeError( + "Expecting one of DSAPublicKey, RSAPublicKey," + " or EllipticCurvePublicKey." + ) res = self._backend._lib.X509_CRL_verify( self._x509_crl, public_key._evp_pkey ) @@ -436,10 +443,11 @@ def extensions(self): x509_exts = self._backend._ffi.gc( x509_exts, lambda x: self._backend._lib.sk_X509_EXTENSION_pop_free( - x, self._backend._ffi.addressof( + x, + self._backend._ffi.addressof( self._backend._lib._original_lib, "X509_EXTENSION_free" - ) - ) + ), + ), ) return _CSR_EXTENSION_PARSER.parse(self._backend, x509_exts) @@ -515,9 +523,11 @@ def get_attribute_for_oid(self, oid): _ASN1Type.PrintableString.value, _ASN1Type.IA5String.value, ): - raise ValueError("OID {} has a disallowed ASN.1 type: {}".format( - oid, asn1_type.type - )) + raise ValueError( + "OID {} has a disallowed ASN.1 type: {}".format( + oid, asn1_type.type + ) + ) data = self._backend._lib.X509_ATTRIBUTE_get0_data( attr, 0, asn1_type.type, self._backend._ffi.NULL @@ -556,9 +566,9 @@ def log_id(self): def timestamp(self): timestamp = self._backend._lib.SCT_get_timestamp(self._sct) milliseconds = timestamp % 1000 - return datetime.datetime.utcfromtimestamp( - timestamp // 1000 - ).replace(microsecond=milliseconds * 1000) + return datetime.datetime.utcfromtimestamp(timestamp // 1000).replace( + microsecond=milliseconds * 1000 + ) @property def entry_type(self): diff --git a/src/cryptography/hazmat/bindings/openssl/_conditional.py b/src/cryptography/hazmat/bindings/openssl/_conditional.py index 3bc879c43c0e..3e0c235cb499 100644 --- a/src/cryptography/hazmat/bindings/openssl/_conditional.py +++ b/src/cryptography/hazmat/bindings/openssl/_conditional.py @@ -14,9 +14,7 @@ def cryptography_has_ec2m(): def cryptography_has_rsa_r_pkcs_decoding_error(): - return [ - "RSA_R_PKCS_DECODING_ERROR" - ] + return ["RSA_R_PKCS_DECODING_ERROR"] def cryptography_has_rsa_oaep_md(): @@ -49,12 +47,12 @@ def cryptography_has_compression(): def cryptography_has_102_verification(): return [ - 'X509_V_ERR_SUITE_B_INVALID_VERSION', - 'X509_V_ERR_SUITE_B_INVALID_ALGORITHM', - 'X509_V_ERR_SUITE_B_INVALID_CURVE', - 'X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM', - 'X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED', - 'X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256', + "X509_V_ERR_SUITE_B_INVALID_VERSION", + "X509_V_ERR_SUITE_B_INVALID_ALGORITHM", + "X509_V_ERR_SUITE_B_INVALID_CURVE", + "X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM", + "X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED", + "X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256", "X509_V_FLAG_SUITEB_128_LOS_ONLY", "X509_V_FLAG_SUITEB_192_LOS", "X509_V_FLAG_SUITEB_128_LOS", @@ -62,9 +60,7 @@ def cryptography_has_102_verification(): def cryptography_has_110_verification_params(): - return [ - "X509_CHECK_FLAG_NEVER_CHECK_SUBJECT" - ] + return ["X509_CHECK_FLAG_NEVER_CHECK_SUBJECT"] def cryptography_has_set_cert_cb(): diff --git a/src/cryptography/hazmat/bindings/openssl/binding.py b/src/cryptography/hazmat/bindings/openssl/binding.py index 6c025433d179..fbe5ca9a5dad 100644 --- a/src/cryptography/hazmat/bindings/openssl/binding.py +++ b/src/cryptography/hazmat/bindings/openssl/binding.py @@ -74,7 +74,7 @@ def _openssl_assert(lib, ok): "please file an issue at https://github.com/pyca/cryptography/" "issues with information on how to reproduce " "this. ({0!r})".format(errors_with_text), - errors_with_text + errors_with_text, ) @@ -97,6 +97,7 @@ class Binding(object): """ OpenSSL API wrapper. """ + lib = None ffi = ffi _lib_loaded = False @@ -140,8 +141,10 @@ def init_static_locks(cls): # the setup for this. __import__("_ssl") - if (not cls.lib.Cryptography_HAS_LOCKING_CALLBACKS or - cls.lib.CRYPTO_get_locking_callback() != cls.ffi.NULL): + if ( + not cls.lib.Cryptography_HAS_LOCKING_CALLBACKS + or cls.lib.CRYPTO_get_locking_callback() != cls.ffi.NULL + ): return # If nothing else has setup a locking callback already, we set up diff --git a/src/cryptography/hazmat/primitives/asymmetric/dh.py b/src/cryptography/hazmat/primitives/asymmetric/dh.py index 4fc995245d95..4e583f3c957a 100644 --- a/src/cryptography/hazmat/primitives/asymmetric/dh.py +++ b/src/cryptography/hazmat/primitives/asymmetric/dh.py @@ -21,8 +21,9 @@ def __init__(self, x, public_numbers): raise TypeError("x must be an integer.") if not isinstance(public_numbers, DHPublicNumbers): - raise TypeError("public_numbers must be an instance of " - "DHPublicNumbers.") + raise TypeError( + "public_numbers must be an instance of " "DHPublicNumbers." + ) self._x = x self._public_numbers = public_numbers @@ -32,8 +33,8 @@ def __eq__(self, other): return NotImplemented return ( - self._x == other._x and - self._public_numbers == other._public_numbers + self._x == other._x + and self._public_numbers == other._public_numbers ) def __ne__(self, other): @@ -53,7 +54,8 @@ def __init__(self, y, parameter_numbers): if not isinstance(parameter_numbers, DHParameterNumbers): raise TypeError( - "parameters must be an instance of DHParameterNumbers.") + "parameters must be an instance of DHParameterNumbers." + ) self._y = y self._parameter_numbers = parameter_numbers @@ -63,8 +65,8 @@ def __eq__(self, other): return NotImplemented return ( - self._y == other._y and - self._parameter_numbers == other._parameter_numbers + self._y == other._y + and self._parameter_numbers == other._parameter_numbers ) def __ne__(self, other): @@ -79,9 +81,8 @@ def public_key(self, backend): class DHParameterNumbers(object): def __init__(self, p, g, q=None): - if ( - not isinstance(p, six.integer_types) or - not isinstance(g, six.integer_types) + if not isinstance(p, six.integer_types) or not isinstance( + g, six.integer_types ): raise TypeError("p and g must be integers") if q is not None and not isinstance(q, six.integer_types): @@ -99,9 +100,7 @@ def __eq__(self, other): return NotImplemented return ( - self._p == other._p and - self._g == other._g and - self._q == other._q + self._p == other._p and self._g == other._g and self._q == other._q ) def __ne__(self, other): diff --git a/src/cryptography/hazmat/primitives/asymmetric/dsa.py b/src/cryptography/hazmat/primitives/asymmetric/dsa.py index 678b9d4943f4..fadedfa46ff4 100644 --- a/src/cryptography/hazmat/primitives/asymmetric/dsa.py +++ b/src/cryptography/hazmat/primitives/asymmetric/dsa.py @@ -152,9 +152,9 @@ def _check_dsa_private_numbers(numbers): class DSAParameterNumbers(object): def __init__(self, p, q, g): if ( - not isinstance(p, six.integer_types) or - not isinstance(q, six.integer_types) or - not isinstance(g, six.integer_types) + not isinstance(p, six.integer_types) + or not isinstance(q, six.integer_types) + or not isinstance(g, six.integer_types) ): raise TypeError( "DSAParameterNumbers p, q, and g arguments must be integers." @@ -182,9 +182,8 @@ def __ne__(self, other): def __repr__(self): return ( - "".format( - self=self - ) + "".format(self=self) ) @@ -212,8 +211,8 @@ def __eq__(self, other): return NotImplemented return ( - self.y == other.y and - self.parameter_numbers == other.parameter_numbers + self.y == other.y + and self.parameter_numbers == other.parameter_numbers ) def __ne__(self, other): diff --git a/src/cryptography/hazmat/primitives/asymmetric/ec.py b/src/cryptography/hazmat/primitives/asymmetric/ec.py index eef922dccbd1..aaa415107f6f 100644 --- a/src/cryptography/hazmat/primitives/asymmetric/ec.py +++ b/src/cryptography/hazmat/primitives/asymmetric/ec.py @@ -166,6 +166,7 @@ def from_encoded_point(cls, curve, data): raise ValueError("Unsupported elliptic curve point type") from cryptography.hazmat.backends.openssl.backend import backend + return backend.load_elliptic_curve_public_bytes(curve, data) @@ -289,26 +290,22 @@ class BrainpoolP512R1(object): _CURVE_TYPES = { "prime192v1": SECP192R1, "prime256v1": SECP256R1, - "secp192r1": SECP192R1, "secp224r1": SECP224R1, "secp256r1": SECP256R1, "secp384r1": SECP384R1, "secp521r1": SECP521R1, "secp256k1": SECP256K1, - "sect163k1": SECT163K1, "sect233k1": SECT233K1, "sect283k1": SECT283K1, "sect409k1": SECT409K1, "sect571k1": SECT571K1, - "sect163r2": SECT163R2, "sect233r1": SECT233R1, "sect283r1": SECT283R1, "sect409r1": SECT409R1, "sect571r1": SECT571R1, - "brainpoolP256r1": BrainpoolP256R1, "brainpoolP384r1": BrainpoolP384R1, "brainpoolP512r1": BrainpoolP512R1, @@ -342,9 +339,8 @@ def derive_private_key(private_value, curve, backend): class EllipticCurvePublicNumbers(object): def __init__(self, x, y, curve): - if ( - not isinstance(x, six.integer_types) or - not isinstance(y, six.integer_types) + if not isinstance(x, six.integer_types) or not isinstance( + y, six.integer_types ): raise TypeError("x and y must be integers.") @@ -370,8 +366,9 @@ def encode_point(self): # key_size is in bits. Convert to bytes and round up byte_length = (self.curve.key_size + 7) // 8 return ( - b'\x04' + utils.int_to_bytes(self.x, byte_length) + - utils.int_to_bytes(self.y, byte_length) + b"\x04" + + utils.int_to_bytes(self.x, byte_length) + + utils.int_to_bytes(self.y, byte_length) ) @classmethod @@ -387,17 +384,17 @@ def from_encoded_point(cls, curve, data): stacklevel=2, ) - if data.startswith(b'\x04'): + if data.startswith(b"\x04"): # key_size is in bits. Convert to bytes and round up byte_length = (curve.key_size + 7) // 8 if len(data) == 2 * byte_length + 1: - x = utils.int_from_bytes(data[1:byte_length + 1], 'big') - y = utils.int_from_bytes(data[byte_length + 1:], 'big') + x = utils.int_from_bytes(data[1 : byte_length + 1], "big") + y = utils.int_from_bytes(data[byte_length + 1 :], "big") return cls(x, y, curve) else: - raise ValueError('Invalid elliptic curve point data length') + raise ValueError("Invalid elliptic curve point data length") else: - raise ValueError('Unsupported elliptic curve point type') + raise ValueError("Unsupported elliptic curve point type") curve = utils.read_only_property("_curve") x = utils.read_only_property("_x") @@ -408,10 +405,10 @@ def __eq__(self, other): return NotImplemented return ( - self.x == other.x and - self.y == other.y and - self.curve.name == other.curve.name and - self.curve.key_size == other.curve.key_size + self.x == other.x + and self.y == other.y + and self.curve.name == other.curve.name + and self.curve.key_size == other.curve.key_size ) def __ne__(self, other): @@ -452,8 +449,8 @@ def __eq__(self, other): return NotImplemented return ( - self.private_value == other.private_value and - self.public_numbers == other.public_numbers + self.private_value == other.private_value + and self.public_numbers == other.public_numbers ) def __ne__(self, other): diff --git a/src/cryptography/hazmat/primitives/asymmetric/ed25519.py b/src/cryptography/hazmat/primitives/asymmetric/ed25519.py index d89445fa29d9..2d07a029bc73 100644 --- a/src/cryptography/hazmat/primitives/asymmetric/ed25519.py +++ b/src/cryptography/hazmat/primitives/asymmetric/ed25519.py @@ -20,10 +20,11 @@ class Ed25519PublicKey(object): @classmethod def from_public_bytes(cls, data): from cryptography.hazmat.backends.openssl.backend import backend + if not backend.ed25519_supported(): raise UnsupportedAlgorithm( "ed25519 is not supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, ) return backend.ed25519_load_public_bytes(data) @@ -46,10 +47,11 @@ class Ed25519PrivateKey(object): @classmethod def generate(cls): from cryptography.hazmat.backends.openssl.backend import backend + if not backend.ed25519_supported(): raise UnsupportedAlgorithm( "ed25519 is not supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, ) return backend.ed25519_generate_key() @@ -57,10 +59,11 @@ def generate(cls): @classmethod def from_private_bytes(cls, data): from cryptography.hazmat.backends.openssl.backend import backend + if not backend.ed25519_supported(): raise UnsupportedAlgorithm( "ed25519 is not supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, ) return backend.ed25519_load_private_bytes(data) diff --git a/src/cryptography/hazmat/primitives/asymmetric/ed448.py b/src/cryptography/hazmat/primitives/asymmetric/ed448.py index 939157ab5901..520ffcbcbcb6 100644 --- a/src/cryptography/hazmat/primitives/asymmetric/ed448.py +++ b/src/cryptography/hazmat/primitives/asymmetric/ed448.py @@ -16,10 +16,11 @@ class Ed448PublicKey(object): @classmethod def from_public_bytes(cls, data): from cryptography.hazmat.backends.openssl.backend import backend + if not backend.ed448_supported(): raise UnsupportedAlgorithm( "ed448 is not supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, ) return backend.ed448_load_public_bytes(data) @@ -42,20 +43,22 @@ class Ed448PrivateKey(object): @classmethod def generate(cls): from cryptography.hazmat.backends.openssl.backend import backend + if not backend.ed448_supported(): raise UnsupportedAlgorithm( "ed448 is not supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, ) return backend.ed448_generate_key() @classmethod def from_private_bytes(cls, data): from cryptography.hazmat.backends.openssl.backend import backend + if not backend.ed448_supported(): raise UnsupportedAlgorithm( "ed448 is not supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, ) return backend.ed448_load_private_bytes(data) diff --git a/src/cryptography/hazmat/primitives/asymmetric/padding.py b/src/cryptography/hazmat/primitives/asymmetric/padding.py index 828e03bc2394..fc8f6e26a917 100644 --- a/src/cryptography/hazmat/primitives/asymmetric/padding.py +++ b/src/cryptography/hazmat/primitives/asymmetric/padding.py @@ -35,8 +35,10 @@ class PSS(object): def __init__(self, mgf, salt_length): self._mgf = mgf - if (not isinstance(salt_length, six.integer_types) and - salt_length is not self.MAX_LENGTH): + if ( + not isinstance(salt_length, six.integer_types) + and salt_length is not self.MAX_LENGTH + ): raise TypeError("salt_length must be an integer.") if salt_length is not self.MAX_LENGTH and salt_length < 0: diff --git a/src/cryptography/hazmat/primitives/asymmetric/rsa.py b/src/cryptography/hazmat/primitives/asymmetric/rsa.py index 640577ad3f2f..ea8b523d0967 100644 --- a/src/cryptography/hazmat/primitives/asymmetric/rsa.py +++ b/src/cryptography/hazmat/primitives/asymmetric/rsa.py @@ -5,6 +5,7 @@ from __future__ import absolute_import, division, print_function import abc + try: # Only available in math in 3.5+ from math import gcd @@ -112,7 +113,7 @@ def generate_private_key(public_exponent, key_size, backend): if not isinstance(backend, RSABackend): raise UnsupportedAlgorithm( "Backend object does not implement RSABackend.", - _Reasons.BACKEND_MISSING_INTERFACE + _Reasons.BACKEND_MISSING_INTERFACE, ) _verify_rsa_parameters(public_exponent, key_size) @@ -130,8 +131,9 @@ def _verify_rsa_parameters(public_exponent, key_size): raise ValueError("key_size must be at least 512-bits.") -def _check_private_key_components(p, q, private_exponent, dmp1, dmq1, iqmp, - public_exponent, modulus): +def _check_private_key_components( + p, q, private_exponent, dmp1, dmq1, iqmp, public_exponent, modulus +): if modulus < 3: raise ValueError("modulus must be >= 3.") @@ -266,15 +268,14 @@ def rsa_recover_prime_factors(n, e, d): class RSAPrivateNumbers(object): - def __init__(self, p, q, d, dmp1, dmq1, iqmp, - public_numbers): + def __init__(self, p, q, d, dmp1, dmq1, iqmp, public_numbers): if ( - not isinstance(p, six.integer_types) or - not isinstance(q, six.integer_types) or - not isinstance(d, six.integer_types) or - not isinstance(dmp1, six.integer_types) or - not isinstance(dmq1, six.integer_types) or - not isinstance(iqmp, six.integer_types) + not isinstance(p, six.integer_types) + or not isinstance(q, six.integer_types) + or not isinstance(d, six.integer_types) + or not isinstance(dmp1, six.integer_types) + or not isinstance(dmq1, six.integer_types) + or not isinstance(iqmp, six.integer_types) ): raise TypeError( "RSAPrivateNumbers p, q, d, dmp1, dmq1, iqmp arguments must" @@ -311,35 +312,36 @@ def __eq__(self, other): return NotImplemented return ( - self.p == other.p and - self.q == other.q and - self.d == other.d and - self.dmp1 == other.dmp1 and - self.dmq1 == other.dmq1 and - self.iqmp == other.iqmp and - self.public_numbers == other.public_numbers + self.p == other.p + and self.q == other.q + and self.d == other.d + and self.dmp1 == other.dmp1 + and self.dmq1 == other.dmq1 + and self.iqmp == other.iqmp + and self.public_numbers == other.public_numbers ) def __ne__(self, other): return not self == other def __hash__(self): - return hash(( - self.p, - self.q, - self.d, - self.dmp1, - self.dmq1, - self.iqmp, - self.public_numbers, - )) + return hash( + ( + self.p, + self.q, + self.d, + self.dmp1, + self.dmq1, + self.iqmp, + self.public_numbers, + ) + ) class RSAPublicNumbers(object): def __init__(self, e, n): - if ( - not isinstance(e, six.integer_types) or - not isinstance(n, six.integer_types) + if not isinstance(e, six.integer_types) or not isinstance( + n, six.integer_types ): raise TypeError("RSAPublicNumbers arguments must be integers.") diff --git a/src/cryptography/hazmat/primitives/asymmetric/utils.py b/src/cryptography/hazmat/primitives/asymmetric/utils.py index 14d2abee9a9c..5f9b677868db 100644 --- a/src/cryptography/hazmat/primitives/asymmetric/utils.py +++ b/src/cryptography/hazmat/primitives/asymmetric/utils.py @@ -6,7 +6,11 @@ from cryptography import utils from cryptography.hazmat._der import ( - DERReader, INTEGER, SEQUENCE, encode_der, encode_der_integer + DERReader, + INTEGER, + SEQUENCE, + encode_der, + encode_der_integer, ) from cryptography.hazmat.primitives import hashes diff --git a/src/cryptography/hazmat/primitives/asymmetric/x25519.py b/src/cryptography/hazmat/primitives/asymmetric/x25519.py index 61a95ffa9847..fc63691536e9 100644 --- a/src/cryptography/hazmat/primitives/asymmetric/x25519.py +++ b/src/cryptography/hazmat/primitives/asymmetric/x25519.py @@ -16,10 +16,11 @@ class X25519PublicKey(object): @classmethod def from_public_bytes(cls, data): from cryptography.hazmat.backends.openssl.backend import backend + if not backend.x25519_supported(): raise UnsupportedAlgorithm( "X25519 is not supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, ) return backend.x25519_load_public_bytes(data) @@ -36,20 +37,22 @@ class X25519PrivateKey(object): @classmethod def generate(cls): from cryptography.hazmat.backends.openssl.backend import backend + if not backend.x25519_supported(): raise UnsupportedAlgorithm( "X25519 is not supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, ) return backend.x25519_generate_key() @classmethod def from_private_bytes(cls, data): from cryptography.hazmat.backends.openssl.backend import backend + if not backend.x25519_supported(): raise UnsupportedAlgorithm( "X25519 is not supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, ) return backend.x25519_load_private_bytes(data) diff --git a/src/cryptography/hazmat/primitives/asymmetric/x448.py b/src/cryptography/hazmat/primitives/asymmetric/x448.py index 475e678ff98c..3ac067bfd5e0 100644 --- a/src/cryptography/hazmat/primitives/asymmetric/x448.py +++ b/src/cryptography/hazmat/primitives/asymmetric/x448.py @@ -16,10 +16,11 @@ class X448PublicKey(object): @classmethod def from_public_bytes(cls, data): from cryptography.hazmat.backends.openssl.backend import backend + if not backend.x448_supported(): raise UnsupportedAlgorithm( "X448 is not supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, ) return backend.x448_load_public_bytes(data) @@ -36,20 +37,22 @@ class X448PrivateKey(object): @classmethod def generate(cls): from cryptography.hazmat.backends.openssl.backend import backend + if not backend.x448_supported(): raise UnsupportedAlgorithm( "X448 is not supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, ) return backend.x448_generate_key() @classmethod def from_private_bytes(cls, data): from cryptography.hazmat.backends.openssl.backend import backend + if not backend.x448_supported(): raise UnsupportedAlgorithm( "X448 is not supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, ) return backend.x448_load_private_bytes(data) diff --git a/src/cryptography/hazmat/primitives/ciphers/__init__.py b/src/cryptography/hazmat/primitives/ciphers/__init__.py index 171b1c693b31..4380f72b2e2e 100644 --- a/src/cryptography/hazmat/primitives/ciphers/__init__.py +++ b/src/cryptography/hazmat/primitives/ciphers/__init__.py @@ -5,8 +5,13 @@ from __future__ import absolute_import, division, print_function from cryptography.hazmat.primitives.ciphers.base import ( - AEADCipherContext, AEADDecryptionContext, AEADEncryptionContext, - BlockCipherAlgorithm, Cipher, CipherAlgorithm, CipherContext + AEADCipherContext, + AEADDecryptionContext, + AEADEncryptionContext, + BlockCipherAlgorithm, + Cipher, + CipherAlgorithm, + CipherContext, ) diff --git a/src/cryptography/hazmat/primitives/ciphers/aead.py b/src/cryptography/hazmat/primitives/ciphers/aead.py index 72cb30c390cf..4eddc1ee6e37 100644 --- a/src/cryptography/hazmat/primitives/ciphers/aead.py +++ b/src/cryptography/hazmat/primitives/ciphers/aead.py @@ -18,7 +18,7 @@ def __init__(self, key): if not backend.aead_cipher_supported(self): raise exceptions.UnsupportedAlgorithm( "ChaCha20Poly1305 is not supported by this version of OpenSSL", - exceptions._Reasons.UNSUPPORTED_CIPHER + exceptions._Reasons.UNSUPPORTED_CIPHER, ) utils._check_byteslike("key", key) @@ -42,18 +42,14 @@ def encrypt(self, nonce, data, associated_data): ) self._check_params(nonce, data, associated_data) - return aead._encrypt( - backend, self, nonce, data, associated_data, 16 - ) + return aead._encrypt(backend, self, nonce, data, associated_data, 16) def decrypt(self, nonce, data, associated_data): if associated_data is None: associated_data = b"" self._check_params(nonce, data, associated_data) - return aead._decrypt( - backend, self, nonce, data, associated_data, 16 - ) + return aead._decrypt(backend, self, nonce, data, associated_data, 16) def _check_params(self, nonce, data, associated_data): utils._check_byteslike("nonce", nonce) @@ -161,18 +157,14 @@ def encrypt(self, nonce, data, associated_data): ) self._check_params(nonce, data, associated_data) - return aead._encrypt( - backend, self, nonce, data, associated_data, 16 - ) + return aead._encrypt(backend, self, nonce, data, associated_data, 16) def decrypt(self, nonce, data, associated_data): if associated_data is None: associated_data = b"" self._check_params(nonce, data, associated_data) - return aead._decrypt( - backend, self, nonce, data, associated_data, 16 - ) + return aead._decrypt(backend, self, nonce, data, associated_data, 16) def _check_params(self, nonce, data, associated_data): utils._check_byteslike("nonce", nonce) diff --git a/src/cryptography/hazmat/primitives/ciphers/algorithms.py b/src/cryptography/hazmat/primitives/ciphers/algorithms.py index f4d5160bb7e5..8072cedd1714 100644 --- a/src/cryptography/hazmat/primitives/ciphers/algorithms.py +++ b/src/cryptography/hazmat/primitives/ciphers/algorithms.py @@ -6,7 +6,8 @@ from cryptography import utils from cryptography.hazmat.primitives.ciphers import ( - BlockCipherAlgorithm, CipherAlgorithm + BlockCipherAlgorithm, + CipherAlgorithm, ) from cryptography.hazmat.primitives.ciphers.modes import ModeWithNonce @@ -17,9 +18,11 @@ def _verify_key_size(algorithm, key): # Verify that the key size matches the expected key size if len(key) * 8 not in algorithm.key_sizes: - raise ValueError("Invalid key size ({}) for {}.".format( - len(key) * 8, algorithm.name - )) + raise ValueError( + "Invalid key size ({}) for {}.".format( + len(key) * 8, algorithm.name + ) + ) return key diff --git a/src/cryptography/hazmat/primitives/ciphers/base.py b/src/cryptography/hazmat/primitives/ciphers/base.py index 4d5f8d60ff49..8adfa9d62120 100644 --- a/src/cryptography/hazmat/primitives/ciphers/base.py +++ b/src/cryptography/hazmat/primitives/ciphers/base.py @@ -10,8 +10,11 @@ from cryptography import utils from cryptography.exceptions import ( - AlreadyFinalized, AlreadyUpdated, NotYetFinalized, UnsupportedAlgorithm, - _Reasons + AlreadyFinalized, + AlreadyUpdated, + NotYetFinalized, + UnsupportedAlgorithm, + _Reasons, ) from cryptography.hazmat.backends.interfaces import CipherBackend from cryptography.hazmat.primitives.ciphers import modes @@ -98,7 +101,7 @@ def __init__(self, algorithm, mode, backend): if not isinstance(backend, CipherBackend): raise UnsupportedAlgorithm( "Backend object does not implement CipherBackend.", - _Reasons.BACKEND_MISSING_INTERFACE + _Reasons.BACKEND_MISSING_INTERFACE, ) if not isinstance(algorithm, CipherAlgorithm): @@ -230,6 +233,7 @@ class _AEADEncryptionContext(_AEADCipherContext): @property def tag(self): if self._ctx is not None: - raise NotYetFinalized("You must finalize encryption before " - "getting the tag.") + raise NotYetFinalized( + "You must finalize encryption before " "getting the tag." + ) return self._tag diff --git a/src/cryptography/hazmat/primitives/ciphers/modes.py b/src/cryptography/hazmat/primitives/ciphers/modes.py index 78fa1c48a53b..dcb24444214f 100644 --- a/src/cryptography/hazmat/primitives/ciphers/modes.py +++ b/src/cryptography/hazmat/primitives/ciphers/modes.py @@ -72,9 +72,11 @@ def _check_aes_key_length(self, algorithm): def _check_iv_length(self, algorithm): if len(self.initialization_vector) * 8 != algorithm.block_size: - raise ValueError("Invalid IV size ({}) for {}.".format( - len(self.initialization_vector), self.name - )) + raise ValueError( + "Invalid IV size ({}) for {}.".format( + len(self.initialization_vector), self.name + ) + ) def _check_iv_and_key_length(self, algorithm): @@ -178,9 +180,11 @@ def __init__(self, nonce): def validate_for_algorithm(self, algorithm): _check_aes_key_length(self, algorithm) if len(self.nonce) * 8 != algorithm.block_size: - raise ValueError("Invalid nonce size ({}) for {}.".format( - len(self.nonce), self.name - )) + raise ValueError( + "Invalid nonce size ({}) for {}.".format( + len(self.nonce), self.name + ) + ) @utils.register_interface(Mode) @@ -206,7 +210,8 @@ def __init__(self, initialization_vector, tag=None, min_tag_length=16): if len(tag) < min_tag_length: raise ValueError( "Authentication tag must be {} bytes or longer.".format( - min_tag_length) + min_tag_length + ) ) self._tag = tag self._min_tag_length = min_tag_length diff --git a/src/cryptography/hazmat/primitives/cmac.py b/src/cryptography/hazmat/primitives/cmac.py index 95a8d9756e45..edf9d5364df4 100644 --- a/src/cryptography/hazmat/primitives/cmac.py +++ b/src/cryptography/hazmat/primitives/cmac.py @@ -6,7 +6,9 @@ from cryptography import utils from cryptography.exceptions import ( - AlreadyFinalized, UnsupportedAlgorithm, _Reasons + AlreadyFinalized, + UnsupportedAlgorithm, + _Reasons, ) from cryptography.hazmat.backends.interfaces import CMACBackend from cryptography.hazmat.primitives import ciphers @@ -17,13 +19,11 @@ def __init__(self, algorithm, backend, ctx=None): if not isinstance(backend, CMACBackend): raise UnsupportedAlgorithm( "Backend object does not implement CMACBackend.", - _Reasons.BACKEND_MISSING_INTERFACE + _Reasons.BACKEND_MISSING_INTERFACE, ) if not isinstance(algorithm, ciphers.BlockCipherAlgorithm): - raise TypeError( - "Expected instance of BlockCipherAlgorithm." - ) + raise TypeError("Expected instance of BlockCipherAlgorithm.") self._algorithm = algorithm self._backend = backend @@ -58,7 +58,5 @@ def copy(self): if self._ctx is None: raise AlreadyFinalized("Context was already finalized.") return CMAC( - self._algorithm, - backend=self._backend, - ctx=self._ctx.copy() + self._algorithm, backend=self._backend, ctx=self._ctx.copy() ) diff --git a/src/cryptography/hazmat/primitives/hashes.py b/src/cryptography/hazmat/primitives/hashes.py index 9be2b60090a5..a39e5df4834a 100644 --- a/src/cryptography/hazmat/primitives/hashes.py +++ b/src/cryptography/hazmat/primitives/hashes.py @@ -10,7 +10,9 @@ from cryptography import utils from cryptography.exceptions import ( - AlreadyFinalized, UnsupportedAlgorithm, _Reasons + AlreadyFinalized, + UnsupportedAlgorithm, + _Reasons, ) from cryptography.hazmat.backends.interfaces import HashBackend @@ -70,7 +72,7 @@ def __init__(self, algorithm, backend, ctx=None): if not isinstance(backend, HashBackend): raise UnsupportedAlgorithm( "Backend object does not implement HashBackend.", - _Reasons.BACKEND_MISSING_INTERFACE + _Reasons.BACKEND_MISSING_INTERFACE, ) if not isinstance(algorithm, HashAlgorithm): diff --git a/src/cryptography/hazmat/primitives/hmac.py b/src/cryptography/hazmat/primitives/hmac.py index 9eceeac2a136..1dd32457f375 100644 --- a/src/cryptography/hazmat/primitives/hmac.py +++ b/src/cryptography/hazmat/primitives/hmac.py @@ -6,7 +6,9 @@ from cryptography import utils from cryptography.exceptions import ( - AlreadyFinalized, UnsupportedAlgorithm, _Reasons + AlreadyFinalized, + UnsupportedAlgorithm, + _Reasons, ) from cryptography.hazmat.backends.interfaces import HMACBackend from cryptography.hazmat.primitives import hashes @@ -18,7 +20,7 @@ def __init__(self, key, algorithm, backend, ctx=None): if not isinstance(backend, HMACBackend): raise UnsupportedAlgorithm( "Backend object does not implement HMACBackend.", - _Reasons.BACKEND_MISSING_INTERFACE + _Reasons.BACKEND_MISSING_INTERFACE, ) if not isinstance(algorithm, hashes.HashAlgorithm): @@ -47,7 +49,7 @@ def copy(self): self._key, self.algorithm, backend=self._backend, - ctx=self._ctx.copy() + ctx=self._ctx.copy(), ) def finalize(self): diff --git a/src/cryptography/hazmat/primitives/kdf/concatkdf.py b/src/cryptography/hazmat/primitives/kdf/concatkdf.py index 7cb63856b11f..f424689c9737 100644 --- a/src/cryptography/hazmat/primitives/kdf/concatkdf.py +++ b/src/cryptography/hazmat/primitives/kdf/concatkdf.py @@ -8,7 +8,10 @@ from cryptography import utils from cryptography.exceptions import ( - AlreadyFinalized, InvalidKey, UnsupportedAlgorithm, _Reasons + AlreadyFinalized, + InvalidKey, + UnsupportedAlgorithm, + _Reasons, ) from cryptography.hazmat.backends.interfaces import HMACBackend from cryptography.hazmat.backends.interfaces import HashBackend @@ -17,16 +20,15 @@ def _int_to_u32be(n): - return struct.pack('>I', n) + return struct.pack(">I", n) def _common_args_checks(algorithm, length, otherinfo): max_length = algorithm.digest_size * (2 ** 32 - 1) if length > max_length: raise ValueError( - "Can not derive keys larger than {} bits.".format( - max_length - )) + "Can not derive keys larger than {} bits.".format(max_length) + ) if otherinfo is not None: utils._check_bytes("otherinfo", otherinfo) @@ -37,7 +39,7 @@ def _concatkdf_derive(key_material, length, auxfn, otherinfo): outlen = 0 counter = 1 - while (length > outlen): + while length > outlen: h = auxfn() h.update(_int_to_u32be(counter)) h.update(key_material) @@ -63,7 +65,7 @@ def __init__(self, algorithm, length, otherinfo, backend): if not isinstance(backend, HashBackend): raise UnsupportedAlgorithm( "Backend object does not implement HashBackend.", - _Reasons.BACKEND_MISSING_INTERFACE + _Reasons.BACKEND_MISSING_INTERFACE, ) self._backend = backend self._used = False @@ -75,8 +77,9 @@ def derive(self, key_material): if self._used: raise AlreadyFinalized self._used = True - return _concatkdf_derive(key_material, self._length, - self._hash, self._otherinfo) + return _concatkdf_derive( + key_material, self._length, self._hash, self._otherinfo + ) def verify(self, key_material, expected_key): if not constant_time.bytes_eq(self.derive(key_material), expected_key): @@ -104,7 +107,7 @@ def __init__(self, algorithm, length, salt, otherinfo, backend): if not isinstance(backend, HMACBackend): raise UnsupportedAlgorithm( "Backend object does not implement HMACBackend.", - _Reasons.BACKEND_MISSING_INTERFACE + _Reasons.BACKEND_MISSING_INTERFACE, ) self._backend = backend self._used = False @@ -116,8 +119,9 @@ def derive(self, key_material): if self._used: raise AlreadyFinalized self._used = True - return _concatkdf_derive(key_material, self._length, - self._hmac, self._otherinfo) + return _concatkdf_derive( + key_material, self._length, self._hmac, self._otherinfo + ) def verify(self, key_material, expected_key): if not constant_time.bytes_eq(self.derive(key_material), expected_key): diff --git a/src/cryptography/hazmat/primitives/kdf/hkdf.py b/src/cryptography/hazmat/primitives/kdf/hkdf.py index 01f0f288b439..0a758044227e 100644 --- a/src/cryptography/hazmat/primitives/kdf/hkdf.py +++ b/src/cryptography/hazmat/primitives/kdf/hkdf.py @@ -8,7 +8,10 @@ from cryptography import utils from cryptography.exceptions import ( - AlreadyFinalized, InvalidKey, UnsupportedAlgorithm, _Reasons + AlreadyFinalized, + InvalidKey, + UnsupportedAlgorithm, + _Reasons, ) from cryptography.hazmat.backends.interfaces import HMACBackend from cryptography.hazmat.primitives import constant_time, hmac @@ -21,7 +24,7 @@ def __init__(self, algorithm, length, salt, info, backend): if not isinstance(backend, HMACBackend): raise UnsupportedAlgorithm( "Backend object does not implement HMACBackend.", - _Reasons.BACKEND_MISSING_INTERFACE + _Reasons.BACKEND_MISSING_INTERFACE, ) self._algorithm = algorithm @@ -57,7 +60,7 @@ def __init__(self, algorithm, length, info, backend): if not isinstance(backend, HMACBackend): raise UnsupportedAlgorithm( "Backend object does not implement HMACBackend.", - _Reasons.BACKEND_MISSING_INTERFACE + _Reasons.BACKEND_MISSING_INTERFACE, ) self._algorithm = algorithm @@ -68,9 +71,8 @@ def __init__(self, algorithm, length, info, backend): if length > max_length: raise ValueError( - "Can not derive keys larger than {} octets.".format( - max_length - )) + "Can not derive keys larger than {} octets.".format(max_length) + ) self._length = length @@ -95,7 +97,7 @@ def _expand(self, key_material): output.append(h.finalize()) counter += 1 - return b"".join(output)[:self._length] + return b"".join(output)[: self._length] def derive(self, key_material): utils._check_byteslike("key_material", key_material) diff --git a/src/cryptography/hazmat/primitives/kdf/kbkdf.py b/src/cryptography/hazmat/primitives/kdf/kbkdf.py index 56783a85cc5d..deb428919192 100644 --- a/src/cryptography/hazmat/primitives/kdf/kbkdf.py +++ b/src/cryptography/hazmat/primitives/kdf/kbkdf.py @@ -10,7 +10,10 @@ from cryptography import utils from cryptography.exceptions import ( - AlreadyFinalized, InvalidKey, UnsupportedAlgorithm, _Reasons + AlreadyFinalized, + InvalidKey, + UnsupportedAlgorithm, + _Reasons, ) from cryptography.hazmat.backends.interfaces import HMACBackend from cryptography.hazmat.primitives import constant_time, hashes, hmac @@ -28,24 +31,35 @@ class CounterLocation(Enum): @utils.register_interface(KeyDerivationFunction) class KBKDFHMAC(object): - def __init__(self, algorithm, mode, length, rlen, llen, - location, label, context, fixed, backend): + def __init__( + self, + algorithm, + mode, + length, + rlen, + llen, + location, + label, + context, + fixed, + backend, + ): if not isinstance(backend, HMACBackend): raise UnsupportedAlgorithm( "Backend object does not implement HMACBackend.", - _Reasons.BACKEND_MISSING_INTERFACE + _Reasons.BACKEND_MISSING_INTERFACE, ) if not isinstance(algorithm, hashes.HashAlgorithm): raise UnsupportedAlgorithm( "Algorithm supplied is not a supported hash algorithm.", - _Reasons.UNSUPPORTED_HASH + _Reasons.UNSUPPORTED_HASH, ) if not backend.hmac_supported(algorithm): raise UnsupportedAlgorithm( "Algorithm supplied is not a supported hmac algorithm.", - _Reasons.UNSUPPORTED_HASH + _Reasons.UNSUPPORTED_HASH, ) if not isinstance(mode, Mode): @@ -55,8 +69,9 @@ def __init__(self, algorithm, mode, length, rlen, llen, raise TypeError("location must be of type CounterLocation") if (label or context) and fixed: - raise ValueError("When supplying fixed data, " - "label and context are ignored.") + raise ValueError( + "When supplying fixed data, " "label and context are ignored." + ) if rlen is None or not self._valid_byte_length(rlen): raise ValueError("rlen must be between 1 and 4") @@ -68,10 +83,10 @@ def __init__(self, algorithm, mode, length, rlen, llen, raise TypeError("llen must be an integer") if label is None: - label = b'' + label = b"" if context is None: - context = b'' + context = b"" utils._check_bytes("label", label) utils._check_bytes("context", context) @@ -89,7 +104,7 @@ def __init__(self, algorithm, mode, length, rlen, llen, def _valid_byte_length(self, value): if not isinstance(value, int): - raise TypeError('value must be of type int') + raise TypeError("value must be of type int") value_bin = utils.int_to_bytes(1, value) if not 1 <= len(value_bin) <= 4: @@ -106,7 +121,7 @@ def derive(self, key_material): # inverse floor division (equivalent to ceiling) rounds = -(-self._length // self._algorithm.digest_size) - output = [b''] + output = [b""] # For counter mode, the number of iterations shall not be # larger than 2^r-1, where r <= 32 is the binary length of the counter @@ -114,7 +129,7 @@ def derive(self, key_material): # PRF will not repeat during a particular call to the KDF function. r_bin = utils.int_to_bytes(1, self._rlen) if rounds > pow(2, len(r_bin) * 8) - 1: - raise ValueError('There are too many iterations.') + raise ValueError("There are too many iterations.") for i in range(1, rounds + 1): h = hmac.HMAC(key_material, self._algorithm, backend=self._backend) @@ -130,7 +145,7 @@ def derive(self, key_material): output.append(h.finalize()) - return b''.join(output)[:self._length] + return b"".join(output)[: self._length] def _generate_fixed_input(self): if self._fixed_data and isinstance(self._fixed_data, bytes): diff --git a/src/cryptography/hazmat/primitives/kdf/pbkdf2.py b/src/cryptography/hazmat/primitives/kdf/pbkdf2.py index 07d8ac676866..1d82f2a64b77 100644 --- a/src/cryptography/hazmat/primitives/kdf/pbkdf2.py +++ b/src/cryptography/hazmat/primitives/kdf/pbkdf2.py @@ -6,7 +6,10 @@ from cryptography import utils from cryptography.exceptions import ( - AlreadyFinalized, InvalidKey, UnsupportedAlgorithm, _Reasons + AlreadyFinalized, + InvalidKey, + UnsupportedAlgorithm, + _Reasons, ) from cryptography.hazmat.backends.interfaces import PBKDF2HMACBackend from cryptography.hazmat.primitives import constant_time @@ -19,14 +22,15 @@ def __init__(self, algorithm, length, salt, iterations, backend): if not isinstance(backend, PBKDF2HMACBackend): raise UnsupportedAlgorithm( "Backend object does not implement PBKDF2HMACBackend.", - _Reasons.BACKEND_MISSING_INTERFACE + _Reasons.BACKEND_MISSING_INTERFACE, ) if not backend.pbkdf2_hmac_supported(algorithm): raise UnsupportedAlgorithm( "{} is not supported for PBKDF2 by this backend.".format( - algorithm.name), - _Reasons.UNSUPPORTED_HASH + algorithm.name + ), + _Reasons.UNSUPPORTED_HASH, ) self._used = False self._algorithm = algorithm @@ -47,7 +51,7 @@ def derive(self, key_material): self._length, self._salt, self._iterations, - key_material + key_material, ) def verify(self, key_material, expected_key): diff --git a/src/cryptography/hazmat/primitives/kdf/scrypt.py b/src/cryptography/hazmat/primitives/kdf/scrypt.py index df9745e68917..1fcc8f9d3643 100644 --- a/src/cryptography/hazmat/primitives/kdf/scrypt.py +++ b/src/cryptography/hazmat/primitives/kdf/scrypt.py @@ -8,7 +8,10 @@ from cryptography import utils from cryptography.exceptions import ( - AlreadyFinalized, InvalidKey, UnsupportedAlgorithm, _Reasons + AlreadyFinalized, + InvalidKey, + UnsupportedAlgorithm, + _Reasons, ) from cryptography.hazmat.backends.interfaces import ScryptBackend from cryptography.hazmat.primitives import constant_time @@ -26,7 +29,7 @@ def __init__(self, salt, length, n, r, p, backend): if not isinstance(backend, ScryptBackend): raise UnsupportedAlgorithm( "Backend object does not implement ScryptBackend.", - _Reasons.BACKEND_MISSING_INTERFACE + _Reasons.BACKEND_MISSING_INTERFACE, ) self._length = length diff --git a/src/cryptography/hazmat/primitives/kdf/x963kdf.py b/src/cryptography/hazmat/primitives/kdf/x963kdf.py index 9eb50b0f85fc..50c30b33d9fe 100644 --- a/src/cryptography/hazmat/primitives/kdf/x963kdf.py +++ b/src/cryptography/hazmat/primitives/kdf/x963kdf.py @@ -8,7 +8,10 @@ from cryptography import utils from cryptography.exceptions import ( - AlreadyFinalized, InvalidKey, UnsupportedAlgorithm, _Reasons + AlreadyFinalized, + InvalidKey, + UnsupportedAlgorithm, + _Reasons, ) from cryptography.hazmat.backends.interfaces import HashBackend from cryptography.hazmat.primitives import constant_time, hashes @@ -16,7 +19,7 @@ def _int_to_u32be(n): - return struct.pack('>I', n) + return struct.pack(">I", n) @utils.register_interface(KeyDerivationFunction) @@ -26,7 +29,8 @@ def __init__(self, algorithm, length, sharedinfo, backend): max_len = algorithm.digest_size * (2 ** 32 - 1) if length > max_len: raise ValueError( - "Can not derive keys larger than {} bits.".format(max_len)) + "Can not derive keys larger than {} bits.".format(max_len) + ) if sharedinfo is not None: utils._check_bytes("sharedinfo", sharedinfo) @@ -37,7 +41,7 @@ def __init__(self, algorithm, length, sharedinfo, backend): if not isinstance(backend, HashBackend): raise UnsupportedAlgorithm( "Backend object does not implement HashBackend.", - _Reasons.BACKEND_MISSING_INTERFACE + _Reasons.BACKEND_MISSING_INTERFACE, ) self._backend = backend self._used = False @@ -61,7 +65,7 @@ def derive(self, key_material): outlen += len(output[-1]) counter += 1 - return b"".join(output)[:self._length] + return b"".join(output)[: self._length] def verify(self, key_material, expected_key): if not constant_time.bytes_eq(self.derive(key_material), expected_key): diff --git a/src/cryptography/hazmat/primitives/keywrap.py b/src/cryptography/hazmat/primitives/keywrap.py index f55c519cff33..7ea16d876e45 100644 --- a/src/cryptography/hazmat/primitives/keywrap.py +++ b/src/cryptography/hazmat/primitives/keywrap.py @@ -44,7 +44,7 @@ def aes_key_wrap(wrapping_key, key_to_wrap, backend): raise ValueError("The key to wrap must be a multiple of 8 bytes") a = b"\xa6\xa6\xa6\xa6\xa6\xa6\xa6\xa6" - r = [key_to_wrap[i:i + 8] for i in range(0, len(key_to_wrap), 8)] + r = [key_to_wrap[i : i + 8] for i in range(0, len(key_to_wrap), 8)] return _wrap_core(wrapping_key, a, r, backend) @@ -55,9 +55,12 @@ def _unwrap_core(wrapping_key, a, r, backend): for j in reversed(range(6)): for i in reversed(range(n)): # pack/unpack are safe as these are always 64-bit chunks - atr = struct.pack( - ">Q", struct.unpack(">Q", a)[0] ^ ((n * j) + i + 1) - ) + r[i] + atr = ( + struct.pack( + ">Q", struct.unpack(">Q", a)[0] ^ ((n * j) + i + 1) + ) + + r[i] + ) # every decryption operation is a discrete 16 byte chunk so # it is safe to reuse the decryptor for the entire operation b = decryptor.update(atr) @@ -83,7 +86,7 @@ def aes_key_wrap_with_padding(wrapping_key, key_to_wrap, backend): assert encryptor.finalize() == b"" return b else: - r = [key_to_wrap[i:i + 8] for i in range(0, len(key_to_wrap), 8)] + r = [key_to_wrap[i : i + 8] for i in range(0, len(key_to_wrap), 8)] return _wrap_core(wrapping_key, aiv, r, backend) @@ -103,7 +106,7 @@ def aes_key_unwrap_with_padding(wrapping_key, wrapped_key, backend): data = b[8:] n = 1 else: - r = [wrapped_key[i:i + 8] for i in range(0, len(wrapped_key), 8)] + r = [wrapped_key[i : i + 8] for i in range(0, len(wrapped_key), 8)] encrypted_aiv = r.pop(0) n = len(r) a, r = _unwrap_core(wrapping_key, encrypted_aiv, r, backend) @@ -117,10 +120,9 @@ def aes_key_unwrap_with_padding(wrapping_key, wrapped_key, backend): (mli,) = struct.unpack(">I", a[4:]) b = (8 * n) - mli if ( - not bytes_eq(a[:4], b"\xa6\x59\x59\xa6") or not - 8 * (n - 1) < mli <= 8 * n or ( - b != 0 and not bytes_eq(data[-b:], b"\x00" * b) - ) + not bytes_eq(a[:4], b"\xa6\x59\x59\xa6") + or not 8 * (n - 1) < mli <= 8 * n + or (b != 0 and not bytes_eq(data[-b:], b"\x00" * b)) ): raise InvalidUnwrap() @@ -141,7 +143,7 @@ def aes_key_unwrap(wrapping_key, wrapped_key, backend): raise ValueError("The wrapping key must be a valid AES key length") aiv = b"\xa6\xa6\xa6\xa6\xa6\xa6\xa6\xa6" - r = [wrapped_key[i:i + 8] for i in range(0, len(wrapped_key), 8)] + r = [wrapped_key[i : i + 8] for i in range(0, len(wrapped_key), 8)] a = r.pop(0) a, r = _unwrap_core(wrapping_key, a, r, backend) if not bytes_eq(a, aiv): diff --git a/src/cryptography/hazmat/primitives/padding.py b/src/cryptography/hazmat/primitives/padding.py index 170c80218b12..95913614cb2d 100644 --- a/src/cryptography/hazmat/primitives/padding.py +++ b/src/cryptography/hazmat/primitives/padding.py @@ -46,8 +46,8 @@ def _byte_padding_update(buffer_, data, block_size): finished_blocks = len(buffer_) // (block_size // 8) - result = buffer_[:finished_blocks * (block_size // 8)] - buffer_ = buffer_[finished_blocks * (block_size // 8):] + result = buffer_[: finished_blocks * (block_size // 8)] + buffer_ = buffer_[finished_blocks * (block_size // 8) :] return buffer_, result @@ -70,8 +70,8 @@ def _byte_unpadding_update(buffer_, data, block_size): finished_blocks = max(len(buffer_) // (block_size // 8) - 1, 0) - result = buffer_[:finished_blocks * (block_size // 8)] - buffer_ = buffer_[finished_blocks * (block_size // 8):] + result = buffer_[: finished_blocks * (block_size // 8)] + buffer_ = buffer_[finished_blocks * (block_size // 8) :] return buffer_, result @@ -113,7 +113,8 @@ def __init__(self, block_size): def update(self, data): self._buffer, result = _byte_padding_update( - self._buffer, data, self.block_size) + self._buffer, data, self.block_size + ) return result def _padding(self, size): @@ -121,7 +122,8 @@ def _padding(self, size): def finalize(self): result = _byte_padding_pad( - self._buffer, self.block_size, self._padding) + self._buffer, self.block_size, self._padding + ) self._buffer = None return result @@ -135,13 +137,14 @@ def __init__(self, block_size): def update(self, data): self._buffer, result = _byte_unpadding_update( - self._buffer, data, self.block_size) + self._buffer, data, self.block_size + ) return result def finalize(self): result = _byte_unpadding_check( - self._buffer, self.block_size, - lib.Cryptography_check_pkcs7_padding) + self._buffer, self.block_size, lib.Cryptography_check_pkcs7_padding + ) self._buffer = None return result @@ -167,7 +170,8 @@ def __init__(self, block_size): def update(self, data): self._buffer, result = _byte_padding_update( - self._buffer, data, self.block_size) + self._buffer, data, self.block_size + ) return result def _padding(self, size): @@ -175,7 +179,8 @@ def _padding(self, size): def finalize(self): result = _byte_padding_pad( - self._buffer, self.block_size, self._padding) + self._buffer, self.block_size, self._padding + ) self._buffer = None return result @@ -189,12 +194,15 @@ def __init__(self, block_size): def update(self, data): self._buffer, result = _byte_unpadding_update( - self._buffer, data, self.block_size) + self._buffer, data, self.block_size + ) return result def finalize(self): result = _byte_unpadding_check( - self._buffer, self.block_size, - lib.Cryptography_check_ansix923_padding) + self._buffer, + self.block_size, + lib.Cryptography_check_ansix923_padding, + ) self._buffer = None return result diff --git a/src/cryptography/hazmat/primitives/poly1305.py b/src/cryptography/hazmat/primitives/poly1305.py index d92f62ad4339..6439686202de 100644 --- a/src/cryptography/hazmat/primitives/poly1305.py +++ b/src/cryptography/hazmat/primitives/poly1305.py @@ -7,17 +7,20 @@ from cryptography import utils from cryptography.exceptions import ( - AlreadyFinalized, UnsupportedAlgorithm, _Reasons + AlreadyFinalized, + UnsupportedAlgorithm, + _Reasons, ) class Poly1305(object): def __init__(self, key): from cryptography.hazmat.backends.openssl.backend import backend + if not backend.poly1305_supported(): raise UnsupportedAlgorithm( "poly1305 is not supported by this version of OpenSSL.", - _Reasons.UNSUPPORTED_MAC + _Reasons.UNSUPPORTED_MAC, ) self._ctx = backend.create_poly1305_ctx(key) diff --git a/src/cryptography/hazmat/primitives/serialization/__init__.py b/src/cryptography/hazmat/primitives/serialization/__init__.py index 87e89c1f8cf5..c2f9b014a62d 100644 --- a/src/cryptography/hazmat/primitives/serialization/__init__.py +++ b/src/cryptography/hazmat/primitives/serialization/__init__.py @@ -5,21 +5,40 @@ from __future__ import absolute_import, division, print_function from cryptography.hazmat.primitives.serialization.base import ( - BestAvailableEncryption, Encoding, KeySerializationEncryption, - NoEncryption, ParameterFormat, PrivateFormat, PublicFormat, - load_der_parameters, load_der_private_key, load_der_public_key, - load_pem_parameters, load_pem_private_key, load_pem_public_key, + BestAvailableEncryption, + Encoding, + KeySerializationEncryption, + NoEncryption, + ParameterFormat, + PrivateFormat, + PublicFormat, + load_der_parameters, + load_der_private_key, + load_der_public_key, + load_pem_parameters, + load_pem_private_key, + load_pem_public_key, ) from cryptography.hazmat.primitives.serialization.ssh import ( - load_ssh_private_key, load_ssh_public_key, + load_ssh_private_key, + load_ssh_public_key, ) __all__ = [ - "load_der_parameters", "load_der_private_key", "load_der_public_key", - "load_pem_parameters", "load_pem_private_key", "load_pem_public_key", - "load_ssh_private_key", "load_ssh_public_key", - "Encoding", "PrivateFormat", "PublicFormat", - "ParameterFormat", "KeySerializationEncryption", "BestAvailableEncryption", + "load_der_parameters", + "load_der_private_key", + "load_der_public_key", + "load_pem_parameters", + "load_pem_private_key", + "load_pem_public_key", + "load_ssh_private_key", + "load_ssh_public_key", + "Encoding", + "PrivateFormat", + "PublicFormat", + "ParameterFormat", + "KeySerializationEncryption", + "BestAvailableEncryption", "NoEncryption", ] diff --git a/src/cryptography/hazmat/primitives/serialization/pkcs12.py b/src/cryptography/hazmat/primitives/serialization/pkcs12.py index 32adef71993b..d4e5015256f0 100644 --- a/src/cryptography/hazmat/primitives/serialization/pkcs12.py +++ b/src/cryptography/hazmat/primitives/serialization/pkcs12.py @@ -16,12 +16,14 @@ def load_key_and_certificates(data, password, backend): def serialize_key_and_certificates(name, key, cert, cas, encryption_algorithm): if key is not None and not isinstance( - key, (rsa.RSAPrivateKeyWithSerialization, - dsa.DSAPrivateKeyWithSerialization, - ec.EllipticCurvePrivateKeyWithSerialization)): - raise TypeError( - "Key must be RSA, DSA, or EllipticCurve private key." - ) + key, + ( + rsa.RSAPrivateKeyWithSerialization, + dsa.DSAPrivateKeyWithSerialization, + ec.EllipticCurvePrivateKeyWithSerialization, + ), + ): + raise TypeError("Key must be RSA, DSA, or EllipticCurve private key.") if cert is not None and not isinstance(cert, x509.Certificate): raise TypeError("cert must be a certificate") diff --git a/src/cryptography/hazmat/primitives/serialization/ssh.py b/src/cryptography/hazmat/primitives/serialization/ssh.py index 3971a8b84eda..35091ed309ea 100644 --- a/src/cryptography/hazmat/primitives/serialization/ssh.py +++ b/src/cryptography/hazmat/primitives/serialization/ssh.py @@ -17,10 +17,15 @@ from cryptography.hazmat.primitives.asymmetric import dsa, ec, ed25519, rsa from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives.serialization import ( - Encoding, NoEncryption, PrivateFormat, PublicFormat, + Encoding, + NoEncryption, + PrivateFormat, + PublicFormat, ) + try: from bcrypt import kdf as _bcrypt_kdf + _bcrypt_supported = True except ImportError: _bcrypt_supported = False @@ -28,6 +33,7 @@ def _bcrypt_kdf(*args, **kwargs): raise UnsupportedAlgorithm("Need bcrypt module") + try: from base64 import encodebytes as _base64_encode except ImportError: @@ -140,7 +146,7 @@ def _get_mpint(data): val, data = _get_sshstr(data) if val and six.indexbytes(val, 0) > 0x7F: raise ValueError("Invalid data") - return utils.int_from_bytes(val, 'big'), data + return utils.int_from_bytes(val, "big"), data def _to_mpint(val): @@ -157,6 +163,7 @@ def _to_mpint(val): class _FragList(object): """Build recursive structure without data copy. """ + def __init__(self, init=None): self.flist = [] if init: @@ -479,7 +486,7 @@ def load_ssh_private_key(data, password, backend): data = binascii.a2b_base64(memoryview(data)[p1:p2]) if not data.startswith(_SK_MAGIC): raise ValueError("Not OpenSSH private key format") - data = memoryview(data)[len(_SK_MAGIC):] + data = memoryview(data)[len(_SK_MAGIC) :] # parse header ciphername, data = _get_sshstr(data) @@ -532,7 +539,7 @@ def load_ssh_private_key(data, password, backend): # yes, SSH does padding check *after* all other parsing is done. # need to follow as it writes zero-byte padding too. - if edata != _PADDING[:len(edata)]: + if edata != _PADDING[: len(edata)]: raise ValueError("Corrupt data: invalid padding") return private_key @@ -591,7 +598,7 @@ def serialize_ssh_private_key(private_key, password=None): f_secrets.put_sshstr(key_type) kformat.encode_private(private_key, f_secrets) f_secrets.put_sshstr(comment) - f_secrets.put_raw(_PADDING[:blklen - (f_secrets.size() % blklen)]) + f_secrets.put_raw(_PADDING[: blklen - (f_secrets.size() % blklen)]) # top-level structure f_main = _FragList() @@ -630,9 +637,9 @@ def load_ssh_public_key(data, backend): key_type = orig_key_type = m.group(1) key_body = m.group(2) with_cert = False - if _CERT_SUFFIX == key_type[-len(_CERT_SUFFIX):]: + if _CERT_SUFFIX == key_type[-len(_CERT_SUFFIX) :]: with_cert = True - key_type = key_type[:-len(_CERT_SUFFIX)] + key_type = key_type[: -len(_CERT_SUFFIX)] kformat = _lookup_kformat(key_type) try: diff --git a/src/cryptography/hazmat/primitives/twofactor/hotp.py b/src/cryptography/hazmat/primitives/twofactor/hotp.py index 4ad1bdc2f08d..ed385502e3df 100644 --- a/src/cryptography/hazmat/primitives/twofactor/hotp.py +++ b/src/cryptography/hazmat/primitives/twofactor/hotp.py @@ -8,9 +8,7 @@ import six -from cryptography.exceptions import ( - UnsupportedAlgorithm, _Reasons -) +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons from cryptography.hazmat.backends.interfaces import HMACBackend from cryptography.hazmat.primitives import constant_time, hmac from cryptography.hazmat.primitives.hashes import SHA1, SHA256, SHA512 @@ -19,12 +17,13 @@ class HOTP(object): - def __init__(self, key, length, algorithm, backend, - enforce_key_length=True): + def __init__( + self, key, length, algorithm, backend, enforce_key_length=True + ): if not isinstance(backend, HMACBackend): raise UnsupportedAlgorithm( "Backend object does not implement HMACBackend.", - _Reasons.BACKEND_MISSING_INTERFACE + _Reasons.BACKEND_MISSING_INTERFACE, ) if len(key) < 16 and enforce_key_length is True: @@ -59,10 +58,10 @@ def _dynamic_truncate(self, counter): hmac_value = ctx.finalize() offset = six.indexbytes(hmac_value, len(hmac_value) - 1) & 0b1111 - p = hmac_value[offset:offset + 4] - return struct.unpack(">I", p)[0] & 0x7fffffff + p = hmac_value[offset : offset + 4] + return struct.unpack(">I", p)[0] & 0x7FFFFFFF def get_provisioning_uri(self, account_name, counter, issuer): - return _generate_uri(self, "hotp", account_name, issuer, [ - ("counter", int(counter)), - ]) + return _generate_uri( + self, "hotp", account_name, issuer, [("counter", int(counter))] + ) diff --git a/src/cryptography/hazmat/primitives/twofactor/totp.py b/src/cryptography/hazmat/primitives/twofactor/totp.py index 499f2824a8e9..6056321eacba 100644 --- a/src/cryptography/hazmat/primitives/twofactor/totp.py +++ b/src/cryptography/hazmat/primitives/twofactor/totp.py @@ -4,9 +4,7 @@ from __future__ import absolute_import, division, print_function -from cryptography.exceptions import ( - UnsupportedAlgorithm, _Reasons -) +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons from cryptography.hazmat.backends.interfaces import HMACBackend from cryptography.hazmat.primitives import constant_time from cryptography.hazmat.primitives.twofactor import InvalidToken @@ -15,12 +13,19 @@ class TOTP(object): - def __init__(self, key, length, algorithm, time_step, backend, - enforce_key_length=True): + def __init__( + self, + key, + length, + algorithm, + time_step, + backend, + enforce_key_length=True, + ): if not isinstance(backend, HMACBackend): raise UnsupportedAlgorithm( "Backend object does not implement HMACBackend.", - _Reasons.BACKEND_MISSING_INTERFACE + _Reasons.BACKEND_MISSING_INTERFACE, ) self._time_step = time_step @@ -35,6 +40,10 @@ def verify(self, totp, time): raise InvalidToken("Supplied TOTP value does not match.") def get_provisioning_uri(self, account_name, issuer): - return _generate_uri(self._hotp, "totp", account_name, issuer, [ - ("period", int(self._time_step)), - ]) + return _generate_uri( + self._hotp, + "totp", + account_name, + issuer, + [("period", int(self._time_step))], + ) diff --git a/src/cryptography/hazmat/primitives/twofactor/utils.py b/src/cryptography/hazmat/primitives/twofactor/utils.py index 0ed8c4c89d57..0afa1ccc04b0 100644 --- a/src/cryptography/hazmat/primitives/twofactor/utils.py +++ b/src/cryptography/hazmat/primitives/twofactor/utils.py @@ -23,8 +23,11 @@ def _generate_uri(hotp, type_name, account_name, issuer, extra_parameters): uriparts = { "type": type_name, - "label": ("%s:%s" % (quote(issuer), quote(account_name)) if issuer - else quote(account_name)), + "label": ( + "%s:%s" % (quote(issuer), quote(account_name)) + if issuer + else quote(account_name) + ), "parameters": urlencode(parameters), } return "otpauth://{type}/{label}?{parameters}".format(**uriparts) diff --git a/src/cryptography/utils.py b/src/cryptography/utils.py index ff4f81d24887..c65768363267 100644 --- a/src/cryptography/utils.py +++ b/src/cryptography/utils.py @@ -45,6 +45,7 @@ def register_decorator(klass): verify_interface(iface, klass) iface.register(klass) return klass + return register_decorator @@ -54,27 +55,33 @@ def register_decorator(klass): verify_interface(iface, klass) iface.register(klass) return klass + return register_decorator if hasattr(int, "from_bytes"): int_from_bytes = int.from_bytes else: + def int_from_bytes(data, byteorder, signed=False): - assert byteorder == 'big' + assert byteorder == "big" assert not signed return int(binascii.hexlify(data), 16) if hasattr(int, "to_bytes"): + def int_to_bytes(integer, length=None): return integer.to_bytes( - length or (integer.bit_length() + 7) // 8 or 1, 'big' + length or (integer.bit_length() + 7) // 8 or 1, "big" ) + + else: + def int_to_bytes(integer, length=None): - hex_string = '%x' % integer + hex_string = "%x" % integer if length is None: n = len(hex_string) else: @@ -106,9 +113,7 @@ def verify_interface(iface, klass): if sig != actual: raise InterfaceNotImplemented( "{}.{}'s signature differs from the expected. Expected: " - "{!r}. Received: {!r}".format( - klass, method, sig, actual - ) + "{!r}. Received: {!r}".format(klass, method, sig, actual) ) @@ -168,4 +173,5 @@ def inner(instance): result = func(instance) setattr(instance, cached_name, result) return result + return property(inner) diff --git a/src/cryptography/x509/__init__.py b/src/cryptography/x509/__init__.py index 47b790089d27..69630e4cba8b 100644 --- a/src/cryptography/x509/__init__.py +++ b/src/cryptography/x509/__init__.py @@ -6,40 +6,95 @@ from cryptography.x509 import certificate_transparency from cryptography.x509.base import ( - AttributeNotFound, Certificate, CertificateBuilder, - CertificateRevocationList, CertificateRevocationListBuilder, - CertificateSigningRequest, CertificateSigningRequestBuilder, - InvalidVersion, RevokedCertificate, RevokedCertificateBuilder, - Version, load_der_x509_certificate, load_der_x509_crl, load_der_x509_csr, - load_pem_x509_certificate, load_pem_x509_crl, load_pem_x509_csr, + AttributeNotFound, + Certificate, + CertificateBuilder, + CertificateRevocationList, + CertificateRevocationListBuilder, + CertificateSigningRequest, + CertificateSigningRequestBuilder, + InvalidVersion, + RevokedCertificate, + RevokedCertificateBuilder, + Version, + load_der_x509_certificate, + load_der_x509_crl, + load_der_x509_csr, + load_pem_x509_certificate, + load_pem_x509_crl, + load_pem_x509_csr, random_serial_number, ) from cryptography.x509.extensions import ( - AccessDescription, AuthorityInformationAccess, - AuthorityKeyIdentifier, BasicConstraints, CRLDistributionPoints, - CRLNumber, CRLReason, CertificateIssuer, CertificatePolicies, - DeltaCRLIndicator, DistributionPoint, DuplicateExtension, ExtendedKeyUsage, - Extension, ExtensionNotFound, ExtensionType, Extensions, FreshestCRL, - GeneralNames, InhibitAnyPolicy, InvalidityDate, IssuerAlternativeName, - IssuingDistributionPoint, KeyUsage, NameConstraints, NoticeReference, - OCSPNoCheck, OCSPNonce, PolicyConstraints, PolicyInformation, - PrecertPoison, PrecertificateSignedCertificateTimestamps, ReasonFlags, - SignedCertificateTimestamps, SubjectAlternativeName, - SubjectInformationAccess, SubjectKeyIdentifier, - TLSFeature, TLSFeatureType, UnrecognizedExtension, UserNotice + AccessDescription, + AuthorityInformationAccess, + AuthorityKeyIdentifier, + BasicConstraints, + CRLDistributionPoints, + CRLNumber, + CRLReason, + CertificateIssuer, + CertificatePolicies, + DeltaCRLIndicator, + DistributionPoint, + DuplicateExtension, + ExtendedKeyUsage, + Extension, + ExtensionNotFound, + ExtensionType, + Extensions, + FreshestCRL, + GeneralNames, + InhibitAnyPolicy, + InvalidityDate, + IssuerAlternativeName, + IssuingDistributionPoint, + KeyUsage, + NameConstraints, + NoticeReference, + OCSPNoCheck, + OCSPNonce, + PolicyConstraints, + PolicyInformation, + PrecertPoison, + PrecertificateSignedCertificateTimestamps, + ReasonFlags, + SignedCertificateTimestamps, + SubjectAlternativeName, + SubjectInformationAccess, + SubjectKeyIdentifier, + TLSFeature, + TLSFeatureType, + UnrecognizedExtension, + UserNotice, ) from cryptography.x509.general_name import ( - DNSName, DirectoryName, GeneralName, IPAddress, OtherName, RFC822Name, - RegisteredID, UniformResourceIdentifier, UnsupportedGeneralNameType, - _GENERAL_NAMES + DNSName, + DirectoryName, + GeneralName, + IPAddress, + OtherName, + RFC822Name, + RegisteredID, + UniformResourceIdentifier, + UnsupportedGeneralNameType, + _GENERAL_NAMES, ) from cryptography.x509.name import ( - Name, NameAttribute, RelativeDistinguishedName + Name, + NameAttribute, + RelativeDistinguishedName, ) from cryptography.x509.oid import ( - AuthorityInformationAccessOID, CRLEntryExtensionOID, - CertificatePoliciesOID, ExtendedKeyUsageOID, ExtensionOID, NameOID, - ObjectIdentifier, SignatureAlgorithmOID, _SIG_OIDS_TO_HASH + AuthorityInformationAccessOID, + CRLEntryExtensionOID, + CertificatePoliciesOID, + ExtendedKeyUsageOID, + ExtensionOID, + NameOID, + ObjectIdentifier, + SignatureAlgorithmOID, + _SIG_OIDS_TO_HASH, ) diff --git a/src/cryptography/x509/base.py b/src/cryptography/x509/base.py index 526fb5d6d582..102468a45bb5 100644 --- a/src/cryptography/x509/base.py +++ b/src/cryptography/x509/base.py @@ -13,7 +13,11 @@ from cryptography import utils from cryptography.hazmat.primitives.asymmetric import ( - dsa, ec, ed25519, ed448, rsa + dsa, + ec, + ed25519, + ed448, + rsa, ) from cryptography.x509.extensions import Extension, ExtensionType from cryptography.x509.name import Name @@ -33,14 +37,14 @@ def _reject_duplicate_extension(extension, extensions): # This is quadratic in the number of extensions for e in extensions: if e.oid == extension.oid: - raise ValueError('This extension has already been set.') + raise ValueError("This extension has already been set.") def _reject_duplicate_attribute(oid, attributes): # This is quadratic in the number of attributes for attr_oid, _ in attributes: if attr_oid == oid: - raise ValueError('This attribute has already been set.') + raise ValueError("This attribute has already been set.") def _convert_to_naive_utc_time(time): @@ -423,9 +427,9 @@ def subject_name(self, name): Sets the certificate requestor's distinguished name. """ if not isinstance(name, Name): - raise TypeError('Expecting x509.Name object.') + raise TypeError("Expecting x509.Name object.") if self._subject_name is not None: - raise ValueError('The subject name may only be set once.') + raise ValueError("The subject name may only be set once.") return CertificateSigningRequestBuilder( name, self._extensions, self._attributes ) @@ -441,8 +445,9 @@ def add_extension(self, extension, critical): _reject_duplicate_extension(extension, self._extensions) return CertificateSigningRequestBuilder( - self._subject_name, self._extensions + [extension], - self._attributes + self._subject_name, + self._extensions + [extension], + self._attributes, ) def add_attribute(self, oid, value): @@ -458,8 +463,9 @@ def add_attribute(self, oid, value): _reject_duplicate_attribute(oid, self._attributes) return CertificateSigningRequestBuilder( - self._subject_name, self._extensions, - self._attributes + [(oid, value)] + self._subject_name, + self._extensions, + self._attributes + [(oid, value)], ) def sign(self, private_key, algorithm, backend): @@ -472,9 +478,16 @@ def sign(self, private_key, algorithm, backend): class CertificateBuilder(object): - def __init__(self, issuer_name=None, subject_name=None, - public_key=None, serial_number=None, not_valid_before=None, - not_valid_after=None, extensions=[]): + def __init__( + self, + issuer_name=None, + subject_name=None, + public_key=None, + serial_number=None, + not_valid_before=None, + not_valid_after=None, + extensions=[], + ): self._version = Version.v3 self._issuer_name = issuer_name self._subject_name = subject_name @@ -489,13 +502,17 @@ def issuer_name(self, name): Sets the CA's distinguished name. """ if not isinstance(name, Name): - raise TypeError('Expecting x509.Name object.') + raise TypeError("Expecting x509.Name object.") if self._issuer_name is not None: - raise ValueError('The issuer name may only be set once.') + raise ValueError("The issuer name may only be set once.") return CertificateBuilder( - name, self._subject_name, self._public_key, - self._serial_number, self._not_valid_before, - self._not_valid_after, self._extensions + name, + self._subject_name, + self._public_key, + self._serial_number, + self._not_valid_before, + self._not_valid_after, + self._extensions, ) def subject_name(self, name): @@ -503,32 +520,48 @@ def subject_name(self, name): Sets the requestor's distinguished name. """ if not isinstance(name, Name): - raise TypeError('Expecting x509.Name object.') + raise TypeError("Expecting x509.Name object.") if self._subject_name is not None: - raise ValueError('The subject name may only be set once.') + raise ValueError("The subject name may only be set once.") return CertificateBuilder( - self._issuer_name, name, self._public_key, - self._serial_number, self._not_valid_before, - self._not_valid_after, self._extensions + self._issuer_name, + name, + self._public_key, + self._serial_number, + self._not_valid_before, + self._not_valid_after, + self._extensions, ) def public_key(self, key): """ Sets the requestor's public key (as found in the signing request). """ - if not isinstance(key, (dsa.DSAPublicKey, rsa.RSAPublicKey, - ec.EllipticCurvePublicKey, - ed25519.Ed25519PublicKey, - ed448.Ed448PublicKey)): - raise TypeError('Expecting one of DSAPublicKey, RSAPublicKey,' - ' EllipticCurvePublicKey, Ed25519PublicKey or' - ' Ed448PublicKey.') + if not isinstance( + key, + ( + dsa.DSAPublicKey, + rsa.RSAPublicKey, + ec.EllipticCurvePublicKey, + ed25519.Ed25519PublicKey, + ed448.Ed448PublicKey, + ), + ): + raise TypeError( + "Expecting one of DSAPublicKey, RSAPublicKey," + " EllipticCurvePublicKey, Ed25519PublicKey or" + " Ed448PublicKey." + ) if self._public_key is not None: - raise ValueError('The public key may only be set once.') + raise ValueError("The public key may only be set once.") return CertificateBuilder( - self._issuer_name, self._subject_name, key, - self._serial_number, self._not_valid_before, - self._not_valid_after, self._extensions + self._issuer_name, + self._subject_name, + key, + self._serial_number, + self._not_valid_before, + self._not_valid_after, + self._extensions, ) def serial_number(self, number): @@ -536,21 +569,26 @@ def serial_number(self, number): Sets the certificate serial number. """ if not isinstance(number, six.integer_types): - raise TypeError('Serial number must be of integral type.') + raise TypeError("Serial number must be of integral type.") if self._serial_number is not None: - raise ValueError('The serial number may only be set once.') + raise ValueError("The serial number may only be set once.") if number <= 0: - raise ValueError('The serial number should be positive.') + raise ValueError("The serial number should be positive.") # ASN.1 integers are always signed, so most significant bit must be # zero. if number.bit_length() >= 160: # As defined in RFC 5280 - raise ValueError('The serial number should not be more than 159 ' - 'bits.') + raise ValueError( + "The serial number should not be more than 159 " "bits." + ) return CertificateBuilder( - self._issuer_name, self._subject_name, - self._public_key, number, self._not_valid_before, - self._not_valid_after, self._extensions + self._issuer_name, + self._subject_name, + self._public_key, + number, + self._not_valid_before, + self._not_valid_after, + self._extensions, ) def not_valid_before(self, time): @@ -558,22 +596,28 @@ def not_valid_before(self, time): Sets the certificate activation time. """ if not isinstance(time, datetime.datetime): - raise TypeError('Expecting datetime object.') + raise TypeError("Expecting datetime object.") if self._not_valid_before is not None: - raise ValueError('The not valid before may only be set once.') + raise ValueError("The not valid before may only be set once.") time = _convert_to_naive_utc_time(time) if time < _EARLIEST_UTC_TIME: - raise ValueError('The not valid before date must be on or after' - ' 1950 January 1).') + raise ValueError( + "The not valid before date must be on or after" + " 1950 January 1)." + ) if self._not_valid_after is not None and time > self._not_valid_after: raise ValueError( - 'The not valid before date must be before the not valid after ' - 'date.' + "The not valid before date must be before the not valid after " + "date." ) return CertificateBuilder( - self._issuer_name, self._subject_name, - self._public_key, self._serial_number, time, - self._not_valid_after, self._extensions + self._issuer_name, + self._subject_name, + self._public_key, + self._serial_number, + time, + self._not_valid_after, + self._extensions, ) def not_valid_after(self, time): @@ -581,23 +625,31 @@ def not_valid_after(self, time): Sets the certificate expiration time. """ if not isinstance(time, datetime.datetime): - raise TypeError('Expecting datetime object.') + raise TypeError("Expecting datetime object.") if self._not_valid_after is not None: - raise ValueError('The not valid after may only be set once.') + raise ValueError("The not valid after may only be set once.") time = _convert_to_naive_utc_time(time) if time < _EARLIEST_UTC_TIME: - raise ValueError('The not valid after date must be on or after' - ' 1950 January 1.') - if (self._not_valid_before is not None and - time < self._not_valid_before): raise ValueError( - 'The not valid after date must be after the not valid before ' - 'date.' + "The not valid after date must be on or after" + " 1950 January 1." + ) + if ( + self._not_valid_before is not None + and time < self._not_valid_before + ): + raise ValueError( + "The not valid after date must be after the not valid before " + "date." ) return CertificateBuilder( - self._issuer_name, self._subject_name, - self._public_key, self._serial_number, self._not_valid_before, - time, self._extensions + self._issuer_name, + self._subject_name, + self._public_key, + self._serial_number, + self._not_valid_before, + time, + self._extensions, ) def add_extension(self, extension, critical): @@ -611,9 +663,13 @@ def add_extension(self, extension, critical): _reject_duplicate_extension(extension, self._extensions) return CertificateBuilder( - self._issuer_name, self._subject_name, - self._public_key, self._serial_number, self._not_valid_before, - self._not_valid_after, self._extensions + [extension] + self._issuer_name, + self._subject_name, + self._public_key, + self._serial_number, + self._not_valid_before, + self._not_valid_after, + self._extensions + [extension], ) def sign(self, private_key, algorithm, backend): @@ -642,8 +698,14 @@ def sign(self, private_key, algorithm, backend): class CertificateRevocationListBuilder(object): - def __init__(self, issuer_name=None, last_update=None, next_update=None, - extensions=[], revoked_certificates=[]): + def __init__( + self, + issuer_name=None, + last_update=None, + next_update=None, + extensions=[], + revoked_certificates=[], + ): self._issuer_name = issuer_name self._last_update = last_update self._next_update = next_update @@ -652,48 +714,59 @@ def __init__(self, issuer_name=None, last_update=None, next_update=None, def issuer_name(self, issuer_name): if not isinstance(issuer_name, Name): - raise TypeError('Expecting x509.Name object.') + raise TypeError("Expecting x509.Name object.") if self._issuer_name is not None: - raise ValueError('The issuer name may only be set once.') + raise ValueError("The issuer name may only be set once.") return CertificateRevocationListBuilder( - issuer_name, self._last_update, self._next_update, - self._extensions, self._revoked_certificates + issuer_name, + self._last_update, + self._next_update, + self._extensions, + self._revoked_certificates, ) def last_update(self, last_update): if not isinstance(last_update, datetime.datetime): - raise TypeError('Expecting datetime object.') + raise TypeError("Expecting datetime object.") if self._last_update is not None: - raise ValueError('Last update may only be set once.') + raise ValueError("Last update may only be set once.") last_update = _convert_to_naive_utc_time(last_update) if last_update < _EARLIEST_UTC_TIME: - raise ValueError('The last update date must be on or after' - ' 1950 January 1.') + raise ValueError( + "The last update date must be on or after" " 1950 January 1." + ) if self._next_update is not None and last_update > self._next_update: raise ValueError( - 'The last update date must be before the next update date.' + "The last update date must be before the next update date." ) return CertificateRevocationListBuilder( - self._issuer_name, last_update, self._next_update, - self._extensions, self._revoked_certificates + self._issuer_name, + last_update, + self._next_update, + self._extensions, + self._revoked_certificates, ) def next_update(self, next_update): if not isinstance(next_update, datetime.datetime): - raise TypeError('Expecting datetime object.') + raise TypeError("Expecting datetime object.") if self._next_update is not None: - raise ValueError('Last update may only be set once.') + raise ValueError("Last update may only be set once.") next_update = _convert_to_naive_utc_time(next_update) if next_update < _EARLIEST_UTC_TIME: - raise ValueError('The last update date must be on or after' - ' 1950 January 1.') + raise ValueError( + "The last update date must be on or after" " 1950 January 1." + ) if self._last_update is not None and next_update < self._last_update: raise ValueError( - 'The next update date must be after the last update date.' + "The next update date must be after the last update date." ) return CertificateRevocationListBuilder( - self._issuer_name, self._last_update, next_update, - self._extensions, self._revoked_certificates + self._issuer_name, + self._last_update, + next_update, + self._extensions, + self._revoked_certificates, ) def add_extension(self, extension, critical): @@ -706,8 +779,11 @@ def add_extension(self, extension, critical): extension = Extension(extension.oid, critical, extension) _reject_duplicate_extension(extension, self._extensions) return CertificateRevocationListBuilder( - self._issuer_name, self._last_update, self._next_update, - self._extensions + [extension], self._revoked_certificates + self._issuer_name, + self._last_update, + self._next_update, + self._extensions + [extension], + self._revoked_certificates, ) def add_revoked_certificate(self, revoked_certificate): @@ -718,9 +794,11 @@ def add_revoked_certificate(self, revoked_certificate): raise TypeError("Must be an instance of RevokedCertificate") return CertificateRevocationListBuilder( - self._issuer_name, self._last_update, - self._next_update, self._extensions, - self._revoked_certificates + [revoked_certificate] + self._issuer_name, + self._last_update, + self._next_update, + self._extensions, + self._revoked_certificates + [revoked_certificate], ) def sign(self, private_key, algorithm, backend): @@ -737,38 +815,41 @@ def sign(self, private_key, algorithm, backend): class RevokedCertificateBuilder(object): - def __init__(self, serial_number=None, revocation_date=None, - extensions=[]): + def __init__( + self, serial_number=None, revocation_date=None, extensions=[] + ): self._serial_number = serial_number self._revocation_date = revocation_date self._extensions = extensions def serial_number(self, number): if not isinstance(number, six.integer_types): - raise TypeError('Serial number must be of integral type.') + raise TypeError("Serial number must be of integral type.") if self._serial_number is not None: - raise ValueError('The serial number may only be set once.') + raise ValueError("The serial number may only be set once.") if number <= 0: - raise ValueError('The serial number should be positive') + raise ValueError("The serial number should be positive") # ASN.1 integers are always signed, so most significant bit must be # zero. if number.bit_length() >= 160: # As defined in RFC 5280 - raise ValueError('The serial number should not be more than 159 ' - 'bits.') + raise ValueError( + "The serial number should not be more than 159 " "bits." + ) return RevokedCertificateBuilder( number, self._revocation_date, self._extensions ) def revocation_date(self, time): if not isinstance(time, datetime.datetime): - raise TypeError('Expecting datetime object.') + raise TypeError("Expecting datetime object.") if self._revocation_date is not None: - raise ValueError('The revocation date may only be set once.') + raise ValueError("The revocation date may only be set once.") time = _convert_to_naive_utc_time(time) if time < _EARLIEST_UTC_TIME: - raise ValueError('The revocation date must be on or after' - ' 1950 January 1.') + raise ValueError( + "The revocation date must be on or after" " 1950 January 1." + ) return RevokedCertificateBuilder( self._serial_number, time, self._extensions ) @@ -780,8 +861,9 @@ def add_extension(self, extension, critical): extension = Extension(extension.oid, critical, extension) _reject_duplicate_extension(extension, self._extensions) return RevokedCertificateBuilder( - self._serial_number, self._revocation_date, - self._extensions + [extension] + self._serial_number, + self._revocation_date, + self._extensions + [extension], ) def build(self, backend): diff --git a/src/cryptography/x509/extensions.py b/src/cryptography/x509/extensions.py index e4a6e821d63e..6a9ead51f0a8 100644 --- a/src/cryptography/x509/extensions.py +++ b/src/cryptography/x509/extensions.py @@ -14,37 +14,42 @@ from cryptography import utils from cryptography.hazmat._der import ( - BIT_STRING, DERReader, OBJECT_IDENTIFIER, SEQUENCE + BIT_STRING, + DERReader, + OBJECT_IDENTIFIER, + SEQUENCE, ) from cryptography.hazmat.primitives import constant_time, serialization from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicKey from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey from cryptography.x509.certificate_transparency import ( - SignedCertificateTimestamp + SignedCertificateTimestamp, ) from cryptography.x509.general_name import GeneralName, IPAddress, OtherName from cryptography.x509.name import RelativeDistinguishedName from cryptography.x509.oid import ( - CRLEntryExtensionOID, ExtensionOID, OCSPExtensionOID, ObjectIdentifier, + CRLEntryExtensionOID, + ExtensionOID, + OCSPExtensionOID, + ObjectIdentifier, ) def _key_identifier_from_public_key(public_key): if isinstance(public_key, RSAPublicKey): data = public_key.public_bytes( - serialization.Encoding.DER, - serialization.PublicFormat.PKCS1, + serialization.Encoding.DER, serialization.PublicFormat.PKCS1, ) elif isinstance(public_key, EllipticCurvePublicKey): data = public_key.public_bytes( serialization.Encoding.X962, - serialization.PublicFormat.UncompressedPoint + serialization.PublicFormat.UncompressedPoint, ) else: # This is a very slow way to do this. serialized = public_key.public_bytes( serialization.Encoding.DER, - serialization.PublicFormat.SubjectPublicKeyInfo + serialization.PublicFormat.SubjectPublicKeyInfo, ) reader = DERReader(serialized) @@ -62,7 +67,7 @@ def _key_identifier_from_public_key(public_key): # BIT STRING contents begin with the number of padding bytes added. It # must be zero for SubjectPublicKeyInfo structures. if public_key.read_byte() != 0: - raise ValueError('Invalid public key encoding') + raise ValueError("Invalid public key encoding") data = public_key.data @@ -133,9 +138,7 @@ def get_extension_for_class(self, extclass): __len__, __iter__, __getitem__ = _make_sequence_methods("_extensions") def __repr__(self): - return ( - "".format(self._extensions) - ) + return "".format(self._extensions) @utils.register_interface(ExtensionType) @@ -170,8 +173,12 @@ def __repr__(self): class AuthorityKeyIdentifier(object): oid = ExtensionOID.AUTHORITY_KEY_IDENTIFIER - def __init__(self, key_identifier, authority_cert_issuer, - authority_cert_serial_number): + def __init__( + self, + key_identifier, + authority_cert_issuer, + authority_cert_serial_number, + ): if (authority_cert_issuer is None) != ( authority_cert_serial_number is None ): @@ -193,9 +200,7 @@ def __init__(self, key_identifier, authority_cert_issuer, if authority_cert_serial_number is not None and not isinstance( authority_cert_serial_number, six.integer_types ): - raise TypeError( - "authority_cert_serial_number must be an integer" - ) + raise TypeError("authority_cert_serial_number must be an integer") self._key_identifier = key_identifier self._authority_cert_issuer = authority_cert_issuer @@ -207,7 +212,7 @@ def from_issuer_public_key(cls, public_key): return cls( key_identifier=digest, authority_cert_issuer=None, - authority_cert_serial_number=None + authority_cert_serial_number=None, ) @classmethod @@ -215,7 +220,7 @@ def from_issuer_subject_key_identifier(cls, ski): return cls( key_identifier=ski.digest, authority_cert_issuer=None, - authority_cert_serial_number=None + authority_cert_serial_number=None, ) def __repr__(self): @@ -231,10 +236,10 @@ def __eq__(self, other): return NotImplemented return ( - self.key_identifier == other.key_identifier and - self.authority_cert_issuer == other.authority_cert_issuer and - self.authority_cert_serial_number == - other.authority_cert_serial_number + self.key_identifier == other.key_identifier + and self.authority_cert_issuer == other.authority_cert_issuer + and self.authority_cert_serial_number + == other.authority_cert_serial_number ) def __ne__(self, other): @@ -245,9 +250,9 @@ def __hash__(self): aci = None else: aci = tuple(self.authority_cert_issuer) - return hash(( - self.key_identifier, aci, self.authority_cert_serial_number - )) + return hash( + (self.key_identifier, aci, self.authority_cert_serial_number) + ) key_identifier = utils.read_only_property("_key_identifier") authority_cert_issuer = utils.read_only_property("_authority_cert_issuer") @@ -371,8 +376,8 @@ def __eq__(self, other): return NotImplemented return ( - self.access_method == other.access_method and - self.access_location == other.access_location + self.access_method == other.access_method + and self.access_location == other.access_location ) def __ne__(self, other): @@ -396,9 +401,8 @@ def __init__(self, ca, path_length): if path_length is not None and not ca: raise ValueError("path_length must be None when ca is False") - if ( - path_length is not None and - (not isinstance(path_length, six.integer_types) or path_length < 0) + if path_length is not None and ( + not isinstance(path_length, six.integer_types) or path_length < 0 ): raise TypeError( "path_length must be a non-negative integer or None" @@ -411,8 +415,9 @@ def __init__(self, ca, path_length): path_length = utils.read_only_property("_path_length") def __repr__(self): - return ("").format(self) + return ( + "" + ).format(self) def __eq__(self, other): if not isinstance(other, BasicConstraints): @@ -555,14 +560,15 @@ def __init__(self, full_name, relative_name, reasons, crl_issuer): "crl_issuer must be None or a list of general names" ) - if reasons and (not isinstance(reasons, frozenset) or not all( - isinstance(x, ReasonFlags) for x in reasons - )): + if reasons and ( + not isinstance(reasons, frozenset) + or not all(isinstance(x, ReasonFlags) for x in reasons) + ): raise TypeError("reasons must be None or frozenset of ReasonFlags") if reasons and ( - ReasonFlags.unspecified in reasons or - ReasonFlags.remove_from_crl in reasons + ReasonFlags.unspecified in reasons + or ReasonFlags.remove_from_crl in reasons ): raise ValueError( "unspecified and remove_from_crl are not valid reasons in a " @@ -583,8 +589,8 @@ def __init__(self, full_name, relative_name, reasons, crl_issuer): def __repr__(self): return ( "" - .format(self) + "tive_name}, reasons={0.reasons}, " + "crl_issuer={0.crl_issuer})>".format(self) ) def __eq__(self, other): @@ -592,10 +598,10 @@ def __eq__(self, other): return NotImplemented return ( - self.full_name == other.full_name and - self.relative_name == other.relative_name and - self.reasons == other.reasons and - self.crl_issuer == other.crl_issuer + self.full_name == other.full_name + and self.relative_name == other.relative_name + and self.reasons == other.reasons + and self.crl_issuer == other.crl_issuer ) def __ne__(self, other): @@ -674,8 +680,8 @@ def __eq__(self, other): return NotImplemented return ( - self.require_explicit_policy == other.require_explicit_policy and - self.inhibit_policy_mapping == other.inhibit_policy_mapping + self.require_explicit_policy == other.require_explicit_policy + and self.inhibit_policy_mapping == other.inhibit_policy_mapping ) def __ne__(self, other): @@ -736,8 +742,8 @@ def __init__(self, policy_identifier, policy_qualifiers): if policy_qualifiers: policy_qualifiers = list(policy_qualifiers) if not all( - isinstance(x, (six.text_type, UserNotice)) - for x in policy_qualifiers + isinstance(x, (six.text_type, UserNotice)) + for x in policy_qualifiers ): raise TypeError( "policy_qualifiers must be a list of strings and/or " @@ -757,8 +763,8 @@ def __eq__(self, other): return NotImplemented return ( - self.policy_identifier == other.policy_identifier and - self.policy_qualifiers == other.policy_qualifiers + self.policy_identifier == other.policy_identifier + and self.policy_qualifiers == other.policy_qualifiers ) def __ne__(self, other): @@ -799,8 +805,8 @@ def __eq__(self, other): return NotImplemented return ( - self.notice_reference == other.notice_reference and - self.explicit_text == other.explicit_text + self.notice_reference == other.notice_reference + and self.explicit_text == other.explicit_text ) def __ne__(self, other): @@ -818,9 +824,7 @@ def __init__(self, organization, notice_numbers): self._organization = organization notice_numbers = list(notice_numbers) if not all(isinstance(x, int) for x in notice_numbers): - raise TypeError( - "notice_numbers must be a list of integers" - ) + raise TypeError("notice_numbers must be a list of integers") self._notice_numbers = notice_numbers @@ -835,8 +839,8 @@ def __eq__(self, other): return NotImplemented return ( - self.organization == other.organization and - self.notice_numbers == other.notice_numbers + self.organization == other.organization + and self.notice_numbers == other.notice_numbers ) def __ne__(self, other): @@ -927,8 +931,8 @@ class TLSFeature(object): def __init__(self, features): features = list(features) if ( - not all(isinstance(x, TLSFeatureType) for x in features) or - len(features) == 0 + not all(isinstance(x, TLSFeatureType) for x in features) + or len(features) == 0 ): raise TypeError( "features must be a list of elements from the TLSFeatureType " @@ -1004,9 +1008,18 @@ def __hash__(self): class KeyUsage(object): oid = ExtensionOID.KEY_USAGE - def __init__(self, digital_signature, content_commitment, key_encipherment, - data_encipherment, key_agreement, key_cert_sign, crl_sign, - encipher_only, decipher_only): + def __init__( + self, + digital_signature, + content_commitment, + key_encipherment, + data_encipherment, + key_agreement, + key_cert_sign, + crl_sign, + encipher_only, + decipher_only, + ): if not key_agreement and (encipher_only or decipher_only): raise ValueError( "encipher_only and decipher_only can only be true when " @@ -1060,42 +1073,49 @@ def __repr__(self): encipher_only = False decipher_only = False - return ("").format( - self, encipher_only, decipher_only) + return ( + "" + ).format(self, encipher_only, decipher_only) def __eq__(self, other): if not isinstance(other, KeyUsage): return NotImplemented return ( - self.digital_signature == other.digital_signature and - self.content_commitment == other.content_commitment and - self.key_encipherment == other.key_encipherment and - self.data_encipherment == other.data_encipherment and - self.key_agreement == other.key_agreement and - self.key_cert_sign == other.key_cert_sign and - self.crl_sign == other.crl_sign and - self._encipher_only == other._encipher_only and - self._decipher_only == other._decipher_only + self.digital_signature == other.digital_signature + and self.content_commitment == other.content_commitment + and self.key_encipherment == other.key_encipherment + and self.data_encipherment == other.data_encipherment + and self.key_agreement == other.key_agreement + and self.key_cert_sign == other.key_cert_sign + and self.crl_sign == other.crl_sign + and self._encipher_only == other._encipher_only + and self._decipher_only == other._decipher_only ) def __ne__(self, other): return not self == other def __hash__(self): - return hash(( - self.digital_signature, self.content_commitment, - self.key_encipherment, self.data_encipherment, - self.key_agreement, self.key_cert_sign, - self.crl_sign, self._encipher_only, - self._decipher_only - )) + return hash( + ( + self.digital_signature, + self.content_commitment, + self.key_encipherment, + self.data_encipherment, + self.key_agreement, + self.key_cert_sign, + self.crl_sign, + self._encipher_only, + self._decipher_only, + ) + ) @utils.register_interface(ExtensionType) @@ -1105,9 +1125,7 @@ class NameConstraints(object): def __init__(self, permitted_subtrees, excluded_subtrees): if permitted_subtrees is not None: permitted_subtrees = list(permitted_subtrees) - if not all( - isinstance(x, GeneralName) for x in permitted_subtrees - ): + if not all(isinstance(x, GeneralName) for x in permitted_subtrees): raise TypeError( "permitted_subtrees must be a list of GeneralName objects " "or None" @@ -1117,9 +1135,7 @@ def __init__(self, permitted_subtrees, excluded_subtrees): if excluded_subtrees is not None: excluded_subtrees = list(excluded_subtrees) - if not all( - isinstance(x, GeneralName) for x in excluded_subtrees - ): + if not all(isinstance(x, GeneralName) for x in excluded_subtrees): raise TypeError( "excluded_subtrees must be a list of GeneralName objects " "or None" @@ -1141,17 +1157,21 @@ def __eq__(self, other): return NotImplemented return ( - self.excluded_subtrees == other.excluded_subtrees and - self.permitted_subtrees == other.permitted_subtrees + self.excluded_subtrees == other.excluded_subtrees + and self.permitted_subtrees == other.permitted_subtrees ) def __ne__(self, other): return not self == other def _validate_ip_name(self, tree): - if any(isinstance(name, IPAddress) and not isinstance( - name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network) - ) for name in tree): + if any( + isinstance(name, IPAddress) + and not isinstance( + name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network) + ) + for name in tree + ): raise TypeError( "IPAddress name constraints must be an IPv4Network or" " IPv6Network object" @@ -1199,17 +1219,19 @@ def __init__(self, oid, critical, value): value = utils.read_only_property("_value") def __repr__(self): - return ("").format(self) + return ( + "" + ).format(self) def __eq__(self, other): if not isinstance(other, Extension): return NotImplemented return ( - self.oid == other.oid and - self.critical == other.critical and - self.value == other.value + self.oid == other.oid + and self.critical == other.critical + and self.value == other.value ) def __ne__(self, other): @@ -1229,6 +1251,7 @@ def __init__(self, general_names): ) self._general_names = general_names + __len__, __iter__, __getitem__ = _make_sequence_methods("_general_names") def get_values_for_type(self, type): @@ -1419,10 +1442,8 @@ def __init__(self, signed_certificate_timestamps): ) def __repr__(self): - return ( - "".format( - list(self) - ) + return "".format( + list(self) ) def __hash__(self): @@ -1433,8 +1454,8 @@ def __eq__(self, other): return NotImplemented return ( - self._signed_certificate_timestamps == - other._signed_certificate_timestamps + self._signed_certificate_timestamps + == other._signed_certificate_timestamps ) def __ne__(self, other): @@ -1462,11 +1483,7 @@ def __init__(self, signed_certificate_timestamps): ) def __repr__(self): - return ( - "".format( - list(self) - ) - ) + return "".format(list(self)) def __hash__(self): return hash(tuple(self._signed_certificate_timestamps)) @@ -1476,8 +1493,8 @@ def __eq__(self, other): return NotImplemented return ( - self._signed_certificate_timestamps == - other._signed_certificate_timestamps + self._signed_certificate_timestamps + == other._signed_certificate_timestamps ) def __ne__(self, other): @@ -1516,23 +1533,27 @@ def __repr__(self): class IssuingDistributionPoint(object): oid = ExtensionOID.ISSUING_DISTRIBUTION_POINT - def __init__(self, full_name, relative_name, only_contains_user_certs, - only_contains_ca_certs, only_some_reasons, indirect_crl, - only_contains_attribute_certs): - if ( - only_some_reasons and ( - not isinstance(only_some_reasons, frozenset) or not all( - isinstance(x, ReasonFlags) for x in only_some_reasons - ) - ) + def __init__( + self, + full_name, + relative_name, + only_contains_user_certs, + only_contains_ca_certs, + only_some_reasons, + indirect_crl, + only_contains_attribute_certs, + ): + if only_some_reasons and ( + not isinstance(only_some_reasons, frozenset) + or not all(isinstance(x, ReasonFlags) for x in only_some_reasons) ): raise TypeError( "only_some_reasons must be None or frozenset of ReasonFlags" ) if only_some_reasons and ( - ReasonFlags.unspecified in only_some_reasons or - ReasonFlags.remove_from_crl in only_some_reasons + ReasonFlags.unspecified in only_some_reasons + or ReasonFlags.remove_from_crl in only_some_reasons ): raise ValueError( "unspecified and remove_from_crl are not valid reasons in an " @@ -1540,10 +1561,10 @@ def __init__(self, full_name, relative_name, only_contains_user_certs, ) if not ( - isinstance(only_contains_user_certs, bool) and - isinstance(only_contains_ca_certs, bool) and - isinstance(indirect_crl, bool) and - isinstance(only_contains_attribute_certs, bool) + isinstance(only_contains_user_certs, bool) + and isinstance(only_contains_ca_certs, bool) + and isinstance(indirect_crl, bool) + and isinstance(only_contains_attribute_certs, bool) ): raise TypeError( "only_contains_user_certs, only_contains_ca_certs, " @@ -1552,8 +1573,10 @@ def __init__(self, full_name, relative_name, only_contains_user_certs, ) crl_constraints = [ - only_contains_user_certs, only_contains_ca_certs, - indirect_crl, only_contains_attribute_certs + only_contains_user_certs, + only_contains_ca_certs, + indirect_crl, + only_contains_attribute_certs, ] if len([x for x in crl_constraints if x]) > 1: @@ -1563,12 +1586,16 @@ def __init__(self, full_name, relative_name, only_contains_user_certs, "indirect_crl, only_contains_attribute_certs" ) - if ( - not any([ - only_contains_user_certs, only_contains_ca_certs, - indirect_crl, only_contains_attribute_certs, full_name, - relative_name, only_some_reasons - ]) + if not any( + [ + only_contains_user_certs, + only_contains_ca_certs, + indirect_crl, + only_contains_attribute_certs, + full_name, + relative_name, + only_some_reasons, + ] ): raise ValueError( "Cannot create empty extension: " @@ -1603,29 +1630,31 @@ def __eq__(self, other): return NotImplemented return ( - self.full_name == other.full_name and - self.relative_name == other.relative_name and - self.only_contains_user_certs == other.only_contains_user_certs and - self.only_contains_ca_certs == other.only_contains_ca_certs and - self.only_some_reasons == other.only_some_reasons and - self.indirect_crl == other.indirect_crl and - self.only_contains_attribute_certs == - other.only_contains_attribute_certs + self.full_name == other.full_name + and self.relative_name == other.relative_name + and self.only_contains_user_certs == other.only_contains_user_certs + and self.only_contains_ca_certs == other.only_contains_ca_certs + and self.only_some_reasons == other.only_some_reasons + and self.indirect_crl == other.indirect_crl + and self.only_contains_attribute_certs + == other.only_contains_attribute_certs ) def __ne__(self, other): return not self == other def __hash__(self): - return hash(( - self.full_name, - self.relative_name, - self.only_contains_user_certs, - self.only_contains_ca_certs, - self.only_some_reasons, - self.indirect_crl, - self.only_contains_attribute_certs, - )) + return hash( + ( + self.full_name, + self.relative_name, + self.only_contains_user_certs, + self.only_contains_ca_certs, + self.only_some_reasons, + self.indirect_crl, + self.only_contains_attribute_certs, + ) + ) full_name = utils.read_only_property("_full_name") relative_name = utils.read_only_property("_relative_name") @@ -1655,9 +1684,8 @@ def __init__(self, oid, value): def __repr__(self): return ( - "".format( - self - ) + "".format(self) ) def __eq__(self, other): diff --git a/src/cryptography/x509/general_name.py b/src/cryptography/x509/general_name.py index 1233841507eb..5336a10f603d 100644 --- a/src/cryptography/x509/general_name.py +++ b/src/cryptography/x509/general_name.py @@ -35,6 +35,7 @@ def _lazy_import_idna(): # we're only using it in deprecated paths. try: import idna + return idna except ImportError: raise ImportError( @@ -119,9 +120,9 @@ def __hash__(self): def _idna_encode(value): idna = _lazy_import_idna() # Retain prefixes '*.' for common/alt names and '.' for name constraints - for prefix in ['*.', '.']: + for prefix in ["*.", "."]: if value.startswith(prefix): - value = value[len(prefix):] + value = value[len(prefix) :] return prefix + idna.encode(value).decode("ascii") return idna.encode(value).decode("ascii") @@ -205,8 +206,8 @@ def _idna_encode(self, value): parsed = urllib_parse.urlparse(value) if parsed.port: netloc = ( - idna.encode(parsed.hostname) + - ":{}".format(parsed.port).encode("ascii") + idna.encode(parsed.hostname) + + ":{}".format(parsed.port).encode("ascii") ).decode("ascii") else: netloc = idna.encode(parsed.hostname).decode("ascii") @@ -214,14 +215,16 @@ def _idna_encode(self, value): # Note that building a URL in this fashion means it should be # semantically indistinguishable from the original but is not # guaranteed to be exactly the same. - return urllib_parse.urlunparse(( - parsed.scheme, - netloc, - parsed.path, - parsed.params, - parsed.query, - parsed.fragment - )) + return urllib_parse.urlunparse( + ( + parsed.scheme, + netloc, + parsed.path, + parsed.params, + parsed.query, + parsed.fragment, + ) + ) def __repr__(self): return "".format(self.value) @@ -300,8 +303,8 @@ def __init__(self, value): ipaddress.IPv4Address, ipaddress.IPv6Address, ipaddress.IPv4Network, - ipaddress.IPv6Network - ) + ipaddress.IPv6Network, + ), ): raise TypeError( "value must be an instance of ipaddress.IPv4Address, " @@ -345,7 +348,8 @@ def __init__(self, type_id, value): def __repr__(self): return "".format( - self.type_id, self.value) + self.type_id, self.value + ) def __eq__(self, other): if not isinstance(other, OtherName): diff --git a/src/cryptography/x509/name.py b/src/cryptography/x509/name.py index 6816e0639ff3..6848b7a31ed4 100644 --- a/src/cryptography/x509/name.py +++ b/src/cryptography/x509/name.py @@ -39,15 +39,15 @@ class _ASN1Type(Enum): #: Short attribute names from RFC 4514: #: https://tools.ietf.org/html/rfc4514#page-7 _NAMEOID_TO_NAME = { - NameOID.COMMON_NAME: 'CN', - NameOID.LOCALITY_NAME: 'L', - NameOID.STATE_OR_PROVINCE_NAME: 'ST', - NameOID.ORGANIZATION_NAME: 'O', - NameOID.ORGANIZATIONAL_UNIT_NAME: 'OU', - NameOID.COUNTRY_NAME: 'C', - NameOID.STREET_ADDRESS: 'STREET', - NameOID.DOMAIN_COMPONENT: 'DC', - NameOID.USER_ID: 'UID', + NameOID.COMMON_NAME: "CN", + NameOID.LOCALITY_NAME: "L", + NameOID.STATE_OR_PROVINCE_NAME: "ST", + NameOID.ORGANIZATION_NAME: "O", + NameOID.ORGANIZATIONAL_UNIT_NAME: "OU", + NameOID.COUNTRY_NAME: "C", + NameOID.STREET_ADDRESS: "STREET", + NameOID.DOMAIN_COMPONENT: "DC", + NameOID.USER_ID: "UID", } @@ -55,22 +55,22 @@ def _escape_dn_value(val): """Escape special characters in RFC4514 Distinguished Name value.""" if not val: - return '' + return "" # See https://tools.ietf.org/html/rfc4514#section-2.4 - val = val.replace('\\', '\\\\') + val = val.replace("\\", "\\\\") val = val.replace('"', '\\"') - val = val.replace('+', '\\+') - val = val.replace(',', '\\,') - val = val.replace(';', '\\;') - val = val.replace('<', '\\<') - val = val.replace('>', '\\>') - val = val.replace('\0', '\\00') - - if val[0] in ('#', ' '): - val = '\\' + val - if val[-1] == ' ': - val = val[:-1] + '\\ ' + val = val.replace("+", "\\+") + val = val.replace(",", "\\,") + val = val.replace(";", "\\;") + val = val.replace("<", "\\<") + val = val.replace(">", "\\>") + val = val.replace("\0", "\\00") + + if val[0] in ("#", " "): + val = "\\" + val + if val[-1] == " ": + val = val[:-1] + "\\ " return val @@ -83,13 +83,11 @@ def __init__(self, oid, value, _type=_SENTINEL): ) if not isinstance(value, six.text_type): - raise TypeError( - "value argument must be a text type." - ) + raise TypeError("value argument must be a text type.") if ( - oid == NameOID.COUNTRY_NAME or - oid == NameOID.JURISDICTION_COUNTRY_NAME + oid == NameOID.COUNTRY_NAME + or oid == NameOID.JURISDICTION_COUNTRY_NAME ): if len(value.encode("utf8")) != 2: raise ValueError( @@ -123,16 +121,13 @@ def rfc4514_string(self): dotted string. """ key = _NAMEOID_TO_NAME.get(self.oid, self.oid.dotted_string) - return '%s=%s' % (key, _escape_dn_value(self.value)) + return "%s=%s" % (key, _escape_dn_value(self.value)) def __eq__(self, other): if not isinstance(other, NameAttribute): return NotImplemented - return ( - self.oid == other.oid and - self.value == other.value - ) + return self.oid == other.oid and self.value == other.value def __ne__(self, other): return not self == other @@ -169,7 +164,7 @@ def rfc4514_string(self): Within each RDN, attributes are joined by '+', although that is rarely used in certificates. """ - return '+'.join(attr.rfc4514_string() for attr in self._attributes) + return "+".join(attr.rfc4514_string() for attr in self._attributes) def __eq__(self, other): if not isinstance(other, RelativeDistinguishedName): @@ -219,8 +214,9 @@ def rfc4514_string(self): real world certificates. According to RFC4514 section 2.1 the RDNSequence must be reversed when converting to string representation. """ - return ','.join( - attr.rfc4514_string() for attr in reversed(self._attributes)) + return ",".join( + attr.rfc4514_string() for attr in reversed(self._attributes) + ) def get_attributes_for_oid(self, oid): return [i for i in self if i.oid == oid] @@ -255,9 +251,9 @@ def __len__(self): return sum(len(rdn) for rdn in self._attributes) def __repr__(self): - rdns = ','.join(attr.rfc4514_string() for attr in self._attributes) + rdns = ",".join(attr.rfc4514_string() for attr in self._attributes) if six.PY2: - return "".format(rdns.encode('utf8')) + return "".format(rdns.encode("utf8")) else: return "".format(rdns) diff --git a/src/cryptography/x509/ocsp.py b/src/cryptography/x509/ocsp.py index 7db92b905a25..c9ec86713b03 100644 --- a/src/cryptography/x509/ocsp.py +++ b/src/cryptography/x509/ocsp.py @@ -13,7 +13,9 @@ from cryptography import x509 from cryptography.hazmat.primitives import hashes from cryptography.x509.base import ( - _EARLIEST_UTC_TIME, _convert_to_naive_utc_time, _reject_duplicate_extension + _EARLIEST_UTC_TIME, + _convert_to_naive_utc_time, + _reject_duplicate_extension, ) @@ -42,8 +44,11 @@ class OCSPResponseStatus(Enum): _RESPONSE_STATUS_TO_ENUM = {x.value: x for x in OCSPResponseStatus} _ALLOWED_HASHES = ( - hashes.SHA1, hashes.SHA224, hashes.SHA256, - hashes.SHA384, hashes.SHA512 + hashes.SHA1, + hashes.SHA224, + hashes.SHA256, + hashes.SHA384, + hashes.SHA512, ) @@ -65,11 +70,13 @@ class OCSPCertStatus(Enum): def load_der_ocsp_request(data): from cryptography.hazmat.backends.openssl.backend import backend + return backend.load_der_ocsp_request(data) def load_der_ocsp_response(data): from cryptography.hazmat.backends.openssl.backend import backend + return backend.load_der_ocsp_response(data) @@ -83,9 +90,8 @@ def add_certificate(self, cert, issuer, algorithm): raise ValueError("Only one certificate can be added to a request") _verify_algorithm(algorithm) - if ( - not isinstance(cert, x509.Certificate) or - not isinstance(issuer, x509.Certificate) + if not isinstance(cert, x509.Certificate) or not isinstance( + issuer, x509.Certificate ): raise TypeError("cert and issuer must be a Certificate") @@ -104,6 +110,7 @@ def add_extension(self, extension, critical): def build(self): from cryptography.hazmat.backends.openssl.backend import backend + if self._request is None: raise ValueError("You must add a certificate before building") @@ -111,20 +118,27 @@ def build(self): class _SingleResponse(object): - def __init__(self, cert, issuer, algorithm, cert_status, this_update, - next_update, revocation_time, revocation_reason): - if ( - not isinstance(cert, x509.Certificate) or - not isinstance(issuer, x509.Certificate) + def __init__( + self, + cert, + issuer, + algorithm, + cert_status, + this_update, + next_update, + revocation_time, + revocation_reason, + ): + if not isinstance(cert, x509.Certificate) or not isinstance( + issuer, x509.Certificate ): raise TypeError("cert and issuer must be a Certificate") _verify_algorithm(algorithm) if not isinstance(this_update, datetime.datetime): raise TypeError("this_update must be a datetime object") - if ( - next_update is not None and - not isinstance(next_update, datetime.datetime) + if next_update is not None and not isinstance( + next_update, datetime.datetime ): raise TypeError("next_update must be a datetime object or None") @@ -155,12 +169,13 @@ def __init__(self, cert, issuer, algorithm, cert_status, this_update, revocation_time = _convert_to_naive_utc_time(revocation_time) if revocation_time < _EARLIEST_UTC_TIME: - raise ValueError('The revocation_time must be on or after' - ' 1950 January 1.') + raise ValueError( + "The revocation_time must be on or after" + " 1950 January 1." + ) - if ( - revocation_reason is not None and - not isinstance(revocation_reason, x509.ReasonFlags) + if revocation_reason is not None and not isinstance( + revocation_reason, x509.ReasonFlags ): raise TypeError( "revocation_reason must be an item from the ReasonFlags " @@ -173,25 +188,40 @@ def __init__(self, cert, issuer, algorithm, cert_status, this_update, class OCSPResponseBuilder(object): - def __init__(self, response=None, responder_id=None, certs=None, - extensions=[]): + def __init__( + self, response=None, responder_id=None, certs=None, extensions=[] + ): self._response = response self._responder_id = responder_id self._certs = certs self._extensions = extensions - def add_response(self, cert, issuer, algorithm, cert_status, this_update, - next_update, revocation_time, revocation_reason): + def add_response( + self, + cert, + issuer, + algorithm, + cert_status, + this_update, + next_update, + revocation_time, + revocation_reason, + ): if self._response is not None: raise ValueError("Only one response per OCSPResponse.") singleresp = _SingleResponse( - cert, issuer, algorithm, cert_status, this_update, next_update, - revocation_time, revocation_reason + cert, + issuer, + algorithm, + cert_status, + this_update, + next_update, + revocation_time, + revocation_reason, ) return OCSPResponseBuilder( - singleresp, self._responder_id, - self._certs, self._extensions, + singleresp, self._responder_id, self._certs, self._extensions, ) def responder_id(self, encoding, responder_cert): @@ -205,8 +235,10 @@ def responder_id(self, encoding, responder_cert): ) return OCSPResponseBuilder( - self._response, (responder_cert, encoding), - self._certs, self._extensions, + self._response, + (responder_cert, encoding), + self._certs, + self._extensions, ) def certificates(self, certs): @@ -218,8 +250,7 @@ def certificates(self, certs): if not all(isinstance(x, x509.Certificate) for x in certs): raise TypeError("certs must be a list of Certificates") return OCSPResponseBuilder( - self._response, self._responder_id, - certs, self._extensions, + self._response, self._responder_id, certs, self._extensions, ) def add_extension(self, extension, critical): @@ -230,12 +261,15 @@ def add_extension(self, extension, critical): _reject_duplicate_extension(extension, self._extensions) return OCSPResponseBuilder( - self._response, self._responder_id, - self._certs, self._extensions + [extension], + self._response, + self._responder_id, + self._certs, + self._extensions + [extension], ) def sign(self, private_key, algorithm): from cryptography.hazmat.backends.openssl.backend import backend + if self._response is None: raise ValueError("You must add a response before signing") if self._responder_id is None: @@ -248,6 +282,7 @@ def sign(self, private_key, algorithm): @classmethod def build_unsuccessful(cls, response_status): from cryptography.hazmat.backends.openssl.backend import backend + if not isinstance(response_status, OCSPResponseStatus): raise TypeError( "response_status must be an item from OCSPResponseStatus" @@ -283,6 +318,7 @@ def serial_number(self): """ The serial number of the cert whose status is being checked """ + @abc.abstractmethod def public_bytes(self, encoding): """ diff --git a/src/cryptography/x509/oid.py b/src/cryptography/x509/oid.py index 544904329f08..2bf606e50d6b 100644 --- a/src/cryptography/x509/oid.py +++ b/src/cryptography/x509/oid.py @@ -31,15 +31,11 @@ class ExtensionOID(object): TLS_FEATURE = ObjectIdentifier("1.3.6.1.5.5.7.1.24") CRL_NUMBER = ObjectIdentifier("2.5.29.20") DELTA_CRL_INDICATOR = ObjectIdentifier("2.5.29.27") - PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS = ( - ObjectIdentifier("1.3.6.1.4.1.11129.2.4.2") - ) - PRECERT_POISON = ( - ObjectIdentifier("1.3.6.1.4.1.11129.2.4.3") - ) - SIGNED_CERTIFICATE_TIMESTAMPS = ( - ObjectIdentifier("1.3.6.1.4.1.11129.2.4.5") + PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS = ObjectIdentifier( + "1.3.6.1.4.1.11129.2.4.2" ) + PRECERT_POISON = ObjectIdentifier("1.3.6.1.4.1.11129.2.4.3") + SIGNED_CERTIFICATE_TIMESTAMPS = ObjectIdentifier("1.3.6.1.4.1.11129.2.4.5") class OCSPExtensionOID(object): @@ -106,12 +102,8 @@ class SignatureAlgorithmOID(object): ED25519 = ObjectIdentifier("1.3.101.112") ED448 = ObjectIdentifier("1.3.101.113") GOSTR3411_94_WITH_3410_2001 = ObjectIdentifier("1.2.643.2.2.3") - GOSTR3410_2012_WITH_3411_2012_256 = ObjectIdentifier( - "1.2.643.7.1.1.3.2" - ) - GOSTR3410_2012_WITH_3411_2012_512 = ObjectIdentifier( - "1.2.643.7.1.1.3.3" - ) + GOSTR3410_2012_WITH_3411_2012_256 = ObjectIdentifier("1.2.643.7.1.1.3.2") + GOSTR3410_2012_WITH_3411_2012_512 = ObjectIdentifier("1.2.643.7.1.1.3.3") _SIG_OIDS_TO_HASH = { @@ -199,7 +191,6 @@ class AttributeOID(object): NameOID.OGRN: "OGRN", NameOID.SNILS: "SNILS", NameOID.UNSTRUCTURED_NAME: "unstructuredName", - SignatureAlgorithmOID.RSA_WITH_MD5: "md5WithRSAEncryption", SignatureAlgorithmOID.RSA_WITH_SHA1: "sha1WithRSAEncryption", SignatureAlgorithmOID.RSA_WITH_SHA224: "sha224WithRSAEncryption", @@ -257,9 +248,7 @@ class AttributeOID(object): ExtensionOID.EXTENDED_KEY_USAGE: "extendedKeyUsage", ExtensionOID.FRESHEST_CRL: "freshestCRL", ExtensionOID.INHIBIT_ANY_POLICY: "inhibitAnyPolicy", - ExtensionOID.ISSUING_DISTRIBUTION_POINT: ( - "issuingDistributionPoint" - ), + ExtensionOID.ISSUING_DISTRIBUTION_POINT: ("issuingDistributionPoint"), ExtensionOID.AUTHORITY_INFORMATION_ACCESS: "authorityInfoAccess", ExtensionOID.SUBJECT_INFORMATION_ACCESS: "subjectInfoAccess", ExtensionOID.OCSP_NO_CHECK: "OCSPNoCheck", diff --git a/tests/conftest.py b/tests/conftest.py index d159affc8cc1..4e3124fa76ea 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -9,15 +9,19 @@ from cryptography.hazmat.backends.openssl import backend as openssl_backend from .utils import ( - check_backend_support, load_wycheproof_tests, skip_if_wycheproof_none + check_backend_support, + load_wycheproof_tests, + skip_if_wycheproof_none, ) def pytest_report_header(config): - return "\n".join([ - "OpenSSL: {}".format(openssl_backend.openssl_version_text()), - "FIPS Enabled: {}".format(openssl_backend._fips_enabled), - ]) + return "\n".join( + [ + "OpenSSL: {}".format(openssl_backend.openssl_version_text()), + "FIPS Enabled: {}".format(openssl_backend._fips_enabled), + ] + ) def pytest_addoption(parser): diff --git a/tests/hazmat/backends/test_openssl.py b/tests/hazmat/backends/test_openssl.py index 9d5d6fb4c327..acec247df4a9 100644 --- a/tests/hazmat/backends/test_openssl.py +++ b/tests/hazmat/backends/test_openssl.py @@ -15,9 +15,7 @@ from cryptography import x509 from cryptography.exceptions import InternalError, _Reasons from cryptography.hazmat.backends.interfaces import DHBackend, RSABackend -from cryptography.hazmat.backends.openssl.backend import ( - Backend, backend -) +from cryptography.hazmat.backends.openssl.backend import Backend, backend from cryptography.hazmat.backends.openssl.ec import _sn_to_elliptic_curve from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import dh, dsa, padding @@ -27,16 +25,21 @@ from ..primitives.fixtures_rsa import RSA_KEY_2048, RSA_KEY_512 from ...doubles import ( - DummyAsymmetricPadding, DummyCipherAlgorithm, DummyHashAlgorithm, DummyMode + DummyAsymmetricPadding, + DummyCipherAlgorithm, + DummyHashAlgorithm, + DummyMode, ) from ...utils import ( - load_nist_vectors, load_vectors_from_file, raises_unsupported_algorithm + load_nist_vectors, + load_vectors_from_file, + raises_unsupported_algorithm, ) from ...x509.test_x509 import _load_cert def skip_if_libre_ssl(openssl_version): - if u'LibreSSL' in openssl_version: + if u"LibreSSL" in openssl_version: pytest.skip("LibreSSL hard-codes RAND_bytes to use arc4random.") @@ -66,10 +69,9 @@ def test_openssl_version_text(self): if it starts with OpenSSL or LibreSSL as that appears to be true for every OpenSSL-alike. """ - assert ( - backend.openssl_version_text().startswith("OpenSSL") or - backend.openssl_version_text().startswith("LibreSSL") - ) + assert backend.openssl_version_text().startswith( + "OpenSSL" + ) or backend.openssl_version_text().startswith("LibreSSL") def test_openssl_version_number(self): assert backend.openssl_version_number() > 0 @@ -87,11 +89,9 @@ def test_nonexistent_cipher(self, mode): b.register_cipher_adapter( DummyCipherAlgorithm, type(mode), - lambda backend, cipher, mode: backend._ffi.NULL - ) - cipher = Cipher( - DummyCipherAlgorithm(), mode, backend=b, + lambda backend, cipher, mode: backend._ffi.NULL, ) + cipher = Cipher(DummyCipherAlgorithm(), mode, backend=b,) with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_CIPHER): cipher.encryptor() @@ -102,8 +102,9 @@ def test_openssl_assert(self): def test_consume_errors(self): for i in range(10): - backend._lib.ERR_put_error(backend._lib.ERR_LIB_EVP, 0, 0, - b"test_openssl.py", -1) + backend._lib.ERR_put_error( + backend._lib.ERR_LIB_EVP, 0, 0, b"test_openssl.py", -1 + ) assert backend._lib.ERR_peek_error() != 0 @@ -131,8 +132,7 @@ def test_unknown_error_in_cipher_finalize(self): cipher = Cipher(AES(b"\0" * 16), CBC(b"\0" * 16), backend=backend) enc = cipher.encryptor() enc.update(b"\0") - backend._lib.ERR_put_error(0, 0, 1, - b"test_openssl.py", -1) + backend._lib.ERR_put_error(0, 0, 1, b"test_openssl.py", -1) with pytest.raises(InternalError): enc.finalize() @@ -170,7 +170,8 @@ def test_bn_to_int(self): @pytest.mark.skipif( not backend._lib.CRYPTOGRAPHY_NEEDS_OSRANDOM_ENGINE, - reason="Requires OpenSSL with ENGINE support and OpenSSL < 1.1.1d") + reason="Requires OpenSSL with ENGINE support and OpenSSL < 1.1.1d", +) @pytest.mark.skip_fips(reason="osrandom engine disabled for FIPS") class TestOpenSSLRandomEngine(object): def setup(self): @@ -190,8 +191,9 @@ def teardown(self): name = backend._lib.ENGINE_get_name(current_default) assert name == backend._lib.Cryptography_osrandom_engine_name - @pytest.mark.skipif(sys.executable is None, - reason="No Python interpreter available.") + @pytest.mark.skipif( + sys.executable is None, reason="No Python interpreter available." + ) def test_osrandom_engine_is_default(self, tmpdir): engine_printer = textwrap.dedent( """ @@ -205,7 +207,7 @@ def test_osrandom_engine_is_default(self, tmpdir): assert res == 1 """ ) - engine_name = tmpdir.join('engine_name') + engine_name = tmpdir.join("engine_name") # If we're running tests via ``python setup.py test`` in a clean # environment then all of our dependencies are going to be installed @@ -216,7 +218,7 @@ def test_osrandom_engine_is_default(self, tmpdir): env = os.environ.copy() env["PYTHONPATH"] = os.pathsep.join(sys.path) - with engine_name.open('w') as out: + with engine_name.open("w") as out: subprocess.check_call( [sys.executable, "-c", engine_printer], env=env, @@ -228,7 +230,7 @@ def test_osrandom_engine_is_default(self, tmpdir): backend._lib.Cryptography_osrandom_engine_name ) - assert engine_name.read().encode('ascii') == osrandom_engine_name + assert engine_name.read().encode("ascii") == osrandom_engine_name def test_osrandom_sanity_check(self): # This test serves as a check against catastrophic failure. @@ -269,14 +271,18 @@ def test_activate_builtin_random_already_active(self): def test_osrandom_engine_implementation(self): name = backend.osrandom_engine_implementation() - assert name in ['/dev/urandom', 'CryptGenRandom', 'getentropy', - 'getrandom'] - if sys.platform.startswith('linux'): - assert name in ['getrandom', '/dev/urandom'] - if sys.platform == 'darwin': - assert name in ['getentropy', '/dev/urandom'] - if sys.platform == 'win32': - assert name == 'CryptGenRandom' + assert name in [ + "/dev/urandom", + "CryptGenRandom", + "getentropy", + "getrandom", + ] + if sys.platform.startswith("linux"): + assert name in ["getrandom", "/dev/urandom"] + if sys.platform == "darwin": + assert name in ["getentropy", "/dev/urandom"] + if sys.platform == "win32": + assert name == "CryptGenRandom" def test_activate_osrandom_already_default(self): e = backend._lib.ENGINE_get_default_RAND() @@ -294,15 +300,18 @@ def test_activate_osrandom_already_default(self): @pytest.mark.skipif( backend._lib.CRYPTOGRAPHY_NEEDS_OSRANDOM_ENGINE, - reason="Requires OpenSSL without ENGINE support or OpenSSL >=1.1.1d") + reason="Requires OpenSSL without ENGINE support or OpenSSL >=1.1.1d", +) class TestOpenSSLNoEngine(object): def test_no_engine_support(self): - assert backend._ffi.string( - backend._lib.Cryptography_osrandom_engine_id - ) == b"no-engine-support" - assert backend._ffi.string( - backend._lib.Cryptography_osrandom_engine_name - ) == b"osrandom_engine disabled" + assert ( + backend._ffi.string(backend._lib.Cryptography_osrandom_engine_id) + == b"no-engine-support" + ) + assert ( + backend._ffi.string(backend._lib.Cryptography_osrandom_engine_name) + == b"osrandom_engine disabled" + ) def test_activate_builtin_random_does_nothing(self): backend.activate_builtin_random() @@ -327,17 +336,24 @@ def test_generate_bad_public_exponent(self): def test_cant_generate_insecure_tiny_key(self): with pytest.raises(ValueError): - backend.generate_rsa_private_key(public_exponent=65537, - key_size=511) + backend.generate_rsa_private_key( + public_exponent=65537, key_size=511 + ) with pytest.raises(ValueError): - backend.generate_rsa_private_key(public_exponent=65537, - key_size=256) + backend.generate_rsa_private_key( + public_exponent=65537, key_size=256 + ) def test_rsa_padding_unsupported_pss_mgf1_hash(self): - assert backend.rsa_padding_supported( - padding.PSS(mgf=padding.MGF1(DummyHashAlgorithm()), salt_length=0) - ) is False + assert ( + backend.rsa_padding_supported( + padding.PSS( + mgf=padding.MGF1(DummyHashAlgorithm()), salt_length=0 + ) + ) + is False + ) def test_rsa_padding_unsupported(self): assert backend.rsa_padding_supported(DummyAsymmetricPadding()) is False @@ -346,22 +362,28 @@ def test_rsa_padding_supported_pkcs1v15(self): assert backend.rsa_padding_supported(padding.PKCS1v15()) is True def test_rsa_padding_supported_pss(self): - assert backend.rsa_padding_supported( - padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=0) - ) is True + assert ( + backend.rsa_padding_supported( + padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=0) + ) + is True + ) def test_rsa_padding_supported_oaep(self): - assert backend.rsa_padding_supported( - padding.OAEP( - mgf=padding.MGF1(algorithm=hashes.SHA1()), - algorithm=hashes.SHA1(), - label=None - ), - ) is True + assert ( + backend.rsa_padding_supported( + padding.OAEP( + mgf=padding.MGF1(algorithm=hashes.SHA1()), + algorithm=hashes.SHA1(), + label=None, + ), + ) + is True + ) @pytest.mark.skipif( backend._lib.Cryptography_HAS_RSA_OAEP_MD == 0, - reason="Requires OpenSSL with rsa_oaep_md (1.0.2+)" + reason="Requires OpenSSL with rsa_oaep_md (1.0.2+)", ) def test_rsa_padding_supported_oaep_sha2_combinations(self): hashalgs = [ @@ -372,30 +394,37 @@ def test_rsa_padding_supported_oaep_sha2_combinations(self): hashes.SHA512(), ] for mgf1alg, oaepalg in itertools.product(hashalgs, hashalgs): - assert backend.rsa_padding_supported( - padding.OAEP( - mgf=padding.MGF1(algorithm=mgf1alg), - algorithm=oaepalg, - label=None - ), - ) is True + assert ( + backend.rsa_padding_supported( + padding.OAEP( + mgf=padding.MGF1(algorithm=mgf1alg), + algorithm=oaepalg, + label=None, + ), + ) + is True + ) def test_rsa_padding_unsupported_mgf(self): - assert backend.rsa_padding_supported( - padding.OAEP( - mgf=DummyMGF(), - algorithm=hashes.SHA1(), - label=None - ), - ) is False + assert ( + backend.rsa_padding_supported( + padding.OAEP( + mgf=DummyMGF(), algorithm=hashes.SHA1(), label=None + ), + ) + is False + ) - assert backend.rsa_padding_supported( - padding.PSS(mgf=DummyMGF(), salt_length=0) - ) is False + assert ( + backend.rsa_padding_supported( + padding.PSS(mgf=DummyMGF(), salt_length=0) + ) + is False + ) @pytest.mark.skipif( backend._lib.Cryptography_HAS_RSA_OAEP_MD == 1, - reason="Requires OpenSSL without rsa_oaep_md (< 1.0.2)" + reason="Requires OpenSSL without rsa_oaep_md (< 1.0.2)", ) def test_unsupported_mgf1_hash_algorithm_decrypt(self): private_key = RSA_KEY_512.private_key(backend) @@ -405,13 +434,13 @@ def test_unsupported_mgf1_hash_algorithm_decrypt(self): padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA1(), - label=None - ) + label=None, + ), ) @pytest.mark.skipif( backend._lib.Cryptography_HAS_RSA_OAEP_MD == 1, - reason="Requires OpenSSL without rsa_oaep_md (< 1.0.2)" + reason="Requires OpenSSL without rsa_oaep_md (< 1.0.2)", ) def test_unsupported_oaep_hash_algorithm_decrypt(self): private_key = RSA_KEY_512.private_key(backend) @@ -421,8 +450,8 @@ def test_unsupported_oaep_hash_algorithm_decrypt(self): padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA256(), - label=None - ) + label=None, + ), ) def test_unsupported_mgf1_hash_algorithm_md5_decrypt(self): @@ -433,8 +462,8 @@ def test_unsupported_mgf1_hash_algorithm_md5_decrypt(self): padding.OAEP( mgf=padding.MGF1(algorithm=hashes.MD5()), algorithm=hashes.MD5(), - label=None - ) + label=None, + ), ) @@ -519,14 +548,15 @@ def test_very_long_pem_serialization_password(self): with pytest.raises(ValueError): load_vectors_from_file( os.path.join( - "asymmetric", "Traditional_OpenSSL_Serialization", - "key1.pem" + "asymmetric", + "Traditional_OpenSSL_Serialization", + "key1.pem", ), lambda pemfile: ( backend.load_pem_private_key( pemfile.read().encode(), password ) - ) + ), ) @@ -545,7 +575,7 @@ def test_password_length_limit(self): key.private_bytes( serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, - serialization.BestAvailableEncryption(password) + serialization.BestAvailableEncryption(password), ) @@ -554,7 +584,7 @@ def test_numeric_string_x509_name_entry(self): cert = _load_cert( os.path.join("x509", "e-trust.ru.der"), x509.load_der_x509_certificate, - backend + backend, ) if backend._lib.CRYPTOGRAPHY_OPENSSL_LESS_THAN_102I: with pytest.raises(ValueError) as exc: @@ -565,42 +595,49 @@ def test_numeric_string_x509_name_entry(self): # erroneously pass. assert str(exc.value) == "Unsupported ASN1 string type. Type: 18" else: - assert cert.subject.get_attributes_for_oid( - x509.ObjectIdentifier("1.2.643.3.131.1.1") - )[0].value == "007710474375" + assert ( + cert.subject.get_attributes_for_oid( + x509.ObjectIdentifier("1.2.643.3.131.1.1") + )[0].value + == "007710474375" + ) @pytest.mark.skipif( backend._lib.Cryptography_HAS_EVP_PKEY_DHX == 1, - reason="Requires OpenSSL without EVP_PKEY_DHX (< 1.0.2)") + reason="Requires OpenSSL without EVP_PKEY_DHX (< 1.0.2)", +) @pytest.mark.requires_backend_interface(interface=DHBackend) class TestOpenSSLDHSerialization(object): - @pytest.mark.parametrize( "vector", load_vectors_from_file( - os.path.join("asymmetric", "DH", "RFC5114.txt"), - load_nist_vectors)) + os.path.join("asymmetric", "DH", "RFC5114.txt"), load_nist_vectors + ), + ) def test_dh_serialization_with_q_unsupported(self, backend, vector): - parameters = dh.DHParameterNumbers(int(vector["p"], 16), - int(vector["g"], 16), - int(vector["q"], 16)) + parameters = dh.DHParameterNumbers( + int(vector["p"], 16), int(vector["g"], 16), int(vector["q"], 16) + ) public = dh.DHPublicNumbers(int(vector["ystatcavs"], 16), parameters) private = dh.DHPrivateNumbers(int(vector["xstatcavs"], 16), public) private_key = private.private_key(backend) public_key = private_key.public_key() with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_SERIALIZATION): - private_key.private_bytes(serialization.Encoding.PEM, - serialization.PrivateFormat.PKCS8, - serialization.NoEncryption()) + private_key.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ) with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_SERIALIZATION): public_key.public_bytes( serialization.Encoding.PEM, - serialization.PublicFormat.SubjectPublicKeyInfo) + serialization.PublicFormat.SubjectPublicKeyInfo, + ) with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_SERIALIZATION): parameters.parameters(backend).parameter_bytes( - serialization.Encoding.PEM, - serialization.ParameterFormat.PKCS3) + serialization.Encoding.PEM, serialization.ParameterFormat.PKCS3 + ) @pytest.mark.parametrize( ("key_path", "loader_func"), @@ -612,14 +649,14 @@ def test_dh_serialization_with_q_unsupported(self, backend, vector): ( os.path.join("asymmetric", "DH", "dhkey_rfc5114_2.der"), serialization.load_der_private_key, - ) - ] + ), + ], ) - def test_private_load_dhx_unsupported(self, key_path, loader_func, - backend): + def test_private_load_dhx_unsupported( + self, key_path, loader_func, backend + ): key_bytes = load_vectors_from_file( - key_path, - lambda pemfile: pemfile.read(), mode="rb" + key_path, lambda pemfile: pemfile.read(), mode="rb" ) with pytest.raises(ValueError): loader_func(key_bytes, None, backend) @@ -634,14 +671,12 @@ def test_private_load_dhx_unsupported(self, key_path, loader_func, ( os.path.join("asymmetric", "DH", "dhpub_rfc5114_2.der"), serialization.load_der_public_key, - ) - ] + ), + ], ) - def test_public_load_dhx_unsupported(self, key_path, loader_func, - backend): + def test_public_load_dhx_unsupported(self, key_path, loader_func, backend): key_bytes = load_vectors_from_file( - key_path, - lambda pemfile: pemfile.read(), mode="rb" + key_path, lambda pemfile: pemfile.read(), mode="rb" ) with pytest.raises(ValueError): loader_func(key_bytes, backend) diff --git a/tests/hazmat/backends/test_openssl_memleak.py b/tests/hazmat/backends/test_openssl_memleak.py index b188fe5babaf..96b5f2ae0930 100644 --- a/tests/hazmat/backends/test_openssl_memleak.py +++ b/tests/hazmat/backends/test_openssl_memleak.py @@ -128,15 +128,14 @@ def assert_no_memory_leaks(s, argv=[]): env = os.environ.copy() env["PYTHONPATH"] = os.pathsep.join(sys.path) argv = [ - sys.executable, "-c", "{}\n\n{}".format(s, MEMORY_LEAK_SCRIPT) + sys.executable, + "-c", + "{}\n\n{}".format(s, MEMORY_LEAK_SCRIPT), ] + argv # Shell out to a fresh Python process because OpenSSL does not allow you to # install new memory hooks after the first malloc/free occurs. proc = subprocess.Popen( - argv, - env=env, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, + argv, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) try: proc.wait() @@ -156,7 +155,7 @@ def assert_no_memory_leaks(s, argv=[]): def skip_if_memtesting_not_supported(): return pytest.mark.skipif( not Binding().lib.Cryptography_HAS_MEM_FUNCTIONS, - reason="Requires OpenSSL memory functions (>=1.1.0)" + reason="Requires OpenSSL memory functions (>=1.1.0)", ) @@ -164,56 +163,78 @@ def skip_if_memtesting_not_supported(): @skip_if_memtesting_not_supported() class TestAssertNoMemoryLeaks(object): def test_no_leak_no_malloc(self): - assert_no_memory_leaks(textwrap.dedent(""" + assert_no_memory_leaks( + textwrap.dedent( + """ def func(): pass - """)) + """ + ) + ) def test_no_leak_free(self): - assert_no_memory_leaks(textwrap.dedent(""" + assert_no_memory_leaks( + textwrap.dedent( + """ def func(): from cryptography.hazmat.bindings.openssl.binding import Binding b = Binding() name = b.lib.X509_NAME_new() b.lib.X509_NAME_free(name) - """)) + """ + ) + ) def test_no_leak_gc(self): - assert_no_memory_leaks(textwrap.dedent(""" + assert_no_memory_leaks( + textwrap.dedent( + """ def func(): from cryptography.hazmat.bindings.openssl.binding import Binding b = Binding() name = b.lib.X509_NAME_new() b.ffi.gc(name, b.lib.X509_NAME_free) - """)) + """ + ) + ) def test_leak(self): with pytest.raises(AssertionError): - assert_no_memory_leaks(textwrap.dedent(""" + assert_no_memory_leaks( + textwrap.dedent( + """ def func(): from cryptography.hazmat.bindings.openssl.binding import ( Binding ) b = Binding() b.lib.X509_NAME_new() - """)) + """ + ) + ) def test_errors(self): with pytest.raises(ValueError): - assert_no_memory_leaks(textwrap.dedent(""" + assert_no_memory_leaks( + textwrap.dedent( + """ def func(): raise ZeroDivisionError - """)) + """ + ) + ) @pytest.mark.skip_fips(reason="FIPS self-test sets allow_customize = 0") @skip_if_memtesting_not_supported() class TestOpenSSLMemoryLeaks(object): - @pytest.mark.parametrize("path", [ - "x509/PKITS_data/certs/ValidcRLIssuerTest28EE.crt", - ]) + @pytest.mark.parametrize( + "path", ["x509/PKITS_data/certs/ValidcRLIssuerTest28EE.crt"] + ) def test_der_x509_certificate_extensions(self, path): - assert_no_memory_leaks(textwrap.dedent(""" + assert_no_memory_leaks( + textwrap.dedent( + """ def func(path): from cryptography import x509 from cryptography.hazmat.backends.openssl import backend @@ -226,13 +247,16 @@ def func(path): ) cert.extensions - """), [path]) + """ + ), + [path], + ) - @pytest.mark.parametrize("path", [ - "x509/cryptography.io.pem", - ]) + @pytest.mark.parametrize("path", ["x509/cryptography.io.pem"]) def test_pem_x509_certificate_extensions(self, path): - assert_no_memory_leaks(textwrap.dedent(""" + assert_no_memory_leaks( + textwrap.dedent( + """ def func(path): from cryptography import x509 from cryptography.hazmat.backends.openssl import backend @@ -245,10 +269,15 @@ def func(path): ) cert.extensions - """), [path]) + """ + ), + [path], + ) def test_x509_csr_extensions(self): - assert_no_memory_leaks(textwrap.dedent(""" + assert_no_memory_leaks( + textwrap.dedent( + """ def func(): from cryptography import x509 from cryptography.hazmat.backends.openssl import backend @@ -265,10 +294,14 @@ def func(): ).sign(private_key, hashes.SHA256(), backend) cert.extensions - """)) + """ + ) + ) def test_ec_private_numbers_private_key(self): - assert_no_memory_leaks(textwrap.dedent(""" + assert_no_memory_leaks( + textwrap.dedent( + """ def func(): from cryptography.hazmat.backends.openssl import backend from cryptography.hazmat.primitives.asymmetric import ec @@ -290,26 +323,38 @@ def func(): ) ) ).private_key(backend) - """)) + """ + ) + ) def test_ec_derive_private_key(self): - assert_no_memory_leaks(textwrap.dedent(""" + assert_no_memory_leaks( + textwrap.dedent( + """ def func(): from cryptography.hazmat.backends.openssl import backend from cryptography.hazmat.primitives.asymmetric import ec ec.derive_private_key(1, ec.SECP256R1(), backend) - """)) + """ + ) + ) def test_x25519_pubkey_from_private_key(self): - assert_no_memory_leaks(textwrap.dedent(""" + assert_no_memory_leaks( + textwrap.dedent( + """ def func(): from cryptography.hazmat.primitives.asymmetric import x25519 private_key = x25519.X25519PrivateKey.generate() private_key.public_key() - """)) + """ + ) + ) def test_create_ocsp_request(self): - assert_no_memory_leaks(textwrap.dedent(""" + assert_no_memory_leaks( + textwrap.dedent( + """ def func(): from cryptography import x509 from cryptography.hazmat.backends.openssl import backend @@ -327,14 +372,18 @@ def func(): cert, cert, hashes.SHA1() ).add_extension(x509.OCSPNonce(b"0000"), False) req = builder.build() - """)) + """ + ) + ) - @pytest.mark.parametrize("path", [ - "pkcs12/cert-aes256cbc-no-key.p12", - "pkcs12/cert-key-aes256cbc.p12", - ]) + @pytest.mark.parametrize( + "path", + ["pkcs12/cert-aes256cbc-no-key.p12", "pkcs12/cert-key-aes256cbc.p12"], + ) def test_load_pkcs12_key_and_certificates(self, path): - assert_no_memory_leaks(textwrap.dedent(""" + assert_no_memory_leaks( + textwrap.dedent( + """ def func(path): from cryptography import x509 from cryptography.hazmat.backends.openssl import backend @@ -345,10 +394,15 @@ def func(path): pkcs12.load_key_and_certificates( f.read(), b"cryptography", backend ) - """), [path]) + """ + ), + [path], + ) def test_create_crl_with_idp(self): - assert_no_memory_leaks(textwrap.dedent(""" + assert_no_memory_leaks( + textwrap.dedent( + """ def func(): import datetime from cryptography import x509 @@ -390,10 +444,14 @@ def func(): crl.extensions.get_extension_for_class( x509.IssuingDistributionPoint ) - """)) + """ + ) + ) def test_create_certificate_with_extensions(self): - assert_no_memory_leaks(textwrap.dedent(""" + assert_no_memory_leaks( + textwrap.dedent( + """ def func(): import datetime @@ -450,10 +508,14 @@ def func(): cert = builder.sign(private_key, hashes.SHA256(), backend) cert.extensions - """)) + """ + ) + ) def test_write_pkcs12_key_and_certificates(self): - assert_no_memory_leaks(textwrap.dedent(""" + assert_no_memory_leaks( + textwrap.dedent( + """ def func(): import os from cryptography import x509 @@ -485,4 +547,6 @@ def func(): encryption = serialization.NoEncryption() pkcs12.serialize_key_and_certificates( b"name", key, cert, [cert2, cert3], encryption) - """)) + """ + ) + ) diff --git a/tests/hazmat/bindings/test_openssl.py b/tests/hazmat/bindings/test_openssl.py index 29a1c459fa96..a4f6ac015695 100644 --- a/tests/hazmat/bindings/test_openssl.py +++ b/tests/hazmat/bindings/test_openssl.py @@ -8,7 +8,10 @@ from cryptography.exceptions import InternalError from cryptography.hazmat.bindings.openssl.binding import ( - Binding, _consume_errors, _openssl_assert, _verify_package_version + Binding, + _consume_errors, + _openssl_assert, + _verify_package_version, ) @@ -95,7 +98,7 @@ def test_openssl_assert_error_on_stack(self): b.lib.EVP_F_EVP_ENCRYPTFINAL_EX, b.lib.EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH, b"", - -1 + -1, ) with pytest.raises(InternalError) as exc_info: _openssl_assert(b.lib, False) @@ -114,7 +117,7 @@ def test_check_startup_errors_are_allowed(self): b.lib.EVP_F_EVP_ENCRYPTFINAL_EX, b.lib.EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH, b"", - -1 + -1, ) b._register_osrandom_engine() assert _consume_errors(b.lib) == [] diff --git a/tests/hazmat/primitives/fixtures_dh.py b/tests/hazmat/primitives/fixtures_dh.py index f4698bc0c30b..b766c4265837 100644 --- a/tests/hazmat/primitives/fixtures_dh.py +++ b/tests/hazmat/primitives/fixtures_dh.py @@ -19,6 +19,8 @@ "d6e6c9077ad91d2691f7f7ee598cb0fac186d91caefe130985139270b4130c93bc4" "37944f4fd4452e2d74dd364f2e21e71f54bff5cae82ab9c9df69ee86d2bc522363a" "0dabc521979b0deada1dbf9a42d5c4484e0abcd06bfa53ddef3c1b20ee3fd59d7c2" - "5e41d2b66c62e37ffffffffffffffff", 16 - ), g=2 + "5e41d2b66c62e37ffffffffffffffff", + 16, + ), + g=2, ) diff --git a/tests/hazmat/primitives/fixtures_dsa.py b/tests/hazmat/primitives/fixtures_dsa.py index dd947ae82257..d4568ead7306 100644 --- a/tests/hazmat/primitives/fixtures_dsa.py +++ b/tests/hazmat/primitives/fixtures_dsa.py @@ -5,7 +5,9 @@ from __future__ import absolute_import, division, print_function from cryptography.hazmat.primitives.asymmetric.dsa import ( - DSAParameterNumbers, DSAPrivateNumbers, DSAPublicNumbers + DSAParameterNumbers, + DSAPrivateNumbers, + DSAPublicNumbers, ) @@ -13,140 +15,147 @@ public_numbers=DSAPublicNumbers( parameter_numbers=DSAParameterNumbers( p=int( - 'd38311e2cd388c3ed698e82fdf88eb92b5a9a483dc88005d4b725ef34' - '1eabb47cf8a7a8a41e792a156b7ce97206c4f9c5ce6fc5ae7912102b6' - 'b502e59050b5b21ce263dddb2044b652236f4d42ab4b5d6aa73189cef' - '1ace778d7845a5c1c1c7147123188f8dc551054ee162b634d60f097f7' - '19076640e20980a0093113a8bd73', 16 + "d38311e2cd388c3ed698e82fdf88eb92b5a9a483dc88005d4b725ef34" + "1eabb47cf8a7a8a41e792a156b7ce97206c4f9c5ce6fc5ae7912102b6" + "b502e59050b5b21ce263dddb2044b652236f4d42ab4b5d6aa73189cef" + "1ace778d7845a5c1c1c7147123188f8dc551054ee162b634d60f097f7" + "19076640e20980a0093113a8bd73", + 16, ), - q=int('96c5390a8b612c0e422bb2b0ea194a3ec935a281', 16), + q=int("96c5390a8b612c0e422bb2b0ea194a3ec935a281", 16), g=int( - '06b7861abbd35cc89e79c52f68d20875389b127361ca66822138ce499' - '1d2b862259d6b4548a6495b195aa0e0b6137ca37eb23b94074d3c3d30' - '0042bdf15762812b6333ef7b07ceba78607610fcc9ee68491dbc1e34c' - 'd12615474e52b18bc934fb00c61d39e7da8902291c4434a4e2224c3f4' - 'fd9f93cd6f4f17fc076341a7e7d9', 16 - ) + "06b7861abbd35cc89e79c52f68d20875389b127361ca66822138ce499" + "1d2b862259d6b4548a6495b195aa0e0b6137ca37eb23b94074d3c3d30" + "0042bdf15762812b6333ef7b07ceba78607610fcc9ee68491dbc1e34c" + "d12615474e52b18bc934fb00c61d39e7da8902291c4434a4e2224c3f4" + "fd9f93cd6f4f17fc076341a7e7d9", + 16, + ), ), y=int( - '6f26d98d41de7d871b6381851c9d91fa03942092ab6097e76422070edb71d' - 'b44ff568280fdb1709f8fc3feab39f1f824adaeb2a298088156ac31af1aa0' - '4bf54f475bdcfdcf2f8a2dd973e922d83e76f016558617603129b21c70bf7' - 'd0e5dc9e68fe332e295b65876eb9a12fe6fca9f1a1ce80204646bf99b5771' - 'd249a6fea627', 16 - ) + "6f26d98d41de7d871b6381851c9d91fa03942092ab6097e76422070edb71d" + "b44ff568280fdb1709f8fc3feab39f1f824adaeb2a298088156ac31af1aa0" + "4bf54f475bdcfdcf2f8a2dd973e922d83e76f016558617603129b21c70bf7" + "d0e5dc9e68fe332e295b65876eb9a12fe6fca9f1a1ce80204646bf99b5771" + "d249a6fea627", + 16, + ), ), - x=int('8185fee9cc7c0e91fd85503274f1cd5a3fd15a49', 16) + x=int("8185fee9cc7c0e91fd85503274f1cd5a3fd15a49", 16), ) DSA_KEY_2048 = DSAPrivateNumbers( public_numbers=DSAPublicNumbers( parameter_numbers=DSAParameterNumbers( p=int( - 'ea1fb1af22881558ef93be8a5f8653c5a559434c49c8c2c12ace5e9c4' - '1434c9cf0a8e9498acb0f4663c08b4484eace845f6fb17dac62c98e70' - '6af0fc74e4da1c6c2b3fbf5a1d58ff82fc1a66f3e8b12252c40278fff' - '9dd7f102eed2cb5b7323ebf1908c234d935414dded7f8d244e54561b0' - 'dca39b301de8c49da9fb23df33c6182e3f983208c560fb5119fbf78eb' - 'e3e6564ee235c6a15cbb9ac247baba5a423bc6582a1a9d8a2b4f0e9e3' - 'd9dbac122f750dd754325135257488b1f6ecabf21bff2947fe0d3b2cb' - '7ffe67f4e7fcdf1214f6053e72a5bb0dd20a0e9fe6db2df0a908c36e9' - '5e60bf49ca4368b8b892b9c79f61ef91c47567c40e1f80ac5aa66ef7', - 16 + "ea1fb1af22881558ef93be8a5f8653c5a559434c49c8c2c12ace5e9c4" + "1434c9cf0a8e9498acb0f4663c08b4484eace845f6fb17dac62c98e70" + "6af0fc74e4da1c6c2b3fbf5a1d58ff82fc1a66f3e8b12252c40278fff" + "9dd7f102eed2cb5b7323ebf1908c234d935414dded7f8d244e54561b0" + "dca39b301de8c49da9fb23df33c6182e3f983208c560fb5119fbf78eb" + "e3e6564ee235c6a15cbb9ac247baba5a423bc6582a1a9d8a2b4f0e9e3" + "d9dbac122f750dd754325135257488b1f6ecabf21bff2947fe0d3b2cb" + "7ffe67f4e7fcdf1214f6053e72a5bb0dd20a0e9fe6db2df0a908c36e9" + "5e60bf49ca4368b8b892b9c79f61ef91c47567c40e1f80ac5aa66ef7", + 16, ), q=int( - '8ec73f3761caf5fdfe6e4e82098bf10f898740dcb808204bf6b18f507' - '192c19d', 16 + "8ec73f3761caf5fdfe6e4e82098bf10f898740dcb808204bf6b18f507" + "192c19d", + 16, ), g=int( - 'e4c4eca88415b23ecf811c96e48cd24200fe916631a68a684e6ccb6b1' - '913413d344d1d8d84a333839d88eee431521f6e357c16e6a93be111a9' - '8076739cd401bab3b9d565bf4fb99e9d185b1e14d61c93700133f908b' - 'ae03e28764d107dcd2ea7674217622074bb19efff482f5f5c1a86d555' - '1b2fc68d1c6e9d8011958ef4b9c2a3a55d0d3c882e6ad7f9f0f3c6156' - '8f78d0706b10a26f23b4f197c322b825002284a0aca91807bba98ece9' - '12b80e10cdf180cf99a35f210c1655fbfdd74f13b1b5046591f840387' - '3d12239834dd6c4eceb42bf7482e1794a1601357b629ddfa971f2ed27' - '3b146ec1ca06d0adf55dd91d65c37297bda78c6d210c0bc26e558302', - 16 - ) + "e4c4eca88415b23ecf811c96e48cd24200fe916631a68a684e6ccb6b1" + "913413d344d1d8d84a333839d88eee431521f6e357c16e6a93be111a9" + "8076739cd401bab3b9d565bf4fb99e9d185b1e14d61c93700133f908b" + "ae03e28764d107dcd2ea7674217622074bb19efff482f5f5c1a86d555" + "1b2fc68d1c6e9d8011958ef4b9c2a3a55d0d3c882e6ad7f9f0f3c6156" + "8f78d0706b10a26f23b4f197c322b825002284a0aca91807bba98ece9" + "12b80e10cdf180cf99a35f210c1655fbfdd74f13b1b5046591f840387" + "3d12239834dd6c4eceb42bf7482e1794a1601357b629ddfa971f2ed27" + "3b146ec1ca06d0adf55dd91d65c37297bda78c6d210c0bc26e558302", + 16, + ), ), y=int( - '6b32e31ab9031dc4dd0b5039a78d07826687ab087ae6de4736f5b0434e125' - '3092e8a0b231f9c87f3fc8a4cb5634eb194bf1b638b7a7889620ce6711567' - 'e36aa36cda4604cfaa601a45918371d4ccf68d8b10a50a0460eb1dc0fff62' - 'ef5e6ee4d473e18ea4a66c196fb7e677a49b48241a0b4a97128eff30fa437' - '050501a584f8771e7280d26d5af30784039159c11ebfea10b692fd0a58215' - 'eeb18bff117e13f08db792ed4151a218e4bed8dddfb0793225bd1e9773505' - '166f4bd8cedbb286ea28232972da7bae836ba97329ba6b0a36508e50a52a7' - '675e476d4d4137eae13f22a9d2fefde708ba8f34bf336c6e76331761e4b06' - '17633fe7ec3f23672fb19d27', 16 - ) + "6b32e31ab9031dc4dd0b5039a78d07826687ab087ae6de4736f5b0434e125" + "3092e8a0b231f9c87f3fc8a4cb5634eb194bf1b638b7a7889620ce6711567" + "e36aa36cda4604cfaa601a45918371d4ccf68d8b10a50a0460eb1dc0fff62" + "ef5e6ee4d473e18ea4a66c196fb7e677a49b48241a0b4a97128eff30fa437" + "050501a584f8771e7280d26d5af30784039159c11ebfea10b692fd0a58215" + "eeb18bff117e13f08db792ed4151a218e4bed8dddfb0793225bd1e9773505" + "166f4bd8cedbb286ea28232972da7bae836ba97329ba6b0a36508e50a52a7" + "675e476d4d4137eae13f22a9d2fefde708ba8f34bf336c6e76331761e4b06" + "17633fe7ec3f23672fb19d27", + 16, + ), ), x=int( - '405772da6e90d809e77d5de796562a2dd4dfd10ef00a83a3aba6bd818a0348a1', - 16 - ) + "405772da6e90d809e77d5de796562a2dd4dfd10ef00a83a3aba6bd818a0348a1", 16 + ), ) DSA_KEY_3072 = DSAPrivateNumbers( public_numbers=DSAPublicNumbers( parameter_numbers=DSAParameterNumbers( p=int( - 'f335666dd1339165af8b9a5e3835adfe15c158e4c3c7bd53132e7d582' - '8c352f593a9a787760ce34b789879941f2f01f02319f6ae0b756f1a84' - '2ba54c85612ed632ee2d79ef17f06b77c641b7b080aff52a03fc2462e' - '80abc64d223723c236deeb7d201078ec01ca1fbc1763139e25099a84e' - 'c389159c409792080736bd7caa816b92edf23f2c351f90074aa5ea265' - '1b372f8b58a0a65554db2561d706a63685000ac576b7e4562e262a142' - '85a9c6370b290e4eb7757527d80b6c0fd5df831d36f3d1d35f12ab060' - '548de1605fd15f7c7aafed688b146a02c945156e284f5b71282045aba' - '9844d48b5df2e9e7a5887121eae7d7b01db7cdf6ff917cd8eb50c6bf1' - 'd54f90cce1a491a9c74fea88f7e7230b047d16b5a6027881d6f154818' - 'f06e513faf40c8814630e4e254f17a47bfe9cb519b98289935bf17673' - 'ae4c8033504a20a898d0032ee402b72d5986322f3bdfb27400561f747' - '6cd715eaabb7338b854e51fc2fa026a5a579b6dcea1b1c0559c13d3c1' - '136f303f4b4d25ad5b692229957', 16 + "f335666dd1339165af8b9a5e3835adfe15c158e4c3c7bd53132e7d582" + "8c352f593a9a787760ce34b789879941f2f01f02319f6ae0b756f1a84" + "2ba54c85612ed632ee2d79ef17f06b77c641b7b080aff52a03fc2462e" + "80abc64d223723c236deeb7d201078ec01ca1fbc1763139e25099a84e" + "c389159c409792080736bd7caa816b92edf23f2c351f90074aa5ea265" + "1b372f8b58a0a65554db2561d706a63685000ac576b7e4562e262a142" + "85a9c6370b290e4eb7757527d80b6c0fd5df831d36f3d1d35f12ab060" + "548de1605fd15f7c7aafed688b146a02c945156e284f5b71282045aba" + "9844d48b5df2e9e7a5887121eae7d7b01db7cdf6ff917cd8eb50c6bf1" + "d54f90cce1a491a9c74fea88f7e7230b047d16b5a6027881d6f154818" + "f06e513faf40c8814630e4e254f17a47bfe9cb519b98289935bf17673" + "ae4c8033504a20a898d0032ee402b72d5986322f3bdfb27400561f747" + "6cd715eaabb7338b854e51fc2fa026a5a579b6dcea1b1c0559c13d3c1" + "136f303f4b4d25ad5b692229957", + 16, ), q=int( - 'd3eba6521240694015ef94412e08bf3cf8d635a455a398d6f210f6169' - '041653b', 16 + "d3eba6521240694015ef94412e08bf3cf8d635a455a398d6f210f6169" + "041653b", + 16, ), g=int( - 'ce84b30ddf290a9f787a7c2f1ce92c1cbf4ef400e3cd7ce4978db2104' - 'd7394b493c18332c64cec906a71c3778bd93341165dee8e6cd4ca6f13' - 'afff531191194ada55ecf01ff94d6cf7c4768b82dd29cd131aaf202ae' - 'fd40e564375285c01f3220af4d70b96f1395420d778228f1461f5d0b8' - 'e47357e87b1fe3286223b553e3fc9928f16ae3067ded6721bedf1d1a0' - '1bfd22b9ae85fce77820d88cdf50a6bde20668ad77a707d1c60fcc5d5' - '1c9de488610d0285eb8ff721ff141f93a9fb23c1d1f7654c07c46e588' - '36d1652828f71057b8aff0b0778ef2ca934ea9d0f37daddade2d823a4' - 'd8e362721082e279d003b575ee59fd050d105dfd71cd63154efe431a0' - '869178d9811f4f231dc5dcf3b0ec0f2b0f9896c32ec6c7ee7d60aa971' - '09e09224907328d4e6acd10117e45774406c4c947da8020649c3168f6' - '90e0bd6e91ac67074d1d436b58ae374523deaf6c93c1e6920db4a080b' - '744804bb073cecfe83fa9398cf150afa286dc7eb7949750cf5001ce10' - '4e9187f7e16859afa8fd0d775ae', 16 - ) + "ce84b30ddf290a9f787a7c2f1ce92c1cbf4ef400e3cd7ce4978db2104" + "d7394b493c18332c64cec906a71c3778bd93341165dee8e6cd4ca6f13" + "afff531191194ada55ecf01ff94d6cf7c4768b82dd29cd131aaf202ae" + "fd40e564375285c01f3220af4d70b96f1395420d778228f1461f5d0b8" + "e47357e87b1fe3286223b553e3fc9928f16ae3067ded6721bedf1d1a0" + "1bfd22b9ae85fce77820d88cdf50a6bde20668ad77a707d1c60fcc5d5" + "1c9de488610d0285eb8ff721ff141f93a9fb23c1d1f7654c07c46e588" + "36d1652828f71057b8aff0b0778ef2ca934ea9d0f37daddade2d823a4" + "d8e362721082e279d003b575ee59fd050d105dfd71cd63154efe431a0" + "869178d9811f4f231dc5dcf3b0ec0f2b0f9896c32ec6c7ee7d60aa971" + "09e09224907328d4e6acd10117e45774406c4c947da8020649c3168f6" + "90e0bd6e91ac67074d1d436b58ae374523deaf6c93c1e6920db4a080b" + "744804bb073cecfe83fa9398cf150afa286dc7eb7949750cf5001ce10" + "4e9187f7e16859afa8fd0d775ae", + 16, + ), ), y=int( - '814824e435e1e6f38daa239aad6dad21033afce6a3ebd35c1359348a0f241' - '8871968c2babfc2baf47742148828f8612183178f126504da73566b6bab33' - 'ba1f124c15aa461555c2451d86c94ee21c3e3fc24c55527e01b1f03adcdd8' - 'ec5cb08082803a7b6a829c3e99eeb332a2cf5c035b0ce0078d3d414d31fa4' - '7e9726be2989b8d06da2e6cd363f5a7d1515e3f4925e0b32adeae3025cc5a' - '996f6fd27494ea408763de48f3bb39f6a06514b019899b312ec570851637b' - '8865cff3a52bf5d54ad5a19e6e400a2d33251055d0a440b50d53f4791391d' - 'c754ad02b9eab74c46b4903f9d76f824339914db108057af7cde657d41766' - 'a99991ac8787694f4185d6f91d7627048f827b405ec67bf2fe56141c4c581' - 'd8c317333624e073e5879a82437cb0c7b435c0ce434e15965db1315d64895' - '991e6bbe7dac040c42052408bbc53423fd31098248a58f8a67da3a39895cd' - '0cc927515d044c1e3cb6a3259c3d0da354cce89ea3552c59609db10ee9899' - '86527436af21d9485ddf25f90f7dff6d2bae', 16 - ) + "814824e435e1e6f38daa239aad6dad21033afce6a3ebd35c1359348a0f241" + "8871968c2babfc2baf47742148828f8612183178f126504da73566b6bab33" + "ba1f124c15aa461555c2451d86c94ee21c3e3fc24c55527e01b1f03adcdd8" + "ec5cb08082803a7b6a829c3e99eeb332a2cf5c035b0ce0078d3d414d31fa4" + "7e9726be2989b8d06da2e6cd363f5a7d1515e3f4925e0b32adeae3025cc5a" + "996f6fd27494ea408763de48f3bb39f6a06514b019899b312ec570851637b" + "8865cff3a52bf5d54ad5a19e6e400a2d33251055d0a440b50d53f4791391d" + "c754ad02b9eab74c46b4903f9d76f824339914db108057af7cde657d41766" + "a99991ac8787694f4185d6f91d7627048f827b405ec67bf2fe56141c4c581" + "d8c317333624e073e5879a82437cb0c7b435c0ce434e15965db1315d64895" + "991e6bbe7dac040c42052408bbc53423fd31098248a58f8a67da3a39895cd" + "0cc927515d044c1e3cb6a3259c3d0da354cce89ea3552c59609db10ee9899" + "86527436af21d9485ddf25f90f7dff6d2bae", + 16, + ), ), x=int( - 'b2764c46113983777d3e7e97589f1303806d14ad9f2f1ef033097de954b17706', - 16 - ) + "b2764c46113983777d3e7e97589f1303806d14ad9f2f1ef033097de954b17706", 16 + ), ) diff --git a/tests/hazmat/primitives/fixtures_ec.py b/tests/hazmat/primitives/fixtures_ec.py index 21c6903173e1..d1d0a46ffe25 100644 --- a/tests/hazmat/primitives/fixtures_ec.py +++ b/tests/hazmat/primitives/fixtures_ec.py @@ -9,288 +9,272 @@ EC_KEY_SECT571R1 = ec.EllipticCurvePrivateNumbers( private_value=int( - '213997069697108634621868251335076179190383272087548888968788698953' - '131928375431570122753130054966269038244076049869476736547896549201' - '7388482714521707824160638375437887802901' + "213997069697108634621868251335076179190383272087548888968788698953" + "131928375431570122753130054966269038244076049869476736547896549201" + "7388482714521707824160638375437887802901" ), public_numbers=ec.EllipticCurvePublicNumbers( curve=ec.SECT571R1(), x=int( - '42585672410900520895287019432267514156432686681290164230262278' - '54789182447139054594501570747809649335533486119017169439209005' - '883737780433424425566023654583165324498640038089' + "42585672410900520895287019432267514156432686681290164230262278" + "54789182447139054594501570747809649335533486119017169439209005" + "883737780433424425566023654583165324498640038089" ), y=int( - '13822523320209387572500458104799806851658024537477228250738334' - '46977851514777531296572763848253279034733550774927720436494321' - '97281333379623823457479233585424800362717541750' - ) - ) + "13822523320209387572500458104799806851658024537477228250738334" + "46977851514777531296572763848253279034733550774927720436494321" + "97281333379623823457479233585424800362717541750" + ), + ), ) EC_KEY_SECT409R1 = ec.EllipticCurvePrivateNumbers( private_value=int( - '604993237916498765317587097853603474519114726157206838874832379003' - '281871982139714656205843929472002062791572217653118715727' + "604993237916498765317587097853603474519114726157206838874832379003" + "281871982139714656205843929472002062791572217653118715727" ), public_numbers=ec.EllipticCurvePublicNumbers( curve=ec.SECT409R1(), x=int( - '76237701339268928039087238870073679814646664010783544301589269' - '2272579213400205907766385199643053767195204247826349822350081' + "76237701339268928039087238870073679814646664010783544301589269" + "2272579213400205907766385199643053767195204247826349822350081" ), y=int( - '10056668929618383045204866060110626563392345494925302478351744' - '01475129090774493235522729123877384838835703483224447476728811' - ) - ) + "10056668929618383045204866060110626563392345494925302478351744" + "01475129090774493235522729123877384838835703483224447476728811" + ), + ), ) EC_KEY_SECT283R1 = ec.EllipticCurvePrivateNumbers( private_value=int( - '589705077255658434962118789801402573495547207239917043241273753671' - '0603230261342427657' + "589705077255658434962118789801402573495547207239917043241273753671" + "0603230261342427657" ), public_numbers=ec.EllipticCurvePublicNumbers( curve=ec.SECT283R1(), x=int( - '10694213430317013187241490088760888472172922291550831393222973' - '531614941756901942108493' + "10694213430317013187241490088760888472172922291550831393222973" + "531614941756901942108493" ), y=int( - '11461553100313943515373601367527399649593366728262918214942116' - '4359557613202950705170' - ) - ) + "11461553100313943515373601367527399649593366728262918214942116" + "4359557613202950705170" + ), + ), ) EC_KEY_SECT233R1 = ec.EllipticCurvePrivateNumbers( private_value=int( - '343470067105388144757135261232658742142830154753739648095101899829' - '8288' + "343470067105388144757135261232658742142830154753739648095101899829" + "8288" ), public_numbers=ec.EllipticCurvePublicNumbers( curve=ec.SECT233R1(), x=int( - '74494951569151557692195071465128140646140765188698294062550374' - '71118267' + "74494951569151557692195071465128140646140765188698294062550374" + "71118267" ), y=int( - '48699150823022962508544923825876164485917001162461401797511748' - '44872205' - ) - ) + "48699150823022962508544923825876164485917001162461401797511748" + "44872205" + ), + ), ) EC_KEY_SECT163R2 = ec.EllipticCurvePrivateNumbers( - private_value=int( - '11788436193853888218177032687141056784083668635' - ), + private_value=int("11788436193853888218177032687141056784083668635"), public_numbers=ec.EllipticCurvePublicNumbers( curve=ec.SECT163R2(), - x=int( - '5247234453330640212490501030772203801908103222463' - ), - y=int( - '3172513801099088785224248292142866317754124455206' - ) - ) + x=int("5247234453330640212490501030772203801908103222463"), + y=int("3172513801099088785224248292142866317754124455206"), + ), ) EC_KEY_SECT571K1 = ec.EllipticCurvePrivateNumbers( private_value=int( - '592811051234886966121888758661314648311634839499582476726008738218' - '165015048237934517672316204181933804884636855291118594744334592153' - '883208936227914544246799490897169723387' + "592811051234886966121888758661314648311634839499582476726008738218" + "165015048237934517672316204181933804884636855291118594744334592153" + "883208936227914544246799490897169723387" ), public_numbers=ec.EllipticCurvePublicNumbers( curve=ec.SECT571K1(), x=int( - '81362471461936552203898455874182916939857774872643607884250052' - '29301336524105230729653881789373412990921493551253481866317181' - '50644729351721577822595637058949405764944491655' + "81362471461936552203898455874182916939857774872643607884250052" + "29301336524105230729653881789373412990921493551253481866317181" + "50644729351721577822595637058949405764944491655" ), y=int( - '14058041260812945396067821061063618047896814719828637241661260' - '31235681542401975593036630733881695595289523801041910183736211' - '587294494888450327374439795428519848065589000434' - ) - ) + "14058041260812945396067821061063618047896814719828637241661260" + "31235681542401975593036630733881695595289523801041910183736211" + "587294494888450327374439795428519848065589000434" + ), + ), ) EC_KEY_SECT409K1 = ec.EllipticCurvePrivateNumbers( private_value=int( - '110321743150399087059465162400463719641470113494908091197354523708' - '934106732952992153105338671368548199643686444619485307877' + "110321743150399087059465162400463719641470113494908091197354523708" + "934106732952992153105338671368548199643686444619485307877" ), public_numbers=ec.EllipticCurvePublicNumbers( curve=ec.SECT409K1(), x=int( - '62280214209410363493525178797944995742119600145953755916426161' - '0790364158569265348038207313261547476506319796469776797725796' + "62280214209410363493525178797944995742119600145953755916426161" + "0790364158569265348038207313261547476506319796469776797725796" ), y=int( - '46653883749102474289095010108777579907422472804577185369332018' - '7318642669590280811057512951467298158275464566214288556375885' - ) - ) + "46653883749102474289095010108777579907422472804577185369332018" + "7318642669590280811057512951467298158275464566214288556375885" + ), + ), ) EC_KEY_SECT283K1 = ec.EllipticCurvePrivateNumbers( private_value=int( - '182508394415444014156574733141549331538128234395356466108310015130' - '3868915489347291850' + "182508394415444014156574733141549331538128234395356466108310015130" + "3868915489347291850" ), public_numbers=ec.EllipticCurvePublicNumbers( curve=ec.SECT283K1(), x=int( - '31141647206111886426350703123670451554123180910379592764773885' - '2959123367428352287032' + "31141647206111886426350703123670451554123180910379592764773885" + "2959123367428352287032" ), y=int( - '71787460144483665964585187837283963089964760704065205376175384' - '58957627834444017112582' - ) - ) + "71787460144483665964585187837283963089964760704065205376175384" + "58957627834444017112582" + ), + ), ) EC_KEY_SECT233K1 = ec.EllipticCurvePrivateNumbers( private_value=int( - '172670089647474613734091436081960550801254775902629891892394471086' - '2070' + "172670089647474613734091436081960550801254775902629891892394471086" + "2070" ), public_numbers=ec.EllipticCurvePublicNumbers( curve=ec.SECT233K1(), x=int( - '55693911474339510991521579392202889561373678973929426354737048' - '68129172' + "55693911474339510991521579392202889561373678973929426354737048" + "68129172" ), y=int( - '11025856248546376145959939911850923631416718241836051344384802' - '737277815' - ) - ) + "11025856248546376145959939911850923631416718241836051344384802" + "737277815" + ), + ), ) EC_KEY_SECT163K1 = ec.EllipticCurvePrivateNumbers( - private_value=int( - '3699303791425402204035307605170569820290317991287' - ), + private_value=int("3699303791425402204035307605170569820290317991287"), public_numbers=ec.EllipticCurvePublicNumbers( curve=ec.SECT163K1(), - x=int( - '4479755902310063321544063130576409926980094120721' - ), - y=int( - '3051218481937171839039826690648109285113977745779' - ) - ) + x=int("4479755902310063321544063130576409926980094120721"), + y=int("3051218481937171839039826690648109285113977745779"), + ), ) EC_KEY_SECP521R1 = ec.EllipticCurvePrivateNumbers( private_value=int( - '662751235215460886290293902658128847495347691199214706697089140769' - '672273950767961331442265530524063943548846724348048614239791498442' - '5997823106818915698960565' + "662751235215460886290293902658128847495347691199214706697089140769" + "672273950767961331442265530524063943548846724348048614239791498442" + "5997823106818915698960565" ), public_numbers=ec.EllipticCurvePublicNumbers( curve=ec.SECP521R1(), x=int( - '12944742826257420846659527752683763193401384271391513286022917' - '29910013082920512632908350502247952686156279140016049549948975' - '670668730618745449113644014505462' + "12944742826257420846659527752683763193401384271391513286022917" + "29910013082920512632908350502247952686156279140016049549948975" + "670668730618745449113644014505462" ), y=int( - '10784108810271976186737587749436295782985563640368689081052886' - '16296815984553198866894145509329328086635278430266482551941240' - '591605833440825557820439734509311' - ) - ) + "10784108810271976186737587749436295782985563640368689081052886" + "16296815984553198866894145509329328086635278430266482551941240" + "591605833440825557820439734509311" + ), + ), ) EC_KEY_SECP384R1 = ec.EllipticCurvePrivateNumbers( private_value=int( - '280814107134858470598753916394807521398239633534281633982576099083' - '35787109896602102090002196616273211495718603965098' + "280814107134858470598753916394807521398239633534281633982576099083" + "35787109896602102090002196616273211495718603965098" ), public_numbers=ec.EllipticCurvePublicNumbers( curve=ec.SECP384R1(), x=int( - '10036914308591746758780165503819213553101287571902957054148542' - '504671046744460374996612408381962208627004841444205030' + "10036914308591746758780165503819213553101287571902957054148542" + "504671046744460374996612408381962208627004841444205030" ), y=int( - '17337335659928075994560513699823544906448896792102247714689323' - '575406618073069185107088229463828921069465902299522926' - ) - ) + "17337335659928075994560513699823544906448896792102247714689323" + "575406618073069185107088229463828921069465902299522926" + ), + ), ) EC_KEY_SECP256R1 = ec.EllipticCurvePrivateNumbers( private_value=int( - '271032978511595617649844168316234344656921218699414461240502635010' - '25776962849' + "271032978511595617649844168316234344656921218699414461240502635010" + "25776962849" ), public_numbers=ec.EllipticCurvePublicNumbers( curve=ec.SECP256R1(), x=int( - '49325986169170464532722748935508337546545346352733747948730305' - '442770101441241' + "49325986169170464532722748935508337546545346352733747948730305" + "442770101441241" ), y=int( - '51709162888529903487188595007092772817469799707382623884187518' - '455962250433661' - ) - ) + "51709162888529903487188595007092772817469799707382623884187518" + "455962250433661" + ), + ), ) EC_KEY_SECP256K1 = ec.EllipticCurvePrivateNumbers( private_value=int( - '683341569008473593765879222774207677458810362976327530563215318048' - '64380736732' + "683341569008473593765879222774207677458810362976327530563215318048" + "64380736732" ), public_numbers=ec.EllipticCurvePublicNumbers( curve=ec.SECP256K1(), x=int( - '59251322975795306609293064274738085741081547489119277536110995' - '120127593127884' + "59251322975795306609293064274738085741081547489119277536110995" + "120127593127884" ), y=int( - '10334192001480392039227801832201340147605940717841294644187071' - '8261641142297801' - ) - ) + "10334192001480392039227801832201340147605940717841294644187071" + "8261641142297801" + ), + ), ) EC_KEY_SECP224R1 = ec.EllipticCurvePrivateNumbers( private_value=int( - '234854340492774342642505519082413233282383066880756900834047566251' - '50' + "234854340492774342642505519082413233282383066880756900834047566251" + "50" ), public_numbers=ec.EllipticCurvePublicNumbers( curve=ec.SECP224R1(), x=int( - '51165676638271204691095081341581621487998422645261573824239666' - '1214' + "51165676638271204691095081341581621487998422645261573824239666" + "1214" ), y=int( - '14936601450555711309158397172719963843891926209168533453717969' - '1265' - ) - ) + "14936601450555711309158397172719963843891926209168533453717969" + "1265" + ), + ), ) EC_KEY_SECP192R1 = ec.EllipticCurvePrivateNumbers( private_value=int( - '4534766128536179420071447168915990251715442361606049349869' + "4534766128536179420071447168915990251715442361606049349869" ), public_numbers=ec.EllipticCurvePublicNumbers( curve=ec.SECP192R1(), - x=int( - '5415069751170397888083674339683360671310515485781457536999' - ), - y=int( - '18671605334415960797751252911958331304288357195986572776' - ) - ) + x=int("5415069751170397888083674339683360671310515485781457536999"), + y=int("18671605334415960797751252911958331304288357195986572776"), + ), ) diff --git a/tests/hazmat/primitives/fixtures_rsa.py b/tests/hazmat/primitives/fixtures_rsa.py index a531783e5847..801fb914cf8e 100644 --- a/tests/hazmat/primitives/fixtures_rsa.py +++ b/tests/hazmat/primitives/fixtures_rsa.py @@ -5,7 +5,8 @@ from __future__ import absolute_import, division, print_function from cryptography.hazmat.primitives.asymmetric.rsa import ( - RSAPrivateNumbers, RSAPublicNumbers + RSAPrivateNumbers, + RSAPublicNumbers, ) @@ -18,7 +19,8 @@ ), d=int( "272869352cacf9c866c4e107acc95d4c608ca91460a93d28588d51cfccc07f449" - "18bbe7660f9f16adc2b4ed36ca310ef3d63b79bd447456e3505736a45a6ed21", 16 + "18bbe7660f9f16adc2b4ed36ca310ef3d63b79bd447456e3505736a45a6ed21", + 16, ), dmp1=int( "addff2ec7564c6b64bc670d250b6f24b0b8db6b2810099813b7e7658cecf5c39", 16 @@ -34,178 +36,239 @@ n=int( "ae5411f963c50e3267fafcf76381c8b1e5f7b741fdb2a544bcf48bd607b10c991" "90caeb8011dc22cf83d921da55ec32bd05cac3ee02ca5e1dbef93952850b525", - 16 + 16, ), - ) + ), ) RSA_KEY_512_ALT = RSAPrivateNumbers( p=int( - "febe19c29a0b50fefa4f7b1832f84df1caf9be8242da25c9d689e18226e67ce5", - 16), + "febe19c29a0b50fefa4f7b1832f84df1caf9be8242da25c9d689e18226e67ce5", 16 + ), q=int( - "eb616c639dd999feda26517e1c77b6878f363fe828c4e6670ec1787f28b1e731", - 16), + "eb616c639dd999feda26517e1c77b6878f363fe828c4e6670ec1787f28b1e731", 16 + ), d=int( "80edecfde704a806445a4cc782b85d3f36f17558f385654ea767f006470fdfcbda5e2" - "206839289d3f419b4e4fb8e1acee1b4fb9c591f69b64ec83937f5829241", 16), + "206839289d3f419b4e4fb8e1acee1b4fb9c591f69b64ec83937f5829241", + 16, + ), dmp1=int( - "7f4fa06e2a3077a54691cc5216bf13ad40a4b9fa3dd0ea4bca259487484baea5", - 16), + "7f4fa06e2a3077a54691cc5216bf13ad40a4b9fa3dd0ea4bca259487484baea5", 16 + ), dmq1=int( - "35eaa70d5a8711c352ed1c15ab27b0e3f46614d575214535ae279b166597fac1", - 16), + "35eaa70d5a8711c352ed1c15ab27b0e3f46614d575214535ae279b166597fac1", 16 + ), iqmp=int( - "cc1f272de6846851ec80cb89a02dbac78f44b47bc08f53b67b4651a3acde8b19", - 16), + "cc1f272de6846851ec80cb89a02dbac78f44b47bc08f53b67b4651a3acde8b19", 16 + ), public_numbers=RSAPublicNumbers( e=65537, n=int( "ea397388b999ef0f7e7416fa000367efd9a0ba0deddd3f8160d1c36d62267f210" "fbd9c97abeb6654450ff03e7601b8caa6c6f4cba18f0b52c179d17e8f258ad5", - 16), - ) + 16, + ), + ), ) RSA_KEY_522 = RSAPrivateNumbers( p=int( "1a8aab9a069f92b52fdf05824f2846223dc27adfc806716a247a77d4c36885e4bf", - 16), + 16, + ), q=int( "19e8d620d177ec54cdb733bb1915e72ef644b1202b889ceb524613efa49c07eb4f", - 16), + 16, + ), d=int( "10b8a7c0a92c1ae2d678097d69db3bfa966b541fb857468291d48d1b52397ea2bac0d" - "4370c159015c7219e3806a01bbafaffdd46f86e3da1e2d1fe80a0369ccd745", 16), + "4370c159015c7219e3806a01bbafaffdd46f86e3da1e2d1fe80a0369ccd745", + 16, + ), dmp1=int( - "3eb6277f66e6e2dcf89f1b8529431f730839dbd9a3e49555159bc8470eee886e5", - 16), + "3eb6277f66e6e2dcf89f1b8529431f730839dbd9a3e49555159bc8470eee886e5", 16 + ), dmq1=int( "184b4d74aa54c361e51eb23fee4eae5e4786b37b11b6e0447af9c0b9c4e4953c5b", - 16), + 16, + ), iqmp=int( - "f80e9ab4fa7b35d0d232ef51c4736d1f2dcf2c7b1dd8716211b1bf1337e74f8ae", - 16), + "f80e9ab4fa7b35d0d232ef51c4736d1f2dcf2c7b1dd8716211b1bf1337e74f8ae", 16 + ), public_numbers=RSAPublicNumbers( e=65537, n=int( "2afaea0e0bb6fca037da7d190b5270a6c665bc18e7a456f7e69beaac4433db748" "ba99acdd14697e453bca596eb35b47f2d48f1f85ef08ce5109dad557a9cf85ebf" - "1", 16), + "1", + 16, + ), ), ) RSA_KEY_599 = RSAPrivateNumbers( p=int( "cf95d20be0c7af69f4b3d909f65d858c26d1a7ef34da8e3977f4fa230580e58814b54" - "24be99", 16), + "24be99", + 16, + ), q=int( "6052be4b28debd4265fe12ace5aa4a0c4eb8d63ff8853c66824b35622161eb48a3bc8" - "c3ada5", 16), + "c3ada5", + 16, + ), d=int( "69d9adc465e61585d3142d7cc8dd30605e8d1cbbf31009bc2cd5538dc40528d5d68ee" "fe6a42d23674b6ec76e192351bf368c8968f0392110bf1c2825dbcff071270b80adcc" - "fa1d19d00a1", 16), + "fa1d19d00a1", + 16, + ), dmp1=int( "a86d10edde456687fba968b1f298d2e07226adb1221b2a466a93f3d83280f0bb46c20" - "2b6811", 16), + "2b6811", + 16, + ), dmq1=int( "40d570e08611e6b1da94b95d46f8e7fe80be48f7a5ff8838375b08039514a399b11c2" - "80735", 16), + "80735", + 16, + ), iqmp=int( "cd051cb0ea68b88765c041262ace2ec4db11dab14afd192742e34d5da3328637fabdf" - "bae26e", 16), + "bae26e", + 16, + ), public_numbers=RSAPublicNumbers( e=65537, n=int( "4e1b470fe00642426f3808e74c959632dd67855a4c503c5b7876ccf4dc7f6a1a4" "9107b90d26daf0a7879a6858218345fbc6e59f01cd095ca5647c27c25265e6c47" - "4fea89537191c7073d9d", 16), - ) + "4fea89537191c7073d9d", + 16, + ), + ), ) RSA_KEY_745 = RSAPrivateNumbers( p=int( "1c5a0cfe9a86debd19eca33ba961f15bc598aa7983a545ce775b933afc89eb51bcf90" - "836257fdd060d4b383240241d", 16 + "836257fdd060d4b383240241d", + 16, ), q=int( "fb2634f657f82ee6b70553382c4e2ed26b947c97ce2f0016f1b282cf2998184ad0527" - "a9eead826dd95fe06b57a025", 16 + "a9eead826dd95fe06b57a025", + 16, ), d=int( "402f30f976bc07d15ff0779abff127b20a8b6b1d0024cc2ad8b6762d38f174f81e792" "3b49d80bdbdd80d9675cbc7b2793ec199a0430eb5c84604dacfdb29259ae6a1a44676" - "22f0b23d4cb0f5cb1db4b8173c8d9d3e57a74dbd200d2141", 16), + "22f0b23d4cb0f5cb1db4b8173c8d9d3e57a74dbd200d2141", + 16, + ), dmp1=int( "e5e95b7751a6649f199be21bef7a51c9e49821d945b6fc5f538b4a670d8762c375b00" - "8e70f31d52b3ea2bd14c3101", 16), + "8e70f31d52b3ea2bd14c3101", + 16, + ), dmq1=int( "12b85d5843645f72990fcf8d2f58408b34b3a3b9d9078dd527fceb5d2fb7839008092" - "dd4aca2a1fb00542801dcef5", 16), + "dd4aca2a1fb00542801dcef5", + 16, + ), iqmp=int( "5672740d947f621fc7969e3a44ec26736f3f819863d330e63e9409e139d20753551ac" - "c16544dd2bdadb9dee917440", 16), + "c16544dd2bdadb9dee917440", + 16, + ), public_numbers=RSAPublicNumbers( e=65537, n=int( "1bd085f92237774d34013b477ceebbb2f2feca71118db9b7429341477947e7b1d" "04e8c43ede3c52bb25781af58d4ff81289f301eac62dc3bcd7dafd7a4d5304e9f" - "308e766952fbf2b62373e66611fa53189987dbef9f7243dcbbeb25831", 16), - ) + "308e766952fbf2b62373e66611fa53189987dbef9f7243dcbbeb25831", + 16, + ), + ), ) RSA_KEY_768 = RSAPrivateNumbers( p=int( "f80c0061b607f93206b68e208906498d68c6e396faf457150cf975c8f849848465869" - "7ecd402313397088044c4c2071b", 16), + "7ecd402313397088044c4c2071b", + 16, + ), q=int( "e5b5dbecc93c6d306fc14e6aa9737f9be2728bc1a326a8713d2849b34c1cb54c63468" - "3a68abb1d345dbf15a3c492cf55", 16), + "3a68abb1d345dbf15a3c492cf55", + 16, + ), d=int( "d44601442255ffa331212c60385b5e898555c75c0272632ff42d57c4b16ca97dbca9f" "d6d99cd2c9fd298df155ed5141b4be06c651934076133331d4564d73faed7ce98e283" - "2f7ce3949bc183be7e7ca34f6dd04a9098b6c73649394b0a76c541", 16), + "2f7ce3949bc183be7e7ca34f6dd04a9098b6c73649394b0a76c541", + 16, + ), dmp1=int( "a5763406fa0b65929661ce7b2b8c73220e43a5ebbfe99ff15ddf464fd238105ad4f2a" - "c83818518d70627d8908703bb03", 16), + "c83818518d70627d8908703bb03", + 16, + ), dmq1=int( "cb467a9ef899a39a685aecd4d0ad27b0bfdc53b68075363c373d8eb2bed8eccaf3533" - "42f4db735a9e087b7539c21ba9d", 16), + "42f4db735a9e087b7539c21ba9d", + 16, + ), iqmp=int( "5fe86bd3aee0c4d09ef11e0530a78a4534c9b833422813b5c934a450c8e564d8097a0" - "6fd74f1ebe2d5573782093f587a", 16), + "6fd74f1ebe2d5573782093f587a", + 16, + ), public_numbers=RSAPublicNumbers( e=65537, n=int( "de92f1eb5f4abf426b6cac9dd1e9bf57132a4988b4ed3f8aecc15e251028bd6df" "46eb97c711624af7db15e6430894d1b640c13929329241ee094f5a4fe1a20bc9b" "75232320a72bc567207ec54d6b48dccb19737cf63acc1021abb337f19130f7", - 16), - ) + 16, + ), + ), ) RSA_KEY_1024 = RSAPrivateNumbers( p=int( "ea4d9d9a1a068be44b9a5f8f6de0512b2c5ba1fb804a4655babba688e6e890b347c1a" - "7426685a929337f513ae4256f0b7e5022d642237f960c5b24b96bee8e51", 16), + "7426685a929337f513ae4256f0b7e5022d642237f960c5b24b96bee8e51", + 16, + ), q=int( "cffb33e400d6f08b410d69deb18a85cf0ed88fcca9f32d6f2f66c62143d49aff92c11" - "4de937d4f1f62d4635ee89af99ce86d38a2b05310f3857c7b5d586ac8f9", 16), + "4de937d4f1f62d4635ee89af99ce86d38a2b05310f3857c7b5d586ac8f9", + 16, + ), d=int( "3d12d46d04ce942fb99be7bf30587b8cd3e21d75a2720e7bda1b867f1d418d91d8b9f" "e1c00181fdde94f2faf33b4e6f800a1b3ae3b972ccb6d5079dcb6c794070ac8306d59" "c00b58b7a9a81122a6b055832de7c72334a07494d8e7c9fbeed2cc37e011d9e6bfc6e" - "9bcddbef7f0f5771d9cf82cd4b268c97ec684575c24b6c881", 16), + "9bcddbef7f0f5771d9cf82cd4b268c97ec684575c24b6c881", + 16, + ), dmp1=int( "470f2b11257b7ec9ca34136f487f939e6861920ad8a9ae132a02e74af5dceaa5b4c98" - "2949ccb44b67e2bcad2f58674db237fe250e0d62b47b28fa1dfaa603b41", 16), + "2949ccb44b67e2bcad2f58674db237fe250e0d62b47b28fa1dfaa603b41", + 16, + ), dmq1=int( "c616e8317d6b3ae8272973709b80e8397256697ff14ea03389de454f619f99915a617" - "45319fefbe154ec1d49441a772c2f63f7d15c478199afc60469bfd0d561", 16), + "45319fefbe154ec1d49441a772c2f63f7d15c478199afc60469bfd0d561", + 16, + ), iqmp=int( "d15e7c9ad357dfcd5dbdc8427680daf1006761bcfba93a7f86589ad88832a8d564b1c" - "d4291a658c96fbaea7ca588795820902d85caebd49c2d731e3fe0243130", 16), + "d4291a658c96fbaea7ca588795820902d85caebd49c2d731e3fe0243130", + 16, + ), public_numbers=RSAPublicNumbers( e=65537, n=int( @@ -213,31 +276,44 @@ "ede07be3bed0e355d48e0dfab1e4fb5187adf42d7d3fb0401c082acb8481bf17f" "0e871f8877be04c3a1197d40aa260e2e0c48ed3fd2b93dc3fc0867591f67f3cd6" "0a77adee1d68a8c3730a5702485f6ac9ede7f0fd2918e037ee4cc1fc1b4c9", - 16), - ) + 16, + ), + ), ) RSA_KEY_1025 = RSAPrivateNumbers( p=int( "18e9bfb7071725da04d31c103fa3563648c69def43a204989214eb57b0c8b299f9ef3" - "5dda79a62d8d67fd2a9b69fbd8d0490aa2edc1e111a2b8eb7c737bb691a5", 16), + "5dda79a62d8d67fd2a9b69fbd8d0490aa2edc1e111a2b8eb7c737bb691a5", + 16, + ), q=int( "d8eccaeeb95815f3079d13685f3f72ca2bf2550b349518049421375df88ca9bbb4ba8" - "cb0e3502203c9eeae174112509153445d251313e4711a102818c66fcbb7", 16), + "cb0e3502203c9eeae174112509153445d251313e4711a102818c66fcbb7", + 16, + ), d=int( "fe9ac54910b8b1bc948a03511c54cab206a1d36d50d591124109a48abb7480977ccb0" "47b4d4f1ce7b0805df2d4fa3fe425f49b78535a11f4b87a4eba0638b3340c23d4e6b2" "1ecebe9d5364ea6ead2d47b27836019e6ecb407000a50dc95a8614c9d0031a6e3a524" - "d2345cfb76e15c1f69d5ba35bdfb6ec63bcb115a757ef79d9", 16), + "d2345cfb76e15c1f69d5ba35bdfb6ec63bcb115a757ef79d9", + 16, + ), dmp1=int( "18537e81006a68ea76d590cc88e73bd26bc38d09c977959748e5265c0ce21c0b5fd26" - "53d975f97ef759b809f791487a8fff1264bf561627fb4527a3f0bbb72c85", 16), + "53d975f97ef759b809f791487a8fff1264bf561627fb4527a3f0bbb72c85", + 16, + ), dmq1=int( "c807eac5a1f1e1239f04b04dd16eff9a00565127a91046fa89e1eb5d6301cace85447" - "4d1f47b0332bd35b4214b66e9166953241538f761f30d969272ee214f17", 16), + "4d1f47b0332bd35b4214b66e9166953241538f761f30d969272ee214f17", + 16, + ), iqmp=int( "133aa74dd41fe70fa244f07d0c4091a22f8c8f0134fe6aea9ec8b55383b758fefe358" - "2beec36eca91715eee7d21931f24fa9e97e8e3a50f9cd0f731574a5eafcc", 16), + "2beec36eca91715eee7d21931f24fa9e97e8e3a50f9cd0f731574a5eafcc", + 16, + ), public_numbers=RSAPublicNumbers( e=65537, n=int( @@ -245,31 +321,44 @@ "bf276fe3523f38f5ddaf3ea9aa88486a9d8760ff732489075862bee0e599de5c5" "f509b4519f4f446521bad15cd279a498fe1e89107ce0d237e3103d7c5eb801666" "42e2924b152aebff97b71fdd2d68ebb45034cc784e2e822ff6d1edf98af3f3", - 16), - ) + 16, + ), + ), ) RSA_KEY_1026 = RSAPrivateNumbers( p=int( "1fcbfb8719c5bdb5fe3eb0937c76bb096e750b9442dfe31d6a877a13aed2a6a4e9f79" - "40f815f1c307dd6bc2b4b207bb6fe5be3a15bd2875a957492ce197cdedb1", 16), + "40f815f1c307dd6bc2b4b207bb6fe5be3a15bd2875a957492ce197cdedb1", + 16, + ), q=int( "1f704a0f6b8966dd52582fdc08227dd3dbaeaa781918b41144b692711091b4ca4eb62" - "985c3513853828ce8739001dfba9a9a7f1a23cbcaf74280be925e2e7b50d", 16), + "985c3513853828ce8739001dfba9a9a7f1a23cbcaf74280be925e2e7b50d", + 16, + ), d=int( "c67975e35a1d0d0b3ebfca736262cf91990cb31cf4ac473c0c816f3bc2720bcba2475" "e8d0de8535d257816c0fc53afc1b597eada8b229069d6ef2792fc23f59ffb4dc6c3d9" "0a3c462082025a4cba7561296dd3d8870c4440d779406f00879afe2c681e7f5ee055e" - "ff829e6e55883ec20830c72300762e6e3a333d94b4dbe4501", 16), + "ff829e6e55883ec20830c72300762e6e3a333d94b4dbe4501", + 16, + ), dmp1=int( "314730ca7066c55d086a9fbdf3670ef7cef816b9efea8b514b882ae9d647217cf41d7" - "e9989269dc9893d02e315cb81f058c49043c2cac47adea58bdf5e20e841", 16), + "e9989269dc9893d02e315cb81f058c49043c2cac47adea58bdf5e20e841", + 16, + ), dmq1=int( "1da28a9d687ff7cfeebc2439240de7505a8796376968c8ec723a2b669af8ce53d9c88" - "af18540bd78b2da429014923fa435f22697ac60812d7ca9c17a557f394cd", 16), + "af18540bd78b2da429014923fa435f22697ac60812d7ca9c17a557f394cd", + 16, + ), iqmp=int( "727947b57b8a36acd85180522f1b381bce5fdbd962743b3b14af98a36771a80f58ddd" - "62675d72a5935190da9ddc6fd6d6d5e9e9f805a2e92ab8d56b820493cdf", 16), + "62675d72a5935190da9ddc6fd6d6d5e9e9f805a2e92ab8d56b820493cdf", + 16, + ), public_numbers=RSAPublicNumbers( e=65537, n=int( @@ -277,31 +366,44 @@ "9cfae6ab0446da18e26f33e1d753bc1cc03585c100cf0ab5ef056695706fc8b0c" "9c710cd73fe6e5beda70f515a96fabd3cc5ac49efcb2594b220ff3b603fcd927f" "6a0838ef04bf52f3ed9eab801f09e5aed1613ddeb946ed0fbb02060b3a36fd", - 16), - ) + 16, + ), + ), ) RSA_KEY_1027 = RSAPrivateNumbers( p=int( "30135e54cfb072c3d3eaf2000f3ed92ceafc85efc867b9d4bf5612f2978c432040093" - "4829f741c0f002b54af2a4433ff872b6321ef00ff1e72cba4e0ced937c7d", 16), + "4829f741c0f002b54af2a4433ff872b6321ef00ff1e72cba4e0ced937c7d", + 16, + ), q=int( "1d01a8aead6f86b78c875f18edd74214e06535d65da054aeb8e1851d6f3319b4fb6d8" - "6b01e07d19f8261a1ded7dc08116345509ab9790e3f13e65c037e5bb7e27", 16), + "6b01e07d19f8261a1ded7dc08116345509ab9790e3f13e65c037e5bb7e27", + 16, + ), d=int( "21cf4477df79561c7818731da9b9c88cd793f1b4b8e175bd0bfb9c0941a4dc648ecf1" "6d96b35166c9ea116f4c2eb33ce1c231e641a37c25e54c17027bdec08ddafcb83642e" "795a0dd133155ccc5eed03b6e745930d9ac7cfe91f9045149f33295af03a2198c660f" - "08d8150d13ce0e2eb02f21ac75d63b55822f77bd5be8d07619", 16), + "08d8150d13ce0e2eb02f21ac75d63b55822f77bd5be8d07619", + 16, + ), dmp1=int( "173fb695931e845179511c18b546b265cb79b517c135902377281bdf9f34205e1f399" - "4603ad63e9f6e7885ea73a929f03fa0d6bed943051ce76cddde2d89d434d", 16), + "4603ad63e9f6e7885ea73a929f03fa0d6bed943051ce76cddde2d89d434d", + 16, + ), dmq1=int( "10956b387b2621327da0c3c8ffea2af8be967ee25163222746c28115a406e632a7f12" - "5a9397224f1fa5c116cd3a313e5c508d31db2deb83b6e082d213e33f7fcf", 16), + "5a9397224f1fa5c116cd3a313e5c508d31db2deb83b6e082d213e33f7fcf", + 16, + ), iqmp=int( "234f833949f2c0d797bc6a0e906331e17394fa8fbc8449395766d3a8d222cf6167c48" - "8e7fe1fe9721d3e3b699a595c8e6f063d92bd840dbc84d763b2b37002109", 16), + "8e7fe1fe9721d3e3b699a595c8e6f063d92bd840dbc84d763b2b37002109", + 16, + ), public_numbers=RSAPublicNumbers( e=65537, n=int( @@ -309,31 +411,44 @@ "0a5ae9f579ef1fd7e42937f921eb3123c4a045cc47a2159fbbf904783e654954c" "42294c30a95c15db7c7b91f136244e548f62474b137087346c5522e54f226f49d" "6c93bc58cb39972e41bde452bb3ae9d60eb93e5e1ce91d222138d9890c7d0b", - 16), - ) + 16, + ), + ), ) RSA_KEY_1028 = RSAPrivateNumbers( p=int( "359d17378fae8e9160097daee78a206bd52efe1b757c12a6da8026cc4fc4bb2620f12" - "b8254f4db6aed8228be8ee3e5a27ec7d31048602f01edb00befd209e8c75", 16), + "b8254f4db6aed8228be8ee3e5a27ec7d31048602f01edb00befd209e8c75", + 16, + ), q=int( "33a2e70b93d397c46e63b273dcd3dcfa64291342a6ce896e1ec8f1c0edc44106550f3" - "c06e7d3ca6ea29eccf3f6ab5ac6235c265313d6ea8e8767e6a343f616581", 16), + "c06e7d3ca6ea29eccf3f6ab5ac6235c265313d6ea8e8767e6a343f616581", + 16, + ), d=int( "880640088d331aa5c0f4cf2887809a420a2bc086e671e6ffe4e47a8c80792c038a314" "9a8e45ef9a72816ab45b36e3af6800351067a6b2751843d4232413146bb575491463a" "8addd06ce3d1bcf7028ec6c5d938c545a20f0a40214b5c574ca7e840062b2b5f8ed49" - "4b144bb2113677c4b10519177fee1d4f5fb8a1c159b0b47c01", 16), + "4b144bb2113677c4b10519177fee1d4f5fb8a1c159b0b47c01", + 16, + ), dmp1=int( "75f8c52dad2c1cea26b8bba63236ee4059489e3d2db766136098bcc6b67fde8f77cd3" - "640035107bfb1ffc6480983cfb84fe0c3be008424ebc968a7db7e01f005", 16), + "640035107bfb1ffc6480983cfb84fe0c3be008424ebc968a7db7e01f005", + 16, + ), dmq1=int( "3893c59469e4ede5cd0e6ff9837ca023ba9b46ff40c60ccf1bec10f7d38db5b1ba817" - "6c41a3f750ec4203b711455aca06d1e0adffc5cffa42bb92c7cb77a6c01", 16), + "6c41a3f750ec4203b711455aca06d1e0adffc5cffa42bb92c7cb77a6c01", + 16, + ), iqmp=int( "ad32aafae3c962ac25459856dc8ef1f733c3df697eced29773677f435d186cf759d1a" - "5563dd421ec47b4d7e7f12f29647c615166d9c43fc49001b29089344f65", 16), + "5563dd421ec47b4d7e7f12f29647c615166d9c43fc49001b29089344f65", + 16, + ), public_numbers=RSAPublicNumbers( e=65537, n=int( @@ -341,31 +456,44 @@ "e3510c68073954d3ba4deb38643e7a820a4cf06e75f7f82eca545d412bd637819" "45c28d406e95a6cced5ae924a8bfa4f3def3e0250d91246c269ec40c89c93a85a" "cd3770ba4d2e774732f43abe94394de43fb57f93ca25f7a59d75d400a3eff5", - 16), - ) + 16, + ), + ), ) RSA_KEY_1029 = RSAPrivateNumbers( p=int( "66f33e513c0b6b6adbf041d037d9b1f0ebf8de52812a3ac397a963d3f71ba64b3ad04" - "e4d4b5e377e6fa22febcac292c907dc8dcfe64c807fd9a7e3a698850d983", 16), + "e4d4b5e377e6fa22febcac292c907dc8dcfe64c807fd9a7e3a698850d983", + 16, + ), q=int( "3b47a89a19022461dcc2d3c05b501ee76955e8ce3cf821beb4afa85a21a26fd7203db" - "deb8941f1c60ada39fd6799f6c07eb8554113f1020460ec40e93cd5f6b21", 16), + "deb8941f1c60ada39fd6799f6c07eb8554113f1020460ec40e93cd5f6b21", + 16, + ), d=int( "280c42af8b1c719821f2f6e2bf5f3dd53c81b1f3e1e7cc4fce6e2f830132da0665bde" "bc1e307106b112b52ad5754867dddd028116cf4471bc14a58696b99524b1ad8f05b31" "cf47256e54ab4399b6a073b2c0452441438dfddf47f3334c13c5ec86ece4d33409056" - "139328fafa992fb5f5156f25f9b21d3e1c37f156d963d97e41", 16), + "139328fafa992fb5f5156f25f9b21d3e1c37f156d963d97e41", + 16, + ), dmp1=int( "198c7402a4ec10944c50ab8488d7b5991c767e75eb2817bd427dff10335ae141fa2e8" - "7c016dc22d975cac229b9ffdf7d943ddfd3a04b8bf82e83c3b32c5698b11", 16), + "7c016dc22d975cac229b9ffdf7d943ddfd3a04b8bf82e83c3b32c5698b11", + 16, + ), dmq1=int( "15fd30c7687b68ef7c2a30cdeb913ec56c4757c218cf9a04d995470797ee5f3a17558" - "fbb6d00af245d2631d893b382da48a72bc8a613024289895952ab245b0c1", 16), + "fbb6d00af245d2631d893b382da48a72bc8a613024289895952ab245b0c1", + 16, + ), iqmp=int( "4f8fde17e84557a3f4e242d889e898545ab55a1a8e075c9bb0220173ccffe84659abe" - "a235104f82e32750309389d4a52af57dbb6e48d831917b6efeb190176570", 16), + "a235104f82e32750309389d4a52af57dbb6e48d831917b6efeb190176570", + 16, + ), public_numbers=RSAPublicNumbers( e=65537, n=int( @@ -373,31 +501,44 @@ "99a9f74981c3eeaaf947d5c2d64a1a80f5c5108a49a715c3f7be95a016b8d3300" "965ead4a4df76e642d761526803e9434d4ec61b10cb50526d4dcaef02593085de" "d8c331c1b27b200a45628403065efcb2c0a0ca1f75d648d40a007fbfbf2cae3", - 16), - ) + 16, + ), + ), ) RSA_KEY_1030 = RSAPrivateNumbers( p=int( "6f4ac8a8172ef1154cf7f80b5e91de723c35a4c512860bfdbafcc3b994a2384bf7796" - "3a2dd0480c7e04d5d418629651a0de8979add6f47b23da14c27a682b69c9", 16), + "3a2dd0480c7e04d5d418629651a0de8979add6f47b23da14c27a682b69c9", + 16, + ), q=int( "65a9f83e07dea5b633e036a9dccfb32c46bf53c81040a19c574c3680838fc6d28bde9" - "55c0ff18b30481d4ab52a9f5e9f835459b1348bbb563ad90b15a682fadb3", 16), + "55c0ff18b30481d4ab52a9f5e9f835459b1348bbb563ad90b15a682fadb3", + 16, + ), d=int( "290db707b3e1a96445ae8ea93af55a9f211a54ebe52995c2eb28085d1e3f09c986e73" "a00010c8e4785786eaaa5c85b98444bd93b585d0c24363ccc22c482e150a3fd900176" "86968e4fa20423ae72823b0049defceccb39bb34aa4ef64e6b14463b76d6a871c859e" - "37285455b94b8e1527d1525b1682ac6f7c8fd79d576c55318c1", 16), + "37285455b94b8e1527d1525b1682ac6f7c8fd79d576c55318c1", + 16, + ), dmp1=int( "23f7fa84010225dea98297032dac5d45745a2e07976605681acfe87e0920a8ab3caf5" - "9d9602f3d63dc0584f75161fd8fff20c626c21c5e02a85282276a74628a9", 16), + "9d9602f3d63dc0584f75161fd8fff20c626c21c5e02a85282276a74628a9", + 16, + ), dmq1=int( "18ebb657765464a8aa44bf019a882b72a2110a77934c54915f70e6375088b10331982" - "962bce1c7edd8ef9d3d95aa2566d2a99da6ebab890b95375919408d00f33", 16), + "962bce1c7edd8ef9d3d95aa2566d2a99da6ebab890b95375919408d00f33", + 16, + ), iqmp=int( "3d59d208743c74054151002d77dcdfc55af3d41357e89af88d7eef2767be54c290255" - "9258d85cf2a1083c035a33e65a1ca46dc8b706847c1c6434cef7b71a9dae", 16), + "9258d85cf2a1083c035a33e65a1ca46dc8b706847c1c6434cef7b71a9dae", + 16, + ), public_numbers=RSAPublicNumbers( e=65537, n=int( @@ -405,31 +546,44 @@ "8fcdbb6b4e12168304f587999f9d96a421fc80cb933a490df85d25883e6a88750" "d6bd8b3d4117251eee8f45e70e6daac7dbbd92a9103c623a09355cf00e3f16168" "e38b9c4cb5b368deabbed8df466bc6835eaba959bc1c2f4ec32a09840becc8b", - 16), - ) + 16, + ), + ), ) RSA_KEY_1031 = RSAPrivateNumbers( p=int( "c0958c08e50137db989fb7cc93abf1984543e2f955d4f43fb2967f40105e79274c852" - "293fa06ce63ca8436155e475ed6d1f73fea4c8e2516cc79153e3dc83e897", 16), + "293fa06ce63ca8436155e475ed6d1f73fea4c8e2516cc79153e3dc83e897", + 16, + ), q=int( "78cae354ea5d6862e5d71d20273b7cddb8cdfab25478fe865180676b04250685c4d03" - "30c216574f7876a7b12dfe69f1661d3b0cea6c2c0dcfb84050f817afc28d", 16), + "30c216574f7876a7b12dfe69f1661d3b0cea6c2c0dcfb84050f817afc28d", + 16, + ), d=int( "1d55cc02b17a5d25bfb39f2bc58389004d0d7255051507f75ef347cdf5519d1a00f4b" "d235ce4171bfab7bdb7a6dcfae1cf41433fb7da5923cc84f15a675c0b83492c95dd99" "a9fc157aea352ffdcbb5d59dbc3662171d5838d69f130678ee27841a79ef64f679ce9" - "3821fa69c03f502244c04b737edad8967def8022a144feaab29", 16), + "3821fa69c03f502244c04b737edad8967def8022a144feaab29", + 16, + ), dmp1=int( "5b1c2504ec3a984f86b4414342b5bcf59a0754f13adf25b2a0edbc43f5ba8c3cc061d" - "80b03e5866d059968f0d10a98deaeb4f7830436d76b22cf41f2914e13eff", 16), + "80b03e5866d059968f0d10a98deaeb4f7830436d76b22cf41f2914e13eff", + 16, + ), dmq1=int( "6c361e1819691ab5d67fb2a8f65c958d301cdf24d90617c68ec7005edfb4a7b638cde" - "79d4b61cfba5c86e8c0ccf296bc7f611cb8d4ae0e072a0f68552ec2d5995", 16), + "79d4b61cfba5c86e8c0ccf296bc7f611cb8d4ae0e072a0f68552ec2d5995", + 16, + ), iqmp=int( "b7d61945fdc8b92e075b15554bab507fa8a18edd0a18da373ec6c766c71eece61136a" - "84b90b6d01741d40458bfad17a9bee9d4a8ed2f6e270782dc3bf5d58b56e", 16), + "84b90b6d01741d40458bfad17a9bee9d4a8ed2f6e270782dc3bf5d58b56e", + 16, + ), public_numbers=RSAPublicNumbers( e=65537, n=int( @@ -437,38 +591,51 @@ "9f73da0690581691626d8a7cf5d972cced9c2091ccf999024b23b4e6dc6d99f80" "a454737dec0caffaebe4a3fac250ed02079267c8f39620b5ae3e125ca35338522" "dc9353ecac19cb2fe3b9e3a9291619dbb1ea3a7c388e9ee6469fbf5fb22892b", - 16), - ) + 16, + ), + ), ) RSA_KEY_1536 = RSAPrivateNumbers( p=int( "f1a65fa4e2aa6e7e2b560251e8a4cd65b625ad9f04f6571785782d1c213d91c961637" "0c572f2783caf2899f7fb690cf99a0184257fbd4b071b212c88fb348279a5387e61f1" - "17e9c62980c45ea863fa9292087c0f66ecdcde6443d5a37268bf71", 16), + "17e9c62980c45ea863fa9292087c0f66ecdcde6443d5a37268bf71", + 16, + ), q=int( "e54c2cbc3839b1da6ae6fea45038d986d6f523a3ae76051ba20583aab711ea5965cf5" "3cf54128cc9573f7460bba0fd6758a57aaf240c391790fb38ab473d83ef735510c53d" - "1d10c31782e8fd7da42615e33565745c30a5e6ceb2a3ae0666cc35", 16), + "1d10c31782e8fd7da42615e33565745c30a5e6ceb2a3ae0666cc35", + 16, + ), d=int( "7bcad87e23da2cb2a8c328883fabce06e1f8e9b776c8bf253ad9884e6200e3bd9bd3b" "a2cbe87d3854527bf005ba5d878c5b0fa20cfb0a2a42884ae95ca12bf7304285e9214" "5e992f7006c7c0ae839ad550da495b143bec0f4806c7f44caed45f3ccc6dc44cfaf30" "7abdb757e3d28e41c2d21366835c0a41e50a95af490ac03af061d2feb36ac0afb87be" "a13fb0f0c5a410727ebedb286c77f9469473fae27ef2c836da6071ef7efc1647f1233" - "4009a89eecb09a8287abc8c2afd1ddd9a1b0641", 16), + "4009a89eecb09a8287abc8c2afd1ddd9a1b0641", + 16, + ), dmp1=int( "a845366cd6f9df1f34861bef7594ed025aa83a12759e245f58adaa9bdff9c3befb760" "75d3701e90038e888eec9bf092df63400152cb25fc07effc6c74c45f0654ccbde15cd" - "90dd5504298a946fa5cf22a956072da27a6602e6c6e5c97f2db9c1", 16), + "90dd5504298a946fa5cf22a956072da27a6602e6c6e5c97f2db9c1", + 16, + ), dmq1=int( "28b0c1e78cdac03310717992d321a3888830ec6829978c048156152d805b4f8919c61" "70b5dd204e5ddf3c6c53bc6aff15d0bd09faff7f351b94abb9db980b31f150a6d7573" - "08eb66938f89a5225cb4dd817a824c89e7a0293b58fc2eefb7e259", 16), + "08eb66938f89a5225cb4dd817a824c89e7a0293b58fc2eefb7e259", + 16, + ), iqmp=int( "6c1536c0e16e42a094b6caaf50231ba81916871497d73dcbbbd4bdeb9e60cae0413b3" "8143b5d680275b29ed7769fe5577e4f9b3647ddb064941120914526d64d80016d2eb7" - "dc362da7c569623157f3d7cff8347f11494bf5c048d77e28d3f515", 16), + "dc362da7c569623157f3d7cff8347f11494bf5c048d77e28d3f515", + 16, + ), public_numbers=RSAPublicNumbers( e=65537, n=int( @@ -477,8 +644,10 @@ "c248ceef4050160705c188043c8559bf6dbfb6c4bb382eda4e9547575a8227d5b" "3c0a7088391364cf9f018d8bea053b226ec65e8cdbeaf48a071d0074860a734b1" "cb7d2146d43014b20776dea42f7853a54690e6cbbf3331a9f43763cfe2a51c329" - "3bea3b2eebec0d8e43eb317a443afe541107d886e5243c096091543ae65", 16), - ) + "3bea3b2eebec0d8e43eb317a443afe541107d886e5243c096091543ae65", + 16, + ), + ), ) RSA_KEY_2048 = RSAPrivateNumbers( @@ -486,12 +655,16 @@ "e14202e58c5f7446648d75e5dc465781f661f6b73000c080368afcfb21377f4ef19da" "845d4ef9bc6b151f6d9f34629103f2e57615f9ba0a3a2fbb035069e1d63b4bb0e78ad" "dad1ec3c6f87e25c877a1c4c1972098e09158ef7b9bc163852a18d44a70b7b31a03dc" - "2614fd9ab7bf002cba79054544af3bfbdb6aed06c7b24e6ab", 16), + "2614fd9ab7bf002cba79054544af3bfbdb6aed06c7b24e6ab", + 16, + ), q=int( "dbe2bea1ff92599bd19f9d045d6ce62250c05cfeac5117f3cf3e626cb696e3d886379" "557d5a57b7476f9cf886accfd40508a805fe3b45a78e1a8a125e516cda91640ee6398" "ec5a39d3e6b177ef12ab00d07907a17640e4ca454fd8487da3c4ffa0d5c2a5edb1221" - "1c8e33c7ee9fa6753771fd111ec04b8317f86693eb2928c89", 16), + "1c8e33c7ee9fa6753771fd111ec04b8317f86693eb2928c89", + 16, + ), d=int( "aef17f80f2653bc30539f26dd4c82ed6abc1d1b53bc0abcdbee47e9a8ab433abde865" "9fcfae1244d22de6ad333c95aee7d47f30b6815065ac3322744d3ea75058002cd1b29" @@ -500,22 +673,30 @@ "c8263ce2802a769a090e993fd49abc50c3d3c78c29bee2de0c98055d2f102f1c5684b" "8dddee611d5205392d8e8dd61a15bf44680972a87f040a611a149271eeb2573f8bf6f" "627dfa70e77def2ee6584914fa0290e041349ea0999cdff3e493365885b906cbcf195" - "843345809a85098cca90fea014a21", 16), + "843345809a85098cca90fea014a21", + 16, + ), dmp1=int( "9ba56522ffcfa5244eae805c87cc0303461f82be29691b9a7c15a5a050df6c143c575" "7c288d3d7ab7f32c782e9d9fcddc10a604e6425c0e5d0e46069035d95a923646d276d" "d9d95b8696fa29ab0de18e53f6f119310f8dd9efca62f0679291166fed8cbd5f18fe1" - "3a5f1ead1d71d8c90f40382818c18c8d069be793dbc094f69", 16), + "3a5f1ead1d71d8c90f40382818c18c8d069be793dbc094f69", + 16, + ), dmq1=int( "a8d4a0aaa2212ccc875796a81353da1fdf00d46676c88d2b96a4bfcdd924622d8e607" "f3ac1c01dda7ebfb0a97dd7875c2a7b2db6728fb827b89c519f5716fb3228f4121647" "04b30253c17de2289e9cce3343baa82eb404f789e094a094577a9b0c5314f1725fdf5" - "8e87611ad20da331bd30b8aebc7dc97d0e9a9ba8579772c9", 16), + "8e87611ad20da331bd30b8aebc7dc97d0e9a9ba8579772c9", + 16, + ), iqmp=int( "17bd5ef638c49440d1853acb3fa63a5aca28cb7f94ed350db7001c8445da8943866a7" "0936e1ee2716c98b484e357cc054d82fbbd98d42f880695d38a1dd4eb096f629b9417" "aca47e6de5da9f34e60e8a0ffd7e35be74deeef67298d94b3e0db73fc4b7a4cb360c8" - "9d2117a0bfd9434d37dc7c027d6b01e5295c875015510917d", 16), + "9d2117a0bfd9434d37dc7c027d6b01e5295c875015510917d", + 16, + ), public_numbers=RSAPublicNumbers( e=65537, n=int( @@ -526,8 +707,10 @@ "c29e53635e24c87a5b2c4215968063cdeb68a972babbc1e3cff00fb9a80e372a4" "d0c2c920d1e8cee333ce470dc2e8145adb05bf29aee1d24f141e8cc784989c587" "fc6fbacd979f3f2163c1d7299b365bc72ffe2848e967aed1e48dcc515b3a50ed4" - "de04fd053846ca10a223b10cc841cc80fdebee44f3114c13e886af583", 16), - ) + "de04fd053846ca10a223b10cc841cc80fdebee44f3114c13e886af583", + 16, + ), + ), ) RSA_KEY_2048_ALT = RSAPrivateNumbers( @@ -598,6 +781,6 @@ "715070507278514207864914944621214574162116786377990456375" "964817771730371110612100247262908550409785456157505694419" "00451152778245269283276012328748538414051025541" - ) - ) + ), + ), ) diff --git a/tests/hazmat/primitives/test_3des.py b/tests/hazmat/primitives/test_3des.py index 0f0f147095df..d14dcad9f71f 100644 --- a/tests/hazmat/primitives/test_3des.py +++ b/tests/hazmat/primitives/test_3des.py @@ -45,11 +45,7 @@ class TestTripleDESModeCBC(object): test_mmt = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "3DES", "CBC"), - [ - "TCBCMMT1.rsp", - "TCBCMMT2.rsp", - "TCBCMMT3.rsp", - ], + ["TCBCMMT1.rsp", "TCBCMMT2.rsp", "TCBCMMT3.rsp"], lambda key1, key2, key3, **kwargs: algorithms.TripleDES( binascii.unhexlify(key1 + key2 + key3) ), @@ -82,11 +78,7 @@ class TestTripleDESModeOFB(object): test_mmt = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "3DES", "OFB"), - [ - "TOFBMMT1.rsp", - "TOFBMMT2.rsp", - "TOFBMMT3.rsp", - ], + ["TOFBMMT1.rsp", "TOFBMMT2.rsp", "TOFBMMT3.rsp"], lambda key1, key2, key3, **kwargs: algorithms.TripleDES( binascii.unhexlify(key1 + key2 + key3) ), @@ -119,11 +111,7 @@ class TestTripleDESModeCFB(object): test_mmt = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "3DES", "CFB"), - [ - "TCFB64MMT1.rsp", - "TCFB64MMT2.rsp", - "TCFB64MMT3.rsp", - ], + ["TCFB64MMT1.rsp", "TCFB64MMT2.rsp", "TCFB64MMT3.rsp"], lambda key1, key2, key3, **kwargs: algorithms.TripleDES( binascii.unhexlify(key1 + key2 + key3) ), @@ -156,11 +144,7 @@ class TestTripleDESModeCFB8(object): test_mmt = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "3DES", "CFB"), - [ - "TCFB8MMT1.rsp", - "TCFB8MMT2.rsp", - "TCFB8MMT3.rsp", - ], + ["TCFB8MMT1.rsp", "TCFB8MMT2.rsp", "TCFB8MMT3.rsp"], lambda key1, key2, key3, **kwargs: algorithms.TripleDES( binascii.unhexlify(key1 + key2 + key3) ), @@ -193,11 +177,7 @@ class TestTripleDESModeECB(object): test_mmt = generate_encrypt_test( load_nist_vectors, os.path.join("ciphers", "3DES", "ECB"), - [ - "TECBMMT1.rsp", - "TECBMMT2.rsp", - "TECBMMT3.rsp", - ], + ["TECBMMT1.rsp", "TECBMMT2.rsp", "TECBMMT3.rsp"], lambda key1, key2, key3, **kwargs: algorithms.TripleDES( binascii.unhexlify(key1 + key2 + key3) ), diff --git a/tests/hazmat/primitives/test_aead.py b/tests/hazmat/primitives/test_aead.py index f8cf648ed45c..753c7c192bc9 100644 --- a/tests/hazmat/primitives/test_aead.py +++ b/tests/hazmat/primitives/test_aead.py @@ -12,13 +12,17 @@ from cryptography.exceptions import InvalidTag, UnsupportedAlgorithm, _Reasons from cryptography.hazmat.backends.interfaces import CipherBackend from cryptography.hazmat.primitives.ciphers.aead import ( - AESCCM, AESGCM, ChaCha20Poly1305 + AESCCM, + AESGCM, + ChaCha20Poly1305, ) from .utils import _load_all_params from ...utils import ( - load_nist_ccm_vectors, load_nist_vectors, load_vectors_from_file, - raises_unsupported_algorithm + load_nist_ccm_vectors, + load_nist_vectors, + load_vectors_from_file, + raises_unsupported_algorithm, ) @@ -37,7 +41,7 @@ def _aead_supported(cls): @pytest.mark.skipif( _aead_supported(ChaCha20Poly1305), - reason="Requires OpenSSL without ChaCha20Poly1305 support" + reason="Requires OpenSSL without ChaCha20Poly1305 support", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) def test_chacha20poly1305_unsupported_on_older_openssl(backend): @@ -47,7 +51,7 @@ def test_chacha20poly1305_unsupported_on_older_openssl(backend): @pytest.mark.skipif( not _aead_supported(ChaCha20Poly1305), - reason="Does not support ChaCha20Poly1305" + reason="Does not support ChaCha20Poly1305", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) class TestChaCha20Poly1305(object): @@ -78,11 +82,12 @@ def test_bad_key(self, backend): [ [object(), b"data", b""], [b"0" * 12, object(), b""], - [b"0" * 12, b"data", object()] - ] + [b"0" * 12, b"data", object()], + ], ) - def test_params_not_bytes_encrypt(self, nonce, data, associated_data, - backend): + def test_params_not_bytes_encrypt( + self, nonce, data, associated_data, backend + ): key = ChaCha20Poly1305.generate_key() chacha = ChaCha20Poly1305(key) with pytest.raises(TypeError): @@ -121,8 +126,8 @@ def test_associated_data_none_equal_to_empty_bytestring(self, backend): "vector", load_vectors_from_file( os.path.join("ciphers", "ChaCha20Poly1305", "openssl.txt"), - load_nist_vectors - ) + load_nist_vectors, + ), ) def test_openssl_vectors(self, vector, backend): key = binascii.unhexlify(vector["key"]) @@ -145,8 +150,8 @@ def test_openssl_vectors(self, vector, backend): "vector", load_vectors_from_file( os.path.join("ciphers", "ChaCha20Poly1305", "boringssl.txt"), - load_nist_vectors - ) + load_nist_vectors, + ), ) def test_boringssl_vectors(self, vector, backend): key = binascii.unhexlify(vector["key"]) @@ -231,22 +236,30 @@ def test_invalid_nonce_length(self, backend): _load_all_params( os.path.join("ciphers", "AES", "CCM"), [ - "DVPT128.rsp", "DVPT192.rsp", "DVPT256.rsp", - "VADT128.rsp", "VADT192.rsp", "VADT256.rsp", - "VNT128.rsp", "VNT192.rsp", "VNT256.rsp", - "VPT128.rsp", "VPT192.rsp", "VPT256.rsp", + "DVPT128.rsp", + "DVPT192.rsp", + "DVPT256.rsp", + "VADT128.rsp", + "VADT192.rsp", + "VADT256.rsp", + "VNT128.rsp", + "VNT192.rsp", + "VNT256.rsp", + "VPT128.rsp", + "VPT192.rsp", + "VPT256.rsp", ], - load_nist_ccm_vectors - ) + load_nist_ccm_vectors, + ), ) def test_vectors(self, vector, backend): key = binascii.unhexlify(vector["key"]) nonce = binascii.unhexlify(vector["nonce"]) - adata = binascii.unhexlify(vector["adata"])[:vector["alen"]] + adata = binascii.unhexlify(vector["adata"])[: vector["alen"]] ct = binascii.unhexlify(vector["ct"]) - pt = binascii.unhexlify(vector["payload"])[:vector["plen"]] + pt = binascii.unhexlify(vector["payload"])[: vector["plen"]] aesccm = AESCCM(key, vector["tlen"]) - if vector.get('fail'): + if vector.get("fail"): with pytest.raises(InvalidTag): aesccm.decrypt(nonce, ct, adata) else: @@ -279,7 +292,7 @@ def test_nonce_too_long(self, backend): [object(), b"data", b""], [b"0" * 12, object(), b""], [b"0" * 12, b"data", object()], - ] + ], ) def test_params_not_bytes(self, nonce, data, associated_data, backend): key = AESCCM.generate_key(128) @@ -345,7 +358,7 @@ def _load_gcm_vectors(): "gcmEncryptExtIV192.rsp", "gcmEncryptExtIV256.rsp", ], - load_nist_vectors + load_nist_vectors, ) return [x for x in vectors if len(x["tag"]) == 32] @@ -393,8 +406,8 @@ def test_vectors(self, backend, vector): [ [object(), b"data", b""], [b"0" * 12, object(), b""], - [b"0" * 12, b"data", object()] - ] + [b"0" * 12, b"data", object()], + ], ) def test_params_not_bytes(self, nonce, data, associated_data, backend): key = AESGCM.generate_key(128) diff --git a/tests/hazmat/primitives/test_aes.py b/tests/hazmat/primitives/test_aes.py index d99ba406d050..03328caff061 100644 --- a/tests/hazmat/primitives/test_aes.py +++ b/tests/hazmat/primitives/test_aes.py @@ -31,11 +31,15 @@ class TestAESModeXTS(object): # data unit length that is divisible by 8. The NIST vectors include # tests for implementations that support encryption of data that is # not divisible modulo 8, but OpenSSL is not such an implementation. - [x for x in _load_all_params( - os.path.join("ciphers", "AES", "XTS", "tweak-128hexstr"), - ["XTSGenAES128.rsp", "XTSGenAES256.rsp"], - load_nist_vectors - ) if int(x["dataunitlen"]) / 8.0 == int(x["dataunitlen"]) // 8] + [ + x + for x in _load_all_params( + os.path.join("ciphers", "AES", "XTS", "tweak-128hexstr"), + ["XTSGenAES128.rsp", "XTSGenAES256.rsp"], + load_nist_vectors, + ) + if int(x["dataunitlen"]) / 8.0 == int(x["dataunitlen"]) // 8 + ], ) def test_xts_vectors(self, vector, backend): key = binascii.unhexlify(vector["key"]) @@ -263,9 +267,7 @@ def test_gcm_tag_with_only_aad(self, backend): tag = binascii.unhexlify(b"0f247e7f9c2505de374006738018493b") cipher = base.Cipher( - algorithms.AES(key), - modes.GCM(iv), - backend=backend + algorithms.AES(key), modes.GCM(iv), backend=backend ) encryptor = cipher.encryptor() encryptor.authenticate_additional_data(aad) @@ -280,9 +282,7 @@ def test_gcm_ciphertext_with_no_aad(self, backend): pt = binascii.unhexlify(b"28286a321293253c3e0aa2704a278032") cipher = base.Cipher( - algorithms.AES(key), - modes.GCM(iv), - backend=backend + algorithms.AES(key), modes.GCM(iv), backend=backend ) encryptor = cipher.encryptor() computed_ct = encryptor.update(pt) + encryptor.finalize() @@ -293,13 +293,11 @@ def test_gcm_ciphertext_limit(self, backend): encryptor = base.Cipher( algorithms.AES(b"\x00" * 16), modes.GCM(b"\x01" * 16), - backend=backend + backend=backend, ).encryptor() encryptor._bytes_processed = modes.GCM._MAX_ENCRYPTED_BYTES - 16 encryptor.update(b"0" * 16) - assert ( - encryptor._bytes_processed == modes.GCM._MAX_ENCRYPTED_BYTES - ) + assert encryptor._bytes_processed == modes.GCM._MAX_ENCRYPTED_BYTES with pytest.raises(ValueError): encryptor.update(b"0") @@ -307,7 +305,7 @@ def test_gcm_aad_limit(self, backend): encryptor = base.Cipher( algorithms.AES(b"\x00" * 16), modes.GCM(b"\x01" * 16), - backend=backend + backend=backend, ).encryptor() encryptor._aad_bytes_processed = modes.GCM._MAX_AAD_BYTES - 16 encryptor.authenticate_additional_data(b"0" * 16) @@ -319,7 +317,7 @@ def test_gcm_ciphertext_increments(self, backend): encryptor = base.Cipher( algorithms.AES(b"\x00" * 16), modes.GCM(b"\x01" * 16), - backend=backend + backend=backend, ).encryptor() encryptor.update(b"0" * 8) assert encryptor._bytes_processed == 8 @@ -332,7 +330,7 @@ def test_gcm_aad_increments(self, backend): encryptor = base.Cipher( algorithms.AES(b"\x00" * 16), modes.GCM(b"\x01" * 16), - backend=backend + backend=backend, ).encryptor() encryptor.authenticate_additional_data(b"0" * 8) assert encryptor._aad_bytes_processed == 8 @@ -345,17 +343,13 @@ def test_gcm_tag_decrypt_none(self, backend): aad = binascii.unhexlify(b"b6d729aab8e6416d7002b9faa794c410d8d2f193") encryptor = base.Cipher( - algorithms.AES(key), - modes.GCM(iv), - backend=backend + algorithms.AES(key), modes.GCM(iv), backend=backend ).encryptor() encryptor.authenticate_additional_data(aad) encryptor.finalize() decryptor = base.Cipher( - algorithms.AES(key), - modes.GCM(iv), - backend=backend + algorithms.AES(key), modes.GCM(iv), backend=backend ).decryptor() decryptor.authenticate_additional_data(aad) with pytest.raises(ValueError): @@ -367,18 +361,14 @@ def test_gcm_tag_decrypt_mode(self, backend): aad = binascii.unhexlify(b"b6d729aab8e6416d7002b9faa794c410d8d2f193") encryptor = base.Cipher( - algorithms.AES(key), - modes.GCM(iv), - backend=backend + algorithms.AES(key), modes.GCM(iv), backend=backend ).encryptor() encryptor.authenticate_additional_data(aad) encryptor.finalize() tag = encryptor.tag decryptor = base.Cipher( - algorithms.AES(key), - modes.GCM(iv, tag), - backend=backend + algorithms.AES(key), modes.GCM(iv, tag), backend=backend ).decryptor() decryptor.authenticate_additional_data(aad) decryptor.finalize() @@ -389,18 +379,14 @@ def test_gcm_tag_decrypt_finalize(self, backend): aad = binascii.unhexlify(b"b6d729aab8e6416d7002b9faa794c410d8d2f193") encryptor = base.Cipher( - algorithms.AES(key), - modes.GCM(iv), - backend=backend + algorithms.AES(key), modes.GCM(iv), backend=backend ).encryptor() encryptor.authenticate_additional_data(aad) encryptor.finalize() tag = encryptor.tag decryptor = base.Cipher( - algorithms.AES(key), - modes.GCM(iv), - backend=backend + algorithms.AES(key), modes.GCM(iv), backend=backend ).decryptor() decryptor.authenticate_additional_data(aad) @@ -408,9 +394,7 @@ def test_gcm_tag_decrypt_finalize(self, backend): def test_gcm_tag_decrypt_finalize_tag_length(self, backend): decryptor = base.Cipher( - algorithms.AES(b"0" * 16), - modes.GCM(b"0" * 12), - backend=backend + algorithms.AES(b"0" * 16), modes.GCM(b"0" * 12), backend=backend ).decryptor() with pytest.raises(ValueError): decryptor.finalize_with_tag(b"tagtooshort") @@ -420,14 +404,14 @@ def test_buffer_protocol(self, backend): enc = base.Cipher( algorithms.AES(bytearray(b"\x00" * 16)), modes.GCM(bytearray(b"\x00" * 12)), - backend + backend, ).encryptor() enc.authenticate_additional_data(bytearray(b"foo")) ct = enc.update(data) + enc.finalize() dec = base.Cipher( algorithms.AES(bytearray(b"\x00" * 16)), modes.GCM(bytearray(b"\x00" * 12), enc.tag), - backend + backend, ).decryptor() dec.authenticate_additional_data(bytearray(b"foo")) pt = dec.update(ct) + dec.finalize() @@ -445,7 +429,7 @@ def test_buffer_protocol(self, backend): modes.XTS(bytearray(b"\x00" * 16)), # Add a dummy mode for coverage of the cipher_supported check. DummyMode(), - ] + ], ) @pytest.mark.requires_backend_interface(interface=CipherBackend) def test_buffer_protocol_alternate_modes(mode, backend): diff --git a/tests/hazmat/primitives/test_arc4.py b/tests/hazmat/primitives/test_arc4.py index 1a1734443704..de20b7098ae7 100644 --- a/tests/hazmat/primitives/test_arc4.py +++ b/tests/hazmat/primitives/test_arc4.py @@ -35,7 +35,7 @@ class TestARC4(object): "rfc-6229-128.txt", "rfc-6229-192.txt", "rfc-6229-256.txt", - "arc4.txt" + "arc4.txt", ], lambda key, **kwargs: algorithms.ARC4(binascii.unhexlify(key)), ) diff --git a/tests/hazmat/primitives/test_asym_utils.py b/tests/hazmat/primitives/test_asym_utils.py index b49ca3f2f84a..70bff012fbcb 100644 --- a/tests/hazmat/primitives/test_asym_utils.py +++ b/tests/hazmat/primitives/test_asym_utils.py @@ -7,7 +7,9 @@ import pytest from cryptography.hazmat.primitives.asymmetric.utils import ( - Prehashed, decode_dss_signature, encode_dss_signature + Prehashed, + decode_dss_signature, + encode_dss_signature, ) @@ -18,11 +20,11 @@ def test_dss_signature(): r_s1 = ( 1037234182290683143945502320610861668562885151617, - 559776156650501990899426031439030258256861634312 + 559776156650501990899426031439030258256861634312, ) sig2 = encode_dss_signature(*r_s1) assert sig2 == ( - b'0-\x02\x15\x00\xb5\xaf0xg\xfb\x8bT9\x00\x13\xccg\x02\r\xdf\x1f,\x0b' + b"0-\x02\x15\x00\xb5\xaf0xg\xfb\x8bT9\x00\x13\xccg\x02\r\xdf\x1f,\x0b" b'\x81\x02\x14b\r;"\xabP1D\x0c>5\xea\xb6\xf4\x81)\x8f\x9e\x9f\x08' ) assert decode_dss_signature(sig2) == r_s1 diff --git a/tests/hazmat/primitives/test_block.py b/tests/hazmat/primitives/test_block.py index 37158f153c7a..f827eee3b6c2 100644 --- a/tests/hazmat/primitives/test_block.py +++ b/tests/hazmat/primitives/test_block.py @@ -8,16 +8,18 @@ import pytest -from cryptography.exceptions import ( - AlreadyFinalized, _Reasons -) +from cryptography.exceptions import AlreadyFinalized, _Reasons from cryptography.hazmat.backends.interfaces import CipherBackend from cryptography.hazmat.primitives.ciphers import ( - Cipher, algorithms, base, modes + Cipher, + algorithms, + base, + modes, ) from .utils import ( - generate_aead_exception_test, generate_aead_tag_exception_test + generate_aead_exception_test, + generate_aead_tag_exception_test, ) from ...doubles import DummyCipherAlgorithm, DummyMode from ...utils import raises_unsupported_algorithm @@ -29,7 +31,7 @@ def test_creates_encryptor(self, backend): cipher = Cipher( algorithms.AES(binascii.unhexlify(b"0" * 32)), modes.CBC(binascii.unhexlify(b"0" * 32)), - backend + backend, ) assert isinstance(cipher.encryptor(), base.CipherContext) @@ -37,7 +39,7 @@ def test_creates_decryptor(self, backend): cipher = Cipher( algorithms.AES(binascii.unhexlify(b"0" * 32)), modes.CBC(binascii.unhexlify(b"0" * 32)), - backend + backend, ) assert isinstance(cipher.decryptor(), base.CipherContext) @@ -53,7 +55,7 @@ def test_use_after_finalize(self, backend): cipher = Cipher( algorithms.AES(binascii.unhexlify(b"0" * 32)), modes.CBC(binascii.unhexlify(b"0" * 32)), - backend + backend, ) encryptor = cipher.encryptor() encryptor.update(b"a" * 16) @@ -74,7 +76,7 @@ def test_use_update_into_after_finalize(self, backend): cipher = Cipher( algorithms.AES(binascii.unhexlify(b"0" * 32)), modes.CBC(binascii.unhexlify(b"0" * 32)), - backend + backend, ) encryptor = cipher.encryptor() encryptor.update(b"a" * 16) @@ -85,9 +87,7 @@ def test_use_update_into_after_finalize(self, backend): def test_unaligned_block_encryption(self, backend): cipher = Cipher( - algorithms.AES(binascii.unhexlify(b"0" * 32)), - modes.ECB(), - backend + algorithms.AES(binascii.unhexlify(b"0" * 32)), modes.ECB(), backend ) encryptor = cipher.encryptor() ct = encryptor.update(b"a" * 15) @@ -105,9 +105,7 @@ def test_unaligned_block_encryption(self, backend): @pytest.mark.parametrize("mode", [DummyMode(), None]) def test_nonexistent_cipher(self, backend, mode): - cipher = Cipher( - DummyCipherAlgorithm(), mode, backend - ) + cipher = Cipher(DummyCipherAlgorithm(), mode, backend) with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_CIPHER): cipher.encryptor() @@ -116,9 +114,7 @@ def test_nonexistent_cipher(self, backend, mode): def test_incorrectly_padded(self, backend): cipher = Cipher( - algorithms.AES(b"\x00" * 16), - modes.CBC(b"\x00" * 16), - backend + algorithms.AES(b"\x00" * 16), modes.CBC(b"\x00" * 16), backend ) encryptor = cipher.encryptor() encryptor.update(b"1") @@ -140,12 +136,10 @@ def test_incorrectly_padded(self, backend): @pytest.mark.requires_backend_interface(interface=CipherBackend) class TestAEADCipherContext(object): test_aead_exceptions = generate_aead_exception_test( - algorithms.AES, - modes.GCM, + algorithms.AES, modes.GCM, ) test_aead_tag_exceptions = generate_aead_tag_exception_test( - algorithms.AES, - modes.GCM, + algorithms.AES, modes.GCM, ) @@ -154,41 +148,31 @@ class TestModeValidation(object): def test_cbc(self, backend): with pytest.raises(ValueError): Cipher( - algorithms.AES(b"\x00" * 16), - modes.CBC(b"abc"), - backend, + algorithms.AES(b"\x00" * 16), modes.CBC(b"abc"), backend, ) def test_ofb(self, backend): with pytest.raises(ValueError): Cipher( - algorithms.AES(b"\x00" * 16), - modes.OFB(b"abc"), - backend, + algorithms.AES(b"\x00" * 16), modes.OFB(b"abc"), backend, ) def test_cfb(self, backend): with pytest.raises(ValueError): Cipher( - algorithms.AES(b"\x00" * 16), - modes.CFB(b"abc"), - backend, + algorithms.AES(b"\x00" * 16), modes.CFB(b"abc"), backend, ) def test_cfb8(self, backend): with pytest.raises(ValueError): Cipher( - algorithms.AES(b"\x00" * 16), - modes.CFB8(b"abc"), - backend, + algorithms.AES(b"\x00" * 16), modes.CFB8(b"abc"), backend, ) def test_ctr(self, backend): with pytest.raises(ValueError): Cipher( - algorithms.AES(b"\x00" * 16), - modes.CTR(b"abc"), - backend, + algorithms.AES(b"\x00" * 16), modes.CTR(b"abc"), backend, ) def test_gcm(self): diff --git a/tests/hazmat/primitives/test_camellia.py b/tests/hazmat/primitives/test_camellia.py index 07a735ad3158..b752345d3e44 100644 --- a/tests/hazmat/primitives/test_camellia.py +++ b/tests/hazmat/primitives/test_camellia.py @@ -13,9 +13,7 @@ from cryptography.hazmat.primitives.ciphers import algorithms, modes from .utils import generate_encrypt_test -from ...utils import ( - load_cryptrec_vectors, load_nist_vectors -) +from ...utils import load_cryptrec_vectors, load_nist_vectors @pytest.mark.supported( @@ -32,7 +30,7 @@ class TestCamelliaModeECB(object): [ "camellia-128-ecb.txt", "camellia-192-ecb.txt", - "camellia-256-ecb.txt" + "camellia-256-ecb.txt", ], lambda key, **kwargs: algorithms.Camellia(binascii.unhexlify(key)), lambda **kwargs: modes.ECB(), diff --git a/tests/hazmat/primitives/test_cast5.py b/tests/hazmat/primitives/test_cast5.py index 87e12a33a846..eff5d252f594 100644 --- a/tests/hazmat/primitives/test_cast5.py +++ b/tests/hazmat/primitives/test_cast5.py @@ -46,7 +46,7 @@ class TestCAST5ModeCBC(object): os.path.join("ciphers", "CAST5"), ["cast5-cbc.txt"], lambda key, **kwargs: algorithms.CAST5(binascii.unhexlify((key))), - lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv)) + lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv)), ) @@ -63,7 +63,7 @@ class TestCAST5ModeOFB(object): os.path.join("ciphers", "CAST5"), ["cast5-ofb.txt"], lambda key, **kwargs: algorithms.CAST5(binascii.unhexlify((key))), - lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv)) + lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv)), ) @@ -80,5 +80,5 @@ class TestCAST5ModeCFB(object): os.path.join("ciphers", "CAST5"), ["cast5-cfb.txt"], lambda key, **kwargs: algorithms.CAST5(binascii.unhexlify((key))), - lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)) + lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)), ) diff --git a/tests/hazmat/primitives/test_chacha20.py b/tests/hazmat/primitives/test_chacha20.py index 7c475c0f70a1..cb12d3c91ae2 100644 --- a/tests/hazmat/primitives/test_chacha20.py +++ b/tests/hazmat/primitives/test_chacha20.py @@ -30,8 +30,8 @@ class TestChaCha20(object): _load_all_params( os.path.join("ciphers", "ChaCha20"), ["rfc7539.txt"], - load_nist_vectors - ) + load_nist_vectors, + ), ) def test_vectors(self, vector, backend): key = binascii.unhexlify(vector["key"]) @@ -47,9 +47,7 @@ def test_vectors(self, vector, backend): def test_buffer_protocol(self, backend): key = bytearray(os.urandom(32)) nonce = bytearray(os.urandom(16)) - cipher = Cipher( - algorithms.ChaCha20(key, nonce), None, backend - ) + cipher = Cipher(algorithms.ChaCha20(key, nonce), None, backend) enc = cipher.encryptor() ct = enc.update(bytearray(b"hello")) + enc.finalize() dec = cipher.decryptor() diff --git a/tests/hazmat/primitives/test_ciphers.py b/tests/hazmat/primitives/test_ciphers.py index f29ba9a916a1..185c21359154 100644 --- a/tests/hazmat/primitives/test_ciphers.py +++ b/tests/hazmat/primitives/test_ciphers.py @@ -14,20 +14,28 @@ from cryptography.hazmat.primitives import ciphers from cryptography.hazmat.primitives.ciphers import modes from cryptography.hazmat.primitives.ciphers.algorithms import ( - AES, ARC4, Blowfish, CAST5, Camellia, IDEA, SEED, TripleDES + AES, + ARC4, + Blowfish, + CAST5, + Camellia, + IDEA, + SEED, + TripleDES, ) from ...utils import ( - load_nist_vectors, load_vectors_from_file, raises_unsupported_algorithm + load_nist_vectors, + load_vectors_from_file, + raises_unsupported_algorithm, ) class TestAES(object): - @pytest.mark.parametrize(("key", "keysize"), [ - (b"0" * 32, 128), - (b"0" * 48, 192), - (b"0" * 64, 256), - ]) + @pytest.mark.parametrize( + ("key", "keysize"), + [(b"0" * 32, 128), (b"0" * 48, 192), (b"0" * 64, 256)], + ) def test_key_size(self, key, keysize): cipher = AES(binascii.unhexlify(key)) assert cipher.key_size == keysize @@ -44,8 +52,7 @@ def test_invalid_key_type(self): class TestAESXTS(object): @pytest.mark.requires_backend_interface(interface=CipherBackend) @pytest.mark.parametrize( - "mode", - (modes.CBC, modes.CTR, modes.CFB, modes.CFB8, modes.OFB) + "mode", (modes.CBC, modes.CTR, modes.CFB, modes.CFB8, modes.OFB) ) def test_invalid_key_size_with_mode(self, mode, backend): with pytest.raises(ValueError): @@ -66,11 +73,10 @@ def test_xts_wrong_key_size(self, backend): class TestCamellia(object): - @pytest.mark.parametrize(("key", "keysize"), [ - (b"0" * 32, 128), - (b"0" * 48, 192), - (b"0" * 64, 256), - ]) + @pytest.mark.parametrize( + ("key", "keysize"), + [(b"0" * 32, 128), (b"0" * 48, 192), (b"0" * 64, 256)], + ) def test_key_size(self, key, keysize): cipher = Camellia(binascii.unhexlify(key)) assert cipher.key_size == keysize @@ -85,11 +91,7 @@ def test_invalid_key_type(self): class TestTripleDES(object): - @pytest.mark.parametrize("key", [ - b"0" * 16, - b"0" * 32, - b"0" * 48, - ]) + @pytest.mark.parametrize("key", [b"0" * 16, b"0" * 32, b"0" * 48]) def test_key_size(self, key): cipher = TripleDES(binascii.unhexlify(key)) assert cipher.key_size == 192 @@ -104,9 +106,10 @@ def test_invalid_key_type(self): class TestBlowfish(object): - @pytest.mark.parametrize(("key", "keysize"), [ - (b"0" * (keysize // 4), keysize) for keysize in range(32, 449, 8) - ]) + @pytest.mark.parametrize( + ("key", "keysize"), + [(b"0" * (keysize // 4), keysize) for keysize in range(32, 449, 8)], + ) def test_key_size(self, key, keysize): cipher = Blowfish(binascii.unhexlify(key)) assert cipher.key_size == keysize @@ -121,9 +124,10 @@ def test_invalid_key_type(self): class TestCAST5(object): - @pytest.mark.parametrize(("key", "keysize"), [ - (b"0" * (keysize // 4), keysize) for keysize in range(40, 129, 8) - ]) + @pytest.mark.parametrize( + ("key", "keysize"), + [(b"0" * (keysize // 4), keysize) for keysize in range(40, 129, 8)], + ) def test_key_size(self, key, keysize): cipher = CAST5(binascii.unhexlify(key)) assert cipher.key_size == keysize @@ -138,15 +142,18 @@ def test_invalid_key_type(self): class TestARC4(object): - @pytest.mark.parametrize(("key", "keysize"), [ - (b"0" * 10, 40), - (b"0" * 14, 56), - (b"0" * 16, 64), - (b"0" * 20, 80), - (b"0" * 32, 128), - (b"0" * 48, 192), - (b"0" * 64, 256), - ]) + @pytest.mark.parametrize( + ("key", "keysize"), + [ + (b"0" * 10, 40), + (b"0" * 14, 56), + (b"0" * 16, 64), + (b"0" * 20, 80), + (b"0" * 32, 128), + (b"0" * 48, 192), + (b"0" * 64, 256), + ], + ) def test_key_size(self, key, keysize): cipher = ARC4(binascii.unhexlify(key)) assert cipher.key_size == keysize @@ -207,8 +214,8 @@ class TestCipherUpdateInto(object): "params", load_vectors_from_file( os.path.join("ciphers", "AES", "ECB", "ECBGFSbox128.rsp"), - load_nist_vectors - ) + load_nist_vectors, + ), ) def test_update_into(self, params, backend): key = binascii.unhexlify(params["key"]) @@ -272,8 +279,8 @@ def test_finalize_with_tag_already_finalized(self, backend): "params", load_vectors_from_file( os.path.join("ciphers", "AES", "ECB", "ECBGFSbox128.rsp"), - load_nist_vectors - ) + load_nist_vectors, + ), ) def test_update_into_multiple_calls(self, params, backend): key = binascii.unhexlify(params["key"]) diff --git a/tests/hazmat/primitives/test_cmac.py b/tests/hazmat/primitives/test_cmac.py index e319396d6865..e4a35df621fd 100644 --- a/tests/hazmat/primitives/test_cmac.py +++ b/tests/hazmat/primitives/test_cmac.py @@ -9,32 +9,42 @@ import pytest from cryptography.exceptions import ( - AlreadyFinalized, InvalidSignature, _Reasons + AlreadyFinalized, + InvalidSignature, + _Reasons, ) from cryptography.hazmat.backends.interfaces import CMACBackend from cryptography.hazmat.primitives.ciphers.algorithms import ( - AES, ARC4, TripleDES + AES, + ARC4, + TripleDES, ) from cryptography.hazmat.primitives.cmac import CMAC from ...utils import ( - load_nist_vectors, load_vectors_from_file, raises_unsupported_algorithm + load_nist_vectors, + load_vectors_from_file, + raises_unsupported_algorithm, ) vectors_aes128 = load_vectors_from_file( - "CMAC/nist-800-38b-aes128.txt", load_nist_vectors) + "CMAC/nist-800-38b-aes128.txt", load_nist_vectors +) vectors_aes192 = load_vectors_from_file( - "CMAC/nist-800-38b-aes192.txt", load_nist_vectors) + "CMAC/nist-800-38b-aes192.txt", load_nist_vectors +) vectors_aes256 = load_vectors_from_file( - "CMAC/nist-800-38b-aes256.txt", load_nist_vectors) + "CMAC/nist-800-38b-aes256.txt", load_nist_vectors +) vectors_aes = vectors_aes128 + vectors_aes192 + vectors_aes256 vectors_3des = load_vectors_from_file( - "CMAC/nist-800-38b-3des.txt", load_nist_vectors) + "CMAC/nist-800-38b-3des.txt", load_nist_vectors +) fake_key = b"\x00" * 16 @@ -43,8 +53,9 @@ class TestCMAC(object): @pytest.mark.supported( only_if=lambda backend: backend.cmac_algorithm_supported( - AES(fake_key)), - skip_message="Does not support CMAC." + AES(fake_key) + ), + skip_message="Does not support CMAC.", ) @pytest.mark.parametrize("params", vectors_aes) def test_aes_generate(self, backend, params): @@ -58,8 +69,9 @@ def test_aes_generate(self, backend, params): @pytest.mark.supported( only_if=lambda backend: backend.cmac_algorithm_supported( - AES(fake_key)), - skip_message="Does not support CMAC." + AES(fake_key) + ), + skip_message="Does not support CMAC.", ) @pytest.mark.parametrize("params", vectors_aes) def test_aes_verify(self, backend, params): @@ -73,8 +85,9 @@ def test_aes_verify(self, backend, params): @pytest.mark.supported( only_if=lambda backend: backend.cmac_algorithm_supported( - TripleDES(fake_key)), - skip_message="Does not support CMAC." + TripleDES(fake_key) + ), + skip_message="Does not support CMAC.", ) @pytest.mark.parametrize("params", vectors_3des) def test_3des_generate(self, backend, params): @@ -93,8 +106,9 @@ def test_3des_generate(self, backend, params): @pytest.mark.supported( only_if=lambda backend: backend.cmac_algorithm_supported( - TripleDES(fake_key)), - skip_message="Does not support CMAC." + TripleDES(fake_key) + ), + skip_message="Does not support CMAC.", ) @pytest.mark.parametrize("params", vectors_3des) def test_3des_verify(self, backend, params): @@ -113,8 +127,9 @@ def test_3des_verify(self, backend, params): @pytest.mark.supported( only_if=lambda backend: backend.cmac_algorithm_supported( - AES(fake_key)), - skip_message="Does not support CMAC." + AES(fake_key) + ), + skip_message="Does not support CMAC.", ) def test_invalid_verify(self, backend): key = b"2b7e151628aed2a6abf7158809cf4f3c" @@ -125,9 +140,8 @@ def test_invalid_verify(self, backend): cmac.verify(b"foobar") @pytest.mark.supported( - only_if=lambda backend: backend.cipher_supported( - ARC4(fake_key), None), - skip_message="Does not support CMAC." + only_if=lambda backend: backend.cipher_supported(ARC4(fake_key), None), + skip_message="Does not support CMAC.", ) def test_invalid_algorithm(self, backend): key = b"0102030405" @@ -136,8 +150,9 @@ def test_invalid_algorithm(self, backend): @pytest.mark.supported( only_if=lambda backend: backend.cmac_algorithm_supported( - AES(fake_key)), - skip_message="Does not support CMAC." + AES(fake_key) + ), + skip_message="Does not support CMAC.", ) def test_raises_after_finalize(self, backend): key = b"2b7e151628aed2a6abf7158809cf4f3c" @@ -158,23 +173,25 @@ def test_raises_after_finalize(self, backend): @pytest.mark.supported( only_if=lambda backend: backend.cmac_algorithm_supported( - AES(fake_key)), - skip_message="Does not support CMAC." + AES(fake_key) + ), + skip_message="Does not support CMAC.", ) def test_verify_reject_unicode(self, backend): key = b"2b7e151628aed2a6abf7158809cf4f3c" cmac = CMAC(AES(key), backend) with pytest.raises(TypeError): - cmac.update(u'') + cmac.update(u"") with pytest.raises(TypeError): - cmac.verify(u'') + cmac.verify(u"") @pytest.mark.supported( only_if=lambda backend: backend.cmac_algorithm_supported( - AES(fake_key)), - skip_message="Does not support CMAC." + AES(fake_key) + ), + skip_message="Does not support CMAC.", ) def test_copy_with_backend(self, backend): key = b"2b7e151628aed2a6abf7158809cf4f3c" @@ -185,8 +202,9 @@ def test_copy_with_backend(self, backend): @pytest.mark.supported( only_if=lambda backend: backend.cmac_algorithm_supported( - AES(fake_key)), - skip_message="Does not support CMAC." + AES(fake_key) + ), + skip_message="Does not support CMAC.", ) def test_buffer_protocol(self, backend): key = bytearray(b"2b7e151628aed2a6abf7158809cf4f3c") diff --git a/tests/hazmat/primitives/test_concatkdf.py b/tests/hazmat/primitives/test_concatkdf.py index 673150999865..271e01175d30 100644 --- a/tests/hazmat/primitives/test_concatkdf.py +++ b/tests/hazmat/primitives/test_concatkdf.py @@ -8,9 +8,7 @@ import pytest -from cryptography.exceptions import ( - AlreadyFinalized, InvalidKey, _Reasons -) +from cryptography.exceptions import AlreadyFinalized, InvalidKey, _Reasons from cryptography.hazmat.backends.interfaces import HMACBackend from cryptography.hazmat.backends.interfaces import HashBackend from cryptography.hazmat.primitives import hashes @@ -102,38 +100,26 @@ def test_invalid_verify(self, backend): def test_unicode_typeerror(self, backend): with pytest.raises(TypeError): ConcatKDFHash( - hashes.SHA256(), - 16, - otherinfo=u"foo", - backend=backend + hashes.SHA256(), 16, otherinfo=u"foo", backend=backend ) with pytest.raises(TypeError): ckdf = ConcatKDFHash( - hashes.SHA256(), - 16, - otherinfo=None, - backend=backend + hashes.SHA256(), 16, otherinfo=None, backend=backend ) ckdf.derive(u"foo") with pytest.raises(TypeError): ckdf = ConcatKDFHash( - hashes.SHA256(), - 16, - otherinfo=None, - backend=backend + hashes.SHA256(), 16, otherinfo=None, backend=backend ) ckdf.verify(u"foo", b"bar") with pytest.raises(TypeError): ckdf = ConcatKDFHash( - hashes.SHA256(), - 16, - otherinfo=None, - backend=backend + hashes.SHA256(), 16, otherinfo=None, backend=backend ) ckdf.verify(b"foo", u"bar") @@ -162,8 +148,10 @@ def test_derive(self, backend): b"8f0af7fce1d045edbc5790931e8d5ca79c73" ) - okm = binascii.unhexlify(b"64ce901db10d558661f10b6836a122a7" - b"605323ce2f39bf27eaaac8b34cf89f2f") + okm = binascii.unhexlify( + b"64ce901db10d558661f10b6836a122a7" + b"605323ce2f39bf27eaaac8b34cf89f2f" + ) oinfo = binascii.unhexlify( b"a1b2c3d4e55e600be5f367e0e8a465f4bf2704db00c9325c" @@ -181,8 +169,10 @@ def test_buffer_protocol(self, backend): b"8f0af7fce1d045edbc5790931e8d5ca79c73" ) - okm = binascii.unhexlify(b"64ce901db10d558661f10b6836a122a7" - b"605323ce2f39bf27eaaac8b34cf89f2f") + okm = binascii.unhexlify( + b"64ce901db10d558661f10b6836a122a7" + b"605323ce2f39bf27eaaac8b34cf89f2f" + ) oinfo = binascii.unhexlify( b"a1b2c3d4e55e600be5f367e0e8a465f4bf2704db00c9325c" @@ -200,8 +190,10 @@ def test_derive_explicit_salt(self, backend): b"8f0af7fce1d045edbc5790931e8d5ca79c73" ) - okm = binascii.unhexlify(b"64ce901db10d558661f10b6836a122a7" - b"605323ce2f39bf27eaaac8b34cf89f2f") + okm = binascii.unhexlify( + b"64ce901db10d558661f10b6836a122a7" + b"605323ce2f39bf27eaaac8b34cf89f2f" + ) oinfo = binascii.unhexlify( b"a1b2c3d4e55e600be5f367e0e8a465f4bf2704db00c9325c" @@ -221,8 +213,10 @@ def test_verify(self, backend): b"8f0af7fce1d045edbc5790931e8d5ca79c73" ) - okm = binascii.unhexlify(b"64ce901db10d558661f10b6836a122a7" - b"605323ce2f39bf27eaaac8b34cf89f2f") + okm = binascii.unhexlify( + b"64ce901db10d558661f10b6836a122a7" + b"605323ce2f39bf27eaaac8b34cf89f2f" + ) oinfo = binascii.unhexlify( b"a1b2c3d4e55e600be5f367e0e8a465f4bf2704db00c9325c" @@ -254,45 +248,38 @@ def test_unicode_typeerror(self, backend): with pytest.raises(TypeError): ConcatKDFHMAC( hashes.SHA256(), - 16, salt=u"foo", + 16, + salt=u"foo", otherinfo=None, - backend=backend + backend=backend, ) with pytest.raises(TypeError): ConcatKDFHMAC( hashes.SHA256(), - 16, salt=None, + 16, + salt=None, otherinfo=u"foo", - backend=backend + backend=backend, ) with pytest.raises(TypeError): ckdf = ConcatKDFHMAC( - hashes.SHA256(), - 16, salt=None, - otherinfo=None, - backend=backend + hashes.SHA256(), 16, salt=None, otherinfo=None, backend=backend ) ckdf.derive(u"foo") with pytest.raises(TypeError): ckdf = ConcatKDFHMAC( - hashes.SHA256(), - 16, salt=None, - otherinfo=None, - backend=backend + hashes.SHA256(), 16, salt=None, otherinfo=None, backend=backend ) ckdf.verify(u"foo", b"bar") with pytest.raises(TypeError): ckdf = ConcatKDFHMAC( - hashes.SHA256(), - 16, salt=None, - otherinfo=None, - backend=backend + hashes.SHA256(), 16, salt=None, otherinfo=None, backend=backend ) ckdf.verify(b"foo", u"bar") diff --git a/tests/hazmat/primitives/test_dh.py b/tests/hazmat/primitives/test_dh.py index 98d1b5337f94..29b0e3ef6b01 100644 --- a/tests/hazmat/primitives/test_dh.py +++ b/tests/hazmat/primitives/test_dh.py @@ -11,7 +11,10 @@ import pytest from cryptography.hazmat.backends.interfaces import ( - DERSerializationBackend, DHBackend, PEMSerializationBackend) + DERSerializationBackend, + DHBackend, + PEMSerializationBackend, +) from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import dh from cryptography.utils import int_from_bytes @@ -25,100 +28,72 @@ def _skip_dhx_unsupported(backend, is_dhx): if not is_dhx: return if not backend.dh_x942_serialization_supported(): - pytest.skip( - "DH x9.42 serialization is not supported" - ) + pytest.skip("DH x9.42 serialization is not supported") def test_dh_parameternumbers(): - params = dh.DHParameterNumbers( - 65537, 2 - ) + params = dh.DHParameterNumbers(65537, 2) assert params.p == 65537 assert params.g == 2 with pytest.raises(TypeError): - dh.DHParameterNumbers( - None, 2 - ) + dh.DHParameterNumbers(None, 2) with pytest.raises(TypeError): - dh.DHParameterNumbers( - 65537, None - ) + dh.DHParameterNumbers(65537, None) with pytest.raises(TypeError): - dh.DHParameterNumbers( - None, None - ) + dh.DHParameterNumbers(None, None) with pytest.raises(ValueError): - dh.DHParameterNumbers( - 65537, 1 - ) + dh.DHParameterNumbers(65537, 1) - params = dh.DHParameterNumbers( - 65537, 7, 1245 - ) + params = dh.DHParameterNumbers(65537, 7, 1245) assert params.p == 65537 assert params.g == 7 assert params.q == 1245 with pytest.raises(TypeError): - dh.DHParameterNumbers( - 65537, 2, "hello" - ) + dh.DHParameterNumbers(65537, 2, "hello") def test_dh_numbers(): - params = dh.DHParameterNumbers( - 65537, 2 - ) + params = dh.DHParameterNumbers(65537, 2) - public = dh.DHPublicNumbers( - 1, params - ) + public = dh.DHPublicNumbers(1, params) assert public.parameter_numbers is params assert public.y == 1 with pytest.raises(TypeError): - dh.DHPublicNumbers( - 1, None - ) + dh.DHPublicNumbers(1, None) with pytest.raises(TypeError): - dh.DHPublicNumbers( - None, params - ) + dh.DHPublicNumbers(None, params) - private = dh.DHPrivateNumbers( - 1, public - ) + private = dh.DHPrivateNumbers(1, public) assert private.public_numbers is public assert private.x == 1 with pytest.raises(TypeError): - dh.DHPrivateNumbers( - 1, None - ) + dh.DHPrivateNumbers(1, None) with pytest.raises(TypeError): - dh.DHPrivateNumbers( - None, public - ) + dh.DHPrivateNumbers(None, public) def test_dh_parameter_numbers_equality(): assert dh.DHParameterNumbers(65537, 2) == dh.DHParameterNumbers(65537, 2) assert dh.DHParameterNumbers(65537, 7, 12345) == dh.DHParameterNumbers( - 65537, 7, 12345) + 65537, 7, 12345 + ) assert dh.DHParameterNumbers(6, 2) != dh.DHParameterNumbers(65537, 2) assert dh.DHParameterNumbers(65537, 2, 123) != dh.DHParameterNumbers( - 65537, 2, 456) + 65537, 2, 456 + ) assert dh.DHParameterNumbers(65537, 5) != dh.DHParameterNumbers(65537, 2) assert dh.DHParameterNumbers(65537, 2) != object() @@ -163,7 +138,8 @@ def test_dh_parameters_supported(self, backend): b"bcfc7f938a269710ed69e330523e4039029b7900977c740990d46efed79b9bbe" b"73505ae878808944ce4d9c6c52daecc0a87dc889c53499be93db8551ee685f30" b"349bf1b443d4ebaee0d5e8b441a40d4e8178f8f612f657a5eb91e0a8e" - b"107755f", 16 + b"107755f", + 16, ) assert backend.dh_parameters_supported(valid_p, 5) assert not backend.dh_parameters_supported(23, 22) @@ -171,12 +147,11 @@ def test_dh_parameters_supported(self, backend): @pytest.mark.parametrize( "vector", load_vectors_from_file( - os.path.join("asymmetric", "DH", "rfc3526.txt"), - load_nist_vectors - ) + os.path.join("asymmetric", "DH", "rfc3526.txt"), load_nist_vectors + ), ) def test_dh_parameters_allows_rfc3526_groups(self, backend, vector): - p = int_from_bytes(binascii.unhexlify(vector["p"]), 'big') + p = int_from_bytes(binascii.unhexlify(vector["p"]), "big") params = dh.DHParameterNumbers(p, int(vector["g"])) param = params.parameters(backend) key = param.generate_private_key() @@ -189,12 +164,13 @@ def test_dh_parameters_allows_rfc3526_groups(self, backend, vector): @pytest.mark.parametrize( "vector", load_vectors_from_file( - os.path.join("asymmetric", "DH", "RFC5114.txt"), - load_nist_vectors)) + os.path.join("asymmetric", "DH", "RFC5114.txt"), load_nist_vectors + ), + ) def test_dh_parameters_supported_with_q(self, backend, vector): - assert backend.dh_parameters_supported(int(vector["p"], 16), - int(vector["g"], 16), - int(vector["q"], 16)) + assert backend.dh_parameters_supported( + int(vector["p"], 16), int(vector["g"], 16), int(vector["q"], 16) + ) @pytest.mark.skip_fips(reason="modulus too small for FIPS") @pytest.mark.parametrize("with_q", [False, True]) @@ -202,7 +178,8 @@ def test_convert_to_numbers(self, backend, with_q): if with_q: vector = load_vectors_from_file( os.path.join("asymmetric", "DH", "RFC5114.txt"), - load_nist_vectors)[0] + load_nist_vectors, + )[0] p = int(vector["p"], 16) g = int(vector["g"], 16) q = int(vector["q"], 16) @@ -223,12 +200,13 @@ def test_convert_to_numbers(self, backend, with_q): deserialized_public = public.public_key(backend) deserialized_private = private.private_key(backend) - assert isinstance(deserialized_params, - dh.DHParametersWithSerialization) - assert isinstance(deserialized_public, - dh.DHPublicKeyWithSerialization) - assert isinstance(deserialized_private, - dh.DHPrivateKeyWithSerialization) + assert isinstance( + deserialized_params, dh.DHParametersWithSerialization + ) + assert isinstance(deserialized_public, dh.DHPublicKeyWithSerialization) + assert isinstance( + deserialized_private, dh.DHPrivateKeyWithSerialization + ) def test_numbers_unsupported_parameters(self, backend): # p is set to 21 because when calling private_key we want it to @@ -249,7 +227,8 @@ def test_generate_dh(self, backend, with_q): if with_q: vector = load_vectors_from_file( os.path.join("asymmetric", "DH", "RFC5114.txt"), - load_nist_vectors)[0] + load_nist_vectors, + )[0] p = int(vector["p"], 16) g = int(vector["g"], 16) q = int(vector["q"], 16) @@ -303,11 +282,13 @@ def test_exchange_algorithm(self, backend): key2 = parameters.generate_private_key() shared_key_bytes = key2.exchange(key1.public_key()) - symkey = int_from_bytes(shared_key_bytes, 'big') + symkey = int_from_bytes(shared_key_bytes, "big") - symkey_manual = pow(key1.public_key().public_numbers().y, - key2.private_numbers().x, - parameters.parameter_numbers().p) + symkey_manual = pow( + key1.public_key().public_numbers().y, + key2.private_numbers().x, + parameters.parameter_numbers().p, + ) assert symkey == symkey_manual @@ -318,44 +299,54 @@ def test_symmetric_key_padding(self, backend): In length 63 bytes instead 64. We make sure here that we add padding to the key. """ - p = int("11859949538425015739337467917303613431031019140213666" - "129025407300654026585086345323066284800963463204246390" - "256567934582260424238844463330887962689642467123") + p = int( + "11859949538425015739337467917303613431031019140213666" + "129025407300654026585086345323066284800963463204246390" + "256567934582260424238844463330887962689642467123" + ) g = 2 - y = int("32155788395534640648739966373159697798396966919821525" - "72238852825117261342483718574508213761865276905503199" - "969908098203345481366464874759377454476688391248") - x = int("409364065449673443397833358558926598469347813468816037" - "268451847116982490733450463194921405069999008617231539" - "7147035896687401350877308899732826446337707128") + y = int( + "32155788395534640648739966373159697798396966919821525" + "72238852825117261342483718574508213761865276905503199" + "969908098203345481366464874759377454476688391248" + ) + x = int( + "409364065449673443397833358558926598469347813468816037" + "268451847116982490733450463194921405069999008617231539" + "7147035896687401350877308899732826446337707128" + ) parameters = dh.DHParameterNumbers(p, g) public = dh.DHPublicNumbers(y, parameters) private = dh.DHPrivateNumbers(x, public) key = private.private_key(backend) symkey = key.exchange(public.public_key(backend)) assert len(symkey) == 512 // 8 - assert symkey[:1] == b'\x00' + assert symkey[:1] == b"\x00" @pytest.mark.parametrize( "vector", load_vectors_from_file( os.path.join("asymmetric", "DH", "bad_exchange.txt"), - load_nist_vectors)) + load_nist_vectors, + ), + ) def test_bad_exchange(self, backend, vector): if ( - backend._fips_enabled and - int(vector["p1"]) < backend._fips_dh_min_modulus + backend._fips_enabled + and int(vector["p1"]) < backend._fips_dh_min_modulus ): pytest.skip("modulus too small for FIPS mode") - parameters1 = dh.DHParameterNumbers(int(vector["p1"]), - int(vector["g"])) + parameters1 = dh.DHParameterNumbers( + int(vector["p1"]), int(vector["g"]) + ) public1 = dh.DHPublicNumbers(int(vector["y1"]), parameters1) private1 = dh.DHPrivateNumbers(int(vector["x1"]), public1) key1 = private1.private_key(backend) pub_key1 = key1.public_key() - parameters2 = dh.DHParameterNumbers(int(vector["p2"]), - int(vector["g"])) + parameters2 = dh.DHParameterNumbers( + int(vector["p2"]), int(vector["g"]) + ) public2 = dh.DHPublicNumbers(int(vector["y2"]), parameters2) private2 = dh.DHPrivateNumbers(int(vector["x2"]), public2) key2 = private2.private_key(backend) @@ -375,32 +366,33 @@ def test_bad_exchange(self, backend, vector): @pytest.mark.parametrize( "vector", load_vectors_from_file( - os.path.join("asymmetric", "DH", "vec.txt"), - load_nist_vectors)) + os.path.join("asymmetric", "DH", "vec.txt"), load_nist_vectors + ), + ) def test_dh_vectors(self, backend, vector): if ( - backend._fips_enabled and - int(vector["p"]) < backend._fips_dh_min_modulus + backend._fips_enabled + and int(vector["p"]) < backend._fips_dh_min_modulus ): pytest.skip("modulus too small for FIPS mode") - parameters = dh.DHParameterNumbers(int(vector["p"]), - int(vector["g"])) + parameters = dh.DHParameterNumbers(int(vector["p"]), int(vector["g"])) public = dh.DHPublicNumbers(int(vector["y"]), parameters) private = dh.DHPrivateNumbers(int(vector["x"]), public) key = private.private_key(backend) symkey = key.exchange(public.public_key(backend)) - assert int_from_bytes(symkey, 'big') == int(vector["k"], 16) + assert int_from_bytes(symkey, "big") == int(vector["k"], 16) @pytest.mark.parametrize( "vector", load_vectors_from_file( - os.path.join("asymmetric", "DH", "RFC5114.txt"), - load_nist_vectors)) + os.path.join("asymmetric", "DH", "RFC5114.txt"), load_nist_vectors + ), + ) def test_dh_vectors_with_q(self, backend, vector): - parameters = dh.DHParameterNumbers(int(vector["p"], 16), - int(vector["g"], 16), - int(vector["q"], 16)) + parameters = dh.DHParameterNumbers( + int(vector["p"], 16), int(vector["g"], 16), int(vector["q"], 16) + ) public1 = dh.DHPublicNumbers(int(vector["ystatcavs"], 16), parameters) private1 = dh.DHPrivateNumbers(int(vector["xstatcavs"], 16), public1) public2 = dh.DHPublicNumbers(int(vector["ystatiut"], 16), parameters) @@ -410,34 +402,28 @@ def test_dh_vectors_with_q(self, backend, vector): symkey1 = key1.exchange(public2.public_key(backend)) symkey2 = key2.exchange(public1.public_key(backend)) - assert int_from_bytes(symkey1, 'big') == int(vector["z"], 16) - assert int_from_bytes(symkey2, 'big') == int(vector["z"], 16) + assert int_from_bytes(symkey1, "big") == int(vector["z"], 16) + assert int_from_bytes(symkey2, "big") == int(vector["z"], 16) @pytest.mark.requires_backend_interface(interface=DHBackend) @pytest.mark.requires_backend_interface(interface=PEMSerializationBackend) @pytest.mark.requires_backend_interface(interface=DERSerializationBackend) class TestDHPrivateKeySerialization(object): - @pytest.mark.parametrize( ("encoding", "loader_func"), [ - [ - serialization.Encoding.PEM, - serialization.load_pem_private_key - ], - [ - serialization.Encoding.DER, - serialization.load_der_private_key - ], - ] + [serialization.Encoding.PEM, serialization.load_pem_private_key], + [serialization.Encoding.DER, serialization.load_der_private_key], + ], ) def test_private_bytes_unencrypted(self, backend, encoding, loader_func): parameters = FFDH3072_P.parameters(backend) key = parameters.generate_private_key() serialized = key.private_bytes( - encoding, serialization.PrivateFormat.PKCS8, - serialization.NoEncryption() + encoding, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), ) loaded_key = loader_func(serialized, None, backend) loaded_priv_num = loaded_key.private_numbers() @@ -451,7 +437,7 @@ def test_private_bytes_unencrypted(self, backend, encoding, loader_func): (serialization.Encoding.DER, serialization.PrivateFormat.Raw), (serialization.Encoding.Raw, serialization.PrivateFormat.Raw), (serialization.Encoding.X962, serialization.PrivateFormat.PKCS8), - ] + ], ) def test_private_bytes_rejects_invalid(self, encoding, fmt, backend): parameters = FFDH3072_P.parameters(backend) @@ -467,35 +453,39 @@ def test_private_bytes_rejects_invalid(self, encoding, fmt, backend): serialization.load_pem_private_key, serialization.Encoding.PEM, False, - ), ( + ), + ( os.path.join("asymmetric", "DH", "dhkey.der"), serialization.load_der_private_key, serialization.Encoding.DER, False, - ), ( + ), + ( os.path.join("asymmetric", "DH", "dhkey_rfc5114_2.pem"), serialization.load_pem_private_key, serialization.Encoding.PEM, True, - ), ( + ), + ( os.path.join("asymmetric", "DH", "dhkey_rfc5114_2.der"), serialization.load_der_private_key, serialization.Encoding.DER, True, - ) - ] + ), + ], ) - def test_private_bytes_match(self, key_path, loader_func, - encoding, is_dhx, backend): + def test_private_bytes_match( + self, key_path, loader_func, encoding, is_dhx, backend + ): _skip_dhx_unsupported(backend, is_dhx) key_bytes = load_vectors_from_file( - key_path, - lambda pemfile: pemfile.read(), mode="rb" + key_path, lambda pemfile: pemfile.read(), mode="rb" ) key = loader_func(key_bytes, None, backend) serialized = key.private_bytes( - encoding, serialization.PrivateFormat.PKCS8, - serialization.NoEncryption() + encoding, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), ) assert serialized == key_bytes @@ -507,30 +497,33 @@ def test_private_bytes_match(self, key_path, loader_func, serialization.load_pem_private_key, os.path.join("asymmetric", "DH", "dhkey.txt"), False, - ), ( + ), + ( os.path.join("asymmetric", "DH", "dhkey.der"), serialization.load_der_private_key, os.path.join("asymmetric", "DH", "dhkey.txt"), False, - ), ( + ), + ( os.path.join("asymmetric", "DH", "dhkey_rfc5114_2.pem"), serialization.load_pem_private_key, os.path.join("asymmetric", "DH", "dhkey_rfc5114_2.txt"), True, - ), ( + ), + ( os.path.join("asymmetric", "DH", "dhkey_rfc5114_2.der"), serialization.load_der_private_key, os.path.join("asymmetric", "DH", "dhkey_rfc5114_2.txt"), True, - ) - ] + ), + ], ) - def test_private_bytes_values(self, key_path, loader_func, - vec_path, is_dhx, backend): + def test_private_bytes_values( + self, key_path, loader_func, vec_path, is_dhx, backend + ): _skip_dhx_unsupported(backend, is_dhx) key_bytes = load_vectors_from_file( - key_path, - lambda pemfile: pemfile.read(), mode="rb" + key_path, lambda pemfile: pemfile.read(), mode="rb" ) vec = load_vectors_from_file(vec_path, load_nist_vectors)[0] key = loader_func(key_bytes, None, backend) @@ -538,12 +531,15 @@ def test_private_bytes_values(self, key_path, loader_func, assert private_numbers.x == int(vec["x"], 16) assert private_numbers.public_numbers.y == int(vec["y"], 16) assert private_numbers.public_numbers.parameter_numbers.g == int( - vec["g"], 16) + vec["g"], 16 + ) assert private_numbers.public_numbers.parameter_numbers.p == int( - vec["p"], 16) + vec["p"], 16 + ) if "q" in vec: assert private_numbers.public_numbers.parameter_numbers.q == int( - vec["q"], 16) + vec["q"], 16 + ) else: assert private_numbers.public_numbers.parameter_numbers.q is None @@ -554,7 +550,7 @@ def test_private_bytes_traditional_openssl_invalid(self, backend): key.private_bytes( serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL, - serialization.NoEncryption() + serialization.NoEncryption(), ) def test_private_bytes_invalid_encoding(self, backend): @@ -564,7 +560,7 @@ def test_private_bytes_invalid_encoding(self, backend): key.private_bytes( "notencoding", serialization.PrivateFormat.PKCS8, - serialization.NoEncryption() + serialization.NoEncryption(), ) def test_private_bytes_invalid_format(self, backend): @@ -574,7 +570,7 @@ def test_private_bytes_invalid_format(self, backend): key.private_bytes( serialization.Encoding.PEM, "invalidformat", - serialization.NoEncryption() + serialization.NoEncryption(), ) def test_private_bytes_invalid_encryption_algorithm(self, backend): @@ -584,7 +580,7 @@ def test_private_bytes_invalid_encryption_algorithm(self, backend): key.private_bytes( serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, - "notanencalg" + "notanencalg", ) def test_private_bytes_unsupported_encryption_type(self, backend): @@ -594,7 +590,7 @@ def test_private_bytes_unsupported_encryption_type(self, backend): key.private_bytes( serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, - DummyKeySerializationEncryption() + DummyKeySerializationEncryption(), ) @@ -602,19 +598,12 @@ def test_private_bytes_unsupported_encryption_type(self, backend): @pytest.mark.requires_backend_interface(interface=PEMSerializationBackend) @pytest.mark.requires_backend_interface(interface=DERSerializationBackend) class TestDHPublicKeySerialization(object): - @pytest.mark.parametrize( ("encoding", "loader_func"), [ - [ - serialization.Encoding.PEM, - serialization.load_pem_public_key - ], - [ - serialization.Encoding.DER, - serialization.load_der_public_key - ], - ] + [serialization.Encoding.PEM, serialization.load_pem_public_key], + [serialization.Encoding.DER, serialization.load_der_public_key], + ], ) def test_public_bytes(self, backend, encoding, loader_func): parameters = FFDH3072_P.parameters(backend) @@ -635,35 +624,37 @@ def test_public_bytes(self, backend, encoding, loader_func): serialization.load_pem_public_key, serialization.Encoding.PEM, False, - ), ( + ), + ( os.path.join("asymmetric", "DH", "dhpub.der"), serialization.load_der_public_key, serialization.Encoding.DER, False, - ), ( + ), + ( os.path.join("asymmetric", "DH", "dhpub_rfc5114_2.pem"), serialization.load_pem_public_key, serialization.Encoding.PEM, True, - ), ( + ), + ( os.path.join("asymmetric", "DH", "dhpub_rfc5114_2.der"), serialization.load_der_public_key, serialization.Encoding.DER, True, - ) - ] + ), + ], ) - def test_public_bytes_match(self, key_path, loader_func, - encoding, is_dhx, backend): + def test_public_bytes_match( + self, key_path, loader_func, encoding, is_dhx, backend + ): _skip_dhx_unsupported(backend, is_dhx) key_bytes = load_vectors_from_file( - key_path, - lambda pemfile: pemfile.read(), mode="rb" + key_path, lambda pemfile: pemfile.read(), mode="rb" ) pub_key = loader_func(key_bytes, backend) serialized = pub_key.public_bytes( - encoding, - serialization.PublicFormat.SubjectPublicKeyInfo, + encoding, serialization.PublicFormat.SubjectPublicKeyInfo, ) assert serialized == key_bytes @@ -675,30 +666,33 @@ def test_public_bytes_match(self, key_path, loader_func, serialization.load_pem_public_key, os.path.join("asymmetric", "DH", "dhkey.txt"), False, - ), ( + ), + ( os.path.join("asymmetric", "DH", "dhpub.der"), serialization.load_der_public_key, os.path.join("asymmetric", "DH", "dhkey.txt"), False, - ), ( + ), + ( os.path.join("asymmetric", "DH", "dhpub_rfc5114_2.pem"), serialization.load_pem_public_key, os.path.join("asymmetric", "DH", "dhkey_rfc5114_2.txt"), True, - ), ( + ), + ( os.path.join("asymmetric", "DH", "dhpub_rfc5114_2.der"), serialization.load_der_public_key, os.path.join("asymmetric", "DH", "dhkey_rfc5114_2.txt"), True, - ) - ] + ), + ], ) - def test_public_bytes_values(self, key_path, loader_func, - vec_path, is_dhx, backend): + def test_public_bytes_values( + self, key_path, loader_func, vec_path, is_dhx, backend + ): _skip_dhx_unsupported(backend, is_dhx) key_bytes = load_vectors_from_file( - key_path, - lambda pemfile: pemfile.read(), mode="rb" + key_path, lambda pemfile: pemfile.read(), mode="rb" ) vec = load_vectors_from_file(vec_path, load_nist_vectors)[0] pub_key = loader_func(key_bytes, backend) @@ -716,8 +710,7 @@ def test_public_bytes_invalid_encoding(self, backend): key = parameters.generate_private_key().public_key() with pytest.raises(TypeError): key.public_bytes( - "notencoding", - serialization.PublicFormat.SubjectPublicKeyInfo + "notencoding", serialization.PublicFormat.SubjectPublicKeyInfo ) def test_public_bytes_pkcs1_unsupported(self, backend): @@ -733,19 +726,12 @@ def test_public_bytes_pkcs1_unsupported(self, backend): @pytest.mark.requires_backend_interface(interface=PEMSerializationBackend) @pytest.mark.requires_backend_interface(interface=DERSerializationBackend) class TestDHParameterSerialization(object): - @pytest.mark.parametrize( ("encoding", "loader_func"), [ - [ - serialization.Encoding.PEM, - serialization.load_pem_parameters - ], - [ - serialization.Encoding.DER, - serialization.load_der_parameters - ], - ] + [serialization.Encoding.PEM, serialization.load_pem_parameters], + [serialization.Encoding.DER, serialization.load_der_parameters], + ], ) def test_parameter_bytes(self, backend, encoding, loader_func): parameters = FFDH3072_P.parameters(backend) @@ -764,35 +750,37 @@ def test_parameter_bytes(self, backend, encoding, loader_func): serialization.load_pem_parameters, serialization.Encoding.PEM, False, - ), ( + ), + ( os.path.join("asymmetric", "DH", "dhp.der"), serialization.load_der_parameters, serialization.Encoding.DER, False, - ), ( + ), + ( os.path.join("asymmetric", "DH", "dhp_rfc5114_2.pem"), serialization.load_pem_parameters, serialization.Encoding.PEM, True, - ), ( + ), + ( os.path.join("asymmetric", "DH", "dhp_rfc5114_2.der"), serialization.load_der_parameters, serialization.Encoding.DER, True, - ) - ] + ), + ], ) - def test_parameter_bytes_match(self, param_path, loader_func, - encoding, backend, is_dhx): + def test_parameter_bytes_match( + self, param_path, loader_func, encoding, backend, is_dhx + ): _skip_dhx_unsupported(backend, is_dhx) param_bytes = load_vectors_from_file( - param_path, - lambda pemfile: pemfile.read(), mode="rb" + param_path, lambda pemfile: pemfile.read(), mode="rb" ) parameters = loader_func(param_bytes, backend) serialized = parameters.parameter_bytes( - encoding, - serialization.ParameterFormat.PKCS3, + encoding, serialization.ParameterFormat.PKCS3, ) assert serialized == param_bytes @@ -804,30 +792,33 @@ def test_parameter_bytes_match(self, param_path, loader_func, serialization.load_pem_parameters, os.path.join("asymmetric", "DH", "dhkey.txt"), False, - ), ( + ), + ( os.path.join("asymmetric", "DH", "dhp.der"), serialization.load_der_parameters, os.path.join("asymmetric", "DH", "dhkey.txt"), False, - ), ( + ), + ( os.path.join("asymmetric", "DH", "dhp_rfc5114_2.pem"), serialization.load_pem_parameters, os.path.join("asymmetric", "DH", "dhkey_rfc5114_2.txt"), True, - ), ( + ), + ( os.path.join("asymmetric", "DH", "dhp_rfc5114_2.der"), serialization.load_der_parameters, os.path.join("asymmetric", "DH", "dhkey_rfc5114_2.txt"), True, - ) - ] + ), + ], ) - def test_public_bytes_values(self, param_path, loader_func, - vec_path, backend, is_dhx): + def test_public_bytes_values( + self, param_path, loader_func, vec_path, backend, is_dhx + ): _skip_dhx_unsupported(backend, is_dhx) key_bytes = load_vectors_from_file( - param_path, - lambda pemfile: pemfile.read(), mode="rb" + param_path, lambda pemfile: pemfile.read(), mode="rb" ) vec = load_vectors_from_file(vec_path, load_nist_vectors)[0] parameters = loader_func(key_bytes, backend) @@ -844,22 +835,25 @@ def test_public_bytes_values(self, param_path, loader_func, [ ( serialization.Encoding.Raw, - serialization.PublicFormat.SubjectPublicKeyInfo + serialization.PublicFormat.SubjectPublicKeyInfo, ), (serialization.Encoding.Raw, serialization.PublicFormat.PKCS1), - ] + list(itertools.product( - [ - serialization.Encoding.Raw, - serialization.Encoding.X962, - serialization.Encoding.PEM, - serialization.Encoding.DER - ], - [ - serialization.PublicFormat.Raw, - serialization.PublicFormat.UncompressedPoint, - serialization.PublicFormat.CompressedPoint - ] - )) + ] + + list( + itertools.product( + [ + serialization.Encoding.Raw, + serialization.Encoding.X962, + serialization.Encoding.PEM, + serialization.Encoding.DER, + ], + [ + serialization.PublicFormat.Raw, + serialization.PublicFormat.UncompressedPoint, + serialization.PublicFormat.CompressedPoint, + ], + ) + ), ) def test_public_bytes_rejects_invalid(self, encoding, fmt, backend): parameters = FFDH3072_P.parameters(backend) @@ -871,22 +865,18 @@ def test_parameter_bytes_invalid_encoding(self, backend): parameters = FFDH3072_P.parameters(backend) with pytest.raises(TypeError): parameters.parameter_bytes( - "notencoding", - serialization.ParameterFormat.PKCS3 + "notencoding", serialization.ParameterFormat.PKCS3 ) def test_parameter_bytes_invalid_format(self, backend): parameters = FFDH3072_P.parameters(backend) with pytest.raises(ValueError): - parameters.parameter_bytes( - serialization.Encoding.PEM, - "notformat" - ) + parameters.parameter_bytes(serialization.Encoding.PEM, "notformat") def test_parameter_bytes_openssh_unsupported(self, backend): parameters = FFDH3072_P.parameters(backend) with pytest.raises(TypeError): parameters.parameter_bytes( serialization.Encoding.OpenSSH, - serialization.ParameterFormat.PKCS3 + serialization.ParameterFormat.PKCS3, ) diff --git a/tests/hazmat/primitives/test_dsa.py b/tests/hazmat/primitives/test_dsa.py index fd1aa6ea5f30..695069a32cfc 100644 --- a/tests/hazmat/primitives/test_dsa.py +++ b/tests/hazmat/primitives/test_dsa.py @@ -11,31 +11,31 @@ from cryptography.exceptions import AlreadyFinalized, InvalidSignature from cryptography.hazmat.backends.interfaces import ( - DSABackend, PEMSerializationBackend + DSABackend, + PEMSerializationBackend, ) from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import dsa from cryptography.hazmat.primitives.asymmetric.utils import ( - Prehashed, encode_dss_signature + Prehashed, + encode_dss_signature, ) from cryptography.utils import CryptographyDeprecationWarning -from .fixtures_dsa import ( - DSA_KEY_1024, DSA_KEY_2048, DSA_KEY_3072 -) +from .fixtures_dsa import DSA_KEY_1024, DSA_KEY_2048, DSA_KEY_3072 from .utils import skip_fips_traditional_openssl from ...doubles import DummyHashAlgorithm, DummyKeySerializationEncryption from ...utils import ( - load_fips_dsa_key_pair_vectors, load_fips_dsa_sig_vectors, + load_fips_dsa_key_pair_vectors, + load_fips_dsa_sig_vectors, load_vectors_from_file, ) def _skip_if_dsa_not_supported(backend, algorithm, p, q, g): - if ( - not backend.dsa_parameters_supported(p, q, g) or - not backend.dsa_hash_supported(algorithm) - ): + if not backend.dsa_parameters_supported( + p, q, g + ) or not backend.dsa_hash_supported(algorithm): pytest.skip( "{} does not support the provided parameters".format(backend) ) @@ -60,21 +60,18 @@ def test_generate_invalid_dsa_parameters(self, backend): @pytest.mark.parametrize( "vector", load_vectors_from_file( - os.path.join( - "asymmetric", "DSA", "FIPS_186-3", "KeyPair.rsp"), - load_fips_dsa_key_pair_vectors - ) + os.path.join("asymmetric", "DSA", "FIPS_186-3", "KeyPair.rsp"), + load_fips_dsa_key_pair_vectors, + ), ) def test_generate_dsa_keys(self, vector, backend): if ( - backend._fips_enabled and - vector['p'] < backend._fips_dsa_min_modulus + backend._fips_enabled + and vector["p"] < backend._fips_dsa_min_modulus ): pytest.skip("Small modulus blocked in FIPS mode") parameters = dsa.DSAParameterNumbers( - p=vector['p'], - q=vector['q'], - g=vector['g'] + p=vector["p"], q=vector["q"], g=vector["g"] ).parameters(backend) skey = parameters.generate_private_key() numbers = skey.private_numbers() @@ -85,10 +82,10 @@ def test_generate_dsa_keys(self, vector, backend): assert parameter_numbers.p == skey_parameters.p assert parameter_numbers.q == skey_parameters.q assert parameter_numbers.g == skey_parameters.g - assert skey_parameters.p == vector['p'] - assert skey_parameters.q == vector['q'] - assert skey_parameters.g == vector['g'] - assert skey.key_size == vector['p'].bit_length() + assert skey_parameters.p == vector["p"] + assert skey_parameters.q == vector["q"] + assert skey_parameters.g == vector["g"] + assert skey.key_size == vector["p"].bit_length() assert pkey.key_size == skey.key_size public_numbers = pkey.public_numbers() assert numbers.public_numbers.y == public_numbers.y @@ -136,7 +133,7 @@ def test_generate_dsa_private_key_and_parameters(self, backend): ( DSA_KEY_2048.public_numbers.parameter_numbers.p, 2 ** 250, - DSA_KEY_2048.public_numbers.parameter_numbers.g + DSA_KEY_2048.public_numbers.parameter_numbers.g, ), ( DSA_KEY_3072.public_numbers.parameter_numbers.p, @@ -146,19 +143,19 @@ def test_generate_dsa_private_key_and_parameters(self, backend): ( DSA_KEY_1024.public_numbers.parameter_numbers.p, DSA_KEY_1024.public_numbers.parameter_numbers.q, - 0 + 0, ), ( DSA_KEY_1024.public_numbers.parameter_numbers.p, DSA_KEY_1024.public_numbers.parameter_numbers.q, - 1 + 1, ), ( DSA_KEY_1024.public_numbers.parameter_numbers.p, DSA_KEY_1024.public_numbers.parameter_numbers.q, - 2 ** 1200 + 2 ** 1200, ), - ] + ], ) def test_invalid_parameters_values(self, p, q, g, backend): with pytest.raises(ValueError): @@ -270,17 +267,18 @@ def test_invalid_parameters_values(self, p, q, g, backend): DSA_KEY_1024.public_numbers.parameter_numbers.q, DSA_KEY_1024.public_numbers.parameter_numbers.g, 2 ** 100, - DSA_KEY_1024.x + DSA_KEY_1024.x, ), - ] + ], ) def test_invalid_dsa_private_key_arguments(self, p, q, g, y, x, backend): with pytest.raises(ValueError): dsa.DSAPrivateNumbers( public_numbers=dsa.DSAPublicNumbers( parameter_numbers=dsa.DSAParameterNumbers(p=p, q=q, g=g), - y=y - ), x=x + y=y, + ), + x=x, ).private_key(backend) @pytest.mark.parametrize( @@ -346,13 +344,12 @@ def test_invalid_dsa_private_key_arguments(self, p, q, g, y, x, backend): 2 ** 1200, DSA_KEY_1024.public_numbers.y, ), - ] + ], ) def test_invalid_dsa_public_key_arguments(self, p, q, g, y, backend): with pytest.raises(ValueError): dsa.DSAPublicNumbers( - parameter_numbers=dsa.DSAParameterNumbers(p=p, q=q, g=g), - y=y + parameter_numbers=dsa.DSAParameterNumbers(p=p, q=q, g=g), y=y ).public_key(backend) def test_large_p(self, backend): @@ -360,7 +357,8 @@ def test_large_p(self, backend): os.path.join("asymmetric", "PEM_Serialization", "dsa_4096.pem"), lambda pemfile: serialization.load_pem_private_key( pemfile.read(), None, backend - ), mode="rb" + ), + mode="rb", ) pn = key.private_numbers() assert pn.public_numbers.parameter_numbers.p.bit_length() == 4096 @@ -373,67 +371,68 @@ def test_large_p(self, backend): q=pn.public_numbers.parameter_numbers.q, g=pn.public_numbers.parameter_numbers.g, ), - y=pn.public_numbers.y - ), x=pn.x + y=pn.public_numbers.y, + ), + x=pn.x, ).private_key(backend) @pytest.mark.requires_backend_interface(interface=DSABackend) class TestDSAVerification(object): _algorithms_dict = { - 'SHA1': hashes.SHA1, - 'SHA224': hashes.SHA224, - 'SHA256': hashes.SHA256, - 'SHA384': hashes.SHA384, - 'SHA512': hashes.SHA512 + "SHA1": hashes.SHA1, + "SHA224": hashes.SHA224, + "SHA256": hashes.SHA256, + "SHA384": hashes.SHA384, + "SHA512": hashes.SHA512, } @pytest.mark.parametrize( "vector", load_vectors_from_file( - os.path.join( - "asymmetric", "DSA", "FIPS_186-3", "SigVer.rsp"), - load_fips_dsa_sig_vectors - ) + os.path.join("asymmetric", "DSA", "FIPS_186-3", "SigVer.rsp"), + load_fips_dsa_sig_vectors, + ), ) def test_dsa_verification(self, vector, backend): - digest_algorithm = vector['digest_algorithm'].replace("-", "") + digest_algorithm = vector["digest_algorithm"].replace("-", "") algorithm = self._algorithms_dict[digest_algorithm] _skip_if_dsa_not_supported( - backend, algorithm, vector['p'], vector['q'], vector['g'] + backend, algorithm, vector["p"], vector["q"], vector["g"] ) public_key = dsa.DSAPublicNumbers( parameter_numbers=dsa.DSAParameterNumbers( - vector['p'], vector['q'], vector['g'] + vector["p"], vector["q"], vector["g"] ), - y=vector['y'] + y=vector["y"], ).public_key(backend) - sig = encode_dss_signature(vector['r'], vector['s']) + sig = encode_dss_signature(vector["r"], vector["s"]) - if vector['result'] == "F": + if vector["result"] == "F": with pytest.raises(InvalidSignature): - public_key.verify(sig, vector['msg'], algorithm()) + public_key.verify(sig, vector["msg"], algorithm()) else: - public_key.verify(sig, vector['msg'], algorithm()) + public_key.verify(sig, vector["msg"], algorithm()) def test_dsa_verify_invalid_asn1(self, backend): public_key = DSA_KEY_1024.public_numbers.public_key(backend) with pytest.raises(InvalidSignature): - public_key.verify(b'fakesig', b'fakemsg', hashes.SHA1()) + public_key.verify(b"fakesig", b"fakemsg", hashes.SHA1()) def test_signature_not_bytes(self, backend): public_key = DSA_KEY_1024.public_numbers.public_key(backend) - with pytest.raises(TypeError), \ - pytest.warns(CryptographyDeprecationWarning): + with pytest.raises(TypeError), pytest.warns( + CryptographyDeprecationWarning + ): public_key.verifier(1234, hashes.SHA1()) def test_use_after_finalize(self, backend): public_key = DSA_KEY_1024.public_numbers.public_key(backend) with pytest.warns(CryptographyDeprecationWarning): - verifier = public_key.verifier(b'fakesig', hashes.SHA1()) - verifier.update(b'irrelevant') + verifier = public_key.verifier(b"fakesig", hashes.SHA1()) + verifier.update(b"irrelevant") with pytest.raises(InvalidSignature): verifier.verify() with pytest.raises(AlreadyFinalized): @@ -473,57 +472,57 @@ def test_prehashed_digest_mismatch(self, backend): def test_prehashed_unsupported_in_signer_ctx(self, backend): private_key = DSA_KEY_1024.private_key(backend) - with pytest.raises(TypeError), \ - pytest.warns(CryptographyDeprecationWarning): + with pytest.raises(TypeError), pytest.warns( + CryptographyDeprecationWarning + ): private_key.signer(Prehashed(hashes.SHA1())) def test_prehashed_unsupported_in_verifier_ctx(self, backend): public_key = DSA_KEY_1024.private_key(backend).public_key() - with pytest.raises(TypeError), \ - pytest.warns(CryptographyDeprecationWarning): - public_key.verifier( - b"0" * 64, Prehashed(hashes.SHA1()) - ) + with pytest.raises(TypeError), pytest.warns( + CryptographyDeprecationWarning + ): + public_key.verifier(b"0" * 64, Prehashed(hashes.SHA1())) @pytest.mark.requires_backend_interface(interface=DSABackend) class TestDSASignature(object): _algorithms_dict = { - 'SHA1': hashes.SHA1, - 'SHA224': hashes.SHA224, - 'SHA256': hashes.SHA256, - 'SHA384': hashes.SHA384, - 'SHA512': hashes.SHA512} + "SHA1": hashes.SHA1, + "SHA224": hashes.SHA224, + "SHA256": hashes.SHA256, + "SHA384": hashes.SHA384, + "SHA512": hashes.SHA512, + } @pytest.mark.parametrize( "vector", load_vectors_from_file( - os.path.join( - "asymmetric", "DSA", "FIPS_186-3", "SigGen.txt"), - load_fips_dsa_sig_vectors - ) + os.path.join("asymmetric", "DSA", "FIPS_186-3", "SigGen.txt"), + load_fips_dsa_sig_vectors, + ), ) def test_dsa_signing(self, vector, backend): - digest_algorithm = vector['digest_algorithm'].replace("-", "") + digest_algorithm = vector["digest_algorithm"].replace("-", "") algorithm = self._algorithms_dict[digest_algorithm] _skip_if_dsa_not_supported( - backend, algorithm, vector['p'], vector['q'], vector['g'] + backend, algorithm, vector["p"], vector["q"], vector["g"] ) private_key = dsa.DSAPrivateNumbers( public_numbers=dsa.DSAPublicNumbers( parameter_numbers=dsa.DSAParameterNumbers( - vector['p'], vector['q'], vector['g'] + vector["p"], vector["q"], vector["g"] ), - y=vector['y'] + y=vector["y"], ), - x=vector['x'] + x=vector["x"], ).private_key(backend) - signature = private_key.sign(vector['msg'], algorithm()) + signature = private_key.sign(vector["msg"], algorithm()) assert signature - private_key.public_key().verify(signature, vector['msg'], algorithm()) + private_key.public_key().verify(signature, vector["msg"], algorithm()) def test_use_after_finalize(self, backend): private_key = DSA_KEY_1024.private_key(backend) @@ -586,8 +585,7 @@ def test_dsa_parameter_numbers_invalid_types(self): def test_dsa_public_numbers(self): parameter_numbers = dsa.DSAParameterNumbers(p=1, q=2, g=3) public_numbers = dsa.DSAPublicNumbers( - y=4, - parameter_numbers=parameter_numbers + y=4, parameter_numbers=parameter_numbers ) assert public_numbers.y == 4 assert public_numbers.parameter_numbers == parameter_numbers @@ -603,12 +601,10 @@ def test_dsa_public_numbers_invalid_types(self): def test_dsa_private_numbers(self): parameter_numbers = dsa.DSAParameterNumbers(p=1, q=2, g=3) public_numbers = dsa.DSAPublicNumbers( - y=4, - parameter_numbers=parameter_numbers + y=4, parameter_numbers=parameter_numbers ) private_numbers = dsa.DSAPrivateNumbers( - x=5, - public_numbers=public_numbers + x=5, public_numbers=public_numbers ) assert private_numbers.x == 5 assert private_numbers.public_numbers == public_numbers @@ -616,8 +612,7 @@ def test_dsa_private_numbers(self): def test_dsa_private_numbers_invalid_types(self): parameter_numbers = dsa.DSAParameterNumbers(p=1, q=2, g=3) public_numbers = dsa.DSAPublicNumbers( - y=4, - parameter_numbers=parameter_numbers + y=4, parameter_numbers=parameter_numbers ) with pytest.raises(TypeError): dsa.DSAPrivateNumbers(x=4, public_numbers=None) @@ -632,8 +627,7 @@ def test_repr(self): ) public_numbers = dsa.DSAPublicNumbers( - y=4, - parameter_numbers=parameter_numbers + y=4, parameter_numbers=parameter_numbers ) assert repr(public_numbers) == ( " the group order. It should be diff --git a/tests/hazmat/primitives/test_hash_vectors.py b/tests/hazmat/primitives/test_hash_vectors.py index 0698f4134fc8..9301b6217101 100644 --- a/tests/hazmat/primitives/test_hash_vectors.py +++ b/tests/hazmat/primitives/test_hash_vectors.py @@ -25,10 +25,7 @@ class TestSHA1(object): test_sha1 = generate_hash_test( load_hash_vectors, os.path.join("hashes", "SHA1"), - [ - "SHA1LongMsg.rsp", - "SHA1ShortMsg.rsp", - ], + ["SHA1LongMsg.rsp", "SHA1ShortMsg.rsp"], hashes.SHA1(), ) @@ -42,10 +39,7 @@ class TestSHA224(object): test_sha224 = generate_hash_test( load_hash_vectors, os.path.join("hashes", "SHA2"), - [ - "SHA224LongMsg.rsp", - "SHA224ShortMsg.rsp", - ], + ["SHA224LongMsg.rsp", "SHA224ShortMsg.rsp"], hashes.SHA224(), ) @@ -59,10 +53,7 @@ class TestSHA256(object): test_sha256 = generate_hash_test( load_hash_vectors, os.path.join("hashes", "SHA2"), - [ - "SHA256LongMsg.rsp", - "SHA256ShortMsg.rsp", - ], + ["SHA256LongMsg.rsp", "SHA256ShortMsg.rsp"], hashes.SHA256(), ) @@ -76,10 +67,7 @@ class TestSHA384(object): test_sha384 = generate_hash_test( load_hash_vectors, os.path.join("hashes", "SHA2"), - [ - "SHA384LongMsg.rsp", - "SHA384ShortMsg.rsp", - ], + ["SHA384LongMsg.rsp", "SHA384ShortMsg.rsp"], hashes.SHA384(), ) @@ -93,10 +81,7 @@ class TestSHA512(object): test_sha512 = generate_hash_test( load_hash_vectors, os.path.join("hashes", "SHA2"), - [ - "SHA512LongMsg.rsp", - "SHA512ShortMsg.rsp", - ], + ["SHA512LongMsg.rsp", "SHA512ShortMsg.rsp"], hashes.SHA512(), ) @@ -110,10 +95,7 @@ class TestSHA512224(object): test_sha512_224 = generate_hash_test( load_hash_vectors, os.path.join("hashes", "SHA2"), - [ - "SHA512_224LongMsg.rsp", - "SHA512_224ShortMsg.rsp", - ], + ["SHA512_224LongMsg.rsp", "SHA512_224ShortMsg.rsp"], hashes.SHA512_224(), ) @@ -127,10 +109,7 @@ class TestSHA512256(object): test_sha512_256 = generate_hash_test( load_hash_vectors, os.path.join("hashes", "SHA2"), - [ - "SHA512_256LongMsg.rsp", - "SHA512_256ShortMsg.rsp", - ], + ["SHA512_256LongMsg.rsp", "SHA512_256ShortMsg.rsp"], hashes.SHA512_256(), ) @@ -144,16 +123,15 @@ class TestMD5(object): test_md5 = generate_hash_test( load_hash_vectors, os.path.join("hashes", "MD5"), - [ - "rfc-1321.txt", - ], + ["rfc-1321.txt"], hashes.MD5(), ) @pytest.mark.supported( only_if=lambda backend: backend.hash_supported( - hashes.BLAKE2b(digest_size=64)), + hashes.BLAKE2b(digest_size=64) + ), skip_message="Does not support BLAKE2b", ) @pytest.mark.requires_backend_interface(interface=HashBackend) @@ -161,16 +139,15 @@ class TestBLAKE2b(object): test_b2b = generate_hash_test( load_hash_vectors, os.path.join("hashes", "blake2"), - [ - "blake2b.txt", - ], + ["blake2b.txt"], hashes.BLAKE2b(digest_size=64), ) @pytest.mark.supported( only_if=lambda backend: backend.hash_supported( - hashes.BLAKE2s(digest_size=32)), + hashes.BLAKE2s(digest_size=32) + ), skip_message="Does not support BLAKE2s", ) @pytest.mark.requires_backend_interface(interface=HashBackend) @@ -178,9 +155,7 @@ class TestBLAKE2s256(object): test_b2s = generate_hash_test( load_hash_vectors, os.path.join("hashes", "blake2"), - [ - "blake2s.txt", - ], + ["blake2s.txt"], hashes.BLAKE2s(digest_size=32), ) @@ -194,10 +169,7 @@ class TestSHA3224(object): test_sha3_224 = generate_hash_test( load_hash_vectors, os.path.join("hashes", "SHA3"), - [ - "SHA3_224LongMsg.rsp", - "SHA3_224ShortMsg.rsp", - ], + ["SHA3_224LongMsg.rsp", "SHA3_224ShortMsg.rsp"], hashes.SHA3_224(), ) @@ -211,10 +183,7 @@ class TestSHA3256(object): test_sha3_256 = generate_hash_test( load_hash_vectors, os.path.join("hashes", "SHA3"), - [ - "SHA3_256LongMsg.rsp", - "SHA3_256ShortMsg.rsp", - ], + ["SHA3_256LongMsg.rsp", "SHA3_256ShortMsg.rsp"], hashes.SHA3_256(), ) @@ -228,10 +197,7 @@ class TestSHA3384(object): test_sha3_384 = generate_hash_test( load_hash_vectors, os.path.join("hashes", "SHA3"), - [ - "SHA3_384LongMsg.rsp", - "SHA3_384ShortMsg.rsp", - ], + ["SHA3_384LongMsg.rsp", "SHA3_384ShortMsg.rsp"], hashes.SHA3_384(), ) @@ -245,17 +211,15 @@ class TestSHA3512(object): test_sha3_512 = generate_hash_test( load_hash_vectors, os.path.join("hashes", "SHA3"), - [ - "SHA3_512LongMsg.rsp", - "SHA3_512ShortMsg.rsp", - ], + ["SHA3_512LongMsg.rsp", "SHA3_512ShortMsg.rsp"], hashes.SHA3_512(), ) @pytest.mark.supported( only_if=lambda backend: backend.hash_supported( - hashes.SHAKE128(digest_size=16)), + hashes.SHAKE128(digest_size=16) + ), skip_message="Does not support SHAKE128", ) @pytest.mark.requires_backend_interface(interface=HashBackend) @@ -263,10 +227,7 @@ class TestSHAKE128(object): test_shake128 = generate_hash_test( load_hash_vectors, os.path.join("hashes", "SHAKE"), - [ - "SHAKE128LongMsg.rsp", - "SHAKE128ShortMsg.rsp", - ], + ["SHAKE128LongMsg.rsp", "SHAKE128ShortMsg.rsp"], hashes.SHAKE128(digest_size=16), ) @@ -274,24 +235,23 @@ class TestSHAKE128(object): "vector", _load_all_params( os.path.join("hashes", "SHAKE"), - [ - "SHAKE128VariableOut.rsp", - ], + ["SHAKE128VariableOut.rsp"], load_nist_vectors, - ) + ), ) def test_shake128_variable(self, vector, backend): - output_length = int(vector['outputlen']) // 8 - msg = binascii.unhexlify(vector['msg']) + output_length = int(vector["outputlen"]) // 8 + msg = binascii.unhexlify(vector["msg"]) shake = hashes.SHAKE128(digest_size=output_length) m = hashes.Hash(shake, backend=backend) m.update(msg) - assert m.finalize() == binascii.unhexlify(vector['output']) + assert m.finalize() == binascii.unhexlify(vector["output"]) @pytest.mark.supported( only_if=lambda backend: backend.hash_supported( - hashes.SHAKE256(digest_size=32)), + hashes.SHAKE256(digest_size=32) + ), skip_message="Does not support SHAKE256", ) @pytest.mark.requires_backend_interface(interface=HashBackend) @@ -299,10 +259,7 @@ class TestSHAKE256(object): test_shake256 = generate_hash_test( load_hash_vectors, os.path.join("hashes", "SHAKE"), - [ - "SHAKE256LongMsg.rsp", - "SHAKE256ShortMsg.rsp", - ], + ["SHAKE256LongMsg.rsp", "SHAKE256ShortMsg.rsp"], hashes.SHAKE256(digest_size=32), ) @@ -310,16 +267,14 @@ class TestSHAKE256(object): "vector", _load_all_params( os.path.join("hashes", "SHAKE"), - [ - "SHAKE256VariableOut.rsp", - ], + ["SHAKE256VariableOut.rsp"], load_nist_vectors, - ) + ), ) def test_shake256_variable(self, vector, backend): - output_length = int(vector['outputlen']) // 8 - msg = binascii.unhexlify(vector['msg']) + output_length = int(vector["outputlen"]) // 8 + msg = binascii.unhexlify(vector["msg"]) shake = hashes.SHAKE256(digest_size=output_length) m = hashes.Hash(shake, backend=backend) m.update(msg) - assert m.finalize() == binascii.unhexlify(vector['output']) + assert m.finalize() == binascii.unhexlify(vector["output"]) diff --git a/tests/hazmat/primitives/test_hashes.py b/tests/hazmat/primitives/test_hashes.py index a743045cb9be..25676921208e 100644 --- a/tests/hazmat/primitives/test_hashes.py +++ b/tests/hazmat/primitives/test_hashes.py @@ -52,10 +52,7 @@ def test_unsupported_hash(self, backend): ) @pytest.mark.requires_backend_interface(interface=HashBackend) class TestSHA1(object): - test_sha1 = generate_base_hash_test( - hashes.SHA1(), - digest_size=20, - ) + test_sha1 = generate_base_hash_test(hashes.SHA1(), digest_size=20,) @pytest.mark.supported( @@ -64,10 +61,7 @@ class TestSHA1(object): ) @pytest.mark.requires_backend_interface(interface=HashBackend) class TestSHA224(object): - test_sha224 = generate_base_hash_test( - hashes.SHA224(), - digest_size=28, - ) + test_sha224 = generate_base_hash_test(hashes.SHA224(), digest_size=28,) @pytest.mark.supported( @@ -76,10 +70,7 @@ class TestSHA224(object): ) @pytest.mark.requires_backend_interface(interface=HashBackend) class TestSHA256(object): - test_sha256 = generate_base_hash_test( - hashes.SHA256(), - digest_size=32, - ) + test_sha256 = generate_base_hash_test(hashes.SHA256(), digest_size=32,) @pytest.mark.supported( @@ -88,10 +79,7 @@ class TestSHA256(object): ) @pytest.mark.requires_backend_interface(interface=HashBackend) class TestSHA384(object): - test_sha384 = generate_base_hash_test( - hashes.SHA384(), - digest_size=48, - ) + test_sha384 = generate_base_hash_test(hashes.SHA384(), digest_size=48,) @pytest.mark.supported( @@ -100,10 +88,7 @@ class TestSHA384(object): ) @pytest.mark.requires_backend_interface(interface=HashBackend) class TestSHA512(object): - test_sha512 = generate_base_hash_test( - hashes.SHA512(), - digest_size=64, - ) + test_sha512 = generate_base_hash_test(hashes.SHA512(), digest_size=64,) @pytest.mark.supported( @@ -112,22 +97,19 @@ class TestSHA512(object): ) @pytest.mark.requires_backend_interface(interface=HashBackend) class TestMD5(object): - test_md5 = generate_base_hash_test( - hashes.MD5(), - digest_size=16, - ) + test_md5 = generate_base_hash_test(hashes.MD5(), digest_size=16,) @pytest.mark.supported( only_if=lambda backend: backend.hash_supported( - hashes.BLAKE2b(digest_size=64)), + hashes.BLAKE2b(digest_size=64) + ), skip_message="Does not support BLAKE2b", ) @pytest.mark.requires_backend_interface(interface=HashBackend) class TestBLAKE2b(object): test_blake2b = generate_base_hash_test( - hashes.BLAKE2b(digest_size=64), - digest_size=64, + hashes.BLAKE2b(digest_size=64), digest_size=64, ) def test_invalid_digest_size(self, backend): @@ -143,14 +125,14 @@ def test_invalid_digest_size(self, backend): @pytest.mark.supported( only_if=lambda backend: backend.hash_supported( - hashes.BLAKE2s(digest_size=32)), + hashes.BLAKE2s(digest_size=32) + ), skip_message="Does not support BLAKE2s", ) @pytest.mark.requires_backend_interface(interface=HashBackend) class TestBLAKE2s(object): test_blake2s = generate_base_hash_test( - hashes.BLAKE2s(digest_size=32), - digest_size=32, + hashes.BLAKE2s(digest_size=32), digest_size=32, ) def test_invalid_digest_size(self, backend): @@ -182,18 +164,12 @@ def test_buffer_protocol_hash(backend): class TestSHAKE(object): - @pytest.mark.parametrize( - "xof", - [hashes.SHAKE128, hashes.SHAKE256] - ) + @pytest.mark.parametrize("xof", [hashes.SHAKE128, hashes.SHAKE256]) def test_invalid_digest_type(self, xof): with pytest.raises(TypeError): xof(digest_size=object()) - @pytest.mark.parametrize( - "xof", - [hashes.SHAKE128, hashes.SHAKE256] - ) + @pytest.mark.parametrize("xof", [hashes.SHAKE128, hashes.SHAKE256]) def test_invalid_digest_size(self, xof): with pytest.raises(ValueError): xof(digest_size=-5) diff --git a/tests/hazmat/primitives/test_hkdf.py b/tests/hazmat/primitives/test_hkdf.py index 195bfb3a4f71..1d7de6c472ee 100644 --- a/tests/hazmat/primitives/test_hkdf.py +++ b/tests/hazmat/primitives/test_hkdf.py @@ -9,15 +9,15 @@ import pytest -from cryptography.exceptions import ( - AlreadyFinalized, InvalidKey, _Reasons -) +from cryptography.exceptions import AlreadyFinalized, InvalidKey, _Reasons from cryptography.hazmat.backends.interfaces import HMACBackend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.hkdf import HKDF, HKDFExpand from ...utils import ( - load_nist_vectors, load_vectors_from_file, raises_unsupported_algorithm + load_nist_vectors, + load_vectors_from_file, + raises_unsupported_algorithm, ) @@ -32,127 +32,67 @@ def test_length_limit(self, backend): big_length, salt=None, info=None, - backend=backend + backend=backend, ) def test_already_finalized(self, backend): - hkdf = HKDF( - hashes.SHA256(), - 16, - salt=None, - info=None, - backend=backend - ) + hkdf = HKDF(hashes.SHA256(), 16, salt=None, info=None, backend=backend) hkdf.derive(b"\x01" * 16) with pytest.raises(AlreadyFinalized): hkdf.derive(b"\x02" * 16) - hkdf = HKDF( - hashes.SHA256(), - 16, - salt=None, - info=None, - backend=backend - ) + hkdf = HKDF(hashes.SHA256(), 16, salt=None, info=None, backend=backend) hkdf.verify(b"\x01" * 16, b"gJ\xfb{\xb1Oi\xc5sMC\xb7\xe4@\xf7u") with pytest.raises(AlreadyFinalized): hkdf.verify(b"\x02" * 16, b"gJ\xfb{\xb1Oi\xc5sMC\xb7\xe4@\xf7u") - hkdf = HKDF( - hashes.SHA256(), - 16, - salt=None, - info=None, - backend=backend - ) + hkdf = HKDF(hashes.SHA256(), 16, salt=None, info=None, backend=backend) def test_verify(self, backend): - hkdf = HKDF( - hashes.SHA256(), - 16, - salt=None, - info=None, - backend=backend - ) + hkdf = HKDF(hashes.SHA256(), 16, salt=None, info=None, backend=backend) hkdf.verify(b"\x01" * 16, b"gJ\xfb{\xb1Oi\xc5sMC\xb7\xe4@\xf7u") def test_verify_invalid(self, backend): - hkdf = HKDF( - hashes.SHA256(), - 16, - salt=None, - info=None, - backend=backend - ) + hkdf = HKDF(hashes.SHA256(), 16, salt=None, info=None, backend=backend) with pytest.raises(InvalidKey): hkdf.verify(b"\x02" * 16, b"gJ\xfb{\xb1Oi\xc5sMC\xb7\xe4@\xf7u") def test_unicode_typeerror(self, backend): with pytest.raises(TypeError): - HKDF( - hashes.SHA256(), - 16, - salt=u"foo", - info=None, - backend=backend - ) + HKDF(hashes.SHA256(), 16, salt=u"foo", info=None, backend=backend) with pytest.raises(TypeError): - HKDF( - hashes.SHA256(), - 16, - salt=None, - info=u"foo", - backend=backend - ) + HKDF(hashes.SHA256(), 16, salt=None, info=u"foo", backend=backend) with pytest.raises(TypeError): hkdf = HKDF( - hashes.SHA256(), - 16, - salt=None, - info=None, - backend=backend + hashes.SHA256(), 16, salt=None, info=None, backend=backend ) hkdf.derive(u"foo") with pytest.raises(TypeError): hkdf = HKDF( - hashes.SHA256(), - 16, - salt=None, - info=None, - backend=backend + hashes.SHA256(), 16, salt=None, info=None, backend=backend ) hkdf.verify(u"foo", b"bar") with pytest.raises(TypeError): hkdf = HKDF( - hashes.SHA256(), - 16, - salt=None, - info=None, - backend=backend + hashes.SHA256(), 16, salt=None, info=None, backend=backend ) hkdf.verify(b"foo", u"bar") def test_derive_short_output(self, backend): - hkdf = HKDF( - hashes.SHA256(), - 4, - salt=None, - info=None, - backend=backend - ) + hkdf = HKDF(hashes.SHA256(), 4, salt=None, info=None, backend=backend) assert hkdf.derive(b"\x01" * 16) == b"gJ\xfb{" @@ -165,7 +105,7 @@ def test_derive_long_output(self, backend): int(vector["l"]), salt=vector["salt"], info=vector["info"], - backend=backend + backend=backend, ) ikm = binascii.unhexlify(vector["ikm"]) @@ -180,7 +120,7 @@ def test_buffer_protocol(self, backend): int(vector["l"]), salt=vector["salt"], info=vector["info"], - backend=backend + backend=backend, ) ikm = bytearray(binascii.unhexlify(vector["ikm"])) @@ -194,8 +134,10 @@ def test_derive(self, backend): b"077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5" ) - okm = (b"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c" - b"5bf34007208d5b887185865") + okm = ( + b"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c" + b"5bf34007208d5b887185865" + ) info = binascii.unhexlify(b"f0f1f2f3f4f5f6f7f8f9") hkdf = HKDFExpand(hashes.SHA256(), 42, info, backend) @@ -203,12 +145,17 @@ def test_derive(self, backend): assert binascii.hexlify(hkdf.derive(prk)) == okm def test_buffer_protocol(self, backend): - prk = bytearray(binascii.unhexlify( - b"077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5" - )) + prk = bytearray( + binascii.unhexlify( + b"077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2" + b"b3e5" + ) + ) - okm = (b"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c" - b"5bf34007208d5b887185865") + okm = ( + b"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c" + b"5bf34007208d5b887185865" + ) info = binascii.unhexlify(b"f0f1f2f3f4f5f6f7f8f9") hkdf = HKDFExpand(hashes.SHA256(), 42, info, backend) @@ -220,8 +167,10 @@ def test_verify(self, backend): b"077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5" ) - okm = (b"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c" - b"5bf34007208d5b887185865") + okm = ( + b"3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c" + b"5bf34007208d5b887185865" + ) info = binascii.unhexlify(b"f0f1f2f3f4f5f6f7f8f9") hkdf = HKDFExpand(hashes.SHA256(), 42, info, backend) diff --git a/tests/hazmat/primitives/test_hkdf_vectors.py b/tests/hazmat/primitives/test_hkdf_vectors.py index 290cefbf6c28..97385e203c19 100644 --- a/tests/hazmat/primitives/test_hkdf_vectors.py +++ b/tests/hazmat/primitives/test_hkdf_vectors.py @@ -17,7 +17,7 @@ @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.SHA1()), - skip_message="Does not support SHA1." + skip_message="Does not support SHA1.", ) @pytest.mark.requires_backend_interface(interface=HMACBackend) class TestHKDFSHA1(object): @@ -25,13 +25,13 @@ class TestHKDFSHA1(object): load_nist_vectors, os.path.join("KDF"), ["rfc-5869-HKDF-SHA1.txt"], - hashes.SHA1() + hashes.SHA1(), ) @pytest.mark.supported( only_if=lambda backend: backend.hmac_supported(hashes.SHA256()), - skip_message="Does not support SHA256." + skip_message="Does not support SHA256.", ) @pytest.mark.requires_backend_interface(interface=HMACBackend) class TestHKDFSHA256(object): @@ -39,5 +39,5 @@ class TestHKDFSHA256(object): load_nist_vectors, os.path.join("KDF"), ["rfc-5869-HKDF-SHA256.txt"], - hashes.SHA256() + hashes.SHA256(), ) diff --git a/tests/hazmat/primitives/test_hmac.py b/tests/hazmat/primitives/test_hmac.py index 0e2fe688ac82..e60ae16f21b2 100644 --- a/tests/hazmat/primitives/test_hmac.py +++ b/tests/hazmat/primitives/test_hmac.py @@ -9,7 +9,9 @@ import pytest from cryptography.exceptions import ( - AlreadyFinalized, InvalidSignature, _Reasons + AlreadyFinalized, + InvalidSignature, + _Reasons, ) from cryptography.hazmat.backends.interfaces import HMACBackend from cryptography.hazmat.primitives import hashes, hmac @@ -25,9 +27,7 @@ ) @pytest.mark.requires_backend_interface(interface=HMACBackend) class TestHMACCopy(object): - test_copy = generate_base_hmac_test( - hashes.MD5(), - ) + test_copy = generate_base_hmac_test(hashes.MD5(),) @pytest.mark.requires_backend_interface(interface=HMACBackend) @@ -55,27 +55,27 @@ def test_raises_after_finalize(self, backend): h.finalize() def test_verify(self, backend): - h = hmac.HMAC(b'', hashes.SHA1(), backend=backend) + h = hmac.HMAC(b"", hashes.SHA1(), backend=backend) digest = h.finalize() - h = hmac.HMAC(b'', hashes.SHA1(), backend=backend) + h = hmac.HMAC(b"", hashes.SHA1(), backend=backend) h.verify(digest) with pytest.raises(AlreadyFinalized): - h.verify(b'') + h.verify(b"") def test_invalid_verify(self, backend): - h = hmac.HMAC(b'', hashes.SHA1(), backend=backend) + h = hmac.HMAC(b"", hashes.SHA1(), backend=backend) with pytest.raises(InvalidSignature): - h.verify(b'') + h.verify(b"") with pytest.raises(AlreadyFinalized): - h.verify(b'') + h.verify(b"") def test_verify_reject_unicode(self, backend): - h = hmac.HMAC(b'', hashes.SHA1(), backend=backend) + h = hmac.HMAC(b"", hashes.SHA1(), backend=backend) with pytest.raises(TypeError): - h.verify(u'') + h.verify(u"") def test_unsupported_hash(self, backend): with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_HASH): diff --git a/tests/hazmat/primitives/test_hmac_vectors.py b/tests/hazmat/primitives/test_hmac_vectors.py index 6ff71fe38508..b463427366bb 100644 --- a/tests/hazmat/primitives/test_hmac_vectors.py +++ b/tests/hazmat/primitives/test_hmac_vectors.py @@ -22,12 +22,7 @@ @pytest.mark.requires_backend_interface(interface=HMACBackend) class TestHMACMD5(object): test_hmac_md5 = generate_hmac_test( - load_hash_vectors, - "HMAC", - [ - "rfc-2202-md5.txt", - ], - hashes.MD5(), + load_hash_vectors, "HMAC", ["rfc-2202-md5.txt"], hashes.MD5(), ) @@ -38,12 +33,7 @@ class TestHMACMD5(object): @pytest.mark.requires_backend_interface(interface=HMACBackend) class TestHMACSHA1(object): test_hmac_sha1 = generate_hmac_test( - load_hash_vectors, - "HMAC", - [ - "rfc-2202-sha1.txt", - ], - hashes.SHA1(), + load_hash_vectors, "HMAC", ["rfc-2202-sha1.txt"], hashes.SHA1(), ) @@ -54,12 +44,7 @@ class TestHMACSHA1(object): @pytest.mark.requires_backend_interface(interface=HMACBackend) class TestHMACSHA224(object): test_hmac_sha224 = generate_hmac_test( - load_hash_vectors, - "HMAC", - [ - "rfc-4231-sha224.txt", - ], - hashes.SHA224(), + load_hash_vectors, "HMAC", ["rfc-4231-sha224.txt"], hashes.SHA224(), ) @@ -70,12 +55,7 @@ class TestHMACSHA224(object): @pytest.mark.requires_backend_interface(interface=HMACBackend) class TestHMACSHA256(object): test_hmac_sha256 = generate_hmac_test( - load_hash_vectors, - "HMAC", - [ - "rfc-4231-sha256.txt", - ], - hashes.SHA256(), + load_hash_vectors, "HMAC", ["rfc-4231-sha256.txt"], hashes.SHA256(), ) @@ -86,12 +66,7 @@ class TestHMACSHA256(object): @pytest.mark.requires_backend_interface(interface=HMACBackend) class TestHMACSHA384(object): test_hmac_sha384 = generate_hmac_test( - load_hash_vectors, - "HMAC", - [ - "rfc-4231-sha384.txt", - ], - hashes.SHA384(), + load_hash_vectors, "HMAC", ["rfc-4231-sha384.txt"], hashes.SHA384(), ) @@ -102,19 +77,14 @@ class TestHMACSHA384(object): @pytest.mark.requires_backend_interface(interface=HMACBackend) class TestHMACSHA512(object): test_hmac_sha512 = generate_hmac_test( - load_hash_vectors, - "HMAC", - [ - "rfc-4231-sha512.txt", - ], - hashes.SHA512(), + load_hash_vectors, "HMAC", ["rfc-4231-sha512.txt"], hashes.SHA512(), ) @pytest.mark.supported( - only_if=lambda backend: backend.hmac_supported(hashes.BLAKE2b( - digest_size=64 - )), + only_if=lambda backend: backend.hmac_supported( + hashes.BLAKE2b(digest_size=64) + ), skip_message="Does not support BLAKE2", ) @pytest.mark.requires_backend_interface(interface=HMACBackend) diff --git a/tests/hazmat/primitives/test_idea.py b/tests/hazmat/primitives/test_idea.py index 6b8a2a870e27..1f766def082a 100644 --- a/tests/hazmat/primitives/test_idea.py +++ b/tests/hazmat/primitives/test_idea.py @@ -46,7 +46,7 @@ class TestIDEAModeCBC(object): os.path.join("ciphers", "IDEA"), ["idea-cbc.txt"], lambda key, **kwargs: algorithms.IDEA(binascii.unhexlify((key))), - lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv)) + lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv)), ) @@ -63,7 +63,7 @@ class TestIDEAModeOFB(object): os.path.join("ciphers", "IDEA"), ["idea-ofb.txt"], lambda key, **kwargs: algorithms.IDEA(binascii.unhexlify((key))), - lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv)) + lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv)), ) @@ -80,5 +80,5 @@ class TestIDEAModeCFB(object): os.path.join("ciphers", "IDEA"), ["idea-cfb.txt"], lambda key, **kwargs: algorithms.IDEA(binascii.unhexlify((key))), - lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)) + lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)), ) diff --git a/tests/hazmat/primitives/test_kbkdf.py b/tests/hazmat/primitives/test_kbkdf.py index a16f1768dd50..5ff5d74ea871 100644 --- a/tests/hazmat/primitives/test_kbkdf.py +++ b/tests/hazmat/primitives/test_kbkdf.py @@ -6,13 +6,13 @@ import pytest -from cryptography.exceptions import ( - AlreadyFinalized, InvalidKey, _Reasons -) +from cryptography.exceptions import AlreadyFinalized, InvalidKey, _Reasons from cryptography.hazmat.backends.interfaces import HMACBackend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.kbkdf import ( - CounterLocation, KBKDFHMAC, Mode + CounterLocation, + KBKDFHMAC, + Mode, ) from ...doubles import DummyHashAlgorithm @@ -22,137 +22,316 @@ @pytest.mark.requires_backend_interface(interface=HMACBackend) class TestKBKDFHMAC(object): def test_invalid_key(self, backend): - kdf = KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 4, 4, - CounterLocation.BeforeFixed, b'label', b'context', - None, backend=backend) + kdf = KBKDFHMAC( + hashes.SHA256(), + Mode.CounterMode, + 32, + 4, + 4, + CounterLocation.BeforeFixed, + b"label", + b"context", + None, + backend=backend, + ) key = kdf.derive(b"material") - kdf = KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 4, 4, - CounterLocation.BeforeFixed, b'label', b'context', - None, backend=backend) + kdf = KBKDFHMAC( + hashes.SHA256(), + Mode.CounterMode, + 32, + 4, + 4, + CounterLocation.BeforeFixed, + b"label", + b"context", + None, + backend=backend, + ) with pytest.raises(InvalidKey): kdf.verify(b"material2", key) def test_already_finalized(self, backend): - kdf = KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 4, 4, - CounterLocation.BeforeFixed, b'label', b'context', - None, backend=backend) - - kdf.derive(b'material') + kdf = KBKDFHMAC( + hashes.SHA256(), + Mode.CounterMode, + 32, + 4, + 4, + CounterLocation.BeforeFixed, + b"label", + b"context", + None, + backend=backend, + ) + + kdf.derive(b"material") with pytest.raises(AlreadyFinalized): - kdf.derive(b'material2') - - kdf = KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 4, 4, - CounterLocation.BeforeFixed, b'label', b'context', - None, backend=backend) + kdf.derive(b"material2") + + kdf = KBKDFHMAC( + hashes.SHA256(), + Mode.CounterMode, + 32, + 4, + 4, + CounterLocation.BeforeFixed, + b"label", + b"context", + None, + backend=backend, + ) - key = kdf.derive(b'material') + key = kdf.derive(b"material") with pytest.raises(AlreadyFinalized): - kdf.verify(b'material', key) + kdf.verify(b"material", key) - kdf = KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 4, 4, - CounterLocation.BeforeFixed, b'label', b'context', - None, backend=backend) - kdf.verify(b'material', key) + kdf = KBKDFHMAC( + hashes.SHA256(), + Mode.CounterMode, + 32, + 4, + 4, + CounterLocation.BeforeFixed, + b"label", + b"context", + None, + backend=backend, + ) + kdf.verify(b"material", key) with pytest.raises(AlreadyFinalized): kdf.verify(b"material", key) def test_key_length(self, backend): - kdf = KBKDFHMAC(hashes.SHA1(), Mode.CounterMode, 85899345920, 4, 4, - CounterLocation.BeforeFixed, b'label', b'context', - None, backend=backend) + kdf = KBKDFHMAC( + hashes.SHA1(), + Mode.CounterMode, + 85899345920, + 4, + 4, + CounterLocation.BeforeFixed, + b"label", + b"context", + None, + backend=backend, + ) with pytest.raises(ValueError): - kdf.derive(b'material') + kdf.derive(b"material") def test_rlen(self, backend): with pytest.raises(ValueError): - KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 5, 4, - CounterLocation.BeforeFixed, b'label', b'context', - None, backend=backend) + KBKDFHMAC( + hashes.SHA256(), + Mode.CounterMode, + 32, + 5, + 4, + CounterLocation.BeforeFixed, + b"label", + b"context", + None, + backend=backend, + ) def test_r_type(self, backend): with pytest.raises(TypeError): - KBKDFHMAC(hashes.SHA1(), Mode.CounterMode, 32, b'r', 4, - CounterLocation.BeforeFixed, b'label', b'context', - None, backend=backend) + KBKDFHMAC( + hashes.SHA1(), + Mode.CounterMode, + 32, + b"r", + 4, + CounterLocation.BeforeFixed, + b"label", + b"context", + None, + backend=backend, + ) def test_l_type(self, backend): with pytest.raises(TypeError): - KBKDFHMAC(hashes.SHA1(), Mode.CounterMode, 32, 4, b'l', - CounterLocation.BeforeFixed, b'label', b'context', - None, backend=backend) + KBKDFHMAC( + hashes.SHA1(), + Mode.CounterMode, + 32, + 4, + b"l", + CounterLocation.BeforeFixed, + b"label", + b"context", + None, + backend=backend, + ) def test_l(self, backend): with pytest.raises(ValueError): - KBKDFHMAC(hashes.SHA1(), Mode.CounterMode, 32, 4, None, - CounterLocation.BeforeFixed, b'label', b'context', - None, backend=backend) + KBKDFHMAC( + hashes.SHA1(), + Mode.CounterMode, + 32, + 4, + None, + CounterLocation.BeforeFixed, + b"label", + b"context", + None, + backend=backend, + ) def test_unsupported_mode(self, backend): with pytest.raises(TypeError): - KBKDFHMAC(hashes.SHA256(), None, 32, 4, 4, - CounterLocation.BeforeFixed, b'label', b'context', - None, backend=backend) + KBKDFHMAC( + hashes.SHA256(), + None, + 32, + 4, + 4, + CounterLocation.BeforeFixed, + b"label", + b"context", + None, + backend=backend, + ) def test_unsupported_location(self, backend): with pytest.raises(TypeError): - KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 4, 4, - None, b'label', b'context', None, - backend=backend) + KBKDFHMAC( + hashes.SHA256(), + Mode.CounterMode, + 32, + 4, + 4, + None, + b"label", + b"context", + None, + backend=backend, + ) def test_unsupported_parameters(self, backend): with pytest.raises(ValueError): - KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 4, 4, - CounterLocation.BeforeFixed, b'label', b'context', - b'fixed', backend=backend) + KBKDFHMAC( + hashes.SHA256(), + Mode.CounterMode, + 32, + 4, + 4, + CounterLocation.BeforeFixed, + b"label", + b"context", + b"fixed", + backend=backend, + ) def test_unsupported_hash(self, backend): with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_HASH): - KBKDFHMAC(object(), Mode.CounterMode, 32, 4, 4, - CounterLocation.BeforeFixed, b'label', b'context', - None, backend=backend) + KBKDFHMAC( + object(), + Mode.CounterMode, + 32, + 4, + 4, + CounterLocation.BeforeFixed, + b"label", + b"context", + None, + backend=backend, + ) def test_unsupported_algorithm(self, backend): with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_HASH): - KBKDFHMAC(DummyHashAlgorithm(), Mode.CounterMode, 32, 4, 4, - CounterLocation.BeforeFixed, b'label', b'context', - None, backend=backend) + KBKDFHMAC( + DummyHashAlgorithm(), + Mode.CounterMode, + 32, + 4, + 4, + CounterLocation.BeforeFixed, + b"label", + b"context", + None, + backend=backend, + ) def test_invalid_backend(self, backend): with raises_unsupported_algorithm(_Reasons.BACKEND_MISSING_INTERFACE): - KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 4, 4, - CounterLocation.BeforeFixed, b'label', b'context', - None, backend=object()) + KBKDFHMAC( + hashes.SHA256(), + Mode.CounterMode, + 32, + 4, + 4, + CounterLocation.BeforeFixed, + b"label", + b"context", + None, + backend=object(), + ) def test_unicode_error_label(self, backend): with pytest.raises(TypeError): - KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 4, 4, - CounterLocation.BeforeFixed, u'label', b'context', - backend=backend) + KBKDFHMAC( + hashes.SHA256(), + Mode.CounterMode, + 32, + 4, + 4, + CounterLocation.BeforeFixed, + u"label", + b"context", + backend=backend, + ) def test_unicode_error_context(self, backend): with pytest.raises(TypeError): - KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 4, 4, - CounterLocation.BeforeFixed, b'label', u'context', - None, backend=backend) + KBKDFHMAC( + hashes.SHA256(), + Mode.CounterMode, + 32, + 4, + 4, + CounterLocation.BeforeFixed, + b"label", + u"context", + None, + backend=backend, + ) def test_unicode_error_key_material(self, backend): with pytest.raises(TypeError): - kdf = KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 32, 4, 4, - CounterLocation.BeforeFixed, b'label', - b'context', None, backend=backend) - kdf.derive(u'material') + kdf = KBKDFHMAC( + hashes.SHA256(), + Mode.CounterMode, + 32, + 4, + 4, + CounterLocation.BeforeFixed, + b"label", + b"context", + None, + backend=backend, + ) + kdf.derive(u"material") def test_buffer_protocol(self, backend): - kdf = KBKDFHMAC(hashes.SHA256(), Mode.CounterMode, 10, 4, 4, - CounterLocation.BeforeFixed, b'label', b'context', - None, backend=backend) + kdf = KBKDFHMAC( + hashes.SHA256(), + Mode.CounterMode, + 10, + 4, + 4, + CounterLocation.BeforeFixed, + b"label", + b"context", + None, + backend=backend, + ) key = kdf.derive(bytearray(b"material")) - assert key == b'\xb7\x01\x05\x98\xf5\x1a\x12L\xc7.' + assert key == b"\xb7\x01\x05\x98\xf5\x1a\x12L\xc7." diff --git a/tests/hazmat/primitives/test_kbkdf_vectors.py b/tests/hazmat/primitives/test_kbkdf_vectors.py index 7bdbbdc765d4..462e04ec5a87 100644 --- a/tests/hazmat/primitives/test_kbkdf_vectors.py +++ b/tests/hazmat/primitives/test_kbkdf_vectors.py @@ -19,5 +19,5 @@ class TestCounterKDFCounterMode(object): test_kbkdfctr = generate_kbkdf_counter_mode_test( load_nist_kbkdf_vectors, os.path.join("KDF"), - ["nist-800-108-KBKDF-CTR.txt"] + ["nist-800-108-KBKDF-CTR.txt"], ) diff --git a/tests/hazmat/primitives/test_keywrap.py b/tests/hazmat/primitives/test_keywrap.py index c74b144b66fc..9b91ccf36b33 100644 --- a/tests/hazmat/primitives/test_keywrap.py +++ b/tests/hazmat/primitives/test_keywrap.py @@ -24,15 +24,15 @@ class TestAESKeyWrap(object): _load_all_params( os.path.join("keywrap", "kwtestvectors"), ["KW_AE_128.txt", "KW_AE_192.txt", "KW_AE_256.txt"], - load_nist_vectors - ) + load_nist_vectors, + ), ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.AES(b"\x00" * 16), modes.ECB() ), skip_message="Does not support AES key wrap (RFC 3394) because AES-ECB" - " is unsupported", + " is unsupported", ) def test_wrap(self, backend, params): wrapping_key = binascii.unhexlify(params["k"]) @@ -45,15 +45,15 @@ def test_wrap(self, backend, params): _load_all_params( os.path.join("keywrap", "kwtestvectors"), ["KW_AD_128.txt", "KW_AD_192.txt", "KW_AD_256.txt"], - load_nist_vectors - ) + load_nist_vectors, + ), ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported( algorithms.AES(b"\x00" * 16), modes.ECB() ), skip_message="Does not support AES key wrap (RFC 3394) because AES-ECB" - " is unsupported", + " is unsupported", ) def test_unwrap(self, backend, params): wrapping_key = binascii.unhexlify(params["k"]) @@ -72,7 +72,7 @@ def test_unwrap(self, backend, params): algorithms.AES(b"\x00" * 16), modes.ECB() ), skip_message="Does not support AES key wrap (RFC 3394) because AES-ECB" - " is unsupported", + " is unsupported", ) def test_wrap_invalid_key_length(self, backend): # The wrapping key must be of length [16, 24, 32] @@ -84,7 +84,7 @@ def test_wrap_invalid_key_length(self, backend): algorithms.AES(b"\x00" * 16), modes.ECB() ), skip_message="Does not support AES key wrap (RFC 3394) because AES-ECB" - " is unsupported", + " is unsupported", ) def test_unwrap_invalid_key_length(self, backend): with pytest.raises(ValueError): @@ -95,7 +95,7 @@ def test_unwrap_invalid_key_length(self, backend): algorithms.AES(b"\x00" * 16), modes.ECB() ), skip_message="Does not support AES key wrap (RFC 3394) because AES-ECB" - " is unsupported", + " is unsupported", ) def test_wrap_invalid_key_to_wrap_length(self, backend): # Keys to wrap must be at least 16 bytes long @@ -121,7 +121,7 @@ def test_unwrap_invalid_wrapped_key_length(self, backend): algorithms.AES(b"\x00" * 16), modes.ECB() ), skip_message="Does not support AES key wrap (RFC 5649) because AES-ECB" - " is unsupported", + " is unsupported", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) class TestAESKeyWrapWithPadding(object): @@ -130,8 +130,8 @@ class TestAESKeyWrapWithPadding(object): _load_all_params( os.path.join("keywrap", "kwtestvectors"), ["KWP_AE_128.txt", "KWP_AE_192.txt", "KWP_AE_256.txt"], - load_nist_vectors - ) + load_nist_vectors, + ), ) def test_wrap(self, backend, params): wrapping_key = binascii.unhexlify(params["k"]) @@ -143,7 +143,7 @@ def test_wrap(self, backend, params): @pytest.mark.parametrize( "params", - _load_all_params("keywrap", ["kwp_botan.txt"], load_nist_vectors) + _load_all_params("keywrap", ["kwp_botan.txt"], load_nist_vectors), ) def test_wrap_additional_vectors(self, backend, params): wrapping_key = binascii.unhexlify(params["key"]) @@ -158,8 +158,8 @@ def test_wrap_additional_vectors(self, backend, params): _load_all_params( os.path.join("keywrap", "kwtestvectors"), ["KWP_AD_128.txt", "KWP_AD_192.txt", "KWP_AD_256.txt"], - load_nist_vectors - ) + load_nist_vectors, + ), ) def test_unwrap(self, backend, params): wrapping_key = binascii.unhexlify(params["k"]) @@ -177,7 +177,7 @@ def test_unwrap(self, backend, params): @pytest.mark.parametrize( "params", - _load_all_params("keywrap", ["kwp_botan.txt"], load_nist_vectors) + _load_all_params("keywrap", ["kwp_botan.txt"], load_nist_vectors), ) def test_unwrap_additional_vectors(self, backend, params): wrapping_key = binascii.unhexlify(params["key"]) @@ -190,18 +190,18 @@ def test_unwrap_additional_vectors(self, backend, params): def test_unwrap_invalid_wrapped_key_length(self, backend): # Keys to unwrap must be at least 16 bytes with pytest.raises( - keywrap.InvalidUnwrap, match='Must be at least 16 bytes' + keywrap.InvalidUnwrap, match="Must be at least 16 bytes" ): keywrap.aes_key_unwrap_with_padding( b"sixteen_byte_key", b"\x00" * 15, backend ) def test_wrap_invalid_key_length(self, backend): - with pytest.raises(ValueError, match='must be a valid AES key length'): + with pytest.raises(ValueError, match="must be a valid AES key length"): keywrap.aes_key_wrap_with_padding(b"badkey", b"\x00", backend) def test_unwrap_invalid_key_length(self, backend): - with pytest.raises(ValueError, match='must be a valid AES key length'): + with pytest.raises(ValueError, match="must be a valid AES key length"): keywrap.aes_key_unwrap_with_padding( b"badkey", b"\x00" * 16, backend ) diff --git a/tests/hazmat/primitives/test_padding.py b/tests/hazmat/primitives/test_padding.py index fb72a794b5ee..f66d0ee8521d 100644 --- a/tests/hazmat/primitives/test_padding.py +++ b/tests/hazmat/primitives/test_padding.py @@ -18,14 +18,17 @@ def test_invalid_block_size(self, size): with pytest.raises(ValueError): padding.PKCS7(size) - @pytest.mark.parametrize(("size", "padded"), [ - (128, b"1111"), - (128, b"1111111111111111"), - (128, b"111111111111111\x06"), - (128, b""), - (128, b"\x06" * 6), - (128, b"\x00" * 16), - ]) + @pytest.mark.parametrize( + ("size", "padded"), + [ + (128, b"1111"), + (128, b"1111111111111111"), + (128, b"111111111111111\x06"), + (128, b""), + (128, b"\x06" * 6), + (128, b"\x00" * 16), + ], + ) def test_invalid_padding(self, size, padded): unpadder = padding.PKCS7(size).unpadder() with pytest.raises(ValueError): @@ -40,46 +43,36 @@ def test_non_bytes(self): with pytest.raises(TypeError): unpadder.update(u"abc") - @pytest.mark.parametrize(("size", "unpadded", "padded"), [ - ( - 128, - b"1111111111", - b"1111111111\x06\x06\x06\x06\x06\x06", - ), - ( - 128, - b"111111111111111122222222222222", - b"111111111111111122222222222222\x02\x02", - ), - ( - 128, - b"1" * 16, - b"1" * 16 + b"\x10" * 16, - ), - ( - 128, - b"1" * 17, - b"1" * 17 + b"\x0F" * 15, - ) - ]) + @pytest.mark.parametrize( + ("size", "unpadded", "padded"), + [ + (128, b"1111111111", b"1111111111\x06\x06\x06\x06\x06\x06"), + ( + 128, + b"111111111111111122222222222222", + b"111111111111111122222222222222\x02\x02", + ), + (128, b"1" * 16, b"1" * 16 + b"\x10" * 16), + (128, b"1" * 17, b"1" * 17 + b"\x0F" * 15), + ], + ) def test_pad(self, size, unpadded, padded): padder = padding.PKCS7(size).padder() result = padder.update(unpadded) result += padder.finalize() assert result == padded - @pytest.mark.parametrize(("size", "unpadded", "padded"), [ - ( - 128, - b"1111111111", - b"1111111111\x06\x06\x06\x06\x06\x06", - ), - ( - 128, - b"111111111111111122222222222222", - b"111111111111111122222222222222\x02\x02", - ), - ]) + @pytest.mark.parametrize( + ("size", "unpadded", "padded"), + [ + (128, b"1111111111", b"1111111111\x06\x06\x06\x06\x06\x06"), + ( + 128, + b"111111111111111122222222222222", + b"111111111111111122222222222222\x02\x02", + ), + ], + ) def test_unpad(self, size, unpadded, padded): unpadder = padding.PKCS7(size).unpadder() result = unpadder.update(padded) @@ -123,15 +116,18 @@ def test_invalid_block_size(self, size): with pytest.raises(ValueError): padding.ANSIX923(size) - @pytest.mark.parametrize(("size", "padded"), [ - (128, b"1111"), - (128, b"1111111111111111"), - (128, b"111111111111111\x06"), - (128, b"1111111111\x06\x06\x06\x06\x06\x06"), - (128, b""), - (128, b"\x06" * 6), - (128, b"\x00" * 16), - ]) + @pytest.mark.parametrize( + ("size", "padded"), + [ + (128, b"1111"), + (128, b"1111111111111111"), + (128, b"111111111111111\x06"), + (128, b"1111111111\x06\x06\x06\x06\x06\x06"), + (128, b""), + (128, b"\x06" * 6), + (128, b"\x00" * 16), + ], + ) def test_invalid_padding(self, size, padded): unpadder = padding.ANSIX923(size).unpadder() with pytest.raises(ValueError): @@ -146,46 +142,36 @@ def test_non_bytes(self): with pytest.raises(TypeError): unpadder.update(u"abc") - @pytest.mark.parametrize(("size", "unpadded", "padded"), [ - ( - 128, - b"1111111111", - b"1111111111\x00\x00\x00\x00\x00\x06", - ), - ( - 128, - b"111111111111111122222222222222", - b"111111111111111122222222222222\x00\x02", - ), - ( - 128, - b"1" * 16, - b"1" * 16 + b"\x00" * 15 + b"\x10", - ), - ( - 128, - b"1" * 17, - b"1" * 17 + b"\x00" * 14 + b"\x0F", - ) - ]) + @pytest.mark.parametrize( + ("size", "unpadded", "padded"), + [ + (128, b"1111111111", b"1111111111\x00\x00\x00\x00\x00\x06"), + ( + 128, + b"111111111111111122222222222222", + b"111111111111111122222222222222\x00\x02", + ), + (128, b"1" * 16, b"1" * 16 + b"\x00" * 15 + b"\x10"), + (128, b"1" * 17, b"1" * 17 + b"\x00" * 14 + b"\x0F"), + ], + ) def test_pad(self, size, unpadded, padded): padder = padding.ANSIX923(size).padder() result = padder.update(unpadded) result += padder.finalize() assert result == padded - @pytest.mark.parametrize(("size", "unpadded", "padded"), [ - ( - 128, - b"1111111111", - b"1111111111\x00\x00\x00\x00\x00\x06", - ), - ( - 128, - b"111111111111111122222222222222", - b"111111111111111122222222222222\x00\x02", - ), - ]) + @pytest.mark.parametrize( + ("size", "unpadded", "padded"), + [ + (128, b"1111111111", b"1111111111\x00\x00\x00\x00\x00\x06"), + ( + 128, + b"111111111111111122222222222222", + b"111111111111111122222222222222\x00\x02", + ), + ], + ) def test_unpad(self, size, unpadded, padded): unpadder = padding.ANSIX923(size).unpadder() result = unpadder.update(padded) diff --git a/tests/hazmat/primitives/test_pbkdf2hmac.py b/tests/hazmat/primitives/test_pbkdf2hmac.py index 0254b2168313..584655fe879c 100644 --- a/tests/hazmat/primitives/test_pbkdf2hmac.py +++ b/tests/hazmat/primitives/test_pbkdf2hmac.py @@ -6,9 +6,7 @@ import pytest -from cryptography.exceptions import ( - AlreadyFinalized, InvalidKey, _Reasons -) +from cryptography.exceptions import AlreadyFinalized, InvalidKey, _Reasons from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC diff --git a/tests/hazmat/primitives/test_pbkdf2hmac_vectors.py b/tests/hazmat/primitives/test_pbkdf2hmac_vectors.py index fe51f543804a..13bdbc5f3554 100644 --- a/tests/hazmat/primitives/test_pbkdf2hmac_vectors.py +++ b/tests/hazmat/primitives/test_pbkdf2hmac_vectors.py @@ -20,10 +20,5 @@ @pytest.mark.requires_backend_interface(interface=PBKDF2HMACBackend) class TestPBKDF2HMACSHA1(object): test_pbkdf2_sha1 = generate_pbkdf2_test( - load_nist_vectors, - "KDF", - [ - "rfc-6070-PBKDF2-SHA1.txt", - ], - hashes.SHA1(), + load_nist_vectors, "KDF", ["rfc-6070-PBKDF2-SHA1.txt"], hashes.SHA1(), ) diff --git a/tests/hazmat/primitives/test_pkcs12.py b/tests/hazmat/primitives/test_pkcs12.py index 61c5342394f9..466dac5c14b2 100644 --- a/tests/hazmat/primitives/test_pkcs12.py +++ b/tests/hazmat/primitives/test_pkcs12.py @@ -14,7 +14,8 @@ from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.serialization import load_pem_private_key from cryptography.hazmat.primitives.serialization.pkcs12 import ( - load_key_and_certificates, serialize_key_and_certificates + load_key_and_certificates, + serialize_key_and_certificates, ) from .utils import load_vectors_from_file @@ -28,19 +29,22 @@ def _test_load_pkcs12_ec_keys(self, filename, password, backend): os.path.join("x509", "custom", "ca", "ca.pem"), lambda pemfile: x509.load_pem_x509_certificate( pemfile.read(), backend - ), mode="rb" + ), + mode="rb", ) key = load_vectors_from_file( os.path.join("x509", "custom", "ca", "ca_key.pem"), lambda pemfile: load_pem_private_key( pemfile.read(), None, backend - ), mode="rb" + ), + mode="rb", ) parsed_key, parsed_cert, parsed_more_certs = load_vectors_from_file( os.path.join("pkcs12", filename), lambda derfile: load_key_and_certificates( derfile.read(), password, backend - ), mode="rb" + ), + mode="rb", ) assert parsed_cert == cert assert parsed_key.private_numbers() == key.private_numbers() @@ -51,7 +55,7 @@ def _test_load_pkcs12_ec_keys(self, filename, password, backend): [ ("cert-key-aes256cbc.p12", b"cryptography"), ("cert-none-key-none.p12", b"cryptography"), - ] + ], ) def test_load_pkcs12_ec_keys(self, filename, password, backend): self._test_load_pkcs12_ec_keys(filename, password, backend) @@ -61,11 +65,11 @@ def test_load_pkcs12_ec_keys(self, filename, password, backend): [ ("cert-rc2-key-3des.p12", b"cryptography"), ("no-password.p12", None), - ] + ], ) @pytest.mark.supported( only_if=lambda backend: backend.cipher_supported(_RC2(), None), - skip_message="Does not support RC2" + skip_message="Does not support RC2", ) @pytest.mark.skip_fips(reason="Unsupported algorithm in FIPS mode") def test_load_pkcs12_ec_keys_rc2(self, filename, password, backend): @@ -76,14 +80,15 @@ def test_load_pkcs12_cert_only(self, backend): os.path.join("x509", "custom", "ca", "ca.pem"), lambda pemfile: x509.load_pem_x509_certificate( pemfile.read(), backend - ), mode="rb" + ), + mode="rb", ) parsed_key, parsed_cert, parsed_more_certs = load_vectors_from_file( os.path.join("pkcs12", "cert-aes256cbc-no-key.p12"), lambda data: load_key_and_certificates( data.read(), b"cryptography", backend ), - mode="rb" + mode="rb", ) assert parsed_cert is None assert parsed_key is None @@ -94,14 +99,15 @@ def test_load_pkcs12_key_only(self, backend): os.path.join("x509", "custom", "ca", "ca_key.pem"), lambda pemfile: load_pem_private_key( pemfile.read(), None, backend - ), mode="rb" + ), + mode="rb", ) parsed_key, parsed_cert, parsed_more_certs = load_vectors_from_file( os.path.join("pkcs12", "no-cert-key-aes256cbc.p12"), lambda data: load_key_and_certificates( data.read(), b"cryptography", backend ), - mode="rb" + mode="rb", ) assert parsed_key.private_numbers() == key.private_numbers() assert parsed_cert is None @@ -109,15 +115,11 @@ def test_load_pkcs12_key_only(self, backend): def test_non_bytes(self, backend): with pytest.raises(TypeError): - load_key_and_certificates( - b"irrelevant", object(), backend - ) + load_key_and_certificates(b"irrelevant", object(), backend) def test_not_a_pkcs12(self, backend): with pytest.raises(ValueError): - load_key_and_certificates( - b"invalid", b"pass", backend - ) + load_key_and_certificates(b"invalid", b"pass", backend) def test_invalid_password(self, backend): with pytest.raises(ValueError): @@ -125,13 +127,15 @@ def test_invalid_password(self, backend): os.path.join("pkcs12", "cert-key-aes256cbc.p12"), lambda derfile: load_key_and_certificates( derfile.read(), b"invalid", backend - ), mode="rb" + ), + mode="rb", ) def test_buffer_protocol(self, backend): p12 = load_vectors_from_file( os.path.join("pkcs12", "cert-key-aes256cbc.p12"), - lambda derfile: derfile.read(), mode="rb" + lambda derfile: derfile.read(), + mode="rb", ) p12buffer = bytearray(p12) parsed_key, parsed_cert, parsed_more_certs = load_key_and_certificates( @@ -147,34 +151,39 @@ def _load_cert(backend, path): path, lambda pemfile: x509.load_pem_x509_certificate( pemfile.read(), backend - ), mode='rb' + ), + mode="rb", ) def _load_ca(backend): - cert = _load_cert(backend, os.path.join('x509', 'custom', 'ca', 'ca.pem')) + cert = _load_cert(backend, os.path.join("x509", "custom", "ca", "ca.pem")) key = load_vectors_from_file( - os.path.join('x509', 'custom', 'ca', 'ca_key.pem'), - lambda pemfile: load_pem_private_key( - pemfile.read(), None, backend - ), mode='rb' + os.path.join("x509", "custom", "ca", "ca_key.pem"), + lambda pemfile: load_pem_private_key(pemfile.read(), None, backend), + mode="rb", ) return cert, key class TestPKCS12Creation(object): - @pytest.mark.parametrize('name', [None, b'name']) - @pytest.mark.parametrize(('encryption_algorithm', 'password'), [ - (serialization.BestAvailableEncryption(b'password'), b'password'), - (serialization.NoEncryption(), None) - ]) + @pytest.mark.parametrize("name", [None, b"name"]) + @pytest.mark.parametrize( + ("encryption_algorithm", "password"), + [ + (serialization.BestAvailableEncryption(b"password"), b"password"), + (serialization.NoEncryption(), None), + ], + ) def test_generate(self, backend, name, encryption_algorithm, password): cert, key = _load_ca(backend) p12 = serialize_key_and_certificates( - name, key, cert, None, encryption_algorithm) + name, key, cert, None, encryption_algorithm + ) - parsed_key, parsed_cert, parsed_more_certs = \ - load_key_and_certificates(p12, password, backend) + parsed_key, parsed_cert, parsed_more_certs = load_key_and_certificates( + p12, password, backend + ) assert parsed_cert == cert assert parsed_key.private_numbers() == key.private_numbers() assert parsed_more_certs == [] @@ -182,53 +191,60 @@ def test_generate(self, backend, name, encryption_algorithm, password): def test_generate_with_cert_key_ca(self, backend): cert, key = _load_ca(backend) cert2 = _load_cert( - backend, os.path.join('x509', 'custom', 'dsa_selfsigned_ca.pem') + backend, os.path.join("x509", "custom", "dsa_selfsigned_ca.pem") ) - cert3 = _load_cert(backend, os.path.join('x509', 'letsencryptx3.pem')) + cert3 = _load_cert(backend, os.path.join("x509", "letsencryptx3.pem")) encryption = serialization.NoEncryption() p12 = serialize_key_and_certificates( - None, key, cert, [cert2, cert3], encryption) + None, key, cert, [cert2, cert3], encryption + ) - parsed_key, parsed_cert, parsed_more_certs = \ - load_key_and_certificates(p12, None, backend) + parsed_key, parsed_cert, parsed_more_certs = load_key_and_certificates( + p12, None, backend + ) assert parsed_cert == cert assert parsed_key.private_numbers() == key.private_numbers() assert parsed_more_certs == [cert2, cert3] def test_generate_wrong_types(self, backend): cert, key = _load_ca(backend) - cert2 = _load_cert(backend, os.path.join('x509', 'letsencryptx3.pem')) + cert2 = _load_cert(backend, os.path.join("x509", "letsencryptx3.pem")) encryption = serialization.NoEncryption() with pytest.raises(TypeError) as exc: serialize_key_and_certificates( - b'name', cert, cert, None, encryption) - assert str(exc.value) == \ - 'Key must be RSA, DSA, or EllipticCurve private key.' + b"name", cert, cert, None, encryption + ) + assert ( + str(exc.value) + == "Key must be RSA, DSA, or EllipticCurve private key." + ) with pytest.raises(TypeError) as exc: - serialize_key_and_certificates(b'name', key, key, None, encryption) - assert str(exc.value) == 'cert must be a certificate' + serialize_key_and_certificates(b"name", key, key, None, encryption) + assert str(exc.value) == "cert must be a certificate" with pytest.raises(TypeError) as exc: - serialize_key_and_certificates( - b'name', key, cert, None, key) - assert str( - exc.value) == ('Key encryption algorithm must be a ' - 'KeySerializationEncryption instance') + serialize_key_and_certificates(b"name", key, cert, None, key) + assert str(exc.value) == ( + "Key encryption algorithm must be a " + "KeySerializationEncryption instance" + ) with pytest.raises(TypeError) as exc: serialize_key_and_certificates(None, key, cert, cert2, encryption) with pytest.raises(TypeError) as exc: serialize_key_and_certificates(None, key, cert, [key], encryption) - assert str(exc.value) == 'all values in cas must be certificates' + assert str(exc.value) == "all values in cas must be certificates" def test_generate_no_cert(self, backend): _, key = _load_ca(backend) p12 = serialize_key_and_certificates( - None, key, None, None, serialization.NoEncryption()) - parsed_key, parsed_cert, parsed_more_certs = \ - load_key_and_certificates(p12, None, backend) + None, key, None, None, serialization.NoEncryption() + ) + parsed_key, parsed_cert, parsed_more_certs = load_key_and_certificates( + p12, None, backend + ) assert parsed_cert is None assert parsed_key.private_numbers() == key.private_numbers() assert parsed_more_certs == [] @@ -239,14 +255,13 @@ def test_must_supply_something(self): None, None, None, None, serialization.NoEncryption() ) assert str(exc.value) == ( - 'You must supply at least one of key, cert, or cas' + "You must supply at least one of key, cert, or cas" ) def test_generate_unsupported_encryption_type(self, backend): cert, key = _load_ca(backend) with pytest.raises(ValueError) as exc: serialize_key_and_certificates( - None, key, cert, None, - DummyKeySerializationEncryption(), + None, key, cert, None, DummyKeySerializationEncryption(), ) - assert str(exc.value) == 'Unsupported key encryption type' + assert str(exc.value) == "Unsupported key encryption type" diff --git a/tests/hazmat/primitives/test_poly1305.py b/tests/hazmat/primitives/test_poly1305.py index edca46230fe7..8779484ac9aa 100644 --- a/tests/hazmat/primitives/test_poly1305.py +++ b/tests/hazmat/primitives/test_poly1305.py @@ -10,18 +10,22 @@ import pytest from cryptography.exceptions import ( - AlreadyFinalized, InvalidSignature, _Reasons + AlreadyFinalized, + InvalidSignature, + _Reasons, ) from cryptography.hazmat.primitives.poly1305 import Poly1305 from ...utils import ( - load_nist_vectors, load_vectors_from_file, raises_unsupported_algorithm + load_nist_vectors, + load_vectors_from_file, + raises_unsupported_algorithm, ) @pytest.mark.supported( only_if=lambda backend: not backend.poly1305_supported(), - skip_message="Requires OpenSSL without poly1305 support" + skip_message="Requires OpenSSL without poly1305 support", ) def test_poly1305_unsupported(backend): with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_MAC): @@ -30,14 +34,14 @@ def test_poly1305_unsupported(backend): @pytest.mark.supported( only_if=lambda backend: backend.poly1305_supported(), - skip_message="Requires OpenSSL with poly1305 support" + skip_message="Requires OpenSSL with poly1305 support", ) class TestPoly1305(object): @pytest.mark.parametrize( "vector", load_vectors_from_file( os.path.join("poly1305", "rfc7539.txt"), load_nist_vectors - ) + ), ) def test_vectors(self, vector, backend): key = binascii.unhexlify(vector["key"]) @@ -67,10 +71,10 @@ def test_raises_after_finalize(self, backend): def test_reject_unicode(self, backend): poly = Poly1305(b"0" * 32) with pytest.raises(TypeError): - poly.update(u'') + poly.update(u"") with pytest.raises(TypeError): - Poly1305.generate_tag(b"0" * 32, u'') + Poly1305.generate_tag(b"0" * 32, u"") def test_verify(self, backend): poly = Poly1305(b"0" * 32) @@ -103,10 +107,10 @@ def test_invalid_verify(self, backend): def test_verify_reject_unicode(self, backend): poly = Poly1305(b"0" * 32) with pytest.raises(TypeError): - poly.verify(u'') + poly.verify(u"") with pytest.raises(TypeError): - Poly1305.verify_tag(b"0" * 32, b"msg", u'') + Poly1305.verify_tag(b"0" * 32, b"msg", u"") def test_invalid_key_type(self, backend): with pytest.raises(TypeError): diff --git a/tests/hazmat/primitives/test_rsa.py b/tests/hazmat/primitives/test_rsa.py index bde8b2095b7d..530f648889c2 100644 --- a/tests/hazmat/primitives/test_rsa.py +++ b/tests/hazmat/primitives/test_rsa.py @@ -11,36 +11,61 @@ import pytest from cryptography.exceptions import ( - AlreadyFinalized, InvalidSignature, _Reasons + AlreadyFinalized, + InvalidSignature, + _Reasons, ) from cryptography.hazmat.backends.interfaces import ( - PEMSerializationBackend, RSABackend + PEMSerializationBackend, + RSABackend, ) from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import ( - padding, rsa, utils as asym_utils + padding, + rsa, + utils as asym_utils, ) from cryptography.hazmat.primitives.asymmetric.rsa import ( - RSAPrivateNumbers, RSAPublicNumbers + RSAPrivateNumbers, + RSAPublicNumbers, ) from cryptography.utils import CryptographyDeprecationWarning 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_512_ALT, RSA_KEY_522, RSA_KEY_599, - RSA_KEY_745, RSA_KEY_768, + 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_512_ALT, + RSA_KEY_522, + RSA_KEY_599, + RSA_KEY_745, + RSA_KEY_768, ) from .utils import ( - _check_rsa_private_numbers, generate_rsa_verification_test, - skip_fips_traditional_openssl + _check_rsa_private_numbers, + generate_rsa_verification_test, + skip_fips_traditional_openssl, ) from ...doubles import ( - DummyAsymmetricPadding, DummyHashAlgorithm, DummyKeySerializationEncryption + DummyAsymmetricPadding, + DummyHashAlgorithm, + DummyKeySerializationEncryption, ) from ...utils import ( - load_nist_vectors, load_pkcs1_vectors, load_rsa_nist_vectors, - load_vectors_from_file, raises_unsupported_algorithm + load_nist_vectors, + load_pkcs1_vectors, + load_rsa_nist_vectors, + load_vectors_from_file, + raises_unsupported_algorithm, ) @@ -89,11 +114,9 @@ def _build_oaep_sha2_vectors(): load_vectors_from_file( os.path.join( base_path, - "oaep-{}-{}.txt".format( - mgf1alg.name, oaepalg.name - ) + "oaep-{}-{}.txt".format(mgf1alg.name, oaepalg.name), ), - load_pkcs1_vectors + load_pkcs1_vectors, ) ) # We've loaded the files, but the loaders don't give us any information @@ -107,8 +130,7 @@ def _build_oaep_sha2_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 + mgf=padding.MGF1(hash_alg), salt_length=padding.PSS.MAX_LENGTH ) ): pytest.skip( @@ -127,19 +149,22 @@ def test_modular_inverse(): "d1f9f6c09fd3d38987f7970247b85a6da84907753d42ec52bc23b745093f4fff5cff3" "617ce43d00121a9accc0051f519c76e08cf02fc18acfe4c9e6aea18da470a2b611d2e" "56a7b35caa2c0239bc041a53cc5875ca0b668ae6377d4b23e932d8c995fd1e58ecfd8" - "c4b73259c0d8a54d691cca3f6fb85c8a5c1baf588e898d481", 16 + "c4b73259c0d8a54d691cca3f6fb85c8a5c1baf588e898d481", + 16, ) q = int( "d1519255eb8f678c86cfd06802d1fbef8b664441ac46b73d33d13a8404580a33a8e74" "cb2ea2e2963125b3d454d7a922cef24dd13e55f989cbabf64255a736671f4629a47b5" "b2347cfcd669133088d1c159518531025297c2d67c9da856a12e80222cd03b4c6ec0f" - "86c957cb7bb8de7a127b645ec9e820aa94581e4762e209f01", 16 + "86c957cb7bb8de7a127b645ec9e820aa94581e4762e209f01", + 16, ) assert rsa._modinv(q, p) == int( "0275e06afa722999315f8f322275483e15e2fb46d827b17800f99110b269a6732748f" "624a382fa2ed1ec68c99f7fc56fb60e76eea51614881f497ba7034c17dde955f92f15" "772f8b2b41f3e56d88b1e096cdd293eba4eae1e82db815e0fadea0c4ec971bc6fd875" - "c20e67e48c31a611e98d32c6213ae4c4d7b53023b2f80c538", 16 + "c20e67e48c31a611e98d32c6213ae4c4d7b53023b2f80c538", + 16, ) @@ -149,16 +174,16 @@ class TestRSA(object): ("public_exponent", "key_size"), itertools.product( (3, 65537), - (1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1536, 2048) - ) + (1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 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) + 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 @@ -169,38 +194,39 @@ def test_generate_rsa_keys(self, backend, public_exponent, key_size): def test_generate_bad_public_exponent(self, backend): with pytest.raises(ValueError): - rsa.generate_private_key(public_exponent=1, - key_size=2048, - backend=backend) + 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) + 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) + 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) + 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) + 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 - ) + "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 @@ -213,15 +239,13 @@ def test_load_pss_vect_example_keys(self, pkcs1_example): dmq1=secret["dmq1"], iqmp=secret["iqmp"], public_numbers=rsa.RSAPublicNumbers( - e=secret["public_exponent"], - n=secret["modulus"] - ) + e=secret["public_exponent"], n=secret["modulus"] + ), ) _check_rsa_private_numbers(private_num) public_num = rsa.RSAPublicNumbers( - e=public["public_exponent"], - n=public["modulus"] + e=public["public_exponent"], n=public["modulus"] ) assert public_num @@ -235,17 +259,18 @@ def test_load_pss_vect_example_keys(self, pkcs1_example): "vector", load_vectors_from_file( os.path.join("asymmetric", "RSA", "oaep-label.txt"), - load_nist_vectors) + 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" + label=b"label", ) ), - skip_message="Does not support RSA OAEP labels" + skip_message="Does not support RSA OAEP labels", ) def test_oaep_label_decrypt(self, vector, backend): private_key = serialization.load_der_private_key( @@ -257,8 +282,8 @@ def test_oaep_label_decrypt(self, vector, backend): padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA512()), algorithm=hashes.SHA512(), - label=binascii.unhexlify(vector["oaeplabel"]) - ) + label=binascii.unhexlify(vector["oaeplabel"]), + ), ) assert vector["output"][1:-1] == decrypted @@ -267,17 +292,17 @@ def test_oaep_label_decrypt(self, vector, backend): [ (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" + label=b"label", ) ), - skip_message="Does not support RSA OAEP labels" + 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) @@ -286,54 +311,52 @@ def test_oaep_label_roundtrip(self, msg, label, backend): padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), - label=label - ) + label=label, + ), ) pt = private_key.decrypt( ct, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), - label=label - ) + label=label, + ), ) assert pt == msg @pytest.mark.parametrize( ("enclabel", "declabel"), - [ - (b"label1", b"label2"), - (b"label3", b""), - (b"", b"label4"), - ] + [(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" + label=b"label", ) ), - skip_message="Does not support RSA OAEP labels" + 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( + msg, + padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), - label=enclabel - ) + label=enclabel, + ), ) with pytest.raises(ValueError): private_key.decrypt( - ct, padding.OAEP( + ct, + padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), - label=declabel - ) + label=declabel, + ), ) @pytest.mark.supported( @@ -341,10 +364,10 @@ def test_oaep_wrong_label(self, enclabel, declabel, backend): padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), - label=b"label" + label=b"label", ) ), - skip_message="Requires backend without RSA OAEP label support" + skip_message="Requires backend without RSA OAEP label support", ) def test_unsupported_oaep_label_decrypt(self, backend): private_key = RSA_KEY_512.private_key(backend) @@ -354,8 +377,8 @@ def test_unsupported_oaep_label_decrypt(self, backend): padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), - label=b"label" - ) + label=b"label", + ), ) @@ -372,15 +395,16 @@ class TestRSASignature(object): only_if=lambda backend: backend.rsa_padding_supported( padding.PKCS1v15() ), - skip_message="Does not support PKCS1v1.5." + skip_message="Does not support PKCS1v1.5.", ) @pytest.mark.parametrize( "pkcs1_example", - _flatten_pkcs1_examples(load_vectors_from_file( - os.path.join( - "asymmetric", "RSA", "pkcs1v15sign-vectors.txt"), - load_pkcs1_vectors - )) + _flatten_pkcs1_examples( + load_vectors_from_file( + os.path.join("asymmetric", "RSA", "pkcs1v15sign-vectors.txt"), + load_pkcs1_vectors, + ) + ), ) def test_pkcs1v15_signing(self, pkcs1_example, backend): private, public, example = pkcs1_example @@ -392,14 +416,13 @@ def test_pkcs1v15_signing(self, pkcs1_example, backend): dmq1=private["dmq1"], iqmp=private["iqmp"], public_numbers=rsa.RSAPublicNumbers( - e=private["public_exponent"], - n=private["modulus"] - ) + e=private["public_exponent"], n=private["modulus"] + ), ).private_key(backend) signature = private_key.sign( binascii.unhexlify(example["message"]), padding.PKCS1v15(), - hashes.SHA1() + hashes.SHA1(), ) assert binascii.hexlify(signature) == example["signature"] @@ -407,18 +430,21 @@ def test_pkcs1v15_signing(self, pkcs1_example, backend): only_if=lambda backend: backend.rsa_padding_supported( padding.PSS( mgf=padding.MGF1(hashes.SHA1()), - salt_length=padding.PSS.MAX_LENGTH + salt_length=padding.PSS.MAX_LENGTH, ) ), - skip_message="Does not support PSS." + skip_message="Does not support PSS.", ) @pytest.mark.parametrize( "pkcs1_example", - _flatten_pkcs1_examples(load_vectors_from_file( - os.path.join( - "asymmetric", "RSA", "pkcs-1v2-1d2-vec", "pss-vect.txt"), - load_pkcs1_vectors - )) + _flatten_pkcs1_examples( + load_vectors_from_file( + os.path.join( + "asymmetric", "RSA", "pkcs-1v2-1d2-vec", "pss-vect.txt" + ), + load_pkcs1_vectors, + ) + ), ) def test_pss_signing(self, pkcs1_example, backend): private, public, example = pkcs1_example @@ -430,21 +456,19 @@ def test_pss_signing(self, pkcs1_example, backend): dmq1=private["dmq1"], iqmp=private["iqmp"], public_numbers=rsa.RSAPublicNumbers( - e=private["public_exponent"], - n=private["modulus"] - ) + e=private["public_exponent"], n=private["modulus"] + ), ).private_key(backend) public_key = rsa.RSAPublicNumbers( - e=public["public_exponent"], - n=public["modulus"] + 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 + salt_length=padding.PSS.MAX_LENGTH, ), - hashes.SHA1() + hashes.SHA1(), ) assert len(signature) == (private_key.key_size + 7) // 8 # PSS signatures contain randomness so we can't do an exact @@ -455,22 +479,21 @@ def test_pss_signing(self, pkcs1_example, backend): binascii.unhexlify(example["message"]), padding.PSS( mgf=padding.MGF1(algorithm=hashes.SHA1()), - salt_length=padding.PSS.MAX_LENGTH + salt_length=padding.PSS.MAX_LENGTH, ), hashes.SHA1(), ) @pytest.mark.parametrize( "hash_alg", - [hashes.SHA224(), hashes.SHA256(), hashes.SHA384(), hashes.SHA512()] + [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_768.private_key(backend) public_key = private_key.public_key() pss = padding.PSS( - mgf=padding.MGF1(hash_alg), - salt_length=padding.PSS.MAX_LENGTH + mgf=padding.MGF1(hash_alg), salt_length=padding.PSS.MAX_LENGTH ) msg = b"testing signature" signature = private_key.sign(msg, pss, hash_alg) @@ -478,15 +501,15 @@ def test_pss_signing_sha2(self, hash_alg, backend): @pytest.mark.supported( only_if=lambda backend: ( - backend.hash_supported(hashes.SHA512()) and - backend.rsa_padding_supported( + backend.hash_supported(hashes.SHA512()) + and backend.rsa_padding_supported( padding.PSS( mgf=padding.MGF1(hashes.SHA1()), - salt_length=padding.PSS.MAX_LENGTH + salt_length=padding.PSS.MAX_LENGTH, ) ) ), - skip_message="Does not support SHA512." + skip_message="Does not support SHA512.", ) def test_pss_minimum_key_size_for_digest(self, backend): private_key = RSA_KEY_522.private_key(backend) @@ -494,23 +517,23 @@ def test_pss_minimum_key_size_for_digest(self, backend): b"no failure", padding.PSS( mgf=padding.MGF1(hashes.SHA1()), - salt_length=padding.PSS.MAX_LENGTH + salt_length=padding.PSS.MAX_LENGTH, ), - hashes.SHA512() + 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 + salt_length=padding.PSS.MAX_LENGTH, ) ), - skip_message="Does not support PSS." + skip_message="Does not support PSS.", ) @pytest.mark.supported( only_if=lambda backend: backend.hash_supported(hashes.SHA512()), - skip_message="Does not support SHA512." + skip_message="Does not support SHA512.", ) def test_pss_signing_digest_too_large_for_key_size(self, backend): private_key = RSA_KEY_512.private_key(backend) @@ -519,19 +542,19 @@ def test_pss_signing_digest_too_large_for_key_size(self, backend): b"msg", padding.PSS( mgf=padding.MGF1(hashes.SHA1()), - salt_length=padding.PSS.MAX_LENGTH + salt_length=padding.PSS.MAX_LENGTH, ), - hashes.SHA512() + 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 + salt_length=padding.PSS.MAX_LENGTH, ) ), - skip_message="Does not support PSS." + skip_message="Does not support PSS.", ) def test_pss_signing_salt_length_too_long(self, backend): private_key = RSA_KEY_512.private_key(backend) @@ -539,17 +562,16 @@ def test_pss_signing_salt_length_too_long(self, backend): private_key.sign( b"failure coming", padding.PSS( - mgf=padding.MGF1(hashes.SHA1()), - salt_length=1000000 + mgf=padding.MGF1(hashes.SHA1()), salt_length=1000000 ), - hashes.SHA1() + hashes.SHA1(), ) @pytest.mark.supported( only_if=lambda backend: backend.rsa_padding_supported( padding.PKCS1v15() ), - skip_message="Does not support PKCS1v1.5." + skip_message="Does not support PKCS1v1.5.", ) def test_use_after_finalize(self, backend): private_key = RSA_KEY_512.private_key(backend) @@ -576,7 +598,7 @@ def test_padding_incorrect_type(self, backend): only_if=lambda backend: backend.rsa_padding_supported( padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=0) ), - skip_message="Does not support PSS." + skip_message="Does not support PSS.", ) def test_unsupported_pss_mgf(self, backend): private_key = RSA_KEY_512.private_key(backend) @@ -584,40 +606,33 @@ def test_unsupported_pss_mgf(self, backend): private_key.sign( b"msg", padding.PSS( - mgf=DummyMGF(), - salt_length=padding.PSS.MAX_LENGTH + mgf=DummyMGF(), salt_length=padding.PSS.MAX_LENGTH ), - hashes.SHA1() + hashes.SHA1(), ) @pytest.mark.supported( only_if=lambda backend: backend.rsa_padding_supported( padding.PKCS1v15() ), - skip_message="Does not support PKCS1v1.5." + skip_message="Does not support PKCS1v1.5.", ) 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() + 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." + skip_message="Does not support PKCS1v1.5.", ) 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() - ) + private_key.sign(b"no failure", padding.PKCS1v15(), hashes.SHA512()) def test_sign(self, backend): private_key = RSA_KEY_512.private_key(backend) @@ -632,7 +647,7 @@ def test_sign(self, backend): only_if=lambda backend: backend.rsa_padding_supported( padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=0) ), - skip_message="Does not support PSS." + skip_message="Does not support PSS.", ) def test_prehashed_sign(self, backend): private_key = RSA_KEY_512.private_key(backend) @@ -648,14 +663,15 @@ def test_prehashed_sign(self, backend): @pytest.mark.supported( only_if=lambda backend: backend.hash_supported( - hashes.BLAKE2s(digest_size=32)), + 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." + skip_message="Does not support PSS.", ) def test_unsupported_hash(self, backend): private_key = RSA_KEY_512.private_key(backend) @@ -668,7 +684,7 @@ def test_unsupported_hash(self, backend): only_if=lambda backend: backend.rsa_padding_supported( padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=0) ), - skip_message="Does not support PSS." + skip_message="Does not support PSS.", ) def test_prehashed_digest_mismatch(self, backend): private_key = RSA_KEY_512.private_key(backend) @@ -685,31 +701,32 @@ def test_prehashed_digest_mismatch(self, backend): only_if=lambda backend: backend.rsa_padding_supported( padding.PKCS1v15() ), - skip_message="Does not support PKCS1v1.5." + skip_message="Does not support PKCS1v1.5.", ) def test_prehashed_unsupported_in_signer_ctx(self, backend): private_key = RSA_KEY_512.private_key(backend) - with pytest.raises(TypeError), \ - pytest.warns(CryptographyDeprecationWarning): + with pytest.raises(TypeError), pytest.warns( + CryptographyDeprecationWarning + ): private_key.signer( - padding.PKCS1v15(), - asym_utils.Prehashed(hashes.SHA1()) + padding.PKCS1v15(), asym_utils.Prehashed(hashes.SHA1()) ) @pytest.mark.supported( only_if=lambda backend: backend.rsa_padding_supported( padding.PKCS1v15() ), - skip_message="Does not support PKCS1v1.5." + skip_message="Does not support PKCS1v1.5.", ) def test_prehashed_unsupported_in_verifier_ctx(self, backend): public_key = RSA_KEY_512.private_key(backend).public_key() - with pytest.raises(TypeError), \ - pytest.warns(CryptographyDeprecationWarning): + with pytest.raises(TypeError), pytest.warns( + CryptographyDeprecationWarning + ): public_key.verifier( b"0" * 64, padding.PKCS1v15(), - asym_utils.Prehashed(hashes.SHA1()) + asym_utils.Prehashed(hashes.SHA1()), ) @@ -719,34 +736,34 @@ class TestRSAVerification(object): only_if=lambda backend: backend.rsa_padding_supported( padding.PKCS1v15() ), - skip_message="Does not support PKCS1v1.5." + skip_message="Does not support PKCS1v1.5.", ) @pytest.mark.parametrize( "pkcs1_example", - _flatten_pkcs1_examples(load_vectors_from_file( - os.path.join( - "asymmetric", "RSA", "pkcs1v15sign-vectors.txt"), - load_pkcs1_vectors - )) + _flatten_pkcs1_examples( + load_vectors_from_file( + os.path.join("asymmetric", "RSA", "pkcs1v15sign-vectors.txt"), + load_pkcs1_vectors, + ) + ), ) def test_pkcs1v15_verification(self, pkcs1_example, backend): private, public, example = pkcs1_example public_key = rsa.RSAPublicNumbers( - e=public["public_exponent"], - n=public["modulus"] + e=public["public_exponent"], n=public["modulus"] ).public_key(backend) public_key.verify( binascii.unhexlify(example["signature"]), binascii.unhexlify(example["message"]), padding.PKCS1v15(), - hashes.SHA1() + hashes.SHA1(), ) @pytest.mark.supported( only_if=lambda backend: backend.rsa_padding_supported( padding.PKCS1v15() ), - skip_message="Does not support PKCS1v1.5." + skip_message="Does not support PKCS1v1.5.", ) def test_invalid_pkcs1v15_signature_wrong_data(self, backend): private_key = RSA_KEY_512.private_key(backend) @@ -756,10 +773,7 @@ def test_invalid_pkcs1v15_signature_wrong_data(self, backend): ) with pytest.raises(InvalidSignature): public_key.verify( - signature, - b"incorrect data", - padding.PKCS1v15(), - hashes.SHA1() + signature, b"incorrect data", padding.PKCS1v15(), hashes.SHA1() ) def test_invalid_signature_sequence_removed(self, backend): @@ -794,14 +808,14 @@ def test_invalid_signature_sequence_removed(self, backend): sig, binascii.unhexlify(b"313233343030"), padding.PKCS1v15(), - hashes.SHA256() + hashes.SHA256(), ) @pytest.mark.supported( only_if=lambda backend: backend.rsa_padding_supported( padding.PKCS1v15() ), - skip_message="Does not support PKCS1v1.5." + skip_message="Does not support PKCS1v1.5.", ) def test_invalid_pkcs1v15_signature_wrong_key(self, backend): private_key = RSA_KEY_512.private_key(backend) @@ -816,54 +830,53 @@ def test_invalid_pkcs1v15_signature_wrong_key(self, backend): @pytest.mark.supported( only_if=lambda backend: backend.rsa_padding_supported( - padding.PSS( - mgf=padding.MGF1(hashes.SHA1()), - salt_length=20 - ) + padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=20) ), - skip_message="Does not support PSS." + skip_message="Does not support PSS.", ) @pytest.mark.parametrize( "pkcs1_example", - _flatten_pkcs1_examples(load_vectors_from_file( - os.path.join( - "asymmetric", "RSA", "pkcs-1v2-1d2-vec", "pss-vect.txt"), - load_pkcs1_vectors - )) + _flatten_pkcs1_examples( + load_vectors_from_file( + os.path.join( + "asymmetric", "RSA", "pkcs-1v2-1d2-vec", "pss-vect.txt" + ), + load_pkcs1_vectors, + ) + ), ) def test_pss_verification(self, pkcs1_example, backend): private, public, example = pkcs1_example public_key = rsa.RSAPublicNumbers( - e=public["public_exponent"], - n=public["modulus"] + 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 + mgf=padding.MGF1(algorithm=hashes.SHA1()), salt_length=20 ), - hashes.SHA1() + hashes.SHA1(), ) @pytest.mark.supported( only_if=lambda backend: backend.rsa_padding_supported( padding.PSS( mgf=padding.MGF1(hashes.SHA1()), - salt_length=padding.PSS.MAX_LENGTH + salt_length=padding.PSS.MAX_LENGTH, ) ), - skip_message="Does not support PSS." + skip_message="Does not support PSS.", ) def test_invalid_pss_signature_wrong_data(self, backend): public_key = rsa.RSAPublicNumbers( n=int( b"dffc2137d5e810cde9e4b4612f5796447218bab913b3fa98bdf7982e4fa6" b"ec4d6653ef2b29fb1642b095befcbea6decc178fb4bed243d3c3592c6854" - b"6af2d3f3", 16 + b"6af2d3f3", + 16, ), - e=65537 + e=65537, ).public_key(backend) signature = binascii.unhexlify( b"0e68c3649df91c5bc3665f96e157efa75b71934aaa514d91e94ca8418d100f45" @@ -875,19 +888,19 @@ def test_invalid_pss_signature_wrong_data(self, backend): b"incorrect data", padding.PSS( mgf=padding.MGF1(algorithm=hashes.SHA1()), - salt_length=padding.PSS.MAX_LENGTH + salt_length=padding.PSS.MAX_LENGTH, ), - hashes.SHA1() + hashes.SHA1(), ) @pytest.mark.supported( only_if=lambda backend: backend.rsa_padding_supported( padding.PSS( mgf=padding.MGF1(hashes.SHA1()), - salt_length=padding.PSS.MAX_LENGTH + salt_length=padding.PSS.MAX_LENGTH, ) ), - skip_message="Does not support PSS." + skip_message="Does not support PSS.", ) def test_invalid_pss_signature_wrong_key(self, backend): signature = binascii.unhexlify( @@ -900,9 +913,10 @@ def test_invalid_pss_signature_wrong_key(self, backend): b"5a95441be90866a14c4d2e139cd16db540ec6c7abab13ffff91443fd46a8" b"960cbb7658ded26a5c95c86f6e40384e1c1239c63e541ba221191c4dd303" b"231b42e33c6dbddf5ec9a746f09bf0c25d0f8d27f93ee0ae5c0d723348f4" - b"030d3581e13522e1", 16 + b"030d3581e13522e1", + 16, ), - e=65537 + e=65537, ).public_key(backend) with pytest.raises(InvalidSignature): public_key.verify( @@ -910,19 +924,19 @@ def test_invalid_pss_signature_wrong_key(self, backend): b"sign me", padding.PSS( mgf=padding.MGF1(algorithm=hashes.SHA1()), - salt_length=padding.PSS.MAX_LENGTH + salt_length=padding.PSS.MAX_LENGTH, ), - hashes.SHA1() + hashes.SHA1(), ) @pytest.mark.supported( only_if=lambda backend: backend.rsa_padding_supported( padding.PSS( mgf=padding.MGF1(hashes.SHA1()), - salt_length=padding.PSS.MAX_LENGTH + salt_length=padding.PSS.MAX_LENGTH, ) ), - skip_message="Does not support PSS." + skip_message="Does not support PSS.", ) def test_invalid_pss_signature_data_too_large_for_modulus(self, backend): signature = binascii.unhexlify( @@ -935,9 +949,10 @@ def test_invalid_pss_signature_data_too_large_for_modulus(self, backend): b"5a95441be90866a14c4d2e139cd16db540ec6c7abab13ffff91443fd46a8" b"960cbb7658ded26a5c95c86f6e40384e1c1239c63e541ba221191c4dd303" b"231b42e33c6dbddf5ec9a746f09bf0c25d0f8d27f93ee0ae5c0d723348f4" - b"030d3581e13522", 16 + b"030d3581e13522", + 16, ), - e=65537 + e=65537, ).public_key(backend) with pytest.raises(InvalidSignature): public_key.verify( @@ -945,16 +960,16 @@ def test_invalid_pss_signature_data_too_large_for_modulus(self, backend): b"sign me", padding.PSS( mgf=padding.MGF1(algorithm=hashes.SHA1()), - salt_length=padding.PSS.MAX_LENGTH + salt_length=padding.PSS.MAX_LENGTH, ), - hashes.SHA1() + hashes.SHA1(), ) @pytest.mark.supported( only_if=lambda backend: backend.rsa_padding_supported( padding.PKCS1v15() ), - skip_message="Does not support PKCS1v1.5." + skip_message="Does not support PKCS1v1.5.", ) def test_use_after_finalize(self, backend): private_key = RSA_KEY_512.private_key(backend) @@ -965,9 +980,7 @@ def test_use_after_finalize(self, backend): with pytest.warns(CryptographyDeprecationWarning): verifier = public_key.verifier( - signature, - padding.PKCS1v15(), - hashes.SHA1() + signature, padding.PKCS1v15(), hashes.SHA1() ) verifier.update(b"sign me") verifier.verify() @@ -988,19 +1001,16 @@ def test_unsupported_padding(self, backend): only_if=lambda backend: backend.rsa_padding_supported( padding.PKCS1v15() ), - skip_message="Does not support PKCS1v1.5." + skip_message="Does not support PKCS1v1.5.", ) def test_signature_not_bytes(self, backend): public_key = RSA_KEY_512.public_numbers.public_key(backend) signature = 1234 - with pytest.raises(TypeError), \ - pytest.warns(CryptographyDeprecationWarning): - public_key.verifier( - signature, - padding.PKCS1v15(), - hashes.SHA1() - ) + with pytest.raises(TypeError), pytest.warns( + CryptographyDeprecationWarning + ): + public_key.verifier(signature, padding.PKCS1v15(), hashes.SHA1()) def test_padding_incorrect_type(self, backend): private_key = RSA_KEY_512.private_key(backend) @@ -1012,7 +1022,7 @@ def test_padding_incorrect_type(self, backend): only_if=lambda backend: backend.rsa_padding_supported( padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=0) ), - skip_message="Does not support PSS." + skip_message="Does not support PSS.", ) def test_unsupported_pss_mgf(self, backend): private_key = RSA_KEY_512.private_key(backend) @@ -1022,24 +1032,23 @@ def test_unsupported_pss_mgf(self, backend): b"sig", b"msg", padding.PSS( - mgf=DummyMGF(), - salt_length=padding.PSS.MAX_LENGTH + mgf=DummyMGF(), salt_length=padding.PSS.MAX_LENGTH ), - hashes.SHA1() + hashes.SHA1(), ) @pytest.mark.supported( only_if=lambda backend: backend.rsa_padding_supported( padding.PSS( mgf=padding.MGF1(hashes.SHA1()), - salt_length=padding.PSS.MAX_LENGTH + salt_length=padding.PSS.MAX_LENGTH, ) ), - skip_message="Does not support PSS." + skip_message="Does not support PSS.", ) @pytest.mark.supported( only_if=lambda backend: backend.hash_supported(hashes.SHA512()), - skip_message="Does not support SHA512." + skip_message="Does not support SHA512.", ) def test_pss_verify_digest_too_large_for_key_size(self, backend): private_key = RSA_KEY_512.private_key(backend) @@ -1054,19 +1063,19 @@ def test_pss_verify_digest_too_large_for_key_size(self, backend): b"msg doesn't matter", padding.PSS( mgf=padding.MGF1(algorithm=hashes.SHA1()), - salt_length=padding.PSS.MAX_LENGTH + salt_length=padding.PSS.MAX_LENGTH, ), - hashes.SHA512() + 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 + salt_length=padding.PSS.MAX_LENGTH, ) ), - skip_message="Does not support PSS." + skip_message="Does not support PSS.", ) def test_pss_verify_salt_length_too_long(self, backend): signature = binascii.unhexlify( @@ -1077,21 +1086,20 @@ def test_pss_verify_salt_length_too_long(self, backend): n=int( b"d309e4612809437548b747d7f9eb9cd3340f54fe42bb3f84a36933b0839c" b"11b0c8b7f67e11f7252370161e31159c49c784d4bc41c42a78ce0f0b40a3" - b"ca8ffb91", 16 + b"ca8ffb91", + 16, ), - e=65537 + e=65537, ).public_key(backend) with pytest.raises(InvalidSignature): public_key.verify( signature, b"sign me", padding.PSS( - mgf=padding.MGF1( - algorithm=hashes.SHA1(), - ), - salt_length=1000000 + mgf=padding.MGF1(algorithm=hashes.SHA1(),), + salt_length=1000000, ), - hashes.SHA1() + hashes.SHA1(), ) def test_verify(self, backend): @@ -1133,219 +1141,229 @@ class TestRSAPSSMGF1Verification(object): only_if=lambda backend: backend.rsa_padding_supported( padding.PSS( mgf=padding.MGF1(hashes.SHA1()), - salt_length=padding.PSS.MAX_LENGTH + salt_length=padding.PSS.MAX_LENGTH, ) ), - skip_message="Does not support PSS using MGF1 with SHA1." - )(generate_rsa_verification_test( - load_rsa_nist_vectors, - os.path.join("asymmetric", "RSA", "FIPS_186-2"), - [ - "SigGenPSS_186-2.rsp", - "SigGenPSS_186-3.rsp", - "SigVerPSS_186-3.rsp", - ], - hashes.SHA1(), - lambda params, hash_alg: padding.PSS( - mgf=padding.MGF1( - algorithm=hash_alg, + skip_message="Does not support PSS using MGF1 with SHA1.", + )( + generate_rsa_verification_test( + load_rsa_nist_vectors, + os.path.join("asymmetric", "RSA", "FIPS_186-2"), + [ + "SigGenPSS_186-2.rsp", + "SigGenPSS_186-3.rsp", + "SigVerPSS_186-3.rsp", + ], + hashes.SHA1(), + lambda params, hash_alg: padding.PSS( + mgf=padding.MGF1(algorithm=hash_alg,), + salt_length=params["salt_length"], ), - salt_length=params["salt_length"] ) - )) + ) test_rsa_pss_mgf1_sha224 = pytest.mark.supported( only_if=lambda backend: backend.rsa_padding_supported( padding.PSS( mgf=padding.MGF1(hashes.SHA224()), - salt_length=padding.PSS.MAX_LENGTH + salt_length=padding.PSS.MAX_LENGTH, ) ), - skip_message="Does not support PSS using MGF1 with SHA224." - )(generate_rsa_verification_test( - load_rsa_nist_vectors, - os.path.join("asymmetric", "RSA", "FIPS_186-2"), - [ - "SigGenPSS_186-2.rsp", - "SigGenPSS_186-3.rsp", - "SigVerPSS_186-3.rsp", - ], - hashes.SHA224(), - lambda params, hash_alg: padding.PSS( - mgf=padding.MGF1( - algorithm=hash_alg, + skip_message="Does not support PSS using MGF1 with SHA224.", + )( + generate_rsa_verification_test( + load_rsa_nist_vectors, + os.path.join("asymmetric", "RSA", "FIPS_186-2"), + [ + "SigGenPSS_186-2.rsp", + "SigGenPSS_186-3.rsp", + "SigVerPSS_186-3.rsp", + ], + hashes.SHA224(), + lambda params, hash_alg: padding.PSS( + mgf=padding.MGF1(algorithm=hash_alg,), + salt_length=params["salt_length"], ), - salt_length=params["salt_length"] ) - )) + ) test_rsa_pss_mgf1_sha256 = pytest.mark.supported( only_if=lambda backend: backend.rsa_padding_supported( padding.PSS( mgf=padding.MGF1(hashes.SHA256()), - salt_length=padding.PSS.MAX_LENGTH + salt_length=padding.PSS.MAX_LENGTH, ) ), - skip_message="Does not support PSS using MGF1 with SHA256." - )(generate_rsa_verification_test( - load_rsa_nist_vectors, - os.path.join("asymmetric", "RSA", "FIPS_186-2"), - [ - "SigGenPSS_186-2.rsp", - "SigGenPSS_186-3.rsp", - "SigVerPSS_186-3.rsp", - ], - hashes.SHA256(), - lambda params, hash_alg: padding.PSS( - mgf=padding.MGF1( - algorithm=hash_alg, + skip_message="Does not support PSS using MGF1 with SHA256.", + )( + generate_rsa_verification_test( + load_rsa_nist_vectors, + os.path.join("asymmetric", "RSA", "FIPS_186-2"), + [ + "SigGenPSS_186-2.rsp", + "SigGenPSS_186-3.rsp", + "SigVerPSS_186-3.rsp", + ], + hashes.SHA256(), + lambda params, hash_alg: padding.PSS( + mgf=padding.MGF1(algorithm=hash_alg,), + salt_length=params["salt_length"], ), - salt_length=params["salt_length"] ) - )) + ) test_rsa_pss_mgf1_sha384 = pytest.mark.supported( only_if=lambda backend: backend.rsa_padding_supported( padding.PSS( mgf=padding.MGF1(hashes.SHA384()), - salt_length=padding.PSS.MAX_LENGTH + salt_length=padding.PSS.MAX_LENGTH, ) ), - skip_message="Does not support PSS using MGF1 with SHA384." - )(generate_rsa_verification_test( - load_rsa_nist_vectors, - os.path.join("asymmetric", "RSA", "FIPS_186-2"), - [ - "SigGenPSS_186-2.rsp", - "SigGenPSS_186-3.rsp", - "SigVerPSS_186-3.rsp", - ], - hashes.SHA384(), - lambda params, hash_alg: padding.PSS( - mgf=padding.MGF1( - algorithm=hash_alg, + skip_message="Does not support PSS using MGF1 with SHA384.", + )( + generate_rsa_verification_test( + load_rsa_nist_vectors, + os.path.join("asymmetric", "RSA", "FIPS_186-2"), + [ + "SigGenPSS_186-2.rsp", + "SigGenPSS_186-3.rsp", + "SigVerPSS_186-3.rsp", + ], + hashes.SHA384(), + lambda params, hash_alg: padding.PSS( + mgf=padding.MGF1(algorithm=hash_alg,), + salt_length=params["salt_length"], ), - salt_length=params["salt_length"] ) - )) + ) test_rsa_pss_mgf1_sha512 = pytest.mark.supported( only_if=lambda backend: backend.rsa_padding_supported( padding.PSS( mgf=padding.MGF1(hashes.SHA512()), - salt_length=padding.PSS.MAX_LENGTH + salt_length=padding.PSS.MAX_LENGTH, ) ), - skip_message="Does not support PSS using MGF1 with SHA512." - )(generate_rsa_verification_test( - load_rsa_nist_vectors, - os.path.join("asymmetric", "RSA", "FIPS_186-2"), - [ - "SigGenPSS_186-2.rsp", - "SigGenPSS_186-3.rsp", - "SigVerPSS_186-3.rsp", - ], - hashes.SHA512(), - lambda params, hash_alg: padding.PSS( - mgf=padding.MGF1( - algorithm=hash_alg, + skip_message="Does not support PSS using MGF1 with SHA512.", + )( + generate_rsa_verification_test( + load_rsa_nist_vectors, + os.path.join("asymmetric", "RSA", "FIPS_186-2"), + [ + "SigGenPSS_186-2.rsp", + "SigGenPSS_186-3.rsp", + "SigVerPSS_186-3.rsp", + ], + hashes.SHA512(), + lambda params, hash_alg: padding.PSS( + mgf=padding.MGF1(algorithm=hash_alg,), + salt_length=params["salt_length"], ), - salt_length=params["salt_length"] ) - )) + ) @pytest.mark.requires_backend_interface(interface=RSABackend) class TestRSAPKCS1Verification(object): test_rsa_pkcs1v15_verify_sha1 = pytest.mark.supported( only_if=lambda backend: ( - backend.hash_supported(hashes.SHA1()) and - backend.rsa_padding_supported(padding.PKCS1v15()) + backend.hash_supported(hashes.SHA1()) + and backend.rsa_padding_supported(padding.PKCS1v15()) ), - skip_message="Does not support SHA1 and PKCS1v1.5." - )(generate_rsa_verification_test( - load_rsa_nist_vectors, - os.path.join("asymmetric", "RSA", "FIPS_186-2"), - [ - "SigGen15_186-2.rsp", - "SigGen15_186-3.rsp", - "SigVer15_186-3.rsp", - ], - hashes.SHA1(), - lambda params, hash_alg: padding.PKCS1v15() - )) + skip_message="Does not support SHA1 and PKCS1v1.5.", + )( + generate_rsa_verification_test( + load_rsa_nist_vectors, + os.path.join("asymmetric", "RSA", "FIPS_186-2"), + [ + "SigGen15_186-2.rsp", + "SigGen15_186-3.rsp", + "SigVer15_186-3.rsp", + ], + hashes.SHA1(), + lambda params, hash_alg: padding.PKCS1v15(), + ) + ) test_rsa_pkcs1v15_verify_sha224 = pytest.mark.supported( only_if=lambda backend: ( - backend.hash_supported(hashes.SHA224()) and - backend.rsa_padding_supported(padding.PKCS1v15()) + backend.hash_supported(hashes.SHA224()) + and backend.rsa_padding_supported(padding.PKCS1v15()) ), - skip_message="Does not support SHA224 and PKCS1v1.5." - )(generate_rsa_verification_test( - load_rsa_nist_vectors, - os.path.join("asymmetric", "RSA", "FIPS_186-2"), - [ - "SigGen15_186-2.rsp", - "SigGen15_186-3.rsp", - "SigVer15_186-3.rsp", - ], - hashes.SHA224(), - lambda params, hash_alg: padding.PKCS1v15() - )) + skip_message="Does not support SHA224 and PKCS1v1.5.", + )( + generate_rsa_verification_test( + load_rsa_nist_vectors, + os.path.join("asymmetric", "RSA", "FIPS_186-2"), + [ + "SigGen15_186-2.rsp", + "SigGen15_186-3.rsp", + "SigVer15_186-3.rsp", + ], + hashes.SHA224(), + lambda params, hash_alg: padding.PKCS1v15(), + ) + ) test_rsa_pkcs1v15_verify_sha256 = pytest.mark.supported( only_if=lambda backend: ( - backend.hash_supported(hashes.SHA256()) and - backend.rsa_padding_supported(padding.PKCS1v15()) + backend.hash_supported(hashes.SHA256()) + and backend.rsa_padding_supported(padding.PKCS1v15()) ), - skip_message="Does not support SHA256 and PKCS1v1.5." - )(generate_rsa_verification_test( - load_rsa_nist_vectors, - os.path.join("asymmetric", "RSA", "FIPS_186-2"), - [ - "SigGen15_186-2.rsp", - "SigGen15_186-3.rsp", - "SigVer15_186-3.rsp", - ], - hashes.SHA256(), - lambda params, hash_alg: padding.PKCS1v15() - )) + skip_message="Does not support SHA256 and PKCS1v1.5.", + )( + generate_rsa_verification_test( + load_rsa_nist_vectors, + os.path.join("asymmetric", "RSA", "FIPS_186-2"), + [ + "SigGen15_186-2.rsp", + "SigGen15_186-3.rsp", + "SigVer15_186-3.rsp", + ], + hashes.SHA256(), + lambda params, hash_alg: padding.PKCS1v15(), + ) + ) test_rsa_pkcs1v15_verify_sha384 = pytest.mark.supported( only_if=lambda backend: ( - backend.hash_supported(hashes.SHA384()) and - backend.rsa_padding_supported(padding.PKCS1v15()) + backend.hash_supported(hashes.SHA384()) + and backend.rsa_padding_supported(padding.PKCS1v15()) ), - skip_message="Does not support SHA384 and PKCS1v1.5." - )(generate_rsa_verification_test( - load_rsa_nist_vectors, - os.path.join("asymmetric", "RSA", "FIPS_186-2"), - [ - "SigGen15_186-2.rsp", - "SigGen15_186-3.rsp", - "SigVer15_186-3.rsp", - ], - hashes.SHA384(), - lambda params, hash_alg: padding.PKCS1v15() - )) + skip_message="Does not support SHA384 and PKCS1v1.5.", + )( + generate_rsa_verification_test( + load_rsa_nist_vectors, + os.path.join("asymmetric", "RSA", "FIPS_186-2"), + [ + "SigGen15_186-2.rsp", + "SigGen15_186-3.rsp", + "SigVer15_186-3.rsp", + ], + hashes.SHA384(), + lambda params, hash_alg: padding.PKCS1v15(), + ) + ) test_rsa_pkcs1v15_verify_sha512 = pytest.mark.supported( only_if=lambda backend: ( - backend.hash_supported(hashes.SHA512()) and - backend.rsa_padding_supported(padding.PKCS1v15()) + backend.hash_supported(hashes.SHA512()) + and backend.rsa_padding_supported(padding.PKCS1v15()) ), - skip_message="Does not support SHA512 and PKCS1v1.5." - )(generate_rsa_verification_test( - load_rsa_nist_vectors, - os.path.join("asymmetric", "RSA", "FIPS_186-2"), - [ - "SigGen15_186-2.rsp", - "SigGen15_186-3.rsp", - "SigVer15_186-3.rsp", - ], - hashes.SHA512(), - lambda params, hash_alg: padding.PKCS1v15() - )) + skip_message="Does not support SHA512 and PKCS1v1.5.", + )( + generate_rsa_verification_test( + load_rsa_nist_vectors, + os.path.join("asymmetric", "RSA", "FIPS_186-2"), + [ + "SigGen15_186-2.rsp", + "SigGen15_186-3.rsp", + "SigVer15_186-3.rsp", + ], + hashes.SHA512(), + lambda params, hash_alg: padding.PKCS1v15(), + ) + ) class TestPSS(object): @@ -1356,20 +1374,12 @@ def test_calculate_max_pss_salt_length(self): def test_invalid_salt_length_not_integer(self): with pytest.raises(TypeError): padding.PSS( - mgf=padding.MGF1( - hashes.SHA1() - ), - salt_length=b"not_a_length" + mgf=padding.MGF1(hashes.SHA1()), salt_length=b"not_a_length" ) def test_invalid_salt_length_negative_integer(self): with pytest.raises(ValueError): - padding.PSS( - mgf=padding.MGF1( - hashes.SHA1() - ), - salt_length=-1 - ) + padding.PSS(mgf=padding.MGF1(hashes.SHA1()), salt_length=-1) def test_valid_pss_parameters(self): algorithm = hashes.SHA1() @@ -1402,11 +1412,7 @@ class TestOAEP(object): def test_invalid_algorithm(self): mgf = padding.MGF1(hashes.SHA1()) with pytest.raises(TypeError): - padding.OAEP( - mgf=mgf, - algorithm=b"", - label=None - ) + padding.OAEP(mgf=mgf, algorithm=b"", label=None) @pytest.mark.requires_backend_interface(interface=RSABackend) @@ -1415,15 +1421,16 @@ class TestRSADecryption(object): only_if=lambda backend: backend.rsa_padding_supported( padding.PKCS1v15() ), - skip_message="Does not support PKCS1v1.5." + skip_message="Does not support PKCS1v1.5.", ) @pytest.mark.parametrize( "vector", - _flatten_pkcs1_examples(load_vectors_from_file( - os.path.join( - "asymmetric", "RSA", "pkcs1v15crypt-vectors.txt"), - load_pkcs1_vectors - )) + _flatten_pkcs1_examples( + load_vectors_from_file( + os.path.join("asymmetric", "RSA", "pkcs1v15crypt-vectors.txt"), + load_pkcs1_vectors, + ) + ), ) def test_decrypt_pkcs1v15_vectors(self, vector, backend): private, public, example = vector @@ -1435,9 +1442,8 @@ def test_decrypt_pkcs1v15_vectors(self, vector, backend): dmq1=private["dmq1"], iqmp=private["iqmp"], public_numbers=rsa.RSAPublicNumbers( - e=private["public_exponent"], - n=private["modulus"] - ) + e=private["public_exponent"], n=private["modulus"] + ), ).private_key(backend) ciphertext = binascii.unhexlify(example["encryption"]) assert len(ciphertext) == (skey.key_size + 7) // 8 @@ -1453,35 +1459,29 @@ def test_unsupported_padding(self, backend): only_if=lambda backend: backend.rsa_padding_supported( padding.PKCS1v15() ), - skip_message="Does not support PKCS1v1.5." + skip_message="Does not support PKCS1v1.5.", ) def test_decrypt_invalid_decrypt(self, backend): private_key = RSA_KEY_512.private_key(backend) with pytest.raises(ValueError): - private_key.decrypt( - b"\x00" * 64, - padding.PKCS1v15() - ) + private_key.decrypt(b"\x00" * 64, padding.PKCS1v15()) @pytest.mark.supported( only_if=lambda backend: backend.rsa_padding_supported( padding.PKCS1v15() ), - skip_message="Does not support PKCS1v1.5." + skip_message="Does not support PKCS1v1.5.", ) def test_decrypt_ciphertext_too_large(self, backend): private_key = RSA_KEY_512.private_key(backend) with pytest.raises(ValueError): - private_key.decrypt( - b"\x00" * 65, - padding.PKCS1v15() - ) + private_key.decrypt(b"\x00" * 65, padding.PKCS1v15()) @pytest.mark.supported( only_if=lambda backend: backend.rsa_padding_supported( padding.PKCS1v15() ), - skip_message="Does not support PKCS1v1.5." + skip_message="Does not support PKCS1v1.5.", ) def test_decrypt_ciphertext_too_small(self, backend): private_key = RSA_KEY_512.private_key(backend) @@ -1490,28 +1490,28 @@ def test_decrypt_ciphertext_too_small(self, backend): b"69d210f2b9bdfb48b12f9ea05009c77da257cc600ccefe3a6283789d8ea0" ) with pytest.raises(ValueError): - private_key.decrypt( - ct, - padding.PKCS1v15() - ) + private_key.decrypt(ct, padding.PKCS1v15()) @pytest.mark.supported( only_if=lambda backend: backend.rsa_padding_supported( padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), - label=None + label=None, ) ), - skip_message="Does not support OAEP." + skip_message="Does not support OAEP.", ) @pytest.mark.parametrize( "vector", - _flatten_pkcs1_examples(load_vectors_from_file( - os.path.join( - "asymmetric", "RSA", "pkcs-1v2-1d2-vec", "oaep-vect.txt"), - load_pkcs1_vectors - )) + _flatten_pkcs1_examples( + load_vectors_from_file( + os.path.join( + "asymmetric", "RSA", "pkcs-1v2-1d2-vec", "oaep-vect.txt" + ), + load_pkcs1_vectors, + ) + ), ) def test_decrypt_oaep_vectors(self, vector, backend): private, public, example = vector @@ -1523,17 +1523,16 @@ def test_decrypt_oaep_vectors(self, vector, backend): dmq1=private["dmq1"], iqmp=private["iqmp"], public_numbers=rsa.RSAPublicNumbers( - e=private["public_exponent"], - n=private["modulus"] - ) + e=private["public_exponent"], n=private["modulus"] + ), ).private_key(backend) message = skey.decrypt( binascii.unhexlify(example["encryption"]), padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), - label=None - ) + label=None, + ), ) assert message == binascii.unhexlify(example["message"]) @@ -1542,15 +1541,14 @@ def test_decrypt_oaep_vectors(self, vector, backend): padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA224()), algorithm=hashes.SHA224(), - label=None + label=None, ) ), - skip_message="Does not support OAEP using SHA224 MGF1 and SHA224 hash." - ) - @pytest.mark.parametrize( - "vector", - _build_oaep_sha2_vectors() + skip_message=( + "Does not support OAEP using SHA224 MGF1 and SHA224 hash." + ), ) + @pytest.mark.parametrize("vector", _build_oaep_sha2_vectors()) def test_decrypt_oaep_sha2_vectors(self, vector, backend): private, public, example, mgf1_alg, hash_alg = vector skey = rsa.RSAPrivateNumbers( @@ -1561,17 +1559,16 @@ def test_decrypt_oaep_sha2_vectors(self, vector, backend): dmq1=private["dmq1"], iqmp=private["iqmp"], public_numbers=rsa.RSAPublicNumbers( - e=private["public_exponent"], - n=private["modulus"] - ) + e=private["public_exponent"], n=private["modulus"] + ), ).private_key(backend) message = skey.decrypt( binascii.unhexlify(example["encryption"]), padding.OAEP( mgf=padding.MGF1(algorithm=mgf1_alg), algorithm=hash_alg, - label=None - ) + label=None, + ), ) assert message == binascii.unhexlify(example["message"]) @@ -1580,10 +1577,10 @@ def test_decrypt_oaep_sha2_vectors(self, vector, backend): padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), - label=None + label=None, ) ), - skip_message="Does not support OAEP." + skip_message="Does not support OAEP.", ) def test_invalid_oaep_decryption(self, backend): # More recent versions of OpenSSL may raise RSA_R_OAEP_DECODING_ERROR @@ -1592,12 +1589,12 @@ def test_invalid_oaep_decryption(self, backend): private_key = RSA_KEY_512.private_key(backend) ciphertext = private_key.public_key().encrypt( - b'secure data', + b"secure data", padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), - label=None - ) + label=None, + ), ) private_key_alt = RSA_KEY_512_ALT.private_key(backend) @@ -1608,8 +1605,8 @@ def test_invalid_oaep_decryption(self, backend): padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), - label=None - ) + label=None, + ), ) @pytest.mark.supported( @@ -1617,27 +1614,27 @@ def test_invalid_oaep_decryption(self, backend): padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), - label=None + label=None, ) ), - skip_message="Does not support OAEP." + skip_message="Does not support OAEP.", ) def test_invalid_oaep_decryption_data_to_large_for_modulus(self, backend): key = RSA_KEY_2048_ALT.private_key(backend) ciphertext = ( - b'\xb1ph\xc0\x0b\x1a|\xe6\xda\xea\xb5\xd7%\x94\x07\xf96\xfb\x96' - b'\x11\x9b\xdc4\xea.-\x91\x80\x13S\x94\x04m\xe9\xc5/F\x1b\x9b:\\' - b'\x1d\x04\x16ML\xae\xb32J\x01yuA\xbb\x83\x1c\x8f\xf6\xa5\xdbp\xcd' - b'\nx\xc7\xf6\x15\xb2/\xdcH\xae\xe7\x13\x13by\r4t\x99\x0fc\x1f\xc1' - b'\x1c\xb1\xdd\xc5\x08\xd1\xee\xa1XQ\xb8H@L5v\xc3\xaf\xf2\r\x97' - b'\xed\xaa\xe7\xf1\xd4xai\xd3\x83\xd9\xaa9\xbfx\xe1\x87F \x01\xff' - b'L\xccv}ae\xb3\xfa\xf2B\xb8\xf9\x04H\x94\x85\xcb\x86\xbb\\ghx!W31' - b'\xc7;t\na_E\xc2\x16\xb0;\xa1\x18\t\x1b\xe1\xdb\x80>)\x15\xc6\x12' - b'\xcb\xeeg`\x8b\x9b\x1b\x05y4\xb0\x84M6\xcd\xa1\x827o\xfd\x96\xba' - b'Z#\x8d\xae\x01\xc9\xf2\xb6\xde\x89{8&eQ\x1e8\x03\x01#?\xb66\\' - b'\xad.\xe9\xfa!\x95 c{\xcaz\xe0*\tP\r\x91\x9a)B\xb5\xadN\xf4$\x83' - b'\t\xb5u\xab\x19\x99' + b"\xb1ph\xc0\x0b\x1a|\xe6\xda\xea\xb5\xd7%\x94\x07\xf96\xfb\x96" + b"\x11\x9b\xdc4\xea.-\x91\x80\x13S\x94\x04m\xe9\xc5/F\x1b\x9b:\\" + b"\x1d\x04\x16ML\xae\xb32J\x01yuA\xbb\x83\x1c\x8f\xf6\xa5\xdbp\xcd" + b"\nx\xc7\xf6\x15\xb2/\xdcH\xae\xe7\x13\x13by\r4t\x99\x0fc\x1f\xc1" + b"\x1c\xb1\xdd\xc5\x08\xd1\xee\xa1XQ\xb8H@L5v\xc3\xaf\xf2\r\x97" + b"\xed\xaa\xe7\xf1\xd4xai\xd3\x83\xd9\xaa9\xbfx\xe1\x87F \x01\xff" + b"L\xccv}ae\xb3\xfa\xf2B\xb8\xf9\x04H\x94\x85\xcb\x86\xbb\\ghx!W31" + b"\xc7;t\na_E\xc2\x16\xb0;\xa1\x18\t\x1b\xe1\xdb\x80>)\x15\xc6\x12" + b"\xcb\xeeg`\x8b\x9b\x1b\x05y4\xb0\x84M6\xcd\xa1\x827o\xfd\x96\xba" + b"Z#\x8d\xae\x01\xc9\xf2\xb6\xde\x89{8&eQ\x1e8\x03\x01#?\xb66\\" + b"\xad.\xe9\xfa!\x95 c{\xcaz\xe0*\tP\r\x91\x9a)B\xb5\xadN\xf4$\x83" + b"\t\xb5u\xab\x19\x99" ) with pytest.raises(ValueError): @@ -1646,8 +1643,8 @@ def test_invalid_oaep_decryption_data_to_large_for_modulus(self, backend): padding.OAEP( algorithm=hashes.SHA1(), mgf=padding.MGF1(hashes.SHA1()), - label=None - ) + label=None, + ), ) def test_unsupported_oaep_mgf(self, backend): @@ -1656,10 +1653,8 @@ def test_unsupported_oaep_mgf(self, backend): private_key.decrypt( b"0" * 64, padding.OAEP( - mgf=DummyMGF(), - algorithm=hashes.SHA1(), - label=None - ) + mgf=DummyMGF(), algorithm=hashes.SHA1(), label=None + ), ) @@ -1670,25 +1665,34 @@ class TestRSAEncryption(object): padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), - label=None + label=None, ) ), - skip_message="Does not support OAEP." + skip_message="Does not support OAEP.", ) @pytest.mark.parametrize( ("key_data", "pad"), itertools.product( - (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_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, + ), [ padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), - label=None + label=None, ) - ] - ) + ], + ), ) def test_rsa_encrypt_oaep(self, key_data, pad, backend): private_key = key_data.private_key(backend) @@ -1705,32 +1709,37 @@ def test_rsa_encrypt_oaep(self, key_data, pad, backend): padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA512(), - label=None + label=None, ) ), - skip_message="Does not support OAEP using SHA256 MGF1 and SHA512 hash." + skip_message=( + "Does not support OAEP using SHA256 MGF1 and SHA512 hash." + ), ) @pytest.mark.parametrize( ("mgf1hash", "oaephash"), - itertools.product([ - hashes.SHA1(), - hashes.SHA224(), - hashes.SHA256(), - hashes.SHA384(), - hashes.SHA512(), - ], [ - hashes.SHA1(), - hashes.SHA224(), - hashes.SHA256(), - hashes.SHA384(), - hashes.SHA512(), - ]) + itertools.product( + [ + hashes.SHA1(), + hashes.SHA224(), + hashes.SHA256(), + hashes.SHA384(), + hashes.SHA512(), + ], + [ + hashes.SHA1(), + hashes.SHA224(), + hashes.SHA256(), + hashes.SHA384(), + hashes.SHA512(), + ], + ), ) def test_rsa_encrypt_oaep_sha2(self, mgf1hash, oaephash, backend): pad = padding.OAEP( mgf=padding.MGF1(algorithm=mgf1hash), algorithm=oaephash, - label=None + label=None, ) private_key = RSA_KEY_2048.private_key(backend) pt = b"encrypt me using sha2 hashes!" @@ -1745,16 +1754,25 @@ def test_rsa_encrypt_oaep_sha2(self, mgf1hash, oaephash, backend): only_if=lambda backend: backend.rsa_padding_supported( padding.PKCS1v15() ), - skip_message="Does not support PKCS1v1.5." + skip_message="Does not support PKCS1v1.5.", ) @pytest.mark.parametrize( ("key_data", "pad"), itertools.product( - (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), - [padding.PKCS1v15()] - ) + ( + 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, + ), + [padding.PKCS1v15()], + ), ) def test_rsa_encrypt_pkcs1v15(self, key_data, pad, backend): private_key = key_data.private_key(backend) @@ -1769,35 +1787,38 @@ def test_rsa_encrypt_pkcs1v15(self, key_data, pad, backend): @pytest.mark.parametrize( ("key_data", "pad"), itertools.product( - (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_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, + ), ( padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), - label=None + label=None, ), - padding.PKCS1v15() - ) - ) + padding.PKCS1v15(), + ), + ), ) def test_rsa_encrypt_key_too_small(self, key_data, pad, backend): private_key = key_data.private_key(backend) public_key = private_key.public_key() # Slightly smaller than the key size but not enough for padding. with pytest.raises(ValueError): - public_key.encrypt( - b"\x00" * (private_key.key_size // 8 - 1), - pad - ) + public_key.encrypt(b"\x00" * (private_key.key_size // 8 - 1), pad) # Larger than the key size. with pytest.raises(ValueError): - public_key.encrypt( - b"\x00" * (private_key.key_size // 8 + 5), - pad - ) + public_key.encrypt(b"\x00" * (private_key.key_size // 8 + 5), pad) def test_unsupported_padding(self, backend): private_key = RSA_KEY_512.private_key(backend) @@ -1816,10 +1837,8 @@ def test_unsupported_oaep_mgf(self, backend): public_key.encrypt( b"ciphertext", padding.OAEP( - mgf=DummyMGF(), - algorithm=hashes.SHA1(), - label=None - ) + mgf=DummyMGF(), algorithm=hashes.SHA1(), label=None + ), ) @@ -1839,7 +1858,7 @@ def test_rsa_private_numbers(self): dmp1=1, dmq1=1, iqmp=2, - public_numbers=public_numbers + public_numbers=public_numbers, ) assert private_numbers.p == 3 @@ -1875,18 +1894,20 @@ def test_public_numbers_invalid_types(self): (3, 5, 1, 1, None, 2, rsa.RSAPublicNumbers(e=1, n=15)), (3, 5, 1, 1, 1, None, rsa.RSAPublicNumbers(e=1, n=15)), (3, 5, 1, 1, 1, 2, None), - ] + ], ) - def test_private_numbers_invalid_types(self, p, q, d, dmp1, dmq1, iqmp, - public_numbers): + def test_private_numbers_invalid_types( + self, p, q, d, dmp1, dmq1, iqmp, public_numbers + ): with pytest.raises(TypeError): rsa.RSAPrivateNumbers( - p=p, q=q, + p=p, + q=q, d=d, dmp1=dmp1, dmq1=dmq1, iqmp=iqmp, - public_numbers=public_numbers + public_numbers=public_numbers, ) @pytest.mark.parametrize( @@ -1896,7 +1917,7 @@ def test_private_numbers_invalid_types(self, p, q, d, dmp1, dmq1, iqmp, (1, 15), # public_exponent < 3 (17, 15), # public_exponent > modulus (14, 15), # public_exponent not odd - ] + ], ) def test_invalid_public_numbers_argument_values(self, e, n, backend): # Start with public_exponent=7, modulus=15. Then change one value at a @@ -1921,10 +1942,11 @@ def test_invalid_public_numbers_argument_values(self, e, n, backend): (3, 11, 3, 1, 3, 2, 6, 33), # public_exponent is not odd (3, 11, 3, 2, 3, 2, 7, 33), # dmp1 is not odd (3, 11, 3, 1, 4, 2, 7, 33), # dmq1 is not odd - ] + ], ) - def test_invalid_private_numbers_argument_values(self, p, q, d, dmp1, dmq1, - iqmp, e, n, backend): + def test_invalid_private_numbers_argument_values( + self, p, q, d, dmp1, dmq1, iqmp, e, n, backend + ): # Start with p=3, q=11, private_exponent=3, public_exponent=7, # modulus=33, dmp1=1, dmq1=3, iqmp=2. Then change one value at # a time to test the bounds. @@ -1937,10 +1959,7 @@ def test_invalid_private_numbers_argument_values(self, p, q, d, dmp1, dmq1, dmp1=dmp1, dmq1=dmq1, iqmp=iqmp, - public_numbers=rsa.RSAPublicNumbers( - e=e, - n=n - ) + public_numbers=rsa.RSAPublicNumbers(e=e, n=n), ).private_key(backend) def test_public_number_repr(self): @@ -2016,18 +2035,19 @@ def test_private_numbers_hash(self): class TestRSAPrimeFactorRecovery(object): @pytest.mark.parametrize( "vector", - _flatten_pkcs1_examples(load_vectors_from_file( - os.path.join( - "asymmetric", "RSA", "pkcs1v15crypt-vectors.txt"), - load_pkcs1_vectors - )) + _flatten_pkcs1_examples( + load_vectors_from_file( + os.path.join("asymmetric", "RSA", "pkcs1v15crypt-vectors.txt"), + load_pkcs1_vectors, + ) + ), ) def test_recover_prime_factors(self, vector): private, public, example = vector p, q = rsa.rsa_recover_prime_factors( private["modulus"], private["public_exponent"], - private["private_exponent"] + private["private_exponent"], ) # Unfortunately there is no convention on which prime should be p # and which one q. The function we use always makes p > q, but the @@ -2049,15 +2069,15 @@ class TestRSAPrivateKeySerialization(object): itertools.product( [ serialization.PrivateFormat.TraditionalOpenSSL, - serialization.PrivateFormat.PKCS8 + serialization.PrivateFormat.PKCS8, ], [ b"s", b"longerpassword", b"!*$&(@#$*&($T@%_somesymbols", b"\x01" * 1000, - ] - ) + ], + ), ) def test_private_bytes_encrypted_pem(self, backend, fmt, password): skip_fips_traditional_openssl(backend, fmt) @@ -2065,7 +2085,7 @@ def test_private_bytes_encrypted_pem(self, backend, fmt, password): serialized = key.private_bytes( serialization.Encoding.PEM, fmt, - serialization.BestAvailableEncryption(password) + serialization.BestAvailableEncryption(password), ) loaded_key = serialization.load_pem_private_key( serialized, password, backend @@ -2081,7 +2101,7 @@ def test_private_bytes_encrypted_pem(self, backend, fmt, password): (serialization.Encoding.DER, serialization.PrivateFormat.Raw), (serialization.Encoding.Raw, serialization.PrivateFormat.Raw), (serialization.Encoding.X962, serialization.PrivateFormat.PKCS8), - ] + ], ) def test_private_bytes_rejects_invalid(self, encoding, fmt, backend): key = RSA_KEY_2048.private_key(backend) @@ -2094,15 +2114,15 @@ def test_private_bytes_rejects_invalid(self, encoding, fmt, backend): [serialization.PrivateFormat.PKCS8, b"s"], [serialization.PrivateFormat.PKCS8, b"longerpassword"], [serialization.PrivateFormat.PKCS8, b"!*$&(@#$*&($T@%_somesymbol"], - [serialization.PrivateFormat.PKCS8, b"\x01" * 1000] - ] + [serialization.PrivateFormat.PKCS8, b"\x01" * 1000], + ], ) def test_private_bytes_encrypted_der(self, backend, fmt, password): key = RSA_KEY_2048.private_key(backend) serialized = key.private_bytes( serialization.Encoding.DER, fmt, - serialization.BestAvailableEncryption(password) + serialization.BestAvailableEncryption(password), ) loaded_key = serialization.load_der_private_key( serialized, password, backend @@ -2117,27 +2137,28 @@ def test_private_bytes_encrypted_der(self, backend, fmt, password): [ serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL, - serialization.load_pem_private_key + serialization.load_pem_private_key, ], [ serialization.Encoding.DER, serialization.PrivateFormat.TraditionalOpenSSL, - serialization.load_der_private_key + serialization.load_der_private_key, ], [ serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, - serialization.load_pem_private_key + serialization.load_pem_private_key, ], [ serialization.Encoding.DER, serialization.PrivateFormat.PKCS8, - serialization.load_der_private_key + serialization.load_der_private_key, ], - ] + ], ) - def test_private_bytes_unencrypted(self, backend, encoding, fmt, - loader_func): + def test_private_bytes_unencrypted( + self, backend, encoding, fmt, loader_func + ): key = RSA_KEY_2048.private_key(backend) serialized = key.private_bytes( encoding, fmt, serialization.NoEncryption() @@ -2157,17 +2178,17 @@ def test_private_bytes_unencrypted(self, backend, encoding, fmt, os.path.join( "asymmetric", "Traditional_OpenSSL_Serialization", - "testrsa.pem" + "testrsa.pem", ), serialization.Encoding.PEM, - serialization.load_pem_private_key + serialization.load_pem_private_key, ], [ os.path.join("asymmetric", "DER_Serialization", "testrsa.der"), serialization.Encoding.DER, - serialization.load_der_private_key + serialization.load_der_private_key, ], - ] + ], ) def test_private_bytes_traditional_openssl_unencrypted( self, backend, key_path, encoding, loader_func @@ -2179,7 +2200,7 @@ def test_private_bytes_traditional_openssl_unencrypted( serialized = key.private_bytes( encoding, serialization.PrivateFormat.TraditionalOpenSSL, - serialization.NoEncryption() + serialization.NoEncryption(), ) assert serialized == key_bytes @@ -2189,7 +2210,7 @@ def test_private_bytes_traditional_der_encrypted_invalid(self, backend): key.private_bytes( serialization.Encoding.DER, serialization.PrivateFormat.TraditionalOpenSSL, - serialization.BestAvailableEncryption(b"password") + serialization.BestAvailableEncryption(b"password"), ) def test_private_bytes_invalid_encoding(self, backend): @@ -2198,7 +2219,7 @@ def test_private_bytes_invalid_encoding(self, backend): key.private_bytes( "notencoding", serialization.PrivateFormat.PKCS8, - serialization.NoEncryption() + serialization.NoEncryption(), ) def test_private_bytes_invalid_format(self, backend): @@ -2207,7 +2228,7 @@ def test_private_bytes_invalid_format(self, backend): key.private_bytes( serialization.Encoding.PEM, "invalidformat", - serialization.NoEncryption() + serialization.NoEncryption(), ) def test_private_bytes_invalid_encryption_algorithm(self, backend): @@ -2216,7 +2237,7 @@ def test_private_bytes_invalid_encryption_algorithm(self, backend): key.private_bytes( serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL, - "notanencalg" + "notanencalg", ) def test_private_bytes_unsupported_encryption_type(self, backend): @@ -2225,7 +2246,7 @@ def test_private_bytes_unsupported_encryption_type(self, backend): key.private_bytes( serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL, - DummyKeySerializationEncryption() + DummyKeySerializationEncryption(), ) @@ -2240,30 +2261,34 @@ class TestRSAPEMPublicKeySerialization(object): serialization.load_pem_public_key, serialization.Encoding.PEM, serialization.PublicFormat.PKCS1, - ), ( + ), + ( os.path.join("asymmetric", "public", "PKCS1", "rsa.pub.der"), serialization.load_der_public_key, serialization.Encoding.DER, serialization.PublicFormat.PKCS1, - ), ( + ), + ( os.path.join("asymmetric", "PKCS8", "unenc-rsa-pkcs8.pub.pem"), serialization.load_pem_public_key, serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo, - ), ( + ), + ( os.path.join( "asymmetric", "DER_Serialization", - "unenc-rsa-pkcs8.pub.der" + "unenc-rsa-pkcs8.pub.der", ), serialization.load_der_public_key, serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo, - ) - ] + ), + ], ) - def test_public_bytes_match(self, key_path, loader_func, encoding, format, - backend): + def test_public_bytes_match( + self, key_path, loader_func, encoding, format, backend + ): key_bytes = load_vectors_from_file( key_path, lambda pemfile: pemfile.read(), mode="rb" ) @@ -2274,7 +2299,8 @@ def test_public_bytes_match(self, key_path, loader_func, encoding, format, def test_public_bytes_openssh(self, backend): key_bytes = load_vectors_from_file( os.path.join("asymmetric", "public", "PKCS1", "rsa.pub.pem"), - lambda pemfile: pemfile.read(), mode="rb" + lambda pemfile: pemfile.read(), + mode="rb", ) key = serialization.load_pem_public_key(key_bytes, backend) @@ -2322,22 +2348,25 @@ def test_public_bytes_invalid_format(self, backend): [ ( serialization.Encoding.Raw, - serialization.PublicFormat.SubjectPublicKeyInfo + serialization.PublicFormat.SubjectPublicKeyInfo, ), (serialization.Encoding.Raw, serialization.PublicFormat.PKCS1), - ] + list(itertools.product( - [ - serialization.Encoding.Raw, - serialization.Encoding.X962, - serialization.Encoding.PEM, - serialization.Encoding.DER - ], - [ - serialization.PublicFormat.Raw, - serialization.PublicFormat.UncompressedPoint, - serialization.PublicFormat.CompressedPoint - ] - )) + ] + + list( + itertools.product( + [ + serialization.Encoding.Raw, + serialization.Encoding.X962, + serialization.Encoding.PEM, + serialization.Encoding.DER, + ], + [ + serialization.PublicFormat.Raw, + serialization.PublicFormat.UncompressedPoint, + serialization.PublicFormat.CompressedPoint, + ], + ) + ), ) def test_public_bytes_rejects_invalid(self, encoding, fmt, backend): key = RSA_KEY_2048.private_key(backend).public_key() diff --git a/tests/hazmat/primitives/test_scrypt.py b/tests/hazmat/primitives/test_scrypt.py index 8f3a14edc569..52e7e153802a 100644 --- a/tests/hazmat/primitives/test_scrypt.py +++ b/tests/hazmat/primitives/test_scrypt.py @@ -10,7 +10,9 @@ import pytest from cryptography.exceptions import ( - AlreadyFinalized, InvalidKey, UnsupportedAlgorithm + AlreadyFinalized, + InvalidKey, + UnsupportedAlgorithm, ) from cryptography.hazmat.backends.interfaces import ScryptBackend from cryptography.hazmat.primitives.kdf.scrypt import Scrypt, _MEM_LIMIT @@ -18,7 +20,8 @@ from tests.utils import load_nist_vectors, load_vectors_from_file vectors = load_vectors_from_file( - os.path.join("KDF", "scrypt.txt"), load_nist_vectors) + os.path.join("KDF", "scrypt.txt"), load_nist_vectors +) def _skip_if_memory_limited(memory_limit, params): @@ -29,8 +32,10 @@ def _skip_if_memory_limited(memory_limit, params): vlen = 32 * int(params["r"]) * (int(params["n"]) + 2) * 4 memory_required = blen + vlen if memory_limit < memory_required: - pytest.skip("Test exceeds Scrypt memory limit. " - "This is likely a 32-bit platform.") + pytest.skip( + "Test exceeds Scrypt memory limit. " + "This is likely a 32-bit platform." + ) def test_memory_limit_skip(): @@ -53,8 +58,14 @@ def test_derive(self, backend, params): salt = params["salt"] derived_key = params["derived_key"] - scrypt = Scrypt(salt, length, work_factor, block_size, - parallelization_factor, backend) + scrypt = Scrypt( + salt, + length, + work_factor, + block_size, + parallelization_factor, + backend, + ) assert binascii.hexlify(scrypt.derive(password)) == derived_key def test_unsupported_backend(self): @@ -66,8 +77,14 @@ def test_unsupported_backend(self): backend = object() with pytest.raises(UnsupportedAlgorithm): - Scrypt(salt, length, work_factor, block_size, - parallelization_factor, backend) + Scrypt( + salt, + length, + work_factor, + block_size, + parallelization_factor, + backend, + ) def test_salt_not_bytes(self, backend): work_factor = 1024 @@ -77,8 +94,14 @@ def test_salt_not_bytes(self, backend): salt = 1 with pytest.raises(TypeError): - Scrypt(salt, length, work_factor, block_size, - parallelization_factor, backend) + Scrypt( + salt, + length, + work_factor, + block_size, + parallelization_factor, + backend, + ) def test_scrypt_malloc_failure(self, backend): password = b"NaCl" @@ -88,8 +111,14 @@ def test_scrypt_malloc_failure(self, backend): length = 64 salt = b"NaCl" - scrypt = Scrypt(salt, length, work_factor, block_size, - parallelization_factor, backend) + scrypt = Scrypt( + salt, + length, + work_factor, + block_size, + parallelization_factor, + backend, + ) with pytest.raises(MemoryError): scrypt.derive(password) @@ -102,8 +131,14 @@ def test_password_not_bytes(self, backend): length = 64 salt = b"NaCl" - scrypt = Scrypt(salt, length, work_factor, block_size, - parallelization_factor, backend) + scrypt = Scrypt( + salt, + length, + work_factor, + block_size, + parallelization_factor, + backend, + ) with pytest.raises(TypeError): scrypt.derive(password) @@ -116,10 +151,16 @@ def test_buffer_protocol(self, backend): length = 10 salt = b"NaCl" - scrypt = Scrypt(salt, length, work_factor, block_size, - parallelization_factor, backend) + scrypt = Scrypt( + salt, + length, + work_factor, + block_size, + parallelization_factor, + backend, + ) - assert scrypt.derive(password) == b'\xf4\x92\x86\xb2\x06\x0c\x848W\x87' + assert scrypt.derive(password) == b"\xf4\x92\x86\xb2\x06\x0c\x848W\x87" @pytest.mark.parametrize("params", vectors) def test_verify(self, backend, params): @@ -132,8 +173,14 @@ def test_verify(self, backend, params): salt = params["salt"] derived_key = params["derived_key"] - scrypt = Scrypt(salt, length, work_factor, block_size, - parallelization_factor, backend) + scrypt = Scrypt( + salt, + length, + work_factor, + block_size, + parallelization_factor, + backend, + ) assert scrypt.verify(password, binascii.unhexlify(derived_key)) is None def test_invalid_verify(self, backend): @@ -145,8 +192,14 @@ def test_invalid_verify(self, backend): salt = b"NaCl" derived_key = b"fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e773" - scrypt = Scrypt(salt, length, work_factor, block_size, - parallelization_factor, backend) + scrypt = Scrypt( + salt, + length, + work_factor, + block_size, + parallelization_factor, + backend, + ) with pytest.raises(InvalidKey): scrypt.verify(password, binascii.unhexlify(derived_key)) @@ -159,8 +212,14 @@ def test_already_finalized(self, backend): length = 64 salt = b"NaCl" - scrypt = Scrypt(salt, length, work_factor, block_size, - parallelization_factor, backend) + scrypt = Scrypt( + salt, + length, + work_factor, + block_size, + parallelization_factor, + backend, + ) scrypt.derive(password) with pytest.raises(AlreadyFinalized): scrypt.derive(password) diff --git a/tests/hazmat/primitives/test_seed.py b/tests/hazmat/primitives/test_seed.py index 2d03d774948a..66da97836a0a 100644 --- a/tests/hazmat/primitives/test_seed.py +++ b/tests/hazmat/primitives/test_seed.py @@ -46,7 +46,7 @@ class TestSEEDModeCBC(object): os.path.join("ciphers", "SEED"), ["rfc-4196.txt"], lambda key, **kwargs: algorithms.SEED(binascii.unhexlify((key))), - lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv)) + lambda iv, **kwargs: modes.CBC(binascii.unhexlify(iv)), ) @@ -63,7 +63,7 @@ class TestSEEDModeOFB(object): os.path.join("ciphers", "SEED"), ["seed-ofb.txt"], lambda key, **kwargs: algorithms.SEED(binascii.unhexlify((key))), - lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv)) + lambda iv, **kwargs: modes.OFB(binascii.unhexlify(iv)), ) @@ -80,5 +80,5 @@ class TestSEEDModeCFB(object): os.path.join("ciphers", "SEED"), ["seed-cfb.txt"], lambda key, **kwargs: algorithms.SEED(binascii.unhexlify((key))), - lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)) + lambda iv, **kwargs: modes.CFB(binascii.unhexlify(iv)), ) diff --git a/tests/hazmat/primitives/test_serialization.py b/tests/hazmat/primitives/test_serialization.py index 44f5cec6a507..46694c64852c 100644 --- a/tests/hazmat/primitives/test_serialization.py +++ b/tests/hazmat/primitives/test_serialization.py @@ -15,26 +15,44 @@ from cryptography.exceptions import UnsupportedAlgorithm, _Reasons from cryptography.hazmat.backends.interfaces import ( - DERSerializationBackend, DSABackend, EllipticCurveBackend, - PEMSerializationBackend, RSABackend + DERSerializationBackend, + DSABackend, + EllipticCurveBackend, + PEMSerializationBackend, + RSABackend, ) from cryptography.hazmat.primitives.asymmetric import ( - dsa, ec, ed25519, ed448, rsa, x25519, x448 + dsa, + ec, + ed25519, + ed448, + rsa, + x25519, + x448, ) from cryptography.hazmat.primitives.serialization import ( - BestAvailableEncryption, Encoding, NoEncryption, - PrivateFormat, PublicFormat, - load_der_parameters, load_der_private_key, - load_der_public_key, load_pem_parameters, load_pem_private_key, + BestAvailableEncryption, + Encoding, + NoEncryption, + PrivateFormat, + PublicFormat, + load_der_parameters, + load_der_private_key, + load_der_public_key, + load_pem_parameters, + load_pem_private_key, load_pem_public_key, - load_ssh_private_key, load_ssh_public_key, ssh, + load_ssh_private_key, + load_ssh_public_key, + ssh, ) from .test_ec import _skip_curve_unsupported from .utils import ( - _check_dsa_private_numbers, _check_rsa_private_numbers, - load_vectors_from_file + _check_dsa_private_numbers, + _check_rsa_private_numbers, + load_vectors_from_file, ) from ...doubles import DummyKeySerializationEncryption from ...utils import raises_unsupported_algorithm @@ -57,12 +75,13 @@ class TestBufferProtocolSerialization(object): (["DER_Serialization", "enc2-rsa-pkcs8.der"], bytearray(b"baz")), (["DER_Serialization", "unenc-rsa-pkcs8.der"], None), (["DER_Serialization", "testrsa.der"], None), - ] + ], ) def test_load_der_rsa_private_key(self, key_path, password, backend): data = load_vectors_from_file( os.path.join("asymmetric", *key_path), - lambda derfile: derfile.read(), mode="rb" + lambda derfile: derfile.read(), + mode="rb", ) key = load_der_private_key(bytearray(data), password, backend) assert key @@ -75,22 +94,23 @@ def test_load_der_rsa_private_key(self, key_path, password, backend): [ ( ["PEM_Serialization", "rsa_private_key.pem"], - bytearray(b"123456") + bytearray(b"123456"), ), (["PKCS8", "unenc-rsa-pkcs8.pem"], None), (["PKCS8", "enc-rsa-pkcs8.pem"], bytearray(b"foobar")), (["PKCS8", "enc2-rsa-pkcs8.pem"], bytearray(b"baz")), ( ["Traditional_OpenSSL_Serialization", "key1.pem"], - bytearray(b"123456") + bytearray(b"123456"), ), - ] + ], ) def test_load_pem_rsa_private_key(self, key_path, password, backend): _skip_fips_format(key_path, password, backend) data = load_vectors_from_file( os.path.join("asymmetric", *key_path), - lambda pemfile: pemfile.read(), mode="rb" + lambda pemfile: pemfile.read(), + mode="rb", ) key = load_pem_private_key(bytearray(data), password, backend) assert key @@ -108,7 +128,7 @@ class TestDERSerialization(object): (["DER_Serialization", "enc2-rsa-pkcs8.der"], b"baz"), (["DER_Serialization", "unenc-rsa-pkcs8.der"], None), (["DER_Serialization", "testrsa.der"], None), - ] + ], ) def test_load_der_rsa_private_key(self, key_path, password, backend): key = load_vectors_from_file( @@ -116,7 +136,7 @@ def test_load_der_rsa_private_key(self, key_path, password, backend): lambda derfile: load_der_private_key( derfile.read(), password, backend ), - mode="rb" + mode="rb", ) assert key assert isinstance(key, rsa.RSAPrivateKey) @@ -130,7 +150,7 @@ def test_load_der_rsa_private_key(self, key_path, password, backend): (["DER_Serialization", "dsa.1024.der"], None), (["DER_Serialization", "dsa.2048.der"], None), (["DER_Serialization", "dsa.3072.der"], None), - ] + ], ) def test_load_der_dsa_private_key(self, key_path, password, backend): key = load_vectors_from_file( @@ -138,17 +158,14 @@ def test_load_der_dsa_private_key(self, key_path, password, backend): lambda derfile: load_der_private_key( derfile.read(), password, backend ), - mode="rb" + mode="rb", ) assert key assert isinstance(key, dsa.DSAPrivateKey) _check_dsa_private_numbers(key.private_numbers()) @pytest.mark.parametrize( - "key_path", - [ - ["DER_Serialization", "enc-rsa-pkcs8.der"], - ] + "key_path", [["DER_Serialization", "enc-rsa-pkcs8.der"]] ) @pytest.mark.requires_backend_interface(interface=RSABackend) def test_password_not_bytes(self, key_path, backend): @@ -161,7 +178,7 @@ def test_password_not_bytes(self, key_path, backend): lambda derfile: load_der_private_key( derfile.read(), password, backend ), - mode="rb" + mode="rb", ) @pytest.mark.parametrize( @@ -169,7 +186,7 @@ def test_password_not_bytes(self, key_path, backend): [ (["DER_Serialization", "ec_private_key.der"], None), (["DER_Serialization", "ec_private_key_encrypted.der"], b"123456"), - ] + ], ) @pytest.mark.requires_backend_interface(interface=EllipticCurveBackend) def test_load_der_ec_private_key(self, key_path, password, backend): @@ -179,7 +196,7 @@ def test_load_der_ec_private_key(self, key_path, password, backend): lambda derfile: load_der_private_key( derfile.read(), password, backend ), - mode="rb" + mode="rb", ) assert key @@ -188,10 +205,7 @@ def test_load_der_ec_private_key(self, key_path, password, backend): assert key.curve.key_size == 256 @pytest.mark.parametrize( - "key_path", - [ - ["DER_Serialization", "enc-rsa-pkcs8.der"], - ] + "key_path", [["DER_Serialization", "enc-rsa-pkcs8.der"]] ) @pytest.mark.requires_backend_interface(interface=RSABackend) def test_wrong_password(self, key_path, backend): @@ -204,14 +218,11 @@ def test_wrong_password(self, key_path, backend): lambda derfile: load_der_private_key( derfile.read(), password, backend ), - mode="rb" + mode="rb", ) @pytest.mark.parametrize( - "key_path", - [ - ["DER_Serialization", "unenc-rsa-pkcs8.der"] - ] + "key_path", [["DER_Serialization", "unenc-rsa-pkcs8.der"]] ) @pytest.mark.requires_backend_interface(interface=RSABackend) def test_unused_password(self, key_path, backend): @@ -224,17 +235,14 @@ def test_unused_password(self, key_path, backend): lambda derfile: load_der_private_key( derfile.read(), password, backend ), - mode="rb" + mode="rb", ) @pytest.mark.parametrize( ("key_path", "password"), itertools.product( - [ - ["DER_Serialization", "enc-rsa-pkcs8.der"], - ], - [b"", None] - ) + [["DER_Serialization", "enc-rsa-pkcs8.der"]], [b"", None] + ), ) @pytest.mark.requires_backend_interface(interface=RSABackend) def test_missing_password(self, key_path, password, backend): @@ -246,16 +254,14 @@ def test_missing_password(self, key_path, password, backend): lambda derfile: load_der_private_key( derfile.read(), password, backend ), - mode="rb" + mode="rb", ) def test_wrong_format(self, backend): key_data = b"---- NOT A KEY ----\n" with pytest.raises(ValueError): - load_der_private_key( - key_data, None, backend - ) + load_der_private_key(key_data, None, backend) with pytest.raises(ValueError): load_der_private_key( @@ -264,7 +270,8 @@ def test_wrong_format(self, backend): def test_corrupt_der_pkcs8(self, backend): # unenc-rsa-pkcs8 with a bunch of data missing. - key_data = textwrap.dedent("""\ + key_data = textwrap.dedent( + """\ MIICdQIBADALBgkqhkiG9w0BAQEEggJhMIICXQIBAAKBgQC7JHoJfg6yNzLMOWet 8Z49a4KD0dCspMAYvo2YAMB7/wdEycocujbhJ2n/seONi+5XqTqqFkM5VBl8rmkk FPZk/7x0xmdsTPECSWnHK+HhoaNDFPR3j8jQhVo1laxiqcEhAHegi5cwtFosuJAv @@ -278,13 +285,12 @@ def test_corrupt_der_pkcs8(self, backend): z+KOpdpPRR5TQmbEMEspjsFpFymMiuYPgmihQbO2cJl1qScY5OkCQQCJ6m5tcN8l Xxg/SNpjEIv+qAyUD96XVlOJlOIeLHQ8kYE0C6ZA+MsqYIzgAreJk88Yn0lU/X0/ mu/UpE/BRZmR - """).encode() + """ + ).encode() bad_der = base64.b64decode(b"".join(key_data.splitlines())) with pytest.raises(ValueError): - load_der_private_key( - bad_der, None, backend - ) + load_der_private_key(bad_der, None, backend) with pytest.raises(ValueError): load_der_private_key( @@ -293,14 +299,16 @@ def test_corrupt_der_pkcs8(self, backend): def test_corrupt_traditional_format_der(self, backend): # privkey with a bunch of data missing. - key_data = textwrap.dedent("""\ + key_data = textwrap.dedent( + """\ MIIBPAIBAAJBAKrbeqkuRk8VcRmWFmtP+LviMB3+6dizWW3DwaffznyHGAFwUJ/I Tv0XtbsCyl3QoyKGhrOAy3RvPK5M38iuXT0CAwEAAQJAZ3cnzaHXM/bxGaR5CR1R rD1qFBAVfoQFiOH9uPJgMaoAuoQEisPHVcZDKcOv4wEg6/TInAIXBnEigtqvRzuy mvcpHZwQJdmdHHkGKAs37Dfxi67HbkUCIQCeZGliHXFa071Fp06ZeWlR2ADonTZz rJBhdTe0v5pCeQIhAIZfkiGgGBX4cIuuckzEm43g9WMUjxP/0GlK39vIyihxAiEA mymehFRT0MvqW5xAKAx7Pgkt8HVKwVhc2LwGKHE0DZM= - """).encode() + """ + ).encode() bad_der = base64.b64decode(b"".join(key_data.splitlines())) with pytest.raises(ValueError): @@ -315,20 +323,20 @@ def test_corrupt_traditional_format_der(self, backend): "key_file", [ os.path.join( - "asymmetric", "DER_Serialization", "unenc-rsa-pkcs8.pub.der"), + "asymmetric", "DER_Serialization", "unenc-rsa-pkcs8.pub.der" + ), os.path.join( - "asymmetric", "DER_Serialization", "rsa_public_key.der"), + "asymmetric", "DER_Serialization", "rsa_public_key.der" + ), os.path.join("asymmetric", "public", "PKCS1", "rsa.pub.der"), - ] + ], ) @pytest.mark.requires_backend_interface(interface=RSABackend) def test_load_der_rsa_public_key(self, key_file, backend): key = load_vectors_from_file( key_file, - lambda derfile: load_der_public_key( - derfile.read(), backend - ), - mode="rb" + lambda derfile: load_der_public_key(derfile.read(), backend), + mode="rb", ) assert key assert isinstance(key, rsa.RSAPublicKey) @@ -343,19 +351,19 @@ def test_load_der_invalid_public_key(self, backend): "key_file", [ os.path.join( - "asymmetric", "DER_Serialization", "unenc-dsa-pkcs8.pub.der"), + "asymmetric", "DER_Serialization", "unenc-dsa-pkcs8.pub.der" + ), os.path.join( - "asymmetric", "DER_Serialization", "dsa_public_key.der"), - ] + "asymmetric", "DER_Serialization", "dsa_public_key.der" + ), + ], ) @pytest.mark.requires_backend_interface(interface=DSABackend) def test_load_der_dsa_public_key(self, key_file, backend): key = load_vectors_from_file( key_file, - lambda derfile: load_der_public_key( - derfile.read(), backend - ), - mode="rb" + lambda derfile: load_der_public_key(derfile.read(), backend), + mode="rb", ) assert key assert isinstance(key, dsa.DSAPublicKey) @@ -365,12 +373,10 @@ def test_load_ec_public_key(self, backend): _skip_curve_unsupported(backend, ec.SECP256R1()) key = load_vectors_from_file( os.path.join( - "asymmetric", "DER_Serialization", - "ec_public_key.der"), - lambda derfile: load_der_public_key( - derfile.read(), backend + "asymmetric", "DER_Serialization", "ec_public_key.der" ), - mode="rb" + lambda derfile: load_der_public_key(derfile.read(), backend), + mode="rb", ) assert key assert isinstance(key, ec.EllipticCurvePublicKey) @@ -381,9 +387,7 @@ def test_wrong_parameters_format(self, backend): param_data = b"---- NOT A KEY ----\n" with pytest.raises(ValueError): - load_der_parameters( - param_data, backend - ) + load_der_parameters(param_data, backend) @pytest.mark.requires_backend_interface(interface=PEMSerializationBackend) @@ -408,9 +412,11 @@ class TestPEMSerialization(object): (["Traditional_OpenSSL_Serialization", "key1.pem"], b"123456"), (["Traditional_OpenSSL_Serialization", "key2.pem"], b"a123456"), (["Traditional_OpenSSL_Serialization", "testrsa.pem"], None), - (["Traditional_OpenSSL_Serialization", "testrsa-encrypted.pem"], - b"password"), - ] + ( + ["Traditional_OpenSSL_Serialization", "testrsa-encrypted.pem"], + b"password", + ), + ], ) def test_load_pem_rsa_private_key(self, key_file, password, backend): _skip_fips_format(key_file, password, backend) @@ -418,7 +424,7 @@ def test_load_pem_rsa_private_key(self, key_file, password, backend): os.path.join("asymmetric", *key_file), lambda pemfile: load_pem_private_key( pemfile.read().encode(), password, backend - ) + ), ) assert key @@ -433,7 +439,7 @@ def test_load_pem_rsa_private_key(self, key_file, password, backend): (["Traditional_OpenSSL_Serialization", "dsa.3072.pem"], None), (["PKCS8", "unenc-dsa-pkcs8.pem"], None), (["PEM_Serialization", "dsa_private_key.pem"], b"123456"), - ] + ], ) def test_load_dsa_private_key(self, key_path, password, backend): _skip_fips_format(key_path, password, backend) @@ -441,7 +447,7 @@ def test_load_dsa_private_key(self, key_path, password, backend): os.path.join("asymmetric", *key_path), lambda pemfile: load_pem_private_key( pemfile.read().encode(), password, backend - ) + ), ) assert key assert isinstance(key, dsa.DSAPrivateKey) @@ -454,7 +460,7 @@ def test_load_dsa_private_key(self, key_path, password, backend): (["PKCS8", "ec_private_key_encrypted.pem"], b"123456"), (["PEM_Serialization", "ec_private_key.pem"], None), (["PEM_Serialization", "ec_private_key_encrypted.pem"], b"123456"), - ] + ], ) @pytest.mark.requires_backend_interface(interface=EllipticCurveBackend) def test_load_pem_ec_private_key(self, key_path, password, backend): @@ -464,7 +470,7 @@ def test_load_pem_ec_private_key(self, key_path, password, backend): os.path.join("asymmetric", *key_path), lambda pemfile: load_pem_private_key( pemfile.read().encode(), password, backend - ) + ), ) assert key @@ -477,16 +483,17 @@ def test_load_pem_ec_private_key(self, key_path, password, backend): [ os.path.join("asymmetric", "PKCS8", "unenc-rsa-pkcs8.pub.pem"), os.path.join( - "asymmetric", "PEM_Serialization", "rsa_public_key.pem"), + "asymmetric", "PEM_Serialization", "rsa_public_key.pem" + ), os.path.join("asymmetric", "public", "PKCS1", "rsa.pub.pem"), - ] + ], ) def test_load_pem_rsa_public_key(self, key_file, backend): key = load_vectors_from_file( key_file, lambda pemfile: load_pem_public_key( pemfile.read().encode(), backend - ) + ), ) assert key assert isinstance(key, rsa.RSAPublicKey) @@ -498,16 +505,16 @@ def test_load_pem_rsa_public_key(self, key_file, backend): [ os.path.join("asymmetric", "PKCS8", "unenc-dsa-pkcs8.pub.pem"), os.path.join( - "asymmetric", "PEM_Serialization", - "dsa_public_key.pem"), - ] + "asymmetric", "PEM_Serialization", "dsa_public_key.pem" + ), + ], ) def test_load_pem_dsa_public_key(self, key_file, backend): key = load_vectors_from_file( key_file, lambda pemfile: load_pem_public_key( pemfile.read().encode(), backend - ) + ), ) assert key assert isinstance(key, dsa.DSAPublicKey) @@ -517,11 +524,11 @@ def test_load_ec_public_key(self, backend): _skip_curve_unsupported(backend, ec.SECP256R1()) key = load_vectors_from_file( os.path.join( - "asymmetric", "PEM_Serialization", - "ec_public_key.pem"), + "asymmetric", "PEM_Serialization", "ec_public_key.pem" + ), lambda pemfile: load_pem_public_key( pemfile.read().encode(), backend - ) + ), ) assert key assert isinstance(key, ec.EllipticCurvePublicKey) @@ -534,52 +541,53 @@ def test_load_ec_public_key(self, backend): def test_rsa_traditional_encrypted_values(self, backend): pkey = load_vectors_from_file( os.path.join( - "asymmetric", "Traditional_OpenSSL_Serialization", "key1.pem"), + "asymmetric", "Traditional_OpenSSL_Serialization", "key1.pem" + ), lambda pemfile: load_pem_private_key( pemfile.read().encode(), b"123456", backend - ) + ), ) assert pkey numbers = pkey.private_numbers() assert numbers.p == int( "fb7d316fc51531b36d93adaefaf52db6ad5beb793d37c4cf9dfc1ddd17cfbafb", - 16 + 16, ) assert numbers.q == int( "df98264e646de9a0fbeab094e31caad5bc7adceaaae3c800ca0275dd4bb307f5", - 16 + 16, ) assert numbers.d == int( "db4848c36f478dd5d38f35ae519643b6b810d404bcb76c00e44015e56ca1cab0" "7bb7ae91f6b4b43fcfc82a47d7ed55b8c575152116994c2ce5325ec24313b911", - 16 + 16, ) assert numbers.dmp1 == int( "ce997f967192c2bcc3853186f1559fd355c190c58ddc15cbf5de9b6df954c727", - 16 + 16, ) assert numbers.dmq1 == int( "b018a57ab20ffaa3862435445d863369b852cf70a67c55058213e3fe10e3848d", - 16 + 16, ) assert numbers.iqmp == int( "6a8d830616924f5cf2d1bc1973f97fde6b63e052222ac7be06aa2532d10bac76", - 16 + 16, ) assert numbers.public_numbers.e == 65537 assert numbers.public_numbers.n == int( "dba786074f2f0350ce1d99f5aed5b520cfe0deb5429ec8f2a88563763f566e77" "9814b7c310e5326edae31198eed439b845dd2db99eaa60f5c16a43f4be6bcf37", - 16 + 16, ) @pytest.mark.parametrize( "key_path", [ ["Traditional_OpenSSL_Serialization", "testrsa.pem"], - ["PKCS8", "unenc-rsa-pkcs8.pem"] - ] + ["PKCS8", "unenc-rsa-pkcs8.pem"], + ], ) def test_unused_password(self, key_path, backend): key_file = os.path.join("asymmetric", *key_path) @@ -590,7 +598,7 @@ def test_unused_password(self, key_path, backend): key_file, lambda pemfile: load_pem_private_key( pemfile.read().encode(), password, backend - ) + ), ) def test_invalid_encoding_with_traditional(self, backend): @@ -602,7 +610,7 @@ def test_invalid_encoding_with_traditional(self, backend): lambda pemfile: load_pem_private_key( pemfile.read(), None, backend ), - mode="rb" + mode="rb", ) for enc in (Encoding.OpenSSH, Encoding.Raw, Encoding.X962): @@ -615,8 +623,8 @@ def test_invalid_encoding_with_traditional(self, backend): "key_path", [ ["Traditional_OpenSSL_Serialization", "testrsa-encrypted.pem"], - ["PKCS8", "enc-rsa-pkcs8.pem"] - ] + ["PKCS8", "enc-rsa-pkcs8.pem"], + ], ) def test_password_not_bytes(self, key_path, backend): key_file = os.path.join("asymmetric", *key_path) @@ -627,15 +635,15 @@ def test_password_not_bytes(self, key_path, backend): key_file, lambda pemfile: load_pem_private_key( pemfile.read().encode(), password, backend - ) + ), ) @pytest.mark.parametrize( "key_path", [ ["Traditional_OpenSSL_Serialization", "testrsa-encrypted.pem"], - ["PKCS8", "enc-rsa-pkcs8.pem"] - ] + ["PKCS8", "enc-rsa-pkcs8.pem"], + ], ) def test_wrong_password(self, key_path, backend): key_file = os.path.join("asymmetric", *key_path) @@ -646,19 +654,18 @@ def test_wrong_password(self, key_path, backend): key_file, lambda pemfile: load_pem_private_key( pemfile.read().encode(), password, backend - ) + ), ) @pytest.mark.parametrize( ("key_path", "password"), itertools.product( [ - ["Traditional_OpenSSL_Serialization", - "testrsa-encrypted.pem"], + ["Traditional_OpenSSL_Serialization", "testrsa-encrypted.pem"], ["PKCS8", "enc-rsa-pkcs8.pem"], ], - [b"", None] - ) + [b"", None], + ), ) def test_missing_password(self, key_path, password, backend): key_file = os.path.join("asymmetric", *key_path) @@ -668,16 +675,14 @@ def test_missing_password(self, key_path, password, backend): key_file, lambda pemfile: load_pem_private_key( pemfile.read().encode(), password, backend - ) + ), ) def test_wrong_private_format(self, backend): key_data = b"---- NOT A KEY ----\n" with pytest.raises(ValueError): - load_pem_private_key( - key_data, None, backend - ) + load_pem_private_key(key_data, None, backend) with pytest.raises(ValueError): load_pem_private_key( @@ -698,7 +703,8 @@ def test_wrong_parameters_format(self, backend): def test_corrupt_traditional_format(self, backend): # privkey.pem with a bunch of data missing. - key_data = textwrap.dedent("""\ + key_data = textwrap.dedent( + """\ -----BEGIN RSA PRIVATE KEY----- MIIBPAIBAAJBAKrbeqkuRk8VcRmWFmtP+LviMB3+6dizWW3DwaffznyHGAFwUJ/I Tv0XtbsCyl3QoyKGhrOAy3RvPK5M38iuXT0CAwEAAQJAZ3cnzaHXM/bxGaR5CR1R @@ -707,12 +713,11 @@ def test_corrupt_traditional_format(self, backend): rJBhdTe0v5pCeQIhAIZfkiGgGBX4cIuuckzEm43g9WMUjxP/0GlK39vIyihxAiEA mymehFRT0MvqW5xAKAx7Pgkt8HVKwVhc2LwGKHE0DZM= -----END RSA PRIVATE KEY----- - """).encode() + """ + ).encode() with pytest.raises(ValueError): - load_pem_private_key( - key_data, None, backend - ) + load_pem_private_key(key_data, None, backend) with pytest.raises(ValueError): load_pem_private_key( @@ -721,7 +726,8 @@ def test_corrupt_traditional_format(self, backend): def test_traditional_encrypted_corrupt_format(self, backend): # privkey.pem with a single bit flipped - key_data = textwrap.dedent("""\ + key_data = textwrap.dedent( + """\ -----BEGIN RSA PRIVATE KEY----- Proc-Type: <,ENCRYPTED DEK-Info: AES-128-CBC,5E22A2BD85A653FB7A3ED20DE84F54CD @@ -734,22 +740,20 @@ def test_traditional_encrypted_corrupt_format(self, backend): 5A295jD9BQp9CY0nNFSsy+qiXWToq2xT3y5zVNEStmN0SCGNaIlUnJzL9IHW+oMI kPmXZMnAYBWeeCF1gf3J3aE5lZInegHNfEI0+J0LazC2aNU5Dg/BNqrmRqKWEIo/ -----END RSA PRIVATE KEY----- - """).encode() + """ + ).encode() password = b"this password is wrong" with pytest.raises(ValueError): - load_pem_private_key( - key_data, None, backend - ) + load_pem_private_key(key_data, None, backend) with pytest.raises(ValueError): - load_pem_private_key( - key_data, password, backend - ) + load_pem_private_key(key_data, password, backend) def test_unsupported_key_encryption(self, backend): - key_data = textwrap.dedent("""\ + key_data = textwrap.dedent( + """\ -----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: FAKE-123,5E22A2BD85A653FB7A3ED20DE84F54CD @@ -762,18 +766,18 @@ def test_unsupported_key_encryption(self, backend): 5A295jD9BQp9CY0nNFSsy+qiXWToq2xT3y5zVNEStmN0SCGNaIlUnJzL9IHW+oMI kPmXZMnAYBWeeCF1gf3J3aE5lZInegHNfEI0+J0LazC2aNU5Dg/BNqrmRqKWEIo/ -----END RSA PRIVATE KEY----- - """).encode() + """ + ).encode() password = b"password" with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_CIPHER): - load_pem_private_key( - key_data, password, backend - ) + load_pem_private_key(key_data, password, backend) def test_corrupt_pkcs8_format(self, backend): # unenc-rsa-pkcs8.pem with a bunch of data missing. - key_data = textwrap.dedent("""\ + key_data = textwrap.dedent( + """\ -----BEGIN PRIVATE KEY----- MIICdQIBADALBgkqhkiG9w0BAQEEggJhMIICXQIBAAKBgQC7JHoJfg6yNzLMOWet 8Z49a4KD0dCspMAYvo2YAMB7/wdEycocujbhJ2n/seONi+5XqTqqFkM5VBl8rmkk @@ -789,12 +793,11 @@ def test_corrupt_pkcs8_format(self, backend): Xxg/SNpjEIv+qAyUD96XVlOJlOIeLHQ8kYE0C6ZA+MsqYIzgAreJk88Yn0lU/X0/ mu/UpE/BRZmR -----END PRIVATE KEY----- - """).encode() + """ + ).encode() with pytest.raises(ValueError): - load_pem_private_key( - key_data, None, backend - ) + load_pem_private_key(key_data, None, backend) with pytest.raises(ValueError): load_pem_private_key( @@ -803,7 +806,8 @@ def test_corrupt_pkcs8_format(self, backend): def test_pks8_encrypted_corrupt_format(self, backend): # enc-rsa-pkcs8.pem with some bits flipped. - key_data = textwrap.dedent("""\ + key_data = textwrap.dedent( + """\ -----BEGIN ENCRYPTED PRIVATE KEY----- MIICojAcBgoqhkiG9w0BDAEDMA4ECHK0M0+QuEL9AgIBIcSCAoDRq+KRY+0XP0tO lwBTzViiXSXoyNnKAZKt5r5K/fGNntv22g/1s/ZNCetrqsJDC5eMUPPacz06jFq/ @@ -821,27 +825,23 @@ def test_pks8_encrypted_corrupt_format(self, backend): 6JLgl8FrvdfjHwIvmSOO1YMNmILBq000Q8WDqyErBDs4hsvtO6VQ4LeqJj6gClX3 qeJNaJFu -----END ENCRYPTED PRIVATE KEY----- - """).encode() + """ + ).encode() password = b"this password is wrong" with pytest.raises(ValueError): - load_pem_private_key( - key_data, None, backend - ) + load_pem_private_key(key_data, None, backend) with pytest.raises(ValueError): - load_pem_private_key( - key_data, password, backend - ) + load_pem_private_key(key_data, password, backend) def test_rsa_pkcs8_encrypted_values(self, backend): pkey = load_vectors_from_file( - os.path.join( - "asymmetric", "PKCS8", "enc-rsa-pkcs8.pem"), + os.path.join("asymmetric", "PKCS8", "enc-rsa-pkcs8.pem"), lambda pemfile: load_pem_private_key( pemfile.read().encode(), b"foobar", backend - ) + ), ) assert pkey @@ -852,7 +852,8 @@ def test_rsa_pkcs8_encrypted_values(self, backend): "376a7fe5b19f95b35ca358ea5c8abd7ae051d49cd2f1e45969a1ae945460" "3c14b278664a0e414ebc8913acb6203626985525e17a600611b028542dd0" "562aad787fb4f1650aa318cdcff751e1b187cbf6785fbe164e9809491b95" - "dd68480567c99b1a57", 16 + "dd68480567c99b1a57", + 16, ) assert numbers.public_numbers.e == 65537 @@ -862,37 +863,43 @@ def test_rsa_pkcs8_encrypted_values(self, backend): "f3d9785c3a2c09e4c8090909fb3721e19a3009ec21221523a729265707a5" "8f13063671c42a4096cad378ef2510cb59e23071489d8893ac4934dd149f" "34f2d094bea57f1c8027c3a77248ac9b91218737d0c3c3dfa7d7829e6977" - "cf7d995688c86c81", 16 + "cf7d995688c86c81", + 16, ) assert numbers.p == int( "00db122ac857b2c0437d7616daa98e597bb75ca9ad3a47a70bec10c10036" "03328794b225c8e3eee6ffd3fd6d2253d28e071fe27d629ab072faa14377" - "ce6118cb67", 16 + "ce6118cb67", + 16, ) assert numbers.q == int( "00df1b8aa8506fcbbbb9d00257f2975e38b33d2698fd0f37e82d7ef38c56" "f21b6ced63c825383782a7115cfcc093300987dbd2853b518d1c8f26382a" - "2d2586d391", 16 + "2d2586d391", + 16, ) assert numbers.dmp1 == int( "00be18aca13e60712fdf5daa85421eb10d86d654b269e1255656194fb0c4" "2dd01a1070ea12c19f5c39e09587af02f7b1a1030d016a9ffabf3b36d699" - "ceaf38d9bf", 16 + "ceaf38d9bf", + 16, ) assert numbers.dmq1 == int( "71aa8978f90a0c050744b77cf1263725b203ac9f730606d8ae1d289dce4a" "28b8d534e9ea347aeb808c73107e583eb80c546d2bddadcdb3c82693a4c1" - "3d863451", 16 + "3d863451", + 16, ) assert numbers.iqmp == int( "136b7b1afac6e6279f71b24217b7083485a5e827d156024609dae39d48a6" "bdb55af2f062cc4a3b077434e6fffad5faa29a2b5dba2bed3e4621e478c0" - "97ccfe7f", 16 + "97ccfe7f", + 16, ) def test_load_pem_dsa_private_key(self, backend): @@ -900,7 +907,7 @@ def test_load_pem_dsa_private_key(self, backend): os.path.join("asymmetric", "PKCS8", "unenc-dsa-pkcs8.pem"), lambda pemfile: load_pem_private_key( pemfile.read().encode(), None, backend - ) + ), ) assert key assert isinstance(key, dsa.DSAPrivateKey) @@ -911,15 +918,14 @@ def test_load_pem_dsa_private_key(self, backend): num = key.private_numbers() pub = num.public_numbers parameter_numbers = pub.parameter_numbers - assert num.x == int("00a535a8e1d0d91beafc8bee1d9b2a3a8de3311203", - 16) + assert num.x == int("00a535a8e1d0d91beafc8bee1d9b2a3a8de3311203", 16) assert pub.y == int( "2b260ea97dc6a12ae932c640e7df3d8ff04a8a05a0324f8d5f1b23f15fa1" "70ff3f42061124eff2586cb11b49a82dcdc1b90fc6a84fb10109cb67db5d" "2da971aeaf17be5e37284563e4c64d9e5fc8480258b319f0de29d54d8350" "70d9e287914d77df81491f4423b62da984eb3f45eb2a29fcea5dae525ac6" "ab6bcce04bfdf5b6", - 16 + 16, ) assert parameter_numbers.p == int( @@ -928,11 +934,12 @@ def test_load_pem_dsa_private_key(self, backend): "071d4dceb2782794ad393cc08a4d4ada7f68d6e839a5fcd34b4e402d82cb" "8a8cb40fec31911bf9bd360b034caacb4c5e947992573c9e90099c1b0f05" "940cabe5d2de49a167", - 16 + 16, ) assert parameter_numbers.q == int( - "00adc0e869b36f0ac013a681fdf4d4899d69820451", 16) + "00adc0e869b36f0ac013a681fdf4d4899d69820451", 16 + ) assert parameter_numbers.g == int( "008c6b4589afa53a4d1048bfc346d1f386ca75521ccf72ddaa251286880e" @@ -940,69 +947,61 @@ def test_load_pem_dsa_private_key(self, backend): "e71141ba324f5b93131929182c88a9fa4062836066cebe74b5c6690c7d10" "1106c240ab7ebd54e4e3301fd086ce6adac922fb2713a2b0887cba13b9bc" "68ce5cfff241cd3246", - 16 + 16, ) @pytest.mark.parametrize( - ("key_file", "password"), - [ - ("bad-oid-dsa-key.pem", None), - ] + ("key_file", "password"), [("bad-oid-dsa-key.pem", None)] ) def test_load_bad_oid_key(self, key_file, password, backend): with pytest.raises(ValueError): load_vectors_from_file( - os.path.join( - "asymmetric", "PKCS8", key_file), + os.path.join("asymmetric", "PKCS8", key_file), lambda pemfile: load_pem_private_key( pemfile.read().encode(), password, backend - ) + ), ) @pytest.mark.parametrize( - ("key_file", "password"), - [ - ("bad-encryption-oid.pem", b"password"), - ] + ("key_file", "password"), [("bad-encryption-oid.pem", b"password")] ) def test_load_bad_encryption_oid_key(self, key_file, password, backend): with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_CIPHER): load_vectors_from_file( - os.path.join( - "asymmetric", "PKCS8", key_file), + os.path.join("asymmetric", "PKCS8", key_file), lambda pemfile: load_pem_private_key( pemfile.read().encode(), password, backend - ) + ), ) @pytest.mark.requires_backend_interface(interface=RSABackend) class TestRSASSHSerialization(object): def test_load_ssh_public_key_unsupported(self, backend): - ssh_key = b'ecdsa-sha2-junk AAAAE2VjZHNhLXNoYTItbmlzdHAyNTY=' + ssh_key = b"ecdsa-sha2-junk AAAAE2VjZHNhLXNoYTItbmlzdHAyNTY=" with pytest.raises(UnsupportedAlgorithm): load_ssh_public_key(ssh_key, backend) def test_load_ssh_public_key_bad_format(self, backend): - ssh_key = b'ssh-rsa not-a-real-key' + ssh_key = b"ssh-rsa not-a-real-key" with pytest.raises(ValueError): load_ssh_public_key(ssh_key, backend) def test_load_ssh_public_key_rsa_too_short(self, backend): - ssh_key = b'ssh-rsa' + ssh_key = b"ssh-rsa" with pytest.raises(ValueError): load_ssh_public_key(ssh_key, backend) def test_load_ssh_public_key_truncated_int(self, backend): - ssh_key = b'ssh-rsa AAAAB3NzaC1yc2EAAAA=' + ssh_key = b"ssh-rsa AAAAB3NzaC1yc2EAAAA=" with pytest.raises(ValueError): load_ssh_public_key(ssh_key, backend) - ssh_key = b'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAACKr+IHXo' + ssh_key = b"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAACKr+IHXo" with pytest.raises(ValueError): load_ssh_public_key(ssh_key, backend) @@ -1071,16 +1070,18 @@ def test_load_ssh_public_key_rsa(self, backend): expected_e = 0x10001 expected_n = int( - '00C3BBF5D13F59322BA0A0B77EA0B6CF570241628AE24B5BA454D' - '23DCA295652B3523B67752653DFFD69587FAD9578DD6406F23691' - 'EA491C3F8B2D391D0312D9653C303B651067ADF887A5241843CEF' - '8019680A088E092FEC305FB04EA070340BB9BD0F1635B2AD84142' - '61B4E2D010ABD8FC6D2FB768912F78EE6B05A60857532B75B75EF' - 'C007601A4EF58BA947B7E75E38F3443CDD87E7C138A1DAD9D9FB3' - '19FF69DA43A9F6F6B0CD243F042CD1A5AFAEB286BD46AEB2D922B' - 'D01385D6892167074A0907F94A2BF08A54ABB2FFFFC89920861D0' - '46F8706AB88DDADBD9E8204D48B87789081E074024C8996783B31' - '7076A98ABF0A2D8550EAF2097D8CCC7BE76EF', 16) + "00C3BBF5D13F59322BA0A0B77EA0B6CF570241628AE24B5BA454D" + "23DCA295652B3523B67752653DFFD69587FAD9578DD6406F23691" + "EA491C3F8B2D391D0312D9653C303B651067ADF887A5241843CEF" + "8019680A088E092FEC305FB04EA070340BB9BD0F1635B2AD84142" + "61B4E2D010ABD8FC6D2FB768912F78EE6B05A60857532B75B75EF" + "C007601A4EF58BA947B7E75E38F3443CDD87E7C138A1DAD9D9FB3" + "19FF69DA43A9F6F6B0CD243F042CD1A5AFAEB286BD46AEB2D922B" + "D01385D6892167074A0907F94A2BF08A54ABB2FFFFC89920861D0" + "46F8706AB88DDADBD9E8204D48B87789081E074024C8996783B31" + "7076A98ABF0A2D8550EAF2097D8CCC7BE76EF", + 16, + ) expected = rsa.RSAPublicNumbers(expected_e, expected_n) @@ -1090,7 +1091,7 @@ def test_load_ssh_public_key_rsa(self, backend): @pytest.mark.requires_backend_interface(interface=DSABackend) class TestDSSSSHSerialization(object): def test_load_ssh_public_key_dss_too_short(self, backend): - ssh_key = b'ssh-dss' + ssh_key = b"ssh-dss" with pytest.raises(ValueError): load_ssh_public_key(ssh_key, backend) @@ -1173,14 +1174,16 @@ def test_load_ssh_public_key_dss(self, backend): "96a7032c01cdd8485b5cbfb73a46bb04708f98a18bc88d4c7812b284da8f900" "6e473e89897f9bc9125c69bbfd8ef691c0e76c1c34e6c843b8fe240e6e5aeb3" "13486e5fa917ab1288ff1a6ebcf9dcdeed3c5fc88474e30476f53a5ec816ef6" - "9f4", 16 + "9f4", + 16, ) expected_p = int( "b9b052d7f07630148d4d838b17790ef4f43437238ebebd5032ea483fd7b7902" "5ec3dc65ebd563ab586a633b4344f6acd10af31353bcf29111fa5e3b8d5c1e8" "7befe3c65f9b8be69c740716698c8366c8ef925b9cec1dcd69e73d926b554e2" "b4b6ddd1453eab39ba0f846e1555adcc33c5a8637128c9ed61104a45505a748" - "f6db", 16 + "f6db", + 16, ) expected_q = 1230879958723280233885494314531920096931919647917 expected_g = int( @@ -1188,11 +1191,12 @@ def test_load_ssh_public_key_dss(self, backend): "7bc249b6cf8f5f5c5022afefd4df5bf9d13bbdf182df5af2a5c5d1dc7604185" "7d5b0e4b22b856c300f850a3b00bac394b728755b8b7a56522eefc491573967" "debb5982fc94d6a8c291f758feae63ad769a5621947221522a2dc31d18ede6f" - "b656", 16 + "b656", + 16, ) expected = dsa.DSAPublicNumbers( expected_y, - dsa.DSAParameterNumbers(expected_p, expected_q, expected_g) + dsa.DSAParameterNumbers(expected_p, expected_q, expected_g), ) assert numbers == expected @@ -1213,11 +1217,13 @@ def test_load_ssh_public_key_ecdsa_nist_p256(self, backend): expected_x = int( "44196257377740326295529888716212621920056478823906609851236662550" - "785814128027", 10 + "785814128027", + 10, ) expected_y = int( "12257763433170736656417248739355923610241609728032203358057767672" - "925775019611", 10 + "925775019611", + 10, ) assert key.public_numbers() == ec.EllipticCurvePublicNumbers( @@ -1249,11 +1255,13 @@ def test_load_ssh_public_key_ecdsa_nist_p384(self, backend): expected_x = int( "31541830871345183397582554827482786756220448716666815789487537666" - "592636882822352575507883817901562613492450642523901", 10 + "592636882822352575507883817901562613492450642523901", + 10, ) expected_y = int( "15111413269431823234030344298767984698884955023183354737123929430" - "995703524272335782455051101616329050844273733614670", 10 + "995703524272335782455051101616329050844273733614670", + 10, ) assert key.public_numbers() == ec.EllipticCurvePublicNumbers( @@ -1274,12 +1282,14 @@ def test_load_ssh_public_key_ecdsa_nist_p521(self, backend): expected_x = int( "54124123120178189598842622575230904027376313369742467279346415219" "77809037378785192537810367028427387173980786968395921877911964629" - "142163122798974160187785455", 10 + "142163122798974160187785455", + 10, ) expected_y = int( "16111775122845033200938694062381820957441843014849125660011303579" "15284560361402515564433711416776946492019498546572162801954089916" - "006665939539407104638103918", 10 + "006665939539407104638103918", + 10, ) assert key.public_numbers() == ec.EllipticCurvePublicNumbers( @@ -1328,7 +1338,7 @@ def test_load_ssh_public_key_ecdsa_nist_p256_bad_curve_name(self, backend): @pytest.mark.supported( only_if=lambda backend: backend.ed25519_supported(), - skip_message="Requires OpenSSL with Ed25519 support" + skip_message="Requires OpenSSL with Ed25519 support", ) class TestEd25519SSHSerialization(object): def test_load_ssh_public_key(self, backend): @@ -1338,9 +1348,7 @@ def test_load_ssh_public_key(self, backend): ) key = load_ssh_public_key(ssh_key, backend) assert isinstance(key, ed25519.Ed25519PublicKey) - assert key.public_bytes( - Encoding.Raw, PublicFormat.Raw - ) == ( + assert key.public_bytes(Encoding.Raw, PublicFormat.Raw) == ( b"m\x9f\x82\x99\xa9`\xee\xb5\xa9\xe01\x19\xdd0\x81\x16\x8d\xfc" b"N\x06G\xecV\xbc\x19\xaf\xc6 - """).splitlines() + """ + ).splitlines() vectors = tuple(load_pkcs1_vectors(vector_data)) expected = ( ( { - 'modulus': int( - '495370a1fb18543c16d3631e3163255df62be6eee890d5f25509e4f77' - '8a8ea6fbbbcdf85dff64e0d972003ab3681fbba6dd41fd541829b2e58' - '2de9f2a4a4e0a2d0900bef4753db3cee0ee06c7dfae8b1d53b5953218' - 'f9cceea695b08668edeaadced9463b1d790d5ebf27e9115b46cad4d9a' - '2b8efab0561b0810344739ada0733f', 16), - 'public_exponent': int('10001', 16), - 'private_exponent': int( - '6c66ffe98980c38fcdeab5159898836165f4b4b817c4f6a8d486ee4ea' - '9130fe9b9092bd136d184f95f504a607eac565846d2fdd6597a8967c7' - '396ef95a6eeebb4578a643966dca4d8ee3de842de63279c618159c1ab' - '54a89437b6a6120e4930afb52a4ba6ced8a4947ac64b30a3497cbe701' - 'c2d6266d517219ad0ec6d347dbe9', 16), - 'p': int( - '8dad7f11363faa623d5d6d5e8a319328d82190d7127d2846c439b0ab7' - '2619b0a43a95320e4ec34fc3a9cea876422305bd76c5ba7be9e2f410c' - '8060645a1d29edb', 16), - 'q': int( - '847e732376fc7900f898ea82eb2b0fc418565fdae62f7d9ec4ce2217b' - '97990dd272db157f99f63c0dcbb9fbacdbd4c4dadb6df67756358ca41' - '74825b48f49706d', 16), - 'dmp1': int( - '05c2a83c124b3621a2aa57ea2c3efe035eff4560f33ddebb7adab81fc' - 'e69a0c8c2edc16520dda83d59a23be867963ac65f2cc710bbcfb96ee1' - '03deb771d105fd85', 16), - 'dmq1': int( - '04cae8aa0d9faa165c87b682ec140b8ed3b50b24594b7a3b2c220b366' - '9bb819f984f55310a1ae7823651d4a02e99447972595139363434e5e3' - '0a7e7d241551e1b9', 16), - 'iqmp': int( - '07d3e47bf686600b11ac283ce88dbb3f6051e8efd04680e44c171ef53' - '1b80b2b7c39fc766320e2cf15d8d99820e96ff30dc69691839c4b40d7' - 'b06e45307dc91f3f', 16), - 'examples': [ + "modulus": int( + "495370a1fb18543c16d3631e3163255df62be6eee890d5f25509e4f77" + "8a8ea6fbbbcdf85dff64e0d972003ab3681fbba6dd41fd541829b2e58" + "2de9f2a4a4e0a2d0900bef4753db3cee0ee06c7dfae8b1d53b5953218" + "f9cceea695b08668edeaadced9463b1d790d5ebf27e9115b46cad4d9a" + "2b8efab0561b0810344739ada0733f", + 16, + ), + "public_exponent": int("10001", 16), + "private_exponent": int( + "6c66ffe98980c38fcdeab5159898836165f4b4b817c4f6a8d486ee4ea" + "9130fe9b9092bd136d184f95f504a607eac565846d2fdd6597a8967c7" + "396ef95a6eeebb4578a643966dca4d8ee3de842de63279c618159c1ab" + "54a89437b6a6120e4930afb52a4ba6ced8a4947ac64b30a3497cbe701" + "c2d6266d517219ad0ec6d347dbe9", + 16, + ), + "p": int( + "8dad7f11363faa623d5d6d5e8a319328d82190d7127d2846c439b0ab7" + "2619b0a43a95320e4ec34fc3a9cea876422305bd76c5ba7be9e2f410c" + "8060645a1d29edb", + 16, + ), + "q": int( + "847e732376fc7900f898ea82eb2b0fc418565fdae62f7d9ec4ce2217b" + "97990dd272db157f99f63c0dcbb9fbacdbd4c4dadb6df67756358ca41" + "74825b48f49706d", + 16, + ), + "dmp1": int( + "05c2a83c124b3621a2aa57ea2c3efe035eff4560f33ddebb7adab81fc" + "e69a0c8c2edc16520dda83d59a23be867963ac65f2cc710bbcfb96ee1" + "03deb771d105fd85", + 16, + ), + "dmq1": int( + "04cae8aa0d9faa165c87b682ec140b8ed3b50b24594b7a3b2c220b366" + "9bb819f984f55310a1ae7823651d4a02e99447972595139363434e5e3" + "0a7e7d241551e1b9", + 16, + ), + "iqmp": int( + "07d3e47bf686600b11ac283ce88dbb3f6051e8efd04680e44c171ef53" + "1b80b2b7c39fc766320e2cf15d8d99820e96ff30dc69691839c4b40d7" + "b06e45307dc91f3f", + 16, + ), + "examples": [ { - 'message': b'81332f4be62948415ea1d899792eeacf6c6e1db1d' - b'a8be13b5cea41db2fed467092e1ff398914c71425' - b'9775f595f8547f735692a575e6923af78f22c6997' - b'ddb90fb6f72d7bb0dd5744a31decd3dc368584983' - b'6ed34aec596304ad11843c4f88489f209735f5fb7' - b'fdaf7cec8addc5818168f880acbf490d51005b7a8' - b'e84e43e54287977571dd99eea4b161eb2df1f5108' - b'f12a4142a83322edb05a75487a3435c9a78ce53ed' - b'93bc550857d7a9fb', - 'salt': b'1d65491d79c864b373009be6f6f2467bac4c78fa', - 'signature': b'0262ac254bfa77f3c1aca22c5179f8f040422b3' - b'c5bafd40a8f21cf0fa5a667ccd5993d42dbafb4' - b'09c520e25fce2b1ee1e716577f1efa17f3da280' - b'52f40f0419b23106d7845aaf01125b698e7a4df' - b'e92d3967bb00c4d0d35ba3552ab9a8b3eef07c7' - b'fecdbc5424ac4db1e20cb37d0b2744769940ea9' - b'07e17fbbca673b20522380c5' - }, { - 'message': b'e2f96eaf0e05e7ba326ecca0ba7fd2f7c02356f3c' - b'ede9d0faabf4fcc8e60a973e5595fd9ea08', - 'salt': b'435c098aa9909eb2377f1248b091b68987ff1838', - 'signature': b'2707b9ad5115c58c94e932e8ec0a280f56339e4' - b'4a1b58d4ddcff2f312e5f34dcfe39e89c6a94dc' - b'ee86dbbdae5b79ba4e0819a9e7bfd9d982e7ee6' - b'c86ee68396e8b3a14c9c8f34b178eb741f9d3f1' - b'21109bf5c8172fada2e768f9ea1433032c004a8' - b'aa07eb990000a48dc94c8bac8aabe2b09b1aa46' - b'c0a2aa0e12f63fbba775ba7e' - } - ] + "message": b"81332f4be62948415ea1d899792eeacf6c6e1db1d" + b"a8be13b5cea41db2fed467092e1ff398914c71425" + b"9775f595f8547f735692a575e6923af78f22c6997" + b"ddb90fb6f72d7bb0dd5744a31decd3dc368584983" + b"6ed34aec596304ad11843c4f88489f209735f5fb7" + b"fdaf7cec8addc5818168f880acbf490d51005b7a8" + b"e84e43e54287977571dd99eea4b161eb2df1f5108" + b"f12a4142a83322edb05a75487a3435c9a78ce53ed" + b"93bc550857d7a9fb", + "salt": b"1d65491d79c864b373009be6f6f2467bac4c78fa", + "signature": b"0262ac254bfa77f3c1aca22c5179f8f040422b3" + b"c5bafd40a8f21cf0fa5a667ccd5993d42dbafb4" + b"09c520e25fce2b1ee1e716577f1efa17f3da280" + b"52f40f0419b23106d7845aaf01125b698e7a4df" + b"e92d3967bb00c4d0d35ba3552ab9a8b3eef07c7" + b"fecdbc5424ac4db1e20cb37d0b2744769940ea9" + b"07e17fbbca673b20522380c5", + }, + { + "message": b"e2f96eaf0e05e7ba326ecca0ba7fd2f7c02356f3c" + b"ede9d0faabf4fcc8e60a973e5595fd9ea08", + "salt": b"435c098aa9909eb2377f1248b091b68987ff1838", + "signature": b"2707b9ad5115c58c94e932e8ec0a280f56339e4" + b"4a1b58d4ddcff2f312e5f34dcfe39e89c6a94dc" + b"ee86dbbdae5b79ba4e0819a9e7bfd9d982e7ee6" + b"c86ee68396e8b3a14c9c8f34b178eb741f9d3f1" + b"21109bf5c8172fada2e768f9ea1433032c004a8" + b"aa07eb990000a48dc94c8bac8aabe2b09b1aa46" + b"c0a2aa0e12f63fbba775ba7e", + }, + ], }, - { - 'modulus': int( - '495370a1fb18543c16d3631e3163255df62be6eee890d5f25509e4f77' - '8a8ea6fbbbcdf85dff64e0d972003ab3681fbba6dd41fd541829b2e58' - '2de9f2a4a4e0a2d0900bef4753db3cee0ee06c7dfae8b1d53b5953218' - 'f9cceea695b08668edeaadced9463b1d790d5ebf27e9115b46cad4d9a' - '2b8efab0561b0810344739ada0733f', 16), - 'public_exponent': int('10001', 16) - } + "modulus": int( + "495370a1fb18543c16d3631e3163255df62be6eee890d5f25509e4f77" + "8a8ea6fbbbcdf85dff64e0d972003ab3681fbba6dd41fd541829b2e58" + "2de9f2a4a4e0a2d0900bef4753db3cee0ee06c7dfae8b1d53b5953218" + "f9cceea695b08668edeaadced9463b1d790d5ebf27e9115b46cad4d9a" + "2b8efab0561b0810344739ada0733f", + 16, + ), + "public_exponent": int("10001", 16), + }, ), ( { - 'modulus': int( - 'e6bd692ac96645790403fdd0f5beb8b9bf92ed10007fc365046419dd0' - '6c05c5b5b2f48ecf989e4ce269109979cbb40b4a0ad24d22483d1ee31' - '5ad4ccb1534268352691c524f6dd8e6c29d224cf246973aec86c5bf6b' - '1401a850d1b9ad1bb8cbcec47b06f0f8c7f45d3fc8f319299c5433ddb' - 'c2b3053b47ded2ecd4a4caefd614833dc8bb622f317ed076b8057fe8d' - 'e3f84480ad5e83e4a61904a4f248fb397027357e1d30e463139815c6f' - 'd4fd5ac5b8172a45230ecb6318a04f1455d84e5a8b', 16), - 'public_exponent': int('10001', 16), - 'private_exponent': int( - '6a7fd84fb85fad073b34406db74f8d61a6abc12196a961dd79565e9da' - '6e5187bce2d980250f7359575359270d91590bb0e427c71460b55d514' - '10b191bcf309fea131a92c8e702738fa719f1e0041f52e40e91f229f4' - 'd96a1e6f172e15596b4510a6daec26105f2bebc53316b87bdf2131166' - '6070e8dfee69d52c71a976caae79c72b68d28580dc686d9f5129d225f' - '82b3d615513a882b3db91416b48ce08888213e37eeb9af800d81cab32' - '8ce420689903c00c7b5fd31b75503a6d419684d629', 16), - 'p': int( - 'f8eb97e98df12664eefdb761596a69ddcd0e76daece6ed4bf5a1b50ac' - '086f7928a4d2f8726a77e515b74da41988f220b1cc87aa1fc810ce99a' - '82f2d1ce821edced794c6941f42c7a1a0b8c4d28c75ec60b652279f61' - '54a762aed165d47dee367', 16), - 'q': int( - 'ed4d71d0a6e24b93c2e5f6b4bbe05f5fb0afa042d204fe3378d365c2f' - '288b6a8dad7efe45d153eef40cacc7b81ff934002d108994b94a5e472' - '8cd9c963375ae49965bda55cbf0efed8d6553b4027f2d86208a6e6b48' - '9c176128092d629e49d3d', 16), - 'dmp1': int( - '2bb68bddfb0c4f56c8558bffaf892d8043037841e7fa81cfa61a38c5e' - '39b901c8ee71122a5da2227bd6cdeeb481452c12ad3d61d5e4f776a0a' - 'b556591befe3e59e5a7fddb8345e1f2f35b9f4cee57c32414c086aec9' - '93e9353e480d9eec6289f', 16), - 'dmq1': int( - '4ff897709fad079746494578e70fd8546130eeab5627c49b080f05ee4' - 'ad9f3e4b7cba9d6a5dff113a41c3409336833f190816d8a6bc42e9bec' - '56b7567d0f3c9c696db619b245d901dd856db7c8092e77e9a1cccd56e' - 'e4dba42c5fdb61aec2669', 16), - 'iqmp': int( - '77b9d1137b50404a982729316efafc7dfe66d34e5a182600d5f30a0a8' - '512051c560d081d4d0a1835ec3d25a60f4e4d6aa948b2bf3dbb5b124c' - 'bbc3489255a3a948372f6978496745f943e1db4f18382ceaa505dfc65' - '757bb3f857a58dce52156', 16), - 'examples': [ + "modulus": int( + "e6bd692ac96645790403fdd0f5beb8b9bf92ed10007fc365046419dd0" + "6c05c5b5b2f48ecf989e4ce269109979cbb40b4a0ad24d22483d1ee31" + "5ad4ccb1534268352691c524f6dd8e6c29d224cf246973aec86c5bf6b" + "1401a850d1b9ad1bb8cbcec47b06f0f8c7f45d3fc8f319299c5433ddb" + "c2b3053b47ded2ecd4a4caefd614833dc8bb622f317ed076b8057fe8d" + "e3f84480ad5e83e4a61904a4f248fb397027357e1d30e463139815c6f" + "d4fd5ac5b8172a45230ecb6318a04f1455d84e5a8b", + 16, + ), + "public_exponent": int("10001", 16), + "private_exponent": int( + "6a7fd84fb85fad073b34406db74f8d61a6abc12196a961dd79565e9da" + "6e5187bce2d980250f7359575359270d91590bb0e427c71460b55d514" + "10b191bcf309fea131a92c8e702738fa719f1e0041f52e40e91f229f4" + "d96a1e6f172e15596b4510a6daec26105f2bebc53316b87bdf2131166" + "6070e8dfee69d52c71a976caae79c72b68d28580dc686d9f5129d225f" + "82b3d615513a882b3db91416b48ce08888213e37eeb9af800d81cab32" + "8ce420689903c00c7b5fd31b75503a6d419684d629", + 16, + ), + "p": int( + "f8eb97e98df12664eefdb761596a69ddcd0e76daece6ed4bf5a1b50ac" + "086f7928a4d2f8726a77e515b74da41988f220b1cc87aa1fc810ce99a" + "82f2d1ce821edced794c6941f42c7a1a0b8c4d28c75ec60b652279f61" + "54a762aed165d47dee367", + 16, + ), + "q": int( + "ed4d71d0a6e24b93c2e5f6b4bbe05f5fb0afa042d204fe3378d365c2f" + "288b6a8dad7efe45d153eef40cacc7b81ff934002d108994b94a5e472" + "8cd9c963375ae49965bda55cbf0efed8d6553b4027f2d86208a6e6b48" + "9c176128092d629e49d3d", + 16, + ), + "dmp1": int( + "2bb68bddfb0c4f56c8558bffaf892d8043037841e7fa81cfa61a38c5e" + "39b901c8ee71122a5da2227bd6cdeeb481452c12ad3d61d5e4f776a0a" + "b556591befe3e59e5a7fddb8345e1f2f35b9f4cee57c32414c086aec9" + "93e9353e480d9eec6289f", + 16, + ), + "dmq1": int( + "4ff897709fad079746494578e70fd8546130eeab5627c49b080f05ee4" + "ad9f3e4b7cba9d6a5dff113a41c3409336833f190816d8a6bc42e9bec" + "56b7567d0f3c9c696db619b245d901dd856db7c8092e77e9a1cccd56e" + "e4dba42c5fdb61aec2669", + 16, + ), + "iqmp": int( + "77b9d1137b50404a982729316efafc7dfe66d34e5a182600d5f30a0a8" + "512051c560d081d4d0a1835ec3d25a60f4e4d6aa948b2bf3dbb5b124c" + "bbc3489255a3a948372f6978496745f943e1db4f18382ceaa505dfc65" + "757bb3f857a58dce52156", + 16, + ), + "examples": [ { - 'message': b'06add75ab689de067744e69a2ebd4b90fa9383003' - b'cd05ff536cbf294cd215f0923b7fc9004f0aa1852' - b'71a1d0061fd0e9777ad1ec0c71591f578bf7b8e5a' - b'1', - 'signature': b'4514210e541d5bad7dd60ae549b943acc44f213' - b'90df5b61318455a17610df5b74d84aed232f17e' - b'59d91dd2659922f812dbd49681690384b954e9a' - b'dfb9b1a968c0cbff763eceed62750c59164b5e0' - b'80a8fef3d55bfe2acfad2752a6a8459fa1fab49' - b'ad378c6964b23ee97fd1034610c5cc14c61e0eb' - b'fb1711f8ade96fe6557b38' + "message": b"06add75ab689de067744e69a2ebd4b90fa9383003" + b"cd05ff536cbf294cd215f0923b7fc9004f0aa1852" + b"71a1d0061fd0e9777ad1ec0c71591f578bf7b8e5a" + b"1", + "signature": b"4514210e541d5bad7dd60ae549b943acc44f213" + b"90df5b61318455a17610df5b74d84aed232f17e" + b"59d91dd2659922f812dbd49681690384b954e9a" + b"dfb9b1a968c0cbff763eceed62750c59164b5e0" + b"80a8fef3d55bfe2acfad2752a6a8459fa1fab49" + b"ad378c6964b23ee97fd1034610c5cc14c61e0eb" + b"fb1711f8ade96fe6557b38", } - ] + ], }, - { - 'modulus': int( - 'e6bd692ac96645790403fdd0f5beb8b9bf92ed10007fc365046419dd0' - '6c05c5b5b2f48ecf989e4ce269109979cbb40b4a0ad24d22483d1ee31' - '5ad4ccb1534268352691c524f6dd8e6c29d224cf246973aec86c5bf6b' - '1401a850d1b9ad1bb8cbcec47b06f0f8c7f45d3fc8f319299c5433ddb' - 'c2b3053b47ded2ecd4a4caefd614833dc8bb622f317ed076b8057fe8d' - 'e3f84480ad5e83e4a61904a4f248fb397027357e1d30e463139815c6f' - 'd4fd5ac5b8172a45230ecb6318a04f1455d84e5a8b', 16), - 'public_exponent': int('10001', 16) - } - ) + "modulus": int( + "e6bd692ac96645790403fdd0f5beb8b9bf92ed10007fc365046419dd0" + "6c05c5b5b2f48ecf989e4ce269109979cbb40b4a0ad24d22483d1ee31" + "5ad4ccb1534268352691c524f6dd8e6c29d224cf246973aec86c5bf6b" + "1401a850d1b9ad1bb8cbcec47b06f0f8c7f45d3fc8f319299c5433ddb" + "c2b3053b47ded2ecd4a4caefd614833dc8bb622f317ed076b8057fe8d" + "e3f84480ad5e83e4a61904a4f248fb397027357e1d30e463139815c6f" + "d4fd5ac5b8172a45230ecb6318a04f1455d84e5a8b", + 16, + ), + "public_exponent": int("10001", 16), + }, + ), ) assert vectors == expected def test_load_pkcs1_oaep_vectors(): - vector_data = textwrap.dedent(""" + vector_data = textwrap.dedent( + """ Test vectors for RSA-OAEP ========================= @@ -1083,88 +1159,106 @@ def test_load_pkcs1_oaep_vectors(): 15 91 2d f6 96 ff e0 70 29 32 94 6d 71 49 2b 44 # ============================================= - """).splitlines() + """ + ).splitlines() vectors = load_pkcs1_vectors(vector_data) expected = [ ( { - 'modulus': int( - 'a8b3b284af8eb50b387034a860f146c4919f318763cd6c5598c8ae481' - '1a1e0abc4c7e0b082d693a5e7fced675cf4668512772c0cbc64a742c6' - 'c630f533c8cc72f62ae833c40bf25842e984bb78bdbf97c0107d55bdb' - '662f5c4e0fab9845cb5148ef7392dd3aaff93ae1e6b667bb3d4247616' - 'd4f5ba10d4cfd226de88d39f16fb', 16), - 'public_exponent': int('10001', 16), - 'private_exponent': int( - '53339cfdb79fc8466a655c7316aca85c55fd8f6dd898fdaf119517ef4' - 'f52e8fd8e258df93fee180fa0e4ab29693cd83b152a553d4ac4d1812b' - '8b9fa5af0e7f55fe7304df41570926f3311f15c4d65a732c483116ee3' - 'd3d2d0af3549ad9bf7cbfb78ad884f84d5beb04724dc7369b31def37d' - '0cf539e9cfcdd3de653729ead5d1', 16), - 'p': int( - 'd32737e7267ffe1341b2d5c0d150a81b586fb3132bed2f8d5262864a9' - 'cb9f30af38be448598d413a172efb802c21acf1c11c520c2f26a471dc' - 'ad212eac7ca39d', 16), - 'q': int( - 'cc8853d1d54da630fac004f471f281c7b8982d8224a490edbeb33d3e3' - 'd5cc93c4765703d1dd791642f1f116a0dd852be2419b2af72bfe9a030' - 'e860b0288b5d77', 16), - 'dmp1': int( - '0e12bf1718e9cef5599ba1c3882fe8046a90874eefce8f2ccc20e4f27' - '41fb0a33a3848aec9c9305fbecbd2d76819967d4671acc6431e403796' - '8db37878e695c1', 16), - 'dmq1': int( - '95297b0f95a2fa67d00707d609dfd4fc05c89dafc2ef6d6ea55bec771' - 'ea333734d9251e79082ecda866efef13c459e1a631386b7e354c899f5' - 'f112ca85d71583', 16), - 'iqmp': int( - '4f456c502493bdc0ed2ab756a3a6ed4d67352a697d4216e93212b127a' - '63d5411ce6fa98d5dbefd73263e3728142743818166ed7dd63687dd2a' - '8ca1d2f4fbd8e1', 16), - 'examples': [ + "modulus": int( + "a8b3b284af8eb50b387034a860f146c4919f318763cd6c5598c8ae481" + "1a1e0abc4c7e0b082d693a5e7fced675cf4668512772c0cbc64a742c6" + "c630f533c8cc72f62ae833c40bf25842e984bb78bdbf97c0107d55bdb" + "662f5c4e0fab9845cb5148ef7392dd3aaff93ae1e6b667bb3d4247616" + "d4f5ba10d4cfd226de88d39f16fb", + 16, + ), + "public_exponent": int("10001", 16), + "private_exponent": int( + "53339cfdb79fc8466a655c7316aca85c55fd8f6dd898fdaf119517ef4" + "f52e8fd8e258df93fee180fa0e4ab29693cd83b152a553d4ac4d1812b" + "8b9fa5af0e7f55fe7304df41570926f3311f15c4d65a732c483116ee3" + "d3d2d0af3549ad9bf7cbfb78ad884f84d5beb04724dc7369b31def37d" + "0cf539e9cfcdd3de653729ead5d1", + 16, + ), + "p": int( + "d32737e7267ffe1341b2d5c0d150a81b586fb3132bed2f8d5262864a9" + "cb9f30af38be448598d413a172efb802c21acf1c11c520c2f26a471dc" + "ad212eac7ca39d", + 16, + ), + "q": int( + "cc8853d1d54da630fac004f471f281c7b8982d8224a490edbeb33d3e3" + "d5cc93c4765703d1dd791642f1f116a0dd852be2419b2af72bfe9a030" + "e860b0288b5d77", + 16, + ), + "dmp1": int( + "0e12bf1718e9cef5599ba1c3882fe8046a90874eefce8f2ccc20e4f27" + "41fb0a33a3848aec9c9305fbecbd2d76819967d4671acc6431e403796" + "8db37878e695c1", + 16, + ), + "dmq1": int( + "95297b0f95a2fa67d00707d609dfd4fc05c89dafc2ef6d6ea55bec771" + "ea333734d9251e79082ecda866efef13c459e1a631386b7e354c899f5" + "f112ca85d71583", + 16, + ), + "iqmp": int( + "4f456c502493bdc0ed2ab756a3a6ed4d67352a697d4216e93212b127a" + "63d5411ce6fa98d5dbefd73263e3728142743818166ed7dd63687dd2a" + "8ca1d2f4fbd8e1", + 16, + ), + "examples": [ { - 'message': b'6628194e12073db03ba94cda9ef9532397d50dba7' - b'9b987004afefe34', - 'seed': b'18b776ea21069d69776a33e96bad48e1dda0a5ef', - 'encryption': b'354fe67b4a126d5d35fe36c777791a3f7ba13d' - b'ef484e2d3908aff722fad468fb21696de95d0b' - b'e911c2d3174f8afcc201035f7b6d8e69402de5' - b'451618c21a535fa9d7bfc5b8dd9fc243f8cf92' - b'7db31322d6e881eaa91a996170e657a05a2664' - b'26d98c88003f8477c1227094a0d9fa1e8c4024' - b'309ce1ecccb5210035d47ac72e8a' - }, { - 'message': b'750c4047f547e8e41411856523298ac9bae245efa' - b'f1397fbe56f9dd5', - 'seed': b'0cc742ce4a9b7f32f951bcb251efd925fe4fe35f', - 'encryption': b'640db1acc58e0568fe5407e5f9b701dff8c3c9' - b'1e716c536fc7fcec6cb5b71c1165988d4a279e' - b'1577d730fc7a29932e3f00c81515236d8d8e31' - b'017a7a09df4352d904cdeb79aa583adcc31ea6' - b'98a4c05283daba9089be5491f67c1a4ee48dc7' - b'4bbbe6643aef846679b4cb395a352d5ed11591' - b'2df696ffe0702932946d71492b44' - } - ] + "message": b"6628194e12073db03ba94cda9ef9532397d50dba7" + b"9b987004afefe34", + "seed": b"18b776ea21069d69776a33e96bad48e1dda0a5ef", + "encryption": b"354fe67b4a126d5d35fe36c777791a3f7ba13d" + b"ef484e2d3908aff722fad468fb21696de95d0b" + b"e911c2d3174f8afcc201035f7b6d8e69402de5" + b"451618c21a535fa9d7bfc5b8dd9fc243f8cf92" + b"7db31322d6e881eaa91a996170e657a05a2664" + b"26d98c88003f8477c1227094a0d9fa1e8c4024" + b"309ce1ecccb5210035d47ac72e8a", + }, + { + "message": b"750c4047f547e8e41411856523298ac9bae245efa" + b"f1397fbe56f9dd5", + "seed": b"0cc742ce4a9b7f32f951bcb251efd925fe4fe35f", + "encryption": b"640db1acc58e0568fe5407e5f9b701dff8c3c9" + b"1e716c536fc7fcec6cb5b71c1165988d4a279e" + b"1577d730fc7a29932e3f00c81515236d8d8e31" + b"017a7a09df4352d904cdeb79aa583adcc31ea6" + b"98a4c05283daba9089be5491f67c1a4ee48dc7" + b"4bbbe6643aef846679b4cb395a352d5ed11591" + b"2df696ffe0702932946d71492b44", + }, + ], }, - { - 'modulus': int( - 'a8b3b284af8eb50b387034a860f146c4919f318763cd6c5598c8ae481' - '1a1e0abc4c7e0b082d693a5e7fced675cf4668512772c0cbc64a742c6' - 'c630f533c8cc72f62ae833c40bf25842e984bb78bdbf97c0107d55bdb' - '662f5c4e0fab9845cb5148ef7392dd3aaff93ae1e6b667bb3d4247616' - 'd4f5ba10d4cfd226de88d39f16fb', 16), - 'public_exponent': int('10001', 16), - } + "modulus": int( + "a8b3b284af8eb50b387034a860f146c4919f318763cd6c5598c8ae481" + "1a1e0abc4c7e0b082d693a5e7fced675cf4668512772c0cbc64a742c6" + "c630f533c8cc72f62ae833c40bf25842e984bb78bdbf97c0107d55bdb" + "662f5c4e0fab9845cb5148ef7392dd3aaff93ae1e6b667bb3d4247616" + "d4f5ba10d4cfd226de88d39f16fb", + 16, + ), + "public_exponent": int("10001", 16), + }, ) ] assert vectors == expected def test_load_hotp_vectors(): - vector_data = textwrap.dedent(""" + vector_data = textwrap.dedent( + """ # HOTP Test Vectors # RFC 4226 Appendix D @@ -1197,7 +1291,8 @@ def test_load_hotp_vectors(): TRUNCATED = 66ef7655 HOTP = 969429 SECRET = 12345678901234567890 - """).splitlines() + """ + ).splitlines() assert load_nist_vectors(vector_data) == [ { @@ -1232,7 +1327,8 @@ def test_load_hotp_vectors(): def test_load_totp_vectors(): - vector_data = textwrap.dedent(""" + vector_data = textwrap.dedent( + """ # TOTP Test Vectors # RFC 6238 Appendix B @@ -1253,7 +1349,8 @@ def test_load_totp_vectors(): TOTP = 90693936 MODE = SHA512 SECRET = 12345678901234567890 - """).splitlines() + """ + ).splitlines() assert load_nist_vectors(vector_data) == [ { @@ -1278,7 +1375,8 @@ def test_load_totp_vectors(): def test_load_rsa_nist_vectors(): - vector_data = textwrap.dedent(""" + vector_data = textwrap.dedent( + """ # CAVS 11.4 # "SigGen PKCS#1 RSASSA-PSS" information # Mod sizes selected: 1024 1536 2048 3072 4096 @@ -1307,33 +1405,40 @@ def test_load_rsa_nist_vectors(): SHAAlg = SHA512 Msg = 3456781293fab829 S = deadbeef0000 - """).splitlines() + """ + ).splitlines() vectors = load_rsa_nist_vectors(vector_data) assert vectors == [ { - "modulus": int("bcb47b2e0dafcba81ff2a2b5cb115ca7e757184c9d72bcdcda" - "707a146b3b4e29989d", 16), + "modulus": int( + "bcb47b2e0dafcba81ff2a2b5cb115ca7e757184c9d72bcdcda" + "707a146b3b4e29989d", + 16, + ), "public_exponent": 65537, "algorithm": "SHA1", "salt_length": 20, "msg": b"1248f62a4389f42f7b4bb131053d6c88a994db2075b912ccbe3ea7dc6" - b"11714f14e", + b"11714f14e", "s": b"682cf53c1145d22a50caa9eb1a9ba70670c5915e0fdfde6457a765de2a8" - b"fe12de97", - "fail": False + b"fe12de97", + "fail": False, }, { - "modulus": int("bcb47b2e0dafcba81ff2a2b5cb115ca7e757184c9d72bcdcda" - "707a146b3b4e29989d", 16), + "modulus": int( + "bcb47b2e0dafcba81ff2a2b5cb115ca7e757184c9d72bcdcda" + "707a146b3b4e29989d", + 16, + ), "public_exponent": 65537, "algorithm": "SHA384", "salt_length": 20, "msg": b"e511903c2f1bfba245467295ac95413ac4746c984c3750a728c388aa6" - b"28b0ebf", + b"28b0ebf", "s": b"9c748702bbcc1f9468864cd360c8c39d007b2d8aaee833606c70f7593cf" - b"0d1519", - "fail": False + b"0d1519", + "fail": False, }, { "modulus": 78187493520, @@ -1342,13 +1447,14 @@ def test_load_rsa_nist_vectors(): "salt_length": 20, "msg": b"3456781293fab829", "s": b"deadbeef0000", - "fail": False + "fail": False, }, ] def test_load_rsa_nist_pkcs1v15_verification_vectors(): - vector_data = textwrap.dedent(""" + vector_data = textwrap.dedent( + """ # CAVS 11.0 # "SigVer PKCS#1 Ver 1.5" information # Mod sizes selected: 1024 1536 2048 3072 4096 @@ -1377,50 +1483,73 @@ def test_load_rsa_nist_pkcs1v15_verification_vectors(): S = 2b91c6ae2b3c46ff18d5b7abe239634cb752d0acb53eea0ccd8ea8483036a50e8faf SaltVal = 11223344555432167890 Result = P - """).splitlines() + """ + ).splitlines() vectors = load_rsa_nist_vectors(vector_data) assert vectors == [ { - "modulus": int("be499b5e7f06c83fa0293e31465c8eb6b58af920bae52a7b5b" - "9bfeb7aa72db126411", 16), - "p": int("e7a80c5d211c06acb900939495f26d365fc2b4825b75e356f89003ea" - "a5931e6be5c3", 16), - "q": int("d248aa248000f720258742da67b711940c8f76e1ecd52b67a6ffe1e4" - "9354d66ff84f", 16), + "modulus": int( + "be499b5e7f06c83fa0293e31465c8eb6b58af920bae52a7b5b" + "9bfeb7aa72db126411", + 16, + ), + "p": int( + "e7a80c5d211c06acb900939495f26d365fc2b4825b75e356f89003ea" + "a5931e6be5c3", + 16, + ), + "q": int( + "d248aa248000f720258742da67b711940c8f76e1ecd52b67a6ffe1e4" + "9354d66ff84f", + 16, + ), "public_exponent": 17, "algorithm": "SHA1", - "private_exponent": int("0d0f17362bdad181db4e1fe03e8de1a3208989914" - "e14bf269558826bfa20faf4b68d", 16), + "private_exponent": int( + "0d0f17362bdad181db4e1fe03e8de1a3208989914" + "e14bf269558826bfa20faf4b68d", + 16, + ), "msg": b"6b9cfac0ba1c7890b13e381ce752195cc1375237db2afcf6a9dcd1f95" - b"ec733a80c", + b"ec733a80c", "s": b"562d87b5781c01d166fef3972669a0495c145b898a17df4743fbefb0a15" - b"82bd6ba9d", + b"82bd6ba9d", "saltval": b"11223344555432167890", - "fail": True + "fail": True, }, { - "modulus": int("be499b5e7f06c83fa0293e31465c8eb6b58af920bae52a7b5b" - "9bfeb7aa72db126411", 16), - "p": int("e7a80c5d211c06acb900939495f26d365fc2b4825b75e356f89003ea" - "a5931e6be5c3", 16), - "q": int("d248aa248000f720258742da67b711940c8f76e1ecd52b67a6ffe1e4" - "9354d66ff84f", 16), + "modulus": int( + "be499b5e7f06c83fa0293e31465c8eb6b58af920bae52a7b5b" + "9bfeb7aa72db126411", + 16, + ), + "p": int( + "e7a80c5d211c06acb900939495f26d365fc2b4825b75e356f89003ea" + "a5931e6be5c3", + 16, + ), + "q": int( + "d248aa248000f720258742da67b711940c8f76e1ecd52b67a6ffe1e4" + "9354d66ff84f", + 16, + ), "public_exponent": 3, "algorithm": "SHA1", "private_exponent": int("bfa20faf4b68d", 16), "msg": b"2a67c70ff14f9b34ddb42e6f89d5971057a0da980fc9ae70c81a84da0" - b"c0ac42737", + b"c0ac42737", "s": b"2b91c6ae2b3c46ff18d5b7abe239634cb752d0acb53eea0ccd8ea848303" - b"6a50e8faf", + b"6a50e8faf", "saltval": b"11223344555432167890", - "fail": False + "fail": False, }, ] def test_load_rsa_nist_pss_verification_vectors(): - vector_data = textwrap.dedent(""" + vector_data = textwrap.dedent( + """ # CAVS 11.0 # "SigVer PKCS#1 RSASSA-PSS" information # Mod sizes selected: 1024 1536 2048 3072 4096 @@ -1450,7 +1579,8 @@ def test_load_rsa_nist_pss_verification_vectors(): S = 2b91c6ae2b3c46ff18d5b7abe239634cb7 SaltVal = 11223344555432167890 Result = P - """).splitlines() + """ + ).splitlines() vectors = load_rsa_nist_vectors(vector_data) assert vectors == [ @@ -1465,7 +1595,7 @@ def test_load_rsa_nist_pss_verification_vectors(): "s": b"562d87b5781c01d166fef3972669a0495c", "saltval": b"11223344555432167890", "salt_length": 10, - "fail": True + "fail": True, }, { "modulus": int("be499b5e7f06c83fa0293e31465c8eb6b5", 16), @@ -1478,13 +1608,14 @@ def test_load_rsa_nist_pss_verification_vectors(): "s": b"2b91c6ae2b3c46ff18d5b7abe239634cb7", "saltval": b"11223344555432167890", "salt_length": 10, - "fail": False + "fail": False, }, ] def test_load_fips_dsa_key_pair_vectors(): - vector_data = textwrap.dedent(""" + vector_data = textwrap.dedent( + """ # CAVS 11.1 # "KeyPair" information # Mod sizes selected: L=1024, N=160:: L=2048, N=224 :: L=2048, N=256 :: L @@ -1599,213 +1730,303 @@ def test_load_fips_dsa_key_pair_vectors(): 623399b473ce712a2184cf2da1861706c41466806aefe41b497db82aca6c31c8f4aa68c17d1d9e\ 380b57998917655783ec96e5234a131f7299398d36f1f5f84297a55ff292f1f060958c358fed34\ 6db2de45127ca728a9417b2c54203e33e53b9a061d924395b09afab8daf3e8dd7eedcec3ac - """).splitlines() + """ + ).splitlines() expected = [ - {'g': int('06b7861abbd35cc89e79c52f68d20875389b127361ca66822138ce499' - '1d2b862259d6b4548a6495b195aa0e0b6137ca37eb23b94074d3c3d3000' - '42bdf15762812b6333ef7b07ceba78607610fcc9ee68491dbc1e34cd12' - '615474e52b18bc934fb00c61d39e7da8902291c4434a4e2224c3f' - '4fd9f93cd6f4f17fc076341a7e7d9', 16), - 'p': int('d38311e2cd388c3ed698e82fdf88eb92b5a9a483dc88005d4b725e' - 'f341eabb47cf8a7a8a41e792a156b7ce97206c4f9c5ce6fc5ae791210' - '2b6b502e59050b5b21ce263dddb2044b652236f4d42ab4b5d6aa73189c' - 'ef1ace778d7845a5c1c1c7147123188f8dc551054ee162b634d60f097f7' - '19076640e20980a0093113a8bd73', 16), - 'q': int('96c5390a8b612c0e422bb2b0ea194a3ec935a281', 16), - 'x': int('8185fee9cc7c0e91fd85503274f1cd5a3fd15a49', 16), - 'y': int('6f26d98d41de7d871b6381851c9d91fa03942092ab6097e76422' - '070edb71db44ff568280fdb1709f8fc3feab39f1f824adaeb2a29808815' - '6ac31af1aa04bf54f475bdcfdcf2f8a2dd973e922d83e76f01655861760' - '3129b21c70bf7d0e5dc9e68fe332e295b65876eb9a12fe6fca9f1a1ce80' - '204646bf99b5771d249a6fea627', 16)}, - {'g': int('06b7861abbd35cc89e79c52f68d20875389b127361ca66822138ce4991d' - '2b862259d6b4548a6495b195aa0e0b6137ca37eb23b94074d3c3d30004' - '2bdf15762812b6333ef7b07ceba78607610fcc9ee68491dbc1e34cd126' - '15474e52b18bc934fb00c61d39e7da8902291c4434a4e2224c3f4fd9' - 'f93cd6f4f17fc076341a7e7d9', 16), - 'p': int('d38311e2cd388c3ed698e82fdf88eb92b5a9a483dc88005d4b725ef341e' - 'abb47cf8a7a8a41e792a156b7ce97206c4f9c5ce6fc5ae7912102b6b50' - '2e59050b5b21ce263dddb2044b652236f4d42ab4b5d6aa73189cef1a' - 'ce778d7845a5c1c1c7147123188f8dc551054ee162b634d6' - '0f097f719076640e20980a0093113a8bd73', 16), - 'q': int('96c5390a8b612c0e422bb2b0ea194a3ec935a281', 16), - 'x': int('85322d6ea73083064376099ca2f65f56e8522d9b', 16), - 'y': int('21f8690f717c9f4dcb8f4b6971de2f15b9231fcf41b7eeb997d781f240' - 'bfdddfd2090d22083c26cca39bf37c9caf1ec89518ea64845a50d747b49' - '131ffff6a2fd11ea7bacbb93c7d05137383a06365af82225dd3713c' - 'a5a45006316f53bd12b0e260d5f79795e5a4c9f353f12867a1d3' - '202394673ada8563b71555e53f415254', 16)}, - - {'g': int('e4c4eca88415b23ecf811c96e48cd24200fe916631a68a684e6ccb6b191' - '3413d344d1d8d84a333839d88eee431521f6e357c16e6a93be111a9807' - '6739cd401bab3b9d565bf4fb99e9d185b1e14d61c93700133f908bae0' - '3e28764d107dcd2ea7674217622074bb19efff482f5f5c1a86d5551b2' - 'fc68d1c6e9d8011958ef4b9c2a3a55d0d3c882e6ad7f9f0f3c61568f78' - 'd0706b10a26f23b4f197c322b825002284a0aca91807bba98ece912' - 'b80e10cdf180cf99a35f210c1655fbfdd74f13b1b5046591f8403873d' - '12239834dd6c4eceb42bf7482e1794a1601357b629ddfa971f2ed273b1' - '46ec1ca06d0adf55dd91d65c37297bda78c6d210c0bc26e558302', 16), - 'p': int('ea1fb1af22881558ef93be8a5f8653c5a559434c49c8c2c12ace' - '5e9c41434c9cf0a8e9498acb0f4663c08b4484eace845f6fb17d' - 'ac62c98e706af0fc74e4da1c6c2b3fbf5a1d58ff82fc1a66f3e8b122' - '52c40278fff9dd7f102eed2cb5b7323ebf1908c234d935414dded7f8d2' - '44e54561b0dca39b301de8c49da9fb23df33c6182e3f983208c560fb5' - '119fbf78ebe3e6564ee235c6a15cbb9ac247baba5a423bc6582a1a9d8a' - '2b4f0e9e3d9dbac122f750dd754325135257488b1f6ecabf21bff2947' - 'fe0d3b2cb7ffe67f4e7fcdf1214f6053e72a5bb0dd20a0e9fe6db2df0a' - '908c36e95e60bf49ca4368b8b892b9c79f61ef91c47567c40e1f80ac' - '5aa66ef7', 16), - 'q': int('8ec73f3761caf5fdfe6e4e82098bf10f898740dcb808204bf6b1' - '8f507192c19d', 16), - 'x': int('405772da6e90d809e77d5de796562a2dd4dfd10ef00a83a3aba6' - 'bd818a0348a1', 16), - 'y': int('6b32e31ab9031dc4dd0b5039a78d07826687ab087ae6de4736f5' - 'b0434e1253092e8a0b231f9c87f3fc8a4cb5634eb194bf1b638' - 'b7a7889620ce6711567e36aa36cda4604cfaa601a45918371d' - '4ccf68d8b10a50a0460eb1dc0fff62ef5e6ee4d473e18ea4a6' - '6c196fb7e677a49b48241a0b4a97128eff30fa437050501a584' - 'f8771e7280d26d5af30784039159c11ebfea10b692fd0a58215ee' - 'b18bff117e13f08db792ed4151a218e4bed8dddfb0793225bd1e97' - '73505166f4bd8cedbb286ea28232972da7bae836ba97329ba6b0a36508' - 'e50a52a7675e476d4d4137eae13f22a9d2fefde708ba8f34bf336c6e7' - '6331761e4b0617633fe7ec3f23672fb19d27', 16)}, - {'g': int('e4c4eca88415b23ecf811c96e48cd24200fe916631a68a684e6ccb6b191' - '3413d344d1d8d84a333839d88eee431521f6e357c16e6a93be111a9807' - '6739cd401bab3b9d565bf4fb99e9d185b1e14d61c93700133f908bae0' - '3e28764d107dcd2ea7674217622074bb19efff482f5f5c1a86d5551b2' - 'fc68d1c6e9d8011958ef4b9c2a3a55d0d3c882e6ad7f9f0f3c61568f78' - 'd0706b10a26f23b4f197c322b825002284a0aca91807bba98ece912' - 'b80e10cdf180cf99a35f210c1655fbfdd74f13b1b5046591f8403873d' - '12239834dd6c4eceb42bf7482e1794a1601357b629ddfa971f2ed273b1' - '46ec1ca06d0adf55dd91d65c37297bda78c6d210c0bc26e558302', 16), - 'p': int('ea1fb1af22881558ef93be8a5f8653c5a559434c49c8c2c12ace' - '5e9c41434c9cf0a8e9498acb0f4663c08b4484eace845f6fb17d' - 'ac62c98e706af0fc74e4da1c6c2b3fbf5a1d58ff82fc1a66f3e8b122' - '52c40278fff9dd7f102eed2cb5b7323ebf1908c234d935414dded7f8d2' - '44e54561b0dca39b301de8c49da9fb23df33c6182e3f983208c560fb5' - '119fbf78ebe3e6564ee235c6a15cbb9ac247baba5a423bc6582a1a9d8a' - '2b4f0e9e3d9dbac122f750dd754325135257488b1f6ecabf21bff2947' - 'fe0d3b2cb7ffe67f4e7fcdf1214f6053e72a5bb0dd20a0e9fe6db2df0a' - '908c36e95e60bf49ca4368b8b892b9c79f61ef91c47567c40e1f80ac' - '5aa66ef7', 16), - 'q': int('8ec73f3761caf5fdfe6e4e82098bf10f898740dcb808204bf6b1' - '8f507192c19d', 16), - 'x': int('0e0b95e31fda3f888059c46c3002ef8f2d6be112d0209aeb9e95' - '45da67aeea80', 16), - 'y': int('778082b77ddba6f56597cc74c3a612abf2ddbd85cc81430c99ab' - '843c1f630b9db0139965f563978164f9bf3a8397256be714625' - 'cd41cd7fa0067d94ea66d7e073f7125af692ad01371d4a17f45' - '50590378f2b074030c20e36911598a1018772f61be3b24de4be' - '5a388ccc09e15a92819c31dec50de9fde105b49eaa097b9d13d' - '9219eeb33b628facfd1c78a7159c8430d0647c506e7e3de74763c' - 'b351eada72c00bef3c9641881e6254870c1e6599f8ca2f1bbb74f' - '39a905e3a34e4544168e6e50c9e3305fd09cab6ed4aff6fda6e0d' - '5bf375c81ac9054406d9193b003c89272f1bd83d48250134b65c77' - 'c2b6332d38d34d9016f0e8975536ad6c348a1faedb0', 16)}, - - {'g': int('ce84b30ddf290a9f787a7c2f1ce92c1cbf4ef400e3cd7ce4978d' - 'b2104d7394b493c18332c64cec906a71c3778bd93341165dee8' - 'e6cd4ca6f13afff531191194ada55ecf01ff94d6cf7c4768b82' - 'dd29cd131aaf202aefd40e564375285c01f3220af4d70b96f1' - '395420d778228f1461f5d0b8e47357e87b1fe3286223b553e3' - 'fc9928f16ae3067ded6721bedf1d1a01bfd22b9ae85fce77820d88cdf' - '50a6bde20668ad77a707d1c60fcc5d51c9de488610d0285eb8ff721f' - 'f141f93a9fb23c1d1f7654c07c46e58836d1652828f71057b8aff0b077' - '8ef2ca934ea9d0f37daddade2d823a4d8e362721082e279d003b575ee' - '59fd050d105dfd71cd63154efe431a0869178d9811f4f231dc5dcf3b' - '0ec0f2b0f9896c32ec6c7ee7d60aa97109e09224907328d4e6acd1011' - '7e45774406c4c947da8020649c3168f690e0bd6e91ac67074d1d436b' - '58ae374523deaf6c93c1e6920db4a080b744804bb073cecfe83fa939' - '8cf150afa286dc7eb7949750cf5001ce104e9187f7e16859afa8fd0d' - '775ae', 16), - 'p': int('f335666dd1339165af8b9a5e3835adfe15c158e4c3c7bd53132e7d5828' - 'c352f593a9a787760ce34b789879941f2f01f02319f6ae0b756f1a842' - 'ba54c85612ed632ee2d79ef17f06b77c641b7b080aff52a03fc2462e8' - '0abc64d223723c236deeb7d201078ec01ca1fbc1763139e25099a84ec' - '389159c409792080736bd7caa816b92edf23f2c351f90074aa5ea2651' - 'b372f8b58a0a65554db2561d706a63685000ac576b7e4562e262a1428' - '5a9c6370b290e4eb7757527d80b6c0fd5df831d36f3d1d35f12ab0605' - '48de1605fd15f7c7aafed688b146a02c945156e284f5b71282045aba9' - '844d48b5df2e9e7a5887121eae7d7b01db7cdf6ff917cd8eb50c6bf1d' - '54f90cce1a491a9c74fea88f7e7230b047d16b5a6027881d6f154818f' - '06e513faf40c8814630e4e254f17a47bfe9cb519b98289935bf17673a' - 'e4c8033504a20a898d0032ee402b72d5986322f3bdfb27400561f7476' - 'cd715eaabb7338b854e51fc2fa026a5a579b6dcea1b1c0559c13d3c11' - '36f303f4b4d25ad5b692229957', 16), - 'q': int('d3eba6521240694015ef94412e08bf3cf8d635a455a398d6f210' - 'f6169041653b', 16), - 'x': int('b2764c46113983777d3e7e97589f1303806d14ad9f2f1ef03309' - '7de954b17706', 16), - 'y': int('814824e435e1e6f38daa239aad6dad21033afce6a3ebd35c1359348a0f2' - '418871968c2babfc2baf47742148828f8612183178f126504da73566b6' - 'bab33ba1f124c15aa461555c2451d86c94ee21c3e3fc24c55527e' - '01b1f03adcdd8ec5cb08082803a7b6a829c3e99eeb332a2cf5c035b0c' - 'e0078d3d414d31fa47e9726be2989b8d06da2e6cd363f5a7d1515e3f4' - '925e0b32adeae3025cc5a996f6fd27494ea408763de48f3bb39f6a06' - '514b019899b312ec570851637b8865cff3a52bf5d54ad5a19e6e400' - 'a2d33251055d0a440b50d53f4791391dc754ad02b9eab74c46b4903' - 'f9d76f824339914db108057af7cde657d41766a99991ac8787694f' - '4185d6f91d7627048f827b405ec67bf2fe56141c4c581d8c317333' - '624e073e5879a82437cb0c7b435c0ce434e15965db1315d648959' - '91e6bbe7dac040c42052408bbc53423fd31098248a58f8a67da3a' - '39895cd0cc927515d044c1e3cb6a3259c3d0da354cce89ea3552c' - '59609db10ee989986527436af21d9485ddf25f90f7dff6d2bae', 16)}, - {'g': int('ce84b30ddf290a9f787a7c2f1ce92c1cbf4ef400e3cd7ce4978d' - 'b2104d7394b493c18332c64cec906a71c3778bd93341165dee8' - 'e6cd4ca6f13afff531191194ada55ecf01ff94d6cf7c4768b82' - 'dd29cd131aaf202aefd40e564375285c01f3220af4d70b96f1' - '395420d778228f1461f5d0b8e47357e87b1fe3286223b553e3' - 'fc9928f16ae3067ded6721bedf1d1a01bfd22b9ae85fce77820d88cdf' - '50a6bde20668ad77a707d1c60fcc5d51c9de488610d0285eb8ff721f' - 'f141f93a9fb23c1d1f7654c07c46e58836d1652828f71057b8aff0b077' - '8ef2ca934ea9d0f37daddade2d823a4d8e362721082e279d003b575ee' - '59fd050d105dfd71cd63154efe431a0869178d9811f4f231dc5dcf3b' - '0ec0f2b0f9896c32ec6c7ee7d60aa97109e09224907328d4e6acd1011' - '7e45774406c4c947da8020649c3168f690e0bd6e91ac67074d1d436b' - '58ae374523deaf6c93c1e6920db4a080b744804bb073cecfe83fa939' - '8cf150afa286dc7eb7949750cf5001ce104e9187f7e16859afa8fd0d' - '775ae', 16), - 'p': int('f335666dd1339165af8b9a5e3835adfe15c158e4c3c7bd53132e7d5828' - 'c352f593a9a787760ce34b789879941f2f01f02319f6ae0b756f1a842' - 'ba54c85612ed632ee2d79ef17f06b77c641b7b080aff52a03fc2462e8' - '0abc64d223723c236deeb7d201078ec01ca1fbc1763139e25099a84ec' - '389159c409792080736bd7caa816b92edf23f2c351f90074aa5ea2651' - 'b372f8b58a0a65554db2561d706a63685000ac576b7e4562e262a1428' - '5a9c6370b290e4eb7757527d80b6c0fd5df831d36f3d1d35f12ab0605' - '48de1605fd15f7c7aafed688b146a02c945156e284f5b71282045aba9' - '844d48b5df2e9e7a5887121eae7d7b01db7cdf6ff917cd8eb50c6bf1d' - '54f90cce1a491a9c74fea88f7e7230b047d16b5a6027881d6f154818f' - '06e513faf40c8814630e4e254f17a47bfe9cb519b98289935bf17673a' - 'e4c8033504a20a898d0032ee402b72d5986322f3bdfb27400561f7476' - 'cd715eaabb7338b854e51fc2fa026a5a579b6dcea1b1c0559c13d3c11' - '36f303f4b4d25ad5b692229957', 16), - 'q': int('d3eba6521240694015ef94412e08bf3cf8d635a455a398d6f210' - 'f6169041653b', 16), - 'x': int('52e3e040efb30e1befd909a0bdbcfd140d005b1bff094af97186' - '080262f1904d', 16), - 'y': int('a5ae6e8f9b7a68ab0516dad4d7b7d002126f811d5a52e3d35c6d' - '387fcb43fd19bf7792362f9c98f8348aa058bb62376685f3d0c3' - '66c520d697fcd8416947151d4bbb6f32b53528a016479e99d2cd' - '48d1fc679027c15f0042f207984efe05c1796bca8eba678dfdd0' - '0b80418e3ea840557e73b09e003882f9a68edba3431d351d1ca0' - '7a8150b018fdbdf6c2f1ab475792a3ccaa6594472a45f8dc777b' - '60bf67de3e0f65c20d11b7d59faedf83fbce52617f500d9e5149' - '47c455274c6e900464767fb56599b81344cf6d12c25cb2b7d038' - 'd7b166b6cf30534811c15d0e8ab880a2ac06786ae2ddde61329a' - '78d526f65245380ce877e979c5b50de66c9c30d66382c8f25465' - '3d25a1eb1d3a4897d7623399b473ce712a2184cf2da1861706c4' - '1466806aefe41b497db82aca6c31c8f4aa68c17d1d9e380b5799' - '8917655783ec96e5234a131f7299398d36f1f5f84297a55ff292' - 'f1f060958c358fed346db2de45127ca728a9417b2c54203e33e5' - '3b9a061d924395b09afab8daf3e8dd7eedcec3ac', 16)} + { + "g": int( + "06b7861abbd35cc89e79c52f68d20875389b127361ca66822138ce499" + "1d2b862259d6b4548a6495b195aa0e0b6137ca37eb23b94074d3c3d3000" + "42bdf15762812b6333ef7b07ceba78607610fcc9ee68491dbc1e34cd12" + "615474e52b18bc934fb00c61d39e7da8902291c4434a4e2224c3f" + "4fd9f93cd6f4f17fc076341a7e7d9", + 16, + ), + "p": int( + "d38311e2cd388c3ed698e82fdf88eb92b5a9a483dc88005d4b725e" + "f341eabb47cf8a7a8a41e792a156b7ce97206c4f9c5ce6fc5ae791210" + "2b6b502e59050b5b21ce263dddb2044b652236f4d42ab4b5d6aa73189c" + "ef1ace778d7845a5c1c1c7147123188f8dc551054ee162b634d60f097f7" + "19076640e20980a0093113a8bd73", + 16, + ), + "q": int("96c5390a8b612c0e422bb2b0ea194a3ec935a281", 16), + "x": int("8185fee9cc7c0e91fd85503274f1cd5a3fd15a49", 16), + "y": int( + "6f26d98d41de7d871b6381851c9d91fa03942092ab6097e76422" + "070edb71db44ff568280fdb1709f8fc3feab39f1f824adaeb2a29808815" + "6ac31af1aa04bf54f475bdcfdcf2f8a2dd973e922d83e76f01655861760" + "3129b21c70bf7d0e5dc9e68fe332e295b65876eb9a12fe6fca9f1a1ce80" + "204646bf99b5771d249a6fea627", + 16, + ), + }, + { + "g": int( + "06b7861abbd35cc89e79c52f68d20875389b127361ca66822138ce4991d" + "2b862259d6b4548a6495b195aa0e0b6137ca37eb23b94074d3c3d30004" + "2bdf15762812b6333ef7b07ceba78607610fcc9ee68491dbc1e34cd126" + "15474e52b18bc934fb00c61d39e7da8902291c4434a4e2224c3f4fd9" + "f93cd6f4f17fc076341a7e7d9", + 16, + ), + "p": int( + "d38311e2cd388c3ed698e82fdf88eb92b5a9a483dc88005d4b725ef341e" + "abb47cf8a7a8a41e792a156b7ce97206c4f9c5ce6fc5ae7912102b6b50" + "2e59050b5b21ce263dddb2044b652236f4d42ab4b5d6aa73189cef1a" + "ce778d7845a5c1c1c7147123188f8dc551054ee162b634d6" + "0f097f719076640e20980a0093113a8bd73", + 16, + ), + "q": int("96c5390a8b612c0e422bb2b0ea194a3ec935a281", 16), + "x": int("85322d6ea73083064376099ca2f65f56e8522d9b", 16), + "y": int( + "21f8690f717c9f4dcb8f4b6971de2f15b9231fcf41b7eeb997d781f240" + "bfdddfd2090d22083c26cca39bf37c9caf1ec89518ea64845a50d747b49" + "131ffff6a2fd11ea7bacbb93c7d05137383a06365af82225dd3713c" + "a5a45006316f53bd12b0e260d5f79795e5a4c9f353f12867a1d3" + "202394673ada8563b71555e53f415254", + 16, + ), + }, + { + "g": int( + "e4c4eca88415b23ecf811c96e48cd24200fe916631a68a684e6ccb6b191" + "3413d344d1d8d84a333839d88eee431521f6e357c16e6a93be111a9807" + "6739cd401bab3b9d565bf4fb99e9d185b1e14d61c93700133f908bae0" + "3e28764d107dcd2ea7674217622074bb19efff482f5f5c1a86d5551b2" + "fc68d1c6e9d8011958ef4b9c2a3a55d0d3c882e6ad7f9f0f3c61568f78" + "d0706b10a26f23b4f197c322b825002284a0aca91807bba98ece912" + "b80e10cdf180cf99a35f210c1655fbfdd74f13b1b5046591f8403873d" + "12239834dd6c4eceb42bf7482e1794a1601357b629ddfa971f2ed273b1" + "46ec1ca06d0adf55dd91d65c37297bda78c6d210c0bc26e558302", + 16, + ), + "p": int( + "ea1fb1af22881558ef93be8a5f8653c5a559434c49c8c2c12ace" + "5e9c41434c9cf0a8e9498acb0f4663c08b4484eace845f6fb17d" + "ac62c98e706af0fc74e4da1c6c2b3fbf5a1d58ff82fc1a66f3e8b122" + "52c40278fff9dd7f102eed2cb5b7323ebf1908c234d935414dded7f8d2" + "44e54561b0dca39b301de8c49da9fb23df33c6182e3f983208c560fb5" + "119fbf78ebe3e6564ee235c6a15cbb9ac247baba5a423bc6582a1a9d8a" + "2b4f0e9e3d9dbac122f750dd754325135257488b1f6ecabf21bff2947" + "fe0d3b2cb7ffe67f4e7fcdf1214f6053e72a5bb0dd20a0e9fe6db2df0a" + "908c36e95e60bf49ca4368b8b892b9c79f61ef91c47567c40e1f80ac" + "5aa66ef7", + 16, + ), + "q": int( + "8ec73f3761caf5fdfe6e4e82098bf10f898740dcb808204bf6b1" + "8f507192c19d", + 16, + ), + "x": int( + "405772da6e90d809e77d5de796562a2dd4dfd10ef00a83a3aba6" + "bd818a0348a1", + 16, + ), + "y": int( + "6b32e31ab9031dc4dd0b5039a78d07826687ab087ae6de4736f5" + "b0434e1253092e8a0b231f9c87f3fc8a4cb5634eb194bf1b638" + "b7a7889620ce6711567e36aa36cda4604cfaa601a45918371d" + "4ccf68d8b10a50a0460eb1dc0fff62ef5e6ee4d473e18ea4a6" + "6c196fb7e677a49b48241a0b4a97128eff30fa437050501a584" + "f8771e7280d26d5af30784039159c11ebfea10b692fd0a58215ee" + "b18bff117e13f08db792ed4151a218e4bed8dddfb0793225bd1e97" + "73505166f4bd8cedbb286ea28232972da7bae836ba97329ba6b0a36508" + "e50a52a7675e476d4d4137eae13f22a9d2fefde708ba8f34bf336c6e7" + "6331761e4b0617633fe7ec3f23672fb19d27", + 16, + ), + }, + { + "g": int( + "e4c4eca88415b23ecf811c96e48cd24200fe916631a68a684e6ccb6b191" + "3413d344d1d8d84a333839d88eee431521f6e357c16e6a93be111a9807" + "6739cd401bab3b9d565bf4fb99e9d185b1e14d61c93700133f908bae0" + "3e28764d107dcd2ea7674217622074bb19efff482f5f5c1a86d5551b2" + "fc68d1c6e9d8011958ef4b9c2a3a55d0d3c882e6ad7f9f0f3c61568f78" + "d0706b10a26f23b4f197c322b825002284a0aca91807bba98ece912" + "b80e10cdf180cf99a35f210c1655fbfdd74f13b1b5046591f8403873d" + "12239834dd6c4eceb42bf7482e1794a1601357b629ddfa971f2ed273b1" + "46ec1ca06d0adf55dd91d65c37297bda78c6d210c0bc26e558302", + 16, + ), + "p": int( + "ea1fb1af22881558ef93be8a5f8653c5a559434c49c8c2c12ace" + "5e9c41434c9cf0a8e9498acb0f4663c08b4484eace845f6fb17d" + "ac62c98e706af0fc74e4da1c6c2b3fbf5a1d58ff82fc1a66f3e8b122" + "52c40278fff9dd7f102eed2cb5b7323ebf1908c234d935414dded7f8d2" + "44e54561b0dca39b301de8c49da9fb23df33c6182e3f983208c560fb5" + "119fbf78ebe3e6564ee235c6a15cbb9ac247baba5a423bc6582a1a9d8a" + "2b4f0e9e3d9dbac122f750dd754325135257488b1f6ecabf21bff2947" + "fe0d3b2cb7ffe67f4e7fcdf1214f6053e72a5bb0dd20a0e9fe6db2df0a" + "908c36e95e60bf49ca4368b8b892b9c79f61ef91c47567c40e1f80ac" + "5aa66ef7", + 16, + ), + "q": int( + "8ec73f3761caf5fdfe6e4e82098bf10f898740dcb808204bf6b1" + "8f507192c19d", + 16, + ), + "x": int( + "0e0b95e31fda3f888059c46c3002ef8f2d6be112d0209aeb9e95" + "45da67aeea80", + 16, + ), + "y": int( + "778082b77ddba6f56597cc74c3a612abf2ddbd85cc81430c99ab" + "843c1f630b9db0139965f563978164f9bf3a8397256be714625" + "cd41cd7fa0067d94ea66d7e073f7125af692ad01371d4a17f45" + "50590378f2b074030c20e36911598a1018772f61be3b24de4be" + "5a388ccc09e15a92819c31dec50de9fde105b49eaa097b9d13d" + "9219eeb33b628facfd1c78a7159c8430d0647c506e7e3de74763c" + "b351eada72c00bef3c9641881e6254870c1e6599f8ca2f1bbb74f" + "39a905e3a34e4544168e6e50c9e3305fd09cab6ed4aff6fda6e0d" + "5bf375c81ac9054406d9193b003c89272f1bd83d48250134b65c77" + "c2b6332d38d34d9016f0e8975536ad6c348a1faedb0", + 16, + ), + }, + { + "g": int( + "ce84b30ddf290a9f787a7c2f1ce92c1cbf4ef400e3cd7ce4978d" + "b2104d7394b493c18332c64cec906a71c3778bd93341165dee8" + "e6cd4ca6f13afff531191194ada55ecf01ff94d6cf7c4768b82" + "dd29cd131aaf202aefd40e564375285c01f3220af4d70b96f1" + "395420d778228f1461f5d0b8e47357e87b1fe3286223b553e3" + "fc9928f16ae3067ded6721bedf1d1a01bfd22b9ae85fce77820d88cdf" + "50a6bde20668ad77a707d1c60fcc5d51c9de488610d0285eb8ff721f" + "f141f93a9fb23c1d1f7654c07c46e58836d1652828f71057b8aff0b077" + "8ef2ca934ea9d0f37daddade2d823a4d8e362721082e279d003b575ee" + "59fd050d105dfd71cd63154efe431a0869178d9811f4f231dc5dcf3b" + "0ec0f2b0f9896c32ec6c7ee7d60aa97109e09224907328d4e6acd1011" + "7e45774406c4c947da8020649c3168f690e0bd6e91ac67074d1d436b" + "58ae374523deaf6c93c1e6920db4a080b744804bb073cecfe83fa939" + "8cf150afa286dc7eb7949750cf5001ce104e9187f7e16859afa8fd0d" + "775ae", + 16, + ), + "p": int( + "f335666dd1339165af8b9a5e3835adfe15c158e4c3c7bd53132e7d5828" + "c352f593a9a787760ce34b789879941f2f01f02319f6ae0b756f1a842" + "ba54c85612ed632ee2d79ef17f06b77c641b7b080aff52a03fc2462e8" + "0abc64d223723c236deeb7d201078ec01ca1fbc1763139e25099a84ec" + "389159c409792080736bd7caa816b92edf23f2c351f90074aa5ea2651" + "b372f8b58a0a65554db2561d706a63685000ac576b7e4562e262a1428" + "5a9c6370b290e4eb7757527d80b6c0fd5df831d36f3d1d35f12ab0605" + "48de1605fd15f7c7aafed688b146a02c945156e284f5b71282045aba9" + "844d48b5df2e9e7a5887121eae7d7b01db7cdf6ff917cd8eb50c6bf1d" + "54f90cce1a491a9c74fea88f7e7230b047d16b5a6027881d6f154818f" + "06e513faf40c8814630e4e254f17a47bfe9cb519b98289935bf17673a" + "e4c8033504a20a898d0032ee402b72d5986322f3bdfb27400561f7476" + "cd715eaabb7338b854e51fc2fa026a5a579b6dcea1b1c0559c13d3c11" + "36f303f4b4d25ad5b692229957", + 16, + ), + "q": int( + "d3eba6521240694015ef94412e08bf3cf8d635a455a398d6f210" + "f6169041653b", + 16, + ), + "x": int( + "b2764c46113983777d3e7e97589f1303806d14ad9f2f1ef03309" + "7de954b17706", + 16, + ), + "y": int( + "814824e435e1e6f38daa239aad6dad21033afce6a3ebd35c1359348a0f2" + "418871968c2babfc2baf47742148828f8612183178f126504da73566b6" + "bab33ba1f124c15aa461555c2451d86c94ee21c3e3fc24c55527e" + "01b1f03adcdd8ec5cb08082803a7b6a829c3e99eeb332a2cf5c035b0c" + "e0078d3d414d31fa47e9726be2989b8d06da2e6cd363f5a7d1515e3f4" + "925e0b32adeae3025cc5a996f6fd27494ea408763de48f3bb39f6a06" + "514b019899b312ec570851637b8865cff3a52bf5d54ad5a19e6e400" + "a2d33251055d0a440b50d53f4791391dc754ad02b9eab74c46b4903" + "f9d76f824339914db108057af7cde657d41766a99991ac8787694f" + "4185d6f91d7627048f827b405ec67bf2fe56141c4c581d8c317333" + "624e073e5879a82437cb0c7b435c0ce434e15965db1315d648959" + "91e6bbe7dac040c42052408bbc53423fd31098248a58f8a67da3a" + "39895cd0cc927515d044c1e3cb6a3259c3d0da354cce89ea3552c" + "59609db10ee989986527436af21d9485ddf25f90f7dff6d2bae", + 16, + ), + }, + { + "g": int( + "ce84b30ddf290a9f787a7c2f1ce92c1cbf4ef400e3cd7ce4978d" + "b2104d7394b493c18332c64cec906a71c3778bd93341165dee8" + "e6cd4ca6f13afff531191194ada55ecf01ff94d6cf7c4768b82" + "dd29cd131aaf202aefd40e564375285c01f3220af4d70b96f1" + "395420d778228f1461f5d0b8e47357e87b1fe3286223b553e3" + "fc9928f16ae3067ded6721bedf1d1a01bfd22b9ae85fce77820d88cdf" + "50a6bde20668ad77a707d1c60fcc5d51c9de488610d0285eb8ff721f" + "f141f93a9fb23c1d1f7654c07c46e58836d1652828f71057b8aff0b077" + "8ef2ca934ea9d0f37daddade2d823a4d8e362721082e279d003b575ee" + "59fd050d105dfd71cd63154efe431a0869178d9811f4f231dc5dcf3b" + "0ec0f2b0f9896c32ec6c7ee7d60aa97109e09224907328d4e6acd1011" + "7e45774406c4c947da8020649c3168f690e0bd6e91ac67074d1d436b" + "58ae374523deaf6c93c1e6920db4a080b744804bb073cecfe83fa939" + "8cf150afa286dc7eb7949750cf5001ce104e9187f7e16859afa8fd0d" + "775ae", + 16, + ), + "p": int( + "f335666dd1339165af8b9a5e3835adfe15c158e4c3c7bd53132e7d5828" + "c352f593a9a787760ce34b789879941f2f01f02319f6ae0b756f1a842" + "ba54c85612ed632ee2d79ef17f06b77c641b7b080aff52a03fc2462e8" + "0abc64d223723c236deeb7d201078ec01ca1fbc1763139e25099a84ec" + "389159c409792080736bd7caa816b92edf23f2c351f90074aa5ea2651" + "b372f8b58a0a65554db2561d706a63685000ac576b7e4562e262a1428" + "5a9c6370b290e4eb7757527d80b6c0fd5df831d36f3d1d35f12ab0605" + "48de1605fd15f7c7aafed688b146a02c945156e284f5b71282045aba9" + "844d48b5df2e9e7a5887121eae7d7b01db7cdf6ff917cd8eb50c6bf1d" + "54f90cce1a491a9c74fea88f7e7230b047d16b5a6027881d6f154818f" + "06e513faf40c8814630e4e254f17a47bfe9cb519b98289935bf17673a" + "e4c8033504a20a898d0032ee402b72d5986322f3bdfb27400561f7476" + "cd715eaabb7338b854e51fc2fa026a5a579b6dcea1b1c0559c13d3c11" + "36f303f4b4d25ad5b692229957", + 16, + ), + "q": int( + "d3eba6521240694015ef94412e08bf3cf8d635a455a398d6f210" + "f6169041653b", + 16, + ), + "x": int( + "52e3e040efb30e1befd909a0bdbcfd140d005b1bff094af97186" + "080262f1904d", + 16, + ), + "y": int( + "a5ae6e8f9b7a68ab0516dad4d7b7d002126f811d5a52e3d35c6d" + "387fcb43fd19bf7792362f9c98f8348aa058bb62376685f3d0c3" + "66c520d697fcd8416947151d4bbb6f32b53528a016479e99d2cd" + "48d1fc679027c15f0042f207984efe05c1796bca8eba678dfdd0" + "0b80418e3ea840557e73b09e003882f9a68edba3431d351d1ca0" + "7a8150b018fdbdf6c2f1ab475792a3ccaa6594472a45f8dc777b" + "60bf67de3e0f65c20d11b7d59faedf83fbce52617f500d9e5149" + "47c455274c6e900464767fb56599b81344cf6d12c25cb2b7d038" + "d7b166b6cf30534811c15d0e8ab880a2ac06786ae2ddde61329a" + "78d526f65245380ce877e979c5b50de66c9c30d66382c8f25465" + "3d25a1eb1d3a4897d7623399b473ce712a2184cf2da1861706c4" + "1466806aefe41b497db82aca6c31c8f4aa68c17d1d9e380b5799" + "8917655783ec96e5234a131f7299398d36f1f5f84297a55ff292" + "f1f060958c358fed346db2de45127ca728a9417b2c54203e33e5" + "3b9a061d924395b09afab8daf3e8dd7eedcec3ac", + 16, + ), + }, ] assert expected == load_fips_dsa_key_pair_vectors(vector_data) def test_load_fips_dsa_sig_ver_vectors(): - vector_data = textwrap.dedent(""" + vector_data = textwrap.dedent( + """ # CAVS 11.0 # "SigVer" information # Mod sizes selected: SHA-1 L=1024, N=160,SHA-384 L=2048, N=256 @@ -1902,166 +2123,236 @@ def test_load_fips_dsa_sig_ver_vectors(): R = 343ea0a9e66277380f604d5880fca686bffab69ca97bfba015a102a7e23dce0e S = 6258488c770e0f5ad7b9da8bade5023fc0d17c6ec517bd08d53e6dc01ac5c2b3 Result = P - """).splitlines() + """ + ).splitlines() expected = [ { - 'p': int('dc5bf3a88b2d99e4c95cdd7a0501cc38630d425cf5c390af3429cff1' - 'f35147b795caea923f0d3577158f8a0c89dabd1962c2c453306b5d70' - 'cacfb01430aceb54e5a5fa6f9340d3bd2da612fceeb76b0ec1ebfae6' - '35a56ab141b108e00dc76eefe2edd0c514c21c457457c39065dba9d0' - 'ecb7569c247172d8438ad2827b60435b', 16), - 'q': int('e956602b83d195dbe945b3ac702fc61f81571f1d', 16), - 'g': int('d7eb9ca20a3c7a079606bafc4c9261ccaba303a5dc9fe9953f197dfe' - '548c234895baa77f441ee6a2d97b909cbbd26ff7b869d24cae51b5c6' - 'edb127a4b5d75cd8b46608bfa148249dffdb59807c5d7dde3fe3080c' - 'a3a2d28312142becb1fa8e24003e21c7287108174b95d5bc711e1c8d' - '9b1076784f5dc37a964a5e51390da713', 16), - 'digest_algorithm': 'SHA-1', - 'msg': binascii.unhexlify( - b'0fe1bfee500bdb76026099b1d37553f6bdfe48c82094ef98cb309dd77733' - b'0bedfaa2f94c823ef74ef4074b50d8706041ac0e371c7c22dcf70263b8d6' - b'0e17a86c7c379cfda8f22469e0df9d49d59439fc99891873628fff25dda5' - b'fac5ac794e948babdde968143ba05f1128f34fdad5875edc4cd71c6c24ba' - b'2060ffbd439ce2b3'), - 'x': int('1d93010c29ecfc432188942f46f19f44f0e1bb5d', 16), - 'y': int('6240ea0647117c38fe705106d56db578f3e10130928452d4f3587881' - 'b8a2bc6873a8befc3237f20914e2a91c7f07a928ee22adeed23d74ab' - '7f82ea11f70497e578f7a9b4cbd6f10226222b0b4da2ea1e49813d6b' - 'b9882fbf675c0846bb80cc891857b89b0ef1beb6cce3378a9aab5d66' - 'ad4cb9277cf447dfe1e64434749432fb', 16), - 'r': int('b5af307867fb8b54390013cc67020ddf1f2c0b81', 16), - 's': int('620d3b22ab5031440c3e35eab6f481298f9e9f08', 16), - 'result': 'P'}, - { - 'p': int('dc5bf3a88b2d99e4c95cdd7a0501cc38630d425cf5c390af3429cff1' - 'f35147b795caea923f0d3577158f8a0c89dabd1962c2c453306b5d70' - 'cacfb01430aceb54e5a5fa6f9340d3bd2da612fceeb76b0ec1ebfae6' - '35a56ab141b108e00dc76eefe2edd0c514c21c457457c39065dba9d0' - 'ecb7569c247172d8438ad2827b60435b', 16), - 'q': int('e956602b83d195dbe945b3ac702fc61f81571f1d', 16), - 'g': int('d7eb9ca20a3c7a079606bafc4c9261ccaba303a5dc9fe9953f197dfe' - '548c234895baa77f441ee6a2d97b909cbbd26ff7b869d24cae51b5c6' - 'edb127a4b5d75cd8b46608bfa148249dffdb59807c5d7dde3fe3080c' - 'a3a2d28312142becb1fa8e24003e21c7287108174b95d5bc711e1c8d' - '9b1076784f5dc37a964a5e51390da713', 16), - 'digest_algorithm': 'SHA-1', - 'msg': binascii.unhexlify( - b'97d50898025d2f9ba633866e968ca75e969d394edba6517204cb3dd537c2' - b'ba38778a2dc9dbc685a915e5676fcd43bc3726bc59ce3d7a9fae35565082' - b'a069c139fa37c90d922b126933db3fa6c5ef6b1edf00d174a51887bb7690' - b'9c6a94fe994ecc7b7fc8f26113b17f30f9d01693df99a125b4f17e184331' - b'c6b6e8ca00f54f3a'), - 'x': int('350e13534692a7e0c4b7d58836046c436fbb2322', 16), - 'y': int('69974de550fe6bd3099150faea1623ad3fb6d9bf23a07215093f3197' - '25ad0877accffd291b6da18eb0cbe51676ceb0977504eb97c27c0b19' - '1883f72fb2710a9fbd8bcf13be0bf854410b32f42b33ec89d3cc1cf8' - '92bcd536c4195ca9ada302ad600c3408739935d77dc247529ca47f84' - '4cc86f5016a2fe962c6e20ca7c4d4e8f', 16), - 'r': int('b5d05faa7005764e8dae0327c5bf1972ff7681b9', 16), - 's': int('18ea15bd9f00475b25204cbc23f8c23e01588015', 16), - 'result': 'F'}, - { - 'p': int('e7c1c86125db9ef417da1ced7ea0861bdad629216a3f3c745df42a4' - '6b989e59f4d98425ee3c932fa3c2b6f637bdb6545bec526faa037e1' - '1f5578a4363b9fca5eba60d6a9cbaa2befd04141d989c7356285132' - 'c2eaf74f2d868521cdc0a17ae9a2546ef863027d3f8cc7949631fd0' - 'e2971417a912c8b8c5c989730db6ea6e8baee0e667850429038093c' - '851ccb6fb173bb081e0efe0bd7450e0946888f89f75e443ab93ef2d' - 'a293a01622cf43c6dd79625d41ba8f9ef7e3086ab39134283d8e96c' - '89249488120fd061e4a87d34af41069c0b4fd3934c31b589cbe85b6' - '8b912718d5dab859fda7082511fad1d152044905005546e19b14aa9' - '6585a55269bf2b831', 16), - 'q': int('8e056ec9d4b7acb580087a6ed9ba3478711bb025d5b8d9c731ef9b3' - '8bd43db2f', 16), - 'g': int('dc2bfb9776786ad310c8b0cdcbba3062402613c67e6959a8d8d1b05' - 'aab636528b7b1fe9cd33765f853d6dbe13d09f2681f8c7b1ed7886a' - 'aed70c7bd76dbe858ffb8bd86235ddf759244678f428c6519af593d' - 'c94eeadbd9852ba2b3d61664e8d58c29d2039af3c3d6d16f90988f6' - 'a8c824569f3d48050e30896a9e17cd0232ef01ab8790008f6973b84' - 'c763a72f4ae8b485abfb7e8efeb86808fa2b281d3e5d65d28f5992a' - '34c077c5aa8026cb2fbc34a45f7e9bd216b10e6f12ecb172e9a6eb8' - 'f2e91316905b6add1fd22e83bc2f089f1d5e6a6e6707c18ff55ddcb' - '7954e8bceaf0efc4e8314910c03b0e51175f344faafee476a373ac9' - '5743cec712b72cf2e', 16), - 'digest_algorithm': 'SHA-384', - 'msg': binascii.unhexlify( - b'6cd6ccfd66bcd832189c5f0c77994210e3bf2c43416f0fe77c4e92f31c5' - b'369538dc2c003f146c5ac79df43194ccf3c44d470d9f1083bd15b99b5bc' - b'f88c32d8a9021f09ea2288d7b3bf345a12aef3949c1e121b9fb371a67c2' - b'd1377364206ac839dd78483561426bda0303f285aa12e9c45d3cdfc6bea' - b'e3549703b187deeb3296'), - 'x': int('56c897b5938ad5b3d437d7e4826da586a6b3be15e893fa1aaa946f2' - '0a028b6b3', 16), - 'y': int('38ad44489e1a5778b9689f4dcf40e2acf23840fb954e987d6e8cb62' - '9106328ac64e1f3c3eba48b21176ad4afe3b733bead382ee1597e1b' - '83e4b43424f2daaba04e5bd79e1436693ac2bddb79a298f026e57e2' - '00a252efd1e848a4a2e90be6e78f5242b468b9c0c6d2615047a5a40' - 'b9ae7e57a519114db55bf3bed65e580f894b094630ca9c217f6accd' - '091e72d2f22da620044ff372d7273f9445017fad492959e59600b74' - '94dbe766a03e40125d4e6747c76f68a5b0cdc0e7d7cee12d08c6fb7' - 'd0fb049e420a33405075ed4463296345ca695fb7feab7c1b5333ae5' - '19fcd4bb6a043f4555378969114743d4face96cad31c0e0089da4e3' - 'f61b6d7dabc088ab7', 16), - 'r': int('3b85b17be240ed658beb3652c9d93e8e9eea160d35ee24596143058' - '02963374e', 16), - 's': int('726800a5174a53b56dce86064109c0273cd11fcfa3c92c5cd6aa910' - '260c0e3c7', 16), - 'result': 'F'}, - { - 'p': int('e7c1c86125db9ef417da1ced7ea0861bdad629216a3f3c745df42a4' - '6b989e59f4d98425ee3c932fa3c2b6f637bdb6545bec526faa037e1' - '1f5578a4363b9fca5eba60d6a9cbaa2befd04141d989c7356285132' - 'c2eaf74f2d868521cdc0a17ae9a2546ef863027d3f8cc7949631fd0' - 'e2971417a912c8b8c5c989730db6ea6e8baee0e667850429038093c' - '851ccb6fb173bb081e0efe0bd7450e0946888f89f75e443ab93ef2d' - 'a293a01622cf43c6dd79625d41ba8f9ef7e3086ab39134283d8e96c' - '89249488120fd061e4a87d34af41069c0b4fd3934c31b589cbe85b6' - '8b912718d5dab859fda7082511fad1d152044905005546e19b14aa9' - '6585a55269bf2b831', 16), - 'q': int('8e056ec9d4b7acb580087a6ed9ba3478711bb025d5b8d9c731ef9b3' - '8bd43db2f', 16), - 'g': int('dc2bfb9776786ad310c8b0cdcbba3062402613c67e6959a8d8d1b05' - 'aab636528b7b1fe9cd33765f853d6dbe13d09f2681f8c7b1ed7886a' - 'aed70c7bd76dbe858ffb8bd86235ddf759244678f428c6519af593d' - 'c94eeadbd9852ba2b3d61664e8d58c29d2039af3c3d6d16f90988f6' - 'a8c824569f3d48050e30896a9e17cd0232ef01ab8790008f6973b84' - 'c763a72f4ae8b485abfb7e8efeb86808fa2b281d3e5d65d28f5992a' - '34c077c5aa8026cb2fbc34a45f7e9bd216b10e6f12ecb172e9a6eb8' - 'f2e91316905b6add1fd22e83bc2f089f1d5e6a6e6707c18ff55ddcb' - '7954e8bceaf0efc4e8314910c03b0e51175f344faafee476a373ac9' - '5743cec712b72cf2e', 16), - 'digest_algorithm': 'SHA-384', - 'msg': binascii.unhexlify( - b'3ad6b0884f358dea09c31a9abc40c45a6000611fc2b907b30eac00413fd' - b'2819de7015488a411609d46c499b8f7afa1b78b352ac7f8535bd805b8ff' - b'2a5eae557098c668f7ccd73af886d6823a6d456c29931ee864ed46d7673' - b'82785728c2a83fcff5271007d2a67d06fa205fd7b9d1a42ea5d6dc76e5e' - b'18a9eb148cd1e8b262ae'), - 'x': int('2faf566a9f057960f1b50c69508f483d9966d6e35743591f3a677a9' - 'dc40e1555', 16), - 'y': int('926425d617babe87c442b03903e32ba5bbf0cd9d602b59c4df791a4d' - '64a6d4333ca0c0d370552539197d327dcd1bbf8c454f24b03fc7805f' - '862db34c7b066ddfddbb11dbd010b27123062d028fe041cb56a2e774' - '88348ae0ab6705d87aac4d4e9e6600e9e706326d9979982cffa839be' - 'b9eacc3963bcca455a507e80c1c37ad4e765b2c9c0477a075e9bc584' - 'feacdf3a35a9391d4711f14e197c54022282bfed9a191213d64127f1' - '7a9c5affec26e0c71f15d3a5b16098fec118c45bf8bb2f3b1560df09' - '49254c1c0aeb0a16d5a95a40fab8521fbe8ea77c51169b587cc3360e' - '5733e6a23b9fded8c40724ea1f9e93614b3a6c9b4f8dbbe915b79449' - '7227ba62', 16), - 'r': int('343ea0a9e66277380f604d5880fca686bffab69ca97bfba015a102a' - '7e23dce0e', 16), - 's': int('6258488c770e0f5ad7b9da8bade5023fc0d17c6ec517bd08d53e6dc' - '01ac5c2b3', 16), - 'result': 'P'} + "p": int( + "dc5bf3a88b2d99e4c95cdd7a0501cc38630d425cf5c390af3429cff1" + "f35147b795caea923f0d3577158f8a0c89dabd1962c2c453306b5d70" + "cacfb01430aceb54e5a5fa6f9340d3bd2da612fceeb76b0ec1ebfae6" + "35a56ab141b108e00dc76eefe2edd0c514c21c457457c39065dba9d0" + "ecb7569c247172d8438ad2827b60435b", + 16, + ), + "q": int("e956602b83d195dbe945b3ac702fc61f81571f1d", 16), + "g": int( + "d7eb9ca20a3c7a079606bafc4c9261ccaba303a5dc9fe9953f197dfe" + "548c234895baa77f441ee6a2d97b909cbbd26ff7b869d24cae51b5c6" + "edb127a4b5d75cd8b46608bfa148249dffdb59807c5d7dde3fe3080c" + "a3a2d28312142becb1fa8e24003e21c7287108174b95d5bc711e1c8d" + "9b1076784f5dc37a964a5e51390da713", + 16, + ), + "digest_algorithm": "SHA-1", + "msg": binascii.unhexlify( + b"0fe1bfee500bdb76026099b1d37553f6bdfe48c82094ef98cb309dd77733" + b"0bedfaa2f94c823ef74ef4074b50d8706041ac0e371c7c22dcf70263b8d6" + b"0e17a86c7c379cfda8f22469e0df9d49d59439fc99891873628fff25dda5" + b"fac5ac794e948babdde968143ba05f1128f34fdad5875edc4cd71c6c24ba" + b"2060ffbd439ce2b3" + ), + "x": int("1d93010c29ecfc432188942f46f19f44f0e1bb5d", 16), + "y": int( + "6240ea0647117c38fe705106d56db578f3e10130928452d4f3587881" + "b8a2bc6873a8befc3237f20914e2a91c7f07a928ee22adeed23d74ab" + "7f82ea11f70497e578f7a9b4cbd6f10226222b0b4da2ea1e49813d6b" + "b9882fbf675c0846bb80cc891857b89b0ef1beb6cce3378a9aab5d66" + "ad4cb9277cf447dfe1e64434749432fb", + 16, + ), + "r": int("b5af307867fb8b54390013cc67020ddf1f2c0b81", 16), + "s": int("620d3b22ab5031440c3e35eab6f481298f9e9f08", 16), + "result": "P", + }, + { + "p": int( + "dc5bf3a88b2d99e4c95cdd7a0501cc38630d425cf5c390af3429cff1" + "f35147b795caea923f0d3577158f8a0c89dabd1962c2c453306b5d70" + "cacfb01430aceb54e5a5fa6f9340d3bd2da612fceeb76b0ec1ebfae6" + "35a56ab141b108e00dc76eefe2edd0c514c21c457457c39065dba9d0" + "ecb7569c247172d8438ad2827b60435b", + 16, + ), + "q": int("e956602b83d195dbe945b3ac702fc61f81571f1d", 16), + "g": int( + "d7eb9ca20a3c7a079606bafc4c9261ccaba303a5dc9fe9953f197dfe" + "548c234895baa77f441ee6a2d97b909cbbd26ff7b869d24cae51b5c6" + "edb127a4b5d75cd8b46608bfa148249dffdb59807c5d7dde3fe3080c" + "a3a2d28312142becb1fa8e24003e21c7287108174b95d5bc711e1c8d" + "9b1076784f5dc37a964a5e51390da713", + 16, + ), + "digest_algorithm": "SHA-1", + "msg": binascii.unhexlify( + b"97d50898025d2f9ba633866e968ca75e969d394edba6517204cb3dd537c2" + b"ba38778a2dc9dbc685a915e5676fcd43bc3726bc59ce3d7a9fae35565082" + b"a069c139fa37c90d922b126933db3fa6c5ef6b1edf00d174a51887bb7690" + b"9c6a94fe994ecc7b7fc8f26113b17f30f9d01693df99a125b4f17e184331" + b"c6b6e8ca00f54f3a" + ), + "x": int("350e13534692a7e0c4b7d58836046c436fbb2322", 16), + "y": int( + "69974de550fe6bd3099150faea1623ad3fb6d9bf23a07215093f3197" + "25ad0877accffd291b6da18eb0cbe51676ceb0977504eb97c27c0b19" + "1883f72fb2710a9fbd8bcf13be0bf854410b32f42b33ec89d3cc1cf8" + "92bcd536c4195ca9ada302ad600c3408739935d77dc247529ca47f84" + "4cc86f5016a2fe962c6e20ca7c4d4e8f", + 16, + ), + "r": int("b5d05faa7005764e8dae0327c5bf1972ff7681b9", 16), + "s": int("18ea15bd9f00475b25204cbc23f8c23e01588015", 16), + "result": "F", + }, + { + "p": int( + "e7c1c86125db9ef417da1ced7ea0861bdad629216a3f3c745df42a4" + "6b989e59f4d98425ee3c932fa3c2b6f637bdb6545bec526faa037e1" + "1f5578a4363b9fca5eba60d6a9cbaa2befd04141d989c7356285132" + "c2eaf74f2d868521cdc0a17ae9a2546ef863027d3f8cc7949631fd0" + "e2971417a912c8b8c5c989730db6ea6e8baee0e667850429038093c" + "851ccb6fb173bb081e0efe0bd7450e0946888f89f75e443ab93ef2d" + "a293a01622cf43c6dd79625d41ba8f9ef7e3086ab39134283d8e96c" + "89249488120fd061e4a87d34af41069c0b4fd3934c31b589cbe85b6" + "8b912718d5dab859fda7082511fad1d152044905005546e19b14aa9" + "6585a55269bf2b831", + 16, + ), + "q": int( + "8e056ec9d4b7acb580087a6ed9ba3478711bb025d5b8d9c731ef9b3" + "8bd43db2f", + 16, + ), + "g": int( + "dc2bfb9776786ad310c8b0cdcbba3062402613c67e6959a8d8d1b05" + "aab636528b7b1fe9cd33765f853d6dbe13d09f2681f8c7b1ed7886a" + "aed70c7bd76dbe858ffb8bd86235ddf759244678f428c6519af593d" + "c94eeadbd9852ba2b3d61664e8d58c29d2039af3c3d6d16f90988f6" + "a8c824569f3d48050e30896a9e17cd0232ef01ab8790008f6973b84" + "c763a72f4ae8b485abfb7e8efeb86808fa2b281d3e5d65d28f5992a" + "34c077c5aa8026cb2fbc34a45f7e9bd216b10e6f12ecb172e9a6eb8" + "f2e91316905b6add1fd22e83bc2f089f1d5e6a6e6707c18ff55ddcb" + "7954e8bceaf0efc4e8314910c03b0e51175f344faafee476a373ac9" + "5743cec712b72cf2e", + 16, + ), + "digest_algorithm": "SHA-384", + "msg": binascii.unhexlify( + b"6cd6ccfd66bcd832189c5f0c77994210e3bf2c43416f0fe77c4e92f31c5" + b"369538dc2c003f146c5ac79df43194ccf3c44d470d9f1083bd15b99b5bc" + b"f88c32d8a9021f09ea2288d7b3bf345a12aef3949c1e121b9fb371a67c2" + b"d1377364206ac839dd78483561426bda0303f285aa12e9c45d3cdfc6bea" + b"e3549703b187deeb3296" + ), + "x": int( + "56c897b5938ad5b3d437d7e4826da586a6b3be15e893fa1aaa946f2" + "0a028b6b3", + 16, + ), + "y": int( + "38ad44489e1a5778b9689f4dcf40e2acf23840fb954e987d6e8cb62" + "9106328ac64e1f3c3eba48b21176ad4afe3b733bead382ee1597e1b" + "83e4b43424f2daaba04e5bd79e1436693ac2bddb79a298f026e57e2" + "00a252efd1e848a4a2e90be6e78f5242b468b9c0c6d2615047a5a40" + "b9ae7e57a519114db55bf3bed65e580f894b094630ca9c217f6accd" + "091e72d2f22da620044ff372d7273f9445017fad492959e59600b74" + "94dbe766a03e40125d4e6747c76f68a5b0cdc0e7d7cee12d08c6fb7" + "d0fb049e420a33405075ed4463296345ca695fb7feab7c1b5333ae5" + "19fcd4bb6a043f4555378969114743d4face96cad31c0e0089da4e3" + "f61b6d7dabc088ab7", + 16, + ), + "r": int( + "3b85b17be240ed658beb3652c9d93e8e9eea160d35ee24596143058" + "02963374e", + 16, + ), + "s": int( + "726800a5174a53b56dce86064109c0273cd11fcfa3c92c5cd6aa910" + "260c0e3c7", + 16, + ), + "result": "F", + }, + { + "p": int( + "e7c1c86125db9ef417da1ced7ea0861bdad629216a3f3c745df42a4" + "6b989e59f4d98425ee3c932fa3c2b6f637bdb6545bec526faa037e1" + "1f5578a4363b9fca5eba60d6a9cbaa2befd04141d989c7356285132" + "c2eaf74f2d868521cdc0a17ae9a2546ef863027d3f8cc7949631fd0" + "e2971417a912c8b8c5c989730db6ea6e8baee0e667850429038093c" + "851ccb6fb173bb081e0efe0bd7450e0946888f89f75e443ab93ef2d" + "a293a01622cf43c6dd79625d41ba8f9ef7e3086ab39134283d8e96c" + "89249488120fd061e4a87d34af41069c0b4fd3934c31b589cbe85b6" + "8b912718d5dab859fda7082511fad1d152044905005546e19b14aa9" + "6585a55269bf2b831", + 16, + ), + "q": int( + "8e056ec9d4b7acb580087a6ed9ba3478711bb025d5b8d9c731ef9b3" + "8bd43db2f", + 16, + ), + "g": int( + "dc2bfb9776786ad310c8b0cdcbba3062402613c67e6959a8d8d1b05" + "aab636528b7b1fe9cd33765f853d6dbe13d09f2681f8c7b1ed7886a" + "aed70c7bd76dbe858ffb8bd86235ddf759244678f428c6519af593d" + "c94eeadbd9852ba2b3d61664e8d58c29d2039af3c3d6d16f90988f6" + "a8c824569f3d48050e30896a9e17cd0232ef01ab8790008f6973b84" + "c763a72f4ae8b485abfb7e8efeb86808fa2b281d3e5d65d28f5992a" + "34c077c5aa8026cb2fbc34a45f7e9bd216b10e6f12ecb172e9a6eb8" + "f2e91316905b6add1fd22e83bc2f089f1d5e6a6e6707c18ff55ddcb" + "7954e8bceaf0efc4e8314910c03b0e51175f344faafee476a373ac9" + "5743cec712b72cf2e", + 16, + ), + "digest_algorithm": "SHA-384", + "msg": binascii.unhexlify( + b"3ad6b0884f358dea09c31a9abc40c45a6000611fc2b907b30eac00413fd" + b"2819de7015488a411609d46c499b8f7afa1b78b352ac7f8535bd805b8ff" + b"2a5eae557098c668f7ccd73af886d6823a6d456c29931ee864ed46d7673" + b"82785728c2a83fcff5271007d2a67d06fa205fd7b9d1a42ea5d6dc76e5e" + b"18a9eb148cd1e8b262ae" + ), + "x": int( + "2faf566a9f057960f1b50c69508f483d9966d6e35743591f3a677a9" + "dc40e1555", + 16, + ), + "y": int( + "926425d617babe87c442b03903e32ba5bbf0cd9d602b59c4df791a4d" + "64a6d4333ca0c0d370552539197d327dcd1bbf8c454f24b03fc7805f" + "862db34c7b066ddfddbb11dbd010b27123062d028fe041cb56a2e774" + "88348ae0ab6705d87aac4d4e9e6600e9e706326d9979982cffa839be" + "b9eacc3963bcca455a507e80c1c37ad4e765b2c9c0477a075e9bc584" + "feacdf3a35a9391d4711f14e197c54022282bfed9a191213d64127f1" + "7a9c5affec26e0c71f15d3a5b16098fec118c45bf8bb2f3b1560df09" + "49254c1c0aeb0a16d5a95a40fab8521fbe8ea77c51169b587cc3360e" + "5733e6a23b9fded8c40724ea1f9e93614b3a6c9b4f8dbbe915b79449" + "7227ba62", + 16, + ), + "r": int( + "343ea0a9e66277380f604d5880fca686bffab69ca97bfba015a102a" + "7e23dce0e", + 16, + ), + "s": int( + "6258488c770e0f5ad7b9da8bade5023fc0d17c6ec517bd08d53e6dc" + "01ac5c2b3", + 16, + ), + "result": "P", + }, ] assert expected == load_fips_dsa_sig_vectors(vector_data) def test_load_fips_dsa_sig_gen_vectors(): - vector_data = textwrap.dedent(""" + vector_data = textwrap.dedent( + """ # CAVS 11.2 # "SigGen" information for "dsa2_values" # Mod sizes selected: SHA-1 L=1024, N=160, SHA-256 L=2048, N=256 @@ -2145,155 +2436,219 @@ def test_load_fips_dsa_sig_gen_vectors(): 60bc1dc46f78ceaaa2c02f5375dd82e708744aa40b15799eb81d7e5b1a R = bcd490568c0a89ba311bef88ea4f4b03d273e793722722327095a378dd6f3522 S = 74498fc43091fcdd2d1ef0775f8286945a01cd72b805256b0451f9cbd943cf82 - """).splitlines() + """ + ).splitlines() expected = [ { - 'p': int('a8f9cd201e5e35d892f85f80e4db2599a5676a3b1d4f190330ed325' - '6b26d0e80a0e49a8fffaaad2a24f472d2573241d4d6d6c7480c80b4' - 'c67bb4479c15ada7ea8424d2502fa01472e760241713dab025ae1b0' - '2e1703a1435f62ddf4ee4c1b664066eb22f2e3bf28bb70a2a76e4fd' - '5ebe2d1229681b5b06439ac9c7e9d8bde283', 16), - 'q': int('f85f0f83ac4df7ea0cdf8f469bfeeaea14156495', 16), - 'g': int('2b3152ff6c62f14622b8f48e59f8af46883b38e79b8c74deeae9df1' - '31f8b856e3ad6c8455dab87cc0da8ac973417ce4f7878557d6cdf40' - 'b35b4a0ca3eb310c6a95d68ce284ad4e25ea28591611ee08b8444bd' - '64b25f3f7c572410ddfb39cc728b9c936f85f419129869929cdb909' - 'a6a3a99bbe089216368171bd0ba81de4fe33', 16), - 'digest_algorithm': 'SHA-1', - 'msg': binascii.unhexlify( - b'3b46736d559bd4e0c2c1b2553a33ad3c6cf23cac998d3d0c0e8fa4b19bc' - b'a06f2f386db2dcff9dca4f40ad8f561ffc308b46c5f31a7735b5fa7e0f9' - b'e6cb512e63d7eea05538d66a75cd0d4234b5ccf6c1715ccaaf9cdc0a222' - b'8135f716ee9bdee7fc13ec27a03a6d11c5c5b3685f51900b1337153bc6c' - b'4e8f52920c33fa37f4e7'), - 'y': int('313fd9ebca91574e1c2eebe1517c57e0c21b0209872140c5328761b' - 'bb2450b33f1b18b409ce9ab7c4cd8fda3391e8e34868357c199e16a' - '6b2eba06d6749def791d79e95d3a4d09b24c392ad89dbf100995ae1' - '9c01062056bb14bce005e8731efde175f95b975089bdcdaea562b32' - '786d96f5a31aedf75364008ad4fffebb970b', 16), - 'r': int('50ed0e810e3f1c7cb6ac62332058448bd8b284c0', 16), - 's': int('c6aded17216b46b7e4b6f2a97c1ad7cc3da83fde', 16)}, - { - 'p': int('a8f9cd201e5e35d892f85f80e4db2599a5676a3b1d4f190330ed325' - '6b26d0e80a0e49a8fffaaad2a24f472d2573241d4d6d6c7480c80b4' - 'c67bb4479c15ada7ea8424d2502fa01472e760241713dab025ae1b0' - '2e1703a1435f62ddf4ee4c1b664066eb22f2e3bf28bb70a2a76e4fd' - '5ebe2d1229681b5b06439ac9c7e9d8bde283', 16), - 'q': int('f85f0f83ac4df7ea0cdf8f469bfeeaea14156495', 16), - 'g': int('2b3152ff6c62f14622b8f48e59f8af46883b38e79b8c74deeae9df1' - '31f8b856e3ad6c8455dab87cc0da8ac973417ce4f7878557d6cdf40' - 'b35b4a0ca3eb310c6a95d68ce284ad4e25ea28591611ee08b8444bd' - '64b25f3f7c572410ddfb39cc728b9c936f85f419129869929cdb909' - 'a6a3a99bbe089216368171bd0ba81de4fe33', 16), - 'digest_algorithm': 'SHA-1', - 'msg': binascii.unhexlify( - b'd2bcb53b044b3e2e4b61ba2f91c0995fb83a6a97525e66441a3b489d959' - b'4238bc740bdeea0f718a769c977e2de003877b5d7dc25b182ae533db33e' - b'78f2c3ff0645f2137abc137d4e7d93ccf24f60b18a820bc07c7b4b5fe08' - b'b4f9e7d21b256c18f3b9d49acc4f93e2ce6f3754c7807757d2e11760426' - b'12cb32fc3f4f70700e25'), - 'y': int('29bdd759aaa62d4bf16b4861c81cf42eac2e1637b9ecba512bdbc13' - 'ac12a80ae8de2526b899ae5e4a231aef884197c944c732693a634d7' - '659abc6975a773f8d3cd5a361fe2492386a3c09aaef12e4a7e73ad7' - 'dfc3637f7b093f2c40d6223a195c136adf2ea3fbf8704a675aa7817' - 'aa7ec7f9adfb2854d4e05c3ce7f76560313b', 16), - 'r': int('a26c00b5750a2d27fe7435b93476b35438b4d8ab', 16), - 's': int('61c9bfcb2938755afa7dad1d1e07c6288617bf70', 16)}, - { - 'p': int('a8adb6c0b4cf9588012e5deff1a871d383e0e2a85b5e8e03d814fe1' - '3a059705e663230a377bf7323a8fa117100200bfd5adf857393b0bb' - 'd67906c081e585410e38480ead51684dac3a38f7b64c9eb109f1973' - '9a4517cd7d5d6291e8af20a3fbf17336c7bf80ee718ee087e322ee4' - '1047dabefbcc34d10b66b644ddb3160a28c0639563d71993a26543e' - 'adb7718f317bf5d9577a6156561b082a10029cd44012b18de684450' - '9fe058ba87980792285f2750969fe89c2cd6498db3545638d5379d1' - '25dccf64e06c1af33a6190841d223da1513333a7c9d78462abaab31' - 'b9f96d5f34445ceb6309f2f6d2c8dde06441e87980d303ef9a1ff00' - '7e8be2f0be06cc15f', 16), - 'q': int('e71f8567447f42e75f5ef85ca20fe557ab0343d37ed09edc3f6e686' - '04d6b9dfb', 16), - 'g': int('5ba24de9607b8998e66ce6c4f812a314c6935842f7ab54cd82b19fa' - '104abfb5d84579a623b2574b37d22ccae9b3e415e48f5c0f9bcbdff' - '8071d63b9bb956e547af3a8df99e5d3061979652ff96b765cb3ee49' - '3643544c75dbe5bb39834531952a0fb4b0378b3fcbb4c8b5800a533' - '0392a2a04e700bb6ed7e0b85795ea38b1b962741b3f33b9dde2f4ec' - '1354f09e2eb78e95f037a5804b6171659f88715ce1a9b0cc90c27f3' - '5ef2f10ff0c7c7a2bb0154d9b8ebe76a3d764aa879af372f4240de8' - '347937e5a90cec9f41ff2f26b8da9a94a225d1a913717d73f10397d' - '2183f1ba3b7b45a68f1ff1893caf69a827802f7b6a48d51da6fbefb' - '64fd9a6c5b75c4561', 16), - 'digest_algorithm': 'SHA-256', - 'msg': binascii.unhexlify( - b'4e3a28bcf90d1d2e75f075d9fbe55b36c5529b17bc3a9ccaba6935c9e20' - b'548255b3dfae0f91db030c12f2c344b3a29c4151c5b209f5e319fdf1c23' - b'b190f64f1fe5b330cb7c8fa952f9d90f13aff1cb11d63181da9efc6f7e1' - b'5bfed4862d1a62c7dcf3ba8bf1ff304b102b1ec3f1497dddf09712cf323' - b'f5610a9d10c3d9132659'), - 'y': int('5a55dceddd1134ee5f11ed85deb4d634a3643f5f36dc3a706892564' - '69a0b651ad22880f14ab85719434f9c0e407e60ea420e2a0cd29422' - 'c4899c416359dbb1e592456f2b3cce233259c117542fd05f31ea25b' - '015d9121c890b90e0bad033be1368d229985aac7226d1c8c2eab325' - 'ef3b2cd59d3b9f7de7dbc94af1a9339eb430ca36c26c46ecfa6c548' - '1711496f624e188ad7540ef5df26f8efacb820bd17a1f618acb50c9' - 'bc197d4cb7ccac45d824a3bf795c234b556b06aeb92917345325208' - '4003f69fe98045fe74002ba658f93475622f76791d9b2623d1b5fff' - '2cc16844746efd2d30a6a8134bfc4c8cc80a46107901fb973c28fc5' - '53130f3286c1489da', 16), - 'r': int('633055e055f237c38999d81c397848c38cce80a55b649d9e7905c29' - '8e2a51447', 16), - 's': int('2bbf68317660ec1e4b154915027b0bc00ee19cfc0bf75d01930504f' - '2ce10a8b0', 16)}, - { - 'p': int('a8adb6c0b4cf9588012e5deff1a871d383e0e2a85b5e8e03d814fe1' - '3a059705e663230a377bf7323a8fa117100200bfd5adf857393b0bb' - 'd67906c081e585410e38480ead51684dac3a38f7b64c9eb109f1973' - '9a4517cd7d5d6291e8af20a3fbf17336c7bf80ee718ee087e322ee4' - '1047dabefbcc34d10b66b644ddb3160a28c0639563d71993a26543e' - 'adb7718f317bf5d9577a6156561b082a10029cd44012b18de684450' - '9fe058ba87980792285f2750969fe89c2cd6498db3545638d5379d1' - '25dccf64e06c1af33a6190841d223da1513333a7c9d78462abaab31' - 'b9f96d5f34445ceb6309f2f6d2c8dde06441e87980d303ef9a1ff00' - '7e8be2f0be06cc15f', 16), - 'q': int('e71f8567447f42e75f5ef85ca20fe557ab0343d37ed09edc3f6e686' - '04d6b9dfb', 16), - 'g': int('5ba24de9607b8998e66ce6c4f812a314c6935842f7ab54cd82b19fa' - '104abfb5d84579a623b2574b37d22ccae9b3e415e48f5c0f9bcbdff' - '8071d63b9bb956e547af3a8df99e5d3061979652ff96b765cb3ee49' - '3643544c75dbe5bb39834531952a0fb4b0378b3fcbb4c8b5800a533' - '0392a2a04e700bb6ed7e0b85795ea38b1b962741b3f33b9dde2f4ec' - '1354f09e2eb78e95f037a5804b6171659f88715ce1a9b0cc90c27f3' - '5ef2f10ff0c7c7a2bb0154d9b8ebe76a3d764aa879af372f4240de8' - '347937e5a90cec9f41ff2f26b8da9a94a225d1a913717d73f10397d' - '2183f1ba3b7b45a68f1ff1893caf69a827802f7b6a48d51da6fbefb' - '64fd9a6c5b75c4561', 16), - 'digest_algorithm': 'SHA-256', - 'msg': binascii.unhexlify( - b'a733b3f588d5ac9b9d4fe2f804df8c256403a9f8eef6f191fc48e1267fb' - b'5b4d546ba11e77b667844e489bf0d5f72990aeb061d01ccd7949a23def7' - b'4a803b7d92d51abfadeb4885ffd8ffd58ab87548a15c087a39b8993b2fa' - b'64c9d31a594eeb7512da16955834336a234435c5a9d0dd9b15a94e11615' - b'4dea63fdc8dd7a512181'), - 'y': int('356ed47537fbf02cb30a8cee0537f300dff1d0c467399ce70b87a87' - '58d5ec9dd256246fccaeb9dfe109f2a984f2ddaa87aad54ce0d31f9' - '07e504521baf4207d7073b0a4a9fc67d8ddda99f87aed6e0367cec2' - '7f9c608af743bf1ee6e11d55a182d43b024ace534029b866f642282' - '8bb81a39aae9601ee81c7f81dd358e69f4e2edfa4654d8a65bc6431' - '1dc86aac4abc1fc7a3f65159661a0d8e288eb8d665cb0adf5ac3d6b' - 'a8e9453facf7542393ae24fd50451d3828086558f7ec528e284935a' - '53f67a1aa8e25d8ad5c4ad55d83aef883a4d9eeb6297e6a53f65049' - 'ba9e2c6b7953a760bc1dc46f78ceaaa2c02f5375dd82e708744aa40' - 'b15799eb81d7e5b1a', 16), - 'r': int('bcd490568c0a89ba311bef88ea4f4b03d273e793722722327095a37' - '8dd6f3522', 16), - 's': int('74498fc43091fcdd2d1ef0775f8286945a01cd72b805256b0451f9c' - 'bd943cf82', 16)} + "p": int( + "a8f9cd201e5e35d892f85f80e4db2599a5676a3b1d4f190330ed325" + "6b26d0e80a0e49a8fffaaad2a24f472d2573241d4d6d6c7480c80b4" + "c67bb4479c15ada7ea8424d2502fa01472e760241713dab025ae1b0" + "2e1703a1435f62ddf4ee4c1b664066eb22f2e3bf28bb70a2a76e4fd" + "5ebe2d1229681b5b06439ac9c7e9d8bde283", + 16, + ), + "q": int("f85f0f83ac4df7ea0cdf8f469bfeeaea14156495", 16), + "g": int( + "2b3152ff6c62f14622b8f48e59f8af46883b38e79b8c74deeae9df1" + "31f8b856e3ad6c8455dab87cc0da8ac973417ce4f7878557d6cdf40" + "b35b4a0ca3eb310c6a95d68ce284ad4e25ea28591611ee08b8444bd" + "64b25f3f7c572410ddfb39cc728b9c936f85f419129869929cdb909" + "a6a3a99bbe089216368171bd0ba81de4fe33", + 16, + ), + "digest_algorithm": "SHA-1", + "msg": binascii.unhexlify( + b"3b46736d559bd4e0c2c1b2553a33ad3c6cf23cac998d3d0c0e8fa4b19bc" + b"a06f2f386db2dcff9dca4f40ad8f561ffc308b46c5f31a7735b5fa7e0f9" + b"e6cb512e63d7eea05538d66a75cd0d4234b5ccf6c1715ccaaf9cdc0a222" + b"8135f716ee9bdee7fc13ec27a03a6d11c5c5b3685f51900b1337153bc6c" + b"4e8f52920c33fa37f4e7" + ), + "y": int( + "313fd9ebca91574e1c2eebe1517c57e0c21b0209872140c5328761b" + "bb2450b33f1b18b409ce9ab7c4cd8fda3391e8e34868357c199e16a" + "6b2eba06d6749def791d79e95d3a4d09b24c392ad89dbf100995ae1" + "9c01062056bb14bce005e8731efde175f95b975089bdcdaea562b32" + "786d96f5a31aedf75364008ad4fffebb970b", + 16, + ), + "r": int("50ed0e810e3f1c7cb6ac62332058448bd8b284c0", 16), + "s": int("c6aded17216b46b7e4b6f2a97c1ad7cc3da83fde", 16), + }, + { + "p": int( + "a8f9cd201e5e35d892f85f80e4db2599a5676a3b1d4f190330ed325" + "6b26d0e80a0e49a8fffaaad2a24f472d2573241d4d6d6c7480c80b4" + "c67bb4479c15ada7ea8424d2502fa01472e760241713dab025ae1b0" + "2e1703a1435f62ddf4ee4c1b664066eb22f2e3bf28bb70a2a76e4fd" + "5ebe2d1229681b5b06439ac9c7e9d8bde283", + 16, + ), + "q": int("f85f0f83ac4df7ea0cdf8f469bfeeaea14156495", 16), + "g": int( + "2b3152ff6c62f14622b8f48e59f8af46883b38e79b8c74deeae9df1" + "31f8b856e3ad6c8455dab87cc0da8ac973417ce4f7878557d6cdf40" + "b35b4a0ca3eb310c6a95d68ce284ad4e25ea28591611ee08b8444bd" + "64b25f3f7c572410ddfb39cc728b9c936f85f419129869929cdb909" + "a6a3a99bbe089216368171bd0ba81de4fe33", + 16, + ), + "digest_algorithm": "SHA-1", + "msg": binascii.unhexlify( + b"d2bcb53b044b3e2e4b61ba2f91c0995fb83a6a97525e66441a3b489d959" + b"4238bc740bdeea0f718a769c977e2de003877b5d7dc25b182ae533db33e" + b"78f2c3ff0645f2137abc137d4e7d93ccf24f60b18a820bc07c7b4b5fe08" + b"b4f9e7d21b256c18f3b9d49acc4f93e2ce6f3754c7807757d2e11760426" + b"12cb32fc3f4f70700e25" + ), + "y": int( + "29bdd759aaa62d4bf16b4861c81cf42eac2e1637b9ecba512bdbc13" + "ac12a80ae8de2526b899ae5e4a231aef884197c944c732693a634d7" + "659abc6975a773f8d3cd5a361fe2492386a3c09aaef12e4a7e73ad7" + "dfc3637f7b093f2c40d6223a195c136adf2ea3fbf8704a675aa7817" + "aa7ec7f9adfb2854d4e05c3ce7f76560313b", + 16, + ), + "r": int("a26c00b5750a2d27fe7435b93476b35438b4d8ab", 16), + "s": int("61c9bfcb2938755afa7dad1d1e07c6288617bf70", 16), + }, + { + "p": int( + "a8adb6c0b4cf9588012e5deff1a871d383e0e2a85b5e8e03d814fe1" + "3a059705e663230a377bf7323a8fa117100200bfd5adf857393b0bb" + "d67906c081e585410e38480ead51684dac3a38f7b64c9eb109f1973" + "9a4517cd7d5d6291e8af20a3fbf17336c7bf80ee718ee087e322ee4" + "1047dabefbcc34d10b66b644ddb3160a28c0639563d71993a26543e" + "adb7718f317bf5d9577a6156561b082a10029cd44012b18de684450" + "9fe058ba87980792285f2750969fe89c2cd6498db3545638d5379d1" + "25dccf64e06c1af33a6190841d223da1513333a7c9d78462abaab31" + "b9f96d5f34445ceb6309f2f6d2c8dde06441e87980d303ef9a1ff00" + "7e8be2f0be06cc15f", + 16, + ), + "q": int( + "e71f8567447f42e75f5ef85ca20fe557ab0343d37ed09edc3f6e686" + "04d6b9dfb", + 16, + ), + "g": int( + "5ba24de9607b8998e66ce6c4f812a314c6935842f7ab54cd82b19fa" + "104abfb5d84579a623b2574b37d22ccae9b3e415e48f5c0f9bcbdff" + "8071d63b9bb956e547af3a8df99e5d3061979652ff96b765cb3ee49" + "3643544c75dbe5bb39834531952a0fb4b0378b3fcbb4c8b5800a533" + "0392a2a04e700bb6ed7e0b85795ea38b1b962741b3f33b9dde2f4ec" + "1354f09e2eb78e95f037a5804b6171659f88715ce1a9b0cc90c27f3" + "5ef2f10ff0c7c7a2bb0154d9b8ebe76a3d764aa879af372f4240de8" + "347937e5a90cec9f41ff2f26b8da9a94a225d1a913717d73f10397d" + "2183f1ba3b7b45a68f1ff1893caf69a827802f7b6a48d51da6fbefb" + "64fd9a6c5b75c4561", + 16, + ), + "digest_algorithm": "SHA-256", + "msg": binascii.unhexlify( + b"4e3a28bcf90d1d2e75f075d9fbe55b36c5529b17bc3a9ccaba6935c9e20" + b"548255b3dfae0f91db030c12f2c344b3a29c4151c5b209f5e319fdf1c23" + b"b190f64f1fe5b330cb7c8fa952f9d90f13aff1cb11d63181da9efc6f7e1" + b"5bfed4862d1a62c7dcf3ba8bf1ff304b102b1ec3f1497dddf09712cf323" + b"f5610a9d10c3d9132659" + ), + "y": int( + "5a55dceddd1134ee5f11ed85deb4d634a3643f5f36dc3a706892564" + "69a0b651ad22880f14ab85719434f9c0e407e60ea420e2a0cd29422" + "c4899c416359dbb1e592456f2b3cce233259c117542fd05f31ea25b" + "015d9121c890b90e0bad033be1368d229985aac7226d1c8c2eab325" + "ef3b2cd59d3b9f7de7dbc94af1a9339eb430ca36c26c46ecfa6c548" + "1711496f624e188ad7540ef5df26f8efacb820bd17a1f618acb50c9" + "bc197d4cb7ccac45d824a3bf795c234b556b06aeb92917345325208" + "4003f69fe98045fe74002ba658f93475622f76791d9b2623d1b5fff" + "2cc16844746efd2d30a6a8134bfc4c8cc80a46107901fb973c28fc5" + "53130f3286c1489da", + 16, + ), + "r": int( + "633055e055f237c38999d81c397848c38cce80a55b649d9e7905c29" + "8e2a51447", + 16, + ), + "s": int( + "2bbf68317660ec1e4b154915027b0bc00ee19cfc0bf75d01930504f" + "2ce10a8b0", + 16, + ), + }, + { + "p": int( + "a8adb6c0b4cf9588012e5deff1a871d383e0e2a85b5e8e03d814fe1" + "3a059705e663230a377bf7323a8fa117100200bfd5adf857393b0bb" + "d67906c081e585410e38480ead51684dac3a38f7b64c9eb109f1973" + "9a4517cd7d5d6291e8af20a3fbf17336c7bf80ee718ee087e322ee4" + "1047dabefbcc34d10b66b644ddb3160a28c0639563d71993a26543e" + "adb7718f317bf5d9577a6156561b082a10029cd44012b18de684450" + "9fe058ba87980792285f2750969fe89c2cd6498db3545638d5379d1" + "25dccf64e06c1af33a6190841d223da1513333a7c9d78462abaab31" + "b9f96d5f34445ceb6309f2f6d2c8dde06441e87980d303ef9a1ff00" + "7e8be2f0be06cc15f", + 16, + ), + "q": int( + "e71f8567447f42e75f5ef85ca20fe557ab0343d37ed09edc3f6e686" + "04d6b9dfb", + 16, + ), + "g": int( + "5ba24de9607b8998e66ce6c4f812a314c6935842f7ab54cd82b19fa" + "104abfb5d84579a623b2574b37d22ccae9b3e415e48f5c0f9bcbdff" + "8071d63b9bb956e547af3a8df99e5d3061979652ff96b765cb3ee49" + "3643544c75dbe5bb39834531952a0fb4b0378b3fcbb4c8b5800a533" + "0392a2a04e700bb6ed7e0b85795ea38b1b962741b3f33b9dde2f4ec" + "1354f09e2eb78e95f037a5804b6171659f88715ce1a9b0cc90c27f3" + "5ef2f10ff0c7c7a2bb0154d9b8ebe76a3d764aa879af372f4240de8" + "347937e5a90cec9f41ff2f26b8da9a94a225d1a913717d73f10397d" + "2183f1ba3b7b45a68f1ff1893caf69a827802f7b6a48d51da6fbefb" + "64fd9a6c5b75c4561", + 16, + ), + "digest_algorithm": "SHA-256", + "msg": binascii.unhexlify( + b"a733b3f588d5ac9b9d4fe2f804df8c256403a9f8eef6f191fc48e1267fb" + b"5b4d546ba11e77b667844e489bf0d5f72990aeb061d01ccd7949a23def7" + b"4a803b7d92d51abfadeb4885ffd8ffd58ab87548a15c087a39b8993b2fa" + b"64c9d31a594eeb7512da16955834336a234435c5a9d0dd9b15a94e11615" + b"4dea63fdc8dd7a512181" + ), + "y": int( + "356ed47537fbf02cb30a8cee0537f300dff1d0c467399ce70b87a87" + "58d5ec9dd256246fccaeb9dfe109f2a984f2ddaa87aad54ce0d31f9" + "07e504521baf4207d7073b0a4a9fc67d8ddda99f87aed6e0367cec2" + "7f9c608af743bf1ee6e11d55a182d43b024ace534029b866f642282" + "8bb81a39aae9601ee81c7f81dd358e69f4e2edfa4654d8a65bc6431" + "1dc86aac4abc1fc7a3f65159661a0d8e288eb8d665cb0adf5ac3d6b" + "a8e9453facf7542393ae24fd50451d3828086558f7ec528e284935a" + "53f67a1aa8e25d8ad5c4ad55d83aef883a4d9eeb6297e6a53f65049" + "ba9e2c6b7953a760bc1dc46f78ceaaa2c02f5375dd82e708744aa40" + "b15799eb81d7e5b1a", + 16, + ), + "r": int( + "bcd490568c0a89ba311bef88ea4f4b03d273e793722722327095a37" + "8dd6f3522", + 16, + ), + "s": int( + "74498fc43091fcdd2d1ef0775f8286945a01cd72b805256b0451f9c" + "bd943cf82", + 16, + ), + }, ] assert expected == load_fips_dsa_sig_vectors(vector_data) def test_load_fips_ecdsa_key_pair_vectors(): - vector_data = textwrap.dedent(""" + vector_data = textwrap.dedent( + """ # CAVS 11.0 # "Key Pair" information # Curves selected: P-192 K-233 B-571 @@ -2346,67 +2701,97 @@ def test_load_fips_ecdsa_key_pair_vectors(): 7d6289980819292a719eb247195529ea60ad62862de0a26c72bfc49ecc81c2f9ed704e3168f Qy = 0721496cf16f988b1aabef3368450441df8439a0ca794170f270ead56203d675b57f5\ a4090a3a2f602a77ff3bac1417f7e25a683f667b3b91f105016a47afad46a0367b18e2bdf0c - """).splitlines() + """ + ).splitlines() expected = [ { "curve": "secp192r1", "d": int("e5ce89a34adddf25ff3bf1ffe6803f57d0220de3118798ea", 16), "x": int("8abf7b3ceb2b02438af19543d3e5b1d573fa9ac60085840f", 16), - "y": int("a87f80182dcd56a6a061f81f7da393e7cffd5e0738c6b245", 16) + "y": int("a87f80182dcd56a6a061f81f7da393e7cffd5e0738c6b245", 16), }, - { "curve": "secp192r1", "d": int("7d14435714ad13ff23341cb567cc91198ff8617cc39751b2", 16), "x": int("39dc723b19527daa1e80425209c56463481b9b47c51f8cbd", 16), "y": int("432a3e84f2a16418834fabaf6b7d2341669512951f1672ad", 16), }, - { "curve": "sect233k1", - "d": int("1da7422b50e3ff051f2aaaed10acea6cbf6110c517da2f4e" - "aca8b5b87", 16), - "x": int("1c7475da9a161e4b3f7d6b086494063543a979e34b8d7ac4" - "4204d47bf9f", 16), - "y": int("131cbd433f112871cc175943991b6a1350bf0cdd57ed8c83" - "1a2a7710c92", 16), + "d": int( + "1da7422b50e3ff051f2aaaed10acea6cbf6110c517da2f4e" "aca8b5b87", + 16, + ), + "x": int( + "1c7475da9a161e4b3f7d6b086494063543a979e34b8d7ac4" + "4204d47bf9f", + 16, + ), + "y": int( + "131cbd433f112871cc175943991b6a1350bf0cdd57ed8c83" + "1a2a7710c92", + 16, + ), }, - { "curve": "sect233k1", - "d": int("530951158f7b1586978c196603c12d25607d2cb0557efadb" - "23cd0ce8", 16), - "x": int("d37500a0391d98d3070d493e2b392a2c79dc736c097ed24b" - "7dd5ddec44", 16), - "y": int("1d996cc79f37d8dba143d4a8ad9a8a60ed7ea760aae1ddba" - "34d883f65d9", 16), + "d": int( + "530951158f7b1586978c196603c12d25607d2cb0557efadb" "23cd0ce8", + 16, + ), + "x": int( + "d37500a0391d98d3070d493e2b392a2c79dc736c097ed24b" + "7dd5ddec44", + 16, + ), + "y": int( + "1d996cc79f37d8dba143d4a8ad9a8a60ed7ea760aae1ddba" + "34d883f65d9", + 16, + ), }, - { "curve": "sect571r1", - "d": int("1443e93c7ef6802655f641ecbe95e75f1f15b02d2e172f49" - "a32e22047d5c00ebe1b3ff0456374461360667dbf07bc67f" - "7d6135ee0d1d46a226a530fefe8ebf3b926e9fbad8d57a6", 16), - "x": int("53e3710d8e7d4138db0a369c97e5332c1be38a20a4a84c36" - "f5e55ea9fd6f34545b864ea64f319e74b5ee9e4e1fa1b7c5" - "b2db0e52467518f8c45b658824871d5d4025a6320ca06f8", 16), - "y": int("3a22cfd370c4a449b936ae97ab97aab11c57686cca99d14e" - "f184f9417fad8bedae4df8357e3710bcda1833b30e297d4b" - "f637938b995d231e557d13f062e81e830af5ab052208ead", 16), + "d": int( + "1443e93c7ef6802655f641ecbe95e75f1f15b02d2e172f49" + "a32e22047d5c00ebe1b3ff0456374461360667dbf07bc67f" + "7d6135ee0d1d46a226a530fefe8ebf3b926e9fbad8d57a6", + 16, + ), + "x": int( + "53e3710d8e7d4138db0a369c97e5332c1be38a20a4a84c36" + "f5e55ea9fd6f34545b864ea64f319e74b5ee9e4e1fa1b7c5" + "b2db0e52467518f8c45b658824871d5d4025a6320ca06f8", + 16, + ), + "y": int( + "3a22cfd370c4a449b936ae97ab97aab11c57686cca99d14e" + "f184f9417fad8bedae4df8357e3710bcda1833b30e297d4b" + "f637938b995d231e557d13f062e81e830af5ab052208ead", + 16, + ), }, - { "curve": "sect571r1", - "d": int("3d2bd44ca9eeee8c860a4873ed55a54bdfdf5dab4060df72" - "92877960b85d1fd496aa33c587347213d7f6bf208a6ab4b4" - "30546e7b6ffbc3135bd12f44a28517867ca3c83a821d6f8", 16), - "x": int("7a7af10f6617090bade18b2e092d0dfdc87cd616db7f2db1" - "33477a82bfe3ea421ebb7d6289980819292a719eb2471955" - "29ea60ad62862de0a26c72bfc49ecc81c2f9ed704e3168f", 16), - "y": int("721496cf16f988b1aabef3368450441df8439a0ca794170f" - "270ead56203d675b57f5a4090a3a2f602a77ff3bac1417f7" - "e25a683f667b3b91f105016a47afad46a0367b18e2bdf0c", 16), + "d": int( + "3d2bd44ca9eeee8c860a4873ed55a54bdfdf5dab4060df72" + "92877960b85d1fd496aa33c587347213d7f6bf208a6ab4b4" + "30546e7b6ffbc3135bd12f44a28517867ca3c83a821d6f8", + 16, + ), + "x": int( + "7a7af10f6617090bade18b2e092d0dfdc87cd616db7f2db1" + "33477a82bfe3ea421ebb7d6289980819292a719eb2471955" + "29ea60ad62862de0a26c72bfc49ecc81c2f9ed704e3168f", + 16, + ), + "y": int( + "721496cf16f988b1aabef3368450441df8439a0ca794170f" + "270ead56203d675b57f5a4090a3a2f602a77ff3bac1417f7" + "e25a683f667b3b91f105016a47afad46a0367b18e2bdf0c", + 16, + ), }, ] @@ -2414,7 +2799,8 @@ def test_load_fips_ecdsa_key_pair_vectors(): def test_load_fips_ecdsa_signing_vectors(): - vector_data = textwrap.dedent(""" + vector_data = textwrap.dedent( + """ # CAVS 11.2 # "SigVer" information for "ecdsa_values" # Curves/SHAs selected: P-192, B-571,SHA-512 @@ -2481,7 +2867,8 @@ def test_load_fips_ecdsa_signing_vectors(): bdcf3035f6829ede041b745955d219dc5d30ddd8b37f6ba0f6d2857504cdc68a1ed812a10 S = 34db9998dc53527114518a7ce3783d674ca8cced823fa05e2942e7a0a20b3cc583dcd9\ 30c43f9b93079c5ee18a1f5a66e7c3527c18610f9b47a4da7e245ef803e0662e4d2ad721c - """).splitlines() + """ + ).splitlines() expected = [ { @@ -2499,7 +2886,7 @@ def test_load_fips_ecdsa_signing_vectors(): "y": int("76fab681d00b414ea636ba215de26d98c41bd7f2e4d65477", 16), "r": int("6994d962bdd0d793ffddf855ec5bf2f91a9698b46258a63e", 16), "s": int("02ba6465a234903744ab02bc8521405b73cf5fc00e1a9f41", 16), - "fail": True + "fail": True, }, { "curve": "secp192r1", @@ -2527,22 +2914,37 @@ def test_load_fips_ecdsa_signing_vectors(): b"d74e38983b24c0748618e2f92ef7cac257ff4bd1f41113f2891eb13c4793" b"0e69ddbe91f270fb" ), - "d": int("3e1b03ffca4399d5b439fac8f87a5cb06930f00d304193d7daf83d59" - "47d0c1e293f74aef8e56849f16147133c37a6b3d1b1883e5d61d6b87" - "1ea036c5291d9a74541f28878cb986", 16), - "x": int("3b236fc135d849d50140fdaae1045e6ae35ef61091e98f5059b30eb1" - "6acdd0deb2bc0d3544bc3a666e0014e50030134fe5466a9e4d3911ed" - "580e28851f3747c0010888e819d3d1f", 16), - "y": int("3a8b6627a587d289032bd76374d16771188d7ff281c39542c8977f68" - "72fa932e5daa14e13792dea9ffe8e9f68d6b525ec99b81a5a60cfb05" - "90cc6f297cfff8d7ba1a8bb81fe2e16", 16), - "r": int("2eb1c5c1fc93cf3c8babed12c031cf1504e094174fd335104cbe4a2a" - "bd210b5a14b1c3a455579f1ed0517c31822340e4dd3c1f967e1b4b9d" - "071a1072afc1a199f8c548cd449a634", 16), - "s": int("22f97bb48641235826cf4e597fa8de849402d6bd6114ad2d7fbcf53a" - "08247e5ee921f1bd5994dffee36eedff5592bb93b8bb148214da3b7b" - "aebffbd96b4f86c55b3f6bbac142442", 16), - "fail": False + "d": int( + "3e1b03ffca4399d5b439fac8f87a5cb06930f00d304193d7daf83d59" + "47d0c1e293f74aef8e56849f16147133c37a6b3d1b1883e5d61d6b87" + "1ea036c5291d9a74541f28878cb986", + 16, + ), + "x": int( + "3b236fc135d849d50140fdaae1045e6ae35ef61091e98f5059b30eb1" + "6acdd0deb2bc0d3544bc3a666e0014e50030134fe5466a9e4d3911ed" + "580e28851f3747c0010888e819d3d1f", + 16, + ), + "y": int( + "3a8b6627a587d289032bd76374d16771188d7ff281c39542c8977f68" + "72fa932e5daa14e13792dea9ffe8e9f68d6b525ec99b81a5a60cfb05" + "90cc6f297cfff8d7ba1a8bb81fe2e16", + 16, + ), + "r": int( + "2eb1c5c1fc93cf3c8babed12c031cf1504e094174fd335104cbe4a2a" + "bd210b5a14b1c3a455579f1ed0517c31822340e4dd3c1f967e1b4b9d" + "071a1072afc1a199f8c548cd449a634", + 16, + ), + "s": int( + "22f97bb48641235826cf4e597fa8de849402d6bd6114ad2d7fbcf53a" + "08247e5ee921f1bd5994dffee36eedff5592bb93b8bb148214da3b7b" + "aebffbd96b4f86c55b3f6bbac142442", + 16, + ), + "fail": False, }, { "curve": "sect571r1", @@ -2554,28 +2956,44 @@ def test_load_fips_ecdsa_signing_vectors(): b"0f10bc31c249b7b46edd2462a55f85560d99bde9d5b06b97817d1dbe0a67" b"c701d6e6e7878272" ), - "d": int("2e09ffd8b434bb7f67d1d3ccf482164f1653c6e4ec64dec2517aa21b" - "7a93b2b21ea1eebb54734882f29303e489f02e3b741a87287e2dcdf3" - "858eb6d2ec668f8b5b26f442ce513a2", 16), - "x": int("36f1be8738dd7dae4486b86a08fe90424f3673e76b10e739442e15f3" - "bfafaf841842ac98e490521b7e7bb94c127529f6ec6a42cc6f06fc80" - "606f1210fe020ff508148f93301c9d3", 16), - "y": int("4d39666ebe99fe214336ad440d776c88eb916f2f4a3433548b87d2ae" - "bed840b424d15c8341b4a0a657bf6a234d4fe78631c8e07ac1f4dc74" - "74cd6b4545d536b7b17c160db4562d9", 16), - "r": int("3d8105f87fe3166046c08e80a28acc98a80b8b7a729623053c2a9e80" - "afd06756edfe09bdcf3035f6829ede041b745955d219dc5d30ddd8b3" - "7f6ba0f6d2857504cdc68a1ed812a10", 16), - "s": int("34db9998dc53527114518a7ce3783d674ca8cced823fa05e2942e7a0" - "a20b3cc583dcd930c43f9b93079c5ee18a1f5a66e7c3527c18610f9b" - "47a4da7e245ef803e0662e4d2ad721c", 16) - } + "d": int( + "2e09ffd8b434bb7f67d1d3ccf482164f1653c6e4ec64dec2517aa21b" + "7a93b2b21ea1eebb54734882f29303e489f02e3b741a87287e2dcdf3" + "858eb6d2ec668f8b5b26f442ce513a2", + 16, + ), + "x": int( + "36f1be8738dd7dae4486b86a08fe90424f3673e76b10e739442e15f3" + "bfafaf841842ac98e490521b7e7bb94c127529f6ec6a42cc6f06fc80" + "606f1210fe020ff508148f93301c9d3", + 16, + ), + "y": int( + "4d39666ebe99fe214336ad440d776c88eb916f2f4a3433548b87d2ae" + "bed840b424d15c8341b4a0a657bf6a234d4fe78631c8e07ac1f4dc74" + "74cd6b4545d536b7b17c160db4562d9", + 16, + ), + "r": int( + "3d8105f87fe3166046c08e80a28acc98a80b8b7a729623053c2a9e80" + "afd06756edfe09bdcf3035f6829ede041b745955d219dc5d30ddd8b3" + "7f6ba0f6d2857504cdc68a1ed812a10", + 16, + ), + "s": int( + "34db9998dc53527114518a7ce3783d674ca8cced823fa05e2942e7a0" + "a20b3cc583dcd930c43f9b93079c5ee18a1f5a66e7c3527c18610f9b" + "47a4da7e245ef803e0662e4d2ad721c", + 16, + ), + }, ] assert expected == load_fips_ecdsa_signing_vectors(vector_data) def test_load_kasvs_dh_vectors(): - vector_data = textwrap.dedent(""" + vector_data = textwrap.dedent( + """ [SHA(s) supported (Used for hashing Z): SHA256 ] # Generated on Thu Mar 17 20:44:26 2011 @@ -2745,70 +3163,83 @@ def test_load_kasvs_dh_vectors(): d518475576730ed528779366568e46b7dd4ed787cb72d0733c93 CAVSHashZZ = 17dbbaa7a20c1390cd8cb3d31ee947bf9dde87739e067b9861ffeea9 Result = P (0 - Correct) - """).splitlines() + """ + ).splitlines() expected = [ { - 'fail_agree': False, - 'fail_z': False, - 'g': int( + "fail_agree": False, + "fail_z": False, + "g": int( "a51883e9ac0539859df3d25c716437008bb4bd8ec4786eb4bc643299daef5" "e3e5af5863a6ac40a597b83a27583f6a658d408825105b16d31b6ed088fc6" "23f648fd6d95e9cefcb0745763cddf564c87bcf4ba7928e74fd6a3080481f" "588d535e4c026b58a21e1e5ec412ff241b436043e29173f1dc6cb943c0974" - "2de989547288", 16), - 'p': int( + "2de989547288", + 16, + ), + "p": int( "da3a8085d372437805de95b88b675122f575df976610c6a844de99f1df82a" "06848bf7a42f18895c97402e81118e01a00d0855d51922f434c022350861d" "58ddf60d65bc6941fc6064b147071a4c30426d82fc90d888f94990267c64b" "eef8c304a4b2b26fb93724d6a9472fa16bc50c5b9b8b59afb62cfe9ea3ba0" - "42c73a6ade35", 16), - 'q': 1386090807861091316803998193774751098153687863463, - 'x1': 381229709512864262422021151581620734547375903702, - 'x2': 479735944608461101114916716909067001453470352916, - 'y1': int( + "42c73a6ade35", + 16, + ), + "q": 1386090807861091316803998193774751098153687863463, + "x1": 381229709512864262422021151581620734547375903702, + "x2": 479735944608461101114916716909067001453470352916, + "y1": int( "5a7890f6d20ee9c7162cd84222cb0c7cb5b4f29244a58fc95327fc41045f4" "76fb3da42fca76a1dd59222a7a7c3872d5af7d8dc254e003eccdb38f29161" "9c51911df2b6ed67d0b459f4bc25819c0078777b9a1a24c72e7c037a3720a" "1edad5863ef5ac75ce816869c820859558d5721089ddbe331f55bef741396" - "a3bbf85c6c1a", 16), - 'y2': int( + "a3bbf85c6c1a", + 16, + ), + "y2": int( "b92af0468b841ea5de4ca91d895b5e922245421de57ed7a88d2de41610b20" "8e8e233705f17b2e9eb91914bad2fa87f0a58519a7da2980bc06e7411c925" "a6050526bd86e621505e6f610b63fdcd9afcfaa96bd087afca44d9197cc35" "b559f731357a5b979250c0f3a254bb8165f5072156e3fd6f9a6e69bcf4b45" - "78f78b3bde7", 16), - 'z': binascii.unhexlify( + "78f78b3bde7", + 16, + ), + "z": binascii.unhexlify( b"8d8f4175e16e15a42eb9099b11528af88741cc206a088971d3064bb291ed" b"a608d1600bff829624db258fd15e95d96d3e74c6be3232afe5c855b9c596" b"81ce13b7aea9ff2b16707e4c02f0e82bf6dadf2149ac62630f6c62dea0e5" b"05e3279404da5ffd5a088e8474ae0c8726b8189cb3d2f04baffe700be849" b"df9f91567fc2ebb8" - ) + ), }, { - 'fail_agree': False, - 'fail_z': False, - 'g': int( + "fail_agree": False, + "fail_z": False, + "g": int( "a51883e9ac0539859df3d25c716437008bb4bd8ec4786eb4bc643299daef5" "e3e5af5863a6ac40a597b83a27583f6a658d408825105b16d31b6ed088fc6" "23f648fd6d95e9cefcb0745763cddf564c87bcf4ba7928e74fd6a3080481f" "588d535e4c026b58a21e1e5ec412ff241b436043e29173f1dc6cb943c0974" - "2de989547288", 16), - 'p': int( + "2de989547288", + 16, + ), + "p": int( "da3a8085d372437805de95b88b675122f575df976610c6a844de99f1df82a" "06848bf7a42f18895c97402e81118e01a00d0855d51922f434c022350861d" "58ddf60d65bc6941fc6064b147071a4c30426d82fc90d888f94990267c64b" "eef8c304a4b2b26fb93724d6a9472fa16bc50c5b9b8b59afb62cfe9ea3ba0" - "42c73a6ade35", 16), - 'q': 1386090807861091316803998193774751098153687863463, - 'x1': int( - "32e642683d745a23dccf4f12f989d8dfd1fd9894c422930950cb4c71", - 16), - 'x2': int( - "7d8ae93df3bc09d399a4157ec562126acf51092c3269ab27f60a3a2b", - 16), - 'y1': int( + "42c73a6ade35", + 16, + ), + "q": 1386090807861091316803998193774751098153687863463, + "x1": int( + "32e642683d745a23dccf4f12f989d8dfd1fd9894c422930950cb4c71", 16 + ), + "x2": int( + "7d8ae93df3bc09d399a4157ec562126acf51092c3269ab27f60a3a2b", 16 + ), + "y1": int( "8cd371363b32fcc2e936e345f2278b77001f2efdf78512c3ee75c12f88507" "e2d5c0e5cdded3bb78435506c8028a3f4d6f028c0f49a0d61f1285795197e" "56deac80279e723f2b3746e213ac8ec60f1cefc2308ff17a7e9e2efab537e" @@ -2817,8 +3248,10 @@ def test_load_kasvs_dh_vectors(): "3e1c450c5798dc05f8265ad9e35095ff112af9e889f00315fa337a76a4506" "70866eca12cc6ad0778576962eb9cdc12721d3c15e4d87b67488a145d4002" "40670eb26695a42879cd3940a55087f6527667277e1212a202dbe455c45c6" - "4b9be4a38153557bbb8fd755", 16), - 'y2': int( + "4b9be4a38153557bbb8fd755", + 16, + ), + "y2": int( "22127e9728e906ea4b1512c8b1e80474b58446210c23ccfc800f83c2c15da" "8159940e494b235266f6a9d5f80529067794f1a9edd566755d23d0a3060fe" "074c5a10122df3e472973bba39ea3a988e8387f5f0491e590b6b5edc299b4" @@ -2827,8 +3260,10 @@ def test_load_kasvs_dh_vectors(): "6c3d75d9bcf83f4b8d1ed39408bd8d973b4ea81e8e832eac361dcd5307133" "88a60971ea9f8b1e69c1e99df1cca12bdaf293dacfa1419c5692ceffa9198" "8aef3321ac8cbc2efae6c4337c8808310fb5a240395a98e6004fe613c39e8" - "4f4177341746d9e388dcb2e8", 16), - 'z': binascii.unhexlify( + "4f4177341746d9e388dcb2e8", + 16, + ), + "z": binascii.unhexlify( b"0efeaa399a182e0a603baf0dd95aa0fae5289ebd47d5f0f60c86bc936839" b"c31c9f7f37bf04f76ab02f4094a8ab10ed907ec7291585cc085c3e8981df" b"2bd46a01c19ec9a2f66709df1d4fefbeb48c8263554e46890f59eb642bf9" @@ -2838,31 +3273,35 @@ def test_load_kasvs_dh_vectors(): b"ce2a585eb9e8f308b48cf4e29593b6f7a02e8625e1e8bff1ea1405f8c8c3" b"4b8339a9a99c7c9de4eb9895df7719ccda9394f53080eff1226f6b9c7ae0" b"a38941e18b1a137aabbb62308eb35ba2" - ) + ), }, { - 'fail_agree': False, - 'fail_z': True, - 'g': int( + "fail_agree": False, + "fail_z": True, + "g": int( "a51883e9ac0539859df3d25c716437008bb4bd8ec4786eb4bc643299daef5" "e3e5af5863a6ac40a597b83a27583f6a658d408825105b16d31b6ed088fc6" "23f648fd6d95e9cefcb0745763cddf564c87bcf4ba7928e74fd6a3080481f" "588d535e4c026b58a21e1e5ec412ff241b436043e29173f1dc6cb943c0974" - "2de989547288", 16), - 'p': int( + "2de989547288", + 16, + ), + "p": int( "da3a8085d372437805de95b88b675122f575df976610c6a844de99f1df82a" "06848bf7a42f18895c97402e81118e01a00d0855d51922f434c022350861d" "58ddf60d65bc6941fc6064b147071a4c30426d82fc90d888f94990267c64b" "eef8c304a4b2b26fb93724d6a9472fa16bc50c5b9b8b59afb62cfe9ea3ba0" - "42c73a6ade35", 16), - 'q': 1386090807861091316803998193774751098153687863463, - 'x1': int( - "66502429aba271e2f2ee2197a2b336e5f0467f192aa28b60dcbf1194", - 16), - 'x2': int( - "106b358be4f068348ac240ecbb454e5c39ca80b078cb0fafd856e9c5", - 16), - 'y1': int( + "42c73a6ade35", + 16, + ), + "q": 1386090807861091316803998193774751098153687863463, + "x1": int( + "66502429aba271e2f2ee2197a2b336e5f0467f192aa28b60dcbf1194", 16 + ), + "x2": int( + "106b358be4f068348ac240ecbb454e5c39ca80b078cb0fafd856e9c5", 16 + ), + "y1": int( "dfb001294215423d7146a2453cdb8598ccef01e1d931a913c3e4ed4a3cf38" "a912066c28e4eaf77dd80ff07183a6160bd95932f513402f864dcf7a70cbe" "dc9b60bbfbc67f72a83d5f6463a2b5a4fc906d3e921f5e1069126113265b4" @@ -2871,8 +3310,10 @@ def test_load_kasvs_dh_vectors(): "51043d351bb74a952e6a694e6e7456f714c47d7c8eeeb4fd83ad93c86b784" "45f9393fdfd65c7dbd7fd6eba9794ddf183901b1d213321fd0ab3f7588ab0" "f6b3692f365a87131eda0e062505861988f6ce63150207545ecf9678e0971" - "330253dfb7cfd546c5346fec", 16), - 'y2': int( + "330253dfb7cfd546c5346fec", + 16, + ), + "y2": int( "715d0781975b7b03162f4401c1eda343fd9bf1140006034573b31828a618c" "356163554cd27da956f7179a69e860fb6efeaa2e2aa9f1261506a8344c492" "9953621381b13d6426e152c0f2f94bfcd2b758eca24923596d427ed8f957e" @@ -2881,8 +3322,10 @@ def test_load_kasvs_dh_vectors(): "ad5c5bd490ea600e04379232fb1077fbf394f4579accdbe352714e25b8891" "6dca8d8f7e0c4ed9594f7693f656a235a2e88ebda48b0d557e32da9f12d2a" "4c3180f05b16b4fba9bec79278a3971b77f9223b5ab78b857e0376c500821" - "1592c8c72d521373ee3b22b8", 16), - 'z': binascii.unhexlify( + "1592c8c72d521373ee3b22b8", + 16, + ), + "z": binascii.unhexlify( b"cf879ebd107bb877457809c3fc410218b7acba3c5967495a8f1c3370d57f" b"038a48dd69f9f69b9f4dd855e7c58a1e4ec32646a978266eb314db468ea1" b"dfcee8a85a1644a5732498c4fbcdf85098c6ed0ce12e431e99142fd23353" @@ -2892,12 +3335,12 @@ def test_load_kasvs_dh_vectors(): b"665095490056287e4fc49e6cb3181cb2bf06444fd0040150271c9ce1f61c" b"13ecd5dd022194a2dbf3e1c7fbc6bd19497c7b888b4da613d28fa6f378a4" b"3369cb8795a1c823f7d6cf4d84bba578" - ) + ), }, { - 'fail_agree': True, - 'fail_z': False, - 'g': int( + "fail_agree": True, + "fail_z": False, + "g": int( "35513ec441402b78353ab1bba550b21c76c89973885a627170262ef52497d" "5d137b8927a212aaab2f051198c90bb81dffd9eb10b36b7ca3b63565b4c10" "25aea3b5e9c4a348c9cfa17f3907a1e4469701c0dedb8a4b9e96c5965b1fb" @@ -2906,8 +3349,10 @@ def test_load_kasvs_dh_vectors(): "65bb4e1e9474993fe382fd23480dc875861be152997a621fdb7aef977ea5b" "4d3d74486b162dc28f95a64cf65587a919a57eef92934fc9410df7f09fa82" "f975328ed82ff29cc3e15a971f56f4ac2dcb289252575e02a6cdb7fcc6cdd" - "d7b0dca9c422e63eb2b8f05", 16), - 'p': int( + "d7b0dca9c422e63eb2b8f05", + 16, + ), + "p": int( "f3722b9b911c6aede9eaeeaa406283de66a097f39a7225df6c3c916e57920" "d356e50478d307dbfd146bfb91b6f68ecbbcf54b3d19c33a4b17293fea3e3" "d6bff8ac4cca93a805386f062a8a27ae906ef5da94d279fd7b3d7289e0095" @@ -2916,17 +3361,19 @@ def test_load_kasvs_dh_vectors(): "3c3dfda8de8429e087c5be97fc5c9db9526031ad3a218bd9916fb4a3c2796" "6d208b1e360014c01e95530c148fb3cd27e6a7250d3c3b81dcd220ca14548" "dbccf99ebb9e334db6bcd14e632c98dd3f9860af7ae450f1b7809b45f0ec1" - "0e6f27672beebc9963befc73", 16), - 'q': int( - "a9a17de95a29091bf8e07dab53ea1aba9403be3c61027c6c8f48bac5", - 16), - 'x1': int( - "1610eaa4e0ccc8857e2b53149e008492b1fbd9025a6e8d95aaee9c0f", - 16), - 'x2': int( - "c4c83d75b27864b052cadc556e500e25aabf0c9d1bc01f0e1fe3862", - 16), - 'y1': int( + "0e6f27672beebc9963befc73", + 16, + ), + "q": int( + "a9a17de95a29091bf8e07dab53ea1aba9403be3c61027c6c8f48bac5", 16 + ), + "x1": int( + "1610eaa4e0ccc8857e2b53149e008492b1fbd9025a6e8d95aaee9c0f", 16 + ), + "x2": int( + "c4c83d75b27864b052cadc556e500e25aabf0c9d1bc01f0e1fe3862", 16 + ), + "y1": int( "51ee21cd9f97015180f258fad5c94ff5a458806b1412087236bf77fe87aae" "1a36735816ed6e2160a731159814b6ae1f3f52c478dd9207094adfb62f766" "7d5c366327e66d23096395e938504db330953a708015f861fe9d948761109" @@ -2935,8 +3382,10 @@ def test_load_kasvs_dh_vectors(): "a6f14ccdb29db02f64911bd83bfdcdfc843dd14a4cab9acb0bda8b293d2f5" "f7050768e57533cbc415a29e6f31cc365e107f91ae3722484e2c7329a85af" "69055a5a104da37e810878896d1b247b02b75234ecff82b1958f42d7b0316" - "22e9394c98b5229112f7f620", 16), - 'y2': int( + "22e9394c98b5229112f7f620", + 16, + ), + "y2": int( "467a857337a82472a1307a64dccc8e9994c5c63ec4312936885d17be41905" "1a5f037fbb052d7010ebe01634d9e8b8b522d9ab4749fdc274f465369b89e" "360df8f70b7865a3c71d2dbcd2df19e9293dab1153d3d63fcb7deb559b684" @@ -2945,8 +3394,10 @@ def test_load_kasvs_dh_vectors(): "c193f460dcd0be7e6e06e546da7653770dc5859df87029e722dbe81361030" "569148d1636988926bf0dcfe47c9d8a54698c08b3b5c70afe86b5c6f64346" "3f8f34889d27d6cfd2d478c2d7b3d008a985c7380f0b43f10024b59c35438" - "80883c42d0e7e0a07326ba3a", 16), - 'z': binascii.unhexlify( + "80883c42d0e7e0a07326ba3a", + 16, + ), + "z": binascii.unhexlify( b"10a30bacab82e652415376baffdbc008c7eb2e5a3aa68bc10ce486ca8498" b"3fd89b1b027bb40e75333406361005f5e756526a95fe01202df9217d81b1" b"713d5187c368fdd4c9c2433d9e6c18844769479b725c4140c92a304ee1bc" @@ -2956,41 +3407,47 @@ def test_load_kasvs_dh_vectors(): b"68c90178974a0602436cd186748bcc63a629edc3a0db59415cccd37a6513" b"0ea477c89da92d41371f5972891cf41f9c7f0e75ccbff9893225384db30d" b"aa5e310f08e3e0fad98bcdf8ecf35fe5" - ) + ), }, { - 'fail_agree': False, - 'fail_z': False, - 'g': int("35513ec441402b78353ab1bba550b21c76c89973885a627170262ef5" - "2497d5d137b8927a212aaab2f051198c90bb81dffd9eb10b36b7ca3b" - "63565b4c1025aea3b5e9c4a348c9cfa17f3907a1e4469701c0dedb8a" - "4b9e96c5965b1fb8c229b0c34baac774bf9dda4fc5ee8764358b3c84" - "812878aab7464bc09e97aecab7d7e3fbb4870e2a3b89667a4158bf1e" - "d1a90dfaf47019fbb52b1b96365bb4e1e9474993fe382fd23480dc87" - "5861be152997a621fdb7aef977ea5b4d3d74486b162dc28f95a64cf6" - "5587a919a57eef92934fc9410df7f09fa82f975328ed82ff29cc3e15" - "a971f56f4ac2dcb289252575e02a6cdb7fcc6cddd7b0dca9c422e63e" - "b2b8f05", 16), - 'p': int("f3722b9b911c6aede9eaeeaa406283de66a097f39a7225df6c3c916e" - "57920d356e50478d307dbfd146bfb91b6f68ecbbcf54b3d19c33a4b1" - "7293fea3e3d6bff8ac4cca93a805386f062a8a27ae906ef5da94d279" - "fd7b3d7289e00956f76bae9c0d2b8d11742ca5809630632aae58f9c6" - "dce00c7380581deffde2187b022f83c6ceaeaadb0844a17fcbb04039" - "ca6843c91f0c9058b22434b263c3dfda8de8429e087c5be97fc5c9db" - "9526031ad3a218bd9916fb4a3c27966d208b1e360014c01e95530c14" - "8fb3cd27e6a7250d3c3b81dcd220ca14548dbccf99ebb9e334db6bcd" - "14e632c98dd3f9860af7ae450f1b7809b45f0ec10e6f27672beebc99" - "63befc73", 16), - 'q': int( - "a9a17de95a29091bf8e07dab53ea1aba9403be3c61027c6c8f48bac5", - 16), - 'x1': int( - "9ee22ac51664e40e0a24dbb94142dba40605e2b6eeaaa0268a0f6847", - 16), - 'x2': int( - "438093a468236658821bf64eb08456139963d4fb27121c3ed6c55876", - 16), - 'y1': int( + "fail_agree": False, + "fail_z": False, + "g": int( + "35513ec441402b78353ab1bba550b21c76c89973885a627170262ef5" + "2497d5d137b8927a212aaab2f051198c90bb81dffd9eb10b36b7ca3b" + "63565b4c1025aea3b5e9c4a348c9cfa17f3907a1e4469701c0dedb8a" + "4b9e96c5965b1fb8c229b0c34baac774bf9dda4fc5ee8764358b3c84" + "812878aab7464bc09e97aecab7d7e3fbb4870e2a3b89667a4158bf1e" + "d1a90dfaf47019fbb52b1b96365bb4e1e9474993fe382fd23480dc87" + "5861be152997a621fdb7aef977ea5b4d3d74486b162dc28f95a64cf6" + "5587a919a57eef92934fc9410df7f09fa82f975328ed82ff29cc3e15" + "a971f56f4ac2dcb289252575e02a6cdb7fcc6cddd7b0dca9c422e63e" + "b2b8f05", + 16, + ), + "p": int( + "f3722b9b911c6aede9eaeeaa406283de66a097f39a7225df6c3c916e" + "57920d356e50478d307dbfd146bfb91b6f68ecbbcf54b3d19c33a4b1" + "7293fea3e3d6bff8ac4cca93a805386f062a8a27ae906ef5da94d279" + "fd7b3d7289e00956f76bae9c0d2b8d11742ca5809630632aae58f9c6" + "dce00c7380581deffde2187b022f83c6ceaeaadb0844a17fcbb04039" + "ca6843c91f0c9058b22434b263c3dfda8de8429e087c5be97fc5c9db" + "9526031ad3a218bd9916fb4a3c27966d208b1e360014c01e95530c14" + "8fb3cd27e6a7250d3c3b81dcd220ca14548dbccf99ebb9e334db6bcd" + "14e632c98dd3f9860af7ae450f1b7809b45f0ec10e6f27672beebc99" + "63befc73", + 16, + ), + "q": int( + "a9a17de95a29091bf8e07dab53ea1aba9403be3c61027c6c8f48bac5", 16 + ), + "x1": int( + "9ee22ac51664e40e0a24dbb94142dba40605e2b6eeaaa0268a0f6847", 16 + ), + "x2": int( + "438093a468236658821bf64eb08456139963d4fb27121c3ed6c55876", 16 + ), + "y1": int( "c2630c9d38ed5c825d1c6a3eba7143f3fc8a049c8bcd1efc212d2af64eca9" "94308208691d330aa8f27fc4a1e55de4e512113996d21375a667f8c26d76d" "ee2f6809b15432a33fb735aca5c2263940f58712bded08f55443dee300b94" @@ -2999,8 +3456,10 @@ def test_load_kasvs_dh_vectors(): "d43c4ffc9a605addbdcce0cb3790c6db846156bb857a7b3df40dc6ed04d19" "cc9eaebb6bbc034e77c3d882a1a62317cce25b6130f0803e3bc49b5e36768" "260073a617034872be0b50bed32740224beaf582d67fbcfef3b3ecc18f9c7" - "1c782e9a68495ef31dc7986e", 16), - 'y2': int( + "1c782e9a68495ef31dc7986e", + 16, + ), + "y2": int( "e192da8e1244e27221c1765344a5bb379dce741d427a734b4bdb6c4d16b24" "90bd37564d745008e63ae46ef332331d79887ac63298ce143e125f8b320c0" "f859b7f5f2c1e0053e4a7a16997e6143ff702300c9863ae7caef5c1dfca0e" @@ -3009,8 +3468,10 @@ def test_load_kasvs_dh_vectors(): "a56431cd48579bf53c903bbe066dd78b23c0996ef3a880f0d91315104366a" "82f01abdecce96fd371f94e8420f8bc5b896c801df573554f749b03d0d28b" "1e1a990bc61c7e9659342ac7e268e9c0b7c40fdaab394f29cf0a54f780022" - "f9a03b0bd28eb7db8b0b1b47", 16), - 'z': binascii.unhexlify( + "f9a03b0bd28eb7db8b0b1b47", + 16, + ), + "z": binascii.unhexlify( b"56f8f40fa4b8f3580f9014b30d60a42933a53a62182a690142f458dc275c" b"3b2f0e721bc5ee6e890b14516419110f5252ff1cceea8e274b2987aa78e3" b"bae90c1935b276b7a1f1c944f79d4774b7a85b3355bdf25cb02bddfbda4e" @@ -3020,8 +3481,8 @@ def test_load_kasvs_dh_vectors(): b"b75d049d4c82097af8a5ce353e14416b3eeb31ba9bc4f6f3dbd846c5299f" b"b5c0043a1b95b9149b39d14df9e6a69547abf8a4d518475576730ed52877" b"9366568e46b7dd4ed787cb72d0733c93" - ) - } + ), + }, ] assert expected == load_kasvs_dh_vectors(vector_data) @@ -3032,7 +3493,8 @@ def test_load_kasvs_ecdh_vectors_empty_vector_data(): def test_load_kasvs_ecdh_vectors(): - vector_data = textwrap.dedent(""" + vector_data = textwrap.dedent( + """ # CAVS 11.0 # Parameter set(s) supported: EA EB EC ED EE # CAVSid: CAVSid (in hex: 434156536964) @@ -3183,148 +3645,291 @@ def test_load_kasvs_ecdh_vectors(): - """).splitlines() + """ + ).splitlines() expected = [ - {'errno': 0, - 'fail': False, - 'COUNT': 0, - 'CAVS': { - 'd': int("f70c297a683d6b7ef82b5af7349606c4447c8b4fc6fa5e80", 16), - 'x': int("f7b5061fb557e516c50abf541d97dbfd76ca7172b22cf590", 16), - 'y': int("135e15e21f9e85c76205fd148a92ac19f9e6243ddab322d1", 16)}, - 'IUT': { - 'd': int("a5b4bbad57f101ca48021cb7440cd681a9d40cd51b99d917", 16), - 'x': int("79a77fcb18a32cdb59ed5d87740f29e8565d649dbf01ce86", 16), - 'y': int("f7187efaa0b1573f1fb00905d46810b880bf738b4c720bb7", 16)}, - 'Z': int("26382468d721761e14a87dc3bee67340095c6455962d1ba3", 16), - 'curve': 'secp192r1'}, - - {'errno': 8, - 'fail': True, - 'COUNT': 2, - 'CAVS': { - 'd': int("5f909dcb0ccce58c82fada748c47297579e6a981b5518a96", 16), - 'x': int("537f1ecfda0e366de393a9bc8188fcc280311bffefe21ecf", 16), - 'y': int("a1fa1f98498d65f2754caff4e5303a4066a5ff89fde95381", 16)}, - 'IUT': { - 'd': int("3357aa7f47f3e09421602cc12cdce4434c68e330d44de05e", 16), - 'x': int("6a33d43d9c72173eabc7a771a5687748c4774c62762e96ec", 16), - 'y': int("8033f238b3abc69470aad4be8dbe4f60a2fd50207626c56a", 16)}, - 'Z': int("3153034f6617326f19c35be8c99a0585431adf09d2f8e0fd", 16), - 'curve': 'secp192r1'}, - - {'errno': 13, - 'fail': False, - 'COUNT': 8, - 'CAVS': { - 'd': int("8fcfaf0524cc868fad20e50410a2205319f1327308d98dc8", 16), - 'x': int("9b0243d80a9e328738080fb4d46bc450243d0efb7ead0c92", 16), - 'y': int("ad5bebad7f03849693071537f60ef858cad214123beee7c7", 16)}, - 'IUT': { - 'd': int("bba95dac90289cb68ca2b006f9757219b70579c299ad7a7d", 16), - 'x': int("7733dc0cb365cd6312724196b9b4eb491fd4d2e31b9afdb1", 16), - 'y': int("92ffa3722acc5b94d772258ba2d471b06c0f53f56fcd8662", 16)}, - 'Z': int("0f3c6e4a29a08296ae730f56a1ebf819ea2edfa6f0434e40", 16), - 'curve': 'secp192r1'}, - - {'errno': 0, - 'fail': False, - 'COUNT': 0, - 'CAVS': { - 'd': int("e53a88af7cf8ce6bf13c8b9ad191494e37a6acc1368c71f4" - "306e39e5", 16), - 'x': int("3a24217c4b957fea922eec9d9ac52d5cb4b3fcd95efde1e4" - "fa0dd6e2", 16), - 'y': int("775b94025a808eb6f4af14ea4b57dca576c35373c6dc198b" - "15b981df", 16)}, - 'IUT': { - 'd': int("09f51e302c6a0fe6ff48f34c208c6af91e70f65f88102e6f" - "cab9af4a", 16), - 'x': int("c5d5706ccd7424c74fd616e699865af96e56f39adea6aa05" - "9e5092b5", 16), - 'y': int("f0729077bb602404d56d2f7e2ba5bb2f383df4a542556788" - "1ff0165d", 16)}, - 'Z': int("b1259ceedfb663d9515089cf727e7024fb3d86cbcec611b4" - "ba0b4ab6", 16), - 'curve': 'secp224r1'}, - - {'errno': 2, - 'fail': True, - 'COUNT': 0, - 'CAVS': { - 'd': int("305dfb4a8850cc59280891147baf457bfe5e2bae98457163" - "4a77dc8d3472fa9b", 16), - 'x': int("202cb5a224e6c2a84e624094486edf04116c8d68ec1f4a0e" - "0ed9ee090e1a900b", 16), - 'y': int("cacf3a5789bb33954be600425d62d9eae5371f90f8816725" - "8814213e4a4f4b1a", 16)}, - 'IUT': { - 'd': int("72cc52808f294b64b6f7233c3d2f5d96cc1d29287320e39e" - "1c151deef0bc14eb", 16), - 'x': int("49a768c9a4ca56e374f685dd76a461b1016c59dcded2c8d8" - "cbd9f23ca453831f", 16), - 'y': int("b1e3bb9b5f12a3b5ae788535d4554bd8c46e0e6130075e4e" - "437d3854cf8f1c34", 16)}, - 'Z': int("c0147c3c2691b450b5edc08b51aea224d9f4359ff67aab6d" - "a3146f396dbceaea", 16), - 'curve': 'secp256r1'}, - - {'errno': 0, - 'fail': False, - 'COUNT': 0, - 'CAVS': { - 'd': int("0e5c98ff2d2a3aab14ad0067b60dbe64e4f541ab5bed11c5" - "a0c55ae1e60b51ff5faaf377837977d80cbfdc33c2ff542b", 16), - 'x': int("d1bf2ac21637d66d6398aac01dcd56ac6f065fb45d1f6f16" - "747bab9e9b01b4630b59b20927aea147355bf41838acb482", 16), - 'y': int("4c9e23f1c5a41647d094086bf4ed31708651f21d996c4778" - "0688ac10f77deee2e43b5241b6caecd2fd5444bc50472e0e", 16)}, - 'IUT': { - 'd': int("f865418473e5bf7d2e1bbcd9bd5a9270c003a9dd35e77813" - "3ca59fcab4bb64fe24d6800e7047bdd033abc8bfa8db35b5", 16), - 'x': int("32b72ab9b558249dcbc6cbade234f58e4f7aa5d3f6420ea9" - "9a5f997e8c2a91fb7fd83779d0d2169428683771c745fd1a", 16), - 'y': int("c749e02a3719bb56bf1dfc4ba3820309c01ab6e84cb29db7" - "cdd80f127233f5295687f8178f3a8704c1063b84c2ee472f", 16)}, - 'Z': int("a781430e6078a179df3f9ee27cd8fdc6188f161b6c4ccc40" - "53ef6c6ca6fc222946883a53c06db08f0a020023ced055aa", 16), - 'curve': 'secp384r1'}, - - {'errno': 7, - 'fail': True, - 'COUNT': 0, - 'CAVS': { - 'd': int("0000002fef62381162942889a6094a6bb9ac1f4ddf66d9cd" - "a9f618232d31b90c50d7da78a47ed91d40cae946898571db" - "972dc294b109815f38feee9eaac0d5f7c3250728", 16), - 'x': int("0000004b05ffa025113390797f2736174aa1c784f4dd34e7" - "64ee40d40e4d2442677ebea3498086c9473e5c92789cbdb0" - "2bb327bbd61d58690f6a83d9ca73bccbde37dec4", 16), - 'y': int("0000004da67cffc98070b82af61feba78787efefb13bd810" - "d80ff92304788e49a4e5b634b3565474a8ecb1615d7b1b77" - "a7a27875adb73a8a5d8f3f84e5e8b744cda250b0", 16)}, - 'IUT': { - 'd': int("00000311a5e520e238141527671a38cb6f776d96a9f82ef7" - "0dffa11dc0895f4060f1abbb9ad6fd259e4a7beaf5f7266e" - "a1bb45bcbfebfda2705e5c551e710fb1d745f57e", 16), - 'x': int("0000010ba3778cb2cc965834c0a9593adc6a222692656d65" - "7fb0d15293edf0ab33762384a96a16fddea7540b7ccbcca4" - "6ec4ac9bcf95fdb5aa18e158aab4d91981bd733e", 16), - 'y': int("0000018522df93ddd636e5bc94daecdc600fa241686ec186" - "34fd30b7cbdfdc9ffba1166ac08df34a31896f6fad191414" - "929261ebd7187afb72919f8a0c926be37f99c1e5", 16)}, - 'Z': int("01a5e4b31be4b1346e53906b6767b1fe94ec1a8a5abc28fb" - "6f01518c056959af3bc9335dddab178b52318cc551255993" - "1b8dc18de0ce810c2c7f15769d7ce70e719c", 16), - 'curve': 'secp521r1'} + { + "errno": 0, + "fail": False, + "COUNT": 0, + "CAVS": { + "d": int( + "f70c297a683d6b7ef82b5af7349606c4447c8b4fc6fa5e80", 16 + ), + "x": int( + "f7b5061fb557e516c50abf541d97dbfd76ca7172b22cf590", 16 + ), + "y": int( + "135e15e21f9e85c76205fd148a92ac19f9e6243ddab322d1", 16 + ), + }, + "IUT": { + "d": int( + "a5b4bbad57f101ca48021cb7440cd681a9d40cd51b99d917", 16 + ), + "x": int( + "79a77fcb18a32cdb59ed5d87740f29e8565d649dbf01ce86", 16 + ), + "y": int( + "f7187efaa0b1573f1fb00905d46810b880bf738b4c720bb7", 16 + ), + }, + "Z": int("26382468d721761e14a87dc3bee67340095c6455962d1ba3", 16), + "curve": "secp192r1", + }, + { + "errno": 8, + "fail": True, + "COUNT": 2, + "CAVS": { + "d": int( + "5f909dcb0ccce58c82fada748c47297579e6a981b5518a96", 16 + ), + "x": int( + "537f1ecfda0e366de393a9bc8188fcc280311bffefe21ecf", 16 + ), + "y": int( + "a1fa1f98498d65f2754caff4e5303a4066a5ff89fde95381", 16 + ), + }, + "IUT": { + "d": int( + "3357aa7f47f3e09421602cc12cdce4434c68e330d44de05e", 16 + ), + "x": int( + "6a33d43d9c72173eabc7a771a5687748c4774c62762e96ec", 16 + ), + "y": int( + "8033f238b3abc69470aad4be8dbe4f60a2fd50207626c56a", 16 + ), + }, + "Z": int("3153034f6617326f19c35be8c99a0585431adf09d2f8e0fd", 16), + "curve": "secp192r1", + }, + { + "errno": 13, + "fail": False, + "COUNT": 8, + "CAVS": { + "d": int( + "8fcfaf0524cc868fad20e50410a2205319f1327308d98dc8", 16 + ), + "x": int( + "9b0243d80a9e328738080fb4d46bc450243d0efb7ead0c92", 16 + ), + "y": int( + "ad5bebad7f03849693071537f60ef858cad214123beee7c7", 16 + ), + }, + "IUT": { + "d": int( + "bba95dac90289cb68ca2b006f9757219b70579c299ad7a7d", 16 + ), + "x": int( + "7733dc0cb365cd6312724196b9b4eb491fd4d2e31b9afdb1", 16 + ), + "y": int( + "92ffa3722acc5b94d772258ba2d471b06c0f53f56fcd8662", 16 + ), + }, + "Z": int("0f3c6e4a29a08296ae730f56a1ebf819ea2edfa6f0434e40", 16), + "curve": "secp192r1", + }, + { + "errno": 0, + "fail": False, + "COUNT": 0, + "CAVS": { + "d": int( + "e53a88af7cf8ce6bf13c8b9ad191494e37a6acc1368c71f4" + "306e39e5", + 16, + ), + "x": int( + "3a24217c4b957fea922eec9d9ac52d5cb4b3fcd95efde1e4" + "fa0dd6e2", + 16, + ), + "y": int( + "775b94025a808eb6f4af14ea4b57dca576c35373c6dc198b" + "15b981df", + 16, + ), + }, + "IUT": { + "d": int( + "09f51e302c6a0fe6ff48f34c208c6af91e70f65f88102e6f" + "cab9af4a", + 16, + ), + "x": int( + "c5d5706ccd7424c74fd616e699865af96e56f39adea6aa05" + "9e5092b5", + 16, + ), + "y": int( + "f0729077bb602404d56d2f7e2ba5bb2f383df4a542556788" + "1ff0165d", + 16, + ), + }, + "Z": int( + "b1259ceedfb663d9515089cf727e7024fb3d86cbcec611b4" "ba0b4ab6", + 16, + ), + "curve": "secp224r1", + }, + { + "errno": 2, + "fail": True, + "COUNT": 0, + "CAVS": { + "d": int( + "305dfb4a8850cc59280891147baf457bfe5e2bae98457163" + "4a77dc8d3472fa9b", + 16, + ), + "x": int( + "202cb5a224e6c2a84e624094486edf04116c8d68ec1f4a0e" + "0ed9ee090e1a900b", + 16, + ), + "y": int( + "cacf3a5789bb33954be600425d62d9eae5371f90f8816725" + "8814213e4a4f4b1a", + 16, + ), + }, + "IUT": { + "d": int( + "72cc52808f294b64b6f7233c3d2f5d96cc1d29287320e39e" + "1c151deef0bc14eb", + 16, + ), + "x": int( + "49a768c9a4ca56e374f685dd76a461b1016c59dcded2c8d8" + "cbd9f23ca453831f", + 16, + ), + "y": int( + "b1e3bb9b5f12a3b5ae788535d4554bd8c46e0e6130075e4e" + "437d3854cf8f1c34", + 16, + ), + }, + "Z": int( + "c0147c3c2691b450b5edc08b51aea224d9f4359ff67aab6d" + "a3146f396dbceaea", + 16, + ), + "curve": "secp256r1", + }, + { + "errno": 0, + "fail": False, + "COUNT": 0, + "CAVS": { + "d": int( + "0e5c98ff2d2a3aab14ad0067b60dbe64e4f541ab5bed11c5" + "a0c55ae1e60b51ff5faaf377837977d80cbfdc33c2ff542b", + 16, + ), + "x": int( + "d1bf2ac21637d66d6398aac01dcd56ac6f065fb45d1f6f16" + "747bab9e9b01b4630b59b20927aea147355bf41838acb482", + 16, + ), + "y": int( + "4c9e23f1c5a41647d094086bf4ed31708651f21d996c4778" + "0688ac10f77deee2e43b5241b6caecd2fd5444bc50472e0e", + 16, + ), + }, + "IUT": { + "d": int( + "f865418473e5bf7d2e1bbcd9bd5a9270c003a9dd35e77813" + "3ca59fcab4bb64fe24d6800e7047bdd033abc8bfa8db35b5", + 16, + ), + "x": int( + "32b72ab9b558249dcbc6cbade234f58e4f7aa5d3f6420ea9" + "9a5f997e8c2a91fb7fd83779d0d2169428683771c745fd1a", + 16, + ), + "y": int( + "c749e02a3719bb56bf1dfc4ba3820309c01ab6e84cb29db7" + "cdd80f127233f5295687f8178f3a8704c1063b84c2ee472f", + 16, + ), + }, + "Z": int( + "a781430e6078a179df3f9ee27cd8fdc6188f161b6c4ccc40" + "53ef6c6ca6fc222946883a53c06db08f0a020023ced055aa", + 16, + ), + "curve": "secp384r1", + }, + { + "errno": 7, + "fail": True, + "COUNT": 0, + "CAVS": { + "d": int( + "0000002fef62381162942889a6094a6bb9ac1f4ddf66d9cd" + "a9f618232d31b90c50d7da78a47ed91d40cae946898571db" + "972dc294b109815f38feee9eaac0d5f7c3250728", + 16, + ), + "x": int( + "0000004b05ffa025113390797f2736174aa1c784f4dd34e7" + "64ee40d40e4d2442677ebea3498086c9473e5c92789cbdb0" + "2bb327bbd61d58690f6a83d9ca73bccbde37dec4", + 16, + ), + "y": int( + "0000004da67cffc98070b82af61feba78787efefb13bd810" + "d80ff92304788e49a4e5b634b3565474a8ecb1615d7b1b77" + "a7a27875adb73a8a5d8f3f84e5e8b744cda250b0", + 16, + ), + }, + "IUT": { + "d": int( + "00000311a5e520e238141527671a38cb6f776d96a9f82ef7" + "0dffa11dc0895f4060f1abbb9ad6fd259e4a7beaf5f7266e" + "a1bb45bcbfebfda2705e5c551e710fb1d745f57e", + 16, + ), + "x": int( + "0000010ba3778cb2cc965834c0a9593adc6a222692656d65" + "7fb0d15293edf0ab33762384a96a16fddea7540b7ccbcca4" + "6ec4ac9bcf95fdb5aa18e158aab4d91981bd733e", + 16, + ), + "y": int( + "0000018522df93ddd636e5bc94daecdc600fa241686ec186" + "34fd30b7cbdfdc9ffba1166ac08df34a31896f6fad191414" + "929261ebd7187afb72919f8a0c926be37f99c1e5", + 16, + ), + }, + "Z": int( + "01a5e4b31be4b1346e53906b6767b1fe94ec1a8a5abc28fb" + "6f01518c056959af3bc9335dddab178b52318cc551255993" + "1b8dc18de0ce810c2c7f15769d7ce70e719c", + 16, + ), + "curve": "secp521r1", + }, ] assert expected == load_kasvs_ecdh_vectors(vector_data) def test_load_kasvs_ecdh_kdf_vectors(): - vector_data = textwrap.dedent(""" + vector_data = textwrap.dedent( + """ # Parameter set(s) supported: EB EC ED EE # CAVSid: CAVSid (in hex: 434156536964) # IUTid: In hex: a1b2c3d4e5 @@ -3361,39 +3966,68 @@ def test_load_kasvs_ecdh_kdf_vectors(): ffdfa60dd7 DKM = ad65fa2d12541c3a21f3cd223efb Result = F (12 - Tag changed ) - """).splitlines() + """ + ).splitlines() expected = [ - {'errno': 12, - 'fail': True, - 'COUNT': 50, - 'CAVS': { - 'd': int("540904b67b3716823dd621ed72ad3dbc615887b4f56f910b" - "78a57199", 16), - 'x': int("28e5f3a72d8f6b8499dd1bcdfceafcecec68a0d715789bcf" - "4b55fe15", 16), - 'y': int("8c8006a7da7c1a19f5328d7e865522b0c0dfb9a29b2c46dc" - "96590d2a", 16)}, - 'IUT': { - 'd': int("5e717ae889fc8d67be11c2ebe1a7d3550051448d68a040b2" - "dee8e327", 16), - 'x': int("ae7f3db340b647d61713f5374c019f1be2b28573cb6219bb" - "7b747223", 16), - 'y': int("800e6bffcf97c15864ec6e5673fb83359b45f89b8a26a27f" - "6f3dfbff", 16)}, - 'OI': int("a1b2c3d4e5bb7f1b40d14ebd70443393990b574341565369" - "645b1582daab9cc6c30d61fdcf1cdfc7e9a304651e0fdb", 16), - 'Z': int("43f23b2c760d686fc99cc008b63aea92f866e224265af60d" - "2d8ae540", 16), - 'DKM': int("ad65fa2d12541c3a21f3cd223efb", 16), - 'curve': 'secp224r1'} + { + "errno": 12, + "fail": True, + "COUNT": 50, + "CAVS": { + "d": int( + "540904b67b3716823dd621ed72ad3dbc615887b4f56f910b" + "78a57199", + 16, + ), + "x": int( + "28e5f3a72d8f6b8499dd1bcdfceafcecec68a0d715789bcf" + "4b55fe15", + 16, + ), + "y": int( + "8c8006a7da7c1a19f5328d7e865522b0c0dfb9a29b2c46dc" + "96590d2a", + 16, + ), + }, + "IUT": { + "d": int( + "5e717ae889fc8d67be11c2ebe1a7d3550051448d68a040b2" + "dee8e327", + 16, + ), + "x": int( + "ae7f3db340b647d61713f5374c019f1be2b28573cb6219bb" + "7b747223", + 16, + ), + "y": int( + "800e6bffcf97c15864ec6e5673fb83359b45f89b8a26a27f" + "6f3dfbff", + 16, + ), + }, + "OI": int( + "a1b2c3d4e5bb7f1b40d14ebd70443393990b574341565369" + "645b1582daab9cc6c30d61fdcf1cdfc7e9a304651e0fdb", + 16, + ), + "Z": int( + "43f23b2c760d686fc99cc008b63aea92f866e224265af60d" "2d8ae540", + 16, + ), + "DKM": int("ad65fa2d12541c3a21f3cd223efb", 16), + "curve": "secp224r1", + } ] assert expected == load_kasvs_ecdh_vectors(vector_data) def test_load_x963_vectors(): - vector_data = textwrap.dedent(""" + vector_data = textwrap.dedent( + """ # CAVS 12.0 # 'ANS X9.63-2001' information for sample @@ -3443,37 +4077,48 @@ def test_load_x963_vectors(): d6e4dd2a599acceb3ea54a6217ce0b50eef4f6b40a5c30250a5a8eeee208002267089dbf351f3f\ 5022aa9638bf1ee419dea9c4ff745a25ac27bda33ca08bd56dd1a59b4106cf2dbbc0ab2aa8e2ef\ a7b17902d34276951ceccab87f9661c3e8816 - """).splitlines() + """ + ).splitlines() assert load_x963_vectors(vector_data) == [ - {"hash": "SHA-1", "count": 0, - "shared_secret_length": 192, - "Z": "1c7d7b5f0597b03d06a018466ed1a93e30ed4b04dc64ccdd", - "sharedinfo_length": 0, - "key_data_length": 128, - "key_data": "bf71dffd8f4d99223936beb46fee8ccc"}, - {"hash": "SHA-1", "count": 1, - "shared_secret_length": 192, - "Z": "5ed096510e3fcf782ceea98e9737993e2b21370f6cda2ab1", - "sharedinfo_length": 0, - "key_data_length": 128, - "key_data": "ec3e224446bfd7b3be1df404104af953"}, - {"hash": "SHA-512", "count": 0, - "shared_secret_length": 521, - "Z": "00aa5bb79b33e389fa58ceadc047197f14e73712f452caa9fc4c9adb369348b\ + { + "hash": "SHA-1", + "count": 0, + "shared_secret_length": 192, + "Z": "1c7d7b5f0597b03d06a018466ed1a93e30ed4b04dc64ccdd", + "sharedinfo_length": 0, + "key_data_length": 128, + "key_data": "bf71dffd8f4d99223936beb46fee8ccc", + }, + { + "hash": "SHA-1", + "count": 1, + "shared_secret_length": 192, + "Z": "5ed096510e3fcf782ceea98e9737993e2b21370f6cda2ab1", + "sharedinfo_length": 0, + "key_data_length": 128, + "key_data": "ec3e224446bfd7b3be1df404104af953", + }, + { + "hash": "SHA-512", + "count": 0, + "shared_secret_length": 521, + "Z": "00aa5bb79b33e389fa58ceadc047197f14e73712f452caa9fc4c9adb369348b\ 81507392f1a86ddfdb7c4ff8231c4bd0f44e44a1b55b1404747a9e2e753f55ef05a2d", - "sharedinfo_length": 128, - "sharedinfo": "e3b5b4c1b0d5cf1d2b3a2f9937895d31", - "key_data_length": 1024, - "key_data": "4463f869f3cc18769b52264b0112b5858f7ad32a5a2d96d8cffabf7f\ + "sharedinfo_length": 128, + "sharedinfo": "e3b5b4c1b0d5cf1d2b3a2f9937895d31", + "key_data_length": 1024, + "key_data": "4463f869f3cc18769b52264b0112b5858f7ad32a5a2d96d8cffabf7f\ a733633d6e4dd2a599acceb3ea54a6217ce0b50eef4f6b40a5c30250a5a8eeee208002267089db\ f351f3f5022aa9638bf1ee419dea9c4ff745a25ac27bda33ca08bd56dd1a59b4106cf2dbbc0ab2\ -aa8e2efa7b17902d34276951ceccab87f9661c3e8816"}, +aa8e2efa7b17902d34276951ceccab87f9661c3e8816", + }, ] def test_load_kbkdf_vectors(): - vector_data = textwrap.dedent(""" + vector_data = textwrap.dedent( + """ # CAVS 14.4 # "SP800-108 - KDF" information for "test1" # KDF Mode Supported: Counter Mode @@ -3523,50 +4168,58 @@ def test_load_kbkdf_vectors(): instring = 7f50fc1f77c3ac752443154c1577d3c47b86fccffe82ff43aa1b91eeb5\ 730d7e9e6aab78374d854aecb7143faba6b1eb90d3d9e7a2f6d78dd9a6c4a701 KO = b8894c6133a46701909b5c8a84322dec - """).splitlines() + """ + ).splitlines() assert load_nist_kbkdf_vectors(vector_data) == [ - {'prf': 'hmac_sha1', - 'ctrlocation': 'before_fixed', - 'rlen': 8, - 'l': 128, - 'ki': b'00a39bd547fb88b2d98727cf64c195c61e1cad6c', - 'fixedinputdatabytelen': b'60', - 'fixedinputdata': b'98132c1ffaf59ae5cbc0a3133d84c551bb97e0c75ecaddfc\ -30056f6876f59803009bffc7d75c4ed46f40b8f80426750d15bc1ddb14ac5dcb69a68242', - 'binary rep of i': b'01', - 'instring': b'0198132c1ffaf59ae5cbc0a3133d84c551bb97e0c75ecaddfc3005\ -6f6876f59803009bffc7d75c4ed46f40b8f80426750d15bc1ddb14ac5dcb69a68242', - 'ko': b'0611e1903609b47ad7a5fc2c82e47702'}, - {'prf': 'hmac_sha1', - 'ctrlocation': 'before_fixed', - 'rlen': 8, - 'l': 128, - 'ki': b'a39bdf744ed7e33fdec060c8736e9725179885a8', - 'fixedinputdatabytelen': b'60', - 'fixedinputdata': b'af71b44940acff98949ad17f1ca20e8fdb3957cacdcd41e9\ -c591e18235019f90b9f8ee6e75700bcab2f8407525a104799b3e9725e27d738a9045e832', - 'binary rep of i': b'01', - 'instring': b'01af71b44940acff98949ad17f1ca20e8fdb3957cacdcd41e9c591\ -e18235019f90b9f8ee6e75700bcab2f8407525a104799b3e9725e27d738a9045e832', - 'ko': b'51dc4668947e3685099bc3b5f8527468'}, - {'prf': 'hmac_sha224', - 'ctrlocation': 'after_fixed', - 'rlen': 8, - 'l': 128, - 'ki': b'ab56556b107a3a79fe084df0f1bb3ad049a6cc1490f20da4b3df282c', - 'fixedinputdatabytelen': b'60', - 'fixedinputdata': b'7f50fc1f77c3ac752443154c1577d3c47b86fccffe82ff43\ -aa1b91eeb5730d7e9e6aab78374d854aecb7143faba6b1eb90d3d9e7a2f6d78dd9a6c4a7', - 'binary rep of i': b'01', - 'instring': b'7f50fc1f77c3ac752443154c1577d3c47b86fccffe82ff43aa1b91\ -eeb5730d7e9e6aab78374d854aecb7143faba6b1eb90d3d9e7a2f6d78dd9a6c4a701', - 'ko': b'b8894c6133a46701909b5c8a84322dec'} + { + "prf": "hmac_sha1", + "ctrlocation": "before_fixed", + "rlen": 8, + "l": 128, + "ki": b"00a39bd547fb88b2d98727cf64c195c61e1cad6c", + "fixedinputdatabytelen": b"60", + "fixedinputdata": b"98132c1ffaf59ae5cbc0a3133d84c551bb97e0c75ecaddfc\ +30056f6876f59803009bffc7d75c4ed46f40b8f80426750d15bc1ddb14ac5dcb69a68242", + "binary rep of i": b"01", + "instring": b"0198132c1ffaf59ae5cbc0a3133d84c551bb97e0c75ecaddfc3005\ +6f6876f59803009bffc7d75c4ed46f40b8f80426750d15bc1ddb14ac5dcb69a68242", + "ko": b"0611e1903609b47ad7a5fc2c82e47702", + }, + { + "prf": "hmac_sha1", + "ctrlocation": "before_fixed", + "rlen": 8, + "l": 128, + "ki": b"a39bdf744ed7e33fdec060c8736e9725179885a8", + "fixedinputdatabytelen": b"60", + "fixedinputdata": b"af71b44940acff98949ad17f1ca20e8fdb3957cacdcd41e9\ +c591e18235019f90b9f8ee6e75700bcab2f8407525a104799b3e9725e27d738a9045e832", + "binary rep of i": b"01", + "instring": b"01af71b44940acff98949ad17f1ca20e8fdb3957cacdcd41e9c591\ +e18235019f90b9f8ee6e75700bcab2f8407525a104799b3e9725e27d738a9045e832", + "ko": b"51dc4668947e3685099bc3b5f8527468", + }, + { + "prf": "hmac_sha224", + "ctrlocation": "after_fixed", + "rlen": 8, + "l": 128, + "ki": b"ab56556b107a3a79fe084df0f1bb3ad049a6cc1490f20da4b3df282c", + "fixedinputdatabytelen": b"60", + "fixedinputdata": b"7f50fc1f77c3ac752443154c1577d3c47b86fccffe82ff43\ +aa1b91eeb5730d7e9e6aab78374d854aecb7143faba6b1eb90d3d9e7a2f6d78dd9a6c4a7", + "binary rep of i": b"01", + "instring": b"7f50fc1f77c3ac752443154c1577d3c47b86fccffe82ff43aa1b91\ +eeb5730d7e9e6aab78374d854aecb7143faba6b1eb90d3d9e7a2f6d78dd9a6c4a701", + "ko": b"b8894c6133a46701909b5c8a84322dec", + }, ] def test_load_nist_ccm_vectors_dvpt(): - vector_data = textwrap.dedent(""" + vector_data = textwrap.dedent( + """ # CAVS 11.0 # "CCM-DVPT" information # AES Keylen: 128 @@ -3606,61 +4259,63 @@ def test_load_nist_ccm_vectors_dvpt(): Adata = 00 CT = 3a65e03af37b81d05acc7ec1bc39deb0 Result = Fail - """).splitlines() + """ + ).splitlines() assert load_nist_ccm_vectors(vector_data) == [ { - 'key': b'4ae701103c63deca5b5a3939d7d05992', - 'alen': 0, - 'plen': 0, - 'nlen': 7, - 'tlen': 4, - 'nonce': b'5a8aa485c316e9', - 'adata': b'00', - 'ct': b'02209f55', - 'fail': False, - 'payload': b'00' - }, - { - 'key': b'4ae701103c63deca5b5a3939d7d05992', - 'alen': 0, - 'plen': 0, - 'nlen': 7, - 'tlen': 4, - 'nonce': b'3796cf51b87266', - 'adata': b'00', - 'ct': b'9a04c241', - 'fail': True, - 'payload': b'00' - }, - { - 'key': b'4bb3c4a4f893ad8c9bdc833c325d62b3', - 'alen': 0, - 'plen': 0, - 'nlen': 7, - 'tlen': 16, - 'nonce': b'5a8aa485c316e9', - 'adata': b'00', - 'ct': b'75d582db43ce9b13ab4b6f7f14341330', - 'fail': False, - 'payload': b'00' - }, - { - 'key': b'4bb3c4a4f893ad8c9bdc833c325d62b3', - 'alen': 0, - 'plen': 0, - 'nlen': 7, - 'tlen': 16, - 'nonce': b'3796cf51b87266', - 'adata': b'00', - 'ct': b'3a65e03af37b81d05acc7ec1bc39deb0', - 'fail': True, - 'payload': b'00' - } + "key": b"4ae701103c63deca5b5a3939d7d05992", + "alen": 0, + "plen": 0, + "nlen": 7, + "tlen": 4, + "nonce": b"5a8aa485c316e9", + "adata": b"00", + "ct": b"02209f55", + "fail": False, + "payload": b"00", + }, + { + "key": b"4ae701103c63deca5b5a3939d7d05992", + "alen": 0, + "plen": 0, + "nlen": 7, + "tlen": 4, + "nonce": b"3796cf51b87266", + "adata": b"00", + "ct": b"9a04c241", + "fail": True, + "payload": b"00", + }, + { + "key": b"4bb3c4a4f893ad8c9bdc833c325d62b3", + "alen": 0, + "plen": 0, + "nlen": 7, + "tlen": 16, + "nonce": b"5a8aa485c316e9", + "adata": b"00", + "ct": b"75d582db43ce9b13ab4b6f7f14341330", + "fail": False, + "payload": b"00", + }, + { + "key": b"4bb3c4a4f893ad8c9bdc833c325d62b3", + "alen": 0, + "plen": 0, + "nlen": 7, + "tlen": 16, + "nonce": b"3796cf51b87266", + "adata": b"00", + "ct": b"3a65e03af37b81d05acc7ec1bc39deb0", + "fail": True, + "payload": b"00", + }, ] def test_load_nist_ccm_vectors_vadt(): - vector_data = textwrap.dedent(""" + vector_data = textwrap.dedent( + """ # CAVS 11.0 # "CCM-VADT" information # AES Keylen: 128 @@ -3700,52 +4355,53 @@ def test_load_nist_ccm_vectors_vadt(): Adata = c5 Payload = 032fee9dbffccc751e6a1ee6d07bb218b3a7ec6bf5740ead CT = f0828917020651c085e42459c544ec52e99372005362baf308ebe - """).splitlines() + """ + ).splitlines() assert load_nist_ccm_vectors(vector_data) == [ { - 'plen': 24, - 'nlen': 13, - 'tlen': 16, - 'alen': 0, - 'key': b'd24a3d3dde8c84830280cb87abad0bb3', - 'nonce': b'f1100035bb24a8d26004e0e24b', - 'adata': b'00', - 'payload': b'7c86135ed9c2a515aaae0e9a208133897269220f30870006', - 'ct': b'1faeb0ee2ca2cd52f0aa3966578344f24e69b742c4ab37ab11233' - }, - { - 'plen': 24, - 'nlen': 13, - 'tlen': 16, - 'alen': 0, - 'key': b'd24a3d3dde8c84830280cb87abad0bb3', - 'nonce': b'f1100035bb24a8d26004e0e24b', - 'adata': b'00', - 'payload': b'48df73208cdc63d716752df7794807b1b2a80794a2433455', - 'ct': b'642145210f947bc4a0b1e678fd8c990c2c1d89d4110a95c954d61' - }, - { - 'plen': 24, - 'nlen': 13, - 'tlen': 16, - 'alen': 1, - 'key': b'08b0da255d2083808a1b4d367090bacc', - 'nonce': b'777828b13679a9e2ca89568233', - 'adata': b'dd', - 'payload': b'1b156d7e2bf7c9a25ad91cff7b0b02161cb78ff9162286b0', - 'ct': b'e8b80af4960d5417c15726406e345c5c46831192b03432eed16b6' - }, - { - 'plen': 24, - 'nlen': 13, - 'tlen': 16, - 'alen': 1, - 'key': b'08b0da255d2083808a1b4d367090bacc', - 'nonce': b'777828b13679a9e2ca89568233', - 'adata': b'c5', - 'payload': b'032fee9dbffccc751e6a1ee6d07bb218b3a7ec6bf5740ead', - 'ct': b'f0828917020651c085e42459c544ec52e99372005362baf308ebe' - } + "plen": 24, + "nlen": 13, + "tlen": 16, + "alen": 0, + "key": b"d24a3d3dde8c84830280cb87abad0bb3", + "nonce": b"f1100035bb24a8d26004e0e24b", + "adata": b"00", + "payload": b"7c86135ed9c2a515aaae0e9a208133897269220f30870006", + "ct": b"1faeb0ee2ca2cd52f0aa3966578344f24e69b742c4ab37ab11233", + }, + { + "plen": 24, + "nlen": 13, + "tlen": 16, + "alen": 0, + "key": b"d24a3d3dde8c84830280cb87abad0bb3", + "nonce": b"f1100035bb24a8d26004e0e24b", + "adata": b"00", + "payload": b"48df73208cdc63d716752df7794807b1b2a80794a2433455", + "ct": b"642145210f947bc4a0b1e678fd8c990c2c1d89d4110a95c954d61", + }, + { + "plen": 24, + "nlen": 13, + "tlen": 16, + "alen": 1, + "key": b"08b0da255d2083808a1b4d367090bacc", + "nonce": b"777828b13679a9e2ca89568233", + "adata": b"dd", + "payload": b"1b156d7e2bf7c9a25ad91cff7b0b02161cb78ff9162286b0", + "ct": b"e8b80af4960d5417c15726406e345c5c46831192b03432eed16b6", + }, + { + "plen": 24, + "nlen": 13, + "tlen": 16, + "alen": 1, + "key": b"08b0da255d2083808a1b4d367090bacc", + "nonce": b"777828b13679a9e2ca89568233", + "adata": b"c5", + "payload": b"032fee9dbffccc751e6a1ee6d07bb218b3a7ec6bf5740ead", + "ct": b"f0828917020651c085e42459c544ec52e99372005362baf308ebe", + }, ] @@ -3767,16 +4423,15 @@ def test_raises_unsupported_algorithm_wrong_reason(): # Check that it fails if the wrong reason code is raised. with pytest.raises(AssertionError): with raises_unsupported_algorithm(None): - raise UnsupportedAlgorithm("An error.", - _Reasons.BACKEND_MISSING_INTERFACE) + raise UnsupportedAlgorithm( + "An error.", _Reasons.BACKEND_MISSING_INTERFACE + ) def test_raises_unsupported_no_exc(): # Check that it fails if no exception is raised. with pytest.raises(pytest.fail.Exception): - with raises_unsupported_algorithm( - _Reasons.BACKEND_MISSING_INTERFACE - ): + with raises_unsupported_algorithm(_Reasons.BACKEND_MISSING_INTERFACE): pass @@ -3785,6 +4440,7 @@ def test_raises_unsupported_algorithm(): with raises_unsupported_algorithm( _Reasons.BACKEND_MISSING_INTERFACE ) as exc_info: - raise UnsupportedAlgorithm("An error.", - _Reasons.BACKEND_MISSING_INTERFACE) + raise UnsupportedAlgorithm( + "An error.", _Reasons.BACKEND_MISSING_INTERFACE + ) assert exc_info.type is UnsupportedAlgorithm diff --git a/tests/test_warnings.py b/tests/test_warnings.py index d27e757fc845..073c699bc084 100644 --- a/tests/test_warnings.py +++ b/tests/test_warnings.py @@ -21,7 +21,7 @@ def test_deprecated(self, monkeypatch): value=1, module_name=mod.__name__, message="deprecated message text", - warning_class=DeprecationWarning + warning_class=DeprecationWarning, ) mod.Y = deprecated( value=2, @@ -55,7 +55,7 @@ def test_deleting_deprecated_members(self, monkeypatch): value=1, module_name=mod.__name__, message="deprecated message text", - warning_class=DeprecationWarning + warning_class=DeprecationWarning, ) mod.Y = deprecated( value=2, diff --git a/tests/utils.py b/tests/utils.py index 401b4e33871c..5d98af00e337 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -29,9 +29,7 @@ def check_backend_support(backend, item): for mark in item.node.iter_markers("supported"): if not mark.kwargs["only_if"](backend): - pytest.skip("{} ({})".format( - mark.kwargs["skip_message"], backend - )) + pytest.skip("{} ({})".format(mark.kwargs["skip_message"], backend)) @contextmanager @@ -55,8 +53,11 @@ def load_nist_vectors(vector_data): line = line.strip() # Blank lines, comments, and section headers are ignored - if not line or line.startswith("#") or (line.startswith("[") and - line.endswith("]")): + if ( + not line + or line.startswith("#") + or (line.startswith("[") and line.endswith("]")) + ): continue if line.strip() == "FAIL": @@ -101,11 +102,9 @@ def load_cryptrec_vectors(vector_data): ct = line.split(" : ")[1].replace(" ", "").encode("ascii") # after a C is found the K+P+C tuple is complete # there are many P+C pairs for each K - cryptrec_list.append({ - "key": key, - "plaintext": pt, - "ciphertext": ct - }) + cryptrec_list.append( + {"key": key, "plaintext": pt, "ciphertext": ct} + ) else: raise ValueError("Invalid line in file '{}'".format(line)) return cryptrec_list @@ -163,9 +162,9 @@ def load_pkcs1_vectors(vector_data): vectors = [] for line in vector_data: if ( - line.startswith("# PSS Example") or - line.startswith("# OAEP Example") or - line.startswith("# PKCS#1 v1.5") + line.startswith("# PSS Example") + or line.startswith("# OAEP Example") + or line.startswith("# PKCS#1 v1.5") ): if example_vector: for key, value in six.iteritems(example_vector): @@ -191,9 +190,8 @@ def load_pkcs1_vectors(vector_data): elif line.startswith("# Encryption"): attr = "encryption" continue - elif ( - example_vector and - line.startswith("# =============================================") + elif example_vector and line.startswith( + "# =============================================" ): for key, value in six.iteritems(example_vector): hex_str = "".join(value).replace(" ", "").encode("ascii") @@ -208,9 +206,8 @@ def load_pkcs1_vectors(vector_data): example_vector[attr].append(line.strip()) continue - if ( - line.startswith("# Example") or - line.startswith("# =============================================") + if line.startswith("# Example") or line.startswith( + "# =============================================" ): if key: assert private_key_vector @@ -228,18 +225,16 @@ def load_pkcs1_vectors(vector_data): examples = [] assert ( - private_key_vector['public_exponent'] == - public_key_vector['public_exponent'] + private_key_vector["public_exponent"] + == public_key_vector["public_exponent"] ) assert ( - private_key_vector['modulus'] == - public_key_vector['modulus'] + private_key_vector["modulus"] + == public_key_vector["modulus"] ) - vectors.append( - (private_key_vector, public_key_vector) - ) + vectors.append((private_key_vector, public_key_vector)) public_key_vector = collections.defaultdict(list) private_key_vector = collections.defaultdict(list) @@ -321,15 +316,10 @@ def load_rsa_nist_vectors(vector_data): "public_exponent": e, "salt_length": salt_length, "algorithm": value, - "fail": False + "fail": False, } else: - test_data = { - "modulus": n, - "p": p, - "q": q, - "algorithm": value - } + test_data = {"modulus": n, "p": p, "q": q, "algorithm": value} if salt_length is not None: test_data["salt_length"] = salt_length data.append(test_data) @@ -359,21 +349,24 @@ def load_fips_dsa_key_pair_vectors(vector_data): continue if line.startswith("P"): - vectors.append({'p': int(line.split("=")[1], 16)}) + vectors.append({"p": int(line.split("=")[1], 16)}) elif line.startswith("Q"): - vectors[-1]['q'] = int(line.split("=")[1], 16) + vectors[-1]["q"] = int(line.split("=")[1], 16) elif line.startswith("G"): - vectors[-1]['g'] = int(line.split("=")[1], 16) - elif line.startswith("X") and 'x' not in vectors[-1]: - vectors[-1]['x'] = int(line.split("=")[1], 16) - elif line.startswith("X") and 'x' in vectors[-1]: - vectors.append({'p': vectors[-1]['p'], - 'q': vectors[-1]['q'], - 'g': vectors[-1]['g'], - 'x': int(line.split("=")[1], 16) - }) + vectors[-1]["g"] = int(line.split("=")[1], 16) + elif line.startswith("X") and "x" not in vectors[-1]: + vectors[-1]["x"] = int(line.split("=")[1], 16) + elif line.startswith("X") and "x" in vectors[-1]: + vectors.append( + { + "p": vectors[-1]["p"], + "q": vectors[-1]["q"], + "g": vectors[-1]["g"], + "x": int(line.split("=")[1], 16), + } + ) elif line.startswith("Y"): - vectors[-1]['y'] = int(line.split("=")[1], 16) + vectors[-1]["y"] = int(line.split("=")[1], 16) return vectors @@ -403,33 +396,37 @@ def load_fips_dsa_sig_vectors(vector_data): name, value = [c.strip() for c in line.split("=")] if name == "P": - vectors.append({'p': int(value, 16), - 'digest_algorithm': digest_algorithm}) + vectors.append( + {"p": int(value, 16), "digest_algorithm": digest_algorithm} + ) elif name == "Q": - vectors[-1]['q'] = int(value, 16) + vectors[-1]["q"] = int(value, 16) elif name == "G": - vectors[-1]['g'] = int(value, 16) - elif name == "Msg" and 'msg' not in vectors[-1]: + vectors[-1]["g"] = int(value, 16) + elif name == "Msg" and "msg" not in vectors[-1]: hexmsg = value.strip().encode("ascii") - vectors[-1]['msg'] = binascii.unhexlify(hexmsg) - elif name == "Msg" and 'msg' in vectors[-1]: + vectors[-1]["msg"] = binascii.unhexlify(hexmsg) + elif name == "Msg" and "msg" in vectors[-1]: hexmsg = value.strip().encode("ascii") - vectors.append({'p': vectors[-1]['p'], - 'q': vectors[-1]['q'], - 'g': vectors[-1]['g'], - 'digest_algorithm': - vectors[-1]['digest_algorithm'], - 'msg': binascii.unhexlify(hexmsg)}) + vectors.append( + { + "p": vectors[-1]["p"], + "q": vectors[-1]["q"], + "g": vectors[-1]["g"], + "digest_algorithm": vectors[-1]["digest_algorithm"], + "msg": binascii.unhexlify(hexmsg), + } + ) elif name == "X": - vectors[-1]['x'] = int(value, 16) + vectors[-1]["x"] = int(value, 16) elif name == "Y": - vectors[-1]['y'] = int(value, 16) + vectors[-1]["y"] = int(value, 16) elif name == "R": - vectors[-1]['r'] = int(value, 16) + vectors[-1]["r"] = int(value, 16) elif name == "S": - vectors[-1]['s'] = int(value, 16) + vectors[-1]["s"] = int(value, 16) elif name == "Result": - vectors[-1]['result'] = value.split("(")[0].strip() + vectors[-1]["result"] = value.split("(")[0].strip() return vectors @@ -441,14 +438,12 @@ def load_fips_dsa_sig_vectors(vector_data): "P-256": "secp256r1", "P-384": "secp384r1", "P-521": "secp521r1", - "K-163": "sect163k1", "K-233": "sect233k1", "K-256": "secp256k1", "K-283": "sect283k1", "K-409": "sect409k1", "K-571": "sect571k1", - "B-163": "sect163r2", "B-233": "sect233r1", "B-283": "sect283r1", @@ -476,10 +471,7 @@ def load_fips_ecdsa_key_pair_vectors(vector_data): if key_data is not None: vectors.append(key_data) - key_data = { - "curve": curve_name, - "d": int(line.split("=")[1], 16) - } + key_data = {"curve": curve_name, "d": int(line.split("=")[1], 16)} elif key_data is not None: if line.startswith("Qx = "): @@ -521,7 +513,7 @@ def load_fips_ecdsa_signing_vectors(vector_data): data = { "curve": curve_name, "digest_algorithm": digest_name, - "message": binascii.unhexlify(hexmsg) + "message": binascii.unhexlify(hexmsg), } elif data is not None: @@ -551,10 +543,7 @@ def load_kasvs_dh_vectors(vector_data): result_rx = re.compile(r"([FP]) \(([0-9]+) -") vectors = [] - data = { - "fail_z": False, - "fail_agree": False - } + data = {"fail_z": False, "fail_agree": False} for line in vector_data: line = line.strip() @@ -596,7 +585,7 @@ def load_kasvs_dh_vectors(vector_data): "q": data["q"], "g": data["g"], "fail_z": False, - "fail_agree": False + "fail_agree": False, } return vectors @@ -646,7 +635,7 @@ def load_kasvs_ecdh_vectors(vector_data): tag = line curve = None elif line.startswith("[Curve selected:"): - curve = curve_name_map[line.split(':')[1].strip()[:-1]] + curve = curve_name_map[line.split(":")[1].strip()[:-1]] if tag is not None and curve is not None: sets[tag.strip("[]")] = curve @@ -775,8 +764,8 @@ def load_nist_kbkdf_vectors(vector_data): if line.startswith("[") and line.endswith("]"): tag_data = line[1:-1] name, value = [c.strip() for c in tag_data.split("=")] - if value.endswith('_BITS'): - value = int(value.split('_')[0]) + if value.endswith("_BITS"): + value = int(value.split("_")[0]) tag.update({name.lower(): value}) continue @@ -798,17 +787,19 @@ def load_nist_kbkdf_vectors(vector_data): def load_ed25519_vectors(vector_data): data = [] for line in vector_data: - secret_key, public_key, message, signature, _ = line.split(':') + secret_key, public_key, message, signature, _ = line.split(":") # In the vectors the first element is secret key + public key secret_key = secret_key[0:64] # In the vectors the signature section is signature + message signature = signature[0:128] - data.append({ - "secret_key": secret_key, - "public_key": public_key, - "message": message, - "signature": signature - }) + data.append( + { + "secret_key": secret_key, + "public_key": public_key, + "message": message, + "signature": signature, + } + ) return data diff --git a/tests/wycheproof/test_aes.py b/tests/wycheproof/test_aes.py index 2b1ed77d019b..e33c01e99f54 100644 --- a/tests/wycheproof/test_aes.py +++ b/tests/wycheproof/test_aes.py @@ -11,9 +11,7 @@ from cryptography.exceptions import InvalidTag from cryptography.hazmat.backends.interfaces import CipherBackend from cryptography.hazmat.primitives import padding -from cryptography.hazmat.primitives.ciphers import ( - Cipher, algorithms, modes -) +from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.primitives.ciphers.aead import AESCCM, AESGCM from ..hazmat.primitives.test_aead import _aead_supported @@ -31,8 +29,9 @@ def test_aes_cbc_pkcs5(backend, wycheproof): cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend) enc = cipher.encryptor() - computed_ct = enc.update( - padder.update(msg) + padder.finalize()) + enc.finalize() + computed_ct = ( + enc.update(padder.update(msg) + padder.finalize()) + enc.finalize() + ) dec = cipher.decryptor() padded_msg = dec.update(ct) + dec.finalize() unpadder = padding.PKCS7(128).unpadder() @@ -69,7 +68,7 @@ def test_aes_gcm(backend, wycheproof): dec = Cipher( algorithms.AES(key), modes.GCM(iv, tag, min_tag_length=len(tag)), - backend + backend, ).decryptor() dec.authenticate_additional_data(aad) computed_msg = dec.update(ct) + dec.finalize() @@ -81,7 +80,7 @@ def test_aes_gcm(backend, wycheproof): dec = Cipher( algorithms.AES(key), modes.GCM(iv, tag, min_tag_length=len(tag)), - backend + backend, ).decryptor() dec.authenticate_additional_data(aad) dec.update(ct) @@ -131,8 +130,8 @@ def test_aes_ccm_aead_api(backend, wycheproof): tag = binascii.unhexlify(wycheproof.testcase["tag"]) if ( - wycheproof.invalid and - wycheproof.testcase["comment"] == "Invalid tag size" + wycheproof.invalid + and wycheproof.testcase["comment"] == "Invalid tag size" ): with pytest.raises(ValueError): AESCCM(key, tag_length=wycheproof.testgroup["tagSize"] // 8) diff --git a/tests/wycheproof/test_chacha20poly1305.py b/tests/wycheproof/test_chacha20poly1305.py index deef5a0a7dfe..48023ca63d70 100644 --- a/tests/wycheproof/test_chacha20poly1305.py +++ b/tests/wycheproof/test_chacha20poly1305.py @@ -17,7 +17,7 @@ @pytest.mark.skipif( not _aead_supported(ChaCha20Poly1305), - reason="Requires OpenSSL with ChaCha20Poly1305 support" + reason="Requires OpenSSL with ChaCha20Poly1305 support", ) @pytest.mark.requires_backend_interface(interface=CipherBackend) @pytest.mark.wycheproof_tests("chacha20_poly1305_test.json") diff --git a/tests/wycheproof/test_dsa.py b/tests/wycheproof/test_dsa.py index 5019dc6addb6..9185b3e2f4e0 100644 --- a/tests/wycheproof/test_dsa.py +++ b/tests/wycheproof/test_dsa.py @@ -34,10 +34,8 @@ def test_dsa_signature(backend, wycheproof): ) digest = _DIGESTS[wycheproof.testgroup["sha"]] - if ( - wycheproof.valid or ( - wycheproof.acceptable and not wycheproof.has_flag("NoLeadingZero") - ) + if wycheproof.valid or ( + wycheproof.acceptable and not wycheproof.has_flag("NoLeadingZero") ): key.verify( binascii.unhexlify(wycheproof.testcase["sig"]), diff --git a/tests/wycheproof/test_ecdsa.py b/tests/wycheproof/test_ecdsa.py index 49a3388d095b..802bb9f00b3e 100644 --- a/tests/wycheproof/test_ecdsa.py +++ b/tests/wycheproof/test_ecdsa.py @@ -75,9 +75,8 @@ def test_ecdsa_signature(backend, wycheproof): if not backend.hash_supported(digest): pytest.skip("Hash {} not supported".format(digest)) - if ( - wycheproof.valid or - (wycheproof.acceptable and not wycheproof.has_flag("MissingZero")) + if wycheproof.valid or ( + wycheproof.acceptable and not wycheproof.has_flag("MissingZero") ): key.verify( binascii.unhexlify(wycheproof.testcase["sig"]), diff --git a/tests/wycheproof/test_eddsa.py b/tests/wycheproof/test_eddsa.py index 5beca130438d..42c1498afff1 100644 --- a/tests/wycheproof/test_eddsa.py +++ b/tests/wycheproof/test_eddsa.py @@ -15,11 +15,9 @@ @pytest.mark.supported( only_if=lambda backend: backend.ed25519_supported(), - skip_message="Requires OpenSSL with Ed25519 support" -) -@pytest.mark.wycheproof_tests( - "eddsa_test.json", + skip_message="Requires OpenSSL with Ed25519 support", ) +@pytest.mark.wycheproof_tests("eddsa_test.json") def test_ed25519_signature(backend, wycheproof): # We want to fail if/when wycheproof adds more edwards curve tests # so we can add them as well. @@ -44,11 +42,9 @@ def test_ed25519_signature(backend, wycheproof): @pytest.mark.supported( only_if=lambda backend: backend.ed448_supported(), - skip_message="Requires OpenSSL with Ed448 support" -) -@pytest.mark.wycheproof_tests( - "ed448_test.json", + skip_message="Requires OpenSSL with Ed448 support", ) +@pytest.mark.wycheproof_tests("ed448_test.json") def test_ed448_signature(backend, wycheproof): key = Ed448PublicKey.from_public_bytes( binascii.unhexlify(wycheproof.testgroup["key"]["pk"]) diff --git a/tests/wycheproof/test_hkdf.py b/tests/wycheproof/test_hkdf.py index 7038d6232c8e..3e1687ea3105 100644 --- a/tests/wycheproof/test_hkdf.py +++ b/tests/wycheproof/test_hkdf.py @@ -35,7 +35,7 @@ def test_hkdf(backend, wycheproof): length=wycheproof.testcase["size"], salt=binascii.unhexlify(wycheproof.testcase["salt"]), info=binascii.unhexlify(wycheproof.testcase["info"]), - backend=backend + backend=backend, ) return @@ -44,7 +44,7 @@ def test_hkdf(backend, wycheproof): length=wycheproof.testcase["size"], salt=binascii.unhexlify(wycheproof.testcase["salt"]), info=binascii.unhexlify(wycheproof.testcase["info"]), - backend=backend + backend=backend, ) result = h.derive(binascii.unhexlify(wycheproof.testcase["ikm"])) assert result == binascii.unhexlify(wycheproof.testcase["okm"]) diff --git a/tests/wycheproof/test_keywrap.py b/tests/wycheproof/test_keywrap.py index 5f694e4d3346..9c7d522e61e0 100644 --- a/tests/wycheproof/test_keywrap.py +++ b/tests/wycheproof/test_keywrap.py @@ -44,11 +44,9 @@ def test_keywrap(backend, wycheproof): key_to_wrap = binascii.unhexlify(wycheproof.testcase["msg"]) expected = binascii.unhexlify(wycheproof.testcase["ct"]) - if ( - wycheproof.valid or ( - wycheproof.acceptable and - wycheproof.testcase["comment"] != "invalid size of wrapped key" - ) + if wycheproof.valid or ( + wycheproof.acceptable + and wycheproof.testcase["comment"] != "invalid size of wrapped key" ): result = keywrap.aes_key_wrap(wrapping_key, key_to_wrap, backend) assert result == expected diff --git a/tests/wycheproof/test_rsa.py b/tests/wycheproof/test_rsa.py index a7c26e6aae47..c71f05adf58c 100644 --- a/tests/wycheproof/test_rsa.py +++ b/tests/wycheproof/test_rsa.py @@ -36,11 +36,9 @@ def should_verify(backend, wycheproof): if wycheproof.acceptable: if ( - ( - backend._lib.CRYPTOGRAPHY_OPENSSL_110_OR_GREATER or - backend._lib.CRYPTOGRAPHY_IS_LIBRESSL - ) and wycheproof.has_flag("MissingNull") - ): + backend._lib.CRYPTOGRAPHY_OPENSSL_110_OR_GREATER + or backend._lib.CRYPTOGRAPHY_IS_LIBRESSL + ) and wycheproof.has_flag("MissingNull"): return False return True @@ -99,9 +97,7 @@ def test_rsa_pkcs1v15_signature(backend, wycheproof): ) -@pytest.mark.wycheproof_tests( - "rsa_sig_gen_misc_test.json" -) +@pytest.mark.wycheproof_tests("rsa_sig_gen_misc_test.json") def test_rsa_pkcs1v15_signature_generation(backend, wycheproof): key = serialization.load_pem_private_key( wycheproof.testgroup["privateKeyPem"].encode(), @@ -150,9 +146,9 @@ def test_rsa_pss_signature(backend, wycheproof): binascii.unhexlify(wycheproof.testcase["msg"]), padding.PSS( mgf=padding.MGF1(mgf_digest), - salt_length=wycheproof.testgroup["sLen"] + salt_length=wycheproof.testgroup["sLen"], ), - digest + digest, ) else: with pytest.raises(InvalidSignature): @@ -161,17 +157,17 @@ def test_rsa_pss_signature(backend, wycheproof): binascii.unhexlify(wycheproof.testcase["msg"]), padding.PSS( mgf=padding.MGF1(mgf_digest), - salt_length=wycheproof.testgroup["sLen"] + salt_length=wycheproof.testgroup["sLen"], ), - digest + digest, ) @pytest.mark.requires_backend_interface(interface=RSABackend) @pytest.mark.supported( only_if=lambda backend: ( - backend._lib.CRYPTOGRAPHY_OPENSSL_110_OR_GREATER or - backend._lib.CRYPTOGRAPHY_IS_LIBRESSL + backend._lib.CRYPTOGRAPHY_OPENSSL_110_OR_GREATER + or backend._lib.CRYPTOGRAPHY_IS_LIBRESSL ), skip_message=( "A handful of these tests fail on OpenSSL 1.0.2 and since upstream " @@ -210,7 +206,7 @@ def test_rsa_oaep_encryption(backend, wycheproof): padding_algo = padding.OAEP( mgf=padding.MGF1(algorithm=mgf_digest), algorithm=digest, - label=binascii.unhexlify(wycheproof.testcase["label"]) + label=binascii.unhexlify(wycheproof.testcase["label"]), ) if not backend.rsa_padding_supported(padding_algo): @@ -222,15 +218,13 @@ def test_rsa_oaep_encryption(backend, wycheproof): if wycheproof.valid or wycheproof.acceptable: pt = key.decrypt( - binascii.unhexlify(wycheproof.testcase["ct"]), - padding_algo + binascii.unhexlify(wycheproof.testcase["ct"]), padding_algo ) assert pt == binascii.unhexlify(wycheproof.testcase["msg"]) else: with pytest.raises(ValueError): key.decrypt( - binascii.unhexlify(wycheproof.testcase["ct"]), - padding_algo + binascii.unhexlify(wycheproof.testcase["ct"]), padding_algo ) @@ -248,13 +242,12 @@ def test_rsa_pkcs1_encryption(backend, wycheproof): if wycheproof.valid: pt = key.decrypt( - binascii.unhexlify(wycheproof.testcase["ct"]), - padding.PKCS1v15() + binascii.unhexlify(wycheproof.testcase["ct"]), padding.PKCS1v15() ) assert pt == binascii.unhexlify(wycheproof.testcase["msg"]) else: with pytest.raises(ValueError): key.decrypt( binascii.unhexlify(wycheproof.testcase["ct"]), - padding.PKCS1v15() + padding.PKCS1v15(), ) diff --git a/tests/wycheproof/test_x25519.py b/tests/wycheproof/test_x25519.py index 295794670825..ce2a965e3a42 100644 --- a/tests/wycheproof/test_x25519.py +++ b/tests/wycheproof/test_x25519.py @@ -9,18 +9,20 @@ import pytest from cryptography.hazmat.primitives.asymmetric.x25519 import ( - X25519PrivateKey, X25519PublicKey + X25519PrivateKey, + X25519PublicKey, ) @pytest.mark.supported( only_if=lambda backend: backend.x25519_supported(), - skip_message="Requires OpenSSL with X25519 support" + skip_message="Requires OpenSSL with X25519 support", ) @pytest.mark.wycheproof_tests("x25519_test.json") def test_x25519(backend, wycheproof): assert set(wycheproof.testgroup.items()) == { - ("curve", "curve25519"), ("type", "XdhComp") + ("curve", "curve25519"), + ("type", "XdhComp"), } private_key = X25519PrivateKey.from_private_bytes( diff --git a/tests/wycheproof/test_x448.py b/tests/wycheproof/test_x448.py index 094bf57c48c8..fcac80996f74 100644 --- a/tests/wycheproof/test_x448.py +++ b/tests/wycheproof/test_x448.py @@ -9,18 +9,20 @@ import pytest from cryptography.hazmat.primitives.asymmetric.x448 import ( - X448PrivateKey, X448PublicKey + X448PrivateKey, + X448PublicKey, ) @pytest.mark.supported( only_if=lambda backend: backend.x448_supported(), - skip_message="Requires OpenSSL with X448 support" + skip_message="Requires OpenSSL with X448 support", ) @pytest.mark.wycheproof_tests("x448_test.json") def test_x448(backend, wycheproof): assert set(wycheproof.testgroup.items()) == { - ("curve", "curve448"), ("type", "XdhComp") + ("curve", "curve448"), + ("type", "XdhComp"), } private_key = X448PrivateKey.from_private_bytes( diff --git a/tests/x509/test_ocsp.py b/tests/x509/test_ocsp.py index 98371a62cf53..5816718a087e 100644 --- a/tests/x509/test_ocsp.py +++ b/tests/x509/test_ocsp.py @@ -24,23 +24,22 @@ def _load_data(filename, loader): return load_vectors_from_file( - filename=filename, - loader=lambda data: loader(data.read()), - mode="rb" + filename=filename, loader=lambda data: loader(data.read()), mode="rb" ) def _cert_and_issuer(): from cryptography.hazmat.backends.openssl.backend import backend + cert = _load_cert( os.path.join("x509", "cryptography.io.pem"), x509.load_pem_x509_certificate, - backend + backend, ) issuer = _load_cert( os.path.join("x509", "rapidssl_sha256_ca_g3.pem"), x509.load_pem_x509_certificate, - backend + backend, ) return cert, issuer @@ -51,23 +50,23 @@ def _generate_root(private_key=None, algorithm=hashes.SHA256()): if private_key is None: private_key = EC_KEY_SECP256R1.private_key(backend) - subject = x509.Name([ - x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u'US'), - x509.NameAttribute(x509.NameOID.COMMON_NAME, u'Cryptography CA'), - ]) - - builder = x509.CertificateBuilder().serial_number( - 123456789 - ).issuer_name( - subject - ).subject_name( - subject - ).public_key( - private_key.public_key() - ).not_valid_before( - datetime.datetime.now() - ).not_valid_after( - datetime.datetime.now() + datetime.timedelta(days=3650) + subject = x509.Name( + [ + x509.NameAttribute(x509.NameOID.COUNTRY_NAME, u"US"), + x509.NameAttribute(x509.NameOID.COMMON_NAME, u"Cryptography CA"), + ] + ) + + builder = ( + x509.CertificateBuilder() + .serial_number(123456789) + .issuer_name(subject) + .subject_name(subject) + .public_key(private_key.public_key()) + .not_valid_before(datetime.datetime.now()) + .not_valid_after( + datetime.datetime.now() + datetime.timedelta(days=3650) + ) ) cert = builder.sign(private_key, algorithm, backend) @@ -84,10 +83,12 @@ def test_load_request(self): os.path.join("x509", "ocsp", "req-sha1.der"), ocsp.load_der_ocsp_request, ) - assert req.issuer_name_hash == (b"8\xcaF\x8c\x07D\x8d\xf4\x81\x96" - b"\xc7mmLpQ\x9e`\xa7\xbd") - assert req.issuer_key_hash == (b"yu\xbb\x84:\xcb,\xdez\t\xbe1" - b"\x1bC\xbc\x1c*MSX") + assert req.issuer_name_hash == ( + b"8\xcaF\x8c\x07D\x8d\xf4\x81\x96" b"\xc7mmLpQ\x9e`\xa7\xbd" + ) + assert req.issuer_key_hash == ( + b"yu\xbb\x84:\xcb,\xdez\t\xbe1" b"\x1bC\xbc\x1c*MSX" + ) assert isinstance(req.hash_algorithm, hashes.SHA1) assert req.serial_number == int( "98D9E5C0B4C373552DF77C5D0F1EB5128E4945F9", 16 @@ -125,7 +126,7 @@ def test_serialize_request(self): req_bytes = load_vectors_from_file( filename=os.path.join("x509", "ocsp", "req-sha1.der"), loader=lambda data: data.read(), - mode="rb" + mode="rb", ) req = ocsp.load_der_ocsp_request(req_bytes) assert req.public_bytes(serialization.Encoding.DER) == req_bytes @@ -196,16 +197,14 @@ def test_create_ocsp_request(self): [ [x509.OCSPNonce(b"0000"), False], [x509.OCSPNonce(b"\x00\x01\x02"), True], - ] + ], ) def test_create_ocsp_request_with_extension(self, ext, critical): cert, issuer = _cert_and_issuer() builder = ocsp.OCSPRequestBuilder() builder = builder.add_certificate( cert, issuer, hashes.SHA1() - ).add_extension( - ext, critical - ) + ).add_extension(ext, critical) req = builder.build() assert len(req.extensions) == 1 assert req.extensions[0].value == ext @@ -219,13 +218,25 @@ def test_add_response_twice(self): time = datetime.datetime.now() builder = ocsp.OCSPResponseBuilder() builder = builder.add_response( - cert, issuer, hashes.SHA256(), ocsp.OCSPCertStatus.GOOD, time, - time, None, None + cert, + issuer, + hashes.SHA256(), + ocsp.OCSPCertStatus.GOOD, + time, + time, + None, + None, ) with pytest.raises(ValueError): builder.add_response( - cert, issuer, hashes.SHA256(), ocsp.OCSPCertStatus.GOOD, time, - time, None, None + cert, + issuer, + hashes.SHA256(), + ocsp.OCSPCertStatus.GOOD, + time, + time, + None, + None, ) def test_invalid_add_response(self): @@ -235,28 +246,58 @@ def test_invalid_add_response(self): builder = ocsp.OCSPResponseBuilder() with pytest.raises(TypeError): builder.add_response( - 'bad', issuer, hashes.SHA256(), ocsp.OCSPCertStatus.GOOD, - time, time, None, None + "bad", + issuer, + hashes.SHA256(), + ocsp.OCSPCertStatus.GOOD, + time, + time, + None, + None, ) with pytest.raises(TypeError): builder.add_response( - cert, 'bad', hashes.SHA256(), ocsp.OCSPCertStatus.GOOD, - time, time, None, None + cert, + "bad", + hashes.SHA256(), + ocsp.OCSPCertStatus.GOOD, + time, + time, + None, + None, ) with pytest.raises(ValueError): builder.add_response( - cert, issuer, 'notahash', ocsp.OCSPCertStatus.GOOD, - time, time, None, None + cert, + issuer, + "notahash", + ocsp.OCSPCertStatus.GOOD, + time, + time, + None, + None, ) with pytest.raises(TypeError): builder.add_response( - cert, issuer, hashes.SHA256(), ocsp.OCSPCertStatus.GOOD, - 'bad', time, None, None + cert, + issuer, + hashes.SHA256(), + ocsp.OCSPCertStatus.GOOD, + "bad", + time, + None, + None, ) with pytest.raises(TypeError): builder.add_response( - cert, issuer, hashes.SHA256(), ocsp.OCSPCertStatus.GOOD, - time, 'bad', None, None + cert, + issuer, + hashes.SHA256(), + ocsp.OCSPCertStatus.GOOD, + time, + "bad", + None, + None, ) with pytest.raises(TypeError): @@ -265,28 +306,58 @@ def test_invalid_add_response(self): ) with pytest.raises(ValueError): builder.add_response( - cert, issuer, hashes.SHA256(), ocsp.OCSPCertStatus.GOOD, - time, time, time, None + cert, + issuer, + hashes.SHA256(), + ocsp.OCSPCertStatus.GOOD, + time, + time, + time, + None, ) with pytest.raises(ValueError): builder.add_response( - cert, issuer, hashes.SHA256(), ocsp.OCSPCertStatus.GOOD, - time, time, None, reason + cert, + issuer, + hashes.SHA256(), + ocsp.OCSPCertStatus.GOOD, + time, + time, + None, + reason, ) with pytest.raises(TypeError): builder.add_response( - cert, issuer, hashes.SHA256(), ocsp.OCSPCertStatus.REVOKED, - time, time, None, reason + cert, + issuer, + hashes.SHA256(), + ocsp.OCSPCertStatus.REVOKED, + time, + time, + None, + reason, ) with pytest.raises(TypeError): builder.add_response( - cert, issuer, hashes.SHA256(), ocsp.OCSPCertStatus.REVOKED, - time, time, time, 0 + cert, + issuer, + hashes.SHA256(), + ocsp.OCSPCertStatus.REVOKED, + time, + time, + time, + 0, ) with pytest.raises(ValueError): builder.add_response( - cert, issuer, hashes.SHA256(), ocsp.OCSPCertStatus.REVOKED, - time, time, time - datetime.timedelta(days=36500), None + cert, + issuer, + hashes.SHA256(), + ocsp.OCSPCertStatus.REVOKED, + time, + time, + time - datetime.timedelta(days=36500), + None, ) def test_invalid_certificates(self): @@ -294,9 +365,9 @@ def test_invalid_certificates(self): with pytest.raises(ValueError): builder.certificates([]) with pytest.raises(TypeError): - builder.certificates(['notacert']) + builder.certificates(["notacert"]) with pytest.raises(TypeError): - builder.certificates('invalid') + builder.certificates("invalid") _, issuer = _cert_and_issuer() builder = builder.certificates([issuer]) @@ -307,9 +378,9 @@ def test_invalid_responder_id(self): builder = ocsp.OCSPResponseBuilder() cert, _ = _cert_and_issuer() with pytest.raises(TypeError): - builder.responder_id(ocsp.OCSPResponderEncoding.HASH, 'invalid') + builder.responder_id(ocsp.OCSPResponderEncoding.HASH, "invalid") with pytest.raises(TypeError): - builder.responder_id('notanenum', cert) + builder.responder_id("notanenum", cert) builder = builder.responder_id(ocsp.OCSPResponderEncoding.NAME, cert) with pytest.raises(ValueError): @@ -337,8 +408,14 @@ def test_sign_no_responder_id(self): this_update = current_time - datetime.timedelta(days=1) next_update = this_update + datetime.timedelta(days=7) builder = builder.add_response( - cert, issuer, hashes.SHA1(), ocsp.OCSPCertStatus.GOOD, this_update, - next_update, None, None + cert, + issuer, + hashes.SHA1(), + ocsp.OCSPCertStatus.GOOD, + this_update, + next_update, + None, + None, ) with pytest.raises(ValueError): builder.sign(private_key, hashes.SHA256()) @@ -353,11 +430,17 @@ def test_sign_invalid_hash_algorithm(self): builder = builder.responder_id( ocsp.OCSPResponderEncoding.NAME, root_cert ).add_response( - cert, issuer, hashes.SHA1(), ocsp.OCSPCertStatus.GOOD, this_update, - next_update, None, None + cert, + issuer, + hashes.SHA1(), + ocsp.OCSPCertStatus.GOOD, + this_update, + next_update, + None, + None, ) with pytest.raises(TypeError): - builder.sign(private_key, 'notahash') + builder.sign(private_key, "notahash") def test_sign_good_cert(self): builder = ocsp.OCSPResponseBuilder() @@ -369,15 +452,23 @@ def test_sign_good_cert(self): builder = builder.responder_id( ocsp.OCSPResponderEncoding.NAME, root_cert ).add_response( - cert, issuer, hashes.SHA1(), ocsp.OCSPCertStatus.GOOD, this_update, - next_update, None, None + cert, + issuer, + hashes.SHA1(), + ocsp.OCSPCertStatus.GOOD, + this_update, + next_update, + None, + None, ) resp = builder.sign(private_key, hashes.SHA256()) assert resp.responder_name == root_cert.subject assert resp.responder_key_hash is None assert (current_time - resp.produced_at).total_seconds() < 10 - assert (resp.signature_algorithm_oid == - x509.SignatureAlgorithmOID.ECDSA_WITH_SHA256) + assert ( + resp.signature_algorithm_oid + == x509.SignatureAlgorithmOID.ECDSA_WITH_SHA256 + ) assert resp.certificate_status == ocsp.OCSPCertStatus.GOOD assert resp.revocation_time is None assert resp.revocation_reason is None @@ -398,8 +489,14 @@ def test_sign_revoked_cert(self): builder = builder.responder_id( ocsp.OCSPResponderEncoding.NAME, root_cert ).add_response( - cert, issuer, hashes.SHA1(), ocsp.OCSPCertStatus.REVOKED, - this_update, next_update, revoked_date, None + cert, + issuer, + hashes.SHA1(), + ocsp.OCSPCertStatus.REVOKED, + this_update, + next_update, + revoked_date, + None, ) resp = builder.sign(private_key, hashes.SHA256()) assert resp.certificate_status == ocsp.OCSPCertStatus.REVOKED @@ -418,13 +515,19 @@ def test_sign_with_appended_certs(self): current_time = datetime.datetime.utcnow().replace(microsecond=0) this_update = current_time - datetime.timedelta(days=1) next_update = this_update + datetime.timedelta(days=7) - builder = builder.responder_id( - ocsp.OCSPResponderEncoding.NAME, root_cert - ).add_response( - cert, issuer, hashes.SHA1(), ocsp.OCSPCertStatus.GOOD, this_update, - next_update, None, None - ).certificates( - [root_cert] + builder = ( + builder.responder_id(ocsp.OCSPResponderEncoding.NAME, root_cert) + .add_response( + cert, + issuer, + hashes.SHA1(), + ocsp.OCSPCertStatus.GOOD, + this_update, + next_update, + None, + None, + ) + .certificates([root_cert]) ) resp = builder.sign(private_key, hashes.SHA256()) assert resp.certificates == [root_cert] @@ -439,8 +542,14 @@ def test_sign_revoked_no_next_update(self): builder = builder.responder_id( ocsp.OCSPResponderEncoding.NAME, root_cert ).add_response( - cert, issuer, hashes.SHA1(), ocsp.OCSPCertStatus.REVOKED, - this_update, None, revoked_date, None + cert, + issuer, + hashes.SHA1(), + ocsp.OCSPCertStatus.REVOKED, + this_update, + None, + revoked_date, + None, ) resp = builder.sign(private_key, hashes.SHA256()) assert resp.certificate_status == ocsp.OCSPCertStatus.REVOKED @@ -463,9 +572,14 @@ def test_sign_revoked_with_reason(self): builder = builder.responder_id( ocsp.OCSPResponderEncoding.NAME, root_cert ).add_response( - cert, issuer, hashes.SHA1(), ocsp.OCSPCertStatus.REVOKED, - this_update, next_update, revoked_date, - x509.ReasonFlags.key_compromise + cert, + issuer, + hashes.SHA1(), + ocsp.OCSPCertStatus.REVOKED, + this_update, + next_update, + revoked_date, + x509.ReasonFlags.key_compromise, ) resp = builder.sign(private_key, hashes.SHA256()) assert resp.certificate_status == ocsp.OCSPCertStatus.REVOKED @@ -487,13 +601,19 @@ def test_sign_responder_id_key_hash(self): builder = builder.responder_id( ocsp.OCSPResponderEncoding.HASH, root_cert ).add_response( - cert, issuer, hashes.SHA1(), ocsp.OCSPCertStatus.GOOD, this_update, - next_update, None, None + cert, + issuer, + hashes.SHA1(), + ocsp.OCSPCertStatus.GOOD, + this_update, + next_update, + None, + None, ) resp = builder.sign(private_key, hashes.SHA256()) assert resp.responder_name is None assert resp.responder_key_hash == ( - b'\x8ca\x94\xe0\x948\xed\x89\xd8\xd4N\x89p\t\xd6\xf9^_\xec}' + b"\x8ca\x94\xe0\x948\xed\x89\xd8\xd4N\x89p\t\xd6\xf9^_\xec}" ) private_key.public_key().verify( resp.signature, resp.tbs_response_bytes, ec.ECDSA(hashes.SHA256()) @@ -509,10 +629,17 @@ def test_invalid_sign_responder_cert_does_not_match_private_key(self): builder = builder.responder_id( ocsp.OCSPResponderEncoding.HASH, root_cert ).add_response( - cert, issuer, hashes.SHA1(), ocsp.OCSPCertStatus.GOOD, this_update, - next_update, None, None + cert, + issuer, + hashes.SHA1(), + ocsp.OCSPCertStatus.GOOD, + this_update, + next_update, + None, + None, ) from cryptography.hazmat.backends.openssl.backend import backend + diff_key = ec.generate_private_key(ec.SECP256R1(), backend) with pytest.raises(ValueError): builder.sign(diff_key, hashes.SHA256()) @@ -524,13 +651,19 @@ def test_sign_with_extension(self): current_time = datetime.datetime.utcnow().replace(microsecond=0) this_update = current_time - datetime.timedelta(days=1) next_update = this_update + datetime.timedelta(days=7) - builder = builder.responder_id( - ocsp.OCSPResponderEncoding.HASH, root_cert - ).add_response( - cert, issuer, hashes.SHA1(), ocsp.OCSPCertStatus.GOOD, this_update, - next_update, None, None - ).add_extension( - x509.OCSPNonce(b"012345"), False + builder = ( + builder.responder_id(ocsp.OCSPResponderEncoding.HASH, root_cert) + .add_response( + cert, + issuer, + hashes.SHA1(), + ocsp.OCSPCertStatus.GOOD, + this_update, + next_update, + None, + None, + ) + .add_extension(x509.OCSPNonce(b"012345"), False) ) resp = builder.sign(private_key, hashes.SHA256()) assert len(resp.extensions) == 1 @@ -548,7 +681,7 @@ def test_sign_with_extension(self): (ocsp.OCSPResponseStatus.TRY_LATER, b"0\x03\n\x01\x03"), (ocsp.OCSPResponseStatus.SIG_REQUIRED, b"0\x03\n\x01\x05"), (ocsp.OCSPResponseStatus.UNAUTHORIZED, b"0\x03\n\x01\x06"), - ] + ], ) def test_build_non_successful_statuses(self, status, der): resp = ocsp.OCSPResponseBuilder.build_unsuccessful(status) @@ -578,58 +711,81 @@ def test_repr(self): @pytest.mark.supported( only_if=lambda backend: ( - backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER), + backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER + ), skip_message="Requires OpenSSL 1.1.0f+", ) def test_eq(self, backend): - sct1 = _load_data( - os.path.join("x509", "ocsp", "resp-sct-extension.der"), - ocsp.load_der_ocsp_response, - ).single_extensions.get_extension_for_class( - x509.SignedCertificateTimestamps - ).value - sct2 = _load_data( - os.path.join("x509", "ocsp", "resp-sct-extension.der"), - ocsp.load_der_ocsp_response, - ).single_extensions.get_extension_for_class( - x509.SignedCertificateTimestamps - ).value + sct1 = ( + _load_data( + os.path.join("x509", "ocsp", "resp-sct-extension.der"), + ocsp.load_der_ocsp_response, + ) + .single_extensions.get_extension_for_class( + x509.SignedCertificateTimestamps + ) + .value + ) + sct2 = ( + _load_data( + os.path.join("x509", "ocsp", "resp-sct-extension.der"), + ocsp.load_der_ocsp_response, + ) + .single_extensions.get_extension_for_class( + x509.SignedCertificateTimestamps + ) + .value + ) assert sct1 == sct2 @pytest.mark.supported( only_if=lambda backend: ( - backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER), + backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER + ), skip_message="Requires OpenSSL 1.1.0f+", ) def test_ne(self, backend): - sct1 = _load_data( - os.path.join("x509", "ocsp", "resp-sct-extension.der"), - ocsp.load_der_ocsp_response, - ).single_extensions.get_extension_for_class( - x509.SignedCertificateTimestamps - ).value + sct1 = ( + _load_data( + os.path.join("x509", "ocsp", "resp-sct-extension.der"), + ocsp.load_der_ocsp_response, + ) + .single_extensions.get_extension_for_class( + x509.SignedCertificateTimestamps + ) + .value + ) sct2 = x509.SignedCertificateTimestamps([]) assert sct1 != sct2 assert sct1 != object() @pytest.mark.supported( only_if=lambda backend: ( - backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER), + backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER + ), skip_message="Requires OpenSSL 1.1.0f+", ) def test_hash(self, backend): - sct1 = _load_data( - os.path.join("x509", "ocsp", "resp-sct-extension.der"), - ocsp.load_der_ocsp_response, - ).single_extensions.get_extension_for_class( - x509.SignedCertificateTimestamps - ).value - sct2 = _load_data( - os.path.join("x509", "ocsp", "resp-sct-extension.der"), - ocsp.load_der_ocsp_response, - ).single_extensions.get_extension_for_class( - x509.SignedCertificateTimestamps - ).value + sct1 = ( + _load_data( + os.path.join("x509", "ocsp", "resp-sct-extension.der"), + ocsp.load_der_ocsp_response, + ) + .single_extensions.get_extension_for_class( + x509.SignedCertificateTimestamps + ) + .value + ) + sct2 = ( + _load_data( + os.path.join("x509", "ocsp", "resp-sct-extension.der"), + ocsp.load_der_ocsp_response, + ) + .single_extensions.get_extension_for_class( + x509.SignedCertificateTimestamps + ) + .value + ) sct3 = x509.SignedCertificateTimestamps([]) assert hash(sct1) == hash(sct2) assert hash(sct1) != hash(sct3) @@ -646,14 +802,17 @@ def test_load_response(self): ocsp.load_der_ocsp_response, ) from cryptography.hazmat.backends.openssl.backend import backend + issuer = _load_cert( os.path.join("x509", "letsencryptx3.pem"), x509.load_pem_x509_certificate, - backend + backend, ) assert resp.response_status == ocsp.OCSPResponseStatus.SUCCESSFUL - assert (resp.signature_algorithm_oid == - x509.SignatureAlgorithmOID.RSA_WITH_SHA256) + assert ( + resp.signature_algorithm_oid + == x509.SignatureAlgorithmOID.RSA_WITH_SHA256 + ) assert isinstance(resp.signature_hash_algorithm, hashes.SHA256) assert resp.signature == base64.b64decode( b"I9KUlyLV/2LbNCVu1BQphxdNlU/jBzXsPYVscPjW5E93pCrSO84GkIWoOJtqsnt" @@ -674,7 +833,7 @@ def test_load_response(self): resp.signature, resp.tbs_response_bytes, PKCS1v15(), - resp.signature_hash_algorithm + resp.signature_hash_algorithm, ) assert resp.certificates == [] assert resp.responder_key_hash is None @@ -686,10 +845,10 @@ def test_load_response(self): assert resp.this_update == datetime.datetime(2018, 8, 30, 11, 0) assert resp.next_update == datetime.datetime(2018, 9, 6, 11, 0) assert resp.issuer_key_hash == ( - b'\xa8Jjc\x04}\xdd\xba\xe6\xd19\xb7\xa6Ee\xef\xf3\xa8\xec\xa1' + b"\xa8Jjc\x04}\xdd\xba\xe6\xd19\xb7\xa6Ee\xef\xf3\xa8\xec\xa1" ) assert resp.issuer_name_hash == ( - b'~\xe6j\xe7r\x9a\xb3\xfc\xf8\xa2 dl\x16\xa1-`q\x08]' + b"~\xe6j\xe7r\x9a\xb3\xfc\xf8\xa2 dl\x16\xa1-`q\x08]" ) assert isinstance(resp.hash_algorithm, hashes.SHA1) assert resp.serial_number == 271024907440004808294641238224534273948400 @@ -783,7 +942,7 @@ def test_load_responder_key_hash(self): ) assert resp.responder_name is None assert resp.responder_key_hash == ( - b'\x0f\x80a\x1c\x821a\xd5/(\xe7\x8dF8\xb4,\xe1\xc6\xd9\xe2' + b"\x0f\x80a\x1c\x821a\xd5/(\xe7\x8dF8\xb4,\xe1\xc6\xd9\xe2" ) def test_load_revoked_reason(self): @@ -817,7 +976,7 @@ def test_serialize_reponse(self): resp_bytes = load_vectors_from_file( filename=os.path.join("x509", "ocsp", "resp-revoked.der"), loader=lambda data: data.read(), - mode="rb" + mode="rb", ) resp = ocsp.load_der_ocsp_response(resp_bytes) assert resp.public_bytes(serialization.Encoding.DER) == resp_bytes @@ -834,7 +993,8 @@ def test_invalid_serialize_encoding(self): @pytest.mark.supported( only_if=lambda backend: ( - backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER), + backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER + ), skip_message="Requires OpenSSL 1.1.0f+", ) def test_single_extensions_sct(self, backend): @@ -848,15 +1008,16 @@ def test_single_extensions_sct(self, backend): assert len(ext.value) == 4 log_ids = [base64.b64encode(sct.log_id) for sct in ext.value] assert log_ids == [ - b'RJRlLrDuzq/EQAfYqP4owNrmgr7YyzG1P9MzlrW2gag=', - b'b1N2rDHwMRnYmQCkURX/dxUcEdkCwQApBo2yCJo32RM=', - b'u9nfvB+KcbWTlCOXqpJ7RzhXlQqrUugakJZkNo4e0YU=', - b'7ku9t3XOYLrhQmkfq+GeZqMPfl+wctiDAMR7iXqo/cs=' + b"RJRlLrDuzq/EQAfYqP4owNrmgr7YyzG1P9MzlrW2gag=", + b"b1N2rDHwMRnYmQCkURX/dxUcEdkCwQApBo2yCJo32RM=", + b"u9nfvB+KcbWTlCOXqpJ7RzhXlQqrUugakJZkNo4e0YU=", + b"7ku9t3XOYLrhQmkfq+GeZqMPfl+wctiDAMR7iXqo/cs=", ] @pytest.mark.supported( only_if=lambda backend: ( - not backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER), + not backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER + ), skip_message="Requires OpenSSL < 1.1.0f", ) def test_skips_single_extensions_scts_if_unsupported(self, backend): @@ -888,7 +1049,7 @@ def test_single_extensions(self, backend): class TestOCSPEdDSA(object): @pytest.mark.supported( only_if=lambda backend: backend.ed25519_supported(), - skip_message="Requires OpenSSL with Ed25519 support / OCSP" + skip_message="Requires OpenSSL with Ed25519 support / OCSP", ) def test_invalid_algorithm(self, backend): builder = ocsp.OCSPResponseBuilder() @@ -902,16 +1063,21 @@ def test_invalid_algorithm(self, backend): builder = builder.responder_id( ocsp.OCSPResponderEncoding.NAME, root_cert ).add_response( - cert, issuer, hashes.SHA1(), ocsp.OCSPCertStatus.REVOKED, - this_update, next_update, revoked_date, - x509.ReasonFlags.key_compromise + cert, + issuer, + hashes.SHA1(), + ocsp.OCSPCertStatus.REVOKED, + this_update, + next_update, + revoked_date, + x509.ReasonFlags.key_compromise, ) with pytest.raises(ValueError): builder.sign(private_key, hashes.SHA256()) @pytest.mark.supported( only_if=lambda backend: backend.ed25519_supported(), - skip_message="Requires OpenSSL with Ed25519 support / OCSP" + skip_message="Requires OpenSSL with Ed25519 support / OCSP", ) def test_sign_ed25519(self, backend): builder = ocsp.OCSPResponseBuilder() @@ -925,9 +1091,14 @@ def test_sign_ed25519(self, backend): builder = builder.responder_id( ocsp.OCSPResponderEncoding.NAME, root_cert ).add_response( - cert, issuer, hashes.SHA1(), ocsp.OCSPCertStatus.REVOKED, - this_update, next_update, revoked_date, - x509.ReasonFlags.key_compromise + cert, + issuer, + hashes.SHA1(), + ocsp.OCSPCertStatus.REVOKED, + this_update, + next_update, + revoked_date, + x509.ReasonFlags.key_compromise, ) resp = builder.sign(private_key, None) assert resp.certificate_status == ocsp.OCSPCertStatus.REVOKED @@ -936,15 +1107,16 @@ def test_sign_ed25519(self, backend): assert resp.this_update == this_update assert resp.next_update == next_update assert resp.signature_hash_algorithm is None - assert (resp.signature_algorithm_oid == - x509.SignatureAlgorithmOID.ED25519) + assert ( + resp.signature_algorithm_oid == x509.SignatureAlgorithmOID.ED25519 + ) private_key.public_key().verify( resp.signature, resp.tbs_response_bytes ) @pytest.mark.supported( only_if=lambda backend: backend.ed448_supported(), - skip_message="Requires OpenSSL with Ed448 support / OCSP" + skip_message="Requires OpenSSL with Ed448 support / OCSP", ) def test_sign_ed448(self, backend): builder = ocsp.OCSPResponseBuilder() @@ -958,9 +1130,14 @@ def test_sign_ed448(self, backend): builder = builder.responder_id( ocsp.OCSPResponderEncoding.NAME, root_cert ).add_response( - cert, issuer, hashes.SHA1(), ocsp.OCSPCertStatus.REVOKED, - this_update, next_update, revoked_date, - x509.ReasonFlags.key_compromise + cert, + issuer, + hashes.SHA1(), + ocsp.OCSPCertStatus.REVOKED, + this_update, + next_update, + revoked_date, + x509.ReasonFlags.key_compromise, ) resp = builder.sign(private_key, None) assert resp.certificate_status == ocsp.OCSPCertStatus.REVOKED @@ -969,8 +1146,7 @@ def test_sign_ed448(self, backend): assert resp.this_update == this_update assert resp.next_update == next_update assert resp.signature_hash_algorithm is None - assert (resp.signature_algorithm_oid == - x509.SignatureAlgorithmOID.ED448) + assert resp.signature_algorithm_oid == x509.SignatureAlgorithmOID.ED448 private_key.public_key().verify( resp.signature, resp.tbs_response_bytes ) diff --git a/tests/x509/test_x509.py b/tests/x509/test_x509.py index ced646506e62..63cfb39f033e 100644 --- a/tests/x509/test_x509.py +++ b/tests/x509/test_x509.py @@ -21,23 +21,44 @@ from cryptography import utils, x509 from cryptography.exceptions import UnsupportedAlgorithm from cryptography.hazmat._der import ( - BIT_STRING, CONSTRUCTED, CONTEXT_SPECIFIC, DERReader, GENERALIZED_TIME, - INTEGER, OBJECT_IDENTIFIER, PRINTABLE_STRING, SEQUENCE, SET, UTC_TIME + BIT_STRING, + CONSTRUCTED, + CONTEXT_SPECIFIC, + DERReader, + GENERALIZED_TIME, + INTEGER, + OBJECT_IDENTIFIER, + PRINTABLE_STRING, + SEQUENCE, + SET, + UTC_TIME, ) from cryptography.hazmat.backends.interfaces import ( - DSABackend, EllipticCurveBackend, RSABackend, X509Backend + DSABackend, + EllipticCurveBackend, + RSABackend, + X509Backend, ) from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import ( - dsa, ec, ed25519, ed448, padding, rsa + dsa, + ec, + ed25519, + ed448, + padding, + rsa, ) from cryptography.hazmat.primitives.asymmetric.utils import ( - decode_dss_signature + decode_dss_signature, ) from cryptography.x509.name import _ASN1Type from cryptography.x509.oid import ( - AuthorityInformationAccessOID, ExtendedKeyUsageOID, ExtensionOID, - NameOID, SignatureAlgorithmOID, SubjectInformationAccessOID, + AuthorityInformationAccessOID, + ExtendedKeyUsageOID, + ExtensionOID, + NameOID, + SignatureAlgorithmOID, + SubjectInformationAccessOID, ) from ..hazmat.primitives.fixtures_dsa import DSA_KEY_2048 @@ -64,14 +85,14 @@ def _load_cert(filename, loader, backend): cert = load_vectors_from_file( filename=filename, loader=lambda pemfile: loader(pemfile.read(), backend), - mode="rb" + mode="rb", ) return cert ParsedCertificate = collections.namedtuple( "ParsedCertificate", - ["not_before_tag", "not_after_tag", "issuer", "subject"] + ["not_before_tag", "not_after_tag", "issuer", "subject"], ) @@ -121,7 +142,7 @@ def test_load_pem_crl(self, backend): crl = _load_cert( os.path.join("x509", "custom", "crl_all_reasons.pem"), x509.load_pem_x509_crl, - backend + backend, ) assert isinstance(crl, x509.CertificateRevocationList) @@ -129,15 +150,15 @@ def test_load_pem_crl(self, backend): assert fingerprint == b"3234b0cb4c0cedf6423724b736729dcfc9e441ef" assert isinstance(crl.signature_hash_algorithm, hashes.SHA256) assert ( - crl.signature_algorithm_oid == - SignatureAlgorithmOID.RSA_WITH_SHA256 + crl.signature_algorithm_oid + == SignatureAlgorithmOID.RSA_WITH_SHA256 ) def test_load_der_crl(self, backend): crl = _load_cert( os.path.join("x509", "PKITS_data", "crls", "GoodCACRL.crl"), x509.load_der_x509_crl, - backend + backend, ) assert isinstance(crl, x509.CertificateRevocationList) @@ -159,7 +180,7 @@ def test_unknown_signature_algorithm(self, backend): "x509", "custom", "crl_md2_unknown_crit_entry_ext.pem" ), x509.load_pem_x509_crl, - backend + backend, ) with pytest.raises(UnsupportedAlgorithm): @@ -169,38 +190,38 @@ def test_issuer(self, backend): crl = _load_cert( os.path.join("x509", "PKITS_data", "crls", "GoodCACRL.crl"), x509.load_der_x509_crl, - backend + backend, ) assert isinstance(crl.issuer, x509.Name) assert list(crl.issuer) == [ - x509.NameAttribute(x509.OID_COUNTRY_NAME, u'US'), + x509.NameAttribute(x509.OID_COUNTRY_NAME, u"US"), x509.NameAttribute( - x509.OID_ORGANIZATION_NAME, u'Test Certificates 2011' + x509.OID_ORGANIZATION_NAME, u"Test Certificates 2011" ), - x509.NameAttribute(x509.OID_COMMON_NAME, u'Good CA') + x509.NameAttribute(x509.OID_COMMON_NAME, u"Good CA"), ] assert crl.issuer.get_attributes_for_oid(x509.OID_COMMON_NAME) == [ - x509.NameAttribute(x509.OID_COMMON_NAME, u'Good CA') + x509.NameAttribute(x509.OID_COMMON_NAME, u"Good CA") ] def test_equality(self, backend): crl1 = _load_cert( os.path.join("x509", "PKITS_data", "crls", "GoodCACRL.crl"), x509.load_der_x509_crl, - backend + backend, ) crl2 = _load_cert( os.path.join("x509", "PKITS_data", "crls", "GoodCACRL.crl"), x509.load_der_x509_crl, - backend + backend, ) crl3 = _load_cert( os.path.join("x509", "custom", "crl_all_reasons.pem"), x509.load_pem_x509_crl, - backend + backend, ) assert crl1 == crl2 @@ -211,7 +232,7 @@ def test_update_dates(self, backend): crl = _load_cert( os.path.join("x509", "custom", "crl_all_reasons.pem"), x509.load_pem_x509_crl, - backend + backend, ) assert isinstance(crl.next_update, datetime.datetime) @@ -224,7 +245,7 @@ def test_revoked_cert_retrieval(self, backend): crl = _load_cert( os.path.join("x509", "custom", "crl_all_reasons.pem"), x509.load_pem_x509_crl, - backend + backend, ) for r in crl: @@ -236,9 +257,10 @@ def test_revoked_cert_retrieval(self, backend): def test_get_revoked_certificate_by_serial_number(self, backend): crl = _load_cert( os.path.join( - "x509", "PKITS_data", "crls", "LongSerialNumberCACRL.crl"), + "x509", "PKITS_data", "crls", "LongSerialNumberCACRL.crl" + ), x509.load_der_x509_crl, - backend + backend, ) serial_number = 725064303890588110203033396814564464046290047507 revoked = crl.get_revoked_certificate_by_serial_number(serial_number) @@ -254,7 +276,7 @@ def test_revoked_cert_retrieval_retain_only_revoked(self, backend): revoked = _load_cert( os.path.join("x509", "custom", "crl_all_reasons.pem"), x509.load_pem_x509_crl, - backend + backend, )[11] assert revoked.revocation_date == datetime.datetime(2015, 1, 1, 0, 0) assert revoked.serial_number == 11 @@ -263,7 +285,7 @@ def test_extensions(self, backend): crl = _load_cert( os.path.join("x509", "custom", "crl_ian_aia_aki.pem"), x509.load_pem_x509_crl, - backend + backend, ) crl_number = crl.extensions.get_extension_for_oid( @@ -281,27 +303,27 @@ def test_extensions(self, backend): assert crl_number.value == x509.CRLNumber(1) assert crl_number.critical is False assert aki.value == x509.AuthorityKeyIdentifier( - key_identifier=( - b'yu\xbb\x84:\xcb,\xdez\t\xbe1\x1bC\xbc\x1c*MSX' - ), + key_identifier=(b"yu\xbb\x84:\xcb,\xdez\t\xbe1\x1bC\xbc\x1c*MSX"), authority_cert_issuer=None, - authority_cert_serial_number=None + authority_cert_serial_number=None, + ) + assert aia.value == x509.AuthorityInformationAccess( + [ + x509.AccessDescription( + AuthorityInformationAccessOID.CA_ISSUERS, + x509.DNSName(u"cryptography.io"), + ) + ] + ) + assert ian.value == x509.IssuerAlternativeName( + [x509.UniformResourceIdentifier(u"https://cryptography.io")] ) - assert aia.value == x509.AuthorityInformationAccess([ - x509.AccessDescription( - AuthorityInformationAccessOID.CA_ISSUERS, - x509.DNSName(u"cryptography.io") - ) - ]) - assert ian.value == x509.IssuerAlternativeName([ - x509.UniformResourceIdentifier(u"https://cryptography.io"), - ]) def test_delta_crl_indicator(self, backend): crl = _load_cert( os.path.join("x509", "custom", "crl_delta_crl_indicator.pem"), x509.load_pem_x509_crl, - backend + backend, ) dci = crl.extensions.get_extension_for_oid( @@ -314,7 +336,7 @@ def test_signature(self, backend): crl = _load_cert( os.path.join("x509", "custom", "crl_all_reasons.pem"), x509.load_pem_x509_crl, - backend + backend, ) assert crl.signature == binascii.unhexlify( @@ -333,31 +355,33 @@ def test_tbs_certlist_bytes(self, backend): crl = _load_cert( os.path.join("x509", "PKITS_data", "crls", "GoodCACRL.crl"), x509.load_der_x509_crl, - backend + backend, ) ca_cert = _load_cert( os.path.join("x509", "PKITS_data", "certs", "GoodCACert.crt"), x509.load_der_x509_certificate, - backend + backend, ) ca_cert.public_key().verify( - crl.signature, crl.tbs_certlist_bytes, - padding.PKCS1v15(), crl.signature_hash_algorithm + crl.signature, + crl.tbs_certlist_bytes, + padding.PKCS1v15(), + crl.signature_hash_algorithm, ) def test_public_bytes_pem(self, backend): crl = _load_cert( os.path.join("x509", "custom", "crl_empty.pem"), x509.load_pem_x509_crl, - backend + backend, ) # Encode it to PEM and load it back. - crl = x509.load_pem_x509_crl(crl.public_bytes( - encoding=serialization.Encoding.PEM, - ), backend) + crl = x509.load_pem_x509_crl( + crl.public_bytes(encoding=serialization.Encoding.PEM,), backend + ) assert len(crl) == 0 assert crl.last_update == datetime.datetime(2015, 12, 20, 23, 44, 47) @@ -367,13 +391,13 @@ def test_public_bytes_der(self, backend): crl = _load_cert( os.path.join("x509", "custom", "crl_all_reasons.pem"), x509.load_pem_x509_crl, - backend + backend, ) # Encode it to DER and load it back. - crl = x509.load_der_x509_crl(crl.public_bytes( - encoding=serialization.Encoding.DER, - ), backend) + crl = x509.load_der_x509_crl( + crl.public_bytes(encoding=serialization.Encoding.DER,), backend + ) assert len(crl) == 12 assert crl.last_update == datetime.datetime(2015, 1, 1, 0, 0, 0) @@ -392,10 +416,11 @@ def test_public_bytes_der(self, backend): x509.load_der_x509_crl, serialization.Encoding.DER, ), - ] + ], ) - def test_public_bytes_match(self, cert_path, loader_func, encoding, - backend): + def test_public_bytes_match( + self, cert_path, loader_func, encoding, backend + ): crl_bytes = load_vectors_from_file( cert_path, lambda pemfile: pemfile.read(), mode="rb" ) @@ -407,22 +432,22 @@ def test_public_bytes_invalid_encoding(self, backend): crl = _load_cert( os.path.join("x509", "custom", "crl_empty.pem"), x509.load_pem_x509_crl, - backend + backend, ) with pytest.raises(TypeError): - crl.public_bytes('NotAnEncoding') + crl.public_bytes("NotAnEncoding") def test_verify_bad(self, backend): crl = _load_cert( os.path.join("x509", "custom", "invalid_signature.pem"), x509.load_pem_x509_crl, - backend + backend, ) crt = _load_cert( os.path.join("x509", "custom", "invalid_signature.pem"), x509.load_pem_x509_certificate, - backend + backend, ) assert not crl.is_signature_valid(crt.public_key()) @@ -431,12 +456,12 @@ def test_verify_good(self, backend): crl = _load_cert( os.path.join("x509", "custom", "valid_signature.pem"), x509.load_pem_x509_crl, - backend + backend, ) crt = _load_cert( os.path.join("x509", "custom", "valid_signature.pem"), x509.load_pem_x509_certificate, - backend + backend, ) assert crl.is_signature_valid(crt.public_key()) @@ -445,7 +470,7 @@ def test_verify_argument_must_be_a_public_key(self, backend): crl = _load_cert( os.path.join("x509", "custom", "valid_signature.pem"), x509.load_pem_x509_crl, - backend + backend, ) with pytest.raises(TypeError): @@ -461,7 +486,7 @@ def test_revoked_basics(self, backend): crl = _load_cert( os.path.join("x509", "custom", "crl_all_reasons.pem"), x509.load_pem_x509_crl, - backend + backend, ) for i, rev in enumerate(crl): @@ -477,14 +502,20 @@ def test_revoked_extensions(self, backend): crl = _load_cert( os.path.join("x509", "custom", "crl_all_reasons.pem"), x509.load_pem_x509_crl, - backend + backend, ) exp_issuer = [ - x509.DirectoryName(x509.Name([ - x509.NameAttribute(x509.OID_COUNTRY_NAME, u"US"), - x509.NameAttribute(x509.OID_COMMON_NAME, u"cryptography.io"), - ])) + x509.DirectoryName( + x509.Name( + [ + x509.NameAttribute(x509.OID_COUNTRY_NAME, u"US"), + x509.NameAttribute( + x509.OID_COMMON_NAME, u"cryptography.io" + ), + ] + ) + ) ] # First revoked cert doesn't have extensions, test if it is handled @@ -504,16 +535,17 @@ def test_revoked_extensions(self, backend): rev1 = crl[1] assert isinstance(rev1.extensions, x509.Extensions) - reason = rev1.extensions.get_extension_for_class( - x509.CRLReason).value + reason = rev1.extensions.get_extension_for_class(x509.CRLReason).value assert reason == x509.CRLReason(x509.ReasonFlags.unspecified) issuer = rev1.extensions.get_extension_for_class( - x509.CertificateIssuer).value + x509.CertificateIssuer + ).value assert issuer == x509.CertificateIssuer(exp_issuer) date = rev1.extensions.get_extension_for_class( - x509.InvalidityDate).value + x509.InvalidityDate + ).value assert date == x509.InvalidityDate(datetime.datetime(2015, 1, 1, 0, 0)) # Check if all reason flags can be found in the CRL. @@ -533,7 +565,7 @@ def test_no_revoked_certs(self, backend): crl = _load_cert( os.path.join("x509", "custom", "crl_empty.pem"), x509.load_pem_x509_crl, - backend + backend, ) assert len(crl) == 0 @@ -541,7 +573,7 @@ def test_duplicate_entry_ext(self, backend): crl = _load_cert( os.path.join("x509", "custom", "crl_dup_entry_ext.pem"), x509.load_pem_x509_crl, - backend + backend, ) with pytest.raises(x509.DuplicateExtension): @@ -553,7 +585,7 @@ def test_unsupported_crit_entry_ext(self, backend): "x509", "custom", "crl_md2_unknown_crit_entry_ext.pem" ), x509.load_pem_x509_crl, - backend + backend, ) ext = crl[0].extensions.get_extension_for_oid( @@ -563,11 +595,9 @@ def test_unsupported_crit_entry_ext(self, backend): def test_unsupported_reason(self, backend): crl = _load_cert( - os.path.join( - "x509", "custom", "crl_unsupported_reason.pem" - ), + os.path.join("x509", "custom", "crl_unsupported_reason.pem"), x509.load_pem_x509_crl, - backend + backend, ) with pytest.raises(ValueError): @@ -579,7 +609,7 @@ def test_invalid_cert_issuer_ext(self, backend): "x509", "custom", "crl_inval_cert_issuer_entry_ext.pem" ), x509.load_pem_x509_crl, - backend + backend, ) with pytest.raises(ValueError): @@ -589,7 +619,7 @@ def test_indexing(self, backend): crl = _load_cert( os.path.join("x509", "custom", "crl_all_reasons.pem"), x509.load_pem_x509_crl, - backend + backend, ) with pytest.raises(IndexError): @@ -606,21 +636,27 @@ def test_get_revoked_certificate_doesnt_reorder(self, backend): private_key = RSA_KEY_2048.private_key(backend) last_update = datetime.datetime(2002, 1, 1, 12, 1) next_update = datetime.datetime(2030, 1, 1, 12, 1) - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([ - x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io CA") - ]) - ).last_update( - last_update - ).next_update( - next_update + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name( + [ + x509.NameAttribute( + NameOID.COMMON_NAME, u"cryptography.io CA" + ) + ] + ) + ) + .last_update(last_update) + .next_update(next_update) ) for i in [2, 500, 3, 49, 7, 1]: - revoked_cert = x509.RevokedCertificateBuilder().serial_number( - i - ).revocation_date( - datetime.datetime(2012, 1, 1, 1, 1) - ).build(backend) + revoked_cert = ( + x509.RevokedCertificateBuilder() + .serial_number(i) + .revocation_date(datetime.datetime(2012, 1, 1, 1, 1)) + .build(backend) + ) builder = builder.add_revoked_certificate(revoked_cert) crl = builder.sign(private_key, hashes.SHA256(), backend) assert crl[0].serial_number == 2 @@ -639,7 +675,7 @@ def test_load_pem_cert(self, backend): cert = _load_cert( os.path.join("x509", "custom", "post2000utctime.pem"), x509.load_pem_x509_certificate, - backend + backend, ) assert isinstance(cert, x509.Certificate) assert cert.serial_number == 11559813051657483483 @@ -662,19 +698,19 @@ def test_alternate_rsa_with_sha1_oid(self, backend): cert = _load_cert( os.path.join("x509", "alternate-rsa-sha1-oid.pem"), x509.load_pem_x509_certificate, - backend + backend, ) assert isinstance(cert.signature_hash_algorithm, hashes.SHA1) assert ( - cert.signature_algorithm_oid == - SignatureAlgorithmOID._RSA_WITH_SHA1 + cert.signature_algorithm_oid + == SignatureAlgorithmOID._RSA_WITH_SHA1 ) def test_load_der_cert(self, backend): cert = _load_cert( os.path.join("x509", "PKITS_data", "certs", "GoodCACert.crt"), x509.load_der_x509_certificate, - backend + backend, ) assert isinstance(cert, x509.Certificate) assert cert.serial_number == 2 @@ -686,7 +722,7 @@ def test_signature(self, backend): cert = _load_cert( os.path.join("x509", "custom", "post2000utctime.pem"), x509.load_pem_x509_certificate, - backend + backend, ) assert cert.signature == binascii.unhexlify( b"8e0f72fcbebe4755abcaf76c8ce0bae17cde4db16291638e1b1ce04a93cdb4c" @@ -705,7 +741,7 @@ def test_tbs_certificate_bytes(self, backend): cert = _load_cert( os.path.join("x509", "custom", "post2000utctime.pem"), x509.load_pem_x509_certificate, - backend + backend, ) assert cert.tbs_certificate_bytes == binascii.unhexlify( b"308202d8a003020102020900a06cb4b955f7f4db300d06092a864886f70d010" @@ -734,132 +770,126 @@ def test_tbs_certificate_bytes(self, backend): b"3040530030101ff" ) cert.public_key().verify( - cert.signature, cert.tbs_certificate_bytes, - padding.PKCS1v15(), cert.signature_hash_algorithm + cert.signature, + cert.tbs_certificate_bytes, + padding.PKCS1v15(), + cert.signature_hash_algorithm, ) def test_issuer(self, backend): cert = _load_cert( os.path.join( - "x509", "PKITS_data", "certs", - "Validpre2000UTCnotBeforeDateTest3EE.crt" + "x509", + "PKITS_data", + "certs", + "Validpre2000UTCnotBeforeDateTest3EE.crt", ), x509.load_der_x509_certificate, - backend + backend, ) issuer = cert.issuer assert isinstance(issuer, x509.Name) assert list(issuer) == [ - x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'), + x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"), x509.NameAttribute( - NameOID.ORGANIZATION_NAME, u'Test Certificates 2011' + NameOID.ORGANIZATION_NAME, u"Test Certificates 2011" ), - x509.NameAttribute(NameOID.COMMON_NAME, u'Good CA') + x509.NameAttribute(NameOID.COMMON_NAME, u"Good CA"), ] assert issuer.get_attributes_for_oid(NameOID.COMMON_NAME) == [ - x509.NameAttribute(NameOID.COMMON_NAME, u'Good CA') + x509.NameAttribute(NameOID.COMMON_NAME, u"Good CA") ] def test_all_issuer_name_types(self, backend): cert = _load_cert( - os.path.join( - "x509", "custom", - "all_supported_names.pem" - ), + os.path.join("x509", "custom", "all_supported_names.pem"), x509.load_pem_x509_certificate, - backend + backend, ) issuer = cert.issuer assert isinstance(issuer, x509.Name) assert list(issuer) == [ - x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'), - x509.NameAttribute(NameOID.COUNTRY_NAME, u'CA'), - x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'Texas'), - x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'Illinois'), - x509.NameAttribute(NameOID.LOCALITY_NAME, u'Chicago'), - x509.NameAttribute(NameOID.LOCALITY_NAME, u'Austin'), - x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'Zero, LLC'), - x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'One, LLC'), - x509.NameAttribute(NameOID.COMMON_NAME, u'common name 0'), - x509.NameAttribute(NameOID.COMMON_NAME, u'common name 1'), - x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u'OU 0'), - x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u'OU 1'), - x509.NameAttribute(NameOID.DN_QUALIFIER, u'dnQualifier0'), - x509.NameAttribute(NameOID.DN_QUALIFIER, u'dnQualifier1'), - x509.NameAttribute(NameOID.SERIAL_NUMBER, u'123'), - x509.NameAttribute(NameOID.SERIAL_NUMBER, u'456'), - x509.NameAttribute(NameOID.TITLE, u'Title 0'), - x509.NameAttribute(NameOID.TITLE, u'Title 1'), - x509.NameAttribute(NameOID.SURNAME, u'Surname 0'), - x509.NameAttribute(NameOID.SURNAME, u'Surname 1'), - x509.NameAttribute(NameOID.GIVEN_NAME, u'Given Name 0'), - x509.NameAttribute(NameOID.GIVEN_NAME, u'Given Name 1'), - x509.NameAttribute(NameOID.PSEUDONYM, u'Incognito 0'), - x509.NameAttribute(NameOID.PSEUDONYM, u'Incognito 1'), - x509.NameAttribute(NameOID.GENERATION_QUALIFIER, u'Last Gen'), - x509.NameAttribute(NameOID.GENERATION_QUALIFIER, u'Next Gen'), - x509.NameAttribute(NameOID.DOMAIN_COMPONENT, u'dc0'), - x509.NameAttribute(NameOID.DOMAIN_COMPONENT, u'dc1'), - x509.NameAttribute(NameOID.EMAIL_ADDRESS, u'test0@test.local'), - x509.NameAttribute(NameOID.EMAIL_ADDRESS, u'test1@test.local'), + x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"), + x509.NameAttribute(NameOID.COUNTRY_NAME, u"CA"), + x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"Texas"), + x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"Illinois"), + x509.NameAttribute(NameOID.LOCALITY_NAME, u"Chicago"), + x509.NameAttribute(NameOID.LOCALITY_NAME, u"Austin"), + x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Zero, LLC"), + x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"One, LLC"), + x509.NameAttribute(NameOID.COMMON_NAME, u"common name 0"), + x509.NameAttribute(NameOID.COMMON_NAME, u"common name 1"), + x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u"OU 0"), + x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u"OU 1"), + x509.NameAttribute(NameOID.DN_QUALIFIER, u"dnQualifier0"), + x509.NameAttribute(NameOID.DN_QUALIFIER, u"dnQualifier1"), + x509.NameAttribute(NameOID.SERIAL_NUMBER, u"123"), + x509.NameAttribute(NameOID.SERIAL_NUMBER, u"456"), + x509.NameAttribute(NameOID.TITLE, u"Title 0"), + x509.NameAttribute(NameOID.TITLE, u"Title 1"), + x509.NameAttribute(NameOID.SURNAME, u"Surname 0"), + x509.NameAttribute(NameOID.SURNAME, u"Surname 1"), + x509.NameAttribute(NameOID.GIVEN_NAME, u"Given Name 0"), + x509.NameAttribute(NameOID.GIVEN_NAME, u"Given Name 1"), + x509.NameAttribute(NameOID.PSEUDONYM, u"Incognito 0"), + x509.NameAttribute(NameOID.PSEUDONYM, u"Incognito 1"), + x509.NameAttribute(NameOID.GENERATION_QUALIFIER, u"Last Gen"), + x509.NameAttribute(NameOID.GENERATION_QUALIFIER, u"Next Gen"), + x509.NameAttribute(NameOID.DOMAIN_COMPONENT, u"dc0"), + x509.NameAttribute(NameOID.DOMAIN_COMPONENT, u"dc1"), + x509.NameAttribute(NameOID.EMAIL_ADDRESS, u"test0@test.local"), + x509.NameAttribute(NameOID.EMAIL_ADDRESS, u"test1@test.local"), ] def test_subject(self, backend): cert = _load_cert( os.path.join( - "x509", "PKITS_data", "certs", - "Validpre2000UTCnotBeforeDateTest3EE.crt" + "x509", + "PKITS_data", + "certs", + "Validpre2000UTCnotBeforeDateTest3EE.crt", ), x509.load_der_x509_certificate, - backend + backend, ) subject = cert.subject assert isinstance(subject, x509.Name) assert list(subject) == [ - x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'), + x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"), x509.NameAttribute( - NameOID.ORGANIZATION_NAME, u'Test Certificates 2011' + NameOID.ORGANIZATION_NAME, u"Test Certificates 2011" ), x509.NameAttribute( NameOID.COMMON_NAME, - u'Valid pre2000 UTC notBefore Date EE Certificate Test3' - ) + u"Valid pre2000 UTC notBefore Date EE Certificate Test3", + ), ] assert subject.get_attributes_for_oid(NameOID.COMMON_NAME) == [ x509.NameAttribute( NameOID.COMMON_NAME, - u'Valid pre2000 UTC notBefore Date EE Certificate Test3' + u"Valid pre2000 UTC notBefore Date EE Certificate Test3", ) ] def test_unicode_name(self, backend): cert = _load_cert( - os.path.join( - "x509", "custom", - "utf8_common_name.pem" - ), + os.path.join("x509", "custom", "utf8_common_name.pem"), x509.load_pem_x509_certificate, - backend + backend, ) assert cert.subject.get_attributes_for_oid(NameOID.COMMON_NAME) == [ - x509.NameAttribute( - NameOID.COMMON_NAME, - u'We heart UTF8!\u2122' - ) + x509.NameAttribute(NameOID.COMMON_NAME, u"We heart UTF8!\u2122") ] assert cert.issuer.get_attributes_for_oid(NameOID.COMMON_NAME) == [ - x509.NameAttribute( - NameOID.COMMON_NAME, - u'We heart UTF8!\u2122' - ) + x509.NameAttribute(NameOID.COMMON_NAME, u"We heart UTF8!\u2122") ] def test_non_ascii_dns_name(self, backend): cert = _load_cert( os.path.join("x509", "utf8-dnsname.pem"), x509.load_pem_x509_certificate, - backend + backend, ) san = cert.extensions.get_extension_for_class( x509.SubjectAlternativeName @@ -868,64 +898,65 @@ def test_non_ascii_dns_name(self, backend): names = san.get_values_for_type(x509.DNSName) assert names == [ - u'partner.biztositas.hu', u'biztositas.hu', u'*.biztositas.hu', - u'biztos\xedt\xe1s.hu', u'*.biztos\xedt\xe1s.hu', - u'xn--biztosts-fza2j.hu', u'*.xn--biztosts-fza2j.hu' + u"partner.biztositas.hu", + u"biztositas.hu", + u"*.biztositas.hu", + u"biztos\xedt\xe1s.hu", + u"*.biztos\xedt\xe1s.hu", + u"xn--biztosts-fza2j.hu", + u"*.xn--biztosts-fza2j.hu", ] def test_all_subject_name_types(self, backend): cert = _load_cert( - os.path.join( - "x509", "custom", - "all_supported_names.pem" - ), + os.path.join("x509", "custom", "all_supported_names.pem"), x509.load_pem_x509_certificate, - backend + backend, ) subject = cert.subject assert isinstance(subject, x509.Name) assert list(subject) == [ - x509.NameAttribute(NameOID.COUNTRY_NAME, u'AU'), - x509.NameAttribute(NameOID.COUNTRY_NAME, u'DE'), - x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'California'), - x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'New York'), - x509.NameAttribute(NameOID.LOCALITY_NAME, u'San Francisco'), - x509.NameAttribute(NameOID.LOCALITY_NAME, u'Ithaca'), - x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'Org Zero, LLC'), - x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'Org One, LLC'), - x509.NameAttribute(NameOID.COMMON_NAME, u'CN 0'), - x509.NameAttribute(NameOID.COMMON_NAME, u'CN 1'), + x509.NameAttribute(NameOID.COUNTRY_NAME, u"AU"), + x509.NameAttribute(NameOID.COUNTRY_NAME, u"DE"), + x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"California"), + x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"New York"), + x509.NameAttribute(NameOID.LOCALITY_NAME, u"San Francisco"), + x509.NameAttribute(NameOID.LOCALITY_NAME, u"Ithaca"), + x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Org Zero, LLC"), + x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Org One, LLC"), + x509.NameAttribute(NameOID.COMMON_NAME, u"CN 0"), + x509.NameAttribute(NameOID.COMMON_NAME, u"CN 1"), x509.NameAttribute( - NameOID.ORGANIZATIONAL_UNIT_NAME, u'Engineering 0' + NameOID.ORGANIZATIONAL_UNIT_NAME, u"Engineering 0" ), x509.NameAttribute( - NameOID.ORGANIZATIONAL_UNIT_NAME, u'Engineering 1' + NameOID.ORGANIZATIONAL_UNIT_NAME, u"Engineering 1" ), - x509.NameAttribute(NameOID.DN_QUALIFIER, u'qualified0'), - x509.NameAttribute(NameOID.DN_QUALIFIER, u'qualified1'), - x509.NameAttribute(NameOID.SERIAL_NUMBER, u'789'), - x509.NameAttribute(NameOID.SERIAL_NUMBER, u'012'), - x509.NameAttribute(NameOID.TITLE, u'Title IX'), - x509.NameAttribute(NameOID.TITLE, u'Title X'), - x509.NameAttribute(NameOID.SURNAME, u'Last 0'), - x509.NameAttribute(NameOID.SURNAME, u'Last 1'), - x509.NameAttribute(NameOID.GIVEN_NAME, u'First 0'), - x509.NameAttribute(NameOID.GIVEN_NAME, u'First 1'), - x509.NameAttribute(NameOID.PSEUDONYM, u'Guy Incognito 0'), - x509.NameAttribute(NameOID.PSEUDONYM, u'Guy Incognito 1'), - x509.NameAttribute(NameOID.GENERATION_QUALIFIER, u'32X'), - x509.NameAttribute(NameOID.GENERATION_QUALIFIER, u'Dreamcast'), - x509.NameAttribute(NameOID.DOMAIN_COMPONENT, u'dc2'), - x509.NameAttribute(NameOID.DOMAIN_COMPONENT, u'dc3'), - x509.NameAttribute(NameOID.EMAIL_ADDRESS, u'test2@test.local'), - x509.NameAttribute(NameOID.EMAIL_ADDRESS, u'test3@test.local'), + x509.NameAttribute(NameOID.DN_QUALIFIER, u"qualified0"), + x509.NameAttribute(NameOID.DN_QUALIFIER, u"qualified1"), + x509.NameAttribute(NameOID.SERIAL_NUMBER, u"789"), + x509.NameAttribute(NameOID.SERIAL_NUMBER, u"012"), + x509.NameAttribute(NameOID.TITLE, u"Title IX"), + x509.NameAttribute(NameOID.TITLE, u"Title X"), + x509.NameAttribute(NameOID.SURNAME, u"Last 0"), + x509.NameAttribute(NameOID.SURNAME, u"Last 1"), + x509.NameAttribute(NameOID.GIVEN_NAME, u"First 0"), + x509.NameAttribute(NameOID.GIVEN_NAME, u"First 1"), + x509.NameAttribute(NameOID.PSEUDONYM, u"Guy Incognito 0"), + x509.NameAttribute(NameOID.PSEUDONYM, u"Guy Incognito 1"), + x509.NameAttribute(NameOID.GENERATION_QUALIFIER, u"32X"), + x509.NameAttribute(NameOID.GENERATION_QUALIFIER, u"Dreamcast"), + x509.NameAttribute(NameOID.DOMAIN_COMPONENT, u"dc2"), + x509.NameAttribute(NameOID.DOMAIN_COMPONENT, u"dc3"), + x509.NameAttribute(NameOID.EMAIL_ADDRESS, u"test2@test.local"), + x509.NameAttribute(NameOID.EMAIL_ADDRESS, u"test3@test.local"), ] def test_load_good_ca_cert(self, backend): cert = _load_cert( os.path.join("x509", "PKITS_data", "certs", "GoodCACert.crt"), x509.load_der_x509_certificate, - backend + backend, ) assert cert.not_valid_before == datetime.datetime(2010, 1, 1, 8, 30) @@ -940,11 +971,13 @@ def test_load_good_ca_cert(self, backend): def test_utc_pre_2000_not_before_cert(self, backend): cert = _load_cert( os.path.join( - "x509", "PKITS_data", "certs", - "Validpre2000UTCnotBeforeDateTest3EE.crt" + "x509", + "PKITS_data", + "certs", + "Validpre2000UTCnotBeforeDateTest3EE.crt", ), x509.load_der_x509_certificate, - backend + backend, ) assert cert.not_valid_before == datetime.datetime(1950, 1, 1, 12, 1) @@ -952,11 +985,13 @@ def test_utc_pre_2000_not_before_cert(self, backend): def test_pre_2000_utc_not_after_cert(self, backend): cert = _load_cert( os.path.join( - "x509", "PKITS_data", "certs", - "Invalidpre2000UTCEEnotAfterDateTest7EE.crt" + "x509", + "PKITS_data", + "certs", + "Invalidpre2000UTCEEnotAfterDateTest7EE.crt", ), x509.load_der_x509_certificate, - backend + backend, ) assert cert.not_valid_after == datetime.datetime(1999, 1, 1, 12, 1) @@ -965,7 +1000,7 @@ def test_post_2000_utc_cert(self, backend): cert = _load_cert( os.path.join("x509", "custom", "post2000utctime.pem"), x509.load_pem_x509_certificate, - backend + backend, ) assert cert.not_valid_before == datetime.datetime( 2014, 11, 26, 21, 41, 20 @@ -977,11 +1012,13 @@ def test_post_2000_utc_cert(self, backend): def test_generalized_time_not_before_cert(self, backend): cert = _load_cert( os.path.join( - "x509", "PKITS_data", "certs", - "ValidGeneralizedTimenotBeforeDateTest4EE.crt" + "x509", + "PKITS_data", + "certs", + "ValidGeneralizedTimenotBeforeDateTest4EE.crt", ), x509.load_der_x509_certificate, - backend + backend, ) assert cert.not_valid_before == datetime.datetime(2002, 1, 1, 12, 1) assert cert.not_valid_after == datetime.datetime(2030, 12, 31, 8, 30) @@ -990,11 +1027,13 @@ def test_generalized_time_not_before_cert(self, backend): def test_generalized_time_not_after_cert(self, backend): cert = _load_cert( os.path.join( - "x509", "PKITS_data", "certs", - "ValidGeneralizedTimenotAfterDateTest8EE.crt" + "x509", + "PKITS_data", + "certs", + "ValidGeneralizedTimenotAfterDateTest8EE.crt", ), x509.load_der_x509_certificate, - backend + backend, ) assert cert.not_valid_before == datetime.datetime(2010, 1, 1, 8, 30) assert cert.not_valid_after == datetime.datetime(2050, 1, 1, 12, 1) @@ -1005,7 +1044,7 @@ def test_invalid_version_cert(self, backend): _load_cert( os.path.join("x509", "custom", "invalid_version.pem"), x509.load_pem_x509_certificate, - backend + backend, ) assert exc.value.parsed_version == 7 @@ -1014,12 +1053,12 @@ def test_eq(self, backend): cert = _load_cert( os.path.join("x509", "custom", "post2000utctime.pem"), x509.load_pem_x509_certificate, - backend + backend, ) cert2 = _load_cert( os.path.join("x509", "custom", "post2000utctime.pem"), x509.load_pem_x509_certificate, - backend + backend, ) assert cert == cert2 @@ -1027,15 +1066,17 @@ def test_ne(self, backend): cert = _load_cert( os.path.join("x509", "custom", "post2000utctime.pem"), x509.load_pem_x509_certificate, - backend + backend, ) cert2 = _load_cert( os.path.join( - "x509", "PKITS_data", "certs", - "ValidGeneralizedTimenotAfterDateTest8EE.crt" + "x509", + "PKITS_data", + "certs", + "ValidGeneralizedTimenotAfterDateTest8EE.crt", ), x509.load_der_x509_certificate, - backend + backend, ) assert cert != cert2 assert cert != object() @@ -1044,20 +1085,22 @@ def test_hash(self, backend): cert1 = _load_cert( os.path.join("x509", "custom", "post2000utctime.pem"), x509.load_pem_x509_certificate, - backend + backend, ) cert2 = _load_cert( os.path.join("x509", "custom", "post2000utctime.pem"), x509.load_pem_x509_certificate, - backend + backend, ) cert3 = _load_cert( os.path.join( - "x509", "PKITS_data", "certs", - "ValidGeneralizedTimenotAfterDateTest8EE.crt" + "x509", + "PKITS_data", + "certs", + "ValidGeneralizedTimenotAfterDateTest8EE.crt", ), x509.load_der_x509_certificate, - backend + backend, ) assert hash(cert1) == hash(cert2) @@ -1067,7 +1110,7 @@ def test_version_1_cert(self, backend): cert = _load_cert( os.path.join("x509", "v1_cert.pem"), x509.load_pem_x509_certificate, - backend + backend, ) assert cert.version is x509.Version.v1 @@ -1083,7 +1126,7 @@ def test_unsupported_signature_hash_algorithm_cert(self, backend): cert = _load_cert( os.path.join("x509", "verisign_md2_root.pem"), x509.load_pem_x509_certificate, - backend + backend, ) with pytest.raises(UnsupportedAlgorithm): cert.signature_hash_algorithm @@ -1093,13 +1136,13 @@ def test_public_bytes_pem(self, backend): cert = _load_cert( os.path.join("x509", "PKITS_data", "certs", "GoodCACert.crt"), x509.load_der_x509_certificate, - backend + backend, ) # Encode it to PEM and load it back. - cert = x509.load_pem_x509_certificate(cert.public_bytes( - encoding=serialization.Encoding.PEM, - ), backend) + cert = x509.load_pem_x509_certificate( + cert.public_bytes(encoding=serialization.Encoding.PEM,), backend + ) # We should recover what we had to start with. assert cert.not_valid_before == datetime.datetime(2010, 1, 1, 8, 30) @@ -1116,13 +1159,13 @@ def test_public_bytes_der(self, backend): cert = _load_cert( os.path.join("x509", "PKITS_data", "certs", "GoodCACert.crt"), x509.load_der_x509_certificate, - backend + backend, ) # Encode it to DER and load it back. - cert = x509.load_der_x509_certificate(cert.public_bytes( - encoding=serialization.Encoding.DER, - ), backend) + cert = x509.load_der_x509_certificate( + cert.public_bytes(encoding=serialization.Encoding.DER,), backend + ) # We should recover what we had to start with. assert cert.not_valid_before == datetime.datetime(2010, 1, 1, 8, 30) @@ -1138,11 +1181,11 @@ def test_public_bytes_invalid_encoding(self, backend): cert = _load_cert( os.path.join("x509", "PKITS_data", "certs", "GoodCACert.crt"), x509.load_der_x509_certificate, - backend + backend, ) with pytest.raises(TypeError): - cert.public_bytes('NotAnEncoding') + cert.public_bytes("NotAnEncoding") @pytest.mark.parametrize( ("cert_path", "loader_func", "encoding"), @@ -1157,10 +1200,11 @@ def test_public_bytes_invalid_encoding(self, backend): x509.load_der_x509_certificate, serialization.Encoding.DER, ), - ] + ], ) - def test_public_bytes_match(self, cert_path, loader_func, encoding, - backend): + def test_public_bytes_match( + self, cert_path, loader_func, encoding, backend + ): cert_bytes = load_vectors_from_file( cert_path, lambda pemfile: pemfile.read(), mode="rb" ) @@ -1170,11 +1214,9 @@ def test_public_bytes_match(self, cert_path, loader_func, encoding, def test_certificate_repr(self, backend): cert = _load_cert( - os.path.join( - "x509", "cryptography.io.pem" - ), + os.path.join("x509", "cryptography.io.pem"), x509.load_pem_x509_certificate, - backend + backend, ) assert repr(cert) == ( " 2 bytes with pytest.raises(ValueError): - x509.NameAttribute( - NameOID.COUNTRY_NAME, - u'\U0001F37A\U0001F37A' - ) + x509.NameAttribute(NameOID.COUNTRY_NAME, u"\U0001F37A\U0001F37A") def test_invalid_type(self): with pytest.raises(TypeError): @@ -4481,28 +4766,23 @@ def test_invalid_type(self): def test_eq(self): assert x509.NameAttribute( - x509.ObjectIdentifier('2.999.1'), u'value' - ) == x509.NameAttribute( - x509.ObjectIdentifier('2.999.1'), u'value' - ) + x509.ObjectIdentifier("2.999.1"), u"value" + ) == x509.NameAttribute(x509.ObjectIdentifier("2.999.1"), u"value") def test_ne(self): assert x509.NameAttribute( - x509.ObjectIdentifier('2.5.4.3'), u'value' - ) != x509.NameAttribute( - x509.ObjectIdentifier('2.5.4.5'), u'value' - ) + x509.ObjectIdentifier("2.5.4.3"), u"value" + ) != x509.NameAttribute(x509.ObjectIdentifier("2.5.4.5"), u"value") assert x509.NameAttribute( - x509.ObjectIdentifier('2.999.1'), u'value' - ) != x509.NameAttribute( - x509.ObjectIdentifier('2.999.1'), u'value2' + x509.ObjectIdentifier("2.999.1"), u"value" + ) != x509.NameAttribute(x509.ObjectIdentifier("2.999.1"), u"value2") + assert ( + x509.NameAttribute(x509.ObjectIdentifier("2.999.2"), u"value") + != object() ) - assert x509.NameAttribute( - x509.ObjectIdentifier('2.999.2'), u'value' - ) != object() def test_repr(self): - na = x509.NameAttribute(x509.ObjectIdentifier('2.5.4.3'), u'value') + na = x509.NameAttribute(x509.ObjectIdentifier("2.5.4.3"), u"value") if not six.PY2: assert repr(na) == ( "", ), ( - u'Certificación', - u'Certificación', + u"Certificación", + u"Certificación", "", ), - ]) + ], + ) def test_repr(self, common_name, org_name, expected_repr): - name = x509.Name([ - x509.NameAttribute(NameOID.COMMON_NAME, common_name), - x509.NameAttribute(NameOID.ORGANIZATION_NAME, org_name), - ]) + name = x509.Name( + [ + x509.NameAttribute(NameOID.COMMON_NAME, common_name), + x509.NameAttribute(NameOID.ORGANIZATION_NAME, org_name), + ] + ) assert repr(name) == expected_repr def test_rfc4514_string(self): - n = x509.Name([ - x509.RelativeDistinguishedName([ - x509.NameAttribute(NameOID.DOMAIN_COMPONENT, u'net'), - ]), - x509.RelativeDistinguishedName([ - x509.NameAttribute(NameOID.DOMAIN_COMPONENT, u'example'), - ]), - x509.RelativeDistinguishedName([ - x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u'Sales'), - x509.NameAttribute(NameOID.COMMON_NAME, u'J. Smith'), - ]), - ]) - assert (n.rfc4514_string() == - 'OU=Sales+CN=J. Smith,DC=example,DC=net') + n = x509.Name( + [ + x509.RelativeDistinguishedName( + [x509.NameAttribute(NameOID.DOMAIN_COMPONENT, u"net")] + ), + x509.RelativeDistinguishedName( + [x509.NameAttribute(NameOID.DOMAIN_COMPONENT, u"example")] + ), + x509.RelativeDistinguishedName( + [ + x509.NameAttribute( + NameOID.ORGANIZATIONAL_UNIT_NAME, u"Sales" + ), + x509.NameAttribute(NameOID.COMMON_NAME, u"J. Smith"), + ] + ), + ] + ) + assert n.rfc4514_string() == "OU=Sales+CN=J. Smith,DC=example,DC=net" def test_rfc4514_string_empty_values(self): - n = x509.Name([ - x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'), - x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u''), - x509.NameAttribute(NameOID.LOCALITY_NAME, u''), - x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'PyCA'), - x509.NameAttribute(NameOID.COMMON_NAME, u'cryptography.io'), - ]) - assert (n.rfc4514_string() == 'CN=cryptography.io,O=PyCA,L=,ST=,C=US') + n = x509.Name( + [ + x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"), + x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u""), + x509.NameAttribute(NameOID.LOCALITY_NAME, u""), + x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"PyCA"), + x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io"), + ] + ) + assert n.rfc4514_string() == "CN=cryptography.io,O=PyCA,L=,ST=,C=US" def test_not_nameattribute(self): with pytest.raises(TypeError): @@ -4765,10 +5108,12 @@ def test_not_nameattribute(self): @pytest.mark.requires_backend_interface(interface=X509Backend) def test_bytes(self, backend): - name = x509.Name([ - x509.NameAttribute(NameOID.COMMON_NAME, u'cryptography.io'), - x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'PyCA'), - ]) + name = x509.Name( + [ + x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io"), + x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"PyCA"), + ] + ) assert name.public_bytes(backend) == binascii.unhexlify( b"30293118301606035504030c0f63727970746f6772617068792e696f310d300" b"b060355040a0c0450794341" @@ -4779,14 +5124,16 @@ def test_bmpstring_bytes(self, backend): # For this test we need an odd length string. BMPString is UCS-2 # encoded so it will always be even length and OpenSSL will error if # you pass an odd length string without encoding it properly first. - name = x509.Name([ - x509.NameAttribute( - NameOID.COMMON_NAME, - u'cryptography.io', - _ASN1Type.BMPString - ), - x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'PyCA'), - ]) + name = x509.Name( + [ + x509.NameAttribute( + NameOID.COMMON_NAME, + u"cryptography.io", + _ASN1Type.BMPString, + ), + x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"PyCA"), + ] + ) assert name.public_bytes(backend) == binascii.unhexlify( b"30383127302506035504031e1e00630072007900700074006f00670072006100" b"7000680079002e0069006f310d300b060355040a0c0450794341" @@ -4795,14 +5142,16 @@ def test_bmpstring_bytes(self, backend): @pytest.mark.requires_backend_interface(interface=X509Backend) def test_universalstring_bytes(self, backend): # UniversalString is UCS-4 - name = x509.Name([ - x509.NameAttribute( - NameOID.COMMON_NAME, - u'cryptography.io', - _ASN1Type.UniversalString - ), - x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'PyCA'), - ]) + name = x509.Name( + [ + x509.NameAttribute( + NameOID.COMMON_NAME, + u"cryptography.io", + _ASN1Type.UniversalString, + ), + x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"PyCA"), + ] + ) assert name.public_bytes(backend) == binascii.unhexlify( b"30563145304306035504031c3c00000063000000720000007900000070000000" b"740000006f000000670000007200000061000000700000006800000079000000" @@ -4812,7 +5161,7 @@ def test_universalstring_bytes(self, backend): @pytest.mark.supported( only_if=lambda backend: backend.ed25519_supported(), - skip_message="Requires OpenSSL with Ed25519 support" + skip_message="Requires OpenSSL with Ed25519 support", ) @pytest.mark.requires_backend_interface(interface=X509Backend) class TestEd25519Certificate(object): @@ -4820,7 +5169,7 @@ def test_load_pem_cert(self, backend): cert = _load_cert( os.path.join("x509", "ed25519", "root-ed25519.pem"), x509.load_pem_x509_certificate, - backend + backend, ) # self-signed, so this will work cert.public_key().verify(cert.signature, cert.tbs_certificate_bytes) @@ -4833,14 +5182,14 @@ def test_deepcopy(self, backend): cert = _load_cert( os.path.join("x509", "ed25519", "root-ed25519.pem"), x509.load_pem_x509_certificate, - backend + backend, ) assert copy.deepcopy(cert) is cert @pytest.mark.supported( only_if=lambda backend: backend.ed448_supported(), - skip_message="Requires OpenSSL with Ed448 support" + skip_message="Requires OpenSSL with Ed448 support", ) @pytest.mark.requires_backend_interface(interface=X509Backend) class TestEd448Certificate(object): @@ -4848,7 +5197,7 @@ def test_load_pem_cert(self, backend): cert = _load_cert( os.path.join("x509", "ed448", "root-ed448.pem"), x509.load_pem_x509_certificate, - backend + backend, ) # self-signed, so this will work cert.public_key().verify(cert.signature, cert.tbs_certificate_bytes) @@ -4862,11 +5211,12 @@ def test_load_pem_cert(self, backend): class TestSignatureRejection(object): """Test if signing rejects DH keys properly. """ + def load_key(self, backend): data = load_vectors_from_file( os.path.join("asymmetric", "DH", "dhkey.pem"), lambda pemfile: pemfile.read(), - mode="rb" + mode="rb", ) return serialization.load_pem_private_key(data, None, backend) @@ -4875,18 +5225,18 @@ def test_crt_signing_check(self, backend): public_key = RSA_KEY_2048.private_key(backend).public_key() not_valid_before = datetime.datetime(2020, 1, 1, 1, 1) not_valid_after = datetime.datetime(2050, 12, 31, 8, 30) - builder = x509.CertificateBuilder().serial_number( - 777 - ).issuer_name(x509.Name([ - x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'), - ])).subject_name(x509.Name([ - x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'), - ])).public_key( - public_key - ).not_valid_before( - not_valid_before - ).not_valid_after( - not_valid_after + builder = ( + x509.CertificateBuilder() + .serial_number(777) + .issuer_name( + x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u"US")]) + ) + .subject_name( + x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u"US")]) + ) + .public_key(public_key) + .not_valid_before(not_valid_before) + .not_valid_after(not_valid_after) ) with pytest.raises(TypeError): @@ -4895,7 +5245,7 @@ def test_crt_signing_check(self, backend): def test_csr_signing_check(self, backend): private_key = self.load_key(backend) builder = x509.CertificateSigningRequestBuilder().subject_name( - x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u'US')]) + x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u"US")]) ) with pytest.raises(TypeError): @@ -4905,9 +5255,14 @@ def test_crl_signing_check(self, backend): private_key = self.load_key(backend) last_time = datetime.datetime.utcnow().replace(microsecond=0) next_time = last_time - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u"CA")]) - ).last_update(last_time).next_update(next_time) + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u"CA")]) + ) + .last_update(last_time) + .next_update(next_time) + ) with pytest.raises(TypeError): builder.sign(private_key, hashes.SHA256(), backend) @@ -4924,7 +5279,5 @@ def notrandom(size): serial_number = x509.random_serial_number() - assert ( - serial_number == utils.int_from_bytes(sample_data, "big") >> 1 - ) + assert serial_number == utils.int_from_bytes(sample_data, "big") >> 1 assert serial_number.bit_length() < 160 diff --git a/tests/x509/test_x509_crlbuilder.py b/tests/x509/test_x509_crlbuilder.py index 04244c1baa7f..922d24917979 100644 --- a/tests/x509/test_x509_crlbuilder.py +++ b/tests/x509/test_x509_crlbuilder.py @@ -12,12 +12,17 @@ from cryptography import x509 from cryptography.hazmat.backends.interfaces import ( - DSABackend, EllipticCurveBackend, RSABackend, X509Backend + DSABackend, + EllipticCurveBackend, + RSABackend, + X509Backend, ) from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import ec, ed25519, ed448 from cryptography.x509.oid import ( - AuthorityInformationAccessOID, NameOID, SignatureAlgorithmOID + AuthorityInformationAccessOID, + NameOID, + SignatureAlgorithmOID, ) from ..hazmat.primitives.fixtures_dsa import DSA_KEY_2048 @@ -34,11 +39,11 @@ def test_issuer_name_invalid(self): def test_set_issuer_name_twice(self): builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u'US')]) + x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u"US")]) ) with pytest.raises(ValueError): builder.issuer_name( - x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u'US')]) + x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u"US")]) ) @pytest.mark.requires_backend_interface(interface=RSABackend) @@ -50,11 +55,20 @@ def test_aware_last_update(self, backend): utc_last = datetime.datetime(2012, 1, 17, 6, 43) next_time = datetime.datetime(2022, 1, 17, 6, 43) private_key = RSA_KEY_2048.private_key(backend) - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([ - x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io CA") - ]) - ).last_update(last_time).next_update(next_time) + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name( + [ + x509.NameAttribute( + NameOID.COMMON_NAME, u"cryptography.io CA" + ) + ] + ) + ) + .last_update(last_time) + .next_update(next_time) + ) crl = builder.sign(private_key, hashes.SHA256(), backend) assert crl.last_update == utc_last @@ -85,11 +99,20 @@ def test_aware_next_update(self, backend): utc_next = datetime.datetime(2022, 1, 17, 6, 43) last_time = datetime.datetime(2012, 1, 17, 6, 43) private_key = RSA_KEY_2048.private_key(backend) - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([ - x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io CA") - ]) - ).last_update(last_time).next_update(next_time) + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name( + [ + x509.NameAttribute( + NameOID.COMMON_NAME, u"cryptography.io CA" + ) + ] + ) + ) + .last_update(last_time) + .next_update(next_time) + ) crl = builder.sign(private_key, hashes.SHA256(), backend) assert crl.next_update == utc_next @@ -114,18 +137,14 @@ def test_set_next_update_twice(self): def test_last_update_after_next_update(self): builder = x509.CertificateRevocationListBuilder() - builder = builder.next_update( - datetime.datetime(2002, 1, 1, 12, 1) - ) + builder = builder.next_update(datetime.datetime(2002, 1, 1, 12, 1)) with pytest.raises(ValueError): builder.last_update(datetime.datetime(2003, 1, 1, 12, 1)) def test_next_update_after_last_update(self): builder = x509.CertificateRevocationListBuilder() - builder = builder.last_update( - datetime.datetime(2002, 1, 1, 12, 1) - ) + builder = builder.last_update(datetime.datetime(2002, 1, 1, 12, 1)) with pytest.raises(ValueError): builder.next_update(datetime.datetime(2001, 1, 1, 12, 1)) @@ -141,9 +160,7 @@ def test_add_invalid_extension(self): builder = x509.CertificateRevocationListBuilder() with pytest.raises(TypeError): - builder.add_extension( - object(), False - ) + builder.add_extension(object(), False) def test_add_invalid_revoked_certificate(self): builder = x509.CertificateRevocationListBuilder() @@ -155,10 +172,10 @@ def test_add_invalid_revoked_certificate(self): @pytest.mark.requires_backend_interface(interface=X509Backend) def test_no_issuer_name(self, backend): private_key = RSA_KEY_2048.private_key(backend) - builder = x509.CertificateRevocationListBuilder().last_update( - datetime.datetime(2002, 1, 1, 12, 1) - ).next_update( - datetime.datetime(2030, 1, 1, 12, 1) + builder = ( + x509.CertificateRevocationListBuilder() + .last_update(datetime.datetime(2002, 1, 1, 12, 1)) + .next_update(datetime.datetime(2030, 1, 1, 12, 1)) ) with pytest.raises(ValueError): @@ -168,10 +185,12 @@ def test_no_issuer_name(self, backend): @pytest.mark.requires_backend_interface(interface=X509Backend) def test_no_last_update(self, backend): private_key = RSA_KEY_2048.private_key(backend) - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u'US')]) - ).next_update( - datetime.datetime(2030, 1, 1, 12, 1) + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u"US")]) + ) + .next_update(datetime.datetime(2030, 1, 1, 12, 1)) ) with pytest.raises(ValueError): @@ -181,10 +200,12 @@ def test_no_last_update(self, backend): @pytest.mark.requires_backend_interface(interface=X509Backend) def test_no_next_update(self, backend): private_key = RSA_KEY_2048.private_key(backend) - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u'US')]) - ).last_update( - datetime.datetime(2030, 1, 1, 12, 1) + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name([x509.NameAttribute(NameOID.COUNTRY_NAME, u"US")]) + ) + .last_update(datetime.datetime(2030, 1, 1, 12, 1)) ) with pytest.raises(ValueError): @@ -196,11 +217,20 @@ def test_sign_empty_list(self, backend): private_key = RSA_KEY_2048.private_key(backend) last_update = datetime.datetime(2002, 1, 1, 12, 1) next_update = datetime.datetime(2030, 1, 1, 12, 1) - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([ - x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io CA") - ]) - ).last_update(last_update).next_update(next_update) + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name( + [ + x509.NameAttribute( + NameOID.COMMON_NAME, u"cryptography.io CA" + ) + ] + ) + ) + .last_update(last_update) + .next_update(next_update) + ) crl = builder.sign(private_key, hashes.SHA256(), backend) assert len(crl) == 0 @@ -216,18 +246,20 @@ def test_sign_empty_list(self, backend): b"\xc3\x9c\xf3\xfc\xd3F\x084\xbb\xceF\x7f\xa0|[\xf3\xe2\x08" b"\xcbY", None, - None + None, ), - x509.AuthorityInformationAccess([ - x509.AccessDescription( - AuthorityInformationAccessOID.CA_ISSUERS, - x509.DNSName(u"cryptography.io") - ) - ]), - x509.IssuerAlternativeName([ - x509.UniformResourceIdentifier(u"https://cryptography.io"), - ]) - ] + x509.AuthorityInformationAccess( + [ + x509.AccessDescription( + AuthorityInformationAccessOID.CA_ISSUERS, + x509.DNSName(u"cryptography.io"), + ) + ] + ), + x509.IssuerAlternativeName( + [x509.UniformResourceIdentifier(u"https://cryptography.io")] + ), + ], ) @pytest.mark.requires_backend_interface(interface=RSABackend) @pytest.mark.requires_backend_interface(interface=X509Backend) @@ -235,16 +267,20 @@ def test_sign_extensions(self, backend, extension): private_key = RSA_KEY_2048.private_key(backend) last_update = datetime.datetime(2002, 1, 1, 12, 1) next_update = datetime.datetime(2030, 1, 1, 12, 1) - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([ - x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io CA") - ]) - ).last_update( - last_update - ).next_update( - next_update - ).add_extension( - extension, False + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name( + [ + x509.NameAttribute( + NameOID.COMMON_NAME, u"cryptography.io CA" + ) + ] + ) + ) + .last_update(last_update) + .next_update(next_update) + .add_extension(extension, False) ) crl = builder.sign(private_key, hashes.SHA256(), backend) @@ -260,22 +296,25 @@ def test_sign_multiple_extensions_critical(self, backend): private_key = RSA_KEY_2048.private_key(backend) last_update = datetime.datetime(2002, 1, 1, 12, 1) next_update = datetime.datetime(2030, 1, 1, 12, 1) - ian = x509.IssuerAlternativeName([ - x509.UniformResourceIdentifier(u"https://cryptography.io"), - ]) + ian = x509.IssuerAlternativeName( + [x509.UniformResourceIdentifier(u"https://cryptography.io")] + ) crl_number = x509.CRLNumber(13) - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([ - x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io CA") - ]) - ).last_update( - last_update - ).next_update( - next_update - ).add_extension( - crl_number, False - ).add_extension( - ian, True + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name( + [ + x509.NameAttribute( + NameOID.COMMON_NAME, u"cryptography.io CA" + ) + ] + ) + ) + .last_update(last_update) + .next_update(next_update) + .add_extension(crl_number, False) + .add_extension(ian, True) ) crl = builder.sign(private_key, hashes.SHA256(), backend) @@ -296,21 +335,30 @@ def test_freshestcrl_extension(self, backend): private_key = RSA_KEY_2048.private_key(backend) last_update = datetime.datetime(2002, 1, 1, 12, 1) next_update = datetime.datetime(2030, 1, 1, 12, 1) - freshest = x509.FreshestCRL([ - x509.DistributionPoint([ - x509.UniformResourceIdentifier(u"http://d.om/delta"), - ], None, None, None) - ]) - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([ - x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io CA") - ]) - ).last_update( - last_update - ).next_update( - next_update - ).add_extension( - freshest, False + freshest = x509.FreshestCRL( + [ + x509.DistributionPoint( + [x509.UniformResourceIdentifier(u"http://d.om/delta")], + None, + None, + None, + ) + ] + ) + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name( + [ + x509.NameAttribute( + NameOID.COMMON_NAME, u"cryptography.io CA" + ) + ] + ) + ) + .last_update(last_update) + .next_update(next_update) + .add_extension(freshest, False) ) crl = builder.sign(private_key, hashes.SHA256(), backend) @@ -329,16 +377,20 @@ def test_add_unsupported_extension(self, backend): private_key = RSA_KEY_2048.private_key(backend) last_update = datetime.datetime(2002, 1, 1, 12, 1) next_update = datetime.datetime(2030, 1, 1, 12, 1) - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([ - x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io CA") - ]) - ).last_update( - last_update - ).next_update( - next_update - ).add_extension( - x509.OCSPNoCheck(), False + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name( + [ + x509.NameAttribute( + NameOID.COMMON_NAME, u"cryptography.io CA" + ) + ] + ) + ) + .last_update(last_update) + .next_update(next_update) + .add_extension(x509.OCSPNoCheck(), False) ) with pytest.raises(NotImplementedError): builder.sign(private_key, hashes.SHA256(), backend) @@ -349,14 +401,19 @@ def test_sign_rsa_key_too_small(self, backend): private_key = RSA_KEY_512.private_key(backend) last_update = datetime.datetime(2002, 1, 1, 12, 1) next_update = datetime.datetime(2030, 1, 1, 12, 1) - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([ - x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io CA") - ]) - ).last_update( - last_update - ).next_update( - next_update + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name( + [ + x509.NameAttribute( + NameOID.COMMON_NAME, u"cryptography.io CA" + ) + ] + ) + ) + .last_update(last_update) + .next_update(next_update) ) with pytest.raises(ValueError): @@ -368,14 +425,19 @@ def test_sign_with_invalid_hash(self, backend): private_key = RSA_KEY_2048.private_key(backend) last_update = datetime.datetime(2002, 1, 1, 12, 1) next_update = datetime.datetime(2030, 1, 1, 12, 1) - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([ - x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io CA") - ]) - ).last_update( - last_update - ).next_update( - next_update + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name( + [ + x509.NameAttribute( + NameOID.COMMON_NAME, u"cryptography.io CA" + ) + ] + ) + ) + .last_update(last_update) + .next_update(next_update) ) with pytest.raises(TypeError): @@ -383,21 +445,26 @@ def test_sign_with_invalid_hash(self, backend): @pytest.mark.supported( only_if=lambda backend: backend.ed25519_supported(), - skip_message="Requires OpenSSL with Ed25519 support" + skip_message="Requires OpenSSL with Ed25519 support", ) @pytest.mark.requires_backend_interface(interface=X509Backend) def test_sign_with_invalid_hash_ed25519(self, backend): private_key = ed25519.Ed25519PrivateKey.generate() last_update = datetime.datetime(2002, 1, 1, 12, 1) next_update = datetime.datetime(2030, 1, 1, 12, 1) - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([ - x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io CA") - ]) - ).last_update( - last_update - ).next_update( - next_update + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name( + [ + x509.NameAttribute( + NameOID.COMMON_NAME, u"cryptography.io CA" + ) + ] + ) + ) + .last_update(last_update) + .next_update(next_update) ) with pytest.raises(ValueError): @@ -407,21 +474,26 @@ def test_sign_with_invalid_hash_ed25519(self, backend): @pytest.mark.supported( only_if=lambda backend: backend.ed448_supported(), - skip_message="Requires OpenSSL with Ed448 support" + skip_message="Requires OpenSSL with Ed448 support", ) @pytest.mark.requires_backend_interface(interface=X509Backend) def test_sign_with_invalid_hash_ed448(self, backend): private_key = ed448.Ed448PrivateKey.generate() last_update = datetime.datetime(2002, 1, 1, 12, 1) next_update = datetime.datetime(2030, 1, 1, 12, 1) - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([ - x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io CA") - ]) - ).last_update( - last_update - ).next_update( - next_update + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name( + [ + x509.NameAttribute( + NameOID.COMMON_NAME, u"cryptography.io CA" + ) + ] + ) + ) + .last_update(last_update) + .next_update(next_update) ) with pytest.raises(ValueError): @@ -436,36 +508,42 @@ def test_sign_dsa_key(self, backend): invalidity_date = x509.InvalidityDate( datetime.datetime(2002, 1, 1, 0, 0) ) - ian = x509.IssuerAlternativeName([ - x509.UniformResourceIdentifier(u"https://cryptography.io"), - ]) - revoked_cert0 = x509.RevokedCertificateBuilder().serial_number( - 2 - ).revocation_date( - datetime.datetime(2012, 1, 1, 1, 1) - ).add_extension( - invalidity_date, False - ).build(backend) + ian = x509.IssuerAlternativeName( + [x509.UniformResourceIdentifier(u"https://cryptography.io")] + ) + revoked_cert0 = ( + x509.RevokedCertificateBuilder() + .serial_number(2) + .revocation_date(datetime.datetime(2012, 1, 1, 1, 1)) + .add_extension(invalidity_date, False) + .build(backend) + ) last_update = datetime.datetime(2002, 1, 1, 12, 1) next_update = datetime.datetime(2030, 1, 1, 12, 1) - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([ - x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io CA") - ]) - ).last_update( - last_update - ).next_update( - next_update - ).add_revoked_certificate( - revoked_cert0 - ).add_extension( - ian, False + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name( + [ + x509.NameAttribute( + NameOID.COMMON_NAME, u"cryptography.io CA" + ) + ] + ) + ) + .last_update(last_update) + .next_update(next_update) + .add_revoked_certificate(revoked_cert0) + .add_extension(ian, False) ) crl = builder.sign(private_key, hashes.SHA256(), backend) - assert crl.extensions.get_extension_for_class( - x509.IssuerAlternativeName - ).value == ian + assert ( + crl.extensions.get_extension_for_class( + x509.IssuerAlternativeName + ).value + == ian + ) assert crl[0].serial_number == revoked_cert0.serial_number assert crl[0].revocation_date == revoked_cert0.revocation_date assert len(crl[0].extensions) == 1 @@ -481,36 +559,42 @@ def test_sign_ec_key(self, backend): invalidity_date = x509.InvalidityDate( datetime.datetime(2002, 1, 1, 0, 0) ) - ian = x509.IssuerAlternativeName([ - x509.UniformResourceIdentifier(u"https://cryptography.io"), - ]) - revoked_cert0 = x509.RevokedCertificateBuilder().serial_number( - 2 - ).revocation_date( - datetime.datetime(2012, 1, 1, 1, 1) - ).add_extension( - invalidity_date, False - ).build(backend) + ian = x509.IssuerAlternativeName( + [x509.UniformResourceIdentifier(u"https://cryptography.io")] + ) + revoked_cert0 = ( + x509.RevokedCertificateBuilder() + .serial_number(2) + .revocation_date(datetime.datetime(2012, 1, 1, 1, 1)) + .add_extension(invalidity_date, False) + .build(backend) + ) last_update = datetime.datetime(2002, 1, 1, 12, 1) next_update = datetime.datetime(2030, 1, 1, 12, 1) - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([ - x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io CA") - ]) - ).last_update( - last_update - ).next_update( - next_update - ).add_revoked_certificate( - revoked_cert0 - ).add_extension( - ian, False + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name( + [ + x509.NameAttribute( + NameOID.COMMON_NAME, u"cryptography.io CA" + ) + ] + ) + ) + .last_update(last_update) + .next_update(next_update) + .add_revoked_certificate(revoked_cert0) + .add_extension(ian, False) ) crl = builder.sign(private_key, hashes.SHA256(), backend) - assert crl.extensions.get_extension_for_class( - x509.IssuerAlternativeName - ).value == ian + assert ( + crl.extensions.get_extension_for_class( + x509.IssuerAlternativeName + ).value + == ian + ) assert crl[0].serial_number == revoked_cert0.serial_number assert crl[0].revocation_date == revoked_cert0.revocation_date assert len(crl[0].extensions) == 1 @@ -520,7 +604,7 @@ def test_sign_ec_key(self, backend): @pytest.mark.supported( only_if=lambda backend: backend.ed25519_supported(), - skip_message="Requires OpenSSL with Ed25519 support" + skip_message="Requires OpenSSL with Ed25519 support", ) @pytest.mark.requires_backend_interface(interface=X509Backend) def test_sign_ed25519_key(self, backend): @@ -528,38 +612,44 @@ def test_sign_ed25519_key(self, backend): invalidity_date = x509.InvalidityDate( datetime.datetime(2002, 1, 1, 0, 0) ) - ian = x509.IssuerAlternativeName([ - x509.UniformResourceIdentifier(u"https://cryptography.io"), - ]) - revoked_cert0 = x509.RevokedCertificateBuilder().serial_number( - 2 - ).revocation_date( - datetime.datetime(2012, 1, 1, 1, 1) - ).add_extension( - invalidity_date, False - ).build(backend) + ian = x509.IssuerAlternativeName( + [x509.UniformResourceIdentifier(u"https://cryptography.io")] + ) + revoked_cert0 = ( + x509.RevokedCertificateBuilder() + .serial_number(2) + .revocation_date(datetime.datetime(2012, 1, 1, 1, 1)) + .add_extension(invalidity_date, False) + .build(backend) + ) last_update = datetime.datetime(2002, 1, 1, 12, 1) next_update = datetime.datetime(2030, 1, 1, 12, 1) - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([ - x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io CA") - ]) - ).last_update( - last_update - ).next_update( - next_update - ).add_revoked_certificate( - revoked_cert0 - ).add_extension( - ian, False + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name( + [ + x509.NameAttribute( + NameOID.COMMON_NAME, u"cryptography.io CA" + ) + ] + ) + ) + .last_update(last_update) + .next_update(next_update) + .add_revoked_certificate(revoked_cert0) + .add_extension(ian, False) ) crl = builder.sign(private_key, None, backend) assert crl.signature_hash_algorithm is None assert crl.signature_algorithm_oid == SignatureAlgorithmOID.ED25519 - assert crl.extensions.get_extension_for_class( - x509.IssuerAlternativeName - ).value == ian + assert ( + crl.extensions.get_extension_for_class( + x509.IssuerAlternativeName + ).value + == ian + ) assert crl[0].serial_number == revoked_cert0.serial_number assert crl[0].revocation_date == revoked_cert0.revocation_date assert len(crl[0].extensions) == 1 @@ -569,7 +659,7 @@ def test_sign_ed25519_key(self, backend): @pytest.mark.supported( only_if=lambda backend: backend.ed448_supported(), - skip_message="Requires OpenSSL with Ed448 support" + skip_message="Requires OpenSSL with Ed448 support", ) @pytest.mark.requires_backend_interface(interface=X509Backend) def test_sign_ed448_key(self, backend): @@ -577,38 +667,44 @@ def test_sign_ed448_key(self, backend): invalidity_date = x509.InvalidityDate( datetime.datetime(2002, 1, 1, 0, 0) ) - ian = x509.IssuerAlternativeName([ - x509.UniformResourceIdentifier(u"https://cryptography.io"), - ]) - revoked_cert0 = x509.RevokedCertificateBuilder().serial_number( - 2 - ).revocation_date( - datetime.datetime(2012, 1, 1, 1, 1) - ).add_extension( - invalidity_date, False - ).build(backend) + ian = x509.IssuerAlternativeName( + [x509.UniformResourceIdentifier(u"https://cryptography.io")] + ) + revoked_cert0 = ( + x509.RevokedCertificateBuilder() + .serial_number(2) + .revocation_date(datetime.datetime(2012, 1, 1, 1, 1)) + .add_extension(invalidity_date, False) + .build(backend) + ) last_update = datetime.datetime(2002, 1, 1, 12, 1) next_update = datetime.datetime(2030, 1, 1, 12, 1) - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([ - x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io CA") - ]) - ).last_update( - last_update - ).next_update( - next_update - ).add_revoked_certificate( - revoked_cert0 - ).add_extension( - ian, False + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name( + [ + x509.NameAttribute( + NameOID.COMMON_NAME, u"cryptography.io CA" + ) + ] + ) + ) + .last_update(last_update) + .next_update(next_update) + .add_revoked_certificate(revoked_cert0) + .add_extension(ian, False) ) crl = builder.sign(private_key, None, backend) assert crl.signature_hash_algorithm is None assert crl.signature_algorithm_oid == SignatureAlgorithmOID.ED448 - assert crl.extensions.get_extension_for_class( - x509.IssuerAlternativeName - ).value == ian + assert ( + crl.extensions.get_extension_for_class( + x509.IssuerAlternativeName + ).value + == ian + ) assert crl[0].serial_number == revoked_cert0.serial_number assert crl[0].revocation_date == revoked_cert0.revocation_date assert len(crl[0].extensions) == 1 @@ -622,11 +718,20 @@ def test_dsa_key_sign_md5(self, backend): private_key = DSA_KEY_2048.private_key(backend) last_time = datetime.datetime(2012, 1, 16, 22, 43) next_time = datetime.datetime(2022, 1, 17, 6, 43) - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([ - x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io CA") - ]) - ).last_update(last_time).next_update(next_time) + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name( + [ + x509.NameAttribute( + NameOID.COMMON_NAME, u"cryptography.io CA" + ) + ] + ) + ) + .last_update(last_time) + .next_update(next_time) + ) with pytest.raises(ValueError): builder.sign(private_key, hashes.MD5(), backend) @@ -638,11 +743,20 @@ def test_ec_key_sign_md5(self, backend): private_key = EC_KEY_SECP256R1.private_key(backend) last_time = datetime.datetime(2012, 1, 16, 22, 43) next_time = datetime.datetime(2022, 1, 17, 6, 43) - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([ - x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io CA") - ]) - ).last_update(last_time).next_update(next_time) + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name( + [ + x509.NameAttribute( + NameOID.COMMON_NAME, u"cryptography.io CA" + ) + ] + ) + ) + .last_update(last_time) + .next_update(next_time) + ) with pytest.raises(ValueError): builder.sign(private_key, hashes.MD5(), backend) @@ -656,30 +770,34 @@ def test_sign_with_revoked_certificates(self, backend): invalidity_date = x509.InvalidityDate( datetime.datetime(2002, 1, 1, 0, 0) ) - revoked_cert0 = x509.RevokedCertificateBuilder().serial_number( - 38 - ).revocation_date( - datetime.datetime(2011, 1, 1, 1, 1) - ).build(backend) - revoked_cert1 = x509.RevokedCertificateBuilder().serial_number( - 2 - ).revocation_date( - datetime.datetime(2012, 1, 1, 1, 1) - ).add_extension( - invalidity_date, False - ).build(backend) - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([ - x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io CA") - ]) - ).last_update( - last_update - ).next_update( - next_update - ).add_revoked_certificate( - revoked_cert0 - ).add_revoked_certificate( - revoked_cert1 + revoked_cert0 = ( + x509.RevokedCertificateBuilder() + .serial_number(38) + .revocation_date(datetime.datetime(2011, 1, 1, 1, 1)) + .build(backend) + ) + revoked_cert1 = ( + x509.RevokedCertificateBuilder() + .serial_number(2) + .revocation_date(datetime.datetime(2012, 1, 1, 1, 1)) + .add_extension(invalidity_date, False) + .build(backend) + ) + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name( + [ + x509.NameAttribute( + NameOID.COMMON_NAME, u"cryptography.io CA" + ) + ] + ) + ) + .last_update(last_update) + .next_update(next_update) + .add_revoked_certificate(revoked_cert0) + .add_revoked_certificate(revoked_cert1) ) crl = builder.sign(private_key, hashes.SHA256(), backend) diff --git a/tests/x509/test_x509_ext.py b/tests/x509/test_x509_ext.py index dd5c7fdc5229..850a8b1a2257 100644 --- a/tests/x509/test_x509_ext.py +++ b/tests/x509/test_x509_ext.py @@ -17,7 +17,10 @@ from cryptography import utils, x509 from cryptography.hazmat.backends.interfaces import ( - DSABackend, EllipticCurveBackend, RSABackend, X509Backend + DSABackend, + EllipticCurveBackend, + RSABackend, + X509Backend, ) from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import ec @@ -25,8 +28,13 @@ from cryptography.x509.extensions import _key_identifier_from_public_key from cryptography.x509.general_name import _lazy_import_idna from cryptography.x509.oid import ( - AuthorityInformationAccessOID, ExtendedKeyUsageOID, ExtensionOID, - NameOID, ObjectIdentifier, SubjectInformationAccessOID, _OID_NAMES + AuthorityInformationAccessOID, + ExtendedKeyUsageOID, + ExtensionOID, + NameOID, + ObjectIdentifier, + SubjectInformationAccessOID, + _OID_NAMES, ) from .test_x509 import _load_cert @@ -36,16 +44,15 @@ def _make_certbuilder(private_key): - name = x509.Name( - [x509.NameAttribute(NameOID.COMMON_NAME, u'example.org')]) + name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u"example.org")]) return ( x509.CertificateBuilder() - .subject_name(name) - .issuer_name(name) - .public_key(private_key.public_key()) - .serial_number(777) - .not_valid_before(datetime.datetime(1999, 1, 1)) - .not_valid_after(datetime.datetime(2020, 1, 1)) + .subject_name(name) + .issuer_name(name) + .public_key(private_key.public_key()) + .serial_number(777) + .not_valid_before(datetime.datetime(1999, 1, 1)) + .not_valid_after(datetime.datetime(2020, 1, 1)) ) @@ -81,26 +88,16 @@ def test_repr(self): ) def test_eq(self): - ext1 = x509.Extension( - x509.ObjectIdentifier('1.2.3.4'), False, 'value' - ) - ext2 = x509.Extension( - x509.ObjectIdentifier('1.2.3.4'), False, 'value' - ) + ext1 = x509.Extension(x509.ObjectIdentifier("1.2.3.4"), False, "value") + ext2 = x509.Extension(x509.ObjectIdentifier("1.2.3.4"), False, "value") assert ext1 == ext2 def test_ne(self): - ext1 = x509.Extension( - x509.ObjectIdentifier('1.2.3.4'), False, 'value' - ) - ext2 = x509.Extension( - x509.ObjectIdentifier('1.2.3.5'), False, 'value' - ) - ext3 = x509.Extension( - x509.ObjectIdentifier('1.2.3.4'), True, 'value' - ) + ext1 = x509.Extension(x509.ObjectIdentifier("1.2.3.4"), False, "value") + ext2 = x509.Extension(x509.ObjectIdentifier("1.2.3.5"), False, "value") + ext3 = x509.Extension(x509.ObjectIdentifier("1.2.3.4"), True, "value") ext4 = x509.Extension( - x509.ObjectIdentifier('1.2.3.4'), False, 'value4' + x509.ObjectIdentifier("1.2.3.4"), False, "value4" ) assert ext1 != ext2 assert ext1 != ext3 @@ -111,17 +108,17 @@ def test_hash(self): ext1 = x509.Extension( ExtensionOID.BASIC_CONSTRAINTS, False, - x509.BasicConstraints(ca=False, path_length=None) + x509.BasicConstraints(ca=False, path_length=None), ) ext2 = x509.Extension( ExtensionOID.BASIC_CONSTRAINTS, False, - x509.BasicConstraints(ca=False, path_length=None) + x509.BasicConstraints(ca=False, path_length=None), ) ext3 = x509.Extension( ExtensionOID.BASIC_CONSTRAINTS, False, - x509.BasicConstraints(ca=True, path_length=None) + x509.BasicConstraints(ca=True, path_length=None), ) assert hash(ext1) == hash(ext2) assert hash(ext1) != hash(ext3) @@ -150,10 +147,12 @@ def test_eq(self): def test_ne(self): ext1 = x509.TLSFeature([x509.TLSFeatureType.status_request]) ext2 = x509.TLSFeature([x509.TLSFeatureType.status_request_v2]) - ext3 = x509.TLSFeature([ - x509.TLSFeatureType.status_request, - x509.TLSFeatureType.status_request_v2 - ]) + ext3 = x509.TLSFeature( + [ + x509.TLSFeatureType.status_request, + x509.TLSFeatureType.status_request_v2, + ] + ) assert ext1 != ext2 assert ext1 != ext3 assert ext1 != object() @@ -161,10 +160,12 @@ def test_ne(self): def test_hash(self): ext1 = x509.TLSFeature([x509.TLSFeatureType.status_request]) ext2 = x509.TLSFeature([x509.TLSFeatureType.status_request]) - ext3 = x509.TLSFeature([ - x509.TLSFeatureType.status_request, - x509.TLSFeatureType.status_request_v2 - ]) + ext3 = x509.TLSFeature( + [ + x509.TLSFeatureType.status_request, + x509.TLSFeatureType.status_request_v2, + ] + ) assert hash(ext1) == hash(ext2) assert hash(ext1) != hash(ext3) @@ -182,10 +183,12 @@ def test_iter(self): assert list(ext2) == ext2_features def test_indexing(self): - ext = x509.TLSFeature([ - x509.TLSFeatureType.status_request, - x509.TLSFeatureType.status_request_v2, - ]) + ext = x509.TLSFeature( + [ + x509.TLSFeatureType.status_request, + x509.TLSFeatureType.status_request_v2, + ] + ) assert ext[-1] == ext[1] assert ext[0] == x509.TLSFeatureType.status_request @@ -249,10 +252,9 @@ def test_hash(self): class TestCertificateIssuer(object): def test_iter_names(self): - ci = x509.CertificateIssuer([ - x509.DNSName(u"cryptography.io"), - x509.DNSName(u"crypto.local"), - ]) + ci = x509.CertificateIssuer( + [x509.DNSName(u"cryptography.io"), x509.DNSName(u"crypto.local")] + ) assert len(ci) == 2 assert list(ci) == [ x509.DNSName(u"cryptography.io"), @@ -260,13 +262,15 @@ def test_iter_names(self): ] def test_indexing(self): - ci = x509.CertificateIssuer([ - x509.DNSName(u"cryptography.io"), - x509.DNSName(u"crypto.local"), - x509.DNSName(u"another.local"), - x509.RFC822Name(u"email@another.local"), - x509.UniformResourceIdentifier(u"http://another.local"), - ]) + ci = x509.CertificateIssuer( + [ + x509.DNSName(u"cryptography.io"), + x509.DNSName(u"crypto.local"), + x509.DNSName(u"another.local"), + x509.RFC822Name(u"email@another.local"), + x509.UniformResourceIdentifier(u"http://another.local"), + ] + ) assert ci[-1] == ci[4] assert ci[2:6:2] == [ci[2], ci[4]] @@ -295,9 +299,7 @@ def test_repr(self): ) def test_get_values_for_type(self): - ci = x509.CertificateIssuer( - [x509.DNSName(u"cryptography.io")] - ) + ci = x509.CertificateIssuer([x509.DNSName(u"cryptography.io")]) names = ci.get_values_for_type(x509.DNSName) assert names == [u"cryptography.io"] @@ -337,9 +339,7 @@ def test_hash(self): def test_repr(self): reason1 = x509.CRLReason(x509.ReasonFlags.unspecified) - assert repr(reason1) == ( - "" - ) + assert repr(reason1) == ("") class TestDeltaCRLIndicator(object): @@ -360,9 +360,7 @@ def test_ne(self): def test_repr(self): delta1 = x509.DeltaCRLIndicator(2) - assert repr(delta1) == ( - "" - ) + assert repr(delta1) == ("") def test_hash(self): delta1 = x509.DeltaCRLIndicator(1) @@ -545,11 +543,11 @@ def test_repr(self): def test_eq(self): pi = x509.PolicyInformation( x509.ObjectIdentifier("1.2.3"), - [u"string", x509.UserNotice(None, u"hi")] + [u"string", x509.UserNotice(None, u"hi")], ) pi2 = x509.PolicyInformation( x509.ObjectIdentifier("1.2.3"), - [u"string", x509.UserNotice(None, u"hi")] + [u"string", x509.UserNotice(None, u"hi")], ) assert pi == pi2 @@ -570,11 +568,11 @@ def test_ne(self): def test_hash(self): pi = x509.PolicyInformation( x509.ObjectIdentifier("1.2.3"), - [u"string", x509.UserNotice(None, u"hi")] + [u"string", x509.UserNotice(None, u"hi")], ) pi2 = x509.PolicyInformation( x509.ObjectIdentifier("1.2.3"), - [u"string", x509.UserNotice(None, u"hi")] + [u"string", x509.UserNotice(None, u"hi")], ) pi3 = x509.PolicyInformation(x509.ObjectIdentifier("1.2.3"), None) assert hash(pi) == hash(pi2) @@ -662,10 +660,9 @@ def test_long_oid(self, backend): cert = _load_cert( os.path.join("x509", "bigoid.pem"), x509.load_pem_x509_certificate, - backend + backend, ) - ext = cert.extensions.get_extension_for_class( - x509.CertificatePolicies) + ext = cert.extensions.get_extension_for_class(x509.CertificatePolicies) oid = x509.ObjectIdentifier( "1.3.6.1.4.1.311.21.8.8950086.10656446.2706058" @@ -698,19 +695,21 @@ def test_cps_uri_policy_qualifier(self, backend): cert = _load_cert( os.path.join("x509", "custom", "cp_cps_uri.pem"), x509.load_pem_x509_certificate, - backend + backend, ) cp = cert.extensions.get_extension_for_oid( ExtensionOID.CERTIFICATE_POLICIES ).value - assert cp == x509.CertificatePolicies([ - x509.PolicyInformation( - x509.ObjectIdentifier("2.16.840.1.12345.1.2.3.4.1"), - [u"http://other.com/cps"] - ) - ]) + assert cp == x509.CertificatePolicies( + [ + x509.PolicyInformation( + x509.ObjectIdentifier("2.16.840.1.12345.1.2.3.4.1"), + [u"http://other.com/cps"], + ) + ] + ) def test_user_notice_with_notice_reference(self, backend): cert = _load_cert( @@ -718,26 +717,28 @@ def test_user_notice_with_notice_reference(self, backend): "x509", "custom", "cp_user_notice_with_notice_reference.pem" ), x509.load_pem_x509_certificate, - backend + backend, ) cp = cert.extensions.get_extension_for_oid( ExtensionOID.CERTIFICATE_POLICIES ).value - assert cp == x509.CertificatePolicies([ - x509.PolicyInformation( - x509.ObjectIdentifier("2.16.840.1.12345.1.2.3.4.1"), - [ - u"http://example.com/cps", - u"http://other.com/cps", - x509.UserNotice( - x509.NoticeReference(u"my org", [1, 2, 3, 4]), - u"thing" - ) - ] - ) - ]) + assert cp == x509.CertificatePolicies( + [ + x509.PolicyInformation( + x509.ObjectIdentifier("2.16.840.1.12345.1.2.3.4.1"), + [ + u"http://example.com/cps", + u"http://other.com/cps", + x509.UserNotice( + x509.NoticeReference(u"my org", [1, 2, 3, 4]), + u"thing", + ), + ], + ) + ] + ) def test_user_notice_with_explicit_text(self, backend): cert = _load_cert( @@ -745,19 +746,21 @@ def test_user_notice_with_explicit_text(self, backend): "x509", "custom", "cp_user_notice_with_explicit_text.pem" ), x509.load_pem_x509_certificate, - backend + backend, ) cp = cert.extensions.get_extension_for_oid( ExtensionOID.CERTIFICATE_POLICIES ).value - assert cp == x509.CertificatePolicies([ - x509.PolicyInformation( - x509.ObjectIdentifier("2.16.840.1.12345.1.2.3.4.1"), - [x509.UserNotice(None, u"thing")] - ) - ]) + assert cp == x509.CertificatePolicies( + [ + x509.PolicyInformation( + x509.ObjectIdentifier("2.16.840.1.12345.1.2.3.4.1"), + [x509.UserNotice(None, u"thing")], + ) + ] + ) def test_user_notice_no_explicit_text(self, backend): cert = _load_cert( @@ -765,24 +768,25 @@ def test_user_notice_no_explicit_text(self, backend): "x509", "custom", "cp_user_notice_no_explicit_text.pem" ), x509.load_pem_x509_certificate, - backend + backend, ) cp = cert.extensions.get_extension_for_oid( ExtensionOID.CERTIFICATE_POLICIES ).value - assert cp == x509.CertificatePolicies([ - x509.PolicyInformation( - x509.ObjectIdentifier("2.16.840.1.12345.1.2.3.4.1"), - [ - x509.UserNotice( - x509.NoticeReference(u"my org", [1, 2, 3, 4]), - None - ) - ] - ) - ]) + assert cp == x509.CertificatePolicies( + [ + x509.PolicyInformation( + x509.ObjectIdentifier("2.16.840.1.12345.1.2.3.4.1"), + [ + x509.UserNotice( + x509.NoticeReference(u"my org", [1, 2, 3, 4]), None + ) + ], + ) + ] + ) class TestKeyUsage(object): @@ -797,7 +801,7 @@ def test_key_agreement_false_encipher_decipher_true(self): key_cert_sign=False, crl_sign=False, encipher_only=True, - decipher_only=False + decipher_only=False, ) with pytest.raises(ValueError): @@ -810,7 +814,7 @@ def test_key_agreement_false_encipher_decipher_true(self): key_cert_sign=False, crl_sign=False, encipher_only=True, - decipher_only=True + decipher_only=True, ) with pytest.raises(ValueError): @@ -823,7 +827,7 @@ def test_key_agreement_false_encipher_decipher_true(self): key_cert_sign=False, crl_sign=False, encipher_only=False, - decipher_only=True + decipher_only=True, ) def test_properties_key_agreement_true(self): @@ -836,7 +840,7 @@ def test_properties_key_agreement_true(self): key_cert_sign=True, crl_sign=False, encipher_only=False, - decipher_only=False + decipher_only=False, ) assert ku.digital_signature is True assert ku.content_commitment is True @@ -856,7 +860,7 @@ def test_key_agreement_true_properties(self): key_cert_sign=False, crl_sign=False, encipher_only=False, - decipher_only=True + decipher_only=True, ) assert ku.key_agreement is True assert ku.encipher_only is False @@ -872,7 +876,7 @@ def test_key_agreement_false_properties(self): key_cert_sign=False, crl_sign=False, encipher_only=False, - decipher_only=False + decipher_only=False, ) assert ku.key_agreement is False with pytest.raises(ValueError): @@ -891,7 +895,7 @@ def test_repr_key_agreement_false(self): key_cert_sign=True, crl_sign=False, encipher_only=False, - decipher_only=False + decipher_only=False, ) assert repr(ku) == ( ", critical=False, value=)>" + "igest=b'\\t#\\x84\\x93\"0I\\x8b\\xc9\\x80\\xaa\\x80\\x98Eoo" + "\\xf7\\xff:\\xc9')>)>" ) else: assert repr(ext) == ( ", critical=False, value=)>" + "igest='\\t#\\x84\\x93\"0I\\x8b\\xc9\\x80\\xaa\\x80\\x98Eoo" + "\\xf7\\xff:\\xc9')>)>" ) def test_eq(self): @@ -1074,16 +1078,16 @@ def test_authority_cert_issuer_not_generalname(self): def test_authority_cert_serial_number_not_integer(self): dirname = x509.DirectoryName( - x509.Name([ - x509.NameAttribute( - x509.ObjectIdentifier('2.999.1'), - u'value1' - ), - x509.NameAttribute( - x509.ObjectIdentifier('2.999.2'), - u'value2' - ), - ]) + x509.Name( + [ + x509.NameAttribute( + x509.ObjectIdentifier("2.999.1"), u"value1" + ), + x509.NameAttribute( + x509.ObjectIdentifier("2.999.2"), u"value2" + ), + ] + ) ) with pytest.raises(TypeError): x509.AuthorityKeyIdentifier(b"identifier", [dirname], "notanint") @@ -1094,16 +1098,16 @@ def test_authority_issuer_none_serial_not_none(self): def test_authority_issuer_not_none_serial_none(self): dirname = x509.DirectoryName( - x509.Name([ - x509.NameAttribute( - x509.ObjectIdentifier('2.999.1'), - u'value1' - ), - x509.NameAttribute( - x509.ObjectIdentifier('2.999.2'), - u'value2' - ), - ]) + x509.Name( + [ + x509.NameAttribute( + x509.ObjectIdentifier("2.999.1"), u"value1" + ), + x509.NameAttribute( + x509.ObjectIdentifier("2.999.2"), u"value2" + ), + ] + ) ) with pytest.raises(ValueError): x509.AuthorityKeyIdentifier(b"identifier", [dirname], None) @@ -1124,7 +1128,7 @@ def test_authority_cert_serial_zero(self): def test_iter_input(self): dirnames = [ x509.DirectoryName( - x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u'myCN')]) + x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u"myCN")]) ) ] aki = x509.AuthorityKeyIdentifier(b"digest", iter(dirnames), 1234) @@ -1132,7 +1136,7 @@ def test_iter_input(self): def test_repr(self): dirname = x509.DirectoryName( - x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u'myCN')]) + x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u"myCN")]) ) aki = x509.AuthorityKeyIdentifier(b"digest", [dirname], 1234) @@ -1151,21 +1155,21 @@ def test_repr(self): def test_eq(self): dirname = x509.DirectoryName( - x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u'myCN')]) + x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u"myCN")]) ) aki = x509.AuthorityKeyIdentifier(b"digest", [dirname], 1234) dirname2 = x509.DirectoryName( - x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u'myCN')]) + x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u"myCN")]) ) aki2 = x509.AuthorityKeyIdentifier(b"digest", [dirname2], 1234) assert aki == aki2 def test_ne(self): dirname = x509.DirectoryName( - x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u'myCN')]) + x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u"myCN")]) ) dirname5 = x509.DirectoryName( - x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u'aCN')]) + x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u"aCN")]) ) aki = x509.AuthorityKeyIdentifier(b"digest", [dirname], 1234) aki2 = x509.AuthorityKeyIdentifier(b"diges", [dirname], 1234) @@ -1180,7 +1184,7 @@ def test_ne(self): def test_hash(self): dirname = x509.DirectoryName( - x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u'myCN')]) + x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u"myCN")]) ) aki1 = x509.AuthorityKeyIdentifier(b"digest", [dirname], 1234) aki2 = x509.AuthorityKeyIdentifier(b"digest", [dirname], 1234) @@ -1211,9 +1215,7 @@ def test_path_length_negative(self): def test_repr(self): na = x509.BasicConstraints(ca=True, path_length=None) - assert repr(na) == ( - "" - ) + assert repr(na) == ("") def test_hash(self): na = x509.BasicConstraints(ca=True, path_length=None) @@ -1242,14 +1244,16 @@ def test_not_all_oids(self): x509.ExtendedKeyUsage(["notoid"]) def test_iter_len(self): - eku = x509.ExtendedKeyUsage([ - x509.ObjectIdentifier("1.3.6.1.5.5.7.3.1"), - x509.ObjectIdentifier("1.3.6.1.5.5.7.3.2"), - ]) + eku = x509.ExtendedKeyUsage( + [ + x509.ObjectIdentifier("1.3.6.1.5.5.7.3.1"), + x509.ObjectIdentifier("1.3.6.1.5.5.7.3.2"), + ] + ) assert len(eku) == 2 assert list(eku) == [ ExtendedKeyUsageOID.SERVER_AUTH, - ExtendedKeyUsageOID.CLIENT_AUTH + ExtendedKeyUsageOID.CLIENT_AUTH, ] def test_iter_input(self): @@ -1261,10 +1265,12 @@ def test_iter_input(self): assert list(aia) == usages def test_repr(self): - eku = x509.ExtendedKeyUsage([ - x509.ObjectIdentifier("1.3.6.1.5.5.7.3.1"), - x509.ObjectIdentifier("1.3.6.1.5.5.7.3.2"), - ]) + eku = x509.ExtendedKeyUsage( + [ + x509.ObjectIdentifier("1.3.6.1.5.5.7.3.1"), + x509.ObjectIdentifier("1.3.6.1.5.5.7.3.2"), + ] + ) assert repr(eku) == ( ", )>" def test_eq(self): - name = x509.Name([ - x509.NameAttribute(x509.ObjectIdentifier('2.999.1'), u'value1') - ]) - name2 = x509.Name([ - x509.NameAttribute(x509.ObjectIdentifier('2.999.1'), u'value1') - ]) + name = x509.Name( + [x509.NameAttribute(x509.ObjectIdentifier("2.999.1"), u"value1")] + ) + name2 = x509.Name( + [x509.NameAttribute(x509.ObjectIdentifier("2.999.1"), u"value1")] + ) gn = x509.DirectoryName(name) gn2 = x509.DirectoryName(name2) assert gn == gn2 def test_ne(self): - name = x509.Name([ - x509.NameAttribute(x509.ObjectIdentifier('2.999.1'), u'value1') - ]) - name2 = x509.Name([ - x509.NameAttribute(x509.ObjectIdentifier('2.999.2'), u'value2') - ]) + name = x509.Name( + [x509.NameAttribute(x509.ObjectIdentifier("2.999.1"), u"value1")] + ) + name2 = x509.Name( + [x509.NameAttribute(x509.ObjectIdentifier("2.999.2"), u"value2")] + ) gn = x509.DirectoryName(name) gn2 = x509.DirectoryName(name2) assert gn != gn2 assert gn != object() def test_hash(self): - name = x509.Name([ - x509.NameAttribute(x509.ObjectIdentifier('2.999.1'), u'value1') - ]) - name2 = x509.Name([ - x509.NameAttribute(x509.ObjectIdentifier('2.999.2'), u'value2') - ]) + name = x509.Name( + [x509.NameAttribute(x509.ObjectIdentifier("2.999.1"), u"value1")] + ) + name2 = x509.Name( + [x509.NameAttribute(x509.ObjectIdentifier("2.999.2"), u"value2")] + ) gn = x509.DirectoryName(name) gn2 = x509.DirectoryName(name) gn3 = x509.DirectoryName(name2) @@ -1918,9 +1911,7 @@ def test_idna_with_port(self): u"gopher://\u043f\u044b\u043a\u0430.cryptography:70/some/path" ) - assert gn.value == ( - u"gopher://xn--80ato2c.cryptography:70/some/path" - ) + assert gn.value == (u"gopher://xn--80ato2c.cryptography:70/some/path") def test_empty_hostname(self): gn = x509.UniformResourceIdentifier(u"ldap:///some-nonsense") @@ -1948,13 +1939,9 @@ def test_hash(self): def test_repr(self): gn = x509.UniformResourceIdentifier(u"string") if not six.PY2: - assert repr(gn) == ( - "" - ) + assert repr(gn) == ("") else: - assert repr(gn) == ( - "" - ) + assert repr(gn) == ("") class TestRegisteredID(object): @@ -2089,17 +2076,14 @@ def test_hash(self): class TestGeneralNames(object): def test_get_values_for_type(self): - gns = x509.GeneralNames( - [x509.DNSName(u"cryptography.io")] - ) + gns = x509.GeneralNames([x509.DNSName(u"cryptography.io")]) names = gns.get_values_for_type(x509.DNSName) assert names == [u"cryptography.io"] def test_iter_names(self): - gns = x509.GeneralNames([ - x509.DNSName(u"cryptography.io"), - x509.DNSName(u"crypto.local"), - ]) + gns = x509.GeneralNames( + [x509.DNSName(u"cryptography.io"), x509.DNSName(u"crypto.local")] + ) assert len(gns) == 2 assert list(gns) == [ x509.DNSName(u"cryptography.io"), @@ -2115,28 +2099,24 @@ def test_iter_input(self): assert list(gns) == names def test_indexing(self): - gn = x509.GeneralNames([ - x509.DNSName(u"cryptography.io"), - x509.DNSName(u"crypto.local"), - x509.DNSName(u"another.local"), - x509.RFC822Name(u"email@another.local"), - x509.UniformResourceIdentifier(u"http://another.local"), - ]) + gn = x509.GeneralNames( + [ + x509.DNSName(u"cryptography.io"), + x509.DNSName(u"crypto.local"), + x509.DNSName(u"another.local"), + x509.RFC822Name(u"email@another.local"), + x509.UniformResourceIdentifier(u"http://another.local"), + ] + ) assert gn[-1] == gn[4] assert gn[2:6:2] == [gn[2], gn[4]] def test_invalid_general_names(self): with pytest.raises(TypeError): - x509.GeneralNames( - [x509.DNSName(u"cryptography.io"), "invalid"] - ) + x509.GeneralNames([x509.DNSName(u"cryptography.io"), "invalid"]) def test_repr(self): - gns = x509.GeneralNames( - [ - x509.DNSName(u"cryptography.io") - ] - ) + gns = x509.GeneralNames([x509.DNSName(u"cryptography.io")]) if not six.PY2: assert repr(gns) == ( "])>" @@ -2147,21 +2127,13 @@ def test_repr(self): ) def test_eq(self): - gns = x509.GeneralNames( - [x509.DNSName(u"cryptography.io")] - ) - gns2 = x509.GeneralNames( - [x509.DNSName(u"cryptography.io")] - ) + gns = x509.GeneralNames([x509.DNSName(u"cryptography.io")]) + gns2 = x509.GeneralNames([x509.DNSName(u"cryptography.io")]) assert gns == gns2 def test_ne(self): - gns = x509.GeneralNames( - [x509.DNSName(u"cryptography.io")] - ) - gns2 = x509.GeneralNames( - [x509.RFC822Name(u"admin@cryptography.io")] - ) + gns = x509.GeneralNames([x509.DNSName(u"cryptography.io")]) + gns2 = x509.GeneralNames([x509.RFC822Name(u"admin@cryptography.io")]) assert gns != gns2 assert gns != object() @@ -2175,17 +2147,14 @@ def test_hash(self): class TestIssuerAlternativeName(object): def test_get_values_for_type(self): - san = x509.IssuerAlternativeName( - [x509.DNSName(u"cryptography.io")] - ) + san = x509.IssuerAlternativeName([x509.DNSName(u"cryptography.io")]) names = san.get_values_for_type(x509.DNSName) assert names == [u"cryptography.io"] def test_iter_names(self): - san = x509.IssuerAlternativeName([ - x509.DNSName(u"cryptography.io"), - x509.DNSName(u"crypto.local"), - ]) + san = x509.IssuerAlternativeName( + [x509.DNSName(u"cryptography.io"), x509.DNSName(u"crypto.local")] + ) assert len(san) == 2 assert list(san) == [ x509.DNSName(u"cryptography.io"), @@ -2193,13 +2162,15 @@ def test_iter_names(self): ] def test_indexing(self): - ian = x509.IssuerAlternativeName([ - x509.DNSName(u"cryptography.io"), - x509.DNSName(u"crypto.local"), - x509.DNSName(u"another.local"), - x509.RFC822Name(u"email@another.local"), - x509.UniformResourceIdentifier(u"http://another.local"), - ]) + ian = x509.IssuerAlternativeName( + [ + x509.DNSName(u"cryptography.io"), + x509.DNSName(u"crypto.local"), + x509.DNSName(u"another.local"), + x509.RFC822Name(u"email@another.local"), + x509.UniformResourceIdentifier(u"http://another.local"), + ] + ) assert ian[-1] == ian[4] assert ian[2:6:2] == [ian[2], ian[4]] @@ -2210,11 +2181,7 @@ def test_invalid_general_names(self): ) def test_repr(self): - san = x509.IssuerAlternativeName( - [ - x509.DNSName(u"cryptography.io") - ] - ) + san = x509.IssuerAlternativeName([x509.DNSName(u"cryptography.io")]) if not six.PY2: assert repr(san) == ( "', u'email ', - u'email ', u'myemail:' + u"email", + u"email ", + u"email ", + u"email ", + u"myemail:", ] def test_other_name(self, backend): cert = _load_cert( - os.path.join( - "x509", "custom", "san_other_name.pem" - ), + os.path.join("x509", "custom", "san_other_name.pem"), x509.load_pem_x509_certificate, - backend + backend, ) ext = cert.extensions.get_extension_for_oid( @@ -2666,8 +2600,9 @@ def test_other_name(self, backend): assert ext is not None assert ext.critical is False - expected = x509.OtherName(x509.ObjectIdentifier("1.2.3.4"), - b'\x16\x0bHello World') + expected = x509.OtherName( + x509.ObjectIdentifier("1.2.3.4"), b"\x16\x0bHello World" + ) assert len(ext.value) == 1 assert list(ext.value)[0] == expected @@ -2675,12 +2610,16 @@ def test_other_name(self, backend): assert othernames == [expected] def test_certbuilder(self, backend): - sans = [u'*.example.org', u'*.xn--4ca7aey.example.com', - u'foobar.example.net'] + sans = [ + u"*.example.org", + u"*.xn--4ca7aey.example.com", + u"foobar.example.net", + ] private_key = RSA_KEY_2048.private_key(backend) builder = _make_certbuilder(private_key) builder = builder.add_extension( - SubjectAlternativeName(list(map(DNSName, sans))), True) + SubjectAlternativeName(list(map(DNSName, sans))), True + ) cert = builder.sign(private_key, hashes.SHA1(), backend) result = [ @@ -2697,11 +2636,9 @@ def test_certbuilder(self, backend): class TestExtendedKeyUsageExtension(object): def test_eku(self, backend): cert = _load_cert( - os.path.join( - "x509", "custom", "extended_key_usage.pem" - ), + os.path.join("x509", "custom", "extended_key_usage.pem"), x509.load_pem_x509_certificate, - backend + backend, ) ext = cert.extensions.get_extension_for_oid( ExtensionOID.EXTENDED_KEY_USAGE @@ -2735,14 +2672,14 @@ def test_invalid_access_location(self): def test_valid_nonstandard_method(self): ad = x509.AccessDescription( ObjectIdentifier("2.999.1"), - x509.UniformResourceIdentifier(u"http://example.com") + x509.UniformResourceIdentifier(u"http://example.com"), ) assert ad is not None def test_repr(self): ad = x509.AccessDescription( AuthorityInformationAccessOID.OCSP, - x509.UniformResourceIdentifier(u"http://ocsp.domain.com") + x509.UniformResourceIdentifier(u"http://ocsp.domain.com"), ) if not six.PY2: assert repr(ad) == ( @@ -2760,26 +2697,26 @@ def test_repr(self): def test_eq(self): ad = x509.AccessDescription( AuthorityInformationAccessOID.OCSP, - x509.UniformResourceIdentifier(u"http://ocsp.domain.com") + x509.UniformResourceIdentifier(u"http://ocsp.domain.com"), ) ad2 = x509.AccessDescription( AuthorityInformationAccessOID.OCSP, - x509.UniformResourceIdentifier(u"http://ocsp.domain.com") + x509.UniformResourceIdentifier(u"http://ocsp.domain.com"), ) assert ad == ad2 def test_ne(self): ad = x509.AccessDescription( AuthorityInformationAccessOID.OCSP, - x509.UniformResourceIdentifier(u"http://ocsp.domain.com") + x509.UniformResourceIdentifier(u"http://ocsp.domain.com"), ) ad2 = x509.AccessDescription( AuthorityInformationAccessOID.CA_ISSUERS, - x509.UniformResourceIdentifier(u"http://ocsp.domain.com") + x509.UniformResourceIdentifier(u"http://ocsp.domain.com"), ) ad3 = x509.AccessDescription( AuthorityInformationAccessOID.OCSP, - x509.UniformResourceIdentifier(u"http://notthesame") + x509.UniformResourceIdentifier(u"http://notthesame"), ) assert ad != ad2 assert ad != ad3 @@ -2788,15 +2725,15 @@ def test_ne(self): def test_hash(self): ad = x509.AccessDescription( AuthorityInformationAccessOID.OCSP, - x509.UniformResourceIdentifier(u"http://ocsp.domain.com") + x509.UniformResourceIdentifier(u"http://ocsp.domain.com"), ) ad2 = x509.AccessDescription( AuthorityInformationAccessOID.OCSP, - x509.UniformResourceIdentifier(u"http://ocsp.domain.com") + x509.UniformResourceIdentifier(u"http://ocsp.domain.com"), ) ad3 = x509.AccessDescription( AuthorityInformationAccessOID.CA_ISSUERS, - x509.UniformResourceIdentifier(u"http://ocsp.domain.com") + x509.UniformResourceIdentifier(u"http://ocsp.domain.com"), ) assert hash(ad) == hash(ad2) assert hash(ad) != hash(ad3) @@ -2851,7 +2788,7 @@ def test_inhibit_policy_mapping(self, backend): cert = _load_cert( os.path.join("x509", "department-of-state-root.pem"), x509.load_pem_x509_certificate, - backend + backend, ) ext = cert.extensions.get_extension_for_oid( ExtensionOID.POLICY_CONSTRAINTS, @@ -2866,7 +2803,7 @@ def test_require_explicit_policy(self, backend): cert = _load_cert( os.path.join("x509", "custom", "policy_constraints_explicit.pem"), x509.load_pem_x509_certificate, - backend + backend, ) ext = cert.extensions.get_extension_for_oid( ExtensionOID.POLICY_CONSTRAINTS @@ -2883,49 +2820,57 @@ def test_invalid_descriptions(self): x509.AuthorityInformationAccess(["notanAccessDescription"]) def test_iter_len(self): - aia = x509.AuthorityInformationAccess([ - x509.AccessDescription( - AuthorityInformationAccessOID.OCSP, - x509.UniformResourceIdentifier(u"http://ocsp.domain.com") - ), - x509.AccessDescription( - AuthorityInformationAccessOID.CA_ISSUERS, - x509.UniformResourceIdentifier(u"http://domain.com/ca.crt") - ) - ]) + aia = x509.AuthorityInformationAccess( + [ + x509.AccessDescription( + AuthorityInformationAccessOID.OCSP, + x509.UniformResourceIdentifier(u"http://ocsp.domain.com"), + ), + x509.AccessDescription( + AuthorityInformationAccessOID.CA_ISSUERS, + x509.UniformResourceIdentifier( + u"http://domain.com/ca.crt" + ), + ), + ] + ) assert len(aia) == 2 assert list(aia) == [ x509.AccessDescription( AuthorityInformationAccessOID.OCSP, - x509.UniformResourceIdentifier(u"http://ocsp.domain.com") + x509.UniformResourceIdentifier(u"http://ocsp.domain.com"), ), x509.AccessDescription( AuthorityInformationAccessOID.CA_ISSUERS, - x509.UniformResourceIdentifier(u"http://domain.com/ca.crt") - ) + x509.UniformResourceIdentifier(u"http://domain.com/ca.crt"), + ), ] def test_iter_input(self): desc = [ x509.AccessDescription( AuthorityInformationAccessOID.OCSP, - x509.UniformResourceIdentifier(u"http://ocsp.domain.com") + x509.UniformResourceIdentifier(u"http://ocsp.domain.com"), ) ] aia = x509.AuthorityInformationAccess(iter(desc)) assert list(aia) == desc def test_repr(self): - aia = x509.AuthorityInformationAccess([ - x509.AccessDescription( - AuthorityInformationAccessOID.OCSP, - x509.UniformResourceIdentifier(u"http://ocsp.domain.com") - ), - x509.AccessDescription( - AuthorityInformationAccessOID.CA_ISSUERS, - x509.UniformResourceIdentifier(u"http://domain.com/ca.crt") - ) - ]) + aia = x509.AuthorityInformationAccess( + [ + x509.AccessDescription( + AuthorityInformationAccessOID.OCSP, + x509.UniformResourceIdentifier(u"http://ocsp.domain.com"), + ), + x509.AccessDescription( + AuthorityInformationAccessOID.CA_ISSUERS, + x509.UniformResourceIdentifier( + u"http://domain.com/ca.crt" + ), + ), + ] + ) if not six.PY2: assert repr(aia) == ( "' + assert repr(onc) == "" class TestInhibitAnyPolicy(object): @@ -4718,11 +4893,9 @@ def test_hash(self): class TestInhibitAnyPolicyExtension(object): def test_inhibit_any_policy(self, backend): cert = _load_cert( - os.path.join( - "x509", "custom", "inhibit_any_policy_5.pem" - ), + os.path.join("x509", "custom", "inhibit_any_policy_5.pem"), x509.load_pem_x509_certificate, - backend + backend, ) iap = cert.extensions.get_extension_for_oid( ExtensionOID.INHIBIT_ANY_POLICY @@ -4739,7 +4912,8 @@ class TestIssuingDistributionPointExtension(object): x509.IssuingDistributionPoint( full_name=[ x509.UniformResourceIdentifier( - u"http://myhost.com/myca.crl") + u"http://myhost.com/myca.crl" + ) ], relative_name=None, only_contains_user_certs=False, @@ -4747,14 +4921,15 @@ class TestIssuingDistributionPointExtension(object): only_some_reasons=None, indirect_crl=True, only_contains_attribute_certs=False, - ) + ), ), ( "crl_idp_fullname_only.pem", x509.IssuingDistributionPoint( full_name=[ x509.UniformResourceIdentifier( - u"http://myhost.com/myca.crl") + u"http://myhost.com/myca.crl" + ) ], relative_name=None, only_contains_user_certs=False, @@ -4762,14 +4937,15 @@ class TestIssuingDistributionPointExtension(object): only_some_reasons=None, indirect_crl=False, only_contains_attribute_certs=False, - ) + ), ), ( "crl_idp_fullname_only_aa.pem", x509.IssuingDistributionPoint( full_name=[ x509.UniformResourceIdentifier( - u"http://myhost.com/myca.crl") + u"http://myhost.com/myca.crl" + ) ], relative_name=None, only_contains_user_certs=False, @@ -4777,14 +4953,15 @@ class TestIssuingDistributionPointExtension(object): only_some_reasons=None, indirect_crl=False, only_contains_attribute_certs=True, - ) + ), ), ( "crl_idp_fullname_only_user.pem", x509.IssuingDistributionPoint( full_name=[ x509.UniformResourceIdentifier( - u"http://myhost.com/myca.crl") + u"http://myhost.com/myca.crl" + ) ], relative_name=None, only_contains_user_certs=True, @@ -4792,23 +4969,26 @@ class TestIssuingDistributionPointExtension(object): only_some_reasons=None, indirect_crl=False, only_contains_attribute_certs=False, - ) + ), ), ( "crl_idp_only_ca.pem", x509.IssuingDistributionPoint( full_name=None, - relative_name=x509.RelativeDistinguishedName([ - x509.NameAttribute( - oid=x509.NameOID.ORGANIZATION_NAME, value=u"PyCA" - ) - ]), + relative_name=x509.RelativeDistinguishedName( + [ + x509.NameAttribute( + oid=x509.NameOID.ORGANIZATION_NAME, + value=u"PyCA", + ) + ] + ), only_contains_user_certs=False, only_contains_ca_certs=True, only_some_reasons=None, indirect_crl=False, only_contains_attribute_certs=False, - ) + ), ), ( "crl_idp_reasons_only.pem", @@ -4817,62 +4997,71 @@ class TestIssuingDistributionPointExtension(object): relative_name=None, only_contains_user_certs=False, only_contains_ca_certs=False, - only_some_reasons=frozenset([ - x509.ReasonFlags.key_compromise - ]), + only_some_reasons=frozenset( + [x509.ReasonFlags.key_compromise] + ), indirect_crl=False, only_contains_attribute_certs=False, - ) + ), ), ( "crl_idp_relative_user_all_reasons.pem", x509.IssuingDistributionPoint( full_name=None, - relative_name=x509.RelativeDistinguishedName([ - x509.NameAttribute( - oid=x509.NameOID.ORGANIZATION_NAME, value=u"PyCA" - ) - ]), + relative_name=x509.RelativeDistinguishedName( + [ + x509.NameAttribute( + oid=x509.NameOID.ORGANIZATION_NAME, + value=u"PyCA", + ) + ] + ), only_contains_user_certs=True, only_contains_ca_certs=False, - only_some_reasons=frozenset([ - x509.ReasonFlags.key_compromise, - x509.ReasonFlags.ca_compromise, - x509.ReasonFlags.affiliation_changed, - x509.ReasonFlags.superseded, - x509.ReasonFlags.cessation_of_operation, - x509.ReasonFlags.certificate_hold, - x509.ReasonFlags.privilege_withdrawn, - x509.ReasonFlags.aa_compromise, - ]), + only_some_reasons=frozenset( + [ + x509.ReasonFlags.key_compromise, + x509.ReasonFlags.ca_compromise, + x509.ReasonFlags.affiliation_changed, + x509.ReasonFlags.superseded, + x509.ReasonFlags.cessation_of_operation, + x509.ReasonFlags.certificate_hold, + x509.ReasonFlags.privilege_withdrawn, + x509.ReasonFlags.aa_compromise, + ] + ), indirect_crl=False, only_contains_attribute_certs=False, - ) + ), ), ( "crl_idp_relativename_only.pem", x509.IssuingDistributionPoint( full_name=None, - relative_name=x509.RelativeDistinguishedName([ - x509.NameAttribute( - oid=x509.NameOID.ORGANIZATION_NAME, value=u"PyCA" - ) - ]), + relative_name=x509.RelativeDistinguishedName( + [ + x509.NameAttribute( + oid=x509.NameOID.ORGANIZATION_NAME, + value=u"PyCA", + ) + ] + ), only_contains_user_certs=False, only_contains_ca_certs=False, only_some_reasons=None, indirect_crl=False, only_contains_attribute_certs=False, - ) + ), ), - ] + ], ) @pytest.mark.requires_backend_interface(interface=RSABackend) @pytest.mark.requires_backend_interface(interface=X509Backend) def test_vectors(self, filename, expected, backend): crl = _load_cert( os.path.join("x509", "custom", filename), - x509.load_pem_x509_crl, backend + x509.load_pem_x509_crl, + backend, ) idp = crl.extensions.get_extension_for_class( x509.IssuingDistributionPoint @@ -4881,51 +5070,96 @@ def test_vectors(self, filename, expected, backend): @pytest.mark.parametrize( ( - "error", "only_contains_user_certs", "only_contains_ca_certs", - "indirect_crl", "only_contains_attribute_certs", - "only_some_reasons", "full_name", "relative_name" + "error", + "only_contains_user_certs", + "only_contains_ca_certs", + "indirect_crl", + "only_contains_attribute_certs", + "only_some_reasons", + "full_name", + "relative_name", ), [ ( - TypeError, False, False, False, False, 'notafrozenset', None, - None + TypeError, + False, + False, + False, + False, + "notafrozenset", + None, + None, ), ( - TypeError, False, False, False, False, frozenset(['bad']), - None, None + TypeError, + False, + False, + False, + False, + frozenset(["bad"]), + None, + None, ), ( - ValueError, False, False, False, False, - frozenset([x509.ReasonFlags.unspecified]), None, None + ValueError, + False, + False, + False, + False, + frozenset([x509.ReasonFlags.unspecified]), + None, + None, ), ( - ValueError, False, False, False, False, - frozenset([x509.ReasonFlags.remove_from_crl]), None, None + ValueError, + False, + False, + False, + False, + frozenset([x509.ReasonFlags.remove_from_crl]), + None, + None, ), - (TypeError, 'notabool', False, False, False, None, None, None), - (TypeError, False, 'notabool', False, False, None, None, None), - (TypeError, False, False, 'notabool', False, None, None, None), - (TypeError, False, False, False, 'notabool', None, None, None), + (TypeError, "notabool", False, False, False, None, None, None), + (TypeError, False, "notabool", False, False, None, None, None), + (TypeError, False, False, "notabool", False, None, None, None), + (TypeError, False, False, False, "notabool", None, None, None), (ValueError, True, True, False, False, None, None, None), (ValueError, False, False, True, True, None, None, None), (ValueError, False, False, False, False, None, None, None), - ] + ], ) - def test_invalid_init(self, error, only_contains_user_certs, - only_contains_ca_certs, indirect_crl, - only_contains_attribute_certs, only_some_reasons, - full_name, relative_name): + def test_invalid_init( + self, + error, + only_contains_user_certs, + only_contains_ca_certs, + indirect_crl, + only_contains_attribute_certs, + only_some_reasons, + full_name, + relative_name, + ): with pytest.raises(error): x509.IssuingDistributionPoint( - full_name, relative_name, only_contains_user_certs, - only_contains_ca_certs, only_some_reasons, indirect_crl, - only_contains_attribute_certs + full_name, + relative_name, + only_contains_user_certs, + only_contains_ca_certs, + only_some_reasons, + indirect_crl, + only_contains_attribute_certs, ) def test_repr(self): idp = x509.IssuingDistributionPoint( - None, None, False, False, - frozenset([x509.ReasonFlags.key_compromise]), False, False + None, + None, + False, + False, + frozenset([x509.ReasonFlags.key_compromise]), + False, + False, ) if not six.PY2: assert repr(idp) == ( @@ -4952,10 +5186,13 @@ def test_eq(self): only_contains_attribute_certs=False, only_some_reasons=None, full_name=None, - relative_name=x509.RelativeDistinguishedName([ - x509.NameAttribute( - oid=x509.NameOID.ORGANIZATION_NAME, value=u"PyCA") - ]) + relative_name=x509.RelativeDistinguishedName( + [ + x509.NameAttribute( + oid=x509.NameOID.ORGANIZATION_NAME, value=u"PyCA" + ) + ] + ), ) idp2 = x509.IssuingDistributionPoint( only_contains_user_certs=False, @@ -4964,10 +5201,13 @@ def test_eq(self): only_contains_attribute_certs=False, only_some_reasons=None, full_name=None, - relative_name=x509.RelativeDistinguishedName([ - x509.NameAttribute( - oid=x509.NameOID.ORGANIZATION_NAME, value=u"PyCA") - ]) + relative_name=x509.RelativeDistinguishedName( + [ + x509.NameAttribute( + oid=x509.NameOID.ORGANIZATION_NAME, value=u"PyCA" + ) + ] + ), ) assert idp1 == idp2 @@ -4979,10 +5219,13 @@ def test_ne(self): only_contains_attribute_certs=False, only_some_reasons=None, full_name=None, - relative_name=x509.RelativeDistinguishedName([ - x509.NameAttribute( - oid=x509.NameOID.ORGANIZATION_NAME, value=u"PyCA") - ]) + relative_name=x509.RelativeDistinguishedName( + [ + x509.NameAttribute( + oid=x509.NameOID.ORGANIZATION_NAME, value=u"PyCA" + ) + ] + ), ) idp2 = x509.IssuingDistributionPoint( only_contains_user_certs=True, @@ -4991,10 +5234,13 @@ def test_ne(self): only_contains_attribute_certs=False, only_some_reasons=None, full_name=None, - relative_name=x509.RelativeDistinguishedName([ - x509.NameAttribute( - oid=x509.NameOID.ORGANIZATION_NAME, value=u"PyCA") - ]) + relative_name=x509.RelativeDistinguishedName( + [ + x509.NameAttribute( + oid=x509.NameOID.ORGANIZATION_NAME, value=u"PyCA" + ) + ] + ), ) assert idp1 != idp2 assert idp1 != object() @@ -5008,11 +5254,18 @@ def test_hash(self): ) idp3 = x509.IssuingDistributionPoint( None, - x509.RelativeDistinguishedName([ - x509.NameAttribute( - oid=x509.NameOID.ORGANIZATION_NAME, value=u"PyCA") - ]), - True, False, None, False, False + x509.RelativeDistinguishedName( + [ + x509.NameAttribute( + oid=x509.NameOID.ORGANIZATION_NAME, value=u"PyCA" + ) + ] + ), + True, + False, + None, + False, + False, ) assert hash(idp1) == hash(idp2) assert hash(idp1) != hash(idp3) @@ -5076,11 +5329,13 @@ def test_hash(self): ), x509.IssuingDistributionPoint( full_name=None, - relative_name=x509.RelativeDistinguishedName([ - x509.NameAttribute( - oid=x509.NameOID.ORGANIZATION_NAME, value=u"PyCA" - ) - ]), + relative_name=x509.RelativeDistinguishedName( + [ + x509.NameAttribute( + oid=x509.NameOID.ORGANIZATION_NAME, value=u"PyCA" + ) + ] + ), only_contains_user_certs=False, only_contains_ca_certs=True, only_some_reasons=None, @@ -5098,53 +5353,65 @@ def test_hash(self): ), x509.IssuingDistributionPoint( full_name=None, - relative_name=x509.RelativeDistinguishedName([ - x509.NameAttribute( - oid=x509.NameOID.ORGANIZATION_NAME, value=u"PyCA"), - x509.NameAttribute( - oid=x509.NameOID.COMMON_NAME, value=u"cryptography") - ]), + relative_name=x509.RelativeDistinguishedName( + [ + x509.NameAttribute( + oid=x509.NameOID.ORGANIZATION_NAME, value=u"PyCA" + ), + x509.NameAttribute( + oid=x509.NameOID.COMMON_NAME, value=u"cryptography" + ), + ] + ), only_contains_user_certs=True, only_contains_ca_certs=False, - only_some_reasons=frozenset([ - x509.ReasonFlags.key_compromise, - x509.ReasonFlags.ca_compromise, - x509.ReasonFlags.affiliation_changed, - x509.ReasonFlags.privilege_withdrawn, - x509.ReasonFlags.aa_compromise, - ]), + only_some_reasons=frozenset( + [ + x509.ReasonFlags.key_compromise, + x509.ReasonFlags.ca_compromise, + x509.ReasonFlags.affiliation_changed, + x509.ReasonFlags.privilege_withdrawn, + x509.ReasonFlags.aa_compromise, + ] + ), indirect_crl=False, only_contains_attribute_certs=False, ), x509.IssuingDistributionPoint( full_name=None, - relative_name=x509.RelativeDistinguishedName([ - x509.NameAttribute( - oid=x509.NameOID.ORGANIZATION_NAME, value=u"PyCA" - ) - ]), + relative_name=x509.RelativeDistinguishedName( + [ + x509.NameAttribute( + oid=x509.NameOID.ORGANIZATION_NAME, value=u"PyCA" + ) + ] + ), only_contains_user_certs=False, only_contains_ca_certs=False, only_some_reasons=None, indirect_crl=False, only_contains_attribute_certs=False, ), - ] + ], ) def test_generate(self, idp, backend): key = RSA_KEY_2048.private_key(backend) last_update = datetime.datetime(2002, 1, 1, 12, 1) next_update = datetime.datetime(2030, 1, 1, 12, 1) - builder = x509.CertificateRevocationListBuilder().issuer_name( - x509.Name([ - x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io CA") - ]) - ).last_update( - last_update - ).next_update( - next_update - ).add_extension( - idp, True + builder = ( + x509.CertificateRevocationListBuilder() + .issuer_name( + x509.Name( + [ + x509.NameAttribute( + NameOID.COMMON_NAME, u"cryptography.io CA" + ) + ] + ) + ) + .last_update(last_update) + .next_update(next_update) + .add_extension(idp, True) ) crl = builder.sign(key, hashes.SHA256(), backend) @@ -5162,7 +5429,7 @@ def test_load(self, backend): cert = _load_cert( os.path.join("x509", "cryptography.io.precert.pem"), x509.load_pem_x509_certificate, - backend + backend, ) poison = cert.extensions.get_extension_for_oid( ExtensionOID.PRECERT_POISON @@ -5175,9 +5442,11 @@ def test_load(self, backend): def test_generate(self, backend): private_key = RSA_KEY_2048.private_key(backend) - cert = _make_certbuilder(private_key).add_extension( - x509.PrecertPoison(), critical=True - ).sign(private_key, hashes.SHA256(), backend) + cert = ( + _make_certbuilder(private_key) + .add_extension(x509.PrecertPoison(), critical=True) + .sign(private_key, hashes.SHA256(), backend) + ) poison = cert.extensions.get_extension_for_oid( ExtensionOID.PRECERT_POISON ).value @@ -5206,7 +5475,7 @@ def test_ne(self): def test_repr(self): pcp = x509.PrecertPoison() - assert repr(pcp) == '' + assert repr(pcp) == "" @pytest.mark.requires_backend_interface(interface=RSABackend) @@ -5214,76 +5483,107 @@ def test_repr(self): class TestSignedCertificateTimestamps(object): @pytest.mark.supported( only_if=lambda backend: ( - backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER), + backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER + ), skip_message="Requires OpenSSL 1.1.0f+", ) def test_eq(self, backend): - sct = _load_cert( - os.path.join("x509", "badssl-sct.pem"), - x509.load_pem_x509_certificate, - backend - ).extensions.get_extension_for_class( - x509.PrecertificateSignedCertificateTimestamps - ).value[0] - sct2 = _load_cert( - os.path.join("x509", "badssl-sct.pem"), - x509.load_pem_x509_certificate, - backend - ).extensions.get_extension_for_class( - x509.PrecertificateSignedCertificateTimestamps - ).value[0] + sct = ( + _load_cert( + os.path.join("x509", "badssl-sct.pem"), + x509.load_pem_x509_certificate, + backend, + ) + .extensions.get_extension_for_class( + x509.PrecertificateSignedCertificateTimestamps + ) + .value[0] + ) + sct2 = ( + _load_cert( + os.path.join("x509", "badssl-sct.pem"), + x509.load_pem_x509_certificate, + backend, + ) + .extensions.get_extension_for_class( + x509.PrecertificateSignedCertificateTimestamps + ) + .value[0] + ) assert sct == sct2 @pytest.mark.supported( only_if=lambda backend: ( - backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER), + backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER + ), skip_message="Requires OpenSSL 1.1.0f+", ) def test_ne(self, backend): - sct = _load_cert( - os.path.join("x509", "badssl-sct.pem"), - x509.load_pem_x509_certificate, - backend - ).extensions.get_extension_for_class( - x509.PrecertificateSignedCertificateTimestamps - ).value[0] - sct2 = _load_cert( - os.path.join("x509", "cryptography-scts.pem"), - x509.load_pem_x509_certificate, - backend - ).extensions.get_extension_for_class( - x509.PrecertificateSignedCertificateTimestamps - ).value[0] + sct = ( + _load_cert( + os.path.join("x509", "badssl-sct.pem"), + x509.load_pem_x509_certificate, + backend, + ) + .extensions.get_extension_for_class( + x509.PrecertificateSignedCertificateTimestamps + ) + .value[0] + ) + sct2 = ( + _load_cert( + os.path.join("x509", "cryptography-scts.pem"), + x509.load_pem_x509_certificate, + backend, + ) + .extensions.get_extension_for_class( + x509.PrecertificateSignedCertificateTimestamps + ) + .value[0] + ) assert sct != sct2 assert sct != object() @pytest.mark.supported( only_if=lambda backend: ( - backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER), + backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER + ), skip_message="Requires OpenSSL 1.1.0f+", ) def test_hash(self, backend): - sct = _load_cert( - os.path.join("x509", "badssl-sct.pem"), - x509.load_pem_x509_certificate, - backend - ).extensions.get_extension_for_class( - x509.PrecertificateSignedCertificateTimestamps - ).value[0] - sct2 = _load_cert( - os.path.join("x509", "badssl-sct.pem"), - x509.load_pem_x509_certificate, - backend - ).extensions.get_extension_for_class( - x509.PrecertificateSignedCertificateTimestamps - ).value[0] - sct3 = _load_cert( - os.path.join("x509", "cryptography-scts.pem"), - x509.load_pem_x509_certificate, - backend - ).extensions.get_extension_for_class( - x509.PrecertificateSignedCertificateTimestamps - ).value[0] + sct = ( + _load_cert( + os.path.join("x509", "badssl-sct.pem"), + x509.load_pem_x509_certificate, + backend, + ) + .extensions.get_extension_for_class( + x509.PrecertificateSignedCertificateTimestamps + ) + .value[0] + ) + sct2 = ( + _load_cert( + os.path.join("x509", "badssl-sct.pem"), + x509.load_pem_x509_certificate, + backend, + ) + .extensions.get_extension_for_class( + x509.PrecertificateSignedCertificateTimestamps + ) + .value[0] + ) + sct3 = ( + _load_cert( + os.path.join("x509", "cryptography-scts.pem"), + x509.load_pem_x509_certificate, + backend, + ) + .extensions.get_extension_for_class( + x509.PrecertificateSignedCertificateTimestamps + ) + .value[0] + ) assert hash(sct) == hash(sct2) assert hash(sct) != hash(sct3) @@ -5302,89 +5602,121 @@ def test_repr(self): @pytest.mark.supported( only_if=lambda backend: ( - backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER), + backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER + ), skip_message="Requires OpenSSL 1.1.0f+", ) def test_eq(self, backend): - psct1 = _load_cert( - os.path.join("x509", "badssl-sct.pem"), - x509.load_pem_x509_certificate, - backend - ).extensions.get_extension_for_class( - x509.PrecertificateSignedCertificateTimestamps - ).value - psct2 = _load_cert( - os.path.join("x509", "badssl-sct.pem"), - x509.load_pem_x509_certificate, - backend - ).extensions.get_extension_for_class( - x509.PrecertificateSignedCertificateTimestamps - ).value + psct1 = ( + _load_cert( + os.path.join("x509", "badssl-sct.pem"), + x509.load_pem_x509_certificate, + backend, + ) + .extensions.get_extension_for_class( + x509.PrecertificateSignedCertificateTimestamps + ) + .value + ) + psct2 = ( + _load_cert( + os.path.join("x509", "badssl-sct.pem"), + x509.load_pem_x509_certificate, + backend, + ) + .extensions.get_extension_for_class( + x509.PrecertificateSignedCertificateTimestamps + ) + .value + ) assert psct1 == psct2 @pytest.mark.supported( only_if=lambda backend: ( - backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER), + backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER + ), skip_message="Requires OpenSSL 1.1.0f+", ) def test_ne(self, backend): - psct1 = _load_cert( - os.path.join("x509", "cryptography-scts.pem"), - x509.load_pem_x509_certificate, - backend - ).extensions.get_extension_for_class( - x509.PrecertificateSignedCertificateTimestamps - ).value - psct2 = _load_cert( - os.path.join("x509", "badssl-sct.pem"), - x509.load_pem_x509_certificate, - backend - ).extensions.get_extension_for_class( - x509.PrecertificateSignedCertificateTimestamps - ).value + psct1 = ( + _load_cert( + os.path.join("x509", "cryptography-scts.pem"), + x509.load_pem_x509_certificate, + backend, + ) + .extensions.get_extension_for_class( + x509.PrecertificateSignedCertificateTimestamps + ) + .value + ) + psct2 = ( + _load_cert( + os.path.join("x509", "badssl-sct.pem"), + x509.load_pem_x509_certificate, + backend, + ) + .extensions.get_extension_for_class( + x509.PrecertificateSignedCertificateTimestamps + ) + .value + ) assert psct1 != psct2 assert psct1 != object() @pytest.mark.supported( only_if=lambda backend: ( - backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER), + backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER + ), skip_message="Requires OpenSSL 1.1.0f+", ) def test_hash(self, backend): - psct1 = _load_cert( - os.path.join("x509", "badssl-sct.pem"), - x509.load_pem_x509_certificate, - backend - ).extensions.get_extension_for_class( - x509.PrecertificateSignedCertificateTimestamps - ).value - psct2 = _load_cert( - os.path.join("x509", "badssl-sct.pem"), - x509.load_pem_x509_certificate, - backend - ).extensions.get_extension_for_class( - x509.PrecertificateSignedCertificateTimestamps - ).value - psct3 = _load_cert( - os.path.join("x509", "cryptography-scts.pem"), - x509.load_pem_x509_certificate, - backend - ).extensions.get_extension_for_class( - x509.PrecertificateSignedCertificateTimestamps - ).value + psct1 = ( + _load_cert( + os.path.join("x509", "badssl-sct.pem"), + x509.load_pem_x509_certificate, + backend, + ) + .extensions.get_extension_for_class( + x509.PrecertificateSignedCertificateTimestamps + ) + .value + ) + psct2 = ( + _load_cert( + os.path.join("x509", "badssl-sct.pem"), + x509.load_pem_x509_certificate, + backend, + ) + .extensions.get_extension_for_class( + x509.PrecertificateSignedCertificateTimestamps + ) + .value + ) + psct3 = ( + _load_cert( + os.path.join("x509", "cryptography-scts.pem"), + x509.load_pem_x509_certificate, + backend, + ) + .extensions.get_extension_for_class( + x509.PrecertificateSignedCertificateTimestamps + ) + .value + ) assert hash(psct1) == hash(psct2) assert hash(psct1) != hash(psct3) @pytest.mark.supported( only_if=lambda backend: ( - backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER), + backend._lib.CRYPTOGRAPHY_OPENSSL_110F_OR_GREATER + ), skip_message="Requires OpenSSL 1.1.0f+", ) def test_simple(self, backend): cert = _load_cert( os.path.join("x509", "badssl-sct.pem"), x509.load_pem_x509_certificate, - backend + backend, ) scts = cert.extensions.get_extension_for_class( x509.PrecertificateSignedCertificateTimestamps @@ -5401,20 +5733,21 @@ def test_simple(self, backend): 2016, 11, 17, 1, 56, 25, 396000 ) assert ( - sct.entry_type == - x509.certificate_transparency.LogEntryType.PRE_CERTIFICATE + sct.entry_type + == x509.certificate_transparency.LogEntryType.PRE_CERTIFICATE ) @pytest.mark.supported( only_if=lambda backend: ( - not backend._lib.CRYPTOGRAPHY_OPENSSL_110_OR_GREATER), + not backend._lib.CRYPTOGRAPHY_OPENSSL_110_OR_GREATER + ), skip_message="Requires OpenSSL < 1.1.0", ) def test_skips_scts_if_unsupported(self, backend): cert = _load_cert( os.path.join("x509", "badssl-sct.pem"), x509.load_pem_x509_certificate, - backend + backend, ) assert len(cert.extensions) == 10 with pytest.raises(x509.ExtensionNotFound): @@ -5433,11 +5766,9 @@ def test_skips_scts_if_unsupported(self, backend): class TestInvalidExtension(object): def test_invalid_certificate_policies_data(self, backend): cert = _load_cert( - os.path.join( - "x509", "custom", "cp_invalid.pem" - ), + os.path.join("x509", "custom", "cp_invalid.pem"), x509.load_pem_x509_certificate, - backend + backend, ) with pytest.raises(ValueError): cert.extensions @@ -5476,6 +5807,6 @@ def test_hash(self): def test_all_extension_oid_members_have_names_defined(): for oid in dir(ExtensionOID): - if oid.startswith('__'): + if oid.startswith("__"): continue assert getattr(ExtensionOID, oid) in _OID_NAMES diff --git a/tests/x509/test_x509_revokedcertbuilder.py b/tests/x509/test_x509_revokedcertbuilder.py index 75c6b2697180..0db6d2a6f7de 100644 --- a/tests/x509/test_x509_revokedcertbuilder.py +++ b/tests/x509/test_x509_revokedcertbuilder.py @@ -30,10 +30,10 @@ def test_serial_number_must_be_positive(self): @pytest.mark.requires_backend_interface(interface=X509Backend) def test_minimal_serial_number(self, backend): revocation_date = datetime.datetime(2002, 1, 1, 12, 1) - builder = x509.RevokedCertificateBuilder().serial_number( - 1 - ).revocation_date( - revocation_date + builder = ( + x509.RevokedCertificateBuilder() + .serial_number(1) + .revocation_date(revocation_date) ) revoked_certificate = builder.build(backend) @@ -42,10 +42,10 @@ def test_minimal_serial_number(self, backend): @pytest.mark.requires_backend_interface(interface=X509Backend) def test_biggest_serial_number(self, backend): revocation_date = datetime.datetime(2002, 1, 1, 12, 1) - builder = x509.RevokedCertificateBuilder().serial_number( - (1 << 159) - 1 - ).revocation_date( - revocation_date + builder = ( + x509.RevokedCertificateBuilder() + .serial_number((1 << 159) - 1) + .revocation_date(revocation_date) ) revoked_certificate = builder.build(backend) @@ -67,10 +67,10 @@ def test_aware_revocation_date(self, backend): time = tz.localize(time) utc_time = datetime.datetime(2012, 1, 17, 6, 43) serial_number = 333 - builder = x509.RevokedCertificateBuilder().serial_number( - serial_number - ).revocation_date( - time + builder = ( + x509.RevokedCertificateBuilder() + .serial_number(serial_number) + .revocation_date(time) ) revoked_certificate = builder.build(backend) @@ -129,10 +129,10 @@ def test_no_revocation_date(self, backend): def test_create_revoked(self, backend): serial_number = 333 revocation_date = datetime.datetime(2002, 1, 1, 12, 1) - builder = x509.RevokedCertificateBuilder().serial_number( - serial_number - ).revocation_date( - revocation_date + builder = ( + x509.RevokedCertificateBuilder() + .serial_number(serial_number) + .revocation_date(revocation_date) ) revoked_certificate = builder.build(backend) @@ -145,21 +145,18 @@ def test_create_revoked(self, backend): [ x509.InvalidityDate(datetime.datetime(2015, 1, 1, 0, 0)), x509.CRLReason(x509.ReasonFlags.ca_compromise), - x509.CertificateIssuer([ - x509.DNSName(u"cryptography.io"), - ]) - ] + x509.CertificateIssuer([x509.DNSName(u"cryptography.io")]), + ], ) @pytest.mark.requires_backend_interface(interface=X509Backend) def test_add_extensions(self, backend, extension): serial_number = 333 revocation_date = datetime.datetime(2002, 1, 1, 12, 1) - builder = x509.RevokedCertificateBuilder().serial_number( - serial_number - ).revocation_date( - revocation_date - ).add_extension( - extension, False + builder = ( + x509.RevokedCertificateBuilder() + .serial_number(serial_number) + .revocation_date(revocation_date) + .add_extension(extension, False) ) revoked_certificate = builder.build(backend) @@ -179,20 +176,17 @@ def test_add_multiple_extensions(self, backend): invalidity_date = x509.InvalidityDate( datetime.datetime(2015, 1, 1, 0, 0) ) - certificate_issuer = x509.CertificateIssuer([ - x509.DNSName(u"cryptography.io"), - ]) + certificate_issuer = x509.CertificateIssuer( + [x509.DNSName(u"cryptography.io")] + ) crl_reason = x509.CRLReason(x509.ReasonFlags.aa_compromise) - builder = x509.RevokedCertificateBuilder().serial_number( - serial_number - ).revocation_date( - revocation_date - ).add_extension( - invalidity_date, True - ).add_extension( - crl_reason, True - ).add_extension( - certificate_issuer, True + builder = ( + x509.RevokedCertificateBuilder() + .serial_number(serial_number) + .revocation_date(revocation_date) + .add_extension(invalidity_date, True) + .add_extension(crl_reason, True) + .add_extension(certificate_issuer, True) ) revoked_certificate = builder.build(backend) diff --git a/tox.ini b/tox.ini index 989adf6ccc3b..239f2467c1cc 100644 --- a/tox.ini +++ b/tox.ini @@ -66,6 +66,7 @@ extras = pep8test commands = flake8 . + black --check . [testenv:packaging] deps = @@ -74,7 +75,7 @@ commands = check-manifest [flake8] -ignore = W504 +ignore = E203,E211,W503,W504 exclude = .tox,*.egg,.git,_build,.hypothesis select = E,W,F,N,I application-import-names = cryptography,cryptography_vectors,tests diff --git a/vectors/cryptography_vectors/__about__.py b/vectors/cryptography_vectors/__about__.py index 420632e6e4f2..05cfe30d989f 100644 --- a/vectors/cryptography_vectors/__about__.py +++ b/vectors/cryptography_vectors/__about__.py @@ -5,8 +5,14 @@ from __future__ import absolute_import, division, print_function __all__ = [ - "__title__", "__summary__", "__uri__", "__version__", "__author__", - "__email__", "__license__", "__copyright__", + "__title__", + "__summary__", + "__uri__", + "__version__", + "__author__", + "__email__", + "__license__", + "__copyright__", ] __title__ = "cryptography_vectors" diff --git a/vectors/cryptography_vectors/__init__.py b/vectors/cryptography_vectors/__init__.py index abcfe14c2f0a..f39ffe03ab0c 100644 --- a/vectors/cryptography_vectors/__init__.py +++ b/vectors/cryptography_vectors/__init__.py @@ -7,14 +7,26 @@ import os from cryptography_vectors.__about__ import ( - __author__, __copyright__, __email__, __license__, __summary__, __title__, - __uri__, __version__ + __author__, + __copyright__, + __email__, + __license__, + __summary__, + __title__, + __uri__, + __version__, ) __all__ = [ - "__title__", "__summary__", "__uri__", "__version__", "__author__", - "__email__", "__license__", "__copyright__", + "__title__", + "__summary__", + "__uri__", + "__version__", + "__author__", + "__email__", + "__license__", + "__copyright__", ] diff --git a/vectors/setup.py b/vectors/setup.py index bf02e389fffe..482c01b35a8f 100644 --- a/vectors/setup.py +++ b/vectors/setup.py @@ -15,20 +15,18 @@ about = {} with open(os.path.join(base_dir, "cryptography_vectors", "__about__.py")) as f: - exec(f.read(), about) + exec (f.read(), about) setup( name=about["__title__"], version=about["__version__"], - description=about["__summary__"], license=about["__license__"], url=about["__uri__"], author=about["__author__"], author_email=about["__email__"], - packages=find_packages(), zip_safe=False, - include_package_data=True + include_package_data=True, )