We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
cffi module names
Hi!

hazmat/bindings/utils.py already sets a modulename for ffi.verify.
However, hazmat/primitives/constant_time.py and hazmat/primitives/padding.py don't. Please set it there as well, this will help with packaging cffi.

Thanks!


--- 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/constant_time.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 cffi
17 
18 import six
19 
20 
21 _ffi = cffi.FFI()
22 _ffi.cdef("""
23 uint8_t Cryptography_constant_time_bytes_eq(uint8_t *, size_t, uint8_t *,
24                                             size_t);
25 """)
26 _lib = _ffi.verify(
27     """
28 uint8_t Cryptography_constant_time_bytes_eq(uint8_t *a, size_t len_a,
29                                             uint8_t *b, size_t len_b) {
30     size_t i = 0;
31     uint8_t mismatch = 0;
32     if (len_a != len_b) {
33         return 0;
34     }
35     for (i = 0; i < len_a; i++) {
36         mismatch |= a[i] ^ b[i];
37     }
38 
39     /* Make sure any bits set are copied to the lowest bit */
40     mismatch |= mismatch >> 4;
41     mismatch |= mismatch >> 2;
42     mismatch |= mismatch >> 1;
43     /* Now check the low bit to see if it's set */
44     return (mismatch & 1) == 0;
45 }
46 """,
47     ext_package="cryptography",
48 )
49 
50 
51 def bytes_eq(a, b):
52     if isinstance(a, six.text_type) or isinstance(b, six.text_type):
53         raise TypeError("Unicode-objects must be encoded before comparing")
54 
55     return _lib.Cryptography_constant_time_bytes_eq(a, len(a), b, len(b)) == 1
56
```

Path: `cryptography/hazmat/primitives/padding.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 cffi
17 
18 import six
19 
20 from cryptography import utils
21 from cryptography.hazmat.primitives import interfaces
22 
23 
24 _ffi = cffi.FFI()
25 _ffi.cdef("""
26 uint8_t Cryptography_check_pkcs7_padding(const uint8_t *, uint8_t);
27 """)
28 _lib = _ffi.verify(
29     """
30 /* Returns the value of the input with the most-significant-bit copied to all
31    of the bits. */
32 static uint8_t Cryptography_DUPLICATE_MSB_TO_ALL(uint8_t a) {
33     return (1 - (a >> (sizeof(uint8_t) * 8 - 1))) - 1;
34 }
35 
36 /* This returns 0xFF if a < b else 0x00, but does so in a constant time
37    fashion */
38 static uint8_t Cryptography_constant_time_lt(uint8_t a, uint8_t b) {
39     a -= b;
40     return Cryptography_DUPLICATE_MSB_TO_ALL(a);
41 }
42 
43 uint8_t Cryptography_check_pkcs7_padding(const uint8_t *data,
44                                          uint8_t block_len) {
45     uint8_t i;
46     uint8_t pad_size = data[block_len - 1];
47     uint8_t mismatch = 0;
48     for (i = 0; i < block_len; i++) {
49         unsigned int mask = Cryptography_constant_time_lt(i, pad_size);
50         uint8_t b = data[block_len - 1 - i];
51         mismatch |= (mask & (pad_size ^ b));
52     }
53 
54     /* Check to make sure the pad_size was within the valid range. */
55     mismatch |= ~Cryptography_constant_time_lt(0, pad_size);
56     mismatch |= Cryptography_constant_time_lt(block_len, pad_size);
57 
58     /* Make sure any bits set are copied to the lowest bit */
59     mismatch |= mismatch >> 4;
60     mismatch |= mismatch >> 2;
61     mismatch |= mismatch >> 1;
62     /* Now check the low bit to see if it's set */
63     return (mismatch & 1) == 0;
64 }
65 """,
66     ext_package="cryptography",
67 )
68 
69 
70 class PKCS7(object):
71     def __init__(self, block_size):
72         if not (0 <= block_size < 256):
73             raise ValueError("block_size must be in range(0, 256)")
74 
75         if block_size % 8 != 0:
76             raise ValueError("block_size must be a multiple of 8")
77 
78         self.block_size = block_size
79 
80     def padder(self):
81         return _PKCS7PaddingContext(self.block_size)
82 
83     def unpadder(self):
84         return _PKCS7UnpaddingContext(self.block_size)
85 
86 
87 @utils.register_interface(interfaces.PaddingContext)
88 class _PKCS7PaddingContext(object):
89     def __init__(self, block_size):
90         self.block_size = block_size
91         # TODO: more copies than necessary, we should use zero-buffer (#193)
92         self._buffer = b""
93 
94     def update(self, data):
95         if self._buffer is None:
96             raise ValueError("Context was already finalized")
97 
98         if isinstance(data, six.text_type):
99             raise TypeError("Unicode-objects must be encoded before padding")
100 
101         self._buffer += data
102 
103         finished_blocks = len(self._buffer) // (self.block_size // 8)
104 
105         result = self._buffer[:finished_blocks * (self.block_size // 8)]
106         self._buffer = self._buffer[finished_blocks * (self.block_size // 8):]
107 
108         return result
109 
110     def finalize(self):
111         if self._buffer is None:
112             raise ValueError("Context was already finalized")
113 
114         pad_size = self.block_size // 8 - len(self._buffer)
115         result = self._buffer + six.int2byte(pad_size) * pad_size
116         self._buffer = None
117         return result
118 
119 
120 @utils.register_interface(interfaces.PaddingContext)
121 class _PKCS7UnpaddingContext(object):
122     def __init__(self, block_size):
123         self.block_size = block_size
124         # TODO: more copies than necessary, we should use zero-buffer (#193)
125         self._buffer = b""
126 
127     def update(self, data):
128         if self._buffer is None:
129             raise ValueError("Context was already finalized")
130 
131         if isinstance(data, six.text_type):
132             raise TypeError("Unicode-objects must be encoded before unpadding")
133 
134         self._buffer += data
135 
136         finished_blocks = max(
137             len(self._buffer) // (self.block_size // 8) - 1,
138             0
139         )
140 
141         result = self._buffer[:finished_blocks * (self.block_size // 8)]
142         self._buffer = self._buffer[finished_blocks * (self.block_size // 8):]
143 
144         return result
145 
146     def finalize(self):
147         if self._buffer is None:
148             raise ValueError("Context was already finalized")
149 
150         if len(self._buffer) != self.block_size // 8:
151             raise ValueError("Invalid padding bytes")
152 
153         valid = _lib.Cryptography_check_pkcs7_padding(
154             self._buffer, self.block_size // 8
155         )
156 
157         if not valid:
158             raise ValueError("Invalid padding bytes")
159 
160         pad_size = six.indexbytes(self._buffer, -1)
161         res = self._buffer[:-pad_size]
162         self._buffer = None
163         return res
164
```
--- 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/constant_time.py b/cryptography/hazmat/primitives/constant_time.py
--- a/cryptography/hazmat/primitives/constant_time.py
+++ b/cryptography/hazmat/primitives/constant_time.py
@@ -13,18 +13,20 @@
 
 from __future__ import absolute_import, division, print_function
 
+import sys
+
 import cffi
 
 import six
 
+from cryptography.hazmat.bindings.utils import _create_modulename
 
-_ffi = cffi.FFI()
-_ffi.cdef("""
+TYPES = """
 uint8_t Cryptography_constant_time_bytes_eq(uint8_t *, size_t, uint8_t *,
                                             size_t);
-""")
-_lib = _ffi.verify(
-    """
+"""
+
+FUNCTIONS = """
 uint8_t Cryptography_constant_time_bytes_eq(uint8_t *a, size_t len_a,
                                             uint8_t *b, size_t len_b) {
     size_t i = 0;
@@ -43,7 +45,13 @@
     /* Now check the low bit to see if it's set */
     return (mismatch & 1) == 0;
 }
-""",
+"""
+
+_ffi = cffi.FFI()
+_ffi.cdef(TYPES)
+_lib = _ffi.verify(
+    source=FUNCTIONS,
+    modulename=_create_modulename([TYPES], FUNCTIONS, sys.version),
     ext_package="cryptography",
 )
 
diff --git a/cryptography/hazmat/primitives/padding.py b/cryptography/hazmat/primitives/padding.py
--- a/cryptography/hazmat/primitives/padding.py
+++ b/cryptography/hazmat/primitives/padding.py
@@ -13,20 +13,22 @@
 
 from __future__ import absolute_import, division, print_function
 
+import sys
+
 import cffi
 
 import six
 
 from cryptography import utils
+from cryptography.hazmat.bindings.utils import _create_modulename
 from cryptography.hazmat.primitives import interfaces
 
 
-_ffi = cffi.FFI()
-_ffi.cdef("""
+TYPES = """
 uint8_t Cryptography_check_pkcs7_padding(const uint8_t *, uint8_t);
-""")
-_lib = _ffi.verify(
-    """
+"""
+
+FUNCTIONS = """
 /* Returns the value of the input with the most-significant-bit copied to all
    of the bits. */
 static uint8_t Cryptography_DUPLICATE_MSB_TO_ALL(uint8_t a) {
@@ -62,7 +64,13 @@
     /* Now check the low bit to see if it's set */
     return (mismatch & 1) == 0;
 }
-""",
+"""
+
+_ffi = cffi.FFI()
+_ffi.cdef(TYPES)
+_lib = _ffi.verify(
+    source=FUNCTIONS,
+    modulename=_create_modulename([TYPES], FUNCTIONS, sys.version),
     ext_package="cryptography",
 )

{"golden_diff": "diff --git a/cryptography/hazmat/primitives/constant_time.py b/cryptography/hazmat/primitives/constant_time.py\n--- a/cryptography/hazmat/primitives/constant_time.py\n+++ b/cryptography/hazmat/primitives/constant_time.py\n@@ -13,18 +13,20 @@\n \n from __future__ import absolute_import, division, print_function\n \n+import sys\n+\n import cffi\n \n import six\n \n+from cryptography.hazmat.bindings.utils import _create_modulename\n \n-_ffi = cffi.FFI()\n-_ffi.cdef(\"\"\"\n+TYPES = \"\"\"\n uint8_t Cryptography_constant_time_bytes_eq(uint8_t *, size_t, uint8_t *,\n                                             size_t);\n-\"\"\")\n-_lib = _ffi.verify(\n-    \"\"\"\n+\"\"\"\n+\n+FUNCTIONS = \"\"\"\n uint8_t Cryptography_constant_time_bytes_eq(uint8_t *a, size_t len_a,\n                                             uint8_t *b, size_t len_b) {\n     size_t i = 0;\n@@ -43,7 +45,13 @@\n     /* Now check the low bit to see if it's set */\n     return (mismatch & 1) == 0;\n }\n-\"\"\",\n+\"\"\"\n+\n+_ffi = cffi.FFI()\n+_ffi.cdef(TYPES)\n+_lib = _ffi.verify(\n+    source=FUNCTIONS,\n+    modulename=_create_modulename([TYPES], FUNCTIONS, sys.version),\n     ext_package=\"cryptography\",\n )\n \ndiff --git a/cryptography/hazmat/primitives/padding.py b/cryptography/hazmat/primitives/padding.py\n--- a/cryptography/hazmat/primitives/padding.py\n+++ b/cryptography/hazmat/primitives/padding.py\n@@ -13,20 +13,22 @@\n \n from __future__ import absolute_import, division, print_function\n \n+import sys\n+\n import cffi\n \n import six\n \n from cryptography import utils\n+from cryptography.hazmat.bindings.utils import _create_modulename\n from cryptography.hazmat.primitives import interfaces\n \n \n-_ffi = cffi.FFI()\n-_ffi.cdef(\"\"\"\n+TYPES = \"\"\"\n uint8_t Cryptography_check_pkcs7_padding(const uint8_t *, uint8_t);\n-\"\"\")\n-_lib = _ffi.verify(\n-    \"\"\"\n+\"\"\"\n+\n+FUNCTIONS = \"\"\"\n /* Returns the value of the input with the most-significant-bit copied to all\n    of the bits. */\n static uint8_t Cryptography_DUPLICATE_MSB_TO_ALL(uint8_t a) {\n@@ -62,7 +64,13 @@\n     /* Now check the low bit to see if it's set */\n     return (mismatch & 1) == 0;\n }\n-\"\"\",\n+\"\"\"\n+\n+_ffi = cffi.FFI()\n+_ffi.cdef(TYPES)\n+_lib = _ffi.verify(\n+    source=FUNCTIONS,\n+    modulename=_create_modulename([TYPES], FUNCTIONS, sys.version),\n     ext_package=\"cryptography\",\n )\n", "issue": "cffi module names\nHi!\n\nhazmat/bindings/utils.py already sets a modulename for ffi.verify.\nHowever, hazmat/primitives/constant_time.py and hazmat/primitives/padding.py don't. Please set it there as well, this will help with packaging cffi.\n\nThanks!\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\nimport cffi\n\nimport six\n\n\n_ffi = cffi.FFI()\n_ffi.cdef(\"\"\"\nuint8_t Cryptography_constant_time_bytes_eq(uint8_t *, size_t, uint8_t *,\n                                            size_t);\n\"\"\")\n_lib = _ffi.verify(\n    \"\"\"\nuint8_t Cryptography_constant_time_bytes_eq(uint8_t *a, size_t len_a,\n                                            uint8_t *b, size_t len_b) {\n    size_t i = 0;\n    uint8_t mismatch = 0;\n    if (len_a != len_b) {\n        return 0;\n    }\n    for (i = 0; i < len_a; i++) {\n        mismatch |= a[i] ^ b[i];\n    }\n\n    /* Make sure any bits set are copied to the lowest bit */\n    mismatch |= mismatch >> 4;\n    mismatch |= mismatch >> 2;\n    mismatch |= mismatch >> 1;\n    /* Now check the low bit to see if it's set */\n    return (mismatch & 1) == 0;\n}\n\"\"\",\n    ext_package=\"cryptography\",\n)\n\n\ndef bytes_eq(a, b):\n    if isinstance(a, six.text_type) or isinstance(b, six.text_type):\n        raise TypeError(\"Unicode-objects must be encoded before comparing\")\n\n    return _lib.Cryptography_constant_time_bytes_eq(a, len(a), b, len(b)) == 1\n", "path": "cryptography/hazmat/primitives/constant_time.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 cffi\n\nimport six\n\nfrom cryptography import utils\nfrom cryptography.hazmat.primitives import interfaces\n\n\n_ffi = cffi.FFI()\n_ffi.cdef(\"\"\"\nuint8_t Cryptography_check_pkcs7_padding(const uint8_t *, uint8_t);\n\"\"\")\n_lib = _ffi.verify(\n    \"\"\"\n/* Returns the value of the input with the most-significant-bit copied to all\n   of the bits. */\nstatic uint8_t Cryptography_DUPLICATE_MSB_TO_ALL(uint8_t a) {\n    return (1 - (a >> (sizeof(uint8_t) * 8 - 1))) - 1;\n}\n\n/* This returns 0xFF if a < b else 0x00, but does so in a constant time\n   fashion */\nstatic uint8_t Cryptography_constant_time_lt(uint8_t a, uint8_t b) {\n    a -= b;\n    return Cryptography_DUPLICATE_MSB_TO_ALL(a);\n}\n\nuint8_t Cryptography_check_pkcs7_padding(const uint8_t *data,\n                                         uint8_t block_len) {\n    uint8_t i;\n    uint8_t pad_size = data[block_len - 1];\n    uint8_t mismatch = 0;\n    for (i = 0; i < block_len; i++) {\n        unsigned int mask = Cryptography_constant_time_lt(i, pad_size);\n        uint8_t b = data[block_len - 1 - i];\n        mismatch |= (mask & (pad_size ^ b));\n    }\n\n    /* Check to make sure the pad_size was within the valid range. */\n    mismatch |= ~Cryptography_constant_time_lt(0, pad_size);\n    mismatch |= Cryptography_constant_time_lt(block_len, pad_size);\n\n    /* Make sure any bits set are copied to the lowest bit */\n    mismatch |= mismatch >> 4;\n    mismatch |= mismatch >> 2;\n    mismatch |= mismatch >> 1;\n    /* Now check the low bit to see if it's set */\n    return (mismatch & 1) == 0;\n}\n\"\"\",\n    ext_package=\"cryptography\",\n)\n\n\nclass PKCS7(object):\n    def __init__(self, block_size):\n        if not (0 <= block_size < 256):\n            raise ValueError(\"block_size must be in range(0, 256)\")\n\n        if block_size % 8 != 0:\n            raise ValueError(\"block_size must be a multiple of 8\")\n\n        self.block_size = block_size\n\n    def padder(self):\n        return _PKCS7PaddingContext(self.block_size)\n\n    def unpadder(self):\n        return _PKCS7UnpaddingContext(self.block_size)\n\n\n@utils.register_interface(interfaces.PaddingContext)\nclass _PKCS7PaddingContext(object):\n    def __init__(self, block_size):\n        self.block_size = block_size\n        # TODO: more copies than necessary, we should use zero-buffer (#193)\n        self._buffer = b\"\"\n\n    def update(self, data):\n        if self._buffer is None:\n            raise ValueError(\"Context was already finalized\")\n\n        if isinstance(data, six.text_type):\n            raise TypeError(\"Unicode-objects must be encoded before padding\")\n\n        self._buffer += data\n\n        finished_blocks = len(self._buffer) // (self.block_size // 8)\n\n        result = self._buffer[:finished_blocks * (self.block_size // 8)]\n        self._buffer = self._buffer[finished_blocks * (self.block_size // 8):]\n\n        return result\n\n    def finalize(self):\n        if self._buffer is None:\n            raise ValueError(\"Context was already finalized\")\n\n        pad_size = self.block_size // 8 - len(self._buffer)\n        result = self._buffer + six.int2byte(pad_size) * pad_size\n        self._buffer = None\n        return result\n\n\n@utils.register_interface(interfaces.PaddingContext)\nclass _PKCS7UnpaddingContext(object):\n    def __init__(self, block_size):\n        self.block_size = block_size\n        # TODO: more copies than necessary, we should use zero-buffer (#193)\n        self._buffer = b\"\"\n\n    def update(self, data):\n        if self._buffer is None:\n            raise ValueError(\"Context was already finalized\")\n\n        if isinstance(data, six.text_type):\n            raise TypeError(\"Unicode-objects must be encoded before unpadding\")\n\n        self._buffer += data\n\n        finished_blocks = max(\n            len(self._buffer) // (self.block_size // 8) - 1,\n            0\n        )\n\n        result = self._buffer[:finished_blocks * (self.block_size // 8)]\n        self._buffer = self._buffer[finished_blocks * (self.block_size // 8):]\n\n        return result\n\n    def finalize(self):\n        if self._buffer is None:\n            raise ValueError(\"Context was already finalized\")\n\n        if len(self._buffer) != self.block_size // 8:\n            raise ValueError(\"Invalid padding bytes\")\n\n        valid = _lib.Cryptography_check_pkcs7_padding(\n            self._buffer, self.block_size // 8\n        )\n\n        if not valid:\n            raise ValueError(\"Invalid padding bytes\")\n\n        pad_size = six.indexbytes(self._buffer, -1)\n        res = self._buffer[:-pad_size]\n        self._buffer = None\n        return res\n", "path": "cryptography/hazmat/primitives/padding.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\nimport sys\n\nimport cffi\n\nimport six\n\nfrom cryptography.hazmat.bindings.utils import _create_modulename\n\nTYPES = \"\"\"\nuint8_t Cryptography_constant_time_bytes_eq(uint8_t *, size_t, uint8_t *,\n                                            size_t);\n\"\"\"\n\nFUNCTIONS = \"\"\"\nuint8_t Cryptography_constant_time_bytes_eq(uint8_t *a, size_t len_a,\n                                            uint8_t *b, size_t len_b) {\n    size_t i = 0;\n    uint8_t mismatch = 0;\n    if (len_a != len_b) {\n        return 0;\n    }\n    for (i = 0; i < len_a; i++) {\n        mismatch |= a[i] ^ b[i];\n    }\n\n    /* Make sure any bits set are copied to the lowest bit */\n    mismatch |= mismatch >> 4;\n    mismatch |= mismatch >> 2;\n    mismatch |= mismatch >> 1;\n    /* Now check the low bit to see if it's set */\n    return (mismatch & 1) == 0;\n}\n\"\"\"\n\n_ffi = cffi.FFI()\n_ffi.cdef(TYPES)\n_lib = _ffi.verify(\n    source=FUNCTIONS,\n    modulename=_create_modulename([TYPES], FUNCTIONS, sys.version),\n    ext_package=\"cryptography\",\n)\n\n\ndef bytes_eq(a, b):\n    if isinstance(a, six.text_type) or isinstance(b, six.text_type):\n        raise TypeError(\"Unicode-objects must be encoded before comparing\")\n\n    return _lib.Cryptography_constant_time_bytes_eq(a, len(a), b, len(b)) == 1\n", "path": "cryptography/hazmat/primitives/constant_time.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 sys\n\nimport cffi\n\nimport six\n\nfrom cryptography import utils\nfrom cryptography.hazmat.bindings.utils import _create_modulename\nfrom cryptography.hazmat.primitives import interfaces\n\n\nTYPES = \"\"\"\nuint8_t Cryptography_check_pkcs7_padding(const uint8_t *, uint8_t);\n\"\"\"\n\nFUNCTIONS = \"\"\"\n/* Returns the value of the input with the most-significant-bit copied to all\n   of the bits. */\nstatic uint8_t Cryptography_DUPLICATE_MSB_TO_ALL(uint8_t a) {\n    return (1 - (a >> (sizeof(uint8_t) * 8 - 1))) - 1;\n}\n\n/* This returns 0xFF if a < b else 0x00, but does so in a constant time\n   fashion */\nstatic uint8_t Cryptography_constant_time_lt(uint8_t a, uint8_t b) {\n    a -= b;\n    return Cryptography_DUPLICATE_MSB_TO_ALL(a);\n}\n\nuint8_t Cryptography_check_pkcs7_padding(const uint8_t *data,\n                                         uint8_t block_len) {\n    uint8_t i;\n    uint8_t pad_size = data[block_len - 1];\n    uint8_t mismatch = 0;\n    for (i = 0; i < block_len; i++) {\n        unsigned int mask = Cryptography_constant_time_lt(i, pad_size);\n        uint8_t b = data[block_len - 1 - i];\n        mismatch |= (mask & (pad_size ^ b));\n    }\n\n    /* Check to make sure the pad_size was within the valid range. */\n    mismatch |= ~Cryptography_constant_time_lt(0, pad_size);\n    mismatch |= Cryptography_constant_time_lt(block_len, pad_size);\n\n    /* Make sure any bits set are copied to the lowest bit */\n    mismatch |= mismatch >> 4;\n    mismatch |= mismatch >> 2;\n    mismatch |= mismatch >> 1;\n    /* Now check the low bit to see if it's set */\n    return (mismatch & 1) == 0;\n}\n\"\"\"\n\n_ffi = cffi.FFI()\n_ffi.cdef(TYPES)\n_lib = _ffi.verify(\n    source=FUNCTIONS,\n    modulename=_create_modulename([TYPES], FUNCTIONS, sys.version),\n    ext_package=\"cryptography\",\n)\n\n\nclass PKCS7(object):\n    def __init__(self, block_size):\n        if not (0 <= block_size < 256):\n            raise ValueError(\"block_size must be in range(0, 256)\")\n\n        if block_size % 8 != 0:\n            raise ValueError(\"block_size must be a multiple of 8\")\n\n        self.block_size = block_size\n\n    def padder(self):\n        return _PKCS7PaddingContext(self.block_size)\n\n    def unpadder(self):\n        return _PKCS7UnpaddingContext(self.block_size)\n\n\n@utils.register_interface(interfaces.PaddingContext)\nclass _PKCS7PaddingContext(object):\n    def __init__(self, block_size):\n        self.block_size = block_size\n        # TODO: more copies than necessary, we should use zero-buffer (#193)\n        self._buffer = b\"\"\n\n    def update(self, data):\n        if self._buffer is None:\n            raise ValueError(\"Context was already finalized\")\n\n        if isinstance(data, six.text_type):\n            raise TypeError(\"Unicode-objects must be encoded before padding\")\n\n        self._buffer += data\n\n        finished_blocks = len(self._buffer) // (self.block_size // 8)\n\n        result = self._buffer[:finished_blocks * (self.block_size // 8)]\n        self._buffer = self._buffer[finished_blocks * (self.block_size // 8):]\n\n        return result\n\n    def finalize(self):\n        if self._buffer is None:\n            raise ValueError(\"Context was already finalized\")\n\n        pad_size = self.block_size // 8 - len(self._buffer)\n        result = self._buffer + six.int2byte(pad_size) * pad_size\n        self._buffer = None\n        return result\n\n\n@utils.register_interface(interfaces.PaddingContext)\nclass _PKCS7UnpaddingContext(object):\n    def __init__(self, block_size):\n        self.block_size = block_size\n        # TODO: more copies than necessary, we should use zero-buffer (#193)\n        self._buffer = b\"\"\n\n    def update(self, data):\n        if self._buffer is None:\n            raise ValueError(\"Context was already finalized\")\n\n        if isinstance(data, six.text_type):\n            raise TypeError(\"Unicode-objects must be encoded before unpadding\")\n\n        self._buffer += data\n\n        finished_blocks = max(\n            len(self._buffer) // (self.block_size // 8) - 1,\n            0\n        )\n\n        result = self._buffer[:finished_blocks * (self.block_size // 8)]\n        self._buffer = self._buffer[finished_blocks * (self.block_size // 8):]\n\n        return result\n\n    def finalize(self):\n        if self._buffer is None:\n            raise ValueError(\"Context was already finalized\")\n\n        if len(self._buffer) != self.block_size // 8:\n            raise ValueError(\"Invalid padding bytes\")\n\n        valid = _lib.Cryptography_check_pkcs7_padding(\n            self._buffer, self.block_size // 8\n        )\n\n        if not valid:\n            raise ValueError(\"Invalid padding bytes\")\n\n        pad_size = six.indexbytes(self._buffer, -1)\n        res = self._buffer[:-pad_size]\n        self._buffer = None\n        return res\n", "path": "cryptography/hazmat/primitives/padding.py"}]}