Debian Codegraph @

lib/Crypto/Cipher/_mode_siv.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 Synthetic Initialization Vector (SIV) mode.
33 """
34
35 __all__ = ['SivMode']
36
37 from binascii import hexlify, unhexlify
38
39 from Crypto.Util.py3compat import bord, _copy_bytes
40
41 from Crypto.Util._raw_api import is_buffer
42
43 from Crypto.Util.number import long_to_bytes, bytes_to_long
44 from Crypto.Protocol.KDF import _S2V
45 from Crypto.Hash import BLAKE2s
46 from Crypto.Random import get_random_bytes
47
48
49 class SivMode(object):
50 """Synthetic Initialization Vector (SIV).
51
52 This is an Authenticated Encryption with Associated Data (`AEAD`_) mode.
53 It provides both confidentiality and authenticity.
54
55 The header of the message may be left in the clear, if needed, and it will
56 still be subject to authentication. The decryption step tells the receiver
57 if the message comes from a source that really knowns the secret key.
58 Additionally, decryption detects if any part of the message - including the
59 header - has been modified or corrupted.
60
61 Unlike other AEAD modes such as CCM, EAX or GCM, accidental reuse of a
62 nonce is not catastrophic for the confidentiality of the message. The only
63 effect is that an attacker can tell when the same plaintext (and same
64 associated data) is protected with the same key.
65
66 The length of the MAC is fixed to the block size of the underlying cipher.
67 The key size is twice the length of the key of the underlying cipher.
68
69 This mode is only available for AES ciphers.
70
71 +--------------------+---------------+-------------------+
72 | Cipher | SIV MAC size | SIV key length |
73 | | (bytes) | (bytes) |
74 +====================+===============+===================+
75 | AES-128 | 16 | 32 |
76 +--------------------+---------------+-------------------+
77 | AES-192 | 16 | 48 |
78 +--------------------+---------------+-------------------+
79 | AES-256 | 16 | 64 |
80 +--------------------+---------------+-------------------+
81
82 See `RFC5297`_ and the `original paper`__.
83
84 .. _RFC5297: https://tools.ietf.org/html/rfc5297
85 .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html
86 .. __: http://www.cs.ucdavis.edu/~rogaway/papers/keywrap.pdf
87
88 :undocumented: __init__
89 """
90
91 def __init__(self, factory, key, nonce, kwargs):
92
93 self.block_size = factory.block_size
94 """The block size of the underlying cipher, in bytes."""
95
96 self._factory = factory
97
98 self._cipher_params = kwargs
99
100 if len(key) not in (32, 48, 64):
101 raise ValueError("Incorrect key length (%d bytes)" % len(key))
102
103 if nonce is not None:
104 if not is_buffer(nonce):
105 raise TypeError("When provided, the nonce must be bytes, bytearray or memoryview")
106
107 if len(nonce) == 0:
108 raise ValueError("When provided, the nonce must be non-empty")
109
110 self.nonce = _copy_bytes(None, None, nonce)
111 """Public attribute is only available in case of non-deterministic
112 encryption."""
113
114 subkey_size = len(key) // 2
115
116 self._mac_tag = None # Cache for MAC tag
117 self._kdf = _S2V(key[:subkey_size],
118 ciphermod=factory,
119 cipher_params=self._cipher_params)
120 self._subkey_cipher = key[subkey_size:]
121
122 # Purely for the purpose of verifying that cipher_params are OK
123 factory.new(key[:subkey_size], factory.MODE_ECB, **kwargs)
124
125 # Allowed transitions after initialization
126 self._next = ["update", "encrypt", "decrypt",
127 "digest", "verify"]
128
129 def _create_ctr_cipher(self, v):
130 """Create a new CTR cipher from V in SIV mode"""
131
132 v_int = bytes_to_long(v)
133 q = v_int & 0xFFFFFFFFFFFFFFFF7FFFFFFF7FFFFFFF
134 return self._factory.new(
135 self._subkey_cipher,
136 self._factory.MODE_CTR,
137 initial_value=q,
138 nonce=b"",
139 **self._cipher_params)
140
141 def update(self, component):
142 """Protect one associated data component
143
144 For SIV, the associated data is a sequence (*vector*) of non-empty
145 byte strings (*components*).
146
147 This method consumes the next component. It must be called
148 once for each of the components that constitue the associated data.
149
150 Note that the components have clear boundaries, so that:
151
152 >>> cipher.update(b"builtin")
153 >>> cipher.update(b"securely")
154
155 is not equivalent to:
156
157 >>> cipher.update(b"built")
158 >>> cipher.update(b"insecurely")
159
160 If there is no associated data, this method must not be called.
161
162 :Parameters:
163 component : bytes/bytearray/memoryview
164 The next associated data component.
165 """
166
167 if "update" not in self._next:
168 raise TypeError("update() can only be called"
169 " immediately after initialization")
170
171 self._next = ["update", "encrypt", "decrypt",
172 "digest", "verify"]
173
174 return self._kdf.update(component)
175
176 def encrypt(self, plaintext):
177 """
178 For SIV, encryption and MAC authentication must take place at the same
179 point. This method shall not be used.
180
181 Use `encrypt_and_digest` instead.
182 """
183
184 raise TypeError("encrypt() not allowed for SIV mode."
185 " Use encrypt_and_digest() instead.")
186
187 def decrypt(self, ciphertext):
188 """
189 For SIV, decryption and verification must take place at the same
190 point. This method shall not be used.
191
192 Use `decrypt_and_verify` instead.
193 """
194
195 raise TypeError("decrypt() not allowed for SIV mode."
196 " Use decrypt_and_verify() instead.")
197
198 def digest(self):
199 """Compute the *binary* MAC tag.
200
201 The caller invokes this function at the very end.
202
203 This method returns the MAC that shall be sent to the receiver,
204 together with the ciphertext.
205
206 :Return: the MAC, as a byte string.
207 """
208
209 if "digest" not in self._next:
210 raise TypeError("digest() cannot be called when decrypting"
211 " or validating a message")
212 self._next = ["digest"]
213 if self._mac_tag is None:
214 self._mac_tag = self._kdf.derive()
215 return self._mac_tag
216
217 def hexdigest(self):
218 """Compute the *printable* MAC tag.
219
220 This method is like `digest`.
221
222 :Return: the MAC, as a hexadecimal string.
223 """
224 return "".join(["%02x" % bord(x) for x in self.digest()])
225
226 def verify(self, received_mac_tag):
227 """Validate the *binary* MAC tag.
228
229 The caller invokes this function at the very end.
230
231 This method checks if the decrypted message is indeed valid
232 (that is, if the key is correct) and it has not been
233 tampered with while in transit.
234
235 :Parameters:
236 received_mac_tag : bytes/bytearray/memoryview
237 This is the *binary* MAC, as received from the sender.
238 :Raises ValueError:
239 if the MAC does not match. The message has been tampered with
240 or the key is incorrect.
241 """
242
243 if "verify" not in self._next:
244 raise TypeError("verify() cannot be called"
245 " when encrypting a message")
246 self._next = ["verify"]
247
248 if self._mac_tag is None:
249 self._mac_tag = self._kdf.derive()
250
251 secret = get_random_bytes(16)
252
253 mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag)
254 mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag)
255
256 if mac1.digest() != mac2.digest():
257 raise ValueError("MAC check failed")
258
259 def hexverify(self, hex_mac_tag):
260 """Validate the *printable* MAC tag.
261
262 This method is like `verify`.
263
264 :Parameters:
265 hex_mac_tag : string
266 This is the *printable* MAC, as received from the sender.
267 :Raises ValueError:
268 if the MAC does not match. The message has been tampered with
269 or the key is incorrect.
270 """
271
272 self.verify(unhexlify(hex_mac_tag))
273
274 def encrypt_and_digest(self, plaintext, output=None):
275 """Perform encrypt() and digest() in one step.
276
277 :Parameters:
278 plaintext : bytes/bytearray/memoryview
279 The piece of data to encrypt.
280 :Keywords:
281 output : bytearray/memoryview
282 The location where the ciphertext must be written to.
283 If ``None``, the ciphertext is returned.
284 :Return:
285 a tuple with two items:
286
287 - the ciphertext, as ``bytes``
288 - the MAC tag, as ``bytes``
289
290 The first item becomes ``None`` when the ``output`` parameter
291 specified a location for the result.
292 """
293
294 if "encrypt" not in self._next:
295 raise TypeError("encrypt() can only be called after"
296 " initialization or an update()")
297
298 self._next = ["digest"]
299
300 # Compute V (MAC)
301 if hasattr(self, 'nonce'):
302 self._kdf.update(self.nonce)
303 self._kdf.update(plaintext)
304 self._mac_tag = self._kdf.derive()
305
306 cipher = self._create_ctr_cipher(self._mac_tag)
307
308 return cipher.encrypt(plaintext, output=output), self._mac_tag
309
310 def decrypt_and_verify(self, ciphertext, mac_tag, output=None):
311 """Perform decryption and verification in one step.
312
313 A cipher object is stateful: once you have decrypted a message
314 you cannot decrypt (or encrypt) another message with the same
315 object.
316
317 You cannot reuse an object for encrypting
318 or decrypting other data with the same key.
319
320 This function does not remove any padding from the plaintext.
321
322 :Parameters:
323 ciphertext : bytes/bytearray/memoryview
324 The piece of data to decrypt.
325 It can be of any length.
326 mac_tag : bytes/bytearray/memoryview
327 This is the *binary* MAC, as received from the sender.
328 :Keywords:
329 output : bytearray/memoryview
330 The location where the plaintext must be written to.
331 If ``None``, the plaintext is returned.
332 :Return: the plaintext as ``bytes`` or ``None`` when the ``output``
333 parameter specified a location for the result.
334 :Raises ValueError:
335 if the MAC does not match. The message has been tampered with
336 or the key is incorrect.
337 """
338
339 if "decrypt" not in self._next:
340 raise TypeError("decrypt() can only be called"
341 " after initialization or an update()")
342 self._next = ["verify"]
343
344 # Take the MAC and start the cipher for decryption
345 self._cipher = self._create_ctr_cipher(mac_tag)
346
347 plaintext = self._cipher.decrypt(ciphertext, output=output)
348
349 if hasattr(self, 'nonce'):
350 self._kdf.update(self.nonce)
351 self._kdf.update(plaintext if output is None else output)
352 self.verify(mac_tag)
353
354 return plaintext
355
356
357 def _create_siv_cipher(factory, **kwargs):
358 """Create a new block cipher, configured in
359 Synthetic Initializaton Vector (SIV) mode.
360
361 :Parameters:
362
363 factory : object
364 A symmetric cipher module from `Crypto.Cipher`
365 (like `Crypto.Cipher.AES`).
366
367 :Keywords:
368
369 key : bytes/bytearray/memoryview
370 The secret key to use in the symmetric cipher.
371 It must be 32, 48 or 64 bytes long.
372 If AES is the chosen cipher, the variants *AES-128*,
373 *AES-192* and or *AES-256* will be used internally.
374
375 nonce : bytes/bytearray/memoryview
376 For deterministic encryption, it is not present.
377
378 Otherwise, it is a value that must never be reused
379 for encrypting message under this key.
380
381 There are no restrictions on its length,
382 but it is recommended to use at least 16 bytes.
383 """
384
385 try:
386 key = kwargs.pop("key")
387 except KeyError as e:
388 raise TypeError("Missing parameter: " + str(e))
389
390 nonce = kwargs.pop("nonce", None)
391
392 return SivMode(factory, key, nonce, kwargs)