Debian Codegraph @

Doc/src/cipher/classic.rst

raw
1 .. _classic_cipher_modes:
2
3 Classic modes of operation for symmetric block ciphers
4 ======================================================
5
6 A block cipher uses a symmetric key to encrypt data of fixed and very short length
7 (the *block size*), such as 16 bytes for AES.
8 In order to cope with data of arbitrary length, the cipher must be
9 combined with a *mode of operation*.
10
11 You create a cipher object with the :func:`new` function
12 in the relevant module under ``Crypto.Cipher``:
13
14 1. the first parameter is always the cryptographic key (a byte string)
15 2. the second parameter is always the constant that selects the desired
16 mode of operation
17
18 Constants for each mode of operation are defined at the module level for each algorithm.
19 Their name starts with ``MODE_``, for instance :const:`Crypto.Cipher.AES.MODE_CBC`.
20 Note that not all ciphers support all modes.
21
22 For instance::
23
24 >>> from Crypto.Cipher import AES
25 >>> from Crypto.Random import get_random_bytes
26 >>>
27 >>> key = get_random_bytes(16)
28 >>> cipher = AES.new(key, AES.MODE_CBC)
29 >>>
30 >>> # You can now use use cipher to encrypt or decrypt...
31
32 The state machine for a cipher configured with a classic mode is:
33
34 .. figure:: simple_mode.png
35 :align: center
36 :figwidth: 50%
37
38 Generic state diagram for a cipher object
39
40 What follows is a list of classic modes of operation: they all provide confidentiality
41 but not data integrity (unlike modern AEAD modes, which are described in :doc:`another section <modern>`).
42
43 .. _ecb_mode:
44
45 ECB mode
46 --------
47 `Electronic CodeBook <https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_Codebook_.28ECB.29>`_.
48 The most basic but also the weakest mode of operation.
49 Each block of plaintext is encrypted independently of any other block.
50
51 .. warning::
52 The ECB mode should not be used because it is `semantically insecure <https://en.wikipedia.org/wiki/Semantic_security>`_.
53 For one, it exposes correlation between blocks.
54
55 The :func:`new` function at the module level under ``Crypto.Cipher`` instantiates
56 a new ECB cipher object for the relevant base algorithm.
57 In the following definition, ``<algorithm>`` could be ``AES``:
58
59 .. function:: Crypto.Cipher.<algorithm>.new(key, mode)
60
61 Create a new ECB object, using <algorithm> as the base block cipher.
62
63 :param bytes key: the cryptographic key
64 :param mode: the constant ``Crypto.Cipher.<algorithm>.MODE_ECB``
65 :return: an ECB cipher object
66
67 The method :func:`encrypt` (and likewise :func:`decrypt`) of an ECB cipher object
68 expects data to have length multiple of the block size (e.g. 16 bytes for AES).
69 You might need to use :mod:`Crypto.Util.Padding` to align the plaintext to the right boundary.
70
71 .. _cbc_mode:
72
73 CBC mode
74 --------
75 `Ciphertext Block Chaining <https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29>`_,
76 defined in `NIST SP 800-38A, section 6.2 <http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf>`_.
77 It is a mode of operation where each plaintext block
78 gets XOR-ed with the previous ciphertext block prior to encryption.
79
80 The :func:`new` function at the module level under ``Crypto.Cipher`` instantiates
81 a new CBC cipher object for the relevant base algorithm.
82 In the following definition, ``<algorithm>`` could be ``AES``:
83
84 .. function:: Crypto.Cipher.<algorithm>.new(key, mode, *, iv=None)
85
86 Create a new CBC object, using <algorithm> as the base block cipher.
87
88 :param bytes key: the cryptographic key
89 :param mode: the constant ``Crypto.Cipher.<algorithm>.MODE_CBC``
90 :param bytes iv: the *Initialization Vector*. A piece of data unpredictable to adversaries.
91 It is as long as the block size (e.g. 16 bytes for AES).
92 If not present, the library creates a random IV value.
93 :return: a CBC cipher object
94
95 The method :func:`encrypt` (and likewise :func:`decrypt`) of a CBC cipher object
96 expects data to have length multiple of the block size (e.g. 16 bytes for AES).
97 You might need to use :mod:`Crypto.Util.Padding` to align the plaintext to the right boundary.
98
99 A CBC cipher object has a read-only attribute :attr:`iv`, holding the
100 *Initialization Vector* (*bytes*).
101
102 Example (encryption)::
103
104 >>> import json
105 >>> from base64 import b64encode
106 >>> from Crypto.Cipher import AES
107 >>> from Crypto.Util.Padding import pad
108 >>> from Crypto.Random import get_random_bytes
109 >>>
110 >>> data = b"secret"
111 >>> key = get_random_bytes(16)
112 >>> cipher = AES.new(key, AES.MODE_CBC)
113 >>> ct_bytes = cipher.encrypt(pad(data, AES.block_size))
114 >>> iv = b64encode(cipher.iv).decode('utf-8')
115 >>> ct = b64encode(ct_bytes).decode('utf-8')
116 >>> result = json.dumps({'iv':iv, 'ciphertext':ct})
117 >>> print(result)
118 '{"iv": "bWRHdzkzVDFJbWNBY0EwSmQ1UXFuQT09", "ciphertext": "VDdxQVo3TFFCbXIzcGpYa1lJbFFZQT09"}'
119
120 Example (decryption)::
121
122 >>> import json
123 >>> from base64 import b64decode
124 >>> from Crypto.Cipher import AES
125 >>> from Crypto.Util.Padding import unpad
126 >>>
127 >>> # We assume that the key was securely shared beforehand
128 >>> try:
129 >>> b64 = json.loads(json_input)
130 >>> iv = b64decode(b64['iv'])
131 >>> ct = b64decode(b64['ciphertext'])
132 >>> cipher = AES.new(key, AES.MODE_CBC, iv)
133 >>> pt = unpad(cipher.decrypt(ct), AES.block_size)
134 >>> print("The message was: ", pt)
135 >>> except (ValueError, KeyError):
136 >>> print("Incorrect decryption")
137
138 .. _ctr_mode:
139
140 CTR mode
141 --------
142 `CounTeR mode <https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Counter_.28CTR.29>`_,
143 defined in `NIST SP 800-38A, section 6.5 and Appendix B <http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf>`_.
144 This mode turns the block cipher into a stream cipher.
145 Each byte of plaintext is XOR-ed with a byte taken from a *keystream*: the result is the ciphertext.
146 The *keystream* is generated by encrypting a sequence of *counter blocks* with ECB.
147
148 .. figure:: ctr_mode.png
149 :align: center
150
151 A *counter block* is exactly as long as the cipher block size (e.g. 16 bytes for AES).
152 It consists of the concatenation of two pieces:
153
154 1. a fixed **nonce**, set at initialization.
155 2. a variable **counter**, which gets increased by 1 for any subsequent counter block.
156 The counter is big endian encoded.
157
158 The :func:`new` function at the module level under ``Crypto.Cipher`` instantiates
159 a new CTR cipher object for the relevant base algorithm.
160 In the following definition, ``<algorithm>`` could be ``AES``:
161
162 .. function:: Crypto.Cipher.<algorithm>.new(key, mode, *, nonce=None, initial_value=None, counter=None)
163
164 Create a new CTR object, using <algorithm> as the base block cipher.
165
166 :param bytes key: the cryptographic key
167 :param mode: the constant ``Crypto.Cipher.<algorithm>.MODE_CTR``
168 :param bytes nonce: the value of the fixed nonce.
169 It must be unique for the combination message/key.
170 Its length varies from 0 to the block size minus 1.
171 If not present, the library creates a random nonce of length equal to block size/2.
172 :param initial_value: the value of the counter for the first counter block.
173 It can be either an integer or *bytes* (which is the same integer, just big endian encoded).
174 If not specified, the counter starts at 0.
175 :type initial_value: integer or bytes
176 :param counter: a custom counter object created with :func:`Crypto.Util.Counter.new`.
177 This allows the definition of a more complex counter block.
178 :return: a CTR cipher object
179
180 The methods :func:`encrypt` and :func:`decrypt` of a CTR cipher object
181 accept data of any length (i.e. padding is not needed).
182 Both raise an ``OverflowError`` exception as soon as the counter wraps around to repeat the original value.
183
184 The CTR cipher object has a read-only attribute :attr:`nonce` (*bytes*).
185
186 Example (encryption)::
187
188 >>> import json
189 >>> from base64 import b64encode
190 >>> from Crypto.Cipher import AES
191 >>> from Crypto.Random import get_random_bytes
192 >>>
193 >>> data = b"secret"
194 >>> key = get_random_bytes(16)
195 >>> cipher = AES.new(key, AES.MODE_CTR)
196 >>> ct_bytes = cipher.encrypt(data)
197 >>> nonce = b64encode(cipher.nonce).decode('utf-8')
198 >>> ct = b64encode(ct_bytes).decode('utf-8')
199 >>> result = json.dumps({'nonce':nonce, 'ciphertext':ct})
200 >>> print(result)
201 {"nonce": "XqP8WbylRt0=", "ciphertext": "Mie5lqje"}
202
203 Example (decryption)::
204
205 >>> import json
206 >>> from base64 import b64decode
207 >>> from Crypto.Cipher import AES
208 >>>
209 >>> # We assume that the key was securely shared beforehand
210 >>> try:
211 >>> b64 = json.loads(json_input)
212 >>> nonce = b64decode(b64['nonce'])
213 >>> ct = b64decode(b64['ciphertext'])
214 >>> cipher = AES.new(key, AES.MODE_CTR, nonce=nonce)
215 >>> pt = cipher.decrypt(ct)
216 >>> print("The message was: ", pt)
217 >>> except (ValueError, KeyError):
218 >>> print("Incorrect decryption")
219
220 .. _cfb_mode:
221
222 CFB mode
223 --------
224 `Cipher FeedBack <https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_Codebook_.28ECB.29>`_,
225 defined in `NIST SP 800-38A, section 6.3 <http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf>`_.
226 It is a mode of operation which turns the block cipher into a stream cipher.
227 Each byte of plaintext is XOR-ed with a byte taken from a *keystream*: the result is the ciphertext.
228
229 The *keystream* is obtained on a per-segment basis: the plaintext is broken up in
230 segments (from 1 byte up to the size of a block). Then, for each segment,
231 the keystream is obtained by encrypting with the block cipher the last piece of
232 ciphertext produced so far - possibly backfilled with the *Initialization Vector*,
233 if not enough ciphertext is available yet.
234
235 The :func:`new` function at the module level under ``Crypto.Cipher`` instantiates
236 a new CFB cipher object for the relevant base algorithm.
237 In the following definition, ``<algorithm>`` could be ``AES``:
238
239 .. function:: Crypto.Cipher.<algorithm>.new(key, mode, *, iv=None, segment_size=8)
240
241 Create a new CFB object, using <algorithm> as the base block cipher.
242
243 :param bytes key: the cryptographic key
244 :param mode: the constant ``Crypto.Cipher.<algorithm>.MODE_CFB``
245 :param bytes iv: the *Initialization Vector*.
246 It must be unique for the combination message/key.
247 It is as long as the block size (e.g. 16 bytes for AES).
248 If not present, the library creates a random IV.
249 :param integer segment_size: the number of **bits** (not bytes!) the plaintext and the
250 ciphertext are segmented in (default if not specified: 8 bits = 1 byte).
251 :return: a CFB cipher object
252
253 The methods :func:`encrypt` and :func:`decrypt` of a CFB cipher object
254 accept data of any length (i.e. padding is not needed).
255
256 The CFB cipher object has a read-only attribute :attr:`iv` (*bytes*), holding
257 the Initialization Vector.
258
259 Example (encryption)::
260
261 >>> import json
262 >>> from base64 import b64encode
263 >>> from Crypto.Cipher import AES
264 >>> from Crypto.Random import get_random_bytes
265 >>>
266 >>> data = b"secret"
267 >>> key = get_random_bytes(16)
268 >>> cipher = AES.new(key, AES.MODE_CFB)
269 >>> ct_bytes = cipher.encrypt(data)
270 >>> iv = b64encode(cipher.iv).decode('utf-8')
271 >>> ct = b64encode(ct_bytes).decode('utf-8')
272 >>> result = json.dumps({'iv':iv, 'ciphertext':ct})
273 >>> print(result)
274 {"iv": "VoamO23kFSOZcK1O2WiCDQ==", "ciphertext": "f8jciJ8/"}
275
276 Example (decryption)::
277
278 >>> import json
279 >>> from base64 import b64decode
280 >>> from Crypto.Cipher import AES
281 >>>
282 >>> # We assume that the key was securely shared beforehand
283 >>> try:
284 >>> b64 = json.loads(json_input)
285 >>> iv = b64decode(b64['iv'])
286 >>> ct = b64decode(b64['ciphertext'])
287 >>> cipher = AES.new(key, AES.MODE_CFB, iv=iv)
288 >>> pt = cipher.decrypt(ct)
289 >>> print("The message was: ", pt)
290 >>> except (ValueError, KeyError):
291 >>> print("Incorrect decryption")
292
293 .. _ofb_mode:
294
295 OFB mode
296 --------
297 `Output FeedBack <https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Output_Feedback_.28OFB.29>`_,
298 defined in `NIST SP 800-38A, section 6.4 <http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf>`_.
299 It is another mode that leads to a stream cipher.
300 Each byte of plaintext is XOR-ed with a byte taken from a *keystream*: the result is the ciphertext.
301 The *keystream* is obtained by recursively encrypting the *Initialization Vector*.
302
303 The :func:`new` function at the module level under ``Crypto.Cipher`` instantiates
304 a new OFB cipher object for the relevant base algorithm.
305 In the following definition, ``<algorithm>`` could be ``AES``:
306
307 .. function:: Crypto.Cipher.<algorithm>.new(key, mode, *, iv=None)
308
309 Create a new OFB object, using <algorithm> as the base block cipher.
310
311 :param bytes key: the cryptographic key
312 :param mode: the constant ``Crypto.Cipher.<algorithm>.MODE_OFB``
313 :param bytes iv: the *Initialization Vector*.
314 It must be unique for the combination message/key.
315 It is as long as the block size (e.g. 16 bytes for AES).
316 If not present, the library creates a random IV.
317 :return: an OFB cipher object
318
319 The methods :func:`encrypt` and :func:`decrypt` of an OFB cipher object
320 accept data of any length (i.e. padding is not needed).
321
322 The OFB cipher object has a read-only attribute :attr:`iv` (*bytes*), holding
323 the Initialization Vector.
324
325 Example (encryption)::
326
327 >>> import json
328 >>> from base64 import b64encode
329 >>> from Crypto.Cipher import AES
330 >>> from Crypto.Random import get_random_bytes
331 >>>
332 >>> data = b"secret"
333 >>> key = get_random_bytes(16)
334 >>> cipher = AES.new(key, AES.MODE_OFB)
335 >>> ct_bytes = cipher.encrypt(data)
336 >>> iv = b64encode(cipher.iv).decode('utf-8')
337 >>> ct = b64encode(ct_bytes).decode('utf-8')
338 >>> result = json.dumps({'iv':iv, 'ciphertext':ct})
339 >>> print(result)
340 {"iv": "NUuRJbL0UMp8+UMCk2/vQA==", "ciphertext": "XGVGc1Gw"}
341
342 Example (decryption)::
343
344 >>> import json
345 >>> from base64 import b64decode
346 >>> from Crypto.Cipher import AES
347 >>>
348 >>> # We assume that the key was securely shared beforehand
349 >>> try:
350 >>> b64 = json.loads(json_input)
351 >>> iv = b64decode(b64['iv'])
352 >>> ct = b64decode(b64['ciphertext'])
353 >>> cipher = AES.new(key, AES.MODE_OFB, iv=iv)
354 >>> pt = cipher.decrypt(ct)
355 >>> print("The message was: ", pt)
356 >>> except (ValueError, KeyError):
357 >>> print("Incorrect decryption")
358
359 .. _openpgp_mode:
360
361 OpenPGP mode
362 ------------
363 Constant: ``Crypto.Cipher.<cipher>.MODE_OPENPGP``.
364
365 OpenPGP (defined in `RFC4880 <https://tools.ietf.org/html/rfc4880>`_).
366 A variant of CFB, with two differences:
367
368 1. The first invocation to the :func:`encrypt` method
369 returns the encrypted IV concatenated to the first chunk
370 of ciphertext (as opposed to the ciphertext only).
371 The encrypted IV is as long as the block size plus 2 more bytes.
372
373 2. When the cipher object is intended for decryption,
374 the parameter ``iv`` to :func:`new` is the encrypted IV
375 (and not the IV, which is still the case for encryption).
376
377 Like for CTR, an OpenPGP cipher object has a read-only attribute :attr:`iv`.
378