Debian Codegraph @

lib/Crypto/Cipher/_mode_eax.py

raw symbols SCIP
1 # ===================================================================
2 #
3 # Copyright (c) 2014, Legrandin <[email protected]>
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
8 # are met:
9 #
10 # 1. Redistributions of source code must retain the above copyright
11 # notice, this list of conditions and the following disclaimer.
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in
14 # the documentation and/or other materials provided with the
15 # distribution.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21 # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 # POSSIBILITY OF SUCH DAMAGE.
29 # ===================================================================
30
31 """
32 EAX mode.
33 """
34
35 __all__ = ['EaxMode']
36
37 import struct
38 from binascii import unhexlify
39
40 from Crypto.Util.py3compat import byte_string, bord, _copy_bytes
41
42 from Crypto.Util._raw_api import is_buffer
43
44 from Crypto.Util.strxor import strxor
45 from Crypto.Util.number import long_to_bytes, bytes_to_long
46
47 from Crypto.Hash import CMAC, BLAKE2s
48 from Crypto.Random import get_random_bytes
49
50
51 class EaxMode(object):
52 """*EAX* mode.
53
54 This is an Authenticated Encryption with Associated Data
55 (`AEAD`_) mode. It provides both confidentiality and authenticity.
56
57 The header of the message may be left in the clear, if needed,
58 and it will still be subject to authentication.
59
60 The decryption step tells the receiver if the message comes
61 from a source that really knowns the secret key.
62 Additionally, decryption detects if any part of the message -
63 including the header - has been modified or corrupted.
64
65 This mode requires a *nonce*.
66
67 This mode is only available for ciphers that operate on 64 or
68 128 bits blocks.
69
70 There are no official standards defining EAX.
71 The implementation is based on `a proposal`__ that
72 was presented to NIST.
73
74 .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html
75 .. __: http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/eax/eax-spec.pdf
76
77 :undocumented: __init__
78 """
79
80 def __init__(self, factory, key, nonce, mac_len, cipher_params):
81 """EAX cipher mode"""
82
83 self.block_size = factory.block_size
84 """The block size of the underlying cipher, in bytes."""
85
86 self.nonce = _copy_bytes(None, None, nonce)
87 """The nonce originally used to create the object."""
88
89 self._mac_len = mac_len
90 self._mac_tag = None # Cache for MAC tag
91
92 # Allowed transitions after initialization
93 self._next = ["update", "encrypt", "decrypt",
94 "digest", "verify"]
95
96 # MAC tag length
97 if not (2 <= self._mac_len <= self.block_size):
98 raise ValueError("'mac_len' must be at least 2 and not larger than %d"
99 % self.block_size)
100
101 # Nonce cannot be empty and must be a byte string
102 if len(self.nonce) == 0:
103 raise ValueError("Nonce cannot be empty in EAX mode")
104 if not is_buffer(nonce):
105 raise TypeError("nonce must be bytes, bytearray or memoryview")
106
107 self._omac = [
108 CMAC.new(key,
109 b'\x00' * (self.block_size - 1) + struct.pack('B', i),
110 ciphermod=factory,
111 cipher_params=cipher_params)
112 for i in range(0, 3)
113 ]
114
115 # Compute MAC of nonce
116 self._omac[0].update(self.nonce)
117 self._signer = self._omac[1]
118
119 # MAC of the nonce is also the initial counter for CTR encryption
120 counter_int = bytes_to_long(self._omac[0].digest())
121 self._cipher = factory.new(key,
122 factory.MODE_CTR,
123 initial_value=counter_int,
124 nonce=b"",
125 **cipher_params)
126
127 def update(self, assoc_data):
128 """Protect associated data
129
130 If there is any associated data, the caller has to invoke
131 this function one or more times, before using
132 ``decrypt`` or ``encrypt``.
133
134 By *associated data* it is meant any data (e.g. packet headers) that
135 will not be encrypted and will be transmitted in the clear.
136 However, the receiver is still able to detect any modification to it.
137
138 If there is no associated data, this method must not be called.
139
140 The caller may split associated data in segments of any size, and
141 invoke this method multiple times, each time with the next segment.
142
143 :Parameters:
144 assoc_data : bytes/bytearray/memoryview
145 A piece of associated data. There are no restrictions on its size.
146 """
147
148 if "update" not in self._next:
149 raise TypeError("update() can only be called"
150 " immediately after initialization")
151
152 self._next = ["update", "encrypt", "decrypt",
153 "digest", "verify"]
154
155 self._signer.update(assoc_data)
156 return self
157
158 def encrypt(self, plaintext, output=None):
159 """Encrypt data with the key and the parameters set at initialization.
160
161 A cipher object is stateful: once you have encrypted a message
162 you cannot encrypt (or decrypt) another message using the same
163 object.
164
165 The data to encrypt can be broken up in two or
166 more pieces and `encrypt` can be called multiple times.
167
168 That is, the statement:
169
170 >>> c.encrypt(a) + c.encrypt(b)
171
172 is equivalent to:
173
174 >>> c.encrypt(a+b)
175
176 This function does not add any padding to the plaintext.
177
178 :Parameters:
179 plaintext : bytes/bytearray/memoryview
180 The piece of data to encrypt.
181 It can be of any length.
182 :Keywords:
183 output : bytearray/memoryview
184 The location where the ciphertext must be written to.
185 If ``None``, the ciphertext is returned.
186 :Return:
187 If ``output`` is ``None``, the ciphertext as ``bytes``.
188 Otherwise, ``None``.
189 """
190
191 if "encrypt" not in self._next:
192 raise TypeError("encrypt() can only be called after"
193 " initialization or an update()")
194 self._next = ["encrypt", "digest"]
195 ct = self._cipher.encrypt(plaintext, output=output)
196 if output is None:
197 self._omac[2].update(ct)
198 else:
199 self._omac[2].update(output)
200 return ct
201
202 def decrypt(self, ciphertext, output=None):
203 """Decrypt data with the key and the parameters set at initialization.
204
205 A cipher object is stateful: once you have decrypted a message
206 you cannot decrypt (or encrypt) another message with the same
207 object.
208
209 The data to decrypt can be broken up in two or
210 more pieces and `decrypt` can be called multiple times.
211
212 That is, the statement:
213
214 >>> c.decrypt(a) + c.decrypt(b)
215
216 is equivalent to:
217
218 >>> c.decrypt(a+b)
219
220 This function does not remove any padding from the plaintext.
221
222 :Parameters:
223 ciphertext : bytes/bytearray/memoryview
224 The piece of data to decrypt.
225 It can be of any length.
226 :Keywords:
227 output : bytearray/memoryview
228 The location where the plaintext must be written to.
229 If ``None``, the plaintext is returned.
230 :Return:
231 If ``output`` is ``None``, the plaintext as ``bytes``.
232 Otherwise, ``None``.
233 """
234
235 if "decrypt" not in self._next:
236 raise TypeError("decrypt() can only be called"
237 " after initialization or an update()")
238 self._next = ["decrypt", "verify"]
239 self._omac[2].update(ciphertext)
240 return self._cipher.decrypt(ciphertext, output=output)
241
242 def digest(self):
243 """Compute the *binary* MAC tag.
244
245 The caller invokes this function at the very end.
246
247 This method returns the MAC that shall be sent to the receiver,
248 together with the ciphertext.
249
250 :Return: the MAC, as a byte string.
251 """
252
253 if "digest" not in self._next:
254 raise TypeError("digest() cannot be called when decrypting"
255 " or validating a message")
256 self._next = ["digest"]
257
258 if not self._mac_tag:
259 tag = b'\x00' * self.block_size
260 for i in range(3):
261 tag = strxor(tag, self._omac[i].digest())
262 self._mac_tag = tag[:self._mac_len]
263
264 return self._mac_tag
265
266 def hexdigest(self):
267 """Compute the *printable* MAC tag.
268
269 This method is like `digest`.
270
271 :Return: the MAC, as a hexadecimal string.
272 """
273 return "".join(["%02x" % bord(x) for x in self.digest()])
274
275 def verify(self, received_mac_tag):
276 """Validate the *binary* MAC tag.
277
278 The caller invokes this function at the very end.
279
280 This method checks if the decrypted message is indeed valid
281 (that is, if the key is correct) and it has not been
282 tampered with while in transit.
283
284 :Parameters:
285 received_mac_tag : bytes/bytearray/memoryview
286 This is the *binary* MAC, as received from the sender.
287 :Raises MacMismatchError:
288 if the MAC does not match. The message has been tampered with
289 or the key is incorrect.
290 """
291
292 if "verify" not in self._next:
293 raise TypeError("verify() cannot be called"
294 " when encrypting a message")
295 self._next = ["verify"]
296
297 if not self._mac_tag:
298 tag = b'\x00' * self.block_size
299 for i in range(3):
300 tag = strxor(tag, self._omac[i].digest())
301 self._mac_tag = tag[:self._mac_len]
302
303 secret = get_random_bytes(16)
304
305 mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag)
306 mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag)
307
308 if mac1.digest() != mac2.digest():
309 raise ValueError("MAC check failed")
310
311 def hexverify(self, hex_mac_tag):
312 """Validate the *printable* MAC tag.
313
314 This method is like `verify`.
315
316 :Parameters:
317 hex_mac_tag : string
318 This is the *printable* MAC, as received from the sender.
319 :Raises MacMismatchError:
320 if the MAC does not match. The message has been tampered with
321 or the key is incorrect.
322 """
323
324 self.verify(unhexlify(hex_mac_tag))
325
326 def encrypt_and_digest(self, plaintext, output=None):
327 """Perform encrypt() and digest() in one step.
328
329 :Parameters:
330 plaintext : bytes/bytearray/memoryview
331 The piece of data to encrypt.
332 :Keywords:
333 output : bytearray/memoryview
334 The location where the ciphertext must be written to.
335 If ``None``, the ciphertext is returned.
336 :Return:
337 a tuple with two items:
338
339 - the ciphertext, as ``bytes``
340 - the MAC tag, as ``bytes``
341
342 The first item becomes ``None`` when the ``output`` parameter
343 specified a location for the result.
344 """
345
346 return self.encrypt(plaintext, output=output), self.digest()
347
348 def decrypt_and_verify(self, ciphertext, received_mac_tag, output=None):
349 """Perform decrypt() and verify() in one step.
350
351 :Parameters:
352 ciphertext : bytes/bytearray/memoryview
353 The piece of data to decrypt.
354 received_mac_tag : bytes/bytearray/memoryview
355 This is the *binary* MAC, as received from the sender.
356 :Keywords:
357 output : bytearray/memoryview
358 The location where the plaintext must be written to.
359 If ``None``, the plaintext is returned.
360 :Return: the plaintext as ``bytes`` or ``None`` when the ``output``
361 parameter specified a location for the result.
362 :Raises MacMismatchError:
363 if the MAC does not match. The message has been tampered with
364 or the key is incorrect.
365 """
366
367 pt = self.decrypt(ciphertext, output=output)
368 self.verify(received_mac_tag)
369 return pt
370
371
372 def _create_eax_cipher(factory, **kwargs):
373 """Create a new block cipher, configured in EAX mode.
374
375 :Parameters:
376 factory : module
377 A symmetric cipher module from `Crypto.Cipher` (like
378 `Crypto.Cipher.AES`).
379
380 :Keywords:
381 key : bytes/bytearray/memoryview
382 The secret key to use in the symmetric cipher.
383
384 nonce : bytes/bytearray/memoryview
385 A value that must never be reused for any other encryption.
386 There are no restrictions on its length, but it is recommended to use
387 at least 16 bytes.
388
389 The nonce shall never repeat for two different messages encrypted with
390 the same key, but it does not need to be random.
391
392 If not specified, a 16 byte long random string is used.
393
394 mac_len : integer
395 Length of the MAC, in bytes. It must be no larger than the cipher
396 block bytes (which is the default).
397 """
398
399 try:
400 key = kwargs.pop("key")
401 nonce = kwargs.pop("nonce", None)
402 if nonce is None:
403 nonce = get_random_bytes(16)
404 mac_len = kwargs.pop("mac_len", factory.block_size)
405 except KeyError as e:
406 raise TypeError("Missing parameter: " + str(e))
407
408 return EaxMode(factory, key, nonce, mac_len, kwargs)