1# SPDX-FileCopyrightText: 2014 Legrandin <helderijs@gmail.com>
2# SPDX-License-Identifier: BSD-2-Clause
3
4"""
5Ciphertext Block Chaining (CBC) mode.
6"""
7
8from __future__ import annotations
9
10from typing import Optional, Union, overload
11
12__all__ = ["CbcMode"]
13from Crypto.Cipher._state_machine import Method
14from Crypto.Random import get_random_bytes
15from Crypto.Util._raw_api import (
16 SmartPointer,
17 VoidPointer,
18 c_size_t,
19 c_uint8_ptr_len,
20 c_uint8_ptr_out,
21 create_output_buffer,
22 get_raw_buffer,
23 is_writeable_buffer,
24 load_pycryptodome_raw_lib,
25)
26from Crypto.Util._typing import Buffer
27
28raw_cbc_lib = load_pycryptodome_raw_lib(
29 "Crypto.Cipher._raw_cbc",
30 """
31 int CBC_start_operation(void *cipher,
32 const uint8_t iv[],
33 size_t iv_len,
34 void **pResult);
35 int CBC_encrypt(void *cbcState,
36 const uint8_t *in,
37 uint8_t *out,
38 size_t data_len);
39 int CBC_decrypt(void *cbcState,
40 const uint8_t *in,
41 uint8_t *out,
42 size_t data_len);
43 int CBC_stop_operation(void *state);
44 """,
45)
46
47
48class CbcMode:
49 """*Cipher-Block Chaining (CBC)*.
50
51 Each of the ciphertext blocks depends on the current
52 and all previous plaintext blocks.
53
54 An Initialization Vector (*IV*) is required.
55
56 See `NIST SP800-38A`_ , Section 6.2 .
57
58 .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
59 """
60
61 def __init__(self, block_cipher: SmartPointer, iv: Buffer) -> None:
62 """Create a new block cipher, configured in CBC mode.
63
64 Args:
65 block_cipher (C pointer):
66 A smart pointer to the low-level block cipher instance.
67
68 iv (bytes/bytearray/memoryview):
69 The initialization vector to use for encryption or decryption.
70 It is as long as the cipher block.
71
72 **The IV must be unpredictable**. Ideally it is picked randomly.
73
74 Reusing the *IV* for encryptions performed with the same key
75 compromises confidentiality.
76 """
77
78 state = VoidPointer()
79 iv_ptr, iv_len = c_uint8_ptr_len(iv)
80 result = raw_cbc_lib.CBC_start_operation(
81 block_cipher.get(), iv_ptr, c_size_t(iv_len), state.address_of()
82 )
83 if result:
84 raise ValueError("Error %d while instantiating the CBC mode" % result)
85
86 # Ensure that object disposal of this Python object will (eventually)
87 # free the memory allocated by the raw library for the cipher mode
88 self._state = SmartPointer(state.get(), raw_cbc_lib.CBC_stop_operation)
89
90 # Memory allocated for the underlying block cipher is now owed
91 # by the cipher mode
92 block_cipher.release()
93
94 self.block_size = len(iv)
95 """The block size of the underlying cipher, in bytes."""
96
97 self.iv = bytes(iv)
98 """The Initialization Vector originally used to create the object.
99 The value does not change."""
100
101 self.IV = self.iv
102 """Alias for `iv`"""
103
104 self._next = [Method.ENCRYPT, Method.DECRYPT]
105
106 @overload
107 def encrypt(self, plaintext: Buffer) -> bytes: ...
108
109 @overload
110 def encrypt(self, plaintext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
111
112 def encrypt(
113 self, plaintext: Buffer, output: Optional[Union[bytearray, memoryview]] = None
114 ) -> Optional[bytes]:
115 """Encrypt data with the key and the parameters set at initialization.
116
117 A cipher object is stateful: once you have encrypted a message
118 you cannot encrypt (or decrypt) another message using the same
119 object.
120
121 The data to encrypt can be broken up in two or
122 more pieces and `encrypt` can be called multiple times.
123
124 That is, the statement:
125
126 >>> c.encrypt(a) + c.encrypt(b)
127
128 is equivalent to:
129
130 >>> c.encrypt(a+b)
131
132 That also means that you cannot reuse an object for encrypting
133 or decrypting other data with the same key.
134
135 This function does not add any padding to the plaintext.
136
137 Args:
138 plaintext (bytes/bytearray/memoryview):
139 The piece of data to encrypt.
140 Its length must be multiple of the cipher block size.
141 Keyword Args:
142 output (bytearray/memoryview):
143 The location where the ciphertext must be written to.
144 If ``None``, the ciphertext is returned.
145 Returns:
146 If ``output`` is ``None``, the ciphertext is returned as ``bytes``.
147 Otherwise, ``None``.
148 """
149
150 if Method.ENCRYPT not in self._next:
151 raise TypeError("encrypt() cannot be called after decrypt()")
152 self._next = [Method.ENCRYPT]
153
154 if output is None:
155 ciphertext = create_output_buffer(len(plaintext))
156 else:
157 ciphertext = output
158
159 if not is_writeable_buffer(output):
160 raise TypeError("output must be a bytearray or a writeable memoryview")
161
162 if len(plaintext) != len(output):
163 raise ValueError("output must have the same length as the input (%d bytes)" % len(plaintext))
164
165 with c_uint8_ptr_out(ciphertext) as ciphertext_ptr:
166 plaintext_ptr, plaintext_len = c_uint8_ptr_len(plaintext)
167 # Check the lengths of the buffers that C code gets
168 if len(ciphertext_ptr) != plaintext_len:
169 raise ValueError("output must have the same length as the input (%d bytes)" % plaintext_len)
170 result = raw_cbc_lib.CBC_encrypt(
171 self._state.get(), plaintext_ptr, ciphertext_ptr, c_size_t(plaintext_len)
172 )
173 if result:
174 if result == 3:
175 raise ValueError("Data must be padded to %d byte boundary in CBC mode" % self.block_size)
176 raise ValueError("Error %d while encrypting in CBC mode" % result)
177
178 if output is None:
179 return get_raw_buffer(ciphertext)
180 else:
181 return None
182
183 @overload
184 def decrypt(self, ciphertext: Buffer) -> bytes: ...
185
186 @overload
187 def decrypt(self, ciphertext: Buffer, output: Union[bytearray, memoryview]) -> None: ...
188
189 def decrypt(
190 self, ciphertext: Buffer, output: Optional[Union[bytearray, memoryview]] = None
191 ) -> Optional[bytes]:
192 """Decrypt data with the key and the parameters set at initialization.
193
194 A cipher object is stateful: once you have decrypted a message
195 you cannot decrypt (or encrypt) another message with the same
196 object.
197
198 The data to decrypt can be broken up in two or
199 more pieces and `decrypt` can be called multiple times.
200
201 That is, the statement:
202
203 >>> c.decrypt(a) + c.decrypt(b)
204
205 is equivalent to:
206
207 >>> c.decrypt(a+b)
208
209 This function does not remove any padding from the plaintext.
210
211 Args:
212 ciphertext (bytes/bytearray/memoryview):
213 The piece of data to decrypt.
214 Its length must be multiple of the cipher block size.
215 Keyword Args:
216 output (bytearray/memoryview):
217 The location where the plaintext must be written to.
218 If ``None``, the plaintext is returned.
219 Returns:
220 If ``output`` is ``None``, the plaintext is returned as ``bytes``.
221 Otherwise, ``None``.
222 """
223
224 if Method.DECRYPT not in self._next:
225 raise TypeError("decrypt() cannot be called after encrypt()")
226 self._next = [Method.DECRYPT]
227
228 if output is None:
229 plaintext = create_output_buffer(len(ciphertext))
230 else:
231 plaintext = output
232
233 if not is_writeable_buffer(output):
234 raise TypeError("output must be a bytearray or a writeable memoryview")
235
236 if len(ciphertext) != len(output):
237 raise ValueError("output must have the same length as the input (%d bytes)" % len(plaintext))
238
239 with c_uint8_ptr_out(plaintext) as plaintext_ptr:
240 ciphertext_ptr, ciphertext_len = c_uint8_ptr_len(ciphertext)
241 # Check the lengths of the buffers that C code gets
242 if len(plaintext_ptr) != ciphertext_len:
243 raise ValueError("output must have the same length as the input (%d bytes)" % ciphertext_len)
244 result = raw_cbc_lib.CBC_decrypt(
245 self._state.get(), ciphertext_ptr, plaintext_ptr, c_size_t(ciphertext_len)
246 )
247 if result:
248 if result == 3:
249 raise ValueError("Data must be padded to %d byte boundary in CBC mode" % self.block_size)
250 raise ValueError("Error %d while decrypting in CBC mode" % result)
251
252 if output is None:
253 return get_raw_buffer(plaintext)
254 else:
255 return None
256
257
258def _create_cbc_cipher(factory, **kwargs):
259 """Instantiate a cipher object that performs CBC encryption/decryption.
260
261 Args:
262 factory (module):
263 The underlying block cipher, a module from ``Crypto.Cipher``.
264
265 Keyword Args:
266 iv (bytes/bytearray/memoryview):
267 The IV to use for CBC.
268
269 IV (bytes/bytearray/memoryview):
270 Alias for ``iv``.
271
272 Any other keyword will be passed to the underlying block cipher.
273 See the relevant documentation for details (at least ``key`` will need
274 to be present).
275 """
276
277 cipher_state = factory._create_base_cipher(kwargs)
278 iv = kwargs.pop("IV", None)
279 IV = kwargs.pop("iv", None)
280
281 if (iv, IV) == (None, None):
282 iv = get_random_bytes(factory.block_size)
283 if iv is not None:
284 if IV is not None:
285 raise TypeError("You must either use 'iv' or 'IV', not both")
286 else:
287 iv = IV
288
289 if len(iv) != factory.block_size:
290 raise ValueError("Incorrect IV length (it must be %d bytes long)" % factory.block_size)
291
292 if kwargs:
293 raise TypeError("Unknown parameters for CBC: %s" % str(kwargs))
294
295 return CbcMode(cipher_state, iv)