Upgrade cryptography from 2.5 to 3.3

Source code is from https://github.com/pyca/cryptography/tree/3.3.x

Run setup.py locally and rename _openssl.so/_padding.so

Bug: 205265538
Test: None
Change-Id: If031739ef5830ba2fb177add74515e4660e2906e
diff --git a/tests/hazmat/primitives/utils.py b/tests/hazmat/primitives/utils.py
index 811dcf9..3f1eff6 100644
--- a/tests/hazmat/primitives/utils.py
+++ b/tests/hazmat/primitives/utils.py
@@ -11,15 +11,21 @@
 import pytest
 
 from cryptography.exceptions import (
-    AlreadyFinalized, AlreadyUpdated, InvalidSignature, InvalidTag,
-    NotYetFinalized
+    AlreadyFinalized,
+    AlreadyUpdated,
+    InvalidSignature,
+    InvalidTag,
+    NotYetFinalized,
 )
-from cryptography.hazmat.primitives import hashes, hmac
+from cryptography.hazmat.primitives import hashes, hmac, serialization
 from cryptography.hazmat.primitives.asymmetric import rsa
 from cryptography.hazmat.primitives.ciphers import Cipher
+from cryptography.hazmat.primitives.ciphers.modes import GCM
 from cryptography.hazmat.primitives.kdf.hkdf import HKDF, HKDFExpand
 from cryptography.hazmat.primitives.kdf.kbkdf import (
-    CounterLocation, KBKDFHMAC, Mode
+    CounterLocation,
+    KBKDFHMAC,
+    Mode,
 )
 from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
 
@@ -35,8 +41,9 @@
     return all_params
 
 
-def generate_encrypt_test(param_loader, path, file_names, cipher_factory,
-                          mode_factory):
+def generate_encrypt_test(
+    param_loader, path, file_names, cipher_factory, mode_factory
+):
     all_params = _load_all_params(path, file_names, param_loader)
 
     @pytest.mark.parametrize("params", all_params)
@@ -54,9 +61,7 @@
     plaintext = params["plaintext"]
     ciphertext = params["ciphertext"]
     cipher = Cipher(
-        cipher_factory(**params),
-        mode_factory(**params),
-        backend=backend
+        cipher_factory(**params), mode_factory(**params), backend=backend
     )
     encryptor = cipher.encryptor()
     actual_ciphertext = encryptor.update(binascii.unhexlify(plaintext))
@@ -68,8 +73,9 @@
     assert actual_plaintext == binascii.unhexlify(plaintext)
 
 
-def generate_aead_test(param_loader, path, file_names, cipher_factory,
-                       mode_factory):
+def generate_aead_test(
+    param_loader, path, file_names, cipher_factory, mode_factory
+):
     all_params = _load_all_params(path, file_names, param_loader)
 
     @pytest.mark.parametrize("params", all_params)
@@ -80,6 +86,20 @@
 
 
 def aead_test(backend, cipher_factory, mode_factory, params):
+    if mode_factory is GCM and len(params["iv"]) < 16:
+        # 16 because this is hex encoded data
+        pytest.skip("Less than 64-bit IVs are no longer supported")
+
+    if (
+        mode_factory is GCM
+        and backend._fips_enabled
+        and len(params["iv"]) != 24
+    ):
+        # Red Hat disables non-96-bit IV support as part of its FIPS
+        # patches. The check is for a byte length of 24 because the value is
+        # hex encoded.
+        pytest.skip("Non-96-bit IVs unsupported in FIPS mode.")
+
     if params.get("pt") is not None:
         plaintext = params["pt"]
     ciphertext = params["ct"]
@@ -87,10 +107,12 @@
     if params.get("fail") is True:
         cipher = Cipher(
             cipher_factory(binascii.unhexlify(params["key"])),
-            mode_factory(binascii.unhexlify(params["iv"]),
-                         binascii.unhexlify(params["tag"]),
-                         len(binascii.unhexlify(params["tag"]))),
-            backend
+            mode_factory(
+                binascii.unhexlify(params["iv"]),
+                binascii.unhexlify(params["tag"]),
+                len(binascii.unhexlify(params["tag"])),
+            ),
+            backend,
         )
         decryptor = cipher.decryptor()
         decryptor.authenticate_additional_data(binascii.unhexlify(aad))
@@ -101,7 +123,7 @@
         cipher = Cipher(
             cipher_factory(binascii.unhexlify(params["key"])),
             mode_factory(binascii.unhexlify(params["iv"]), None),
-            backend
+            backend,
         )
         encryptor = cipher.encryptor()
         encryptor.authenticate_additional_data(binascii.unhexlify(aad))
@@ -111,10 +133,12 @@
         assert binascii.hexlify(encryptor.tag[:tag_len]) == params["tag"]
         cipher = Cipher(
             cipher_factory(binascii.unhexlify(params["key"])),
-            mode_factory(binascii.unhexlify(params["iv"]),
-                         binascii.unhexlify(params["tag"]),
-                         min_tag_length=tag_len),
-            backend
+            mode_factory(
+                binascii.unhexlify(params["iv"]),
+                binascii.unhexlify(params["tag"]),
+                min_tag_length=tag_len,
+            ),
+            backend,
         )
         decryptor = cipher.decryptor()
         decryptor.authenticate_additional_data(binascii.unhexlify(aad))
@@ -123,13 +147,15 @@
         assert actual_plaintext == binascii.unhexlify(plaintext)
 
 
-def generate_stream_encryption_test(param_loader, path, file_names,
-                                    cipher_factory):
+def generate_stream_encryption_test(
+    param_loader, path, file_names, cipher_factory
+):
     all_params = _load_all_params(path, file_names, param_loader)
 
     @pytest.mark.parametrize("params", all_params)
     def test_stream_encryption(self, backend, params):
         stream_encryption_test(backend, cipher_factory, params)
+
     return test_stream_encryption
 
 
@@ -157,6 +183,7 @@
     @pytest.mark.parametrize("params", all_params)
     def test_hash(self, backend, params):
         hash_test(backend, hash_cls, params)
+
     return test_hash
 
 
@@ -171,6 +198,7 @@
 def generate_base_hash_test(algorithm, digest_size):
     def test_base_hash(self, backend):
         base_hash_test(backend, algorithm, digest_size)
+
     return test_base_hash
 
 
@@ -191,6 +219,7 @@
 def generate_base_hmac_test(hash_cls):
     def test_base_hmac(self, backend):
         base_hmac_test(backend, hash_cls)
+
     return test_base_hmac
 
 
@@ -208,6 +237,7 @@
     @pytest.mark.parametrize("params", all_params)
     def test_hmac(self, backend, params):
         hmac_test(backend, algorithm, params)
+
     return test_hmac
 
 
@@ -224,6 +254,7 @@
     @pytest.mark.parametrize("params", all_params)
     def test_pbkdf2(self, backend, params):
         pbkdf2_test(backend, algorithm, params)
+
     return test_pbkdf2
 
 
@@ -236,7 +267,7 @@
         int(params["length"]),
         params["salt"],
         int(params["iterations"]),
-        backend
+        backend,
     )
     derived_key = kdf.derive(params["password"])
     assert binascii.hexlify(derived_key) == params["derived_key"]
@@ -245,6 +276,7 @@
 def generate_aead_exception_test(cipher_factory, mode_factory):
     def test_aead_exception(self, backend):
         aead_exception_test(backend, cipher_factory, mode_factory)
+
     return test_aead_exception
 
 
@@ -252,7 +284,7 @@
     cipher = Cipher(
         cipher_factory(binascii.unhexlify(b"0" * 32)),
         mode_factory(binascii.unhexlify(b"0" * 24)),
-        backend
+        backend,
     )
     encryptor = cipher.encryptor()
     encryptor.update(b"a" * 16)
@@ -270,7 +302,7 @@
     cipher = Cipher(
         cipher_factory(binascii.unhexlify(b"0" * 32)),
         mode_factory(binascii.unhexlify(b"0" * 24), b"0" * 16),
-        backend
+        backend,
     )
     decryptor = cipher.decryptor()
     decryptor.update(b"a" * 16)
@@ -281,6 +313,7 @@
 def generate_aead_tag_exception_test(cipher_factory, mode_factory):
     def test_aead_tag_exception(self, backend):
         aead_tag_exception_test(backend, cipher_factory, mode_factory)
+
     return test_aead_tag_exception
 
 
@@ -288,7 +321,7 @@
     cipher = Cipher(
         cipher_factory(binascii.unhexlify(b"0" * 32)),
         mode_factory(binascii.unhexlify(b"0" * 24)),
-        backend
+        backend,
     )
 
     with pytest.raises(ValueError):
@@ -300,7 +333,7 @@
     cipher = Cipher(
         cipher_factory(binascii.unhexlify(b"0" * 32)),
         mode_factory(binascii.unhexlify(b"0" * 24), b"0" * 16),
-        backend
+        backend,
     )
     with pytest.raises(ValueError):
         cipher.encryptor()
@@ -312,7 +345,7 @@
         int(params["l"]),
         salt=binascii.unhexlify(params["salt"]) or None,
         info=binascii.unhexlify(params["info"]) or None,
-        backend=backend
+        backend=backend,
     )
 
     okm = hkdf.derive(binascii.unhexlify(params["ikm"]))
@@ -326,7 +359,7 @@
         int(params["l"]),
         salt=binascii.unhexlify(params["salt"]) or None,
         info=binascii.unhexlify(params["info"]) or None,
-        backend=backend
+        backend=backend,
     )
 
     prk = hkdf._extract(binascii.unhexlify(params["ikm"]))
@@ -339,7 +372,7 @@
         algorithm,
         int(params["l"]),
         info=binascii.unhexlify(params["info"]) or None,
-        backend=backend
+        backend=backend,
     )
 
     okm = hkdf.derive(binascii.unhexlify(params["prk"]))
@@ -353,8 +386,7 @@
     all_tests = [hkdf_extract_test, hkdf_expand_test, hkdf_derive_test]
 
     @pytest.mark.parametrize(
-        ("params", "hkdf_test"),
-        itertools.product(all_params, all_tests)
+        ("params", "hkdf_test"), itertools.product(all_params, all_tests)
     )
     def test_hkdf(self, backend, params, hkdf_test):
         hkdf_test(backend, algorithm, params)
@@ -368,16 +400,17 @@
     @pytest.mark.parametrize("params", all_params)
     def test_kbkdf(self, backend, params):
         kbkdf_counter_mode_test(backend, params)
+
     return test_kbkdf
 
 
 def kbkdf_counter_mode_test(backend, params):
     supported_algorithms = {
-        'hmac_sha1': hashes.SHA1,
-        'hmac_sha224': hashes.SHA224,
-        'hmac_sha256': hashes.SHA256,
-        'hmac_sha384': hashes.SHA384,
-        'hmac_sha512': hashes.SHA512,
+        "hmac_sha1": hashes.SHA1,
+        "hmac_sha224": hashes.SHA224,
+        "hmac_sha256": hashes.SHA256,
+        "hmac_sha384": hashes.SHA384,
+        "hmac_sha512": hashes.SHA512,
     }
 
     supported_counter_locations = {
@@ -385,39 +418,44 @@
         "after_fixed": CounterLocation.AfterFixed,
     }
 
-    algorithm = supported_algorithms.get(params.get('prf'))
+    algorithm = supported_algorithms.get(params.get("prf"))
     if algorithm is None or not backend.hmac_supported(algorithm()):
-        pytest.skip("KBKDF does not support algorithm: {0}".format(
-            params.get('prf')
-        ))
+        pytest.skip(
+            "KBKDF does not support algorithm: {}".format(params.get("prf"))
+        )
 
     ctr_loc = supported_counter_locations.get(params.get("ctrlocation"))
     if ctr_loc is None or not isinstance(ctr_loc, CounterLocation):
-        pytest.skip("Does not support counter location: {0}".format(
-            params.get('ctrlocation')
-        ))
+        pytest.skip(
+            "Does not support counter location: {}".format(
+                params.get("ctrlocation")
+            )
+        )
 
     ctrkdf = KBKDFHMAC(
         algorithm(),
         Mode.CounterMode,
-        params['l'] // 8,
-        params['rlen'] // 8,
+        params["l"] // 8,
+        params["rlen"] // 8,
         None,
         ctr_loc,
         None,
         None,
-        binascii.unhexlify(params['fixedinputdata']),
-        backend=backend)
+        binascii.unhexlify(params["fixedinputdata"]),
+        backend=backend,
+    )
 
-    ko = ctrkdf.derive(binascii.unhexlify(params['ki']))
+    ko = ctrkdf.derive(binascii.unhexlify(params["ki"]))
     assert binascii.hexlify(ko) == params["ko"]
 
 
-def generate_rsa_verification_test(param_loader, path, file_names, hash_alg,
-                                   pad_factory):
+def generate_rsa_verification_test(
+    param_loader, path, file_names, hash_alg, pad_factory
+):
     all_params = _load_all_params(path, file_names, param_loader)
-    all_params = [i for i in all_params
-                  if i["algorithm"] == hash_alg.name.upper()]
+    all_params = [
+        i for i in all_params if i["algorithm"] == hash_alg.name.upper()
+    ]
 
     @pytest.mark.parametrize("params", all_params)
     def test_rsa_verification(self, backend, params):
@@ -428,8 +466,7 @@
 
 def rsa_verification_test(backend, params, hash_alg, pad_factory):
     public_numbers = rsa.RSAPublicNumbers(
-        e=params["public_exponent"],
-        n=params["modulus"]
+        e=params["public_exponent"], n=params["modulus"]
     )
     public_key = public_numbers.public_key(backend)
     pad = pad_factory(params, hash_alg)
@@ -437,19 +474,9 @@
     msg = binascii.unhexlify(params["msg"])
     if params["fail"]:
         with pytest.raises(InvalidSignature):
-            public_key.verify(
-                signature,
-                msg,
-                pad,
-                hash_alg
-            )
+            public_key.verify(signature, msg, pad, hash_alg)
     else:
-        public_key.verify(
-            signature,
-            msg,
-            pad,
-            hash_alg
-        )
+        public_key.verify(signature, msg, pad, hash_alg)
 
 
 def _check_rsa_private_numbers(skey):
@@ -470,3 +497,13 @@
     pkey = skey.public_numbers
     params = pkey.parameter_numbers
     assert pow(params.g, skey.x, params.p) == pkey.y
+
+
+def skip_fips_traditional_openssl(backend, fmt):
+    if (
+        fmt is serialization.PrivateFormat.TraditionalOpenSSL
+        and backend._fips_enabled
+    ):
+        pytest.skip(
+            "Traditional OpenSSL key format is not supported in FIPS mode."
+        )