_mode_ccm.py 24 KB

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