wec@sdZdgZddlZddlmZddlmZmZmZddl m Z ddl m Z ddl mZdd lmZdd lmZd Zed d ddddZdefdYZdZdS(s" Counter with CBC-MAC (CCM) mode. tCcmModeiN(t unhexlify(t byte_stringtbordt _copy_bytes(tis_writeable_buffer(tstrxor(t long_to_bytes(tBLAKE2s(tget_random_bytescKstdd|S(NtEnum((ttype(tenums((s=/usr/lib64/python2.7/site-packages/Crypto/Cipher/_mode_ccm.pytenum3st NOT_STARTEDitPROCESSING_AUTH_DATAitPROCESSING_PLAINTEXTicBseZdZdZdZdZdZddZddZ ddZ d Z d Z d Z d Zd ZddZddZRS(s Counter with CBC-MAC (CCM). This is an Authenticated Encryption with Associated Data (`AEAD`_) mode. It provides both confidentiality and authenticity. The header of the message may be left in the clear, if needed, and it will still be subject to authentication. The decryption step tells the receiver if the message comes from a source that really knowns the secret key. Additionally, decryption detects if any part of the message - including the header - has been modified or corrupted. This mode requires a nonce. The nonce shall never repeat for two different messages encrypted with the same key, but it does not need to be random. Note that there is a trade-off between the size of the nonce and the maximum size of a single message you can encrypt. It is important to use a large nonce if the key is reused across several messages and the nonce is chosen randomly. It is acceptable to us a short nonce if the key is only used a few times or if the nonce is taken from a counter. The following table shows the trade-off when the nonce is chosen at random. The column on the left shows how many messages it takes for the keystream to repeat **on average**. In practice, you will want to stop using the key way before that. +--------------------+---------------+-------------------+ | Avg. # of messages | nonce | Max. message | | before keystream | size | size | | repeats | (bytes) | (bytes) | +====================+===============+===================+ | 2^52 | 13 | 64K | +--------------------+---------------+-------------------+ | 2^48 | 12 | 16M | +--------------------+---------------+-------------------+ | 2^44 | 11 | 4G | +--------------------+---------------+-------------------+ | 2^40 | 10 | 1T | +--------------------+---------------+-------------------+ | 2^36 | 9 | 64P | +--------------------+---------------+-------------------+ | 2^32 | 8 | 16E | +--------------------+---------------+-------------------+ This mode is only available for ciphers that operate on 128 bits blocks (e.g. AES but not TDES). See `NIST SP800-38C`_ or RFC3610_. .. _`NIST SP800-38C`: http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C.pdf .. _RFC3610: https://tools.ietf.org/html/rfc3610 .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html :undocumented: __init__ c Cs|j|_tdd||_||_tdd||_||_||_||_||_ d|_ |jdkrt dn|dkrt d |n|od t |kod knst d n|jj ||jd d||_tj|_d|_dddddg|_d|_d|_g|_dt |}|jj ||jjdtjd|d|j||_|jjd|_d||fkr|jndS(NisFCCM mode is only available for ciphers that operate on 128 bits blocksiiii i is@Parameter 'mac_len' must be even and in the range 4..16 (not %d)ii s<Length of parameter 'nonce' must be in the range 7..13 bytestivttupdatetencrypttdecrypttdigesttverifyiitnoncetBi(iiii i iitR(t block_sizeRtNoneRt_factoryt_keyt_mac_lent_msg_lent _assoc_lent_cipher_paramst_mac_tagt ValueErrortlentnewtMODE_CBCt_mact MacStatusRt _mac_statust_tt_nextt_cumul_assoc_lent_cumul_msg_lent_cachetMODE_CTRtstructtpackt_cipherRt_s_0t _start_mac( tselftfactorytkeyRtmac_lentmsg_lent assoc_lent cipher_paramstq((s=/usr/lib64/python2.7/site-packages/Crypto/Cipher/_mode_ccm.pyt__init__tsF         (            cCs|jtjkstd|j|jfks6tt|jt sNtdt |j }d|jdkd|j dd|d}t jd||j t|j|}d}|jdkr,|jddkrd}n*|jdkrd }d }n d }d}|t|j|7}n|jjd||jjd|dj|j}d|_tj|_|j|dS(Nii@iiiiRtii sisiiI(R*R)RtAssertionErrorRR!R t isinstanceR/tlistR%RRR1R2RtinserttjoinRt_update(R6R=tflagstb_0tassoc_len_encodedtenc_sizetfirst_data_to_mac((s=/usr/lib64/python2.7/site-packages/Crypto/Cipher/_mode_ccm.pyR5s.# )    cCsp|jtjkstt|j|jks6tt|j}|dkrl|jd|j|ndS(NiR(R*R)RR@R%R/RRE(R6t len_cache((s=/usr/lib64/python2.7/site-packages/Crypto/Cipher/_mode_ccm.pyt_pad_cache_and_updates  cCsd|jkrtdndddddg|_|jt|7_|jdk r{|j|jkr{tdn|j||S( sxProtect associated data If there is any associated data, the caller has to invoke this function one or more times, before using ``decrypt`` or ``encrypt``. By *associated data* it is meant any data (e.g. packet headers) that will not be encrypted and will be transmitted in the clear. However, the receiver is still able to detect any modification to it. In CCM, the *associated data* is also called *additional authenticated data* (AAD). If there is no associated data, this method must not be called. The caller may split associated data in segments of any size, and invoke this method multiple times, each time with the next segment. :Parameters: assoc_data : bytes/bytearray/memoryview A piece of associated data. There are no restrictions on its size. Rs<update() can only be called immediately after initializationRRRRsAssociated data is too longN(R,t TypeErrorR-R%R!RR$RE(R6t assoc_data((s=/usr/lib64/python2.7/site-packages/Crypto/Cipher/_mode_ccm.pyRs  R?cCsk|jtjkrGt|r3tdd|}n|jj|dSt|j|j kset t|jdkr t |j t|jt|}|jtd||7_t|d|}t|j|j krdS|j j |j|_d|_nt||j |j }t|d||_|dkrg|j j || d|_ndS(sPUpdate the MAC with associated data or plaintext (without FSM checks)NiR?i(R*R)RRRRR/tappendR%RR@tminR(RR+(R6t assoc_data_pttfillert update_len((s=/usr/lib64/python2.7/site-packages/Crypto/Cipher/_mode_ccm.pyREs&   cCszd|jkrtdnddg|_|jdkrt|jtsTttg|jD]}t |^qa|_|j dk r|j qn!|j |jkrt dn|j dkrt ||_ |j dg|_n|jt |7_|j|j kr,t dn|jtjkrW|jtj|_n|j||jj|d|S(sbEncrypt data with the key set at initialization. A cipher object is stateful: once you have encrypted a message you cannot encrypt (or decrypt) another message using the same object. This method can be called only **once** if ``msg_len`` was not passed at initialization. If ``msg_len`` was given, the data to encrypt can be broken up in two or more pieces and `encrypt` can be called multiple times. That is, the statement: >>> c.encrypt(a) + c.encrypt(b) is equivalent to: >>> c.encrypt(a+b) This function does not add any padding to the plaintext. :Parameters: plaintext : bytes/bytearray/memoryview The piece of data to encrypt. It can be of any length. :Keywords: output : bytearray/memoryview The location where the ciphertext must be written to. If ``None``, the ciphertext is returned. :Return: If ``output`` is ``None``, the ciphertext as ``bytes``. Otherwise, ``None``. Rs@encrypt() can only be called after initialization or an update()RsAssociated data is too shortsMessage is too longtoutputN(R,RMR!RRAR/RBR@tsumR%R R5R-R$R.R*R)RRLRRER3R(R6t plaintextRTtx((s=/usr/lib64/python2.7/site-packages/Crypto/Cipher/_mode_ccm.pyR.s,%+   cCsd|jkrtdnddg|_|jdkrt|jtsTttg|jD]}t |^qa|_|j dk r|j qn!|j |jkrt dn|j dkrt ||_ |j dg|_n|jt |7_|j|j kr,t dn|jtjkrW|jtj|_n|jj|d|}|dkr|j|n |j||S(sdDecrypt data with the key set at initialization. A cipher object is stateful: once you have decrypted a message you cannot decrypt (or encrypt) another message with the same object. This method can be called only **once** if ``msg_len`` was not passed at initialization. If ``msg_len`` was given, the data to decrypt can be broken up in two or more pieces and `decrypt` can be called multiple times. That is, the statement: >>> c.decrypt(a) + c.decrypt(b) is equivalent to: >>> c.decrypt(a+b) This function does not remove any padding from the plaintext. :Parameters: ciphertext : bytes/bytearray/memoryview The piece of data to decrypt. It can be of any length. :Keywords: output : bytearray/memoryview The location where the plaintext must be written to. If ``None``, the plaintext is returned. :Return: If ``output`` is ``None``, the plaintext as ``bytes``. Otherwise, ``None``. Rs@decrypt() can only be called after initialization or an update()RsAssociated data is too shortsMessage is too longRTN(R,RMR!RRAR/RBR@RUR%R R5R-R$R.R*R)RRLRR3RRE(R6t ciphertextRTRWRV((s=/usr/lib64/python2.7/site-packages/Crypto/Cipher/_mode_ccm.pyRws2%+    cCs4d|jkrtdndg|_|jS(sCompute the *binary* MAC tag. The caller invokes this function at the very end. This method returns the MAC that shall be sent to the receiver, together with the ciphertext. :Return: the MAC, as a byte string. RsAdigest() cannot be called when decrypting or validating a message(R,RMt_digest(R6((s=/usr/lib64/python2.7/site-packages/Crypto/Cipher/_mode_ccm.pyRs  cCs|jr|jS|jdkrt|jts7ttg|jD]}t|^qD|_|j dk r|j qn!|j |jkrt dn|j dkrd|_ |j n|j |j krt dn|jt|j|j|j |_|jS(NsAssociated data is too shortisMessage is too short(R#R!RRAR/RBR@RUR%R R5R-R$R.RLRR+R4R(R6RW((s=/usr/lib64/python2.7/site-packages/Crypto/Cipher/_mode_ccm.pyRYs" +   cCs0djg|jD]}dt|^qS(sCompute the *printable* MAC tag. This method is like `digest`. :Return: the MAC, as a hexadecimal string. R?s%02x(RDRR(R6RW((s=/usr/lib64/python2.7/site-packages/Crypto/Cipher/_mode_ccm.pyt hexdigestscCsd|jkrtdndg|_|jtd}tjddd|d|j}tjddd|d|}|j|jkrtdnd S( s(Validate the *binary* MAC tag. The caller invokes this function at the very end. This method checks if the decrypted message is indeed valid (that is, if the key is correct) and it has not been tampered with while in transit. :Parameters: received_mac_tag : bytes/bytearray/memoryview This is the *binary* MAC, as received from the sender. :Raises ValueError: if the MAC does not match. The message has been tampered with or the key is incorrect. Rs3verify() cannot be called when encrypting a messageit digest_bitsiR8tdatasMAC check failedN( R,RMRYR RR&R#RR$(R6treceived_mac_tagtsecrettmac1tmac2((s=/usr/lib64/python2.7/site-packages/Crypto/Cipher/_mode_ccm.pyRs   !cCs|jt|dS(sWValidate the *printable* MAC tag. This method is like `verify`. :Parameters: hex_mac_tag : string This is the *printable* MAC, as received from the sender. :Raises ValueError: if the MAC does not match. The message has been tampered with or the key is incorrect. N(RR(R6t hex_mac_tag((s=/usr/lib64/python2.7/site-packages/Crypto/Cipher/_mode_ccm.pyt hexverifys cCs|j|d||jfS(s\Perform encrypt() and digest() in one step. :Parameters: plaintext : bytes/bytearray/memoryview The piece of data to encrypt. :Keywords: output : bytearray/memoryview The location where the ciphertext must be written to. If ``None``, the ciphertext is returned. :Return: a tuple with two items: - the ciphertext, as ``bytes`` - the MAC tag, as ``bytes`` The first item becomes ``None`` when the ``output`` parameter specified a location for the result. RT(RR(R6RVRT((s=/usr/lib64/python2.7/site-packages/Crypto/Cipher/_mode_ccm.pytencrypt_and_digest+scCs&|j|d|}|j||S(sPerform decrypt() and verify() in one step. :Parameters: ciphertext : bytes/bytearray/memoryview The piece of data to decrypt. received_mac_tag : bytes/bytearray/memoryview This is the *binary* MAC, as received from the sender. :Keywords: output : bytearray/memoryview The location where the plaintext must be written to. If ``None``, the plaintext is returned. :Return: the plaintext as ``bytes`` or ``None`` when the ``output`` parameter specified a location for the result. :Raises ValueError: if the MAC does not match. The message has been tampered with or the key is incorrect. RT(RR(R6RXR]RTRV((s=/usr/lib64/python2.7/site-packages/Crypto/Cipher/_mode_ccm.pytdecrypt_and_verifyAs N(t__name__t __module__t__doc__R>R5RLRRERRRRRYRZRRbRcRd(((s=/usr/lib64/python2.7/site-packages/Crypto/Cipher/_mode_ccm.pyR9s9 D $ & I N     c Ksy|jd}}Wn)tk rB}tdt|nX|jdd}|dkrptd}n|jd|j}|jdd}|jdd}t|}t|||||||S( sNCreate a new block cipher, configured in CCM mode. :Parameters: factory : module A symmetric cipher module from `Crypto.Cipher` (like `Crypto.Cipher.AES`). :Keywords: key : bytes/bytearray/memoryview The secret key to use in the symmetric cipher. nonce : bytes/bytearray/memoryview A value that must never be reused for any other encryption. Its length must be in the range ``[7..13]``. 11 or 12 bytes are reasonable values in general. Bear in mind that with CCM there is a trade-off between nonce length and maximum message size. If not specified, a 11 byte long random string is used. mac_len : integer Length of the MAC, in bytes. It must be even and in the range ``[4..16]``. The default is 16. msg_len : integer Length of the message to (de)cipher. If not specified, ``encrypt`` or ``decrypt`` may only be called once. assoc_len : integer Length of the associated data. If not specified, all data is internally buffered. R8sMissing parameter: Ri R9R:R;N( tpoptKeyErrorRMtstrRR RtdictR( R7tkwargsR8teRR9R:R;R<((s=/usr/lib64/python2.7/site-packages/Crypto/Cipher/_mode_ccm.pyt_create_ccm_cipherYs#  (Rgt__all__R1tbinasciiRtCrypto.Util.py3compatRRRtCrypto.Util._raw_apiRtCrypto.Util.strxorRtCrypto.Util.numberRt Crypto.HashRt Crypto.RandomR R R)tobjectRRn(((s=/usr/lib64/python2.7/site-packages/Crypto/Cipher/_mode_ccm.pyt!s   "