We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Check IV lengths are correct for cipher
OpenSSL can't be bothered to check these itself, because crypto is real easy and not important.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `cryptography/hazmat/primitives/ciphers/base.py`
Content:
```
1 # Licensed under the Apache License, Version 2.0 (the "License");
2 # you may not use this file except in compliance with the License.
3 # You may obtain a copy of the License at
4 #
5 #    http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS,
9 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
10 # implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13 
14 from __future__ import absolute_import, division, print_function
15 
16 from cryptography import utils
17 from cryptography.exceptions import (
18     AlreadyFinalized, NotYetFinalized, AlreadyUpdated,
19 )
20 from cryptography.hazmat.primitives import interfaces
21 
22 
23 class Cipher(object):
24     def __init__(self, algorithm, mode, backend):
25         if not isinstance(algorithm, interfaces.CipherAlgorithm):
26             raise TypeError("Expected interface of interfaces.CipherAlgorithm")
27 
28         self.algorithm = algorithm
29         self.mode = mode
30         self._backend = backend
31 
32     def encryptor(self):
33         if isinstance(self.mode, interfaces.ModeWithAuthenticationTag):
34             if self.mode.tag is not None:
35                 raise ValueError(
36                     "Authentication tag must be None when encrypting"
37                 )
38         ctx = self._backend.create_symmetric_encryption_ctx(
39             self.algorithm, self.mode
40         )
41         return self._wrap_ctx(ctx, encrypt=True)
42 
43     def decryptor(self):
44         if isinstance(self.mode, interfaces.ModeWithAuthenticationTag):
45             if self.mode.tag is None:
46                 raise ValueError(
47                     "Authentication tag must be provided when decrypting"
48                 )
49         ctx = self._backend.create_symmetric_decryption_ctx(
50             self.algorithm, self.mode
51         )
52         return self._wrap_ctx(ctx, encrypt=False)
53 
54     def _wrap_ctx(self, ctx, encrypt):
55         if isinstance(self.mode, interfaces.ModeWithAuthenticationTag):
56             if encrypt:
57                 return _AEADEncryptionContext(ctx)
58             else:
59                 return _AEADCipherContext(ctx)
60         else:
61             return _CipherContext(ctx)
62 
63 
64 @utils.register_interface(interfaces.CipherContext)
65 class _CipherContext(object):
66     def __init__(self, ctx):
67         self._ctx = ctx
68 
69     def update(self, data):
70         if self._ctx is None:
71             raise AlreadyFinalized("Context was already finalized")
72         return self._ctx.update(data)
73 
74     def finalize(self):
75         if self._ctx is None:
76             raise AlreadyFinalized("Context was already finalized")
77         data = self._ctx.finalize()
78         self._ctx = None
79         return data
80 
81 
82 @utils.register_interface(interfaces.AEADCipherContext)
83 @utils.register_interface(interfaces.CipherContext)
84 class _AEADCipherContext(object):
85     def __init__(self, ctx):
86         self._ctx = ctx
87         self._tag = None
88         self._updated = False
89 
90     def update(self, data):
91         if self._ctx is None:
92             raise AlreadyFinalized("Context was already finalized")
93         self._updated = True
94         return self._ctx.update(data)
95 
96     def finalize(self):
97         if self._ctx is None:
98             raise AlreadyFinalized("Context was already finalized")
99         data = self._ctx.finalize()
100         self._tag = self._ctx.tag
101         self._ctx = None
102         return data
103 
104     def authenticate_additional_data(self, data):
105         if self._ctx is None:
106             raise AlreadyFinalized("Context was already finalized")
107         if self._updated:
108             raise AlreadyUpdated("Update has been called on this context")
109         self._ctx.authenticate_additional_data(data)
110 
111 
112 @utils.register_interface(interfaces.AEADEncryptionContext)
113 class _AEADEncryptionContext(_AEADCipherContext):
114     @property
115     def tag(self):
116         if self._ctx is not None:
117             raise NotYetFinalized("You must finalize encryption before "
118                                   "getting the tag")
119         return self._tag
120
```

Path: `cryptography/hazmat/primitives/interfaces.py`
Content:
```
1 # Licensed under the Apache License, Version 2.0 (the "License");
2 # you may not use this file except in compliance with the License.
3 # You may obtain a copy of the License at
4 #
5 #    http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS,
9 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
10 # implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13 
14 from __future__ import absolute_import, division, print_function
15 
16 import abc
17 
18 import six
19 
20 
21 class CipherAlgorithm(six.with_metaclass(abc.ABCMeta)):
22     @abc.abstractproperty
23     def name(self):
24         """
25         A string naming this mode (e.g. "AES", "Camellia").
26         """
27 
28     @abc.abstractproperty
29     def key_size(self):
30         """
31         The size of the key being used as an integer in bits (e.g. 128, 256).
32         """
33 
34 
35 class BlockCipherAlgorithm(six.with_metaclass(abc.ABCMeta)):
36     @abc.abstractproperty
37     def block_size(self):
38         """
39         The size of a block as an integer in bits (e.g. 64, 128).
40         """
41 
42 
43 class Mode(six.with_metaclass(abc.ABCMeta)):
44     @abc.abstractproperty
45     def name(self):
46         """
47         A string naming this mode (e.g. "ECB", "CBC").
48         """
49 
50 
51 class ModeWithInitializationVector(six.with_metaclass(abc.ABCMeta)):
52     @abc.abstractproperty
53     def initialization_vector(self):
54         """
55         The value of the initialization vector for this mode as bytes.
56         """
57 
58 
59 class ModeWithNonce(six.with_metaclass(abc.ABCMeta)):
60     @abc.abstractproperty
61     def nonce(self):
62         """
63         The value of the nonce for this mode as bytes.
64         """
65 
66 
67 class ModeWithAuthenticationTag(six.with_metaclass(abc.ABCMeta)):
68     @abc.abstractproperty
69     def tag(self):
70         """
71         The value of the tag supplied to the constructor of this mode.
72         """
73 
74 
75 class CipherContext(six.with_metaclass(abc.ABCMeta)):
76     @abc.abstractmethod
77     def update(self, data):
78         """
79         Processes the provided bytes through the cipher and returns the results
80         as bytes.
81         """
82 
83     @abc.abstractmethod
84     def finalize(self):
85         """
86         Returns the results of processing the final block as bytes.
87         """
88 
89 
90 class AEADCipherContext(six.with_metaclass(abc.ABCMeta)):
91     @abc.abstractmethod
92     def authenticate_additional_data(self, data):
93         """
94         Authenticates the provided bytes.
95         """
96 
97 
98 class AEADEncryptionContext(six.with_metaclass(abc.ABCMeta)):
99     @abc.abstractproperty
100     def tag(self):
101         """
102         Returns tag bytes. This is only available after encryption is
103         finalized.
104         """
105 
106 
107 class PaddingContext(six.with_metaclass(abc.ABCMeta)):
108     @abc.abstractmethod
109     def update(self, data):
110         """
111         Pads the provided bytes and returns any available data as bytes.
112         """
113 
114     @abc.abstractmethod
115     def finalize(self):
116         """
117         Finalize the padding, returns bytes.
118         """
119 
120 
121 class HashAlgorithm(six.with_metaclass(abc.ABCMeta)):
122     @abc.abstractproperty
123     def name(self):
124         """
125         A string naming this algorithm (e.g. "sha256", "md5").
126         """
127 
128     @abc.abstractproperty
129     def digest_size(self):
130         """
131         The size of the resulting digest in bytes.
132         """
133 
134     @abc.abstractproperty
135     def block_size(self):
136         """
137         The internal block size of the hash algorithm in bytes.
138         """
139 
140 
141 class HashContext(six.with_metaclass(abc.ABCMeta)):
142     @abc.abstractproperty
143     def algorithm(self):
144         """
145         A HashAlgorithm that will be used by this context.
146         """
147 
148     @abc.abstractmethod
149     def update(self, data):
150         """
151         Processes the provided bytes through the hash.
152         """
153 
154     @abc.abstractmethod
155     def finalize(self):
156         """
157         Finalizes the hash context and returns the hash digest as bytes.
158         """
159 
160     @abc.abstractmethod
161     def copy(self):
162         """
163         Return a HashContext that is a copy of the current context.
164         """
165
```

Path: `cryptography/hazmat/primitives/ciphers/modes.py`
Content:
```
1 # Licensed under the Apache License, Version 2.0 (the "License");
2 # you may not use this file except in compliance with the License.
3 # You may obtain a copy of the License at
4 #
5 #    http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS,
9 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
10 # implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13 
14 from __future__ import absolute_import, division, print_function
15 
16 from cryptography import utils
17 from cryptography.hazmat.primitives import interfaces
18 
19 
20 @utils.register_interface(interfaces.Mode)
21 @utils.register_interface(interfaces.ModeWithInitializationVector)
22 class CBC(object):
23     name = "CBC"
24 
25     def __init__(self, initialization_vector):
26         self.initialization_vector = initialization_vector
27 
28 
29 @utils.register_interface(interfaces.Mode)
30 class ECB(object):
31     name = "ECB"
32 
33 
34 @utils.register_interface(interfaces.Mode)
35 @utils.register_interface(interfaces.ModeWithInitializationVector)
36 class OFB(object):
37     name = "OFB"
38 
39     def __init__(self, initialization_vector):
40         self.initialization_vector = initialization_vector
41 
42 
43 @utils.register_interface(interfaces.Mode)
44 @utils.register_interface(interfaces.ModeWithInitializationVector)
45 class CFB(object):
46     name = "CFB"
47 
48     def __init__(self, initialization_vector):
49         self.initialization_vector = initialization_vector
50 
51 
52 @utils.register_interface(interfaces.Mode)
53 @utils.register_interface(interfaces.ModeWithNonce)
54 class CTR(object):
55     name = "CTR"
56 
57     def __init__(self, nonce):
58         self.nonce = nonce
59 
60 
61 @utils.register_interface(interfaces.Mode)
62 @utils.register_interface(interfaces.ModeWithInitializationVector)
63 @utils.register_interface(interfaces.ModeWithAuthenticationTag)
64 class GCM(object):
65     name = "GCM"
66 
67     def __init__(self, initialization_vector, tag=None):
68         if tag is not None and len(tag) < 4:
69             raise ValueError(
70                 "Authentication tag must be 4 bytes or longer"
71             )
72 
73         self.initialization_vector = initialization_vector
74         self.tag = tag
75
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/cryptography/hazmat/primitives/ciphers/base.py b/cryptography/hazmat/primitives/ciphers/base.py
--- a/cryptography/hazmat/primitives/ciphers/base.py
+++ b/cryptography/hazmat/primitives/ciphers/base.py
@@ -25,6 +25,9 @@
         if not isinstance(algorithm, interfaces.CipherAlgorithm):
             raise TypeError("Expected interface of interfaces.CipherAlgorithm")
 
+        if mode is not None:
+            mode.validate_for_algorithm(algorithm)
+
         self.algorithm = algorithm
         self.mode = mode
         self._backend = backend
diff --git a/cryptography/hazmat/primitives/ciphers/modes.py b/cryptography/hazmat/primitives/ciphers/modes.py
--- a/cryptography/hazmat/primitives/ciphers/modes.py
+++ b/cryptography/hazmat/primitives/ciphers/modes.py
@@ -25,11 +25,20 @@
     def __init__(self, initialization_vector):
         self.initialization_vector = initialization_vector
 
+    def validate_for_algorithm(self, algorithm):
+        if len(self.initialization_vector) * 8 != algorithm.block_size:
+            raise ValueError("Invalid iv size ({0}) for {1}".format(
+                len(self.initialization_vector), self.name
+            ))
+
 
 @utils.register_interface(interfaces.Mode)
 class ECB(object):
     name = "ECB"
 
+    def validate_for_algorithm(self, algorithm):
+        pass
+
 
 @utils.register_interface(interfaces.Mode)
 @utils.register_interface(interfaces.ModeWithInitializationVector)
@@ -39,6 +48,12 @@
     def __init__(self, initialization_vector):
         self.initialization_vector = initialization_vector
 
+    def validate_for_algorithm(self, algorithm):
+        if len(self.initialization_vector) * 8 != algorithm.block_size:
+            raise ValueError("Invalid iv size ({0}) for {1}".format(
+                len(self.initialization_vector), self.name
+            ))
+
 
 @utils.register_interface(interfaces.Mode)
 @utils.register_interface(interfaces.ModeWithInitializationVector)
@@ -48,6 +63,12 @@
     def __init__(self, initialization_vector):
         self.initialization_vector = initialization_vector
 
+    def validate_for_algorithm(self, algorithm):
+        if len(self.initialization_vector) * 8 != algorithm.block_size:
+            raise ValueError("Invalid iv size ({0}) for {1}".format(
+                len(self.initialization_vector), self.name
+            ))
+
 
 @utils.register_interface(interfaces.Mode)
 @utils.register_interface(interfaces.ModeWithNonce)
@@ -57,6 +78,12 @@
     def __init__(self, nonce):
         self.nonce = nonce
 
+    def validate_for_algorithm(self, algorithm):
+        if len(self.nonce) * 8 != algorithm.block_size:
+            raise ValueError("Invalid nonce size ({0}) for {1}".format(
+                len(self.nonce), self.name
+            ))
+
 
 @utils.register_interface(interfaces.Mode)
 @utils.register_interface(interfaces.ModeWithInitializationVector)
@@ -65,6 +92,9 @@
     name = "GCM"
 
     def __init__(self, initialization_vector, tag=None):
+        # len(initialization_vector) must in [1, 2 ** 64), but it's impossible
+        # to actually construct a bytes object that large, so we don't check
+        # for it
         if tag is not None and len(tag) < 4:
             raise ValueError(
                 "Authentication tag must be 4 bytes or longer"
@@ -72,3 +102,6 @@
 
         self.initialization_vector = initialization_vector
         self.tag = tag
+
+    def validate_for_algorithm(self, algorithm):
+        pass
diff --git a/cryptography/hazmat/primitives/interfaces.py b/cryptography/hazmat/primitives/interfaces.py
--- a/cryptography/hazmat/primitives/interfaces.py
+++ b/cryptography/hazmat/primitives/interfaces.py
@@ -47,6 +47,13 @@
         A string naming this mode (e.g. "ECB", "CBC").
         """
 
+    @abc.abstractmethod
+    def validate_for_algorithm(self, algorithm):
+        """
+        Checks that all the necessary invariants of this (mode, algorithm)
+        combination are met.
+        """
+
 
 class ModeWithInitializationVector(six.with_metaclass(abc.ABCMeta)):
     @abc.abstractproperty

{"golden_diff": "diff --git a/cryptography/hazmat/primitives/ciphers/base.py b/cryptography/hazmat/primitives/ciphers/base.py\n--- a/cryptography/hazmat/primitives/ciphers/base.py\n+++ b/cryptography/hazmat/primitives/ciphers/base.py\n@@ -25,6 +25,9 @@\n         if not isinstance(algorithm, interfaces.CipherAlgorithm):\n             raise TypeError(\"Expected interface of interfaces.CipherAlgorithm\")\n \n+        if mode is not None:\n+            mode.validate_for_algorithm(algorithm)\n+\n         self.algorithm = algorithm\n         self.mode = mode\n         self._backend = backend\ndiff --git a/cryptography/hazmat/primitives/ciphers/modes.py b/cryptography/hazmat/primitives/ciphers/modes.py\n--- a/cryptography/hazmat/primitives/ciphers/modes.py\n+++ b/cryptography/hazmat/primitives/ciphers/modes.py\n@@ -25,11 +25,20 @@\n     def __init__(self, initialization_vector):\n         self.initialization_vector = initialization_vector\n \n+    def validate_for_algorithm(self, algorithm):\n+        if len(self.initialization_vector) * 8 != algorithm.block_size:\n+            raise ValueError(\"Invalid iv size ({0}) for {1}\".format(\n+                len(self.initialization_vector), self.name\n+            ))\n+\n \n @utils.register_interface(interfaces.Mode)\n class ECB(object):\n     name = \"ECB\"\n \n+    def validate_for_algorithm(self, algorithm):\n+        pass\n+\n \n @utils.register_interface(interfaces.Mode)\n @utils.register_interface(interfaces.ModeWithInitializationVector)\n@@ -39,6 +48,12 @@\n     def __init__(self, initialization_vector):\n         self.initialization_vector = initialization_vector\n \n+    def validate_for_algorithm(self, algorithm):\n+        if len(self.initialization_vector) * 8 != algorithm.block_size:\n+            raise ValueError(\"Invalid iv size ({0}) for {1}\".format(\n+                len(self.initialization_vector), self.name\n+            ))\n+\n \n @utils.register_interface(interfaces.Mode)\n @utils.register_interface(interfaces.ModeWithInitializationVector)\n@@ -48,6 +63,12 @@\n     def __init__(self, initialization_vector):\n         self.initialization_vector = initialization_vector\n \n+    def validate_for_algorithm(self, algorithm):\n+        if len(self.initialization_vector) * 8 != algorithm.block_size:\n+            raise ValueError(\"Invalid iv size ({0}) for {1}\".format(\n+                len(self.initialization_vector), self.name\n+            ))\n+\n \n @utils.register_interface(interfaces.Mode)\n @utils.register_interface(interfaces.ModeWithNonce)\n@@ -57,6 +78,12 @@\n     def __init__(self, nonce):\n         self.nonce = nonce\n \n+    def validate_for_algorithm(self, algorithm):\n+        if len(self.nonce) * 8 != algorithm.block_size:\n+            raise ValueError(\"Invalid nonce size ({0}) for {1}\".format(\n+                len(self.nonce), self.name\n+            ))\n+\n \n @utils.register_interface(interfaces.Mode)\n @utils.register_interface(interfaces.ModeWithInitializationVector)\n@@ -65,6 +92,9 @@\n     name = \"GCM\"\n \n     def __init__(self, initialization_vector, tag=None):\n+        # len(initialization_vector) must in [1, 2 ** 64), but it's impossible\n+        # to actually construct a bytes object that large, so we don't check\n+        # for it\n         if tag is not None and len(tag) < 4:\n             raise ValueError(\n                 \"Authentication tag must be 4 bytes or longer\"\n@@ -72,3 +102,6 @@\n \n         self.initialization_vector = initialization_vector\n         self.tag = tag\n+\n+    def validate_for_algorithm(self, algorithm):\n+        pass\ndiff --git a/cryptography/hazmat/primitives/interfaces.py b/cryptography/hazmat/primitives/interfaces.py\n--- a/cryptography/hazmat/primitives/interfaces.py\n+++ b/cryptography/hazmat/primitives/interfaces.py\n@@ -47,6 +47,13 @@\n         A string naming this mode (e.g. \"ECB\", \"CBC\").\n         \"\"\"\n \n+    @abc.abstractmethod\n+    def validate_for_algorithm(self, algorithm):\n+        \"\"\"\n+        Checks that all the necessary invariants of this (mode, algorithm)\n+        combination are met.\n+        \"\"\"\n+\n \n class ModeWithInitializationVector(six.with_metaclass(abc.ABCMeta)):\n     @abc.abstractproperty\n", "issue": "Check IV lengths are correct for cipher\nOpenSSL can't be bothered to check these itself, because crypto is real easy and not important.\n\n", "before_files": [{"content": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import, division, print_function\n\nfrom cryptography import utils\nfrom cryptography.exceptions import (\n    AlreadyFinalized, NotYetFinalized, AlreadyUpdated,\n)\nfrom cryptography.hazmat.primitives import interfaces\n\n\nclass Cipher(object):\n    def __init__(self, algorithm, mode, backend):\n        if not isinstance(algorithm, interfaces.CipherAlgorithm):\n            raise TypeError(\"Expected interface of interfaces.CipherAlgorithm\")\n\n        self.algorithm = algorithm\n        self.mode = mode\n        self._backend = backend\n\n    def encryptor(self):\n        if isinstance(self.mode, interfaces.ModeWithAuthenticationTag):\n            if self.mode.tag is not None:\n                raise ValueError(\n                    \"Authentication tag must be None when encrypting\"\n                )\n        ctx = self._backend.create_symmetric_encryption_ctx(\n            self.algorithm, self.mode\n        )\n        return self._wrap_ctx(ctx, encrypt=True)\n\n    def decryptor(self):\n        if isinstance(self.mode, interfaces.ModeWithAuthenticationTag):\n            if self.mode.tag is None:\n                raise ValueError(\n                    \"Authentication tag must be provided when decrypting\"\n                )\n        ctx = self._backend.create_symmetric_decryption_ctx(\n            self.algorithm, self.mode\n        )\n        return self._wrap_ctx(ctx, encrypt=False)\n\n    def _wrap_ctx(self, ctx, encrypt):\n        if isinstance(self.mode, interfaces.ModeWithAuthenticationTag):\n            if encrypt:\n                return _AEADEncryptionContext(ctx)\n            else:\n                return _AEADCipherContext(ctx)\n        else:\n            return _CipherContext(ctx)\n\n\n@utils.register_interface(interfaces.CipherContext)\nclass _CipherContext(object):\n    def __init__(self, ctx):\n        self._ctx = ctx\n\n    def update(self, data):\n        if self._ctx is None:\n            raise AlreadyFinalized(\"Context was already finalized\")\n        return self._ctx.update(data)\n\n    def finalize(self):\n        if self._ctx is None:\n            raise AlreadyFinalized(\"Context was already finalized\")\n        data = self._ctx.finalize()\n        self._ctx = None\n        return data\n\n\n@utils.register_interface(interfaces.AEADCipherContext)\n@utils.register_interface(interfaces.CipherContext)\nclass _AEADCipherContext(object):\n    def __init__(self, ctx):\n        self._ctx = ctx\n        self._tag = None\n        self._updated = False\n\n    def update(self, data):\n        if self._ctx is None:\n            raise AlreadyFinalized(\"Context was already finalized\")\n        self._updated = True\n        return self._ctx.update(data)\n\n    def finalize(self):\n        if self._ctx is None:\n            raise AlreadyFinalized(\"Context was already finalized\")\n        data = self._ctx.finalize()\n        self._tag = self._ctx.tag\n        self._ctx = None\n        return data\n\n    def authenticate_additional_data(self, data):\n        if self._ctx is None:\n            raise AlreadyFinalized(\"Context was already finalized\")\n        if self._updated:\n            raise AlreadyUpdated(\"Update has been called on this context\")\n        self._ctx.authenticate_additional_data(data)\n\n\n@utils.register_interface(interfaces.AEADEncryptionContext)\nclass _AEADEncryptionContext(_AEADCipherContext):\n    @property\n    def tag(self):\n        if self._ctx is not None:\n            raise NotYetFinalized(\"You must finalize encryption before \"\n                                  \"getting the tag\")\n        return self._tag\n", "path": "cryptography/hazmat/primitives/ciphers/base.py"}, {"content": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import, division, print_function\n\nimport abc\n\nimport six\n\n\nclass CipherAlgorithm(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractproperty\n    def name(self):\n        \"\"\"\n        A string naming this mode (e.g. \"AES\", \"Camellia\").\n        \"\"\"\n\n    @abc.abstractproperty\n    def key_size(self):\n        \"\"\"\n        The size of the key being used as an integer in bits (e.g. 128, 256).\n        \"\"\"\n\n\nclass BlockCipherAlgorithm(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractproperty\n    def block_size(self):\n        \"\"\"\n        The size of a block as an integer in bits (e.g. 64, 128).\n        \"\"\"\n\n\nclass Mode(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractproperty\n    def name(self):\n        \"\"\"\n        A string naming this mode (e.g. \"ECB\", \"CBC\").\n        \"\"\"\n\n\nclass ModeWithInitializationVector(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractproperty\n    def initialization_vector(self):\n        \"\"\"\n        The value of the initialization vector for this mode as bytes.\n        \"\"\"\n\n\nclass ModeWithNonce(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractproperty\n    def nonce(self):\n        \"\"\"\n        The value of the nonce for this mode as bytes.\n        \"\"\"\n\n\nclass ModeWithAuthenticationTag(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractproperty\n    def tag(self):\n        \"\"\"\n        The value of the tag supplied to the constructor of this mode.\n        \"\"\"\n\n\nclass CipherContext(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractmethod\n    def update(self, data):\n        \"\"\"\n        Processes the provided bytes through the cipher and returns the results\n        as bytes.\n        \"\"\"\n\n    @abc.abstractmethod\n    def finalize(self):\n        \"\"\"\n        Returns the results of processing the final block as bytes.\n        \"\"\"\n\n\nclass AEADCipherContext(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractmethod\n    def authenticate_additional_data(self, data):\n        \"\"\"\n        Authenticates the provided bytes.\n        \"\"\"\n\n\nclass AEADEncryptionContext(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractproperty\n    def tag(self):\n        \"\"\"\n        Returns tag bytes. This is only available after encryption is\n        finalized.\n        \"\"\"\n\n\nclass PaddingContext(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractmethod\n    def update(self, data):\n        \"\"\"\n        Pads the provided bytes and returns any available data as bytes.\n        \"\"\"\n\n    @abc.abstractmethod\n    def finalize(self):\n        \"\"\"\n        Finalize the padding, returns bytes.\n        \"\"\"\n\n\nclass HashAlgorithm(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractproperty\n    def name(self):\n        \"\"\"\n        A string naming this algorithm (e.g. \"sha256\", \"md5\").\n        \"\"\"\n\n    @abc.abstractproperty\n    def digest_size(self):\n        \"\"\"\n        The size of the resulting digest in bytes.\n        \"\"\"\n\n    @abc.abstractproperty\n    def block_size(self):\n        \"\"\"\n        The internal block size of the hash algorithm in bytes.\n        \"\"\"\n\n\nclass HashContext(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractproperty\n    def algorithm(self):\n        \"\"\"\n        A HashAlgorithm that will be used by this context.\n        \"\"\"\n\n    @abc.abstractmethod\n    def update(self, data):\n        \"\"\"\n        Processes the provided bytes through the hash.\n        \"\"\"\n\n    @abc.abstractmethod\n    def finalize(self):\n        \"\"\"\n        Finalizes the hash context and returns the hash digest as bytes.\n        \"\"\"\n\n    @abc.abstractmethod\n    def copy(self):\n        \"\"\"\n        Return a HashContext that is a copy of the current context.\n        \"\"\"\n", "path": "cryptography/hazmat/primitives/interfaces.py"}, {"content": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import, division, print_function\n\nfrom cryptography import utils\nfrom cryptography.hazmat.primitives import interfaces\n\n\n@utils.register_interface(interfaces.Mode)\n@utils.register_interface(interfaces.ModeWithInitializationVector)\nclass CBC(object):\n    name = \"CBC\"\n\n    def __init__(self, initialization_vector):\n        self.initialization_vector = initialization_vector\n\n\n@utils.register_interface(interfaces.Mode)\nclass ECB(object):\n    name = \"ECB\"\n\n\n@utils.register_interface(interfaces.Mode)\n@utils.register_interface(interfaces.ModeWithInitializationVector)\nclass OFB(object):\n    name = \"OFB\"\n\n    def __init__(self, initialization_vector):\n        self.initialization_vector = initialization_vector\n\n\n@utils.register_interface(interfaces.Mode)\n@utils.register_interface(interfaces.ModeWithInitializationVector)\nclass CFB(object):\n    name = \"CFB\"\n\n    def __init__(self, initialization_vector):\n        self.initialization_vector = initialization_vector\n\n\n@utils.register_interface(interfaces.Mode)\n@utils.register_interface(interfaces.ModeWithNonce)\nclass CTR(object):\n    name = \"CTR\"\n\n    def __init__(self, nonce):\n        self.nonce = nonce\n\n\n@utils.register_interface(interfaces.Mode)\n@utils.register_interface(interfaces.ModeWithInitializationVector)\n@utils.register_interface(interfaces.ModeWithAuthenticationTag)\nclass GCM(object):\n    name = \"GCM\"\n\n    def __init__(self, initialization_vector, tag=None):\n        if tag is not None and len(tag) < 4:\n            raise ValueError(\n                \"Authentication tag must be 4 bytes or longer\"\n            )\n\n        self.initialization_vector = initialization_vector\n        self.tag = tag\n", "path": "cryptography/hazmat/primitives/ciphers/modes.py"}], "after_files": [{"content": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import, division, print_function\n\nfrom cryptography import utils\nfrom cryptography.exceptions import (\n    AlreadyFinalized, NotYetFinalized, AlreadyUpdated,\n)\nfrom cryptography.hazmat.primitives import interfaces\n\n\nclass Cipher(object):\n    def __init__(self, algorithm, mode, backend):\n        if not isinstance(algorithm, interfaces.CipherAlgorithm):\n            raise TypeError(\"Expected interface of interfaces.CipherAlgorithm\")\n\n        if mode is not None:\n            mode.validate_for_algorithm(algorithm)\n\n        self.algorithm = algorithm\n        self.mode = mode\n        self._backend = backend\n\n    def encryptor(self):\n        if isinstance(self.mode, interfaces.ModeWithAuthenticationTag):\n            if self.mode.tag is not None:\n                raise ValueError(\n                    \"Authentication tag must be None when encrypting\"\n                )\n        ctx = self._backend.create_symmetric_encryption_ctx(\n            self.algorithm, self.mode\n        )\n        return self._wrap_ctx(ctx, encrypt=True)\n\n    def decryptor(self):\n        if isinstance(self.mode, interfaces.ModeWithAuthenticationTag):\n            if self.mode.tag is None:\n                raise ValueError(\n                    \"Authentication tag must be provided when decrypting\"\n                )\n        ctx = self._backend.create_symmetric_decryption_ctx(\n            self.algorithm, self.mode\n        )\n        return self._wrap_ctx(ctx, encrypt=False)\n\n    def _wrap_ctx(self, ctx, encrypt):\n        if isinstance(self.mode, interfaces.ModeWithAuthenticationTag):\n            if encrypt:\n                return _AEADEncryptionContext(ctx)\n            else:\n                return _AEADCipherContext(ctx)\n        else:\n            return _CipherContext(ctx)\n\n\n@utils.register_interface(interfaces.CipherContext)\nclass _CipherContext(object):\n    def __init__(self, ctx):\n        self._ctx = ctx\n\n    def update(self, data):\n        if self._ctx is None:\n            raise AlreadyFinalized(\"Context was already finalized\")\n        return self._ctx.update(data)\n\n    def finalize(self):\n        if self._ctx is None:\n            raise AlreadyFinalized(\"Context was already finalized\")\n        data = self._ctx.finalize()\n        self._ctx = None\n        return data\n\n\n@utils.register_interface(interfaces.AEADCipherContext)\n@utils.register_interface(interfaces.CipherContext)\nclass _AEADCipherContext(object):\n    def __init__(self, ctx):\n        self._ctx = ctx\n        self._tag = None\n        self._updated = False\n\n    def update(self, data):\n        if self._ctx is None:\n            raise AlreadyFinalized(\"Context was already finalized\")\n        self._updated = True\n        return self._ctx.update(data)\n\n    def finalize(self):\n        if self._ctx is None:\n            raise AlreadyFinalized(\"Context was already finalized\")\n        data = self._ctx.finalize()\n        self._tag = self._ctx.tag\n        self._ctx = None\n        return data\n\n    def authenticate_additional_data(self, data):\n        if self._ctx is None:\n            raise AlreadyFinalized(\"Context was already finalized\")\n        if self._updated:\n            raise AlreadyUpdated(\"Update has been called on this context\")\n        self._ctx.authenticate_additional_data(data)\n\n\n@utils.register_interface(interfaces.AEADEncryptionContext)\nclass _AEADEncryptionContext(_AEADCipherContext):\n    @property\n    def tag(self):\n        if self._ctx is not None:\n            raise NotYetFinalized(\"You must finalize encryption before \"\n                                  \"getting the tag\")\n        return self._tag\n", "path": "cryptography/hazmat/primitives/ciphers/base.py"}, {"content": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import, division, print_function\n\nimport abc\n\nimport six\n\n\nclass CipherAlgorithm(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractproperty\n    def name(self):\n        \"\"\"\n        A string naming this mode (e.g. \"AES\", \"Camellia\").\n        \"\"\"\n\n    @abc.abstractproperty\n    def key_size(self):\n        \"\"\"\n        The size of the key being used as an integer in bits (e.g. 128, 256).\n        \"\"\"\n\n\nclass BlockCipherAlgorithm(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractproperty\n    def block_size(self):\n        \"\"\"\n        The size of a block as an integer in bits (e.g. 64, 128).\n        \"\"\"\n\n\nclass Mode(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractproperty\n    def name(self):\n        \"\"\"\n        A string naming this mode (e.g. \"ECB\", \"CBC\").\n        \"\"\"\n\n    @abc.abstractmethod\n    def validate_for_algorithm(self, algorithm):\n        \"\"\"\n        Checks that all the necessary invariants of this (mode, algorithm)\n        combination are met.\n        \"\"\"\n\n\nclass ModeWithInitializationVector(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractproperty\n    def initialization_vector(self):\n        \"\"\"\n        The value of the initialization vector for this mode as bytes.\n        \"\"\"\n\n\nclass ModeWithNonce(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractproperty\n    def nonce(self):\n        \"\"\"\n        The value of the nonce for this mode as bytes.\n        \"\"\"\n\n\nclass ModeWithAuthenticationTag(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractproperty\n    def tag(self):\n        \"\"\"\n        The value of the tag supplied to the constructor of this mode.\n        \"\"\"\n\n\nclass CipherContext(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractmethod\n    def update(self, data):\n        \"\"\"\n        Processes the provided bytes through the cipher and returns the results\n        as bytes.\n        \"\"\"\n\n    @abc.abstractmethod\n    def finalize(self):\n        \"\"\"\n        Returns the results of processing the final block as bytes.\n        \"\"\"\n\n\nclass AEADCipherContext(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractmethod\n    def authenticate_additional_data(self, data):\n        \"\"\"\n        Authenticates the provided bytes.\n        \"\"\"\n\n\nclass AEADEncryptionContext(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractproperty\n    def tag(self):\n        \"\"\"\n        Returns tag bytes. This is only available after encryption is\n        finalized.\n        \"\"\"\n\n\nclass PaddingContext(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractmethod\n    def update(self, data):\n        \"\"\"\n        Pads the provided bytes and returns any available data as bytes.\n        \"\"\"\n\n    @abc.abstractmethod\n    def finalize(self):\n        \"\"\"\n        Finalize the padding, returns bytes.\n        \"\"\"\n\n\nclass HashAlgorithm(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractproperty\n    def name(self):\n        \"\"\"\n        A string naming this algorithm (e.g. \"sha256\", \"md5\").\n        \"\"\"\n\n    @abc.abstractproperty\n    def digest_size(self):\n        \"\"\"\n        The size of the resulting digest in bytes.\n        \"\"\"\n\n    @abc.abstractproperty\n    def block_size(self):\n        \"\"\"\n        The internal block size of the hash algorithm in bytes.\n        \"\"\"\n\n\nclass HashContext(six.with_metaclass(abc.ABCMeta)):\n    @abc.abstractproperty\n    def algorithm(self):\n        \"\"\"\n        A HashAlgorithm that will be used by this context.\n        \"\"\"\n\n    @abc.abstractmethod\n    def update(self, data):\n        \"\"\"\n        Processes the provided bytes through the hash.\n        \"\"\"\n\n    @abc.abstractmethod\n    def finalize(self):\n        \"\"\"\n        Finalizes the hash context and returns the hash digest as bytes.\n        \"\"\"\n\n    @abc.abstractmethod\n    def copy(self):\n        \"\"\"\n        Return a HashContext that is a copy of the current context.\n        \"\"\"\n", "path": "cryptography/hazmat/primitives/interfaces.py"}, {"content": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import, division, print_function\n\nfrom cryptography import utils\nfrom cryptography.hazmat.primitives import interfaces\n\n\n@utils.register_interface(interfaces.Mode)\n@utils.register_interface(interfaces.ModeWithInitializationVector)\nclass CBC(object):\n    name = \"CBC\"\n\n    def __init__(self, initialization_vector):\n        self.initialization_vector = initialization_vector\n\n    def validate_for_algorithm(self, algorithm):\n        if len(self.initialization_vector) * 8 != algorithm.block_size:\n            raise ValueError(\"Invalid iv size ({0}) for {1}\".format(\n                len(self.initialization_vector), self.name\n            ))\n\n\n@utils.register_interface(interfaces.Mode)\nclass ECB(object):\n    name = \"ECB\"\n\n    def validate_for_algorithm(self, algorithm):\n        pass\n\n\n@utils.register_interface(interfaces.Mode)\n@utils.register_interface(interfaces.ModeWithInitializationVector)\nclass OFB(object):\n    name = \"OFB\"\n\n    def __init__(self, initialization_vector):\n        self.initialization_vector = initialization_vector\n\n    def validate_for_algorithm(self, algorithm):\n        if len(self.initialization_vector) * 8 != algorithm.block_size:\n            raise ValueError(\"Invalid iv size ({0}) for {1}\".format(\n                len(self.initialization_vector), self.name\n            ))\n\n\n@utils.register_interface(interfaces.Mode)\n@utils.register_interface(interfaces.ModeWithInitializationVector)\nclass CFB(object):\n    name = \"CFB\"\n\n    def __init__(self, initialization_vector):\n        self.initialization_vector = initialization_vector\n\n    def validate_for_algorithm(self, algorithm):\n        if len(self.initialization_vector) * 8 != algorithm.block_size:\n            raise ValueError(\"Invalid iv size ({0}) for {1}\".format(\n                len(self.initialization_vector), self.name\n            ))\n\n\n@utils.register_interface(interfaces.Mode)\n@utils.register_interface(interfaces.ModeWithNonce)\nclass CTR(object):\n    name = \"CTR\"\n\n    def __init__(self, nonce):\n        self.nonce = nonce\n\n    def validate_for_algorithm(self, algorithm):\n        if len(self.nonce) * 8 != algorithm.block_size:\n            raise ValueError(\"Invalid nonce size ({0}) for {1}\".format(\n                len(self.nonce), self.name\n            ))\n\n\n@utils.register_interface(interfaces.Mode)\n@utils.register_interface(interfaces.ModeWithInitializationVector)\n@utils.register_interface(interfaces.ModeWithAuthenticationTag)\nclass GCM(object):\n    name = \"GCM\"\n\n    def __init__(self, initialization_vector, tag=None):\n        # len(initialization_vector) must in [1, 2 ** 64), but it's impossible\n        # to actually construct a bytes object that large, so we don't check\n        # for it\n        if tag is not None and len(tag) < 4:\n            raise ValueError(\n                \"Authentication tag must be 4 bytes or longer\"\n            )\n\n        self.initialization_vector = initialization_vector\n        self.tag = tag\n\n    def validate_for_algorithm(self, algorithm):\n        pass\n", "path": "cryptography/hazmat/primitives/ciphers/modes.py"}]}