Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/Crypto/Cipher/blockalgo.py: 30%
348 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 07:03 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 07:03 +0000
1# -*- coding: utf-8 -*-
2#
3# Cipher/blockalgo.py
4#
5# ===================================================================
6# The contents of this file are dedicated to the public domain. To
7# the extent that dedication to the public domain is not available,
8# everyone is granted a worldwide, perpetual, royalty-free,
9# non-exclusive license to exercise all rights associated with the
10# contents of this file for any purpose whatsoever.
11# No rights are reserved.
12#
13# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
14# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
16# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
17# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
18# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
19# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20# SOFTWARE.
21# ===================================================================
22"""Module with definitions common to all block ciphers."""
24import sys
25if sys.version_info[0] == 2 and sys.version_info[1] == 1:
26 from Crypto.Util.py21compat import *
28from Crypto.Util.py3compat import *
30from binascii import unhexlify
32from Crypto.Util import Counter
33from Crypto.Util.strxor import strxor
34from Crypto.Util.number import long_to_bytes, bytes_to_long
35import Crypto.Util.Counter
36from Crypto.Hash import CMAC
37from Crypto.Hash.CMAC import _SmoothMAC
38from Crypto.Protocol.KDF import _S2V
40from Crypto.Util import _galois
42#: *Electronic Code Book (ECB)*.
43#: This is the simplest encryption mode. Each of the plaintext blocks
44#: is directly encrypted into a ciphertext block, independently of
45#: any other block. This mode exposes frequency of symbols
46#: in your plaintext. Other modes (e.g. *CBC*) should be used instead.
47#:
48#: See `NIST SP800-38A`_ , Section 6.1 .
49#:
50#: .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
51MODE_ECB = 1
53#: *Cipher-Block Chaining (CBC)*. Each of the ciphertext blocks depends
54#: on the current and all previous plaintext blocks. An Initialization Vector
55#: (*IV*) is required.
56#:
57#: The *IV* is a data block to be transmitted to the receiver.
58#: The *IV* can be made public, but it must be authenticated by the receiver
59#: and it should be picked randomly.
60#:
61#: See `NIST SP800-38A`_ , Section 6.2 .
62#:
63#: .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
64MODE_CBC = 2
66#: *Cipher FeedBack (CFB)*. This mode is similar to CBC, but it transforms
67#: the underlying block cipher into a stream cipher. Plaintext and ciphertext
68#: are processed in *segments* of **s** bits. The mode is therefore sometimes
69#: labelled **s**-bit CFB. An Initialization Vector (*IV*) is required.
70#:
71#: When encrypting, each ciphertext segment contributes to the encryption of
72#: the next plaintext segment.
73#:
74#: This *IV* is a data block to be transmitted to the receiver.
75#: The *IV* can be made public, but it should be picked randomly.
76#: Reusing the same *IV* for encryptions done with the same key lead to
77#: catastrophic cryptographic failures.
78#:
79#: See `NIST SP800-38A`_ , Section 6.3 .
80#:
81#: .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
82MODE_CFB = 3
84#: This mode should not be used.
85MODE_PGP = 4
87#: *Output FeedBack (OFB)*. This mode is very similar to CBC, but it
88#: transforms the underlying block cipher into a stream cipher.
89#: The keystream is the iterated block encryption of an
90#: Initialization Vector (*IV*).
91#:
92#: The *IV* is a data block to be transmitted to the receiver.
93#: The *IV* can be made public, but it should be picked randomly.
94#:
95#: Reusing the same *IV* for encryptions done with the same key lead to
96#: catastrophic cryptograhic failures.
97#:
98#: See `NIST SP800-38A`_ , Section 6.4 .
99#:
100#: .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
101MODE_OFB = 5
103#: *CounTeR (CTR)*. This mode is very similar to ECB, in that
104#: encryption of one block is done independently of all other blocks.
105#: Unlike ECB, the block *position* contributes to the encryption and no
106#: information leaks about symbol frequency.
107#:
108#: Each message block is associated to a *counter* which must be unique
109#: across all messages that get encrypted with the same key (not just within
110#: the same message). The counter is as big as the block size.
111#:
112#: Counters can be generated in several ways. The most straightword one is
113#: to choose an *initial counter block* (which can be made public, similarly
114#: to the *IV* for the other modes) and increment its lowest **m** bits by
115#: one (modulo *2^m*) for each block. In most cases, **m** is chosen to be half
116#: the block size.
117#:
118#: Reusing the same *initial counter block* for encryptions done with the same
119#: key lead to catastrophic cryptograhic failures.
120#:
121#: See `NIST SP800-38A`_ , Section 6.5 (for the mode) and Appendix B (for how
122#: to manage the *initial counter block*).
123#:
124#: .. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf
125MODE_CTR = 6
127#: *OpenPGP CFB*. This mode is a variant of CFB, and it is only used in PGP and
128#: OpenPGP_ applications. An Initialization Vector (*IV*) is required.
129#:
130#: Unlike CFB, the IV is not transmitted to the receiver.
131#: Instead, the *encrypted* IV is.
132#: The IV is a random data block. Two of its bytes are duplicated to act
133#: as a checksum for the correctness of the key. The encrypted IV is
134#: therefore 2 bytes longer than the clean IV.
135#:
136#: .. _OpenPGP: http://tools.ietf.org/html/rfc4880
137MODE_OPENPGP = 7
139#: *Counter with CBC-MAC (CCM)*. This is an Authenticated Encryption with
140#: Associated Data (`AEAD`_) mode. It provides both confidentiality and
141#: authenticity.
142#: The header of the message may be left in the clear, if needed, and it will
143#: still be subject to authentication. The decryption step tells the receiver
144#: if the message comes from a source that really knowns the secret key.
145#: Additionally, decryption detects if any part of the message - including the
146#: header - has been modified or corrupted.
147#:
148#: This mode requires a nonce. The nonce shall never repeat for two
149#: different messages encrypted with the same key, but it does not need
150#: to be random.
151#: Note that there is a trade-off between the size of the nonce and the
152#: maximum size of a single message you can encrypt.
153#:
154#: It is important to use a large nonce if the key is reused across several
155#: messages and the nonce is chosen randomly.
156#:
157#: It is acceptable to us a short nonce if the key is only used a few times or
158#: if the nonce is taken from a counter.
159#:
160#: The following table shows the trade-off when the nonce is chosen at
161#: random. The column on the left shows how many messages it takes
162#: for the keystream to repeat **on average**. In practice, you will want to
163#: stop using the key way before that.
164#:
165#: +--------------------+---------------+-------------------+
166#: | Avg. # of messages | nonce | Max. message |
167#: | before keystream | size | size |
168#: | repeats | (bytes) | (bytes) |
169#: +====================+===============+===================+
170#: | 2**52 | 13 | 64K |
171#: +--------------------+---------------+-------------------+
172#: | 2**48 | 12 | 16M |
173#: +--------------------+---------------+-------------------+
174#: | 2**44 | 11 | 4G |
175#: +--------------------+---------------+-------------------+
176#: | 2**40 | 10 | 1T |
177#: +--------------------+---------------+-------------------+
178#: | 2**36 | 9 | 64P |
179#: +--------------------+---------------+-------------------+
180#: | 2**32 | 8 | 16E |
181#: +--------------------+---------------+-------------------+
182#:
183#: This mode is only available for ciphers that operate on 128 bits blocks
184#: (e.g. AES but not TDES).
185#:
186#: See `NIST SP800-38C`_ or RFC3610_ .
187#:
188#: .. _`NIST SP800-38C`: http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C.pdf
189#: .. _RFC3610: https://tools.ietf.org/html/rfc3610
190#: .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html
191MODE_CCM = 8
193#: *EAX*. This is an Authenticated Encryption with Associated Data
194#: (`AEAD`_) mode. It provides both confidentiality and authenticity.
195#:
196#: The header of the message may be left in the clear, if needed, and it will
197#: still be subject to authentication.
198#:
199#: The decryption step tells the receiver if the message comes from a source
200#: that really knowns the secret key.
201#: Additionally, decryption detects if any part of the message - including the
202#: header - has been modified or corrupted.
203#:
204#: This mode requires a nonce. The nonce shall never repeat for two
205#: different messages encrypted with the same key, but it does not need to
206#: be random.
207#
208#: This mode is only available for ciphers that operate on 64 or
209#: 128 bits blocks.
210#:
211#: There are no official standards defining EAX. The implementation is based on
212#: `a proposal`__ that was presented to NIST.
213#:
214#: .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html
215#: .. __: http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/eax/eax-spec.pdf
216MODE_EAX = 9
218#: *Synthetic Initialization Vector*. This is an Authenticated Encryption with
219#: Associated Data (`AEAD`_) mode. It provides both confidentiality and
220#: authenticity.
221#: The header of the message may be left in the clear, if needed, and it will
222#: still be subject to authentication. The decryption step tells the receiver
223#: if the message comes from a source that really knowns the secret key.
224#: Additionally, decryption detects if any part of the message - including the
225#: header - has been modified or corrupted.
226#:
227#: If the data being encrypted is completely unpredictable to an adversary
228#: (e.g. a secret key, for key wrapping purposes) a nonce is not strictly
229#: required.
230#:
231#: Otherwise, a nonce has to be provided; the nonce shall never repeat
232#: for two different messages encrypted with the same key, but it does not
233#: need to be random.
234#:
235#: Unlike other AEAD modes such as CCM, EAX or GCM, accidental reuse of a
236#: nonce is not catastrophic for the confidentiality of the message. The only
237#: effect is that an attacker can tell when the same plaintext (and same
238#: associated data) is protected with the same key.
239#:
240#: The length of the MAC is fixed to the block size of the underlying cipher.
241#: The key size is twice the length of the key of the underlying cipher.
242#:
243#: This mode is only available for AES ciphers.
244#:
245#: +--------------------+---------------+-------------------+
246#: | Cipher | SIV MAC size | SIV key length |
247#: | | (bytes) | (bytes) |
248#: +====================+===============+===================+
249#: | AES-128 | 16 | 32 |
250#: +--------------------+---------------+-------------------+
251#: | AES-192 | 16 | 48 |
252#: +--------------------+---------------+-------------------+
253#: | AES-256 | 16 | 64 |
254#: +--------------------+---------------+-------------------+
255#:
256#: See `RFC5297`_ and the `original paper`__.
257#:
258#: .. _RFC5297: https://tools.ietf.org/html/rfc5297
259#: .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html
260#: .. __: http://www.cs.ucdavis.edu/~rogaway/papers/keywrap.pdf
261MODE_SIV = 10
263#: *Galois/Counter Mode (GCM)*. This is an Authenticated Encryption with
264#: Associated Data (`AEAD`_) mode. It provides both confidentiality and
265#: authenticity.
266#: The header of the message may be left in the clear, if needed, and it will
267#: still be subject to authentication. The decryption step tells the receiver
268#: if the message comes from a source that really knowns the secret key.
269#: Additionally, decryption detects if any part of the message - including the
270#: header - has been modified or corrupted.
271#:
272#: This mode requires a nonce. The nonce shall never repeat for two
273#: different messages encrypted with the same key, but it does not need to
274#: be random.
275#:
276#: This mode is only available for ciphers that operate on 128 bits blocks
277#: (e.g. AES but not TDES).
278#:
279#: See `NIST SP800-38D`_ .
280#:
281#: .. _`NIST SP800-38D`: http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf
282#: .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html
283MODE_GCM = 11
286def _getParameter(name, index, args, kwargs, default=None):
287 """Find a parameter in tuple and dictionary arguments a function receives"""
289 param = kwargs.get(name)
290 if len(args) > index:
291 if param:
292 raise TypeError("Parameter '%s' is specified twice" % name)
293 param = args[index]
294 return param or default
297class _CBCMAC(_SmoothMAC):
299 def __init__(self, key, ciphermod):
300 _SmoothMAC.__init__(self, ciphermod.block_size, None, 0)
301 self._key = key
302 self._factory = ciphermod
304 def _ignite(self, data):
305 if self._mac:
306 raise TypeError("_ignite() cannot be called twice")
308 self._buffer.insert(0, data)
309 self._buffer_len += len(data)
310 self._mac = self._factory.new(self._key, MODE_CBC, bchr(0) * 16)
311 self.update(b(""))
313 def _update(self, block_data):
314 self._t = self._mac.encrypt(block_data)[-16:]
316 def _digest(self, left_data):
317 return self._t
320class _GHASH(_SmoothMAC):
321 """GHASH function defined in NIST SP 800-38D, Algorithm 2.
323 If X_1, X_2, .. X_m are the blocks of input data, the function
324 computes:
326 X_1*H^{m} + X_2*H^{m-1} + ... + X_m*H
328 in the Galois field GF(2^256) using the reducing polynomial
329 (x^128 + x^7 + x^2 + x + 1).
330 """
332 def __init__(self, hash_subkey, block_size):
333 _SmoothMAC.__init__(self, block_size, None, 0)
334 self._hash_subkey = _galois.ghash_expand(hash_subkey)
335 self._last_y = bchr(0) * 16
336 self._mac = _galois.ghash
338 def copy(self):
339 clone = _GHASH(self._hash_subkey, self._bs)
340 _SmoothMAC._deep_copy(self, clone)
341 clone._last_y = self._last_y
342 return clone
344 def _update(self, block_data):
345 self._last_y = _galois.ghash(block_data, self._last_y,
346 self._hash_subkey)
348 def _digest(self, left_data):
349 return self._last_y
352class BlockAlgo:
353 """Class modelling an abstract block cipher."""
355 def __init__(self, factory, key, *args, **kwargs):
356 self.mode = _getParameter('mode', 0, args, kwargs, default=MODE_ECB)
357 self.block_size = factory.block_size
358 self._factory = factory
359 self._tag = None
361 if self.mode == MODE_CCM:
362 if self.block_size != 16:
363 raise TypeError("CCM mode is only available for ciphers that operate on 128 bits blocks")
365 self._mac_len = kwargs.get('mac_len', 16) # t
366 if self._mac_len not in (4, 6, 8, 10, 12, 14, 16):
367 raise ValueError("Parameter 'mac_len' must be even and in the range 4..16")
369 self.nonce = _getParameter('nonce', 1, args, kwargs) # N
370 if not (self.nonce and 7 <= len(self.nonce) <= 13):
371 raise ValueError("Length of parameter 'nonce' must be"
372 " in the range 7..13 bytes")
374 self._key = key
375 self._msg_len = kwargs.get('msg_len', None) # p
376 self._assoc_len = kwargs.get('assoc_len', None) # a
378 self._cipherMAC = _CBCMAC(key, factory)
379 self._done_assoc_data = False # True when all associated data
380 # has been processed
382 # Allowed transitions after initialization
383 self._next = [self.update, self.encrypt, self.decrypt,
384 self.digest, self.verify]
386 # Try to start CCM
387 self._start_ccm()
389 elif self.mode == MODE_OPENPGP:
390 self._start_PGP(factory, key, *args, **kwargs)
391 elif self.mode == MODE_EAX:
392 self._start_eax(factory, key, *args, **kwargs)
393 elif self.mode == MODE_SIV:
394 self._start_siv(factory, key, *args, **kwargs)
395 elif self.mode == MODE_GCM:
396 self._start_gcm(factory, key, *args, **kwargs)
397 else:
398 self._cipher = factory.new(key, *args, **kwargs)
399 self.IV = self._cipher.IV
401 def _start_gcm(self, factory, key, *args, **kwargs):
403 if self.block_size != 16:
404 raise TypeError("GCM mode is only available for ciphers that operate on 128 bits blocks")
406 self.nonce = _getParameter('nonce', 1, args, kwargs)
407 if not self.nonce:
408 raise TypeError("MODE_GCM requires a nonce")
410 self._mac_len = kwargs.get('mac_len', 16)
411 if not (self._mac_len and 4 <= self._mac_len <= 16):
412 raise ValueError("Parameter 'mac_len' must not be larger than 16 bytes")
414 # Allowed transitions after initialization
415 self._next = [self.update, self.encrypt, self.decrypt,
416 self.digest, self.verify]
418 self._done_assoc_data = False
420 # Length of the ciphertext or plaintext
421 self._msg_len = 0
423 # Step 1 in SP800-38D, Algorithm 4 (encryption) - Compute H
424 # See also Algorithm 5 (decryption)
425 hash_subkey = factory.new(key).encrypt(bchr(0) * 16)
427 # Step 2 - Compute J0 (integer, not byte string!)
428 if len(self.nonce) == 12:
429 self._j0 = bytes_to_long(self.nonce + b("\x00\x00\x00\x01"))
430 else:
431 fill = (16 - (len(self.nonce) % 16)) % 16 + 8
432 ghash_in = (self.nonce +
433 bchr(0) * fill +
434 long_to_bytes(8 * len(self.nonce), 8))
436 mac = _GHASH(hash_subkey, factory.block_size)
437 mac.update(ghash_in)
438 self._j0 = bytes_to_long(mac.digest())
440 # Step 3 - Prepare GCTR cipher for encryption/decryption
441 ctr = Counter.new(128, initial_value=self._j0 + 1,
442 allow_wraparound=True)
443 self._cipher = self._factory.new(key, MODE_CTR, counter=ctr)
445 # Step 5 - Bootstrat GHASH
446 self._cipherMAC = _GHASH(hash_subkey, factory.block_size)
448 # Step 6 - Prepare GCTR cipher for GMAC
449 ctr = Counter.new(128, initial_value=self._j0, allow_wraparound=True)
450 self._tag_cipher = self._factory.new(key, MODE_CTR, counter=ctr)
452 def _start_siv(self, factory, key, *args, **kwargs):
454 subkey_size, rem = divmod(len(key), 2)
455 if rem:
456 raise ValueError("MODE_SIV requires a key twice as long as for the underlying cipher")
458 # IV is optional
459 self.nonce = _getParameter('nonce', 1, args, kwargs)
461 self._cipherMAC = _S2V(key[:subkey_size], ciphermod=factory)
462 self._subkey_ctr = key[subkey_size:]
463 self._mac_len = factory.block_size
465 self._cipherMAC = self._cipherMAC
467 # Allowed transitions after initialization
468 self._next = [self.update, self.encrypt, self.decrypt,
469 self.digest, self.verify]
471 def _siv_ctr_cipher(self, tag):
472 """Create a new CTR cipher from the MAC in SIV mode"""
474 tag_int = bytes_to_long(tag)
475 init_counter = tag_int ^ (tag_int & 0x8000000080000000)
476 ctr = Counter.new(self._factory.block_size * 8,
477 initial_value=init_counter,
478 allow_wraparound=True)
480 return self._factory.new(self._subkey_ctr, MODE_CTR, counter=ctr)
482 def _start_eax(self, factory, key, *args, **kwargs):
484 self.nonce = _getParameter('nonce', 1, args, kwargs)
485 if not self.nonce:
486 raise TypeError("MODE_EAX requires a nonce")
488 # Allowed transitions after initialization
489 self._next = [self.update, self.encrypt, self.decrypt,
490 self.digest, self.verify]
492 self._mac_len = kwargs.get('mac_len', self.block_size)
493 if not (self._mac_len and 4 <= self._mac_len <= self.block_size):
494 raise ValueError("Parameter 'mac_len' must not be larger than %d"
495 % self.block_size)
497 self._omac = [
498 CMAC.new(key, bchr(0) * (self.block_size - 1) + bchr(i),
499 ciphermod=factory)
500 for i in range(0, 3)
501 ]
503 # Compute MAC of nonce
504 self._omac[0].update(self.nonce)
506 self._cipherMAC = self._omac[1]
508 # MAC of the nonce is also the initial counter for CTR encryption
509 counter_int = bytes_to_long(self._omac[0].digest())
510 counter_obj = Crypto.Util.Counter.new(
511 self.block_size * 8,
512 initial_value=counter_int,
513 allow_wraparound=True)
514 self._cipher = factory.new(key, MODE_CTR, counter=counter_obj)
516 def _start_PGP(self, factory, key, *args, **kwargs):
517 # OPENPGP mode. For details, see 13.9 in RCC4880.
518 #
519 # A few members are specifically created for this mode:
520 # - _encrypted_iv, set in this constructor
521 # - _done_first_block, set to True after the first encryption
522 # - _done_last_block, set to True after a partial block is processed
524 self._done_first_block = False
525 self._done_last_block = False
526 self.IV = _getParameter('IV', 1, args, kwargs)
527 if self.IV is None:
528 # TODO: Decide whether 'IV' or 'iv' should be used going forward,
529 # and deprecate the other. 'IV' is consistent with the rest of
530 # PyCrypto, but 'iv' is more common in Python generally. For now,
531 # we'll support both here. When in doubt, use a positional
532 # parameter for now.
533 self.IV = _getParameter('iv', 1, args, kwargs)
534 if not self.IV:
535 raise ValueError("MODE_OPENPGP requires an IV")
537 # Instantiate a temporary cipher to process the IV
538 IV_cipher = factory.new(
539 key,
540 MODE_CFB,
541 b('\x00') * self.block_size, # IV for CFB
542 segment_size=self.block_size * 8)
544 # The cipher will be used for...
545 if len(self.IV) == self.block_size:
546 # ... encryption
547 self._encrypted_IV = IV_cipher.encrypt(
548 self.IV + self.IV[-2:] + # Plaintext
549 b('\x00') * (self.block_size - 2) # Padding
550 )[:self.block_size + 2]
551 elif len(self.IV) == self.block_size + 2:
552 # ... decryption
553 self._encrypted_IV = self.IV
554 self.IV = IV_cipher.decrypt(
555 self.IV + # Ciphertext
556 b('\x00') * (self.block_size - 2) # Padding
557 )[:self.block_size + 2]
558 if self.IV[-2:] != self.IV[-4:-2]:
559 raise ValueError("Failed integrity check for OPENPGP IV")
560 self.IV = self.IV[:-2]
561 else:
562 raise ValueError("Length of IV must be %d or %d bytes for MODE_OPENPGP"
563 % (self.block_size, self.block_size+2))
565 # Instantiate the cipher for the real PGP data
566 self._cipher = factory.new(
567 key,
568 MODE_CFB,
569 self._encrypted_IV[-self.block_size:],
570 segment_size=self.block_size * 8
571 )
573 def _start_ccm(self, assoc_len=None, msg_len=None):
574 # CCM mode. This method creates the 2 ciphers used for the MAC
575 # (self._cipherMAC) and for the encryption/decryption (self._cipher).
576 #
577 # Member _assoc_buffer may already contain user data that needs to be
578 # authenticated.
580 if self._cipherMAC.can_reduce():
581 # Already started
582 return
583 if assoc_len is not None:
584 self._assoc_len = assoc_len
585 if msg_len is not None:
586 self._msg_len = msg_len
587 if None in (self._assoc_len, self._msg_len):
588 return
590 # q is the length of Q, the encoding of the message length
591 q = 15 - len(self.nonce)
593 ## Compute B_0
594 flags = (
595 64 * (self._assoc_len > 0) +
596 8 * divmod(self._mac_len - 2, 2)[0] +
597 (q - 1)
598 )
599 b_0 = bchr(flags) + self.nonce + long_to_bytes(self._msg_len, q)
601 # Start CBC MAC with zero IV
602 assoc_len_encoded = b('')
603 if self._assoc_len > 0:
604 if self._assoc_len < (2 ** 16 - 2 ** 8):
605 enc_size = 2
606 elif self._assoc_len < (2 ** 32):
607 assoc_len_encoded = b('\xFF\xFE')
608 enc_size = 4
609 else:
610 assoc_len_encoded = b('\xFF\xFF')
611 enc_size = 8
612 assoc_len_encoded += long_to_bytes(self._assoc_len, enc_size)
613 self._cipherMAC._ignite(b_0 + assoc_len_encoded)
615 # Start CTR cipher
616 prefix = bchr(q - 1) + self.nonce
617 ctr = Counter.new(128 - len(prefix) * 8, prefix, initial_value=0)
618 self._cipher = self._factory.new(self._key, MODE_CTR, counter=ctr)
619 # Will XOR against CBC MAC
620 self._s_0 = self._cipher.encrypt(bchr(0) * 16)
622 def update(self, assoc_data):
623 """Protect associated data
625 When using an AEAD mode like CCM, EAX, GCM or SIV, and
626 if there is any associated data, the caller has to invoke
627 this function one or more times, before using
628 ``decrypt`` or ``encrypt``.
630 By *associated data* it is meant any data (e.g. packet headers) that
631 will not be encrypted and will be transmitted in the clear.
632 However, the receiver is still able to detect any modification to it.
633 In CCM and GCM, the *associated data* is also called
634 *additional authenticated data* (AAD).
635 In EAX, the *associated data* is called *header*.
637 If there is no associated data, this method must not be called.
639 The caller may split associated data in segments of any size, and
640 invoke this method multiple times, each time with the next segment.
642 :Parameters:
643 assoc_data : byte string
644 A piece of associated data. There are no restrictions on its size.
645 """
647 if self.mode not in (MODE_CCM, MODE_EAX, MODE_SIV, MODE_GCM):
648 raise TypeError("update() not supported by this mode of operation")
650 if self.update not in self._next:
651 raise TypeError("update() can only be called immediately after initialization")
653 self._next = [self.update, self.encrypt, self.decrypt,
654 self.digest, self.verify]
656 return self._cipherMAC.update(assoc_data)
658 def encrypt(self, plaintext):
659 """Encrypt data with the key and the parameters set at initialization.
661 A cipher object is stateful: once you have encrypted a message
662 you cannot encrypt (or decrypt) another message using the same
663 object.
665 For `MODE_SIV` (always) and `MODE_CCM` (when ``msg_len`` was not
666 passed at initialization), this method can be called only **once**.
668 For all other modes, the data to encrypt can be broken up in two or
669 more pieces and `encrypt` can be called multiple times.
671 That is, the statement:
673 >>> c.encrypt(a) + c.encrypt(b)
675 is equivalent to:
677 >>> c.encrypt(a+b)
679 That also means that you cannot reuse an object for encrypting
680 or decrypting other data with the same key.
682 This function does not add any padding to the plaintext.
684 - For `MODE_ECB` and `MODE_CBC`, *plaintext* length (in bytes) must be
685 a multiple of *block_size*.
687 - For `MODE_CFB`, *plaintext* length (in bytes) must be a multiple
688 of *segment_size*/8.
690 - For `MODE_OFB`, `MODE_CTR` and all AEAD modes
691 *plaintext* can be of any length.
693 - For `MODE_OPENPGP`, *plaintext* must be a multiple of *block_size*,
694 unless it is the last chunk of the message.
696 :Parameters:
697 plaintext : byte string
698 The piece of data to encrypt.
699 :Return:
700 the encrypted data, as a byte string. It is as long as
701 *plaintext* with one exception: when encrypting the first message
702 chunk with `MODE_OPENPGP`, the encypted IV is prepended to the
703 returned ciphertext.
704 """
706 if self.mode == MODE_OPENPGP:
707 padding_length = (self.block_size - len(plaintext) % self.block_size) % self.block_size
708 if padding_length > 0:
709 # CFB mode requires ciphertext to have length multiple
710 # of block size,
711 # but PGP mode allows the last block to be shorter
712 if self._done_last_block:
713 raise ValueError("Only the last chunk is allowed to have length not multiple of %d bytes",
714 self.block_size)
715 self._done_last_block = True
716 padded = plaintext + b('\x00') * padding_length
717 res = self._cipher.encrypt(padded)[:len(plaintext)]
718 else:
719 res = self._cipher.encrypt(plaintext)
720 if not self._done_first_block:
721 res = self._encrypted_IV + res
722 self._done_first_block = True
723 return res
725 if self.mode in (MODE_CCM, MODE_EAX, MODE_SIV, MODE_GCM):
726 if self.encrypt not in self._next:
727 raise TypeError("encrypt() can only be called after initialization or an update()")
728 self._next = [self.encrypt, self.digest]
730 if self.mode == MODE_CCM:
731 if self._assoc_len is None:
732 self._start_ccm(assoc_len=self._cipherMAC.get_len())
733 if self._msg_len is None:
734 self._start_ccm(msg_len=len(plaintext))
735 self._next = [self.digest]
736 if not self._done_assoc_data:
737 self._cipherMAC.zero_pad()
738 self._done_assoc_data = True
740 self._cipherMAC.update(plaintext)
742 if self.mode == MODE_SIV:
743 self._next = [self.digest]
745 if self.nonce:
746 self._cipherMAC.update(self.nonce)
748 self._cipherMAC.update(plaintext)
749 self._cipher = self._siv_ctr_cipher(self._cipherMAC.derive())
751 ct = self._cipher.encrypt(plaintext)
753 if self.mode == MODE_EAX:
754 self._omac[2].update(ct)
756 if self.mode == MODE_GCM:
757 if not self._done_assoc_data:
758 self._cipherMAC.zero_pad()
759 self._done_assoc_data = True
760 self._cipherMAC.update(ct)
761 self._msg_len += len(plaintext)
763 return ct
765 def decrypt(self, ciphertext):
766 """Decrypt data with the key and the parameters set at initialization.
768 A cipher object is stateful: once you have decrypted a message
769 you cannot decrypt (or encrypt) another message with the same
770 object.
772 For `MODE_SIV` (always) and `MODE_CCM` (when ``msg_len`` was not
773 passed at initialization), this method can be called only **once**.
775 For all other modes, the data to decrypt can be broken up in two or
776 more pieces and `decrypt` can be called multiple times.
778 That is, the statement:
780 >>> c.decrypt(a) + c.decrypt(b)
782 is equivalent to:
784 >>> c.decrypt(a+b)
786 That also means that you cannot reuse an object for encrypting
787 or decrypting other data with the same key.
789 This function does not remove any padding from the plaintext.
791 - For `MODE_ECB` and `MODE_CBC`, *ciphertext* length (in bytes) must
792 be a multiple of *block_size*.
794 - For `MODE_CFB`, *ciphertext* length (in bytes) must be a multiple
795 of *segment_size*/8.
797 - For `MODE_OFB`, `MODE_CTR` and all AEAD modes
798 *ciphertext* can be of any length.
800 - For `MODE_OPENPGP`, *plaintext* must be a multiple of *block_size*,
801 unless it is the last chunk of the message.
803 - For `MODE_SIV`, *ciphertext* can be of any length, but it must also
804 include the MAC (concatenated at the end).
806 :Parameters:
807 ciphertext : byte string
808 The piece of data to decrypt (plus the MAC, for `MODE_SIV` only).
810 :Return: the decrypted data (byte string).
811 """
813 if self.mode == MODE_OPENPGP:
814 padding_length = (self.block_size - len(ciphertext) % self.block_size) % self.block_size
815 if padding_length > 0:
816 # CFB mode requires ciphertext to have length multiple
817 # of block size,
818 # but PGP mode allows the last block to be shorter
819 if self._done_last_block:
820 raise ValueError("Only the last chunk is allowed to have length not multiple of %d bytes",
821 self.block_size)
822 self._done_last_block = True
823 padded = ciphertext + b('\x00') * padding_length
824 res = self._cipher.decrypt(padded)[:len(ciphertext)]
825 else:
826 res = self._cipher.decrypt(ciphertext)
827 return res
829 if self.mode == MODE_SIV:
830 raise TypeError("decrypt() not allowed for SIV mode."
831 " Use decrypt_and_verify() instead.")
833 if self.mode in (MODE_CCM, MODE_EAX, MODE_GCM):
835 if self.decrypt not in self._next:
836 raise TypeError("decrypt() can only be called after initialization or an update()")
837 self._next = [self.decrypt, self.verify]
839 if self.mode == MODE_CCM:
840 if self._assoc_len is None:
841 self._start_ccm(assoc_len=self._cipherMAC.get_len())
842 if self._msg_len is None:
843 self._start_ccm(msg_len=len(ciphertext))
844 self._next = [self.verify]
845 if not self._done_assoc_data:
846 self._cipherMAC.zero_pad()
847 self._done_assoc_data = True
849 if self.mode == MODE_GCM:
850 if not self._done_assoc_data:
851 self._cipherMAC.zero_pad()
852 self._done_assoc_data = True
854 self._cipherMAC.update(ciphertext)
855 self._msg_len += len(ciphertext)
857 if self.mode == MODE_EAX:
858 self._omac[2].update(ciphertext)
860 pt = self._cipher.decrypt(ciphertext)
862 if self.mode == MODE_CCM:
863 self._cipherMAC.update(pt)
865 return pt
867 def digest(self):
868 """Compute the *binary* MAC tag in an AEAD mode.
870 When using an AEAD mode like CCM or EAX, the caller invokes
871 this function at the very end.
873 This method returns the MAC that shall be sent to the receiver,
874 together with the ciphertext.
876 :Return: the MAC, as a byte string.
877 """
879 if self.mode not in (MODE_CCM, MODE_EAX, MODE_SIV, MODE_GCM):
880 raise TypeError("digest() not supported by this mode of operation")
882 if self.digest not in self._next:
883 raise TypeError("digest() cannot be called when decrypting or validating a message")
884 self._next = [self.digest]
886 return self._compute_mac()
888 def _compute_mac(self):
889 """Compute MAC without any FSM checks."""
891 if self._tag:
892 return self._tag
894 if self.mode == MODE_CCM:
896 if self._assoc_len is None:
897 self._start_ccm(assoc_len=self._cipherMAC.get_len())
898 if self._msg_len is None:
899 self._start_ccm(msg_len=0)
900 self._cipherMAC.zero_pad()
901 self._tag = strxor(self._cipherMAC.digest(),
902 self._s_0)[:self._mac_len]
904 if self.mode == MODE_GCM:
906 # Step 5 in NIST SP 800-38D, Algorithm 4 - Compute S
907 self._cipherMAC.zero_pad()
908 auth_len = self._cipherMAC.get_len() - self._msg_len
909 for tlen in (auth_len, self._msg_len):
910 self._cipherMAC.update(long_to_bytes(8 * tlen, 8))
911 s_tag = self._cipherMAC.digest()
913 # Step 6 - Compute T
914 self._tag = self._tag_cipher.encrypt(s_tag)[:self._mac_len]
916 if self.mode == MODE_EAX:
917 tag = bchr(0) * self.block_size
918 for i in range(3):
919 tag = strxor(tag, self._omac[i].digest())
920 self._tag = tag[:self._mac_len]
922 if self.mode == MODE_SIV:
923 self._tag = self._cipherMAC.derive()
925 return self._tag
927 def hexdigest(self):
928 """Compute the *printable* MAC tag in an AEAD mode.
930 This method is like `digest`.
932 :Return: the MAC, as a hexadecimal string.
933 """
934 return "".join(["%02x" % bord(x) for x in self.digest()])
936 def verify(self, mac_tag):
937 """Validate the *binary* MAC tag in an AEAD mode.
939 When using an AEAD mode like CCM or EAX, the caller invokes
940 this function at the very end.
942 This method checks if the decrypted message is indeed valid
943 (that is, if the key is correct) and it has not been
944 tampered with while in transit.
946 :Parameters:
947 mac_tag : byte string
948 This is the *binary* MAC, as received from the sender.
949 :Raises ValueError:
950 if the MAC does not match. The message has been tampered with
951 or the key is incorrect.
952 """
954 if self.mode not in (MODE_CCM, MODE_EAX, MODE_SIV, MODE_GCM):
955 raise TypeError("verify() not supported by this mode of operation")
957 if self.verify not in self._next:
958 raise TypeError("verify() cannot be called when encrypting a message")
959 self._next = [self.verify]
961 res = 0
962 # Constant-time comparison
963 for x, y in zip(self._compute_mac(), mac_tag):
964 res |= bord(x) ^ bord(y)
965 if res or len(mac_tag) != self._mac_len:
966 raise ValueError("MAC check failed")
968 def hexverify(self, hex_mac_tag):
969 """Validate the *printable* MAC tag in an AEAD mode.
971 This method is like `verify`.
973 :Parameters:
974 hex_mac_tag : string
975 This is the *printable* MAC, as received from the sender.
976 :Raises ValueError:
977 if the MAC does not match. The message has been tampered with
978 or the key is incorrect.
979 """
981 self.verify(unhexlify(hex_mac_tag))
983 def encrypt_and_digest(self, plaintext):
984 """Perform encrypt() and digest() in one step.
986 :Parameters:
987 plaintext : byte string
988 The piece of data to encrypt.
989 :Return:
990 a tuple with two byte strings:
992 - the encrypted data
993 - the MAC
994 """
996 return self.encrypt(plaintext), self.digest()
998 def decrypt_and_verify(self, ciphertext, mac_tag):
999 """Perform decrypt() and verify() in one step.
1001 :Parameters:
1002 ciphertext : byte string
1003 The piece of data to decrypt.
1004 mac_tag : byte string
1005 This is the *binary* MAC, as received from the sender.
1007 :Return: the decrypted data (byte string).
1008 :Raises ValueError:
1009 if the MAC does not match. The message has been tampered with
1010 or the key is incorrect.
1011 """
1013 if self.mode == MODE_SIV:
1014 if self.decrypt not in self._next:
1015 raise TypeError("decrypt() can only be called"
1016 " after initialization or an update()")
1017 self._next = [self.verify]
1019 # Take the MAC and start the cipher for decryption
1020 self._mac = mac_tag
1021 self._cipher = self._siv_ctr_cipher(self._mac)
1023 pt = self._cipher.decrypt(ciphertext)
1025 if self.nonce:
1026 self._cipherMAC.update(self.nonce)
1027 if pt:
1028 self._cipherMAC.update(pt)
1029 else:
1030 pt = self.decrypt(ciphertext)
1032 self.verify(mac_tag)
1033 return pt