_mode_ccm.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2014, Legrandin <helderijs@gmail.com>
  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. Counter with CBC-MAC (CCM) mode.
  32. """
  33. __all__ = ['CcmMode']
  34. import struct
  35. from binascii import unhexlify
  36. from Crypto.Util.py3compat import (byte_string, bord,
  37. _copy_bytes)
  38. from Crypto.Util._raw_api import is_writeable_buffer
  39. from Crypto.Util.strxor import strxor
  40. from Crypto.Util.number import long_to_bytes
  41. from Crypto.Hash import BLAKE2s
  42. from Crypto.Random import get_random_bytes
  43. def enum(**enums):
  44. return type('Enum', (), enums)
  45. MacStatus = enum(NOT_STARTED=0, PROCESSING_AUTH_DATA=1, PROCESSING_PLAINTEXT=2)
  46. class CCMMessageTooLongError(ValueError):
  47. pass
  48. class CcmMode(object):
  49. """Counter with CBC-MAC (CCM).
  50. This is an Authenticated Encryption with Associated Data (`AEAD`_) mode.
  51. It provides both confidentiality and authenticity.
  52. The header of the message may be left in the clear, if needed, and it will
  53. still be subject to authentication. The decryption step tells the receiver
  54. if the message comes from a source that really knowns the secret key.
  55. Additionally, decryption detects if any part of the message - including the
  56. header - has been modified or corrupted.
  57. This mode requires a nonce. The nonce shall never repeat for two
  58. different messages encrypted with the same key, but it does not need
  59. to be random.
  60. Note that there is a trade-off between the size of the nonce and the
  61. maximum size of a single message you can encrypt.
  62. It is important to use a large nonce if the key is reused across several
  63. messages and the nonce is chosen randomly.
  64. It is acceptable to us a short nonce if the key is only used a few times or
  65. if the nonce is taken from a counter.
  66. The following table shows the trade-off when the nonce is chosen at
  67. random. The column on the left shows how many messages it takes
  68. for the keystream to repeat **on average**. In practice, you will want to
  69. stop using the key way before that.
  70. +--------------------+---------------+-------------------+
  71. | Avg. # of messages | nonce | Max. message |
  72. | before keystream | size | size |
  73. | repeats | (bytes) | (bytes) |
  74. +====================+===============+===================+
  75. | 2^52 | 13 | 64K |
  76. +--------------------+---------------+-------------------+
  77. | 2^48 | 12 | 16M |
  78. +--------------------+---------------+-------------------+
  79. | 2^44 | 11 | 4G |
  80. +--------------------+---------------+-------------------+
  81. | 2^40 | 10 | 1T |
  82. +--------------------+---------------+-------------------+
  83. | 2^36 | 9 | 64P |
  84. +--------------------+---------------+-------------------+
  85. | 2^32 | 8 | 16E |
  86. +--------------------+---------------+-------------------+
  87. This mode is only available for ciphers that operate on 128 bits blocks
  88. (e.g. AES but not TDES).
  89. See `NIST SP800-38C`_ or RFC3610_.
  90. .. _`NIST SP800-38C`: http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C.pdf
  91. .. _RFC3610: https://tools.ietf.org/html/rfc3610
  92. .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html
  93. :undocumented: __init__
  94. """
  95. def __init__(self, factory, key, nonce, mac_len, msg_len, assoc_len,
  96. cipher_params):
  97. self.block_size = factory.block_size
  98. """The block size of the underlying cipher, in bytes."""
  99. self.nonce = _copy_bytes(None, None, nonce)
  100. """The nonce used for this cipher instance"""
  101. self._factory = factory
  102. self._key = _copy_bytes(None, None, key)
  103. self._mac_len = mac_len
  104. self._msg_len = msg_len
  105. self._assoc_len = assoc_len
  106. self._cipher_params = cipher_params
  107. self._mac_tag = None # Cache for MAC tag
  108. if self.block_size != 16:
  109. raise ValueError("CCM mode is only available for ciphers"
  110. " that operate on 128 bits blocks")
  111. # MAC tag length (Tlen)
  112. if mac_len not in (4, 6, 8, 10, 12, 14, 16):
  113. raise ValueError("Parameter 'mac_len' must be even"
  114. " and in the range 4..16 (not %d)" % mac_len)
  115. # Nonce value
  116. if not (7 <= len(nonce) <= 13):
  117. raise ValueError("Length of parameter 'nonce' must be"
  118. " in the range 7..13 bytes")
  119. # Message length (if known already)
  120. q = 15 - len(nonce) # length of Q, the encoded message length
  121. if msg_len and len(long_to_bytes(msg_len)) > q:
  122. raise CCMMessageTooLongError("Message too long for a %u-byte nonce" % len(nonce))
  123. # Create MAC object (the tag will be the last block
  124. # bytes worth of ciphertext)
  125. self._mac = self._factory.new(key,
  126. factory.MODE_CBC,
  127. iv=b'\x00' * 16,
  128. **cipher_params)
  129. self._mac_status = MacStatus.NOT_STARTED
  130. self._t = None
  131. # Allowed transitions after initialization
  132. self._next = ["update", "encrypt", "decrypt",
  133. "digest", "verify"]
  134. # Cumulative lengths
  135. self._cumul_assoc_len = 0
  136. self._cumul_msg_len = 0
  137. # Cache for unaligned associated data/plaintext.
  138. # This is a list with byte strings, but when the MAC starts,
  139. # it will become a binary string no longer than the block size.
  140. self._cache = []
  141. # Start CTR cipher, by formatting the counter (A.3)
  142. self._cipher = self._factory.new(key,
  143. self._factory.MODE_CTR,
  144. nonce=struct.pack("B", q - 1) + self.nonce,
  145. **cipher_params)
  146. # S_0, step 6 in 6.1 for j=0
  147. self._s_0 = self._cipher.encrypt(b'\x00' * 16)
  148. # Try to start the MAC
  149. if None not in (assoc_len, msg_len):
  150. self._start_mac()
  151. def _start_mac(self):
  152. assert(self._mac_status == MacStatus.NOT_STARTED)
  153. assert(None not in (self._assoc_len, self._msg_len))
  154. assert(isinstance(self._cache, list))
  155. # Formatting control information and nonce (A.2.1)
  156. q = 15 - len(self.nonce) # length of Q, the encoded message length (2..8)
  157. flags = (self._assoc_len > 0) << 6
  158. flags |= ((self._mac_len - 2) // 2) << 3
  159. flags |= q - 1
  160. b_0 = struct.pack("B", flags) + self.nonce + long_to_bytes(self._msg_len, q)
  161. # Formatting associated data (A.2.2)
  162. # Encoded 'a' is concatenated with the associated data 'A'
  163. assoc_len_encoded = b''
  164. if self._assoc_len > 0:
  165. if self._assoc_len < (2 ** 16 - 2 ** 8):
  166. enc_size = 2
  167. elif self._assoc_len < (2 ** 32):
  168. assoc_len_encoded = b'\xFF\xFE'
  169. enc_size = 4
  170. else:
  171. assoc_len_encoded = b'\xFF\xFF'
  172. enc_size = 8
  173. assoc_len_encoded += long_to_bytes(self._assoc_len, enc_size)
  174. # b_0 and assoc_len_encoded must be processed first
  175. self._cache.insert(0, b_0)
  176. self._cache.insert(1, assoc_len_encoded)
  177. # Process all the data cached so far
  178. first_data_to_mac = b"".join(self._cache)
  179. self._cache = b""
  180. self._mac_status = MacStatus.PROCESSING_AUTH_DATA
  181. self._update(first_data_to_mac)
  182. def _pad_cache_and_update(self):
  183. assert(self._mac_status != MacStatus.NOT_STARTED)
  184. assert(len(self._cache) < self.block_size)
  185. # Associated data is concatenated with the least number
  186. # of zero bytes (possibly none) to reach alignment to
  187. # the 16 byte boundary (A.2.3)
  188. len_cache = len(self._cache)
  189. if len_cache > 0:
  190. self._update(b'\x00' * (self.block_size - len_cache))
  191. def update(self, assoc_data):
  192. """Protect associated data
  193. If there is any associated data, the caller has to invoke
  194. this function one or more times, before using
  195. ``decrypt`` or ``encrypt``.
  196. By *associated data* it is meant any data (e.g. packet headers) that
  197. will not be encrypted and will be transmitted in the clear.
  198. However, the receiver is still able to detect any modification to it.
  199. In CCM, the *associated data* is also called
  200. *additional authenticated data* (AAD).
  201. If there is no associated data, this method must not be called.
  202. The caller may split associated data in segments of any size, and
  203. invoke this method multiple times, each time with the next segment.
  204. :Parameters:
  205. assoc_data : bytes/bytearray/memoryview
  206. A piece of associated data. There are no restrictions on its size.
  207. """
  208. if "update" not in self._next:
  209. raise TypeError("update() can only be called"
  210. " immediately after initialization")
  211. self._next = ["update", "encrypt", "decrypt",
  212. "digest", "verify"]
  213. self._cumul_assoc_len += len(assoc_data)
  214. if self._assoc_len is not None and \
  215. self._cumul_assoc_len > self._assoc_len:
  216. raise ValueError("Associated data is too long")
  217. self._update(assoc_data)
  218. return self
  219. def _update(self, assoc_data_pt=b""):
  220. """Update the MAC with associated data or plaintext
  221. (without FSM checks)"""
  222. # If MAC has not started yet, we just park the data into a list.
  223. # If the data is mutable, we create a copy and store that instead.
  224. if self._mac_status == MacStatus.NOT_STARTED:
  225. if is_writeable_buffer(assoc_data_pt):
  226. assoc_data_pt = _copy_bytes(None, None, assoc_data_pt)
  227. self._cache.append(assoc_data_pt)
  228. return
  229. assert(len(self._cache) < self.block_size)
  230. if len(self._cache) > 0:
  231. filler = min(self.block_size - len(self._cache),
  232. len(assoc_data_pt))
  233. self._cache += _copy_bytes(None, filler, assoc_data_pt)
  234. assoc_data_pt = _copy_bytes(filler, None, assoc_data_pt)
  235. if len(self._cache) < self.block_size:
  236. return
  237. # The cache is exactly one block
  238. self._t = self._mac.encrypt(self._cache)
  239. self._cache = b""
  240. update_len = len(assoc_data_pt) // self.block_size * self.block_size
  241. self._cache = _copy_bytes(update_len, None, assoc_data_pt)
  242. if update_len > 0:
  243. self._t = self._mac.encrypt(assoc_data_pt[:update_len])[-16:]
  244. def encrypt(self, plaintext, output=None):
  245. """Encrypt data with the key set at initialization.
  246. A cipher object is stateful: once you have encrypted a message
  247. you cannot encrypt (or decrypt) another message using the same
  248. object.
  249. This method can be called only **once** if ``msg_len`` was
  250. not passed at initialization.
  251. If ``msg_len`` was given, the data to encrypt can be broken
  252. up in two or more pieces and `encrypt` can be called
  253. multiple times.
  254. That is, the statement:
  255. >>> c.encrypt(a) + c.encrypt(b)
  256. is equivalent to:
  257. >>> c.encrypt(a+b)
  258. This function does not add any padding to the plaintext.
  259. :Parameters:
  260. plaintext : bytes/bytearray/memoryview
  261. The piece of data to encrypt.
  262. It can be of any length.
  263. :Keywords:
  264. output : bytearray/memoryview
  265. The location where the ciphertext must be written to.
  266. If ``None``, the ciphertext is returned.
  267. :Return:
  268. If ``output`` is ``None``, the ciphertext as ``bytes``.
  269. Otherwise, ``None``.
  270. """
  271. if "encrypt" not in self._next:
  272. raise TypeError("encrypt() can only be called after"
  273. " initialization or an update()")
  274. self._next = ["encrypt", "digest"]
  275. # No more associated data allowed from now
  276. if self._assoc_len is None:
  277. assert(isinstance(self._cache, list))
  278. self._assoc_len = sum([len(x) for x in self._cache])
  279. if self._msg_len is not None:
  280. self._start_mac()
  281. else:
  282. if self._cumul_assoc_len < self._assoc_len:
  283. raise ValueError("Associated data is too short")
  284. # Only once piece of plaintext accepted if message length was
  285. # not declared in advance
  286. if self._msg_len is None:
  287. q = 15 - len(self.nonce)
  288. if len(long_to_bytes(len(plaintext))) > q:
  289. raise CCMMessageTooLongError("Message too long for a %u-byte nonce" % len(self.nonce))
  290. self._msg_len = len(plaintext)
  291. self._start_mac()
  292. self._next = ["digest"]
  293. self._cumul_msg_len += len(plaintext)
  294. if self._cumul_msg_len > self._msg_len:
  295. msg = "Message longer than declared for (%u bytes vs %u bytes" % \
  296. (self._cumul_msg_len, self._msg_len)
  297. raise CCMMessageTooLongError(msg)
  298. if self._mac_status == MacStatus.PROCESSING_AUTH_DATA:
  299. # Associated data is concatenated with the least number
  300. # of zero bytes (possibly none) to reach alignment to
  301. # the 16 byte boundary (A.2.3)
  302. self._pad_cache_and_update()
  303. self._mac_status = MacStatus.PROCESSING_PLAINTEXT
  304. self._update(plaintext)
  305. return self._cipher.encrypt(plaintext, output=output)
  306. def decrypt(self, ciphertext, output=None):
  307. """Decrypt data with the key set at initialization.
  308. A cipher object is stateful: once you have decrypted a message
  309. you cannot decrypt (or encrypt) another message with the same
  310. object.
  311. This method can be called only **once** if ``msg_len`` was
  312. not passed at initialization.
  313. If ``msg_len`` was given, the data to decrypt can be
  314. broken up in two or more pieces and `decrypt` can be
  315. called multiple times.
  316. That is, the statement:
  317. >>> c.decrypt(a) + c.decrypt(b)
  318. is equivalent to:
  319. >>> c.decrypt(a+b)
  320. This function does not remove any padding from the plaintext.
  321. :Parameters:
  322. ciphertext : bytes/bytearray/memoryview
  323. The piece of data to decrypt.
  324. It can be of any length.
  325. :Keywords:
  326. output : bytearray/memoryview
  327. The location where the plaintext must be written to.
  328. If ``None``, the plaintext is returned.
  329. :Return:
  330. If ``output`` is ``None``, the plaintext as ``bytes``.
  331. Otherwise, ``None``.
  332. """
  333. if "decrypt" not in self._next:
  334. raise TypeError("decrypt() can only be called"
  335. " after initialization or an update()")
  336. self._next = ["decrypt", "verify"]
  337. # No more associated data allowed from now
  338. if self._assoc_len is None:
  339. assert(isinstance(self._cache, list))
  340. self._assoc_len = sum([len(x) for x in self._cache])
  341. if self._msg_len is not None:
  342. self._start_mac()
  343. else:
  344. if self._cumul_assoc_len < self._assoc_len:
  345. raise ValueError("Associated data is too short")
  346. # Only once piece of ciphertext accepted if message length was
  347. # not declared in advance
  348. if self._msg_len is None:
  349. q = 15 - len(self.nonce)
  350. if len(long_to_bytes(len(ciphertext))) > q:
  351. raise CCMMessageTooLongError("Message too long for a %u-byte nonce" % len(self.nonce))
  352. self._msg_len = len(ciphertext)
  353. self._start_mac()
  354. self._next = ["verify"]
  355. self._cumul_msg_len += len(ciphertext)
  356. if self._cumul_msg_len > self._msg_len:
  357. msg = "Message longer than declared for (%u bytes vs %u bytes" % \
  358. (self._cumul_msg_len, self._msg_len)
  359. raise CCMMessageTooLongError(msg)
  360. if self._mac_status == MacStatus.PROCESSING_AUTH_DATA:
  361. # Associated data is concatenated with the least number
  362. # of zero bytes (possibly none) to reach alignment to
  363. # the 16 byte boundary (A.2.3)
  364. self._pad_cache_and_update()
  365. self._mac_status = MacStatus.PROCESSING_PLAINTEXT
  366. # Encrypt is equivalent to decrypt with the CTR mode
  367. plaintext = self._cipher.encrypt(ciphertext, output=output)
  368. if output is None:
  369. self._update(plaintext)
  370. else:
  371. self._update(output)
  372. return plaintext
  373. def digest(self):
  374. """Compute the *binary* MAC tag.
  375. The caller invokes this function at the very end.
  376. This method returns the MAC that shall be sent to the receiver,
  377. together with the ciphertext.
  378. :Return: the MAC, as a byte string.
  379. """
  380. if "digest" not in self._next:
  381. raise TypeError("digest() cannot be called when decrypting"
  382. " or validating a message")
  383. self._next = ["digest"]
  384. return self._digest()
  385. def _digest(self):
  386. if self._mac_tag:
  387. return self._mac_tag
  388. if self._assoc_len is None:
  389. assert(isinstance(self._cache, list))
  390. self._assoc_len = sum([len(x) for x in self._cache])
  391. if self._msg_len is not None:
  392. self._start_mac()
  393. else:
  394. if self._cumul_assoc_len < self._assoc_len:
  395. raise ValueError("Associated data is too short")
  396. if self._msg_len is None:
  397. self._msg_len = 0
  398. self._start_mac()
  399. if self._cumul_msg_len != self._msg_len:
  400. raise ValueError("Message is too short")
  401. # Both associated data and payload are concatenated with the least
  402. # number of zero bytes (possibly none) that align it to the
  403. # 16 byte boundary (A.2.2 and A.2.3)
  404. self._pad_cache_and_update()
  405. # Step 8 in 6.1 (T xor MSB_Tlen(S_0))
  406. self._mac_tag = strxor(self._t, self._s_0)[:self._mac_len]
  407. return self._mac_tag
  408. def hexdigest(self):
  409. """Compute the *printable* MAC tag.
  410. This method is like `digest`.
  411. :Return: the MAC, as a hexadecimal string.
  412. """
  413. return "".join(["%02x" % bord(x) for x in self.digest()])
  414. def verify(self, received_mac_tag):
  415. """Validate the *binary* MAC tag.
  416. The caller invokes this function at the very end.
  417. This method checks if the decrypted message is indeed valid
  418. (that is, if the key is correct) and it has not been
  419. tampered with while in transit.
  420. :Parameters:
  421. received_mac_tag : bytes/bytearray/memoryview
  422. This is the *binary* MAC, as received from the sender.
  423. :Raises ValueError:
  424. if the MAC does not match. The message has been tampered with
  425. or the key is incorrect.
  426. """
  427. if "verify" not in self._next:
  428. raise TypeError("verify() cannot be called"
  429. " when encrypting a message")
  430. self._next = ["verify"]
  431. self._digest()
  432. secret = get_random_bytes(16)
  433. mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag)
  434. mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag)
  435. if mac1.digest() != mac2.digest():
  436. raise ValueError("MAC check failed")
  437. def hexverify(self, hex_mac_tag):
  438. """Validate the *printable* MAC tag.
  439. This method is like `verify`.
  440. :Parameters:
  441. hex_mac_tag : string
  442. This is the *printable* MAC, as received from the sender.
  443. :Raises ValueError:
  444. if the MAC does not match. The message has been tampered with
  445. or the key is incorrect.
  446. """
  447. self.verify(unhexlify(hex_mac_tag))
  448. def encrypt_and_digest(self, plaintext, output=None):
  449. """Perform encrypt() and digest() in one step.
  450. :Parameters:
  451. plaintext : bytes/bytearray/memoryview
  452. The piece of data to encrypt.
  453. :Keywords:
  454. output : bytearray/memoryview
  455. The location where the ciphertext must be written to.
  456. If ``None``, the ciphertext is returned.
  457. :Return:
  458. a tuple with two items:
  459. - the ciphertext, as ``bytes``
  460. - the MAC tag, as ``bytes``
  461. The first item becomes ``None`` when the ``output`` parameter
  462. specified a location for the result.
  463. """
  464. return self.encrypt(plaintext, output=output), self.digest()
  465. def decrypt_and_verify(self, ciphertext, received_mac_tag, output=None):
  466. """Perform decrypt() and verify() in one step.
  467. :Parameters:
  468. ciphertext : bytes/bytearray/memoryview
  469. The piece of data to decrypt.
  470. received_mac_tag : bytes/bytearray/memoryview
  471. This is the *binary* MAC, as received from the sender.
  472. :Keywords:
  473. output : bytearray/memoryview
  474. The location where the plaintext must be written to.
  475. If ``None``, the plaintext is returned.
  476. :Return: the plaintext as ``bytes`` or ``None`` when the ``output``
  477. parameter specified a location for the result.
  478. :Raises ValueError:
  479. if the MAC does not match. The message has been tampered with
  480. or the key is incorrect.
  481. """
  482. plaintext = self.decrypt(ciphertext, output=output)
  483. self.verify(received_mac_tag)
  484. return plaintext
  485. def _create_ccm_cipher(factory, **kwargs):
  486. """Create a new block cipher, configured in CCM mode.
  487. :Parameters:
  488. factory : module
  489. A symmetric cipher module from `Crypto.Cipher` (like
  490. `Crypto.Cipher.AES`).
  491. :Keywords:
  492. key : bytes/bytearray/memoryview
  493. The secret key to use in the symmetric cipher.
  494. nonce : bytes/bytearray/memoryview
  495. A value that must never be reused for any other encryption.
  496. Its length must be in the range ``[7..13]``.
  497. 11 or 12 bytes are reasonable values in general. Bear in
  498. mind that with CCM there is a trade-off between nonce length and
  499. maximum message size.
  500. If not specified, a 11 byte long random string is used.
  501. mac_len : integer
  502. Length of the MAC, in bytes. It must be even and in
  503. the range ``[4..16]``. The default is 16.
  504. msg_len : integer
  505. Length of the message to (de)cipher.
  506. If not specified, ``encrypt`` or ``decrypt`` may only be called once.
  507. assoc_len : integer
  508. Length of the associated data.
  509. If not specified, all data is internally buffered.
  510. """
  511. try:
  512. key = key = kwargs.pop("key")
  513. except KeyError as e:
  514. raise TypeError("Missing parameter: " + str(e))
  515. nonce = kwargs.pop("nonce", None) # N
  516. if nonce is None:
  517. nonce = get_random_bytes(11)
  518. mac_len = kwargs.pop("mac_len", factory.block_size)
  519. msg_len = kwargs.pop("msg_len", None) # p
  520. assoc_len = kwargs.pop("assoc_len", None) # a
  521. cipher_params = dict(kwargs)
  522. return CcmMode(factory, key, nonce, mac_len, msg_len,
  523. assoc_len, cipher_params)