1.. hazmat:: /fernet 2 3 4Symmetric encryption 5==================== 6 7.. module:: cryptography.hazmat.primitives.ciphers 8 9Symmetric encryption is a way to `encrypt`_ or hide the contents of material 10where the sender and receiver both use the same secret key. Note that symmetric 11encryption is **not** sufficient for most applications because it only 12provides secrecy but not authenticity. That means an attacker can't see the 13message but an attacker can create bogus messages and force the application to 14decrypt them. 15 16For this reason it is **strongly** recommended to combine encryption with a 17message authentication code, such as :doc:`HMAC </hazmat/primitives/mac/hmac>`, 18in an "encrypt-then-MAC" formulation as `described by Colin Percival`_. 19``cryptography`` includes a recipe named :doc:`/fernet` that does this for you. 20**To minimize the risk of security issues you should evaluate Fernet to see if 21it fits your needs before implementing anything using this module.** 22 23.. class:: Cipher(algorithm, mode, backend) 24 25 Cipher objects combine an algorithm such as 26 :class:`~cryptography.hazmat.primitives.ciphers.algorithms.AES` with a 27 mode like 28 :class:`~cryptography.hazmat.primitives.ciphers.modes.CBC` or 29 :class:`~cryptography.hazmat.primitives.ciphers.modes.CTR`. A simple 30 example of encrypting and then decrypting content with AES is: 31 32 .. doctest:: 33 34 >>> import os 35 >>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes 36 >>> from cryptography.hazmat.backends import default_backend 37 >>> backend = default_backend() 38 >>> key = os.urandom(32) 39 >>> iv = os.urandom(16) 40 >>> cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend) 41 >>> encryptor = cipher.encryptor() 42 >>> ct = encryptor.update(b"a secret message") + encryptor.finalize() 43 >>> decryptor = cipher.decryptor() 44 >>> decryptor.update(ct) + decryptor.finalize() 45 b'a secret message' 46 47 :param algorithms: A 48 :class:`~cryptography.hazmat.primitives.ciphers.CipherAlgorithm` 49 instance such as those described 50 :ref:`below <symmetric-encryption-algorithms>`. 51 :param mode: A :class:`~cryptography.hazmat.primitives.ciphers.modes.Mode` 52 instance such as those described 53 :ref:`below <symmetric-encryption-modes>`. 54 :param backend: A 55 :class:`~cryptography.hazmat.backends.interfaces.CipherBackend` 56 instance. 57 58 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if the 59 provided ``backend`` does not implement 60 :class:`~cryptography.hazmat.backends.interfaces.CipherBackend` 61 62 .. method:: encryptor() 63 64 :return: An encrypting 65 :class:`~cryptography.hazmat.primitives.ciphers.CipherContext` 66 instance. 67 68 If the backend doesn't support the requested combination of ``cipher`` 69 and ``mode`` an :class:`~cryptography.exceptions.UnsupportedAlgorithm` 70 exception will be raised. 71 72 .. method:: decryptor() 73 74 :return: A decrypting 75 :class:`~cryptography.hazmat.primitives.ciphers.CipherContext` 76 instance. 77 78 If the backend doesn't support the requested combination of ``cipher`` 79 and ``mode`` an :class:`~cryptography.exceptions.UnsupportedAlgorithm` 80 exception will be raised. 81 82.. _symmetric-encryption-algorithms: 83 84Algorithms 85~~~~~~~~~~ 86 87.. currentmodule:: cryptography.hazmat.primitives.ciphers.algorithms 88 89.. class:: AES(key) 90 91 AES (Advanced Encryption Standard) is a block cipher standardized by NIST. 92 AES is both fast, and cryptographically strong. It is a good default 93 choice for encryption. 94 95 :param key: The secret key. This must be kept secret. Either ``128``, 96 ``192``, or ``256`` :term:`bits` long. 97 :type key: :term:`bytes-like` 98 99.. class:: Camellia(key) 100 101 Camellia is a block cipher approved for use by `CRYPTREC`_ and ISO/IEC. 102 It is considered to have comparable security and performance to AES but 103 is not as widely studied or deployed. 104 105 :param key: The secret key. This must be kept secret. Either ``128``, 106 ``192``, or ``256`` :term:`bits` long. 107 :type key: :term:`bytes-like` 108 109.. class:: ChaCha20(key) 110 111 .. versionadded:: 2.1 112 113 .. note:: 114 115 In most cases users should use 116 :class:`~cryptography.hazmat.primitives.ciphers.aead.ChaCha20Poly1305` 117 instead of this class. `ChaCha20` alone does not provide integrity 118 so it must be combined with a MAC to be secure. 119 :class:`~cryptography.hazmat.primitives.ciphers.aead.ChaCha20Poly1305` 120 does this for you. 121 122 ChaCha20 is a stream cipher used in several IETF protocols. It is 123 standardized in :rfc:`7539`. 124 125 :param key: The secret key. This must be kept secret. ``256`` 126 :term:`bits` (32 bytes) in length. 127 :type key: :term:`bytes-like` 128 129 :param nonce: Should be unique, a :term:`nonce`. It is 130 critical to never reuse a ``nonce`` with a given key. Any reuse of a 131 nonce with the same key compromises the security of every message 132 encrypted with that key. The nonce does not need to be kept secret 133 and may be included with the ciphertext. This must be ``128`` 134 :term:`bits` in length. 135 :type nonce: :term:`bytes-like` 136 137 .. note:: 138 139 In :rfc:`7539` the nonce is defined as a 96-bit value that is later 140 concatenated with a block counter (encoded as a 32-bit 141 little-endian). If you have a separate nonce and block counter 142 you will need to concatenate it yourself before passing it. For 143 example, if you have an initial block counter of 2 and a 96-bit 144 nonce the concatenated nonce would be 145 ``struct.pack("<i", 2) + nonce``. 146 147 .. doctest:: 148 149 >>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes 150 >>> from cryptography.hazmat.backends import default_backend 151 >>> nonce = os.urandom(16) 152 >>> algorithm = algorithms.ChaCha20(key, nonce) 153 >>> cipher = Cipher(algorithm, mode=None, backend=default_backend()) 154 >>> encryptor = cipher.encryptor() 155 >>> ct = encryptor.update(b"a secret message") 156 >>> decryptor = cipher.decryptor() 157 >>> decryptor.update(ct) 158 b'a secret message' 159 160.. class:: TripleDES(key) 161 162 Triple DES (Data Encryption Standard), sometimes referred to as 3DES, is a 163 block cipher standardized by NIST. Triple DES has known crypto-analytic 164 flaws, however none of them currently enable a practical attack. 165 Nonetheless, Triple DES is not recommended for new applications because it 166 is incredibly slow; old applications should consider moving away from it. 167 168 :param key: The secret key. This must be kept secret. Either ``64``, 169 ``128``, or ``192`` :term:`bits` long. DES only uses ``56``, ``112``, 170 or ``168`` bits of the key as there is a parity byte in each component 171 of the key. Some writing refers to there being up to three separate 172 keys that are each ``56`` bits long, they can simply be concatenated 173 to produce the full key. 174 :type key: :term:`bytes-like` 175 176.. class:: CAST5(key) 177 178 .. versionadded:: 0.2 179 180 CAST5 (also known as CAST-128) is a block cipher approved for use in the 181 Canadian government by the `Communications Security Establishment`_. It is 182 a variable key length cipher and supports keys from 40-128 :term:`bits` in 183 length. 184 185 :param key: The secret key, This must be kept secret. 40 to 128 186 :term:`bits` in length in increments of 8 bits. 187 :type key: :term:`bytes-like` 188 189.. class:: SEED(key) 190 191 .. versionadded:: 0.4 192 193 SEED is a block cipher developed by the Korea Information Security Agency 194 (KISA). It is defined in :rfc:`4269` and is used broadly throughout South 195 Korean industry, but rarely found elsewhere. 196 197 :param key: The secret key. This must be kept secret. ``128`` 198 :term:`bits` in length. 199 :type key: :term:`bytes-like` 200 201Weak ciphers 202------------ 203 204.. warning:: 205 206 These ciphers are considered weak for a variety of reasons. New 207 applications should avoid their use and existing applications should 208 strongly consider migrating away. 209 210.. class:: Blowfish(key) 211 212 Blowfish is a block cipher developed by Bruce Schneier. It is known to be 213 susceptible to attacks when using weak keys. The author has recommended 214 that users of Blowfish move to newer algorithms such as :class:`AES`. 215 216 :param key: The secret key. This must be kept secret. 32 to 448 217 :term:`bits` in length in increments of 8 bits. 218 :type key: :term:`bytes-like` 219 220.. class:: ARC4(key) 221 222 ARC4 (Alleged RC4) is a stream cipher with serious weaknesses in its 223 initial stream output. Its use is strongly discouraged. ARC4 does not use 224 mode constructions. 225 226 :param key: The secret key. This must be kept secret. Either ``40``, 227 ``56``, ``64``, ``80``, ``128``, ``192``, or ``256`` :term:`bits` in 228 length. 229 :type key: :term:`bytes-like` 230 231 .. doctest:: 232 233 >>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes 234 >>> from cryptography.hazmat.backends import default_backend 235 >>> algorithm = algorithms.ARC4(key) 236 >>> cipher = Cipher(algorithm, mode=None, backend=default_backend()) 237 >>> encryptor = cipher.encryptor() 238 >>> ct = encryptor.update(b"a secret message") 239 >>> decryptor = cipher.decryptor() 240 >>> decryptor.update(ct) 241 b'a secret message' 242 243.. class:: IDEA(key) 244 245 IDEA (`International Data Encryption Algorithm`_) is a block cipher created 246 in 1991. It is an optional component of the `OpenPGP`_ standard. This cipher 247 is susceptible to attacks when using weak keys. It is recommended that you 248 do not use this cipher for new applications. 249 250 :param key: The secret key. This must be kept secret. ``128`` 251 :term:`bits` in length. 252 :type key: :term:`bytes-like` 253 254 255.. _symmetric-encryption-modes: 256 257Modes 258~~~~~ 259 260.. module:: cryptography.hazmat.primitives.ciphers.modes 261 262.. class:: CBC(initialization_vector) 263 264 CBC (Cipher Block Chaining) is a mode of operation for block ciphers. It is 265 considered cryptographically strong. 266 267 **Padding is required when using this mode.** 268 269 :param initialization_vector: Must be :doc:`random bytes 270 </random-numbers>`. They do not need to be kept secret and they can be 271 included in a transmitted message. Must be the same number of bytes as 272 the ``block_size`` of the cipher. Each time something is encrypted a 273 new ``initialization_vector`` should be generated. Do not reuse an 274 ``initialization_vector`` with a given ``key``, and particularly do not 275 use a constant ``initialization_vector``. 276 :type initialization_vector: :term:`bytes-like` 277 278 A good construction looks like: 279 280 .. doctest:: 281 282 >>> import os 283 >>> from cryptography.hazmat.primitives.ciphers.modes import CBC 284 >>> iv = os.urandom(16) 285 >>> mode = CBC(iv) 286 287 While the following is bad and will leak information: 288 289 .. doctest:: 290 291 >>> from cryptography.hazmat.primitives.ciphers.modes import CBC 292 >>> iv = b"a" * 16 293 >>> mode = CBC(iv) 294 295 296.. class:: CTR(nonce) 297 298 .. warning:: 299 300 Counter mode is not recommended for use with block ciphers that have a 301 block size of less than 128-:term:`bits`. 302 303 CTR (Counter) is a mode of operation for block ciphers. It is considered 304 cryptographically strong. It transforms a block cipher into a stream 305 cipher. 306 307 **This mode does not require padding.** 308 309 :param nonce: Should be unique, a :term:`nonce`. It is 310 critical to never reuse a ``nonce`` with a given key. Any reuse of a 311 nonce with the same key compromises the security of every message 312 encrypted with that key. Must be the same number of bytes as the 313 ``block_size`` of the cipher with a given key. The nonce does not need 314 to be kept secret and may be included with the ciphertext. 315 :type nonce: :term:`bytes-like` 316 317.. class:: OFB(initialization_vector) 318 319 OFB (Output Feedback) is a mode of operation for block ciphers. It 320 transforms a block cipher into a stream cipher. 321 322 **This mode does not require padding.** 323 324 :param initialization_vector: Must be :doc:`random bytes 325 </random-numbers>`. They do not need to be kept secret and they can be 326 included in a transmitted message. Must be the same number of bytes as 327 the ``block_size`` of the cipher. Do not reuse an 328 ``initialization_vector`` with a given ``key``. 329 :type initialization_vector: :term:`bytes-like` 330 331.. class:: CFB(initialization_vector) 332 333 CFB (Cipher Feedback) is a mode of operation for block ciphers. It 334 transforms a block cipher into a stream cipher. 335 336 **This mode does not require padding.** 337 338 :param initialization_vector: Must be :doc:`random bytes 339 </random-numbers>`. They do not need to be kept secret and they can be 340 included in a transmitted message. Must be the same number of bytes as 341 the ``block_size`` of the cipher. Do not reuse an 342 ``initialization_vector`` with a given ``key``. 343 :type initialization_vector: :term:`bytes-like` 344 345.. class:: CFB8(initialization_vector) 346 347 CFB (Cipher Feedback) is a mode of operation for block ciphers. It 348 transforms a block cipher into a stream cipher. The CFB8 variant uses an 349 8-bit shift register. 350 351 **This mode does not require padding.** 352 353 :param initialization_vector: Must be :doc:`random bytes 354 </random-numbers>`. They do not need to be kept secret and they can be 355 included in a transmitted message. Must be the same number of bytes as 356 the ``block_size`` of the cipher. Do not reuse an 357 ``initialization_vector`` with a given ``key``. 358 :type initialization_vector: :term:`bytes-like` 359 360.. class:: GCM(initialization_vector, tag=None, min_tag_length=16) 361 362 .. danger:: 363 364 If you are encrypting data that can fit into memory you should strongly 365 consider using 366 :class:`~cryptography.hazmat.primitives.ciphers.aead.AESGCM` instead 367 of this. 368 369 When using this mode you **must** not use the decrypted data until 370 the appropriate finalization method 371 (:meth:`~cryptography.hazmat.primitives.ciphers.CipherContext.finalize` 372 or 373 :meth:`~cryptography.hazmat.primitives.ciphers.AEADDecryptionContext.finalize_with_tag`) 374 has been called. GCM provides **no** guarantees of ciphertext integrity 375 until decryption is complete. 376 377 GCM (Galois Counter Mode) is a mode of operation for block ciphers. An 378 AEAD (authenticated encryption with additional data) mode is a type of 379 block cipher mode that simultaneously encrypts the message as well as 380 authenticating it. Additional unencrypted data may also be authenticated. 381 Additional means of verifying integrity such as 382 :doc:`HMAC </hazmat/primitives/mac/hmac>` are not necessary. 383 384 **This mode does not require padding.** 385 386 :param initialization_vector: Must be unique, a :term:`nonce`. 387 They do not need to be kept secret and they can be included in a 388 transmitted message. NIST `recommends a 96-bit IV length`_ for 389 performance critical situations but it can be up to 2\ :sup:`64` - 1 390 :term:`bits`. Do not reuse an ``initialization_vector`` with a given 391 ``key``. 392 :type initialization_vector: :term:`bytes-like` 393 394 .. note:: 395 396 Cryptography will generate a 128-bit tag when finalizing encryption. 397 You can shorten a tag by truncating it to the desired length but this 398 is **not recommended** as it makes it easier to forge messages, and 399 also potentially leaks the key (`NIST SP-800-38D`_ recommends 400 96-:term:`bits` or greater). Applications wishing to allow truncation 401 can pass the ``min_tag_length`` parameter. 402 403 .. versionchanged:: 0.5 404 405 The ``min_tag_length`` parameter was added in ``0.5``, previously 406 truncation down to ``4`` bytes was always allowed. 407 408 :param bytes tag: The tag bytes to verify during decryption. When 409 encrypting this must be ``None``. When decrypting, it may be ``None`` 410 if the tag is supplied on finalization using 411 :meth:`~cryptography.hazmat.primitives.ciphers.AEADDecryptionContext.finalize_with_tag`. 412 Otherwise, the tag is mandatory. 413 414 :param int min_tag_length: The minimum length ``tag`` must be. By default 415 this is ``16``, meaning tag truncation is not allowed. Allowing tag 416 truncation is strongly discouraged for most applications. 417 418 :raises ValueError: This is raised if ``len(tag) < min_tag_length`` or the 419 ``initialization_vector`` is too short. 420 421 :raises NotImplementedError: This is raised if the version of the OpenSSL 422 backend used is 1.0.1 or earlier. 423 424 An example of securely encrypting and decrypting data with ``AES`` in the 425 ``GCM`` mode looks like: 426 427 .. testcode:: 428 429 import os 430 431 from cryptography.hazmat.backends import default_backend 432 from cryptography.hazmat.primitives.ciphers import ( 433 Cipher, algorithms, modes 434 ) 435 436 def encrypt(key, plaintext, associated_data): 437 # Generate a random 96-bit IV. 438 iv = os.urandom(12) 439 440 # Construct an AES-GCM Cipher object with the given key and a 441 # randomly generated IV. 442 encryptor = Cipher( 443 algorithms.AES(key), 444 modes.GCM(iv), 445 backend=default_backend() 446 ).encryptor() 447 448 # associated_data will be authenticated but not encrypted, 449 # it must also be passed in on decryption. 450 encryptor.authenticate_additional_data(associated_data) 451 452 # Encrypt the plaintext and get the associated ciphertext. 453 # GCM does not require padding. 454 ciphertext = encryptor.update(plaintext) + encryptor.finalize() 455 456 return (iv, ciphertext, encryptor.tag) 457 458 def decrypt(key, associated_data, iv, ciphertext, tag): 459 # Construct a Cipher object, with the key, iv, and additionally the 460 # GCM tag used for authenticating the message. 461 decryptor = Cipher( 462 algorithms.AES(key), 463 modes.GCM(iv, tag), 464 backend=default_backend() 465 ).decryptor() 466 467 # We put associated_data back in or the tag will fail to verify 468 # when we finalize the decryptor. 469 decryptor.authenticate_additional_data(associated_data) 470 471 # Decryption gets us the authenticated plaintext. 472 # If the tag does not match an InvalidTag exception will be raised. 473 return decryptor.update(ciphertext) + decryptor.finalize() 474 475 iv, ciphertext, tag = encrypt( 476 key, 477 b"a secret message!", 478 b"authenticated but not encrypted payload" 479 ) 480 481 print(decrypt( 482 key, 483 b"authenticated but not encrypted payload", 484 iv, 485 ciphertext, 486 tag 487 )) 488 489 .. testoutput:: 490 491 b'a secret message!' 492 493.. class:: XTS(tweak) 494 495 .. versionadded:: 2.1 496 497 .. warning:: 498 499 XTS mode is meant for disk encryption and should not be used in other 500 contexts. ``cryptography`` only supports XTS mode with 501 :class:`~cryptography.hazmat.primitives.ciphers.algorithms.AES`. 502 503 .. note:: 504 505 AES XTS keys are double length. This means that to do AES-128 506 encryption in XTS mode you need a 256-bit key. Similarly, AES-256 507 requires passing a 512-bit key. AES 192 is not supported in XTS mode. 508 509 XTS (XEX-based tweaked-codebook mode with ciphertext stealing) is a mode 510 of operation for the AES block cipher that is used for `disk encryption`_. 511 512 **This mode does not require padding.** 513 514 :param tweak: The tweak is a 16 byte value typically derived from 515 something like the disk sector number. A given ``(tweak, key)`` pair 516 should not be reused, although doing so is less catastrophic than 517 in CTR mode. 518 :type tweak: :term:`bytes-like` 519 520Insecure modes 521-------------- 522 523.. warning:: 524 525 These modes are insecure. New applications should never make use of them, 526 and existing applications should strongly consider migrating away. 527 528 529.. class:: ECB() 530 531 ECB (Electronic Code Book) is the simplest mode of operation for block 532 ciphers. Each block of data is encrypted in the same way. This means 533 identical plaintext blocks will always result in identical ciphertext 534 blocks, which can leave `significant patterns in the output`_. 535 536 **Padding is required when using this mode.** 537 538Interfaces 539~~~~~~~~~~ 540 541.. currentmodule:: cryptography.hazmat.primitives.ciphers 542 543.. class:: CipherContext 544 545 When calling ``encryptor()`` or ``decryptor()`` on a ``Cipher`` object 546 the result will conform to the ``CipherContext`` interface. You can then 547 call ``update(data)`` with data until you have fed everything into the 548 context. Once that is done call ``finalize()`` to finish the operation and 549 obtain the remainder of the data. 550 551 Block ciphers require that the plaintext or ciphertext always be a multiple 552 of their block size. Because of that **padding** is sometimes required to 553 make a message the correct size. ``CipherContext`` will not automatically 554 apply any padding; you'll need to add your own. For block ciphers the 555 recommended padding is 556 :class:`~cryptography.hazmat.primitives.padding.PKCS7`. If you are using a 557 stream cipher mode (such as 558 :class:`~cryptography.hazmat.primitives.ciphers.modes.CTR`) you don't have 559 to worry about this. 560 561 .. method:: update(data) 562 563 :param data: The data you wish to pass into the context. 564 :type data: :term:`bytes-like` 565 :return bytes: Returns the data that was encrypted or decrypted. 566 :raises cryptography.exceptions.AlreadyFinalized: See :meth:`finalize` 567 568 When the ``Cipher`` was constructed in a mode that turns it into a 569 stream cipher (e.g. 570 :class:`~cryptography.hazmat.primitives.ciphers.modes.CTR`), this will 571 return bytes immediately, however in other modes it will return chunks 572 whose size is determined by the cipher's block size. 573 574 .. method:: update_into(data, buf) 575 576 .. versionadded:: 1.8 577 578 .. warning:: 579 580 This method allows you to avoid a memory copy by passing a writable 581 buffer and reading the resulting data. You are responsible for 582 correctly sizing the buffer and properly handling the data. This 583 method should only be used when extremely high performance is a 584 requirement and you will be making many small calls to 585 ``update_into``. 586 587 :param data: The data you wish to pass into the context. 588 :type data: :term:`bytes-like` 589 :param buf: A writable Python buffer that the data will be written 590 into. This buffer should be ``len(data) + n - 1`` bytes where ``n`` 591 is the block size (in bytes) of the cipher and mode combination. 592 :return int: Number of bytes written. 593 :raises NotImplementedError: This is raised if the version of ``cffi`` 594 used is too old (this can happen on older PyPy releases). 595 :raises ValueError: This is raised if the supplied buffer is too small. 596 597 .. doctest:: 598 599 >>> import os 600 >>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes 601 >>> from cryptography.hazmat.backends import default_backend 602 >>> backend = default_backend() 603 >>> key = os.urandom(32) 604 >>> iv = os.urandom(16) 605 >>> cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend) 606 >>> encryptor = cipher.encryptor() 607 >>> # the buffer needs to be at least len(data) + n - 1 where n is cipher/mode block size in bytes 608 >>> buf = bytearray(31) 609 >>> len_encrypted = encryptor.update_into(b"a secret message", buf) 610 >>> # get the ciphertext from the buffer reading only the bytes written to it (len_encrypted) 611 >>> ct = bytes(buf[:len_encrypted]) + encryptor.finalize() 612 >>> decryptor = cipher.decryptor() 613 >>> len_decrypted = decryptor.update_into(ct, buf) 614 >>> # get the plaintext from the buffer reading only the bytes written (len_decrypted) 615 >>> bytes(buf[:len_decrypted]) + decryptor.finalize() 616 b'a secret message' 617 618 .. method:: finalize() 619 620 :return bytes: Returns the remainder of the data. 621 :raises ValueError: This is raised when the data provided isn't 622 a multiple of the algorithm's block size. 623 624 Once ``finalize`` is called this object can no longer be used and 625 :meth:`update` and :meth:`finalize` will raise an 626 :class:`~cryptography.exceptions.AlreadyFinalized` exception. 627 628.. class:: AEADCipherContext 629 630 When calling ``encryptor`` or ``decryptor`` on a ``Cipher`` object 631 with an AEAD mode (e.g. 632 :class:`~cryptography.hazmat.primitives.ciphers.modes.GCM`) the result will 633 conform to the ``AEADCipherContext`` and ``CipherContext`` interfaces. If 634 it is an encryption or decryption context it will additionally be an 635 ``AEADEncryptionContext`` or ``AEADDecryptionContext`` instance, 636 respectively. ``AEADCipherContext`` contains an additional method 637 :meth:`authenticate_additional_data` for adding additional authenticated 638 but unencrypted data (see note below). You should call this before calls to 639 ``update``. When you are done call ``finalize`` to finish the operation. 640 641 .. note:: 642 643 In AEAD modes all data passed to ``update()`` will be both encrypted 644 and authenticated. Do not pass encrypted data to the 645 ``authenticate_additional_data()`` method. It is meant solely for 646 additional data you may want to authenticate but leave unencrypted. 647 648 .. method:: authenticate_additional_data(data) 649 650 :param data: Any data you wish to authenticate but not encrypt. 651 :type data: :term:`bytes-like` 652 :raises: :class:`~cryptography.exceptions.AlreadyFinalized` 653 654.. class:: AEADEncryptionContext 655 656 When creating an encryption context using ``encryptor`` on a ``Cipher`` 657 object with an AEAD mode such as 658 :class:`~cryptography.hazmat.primitives.ciphers.modes.GCM` an object 659 conforming to both the ``AEADEncryptionContext`` and ``AEADCipherContext`` 660 interfaces will be returned. This interface provides one 661 additional attribute ``tag``. ``tag`` can only be obtained after 662 ``finalize`` has been called. 663 664 .. attribute:: tag 665 666 :return bytes: Returns the tag value as bytes. 667 :raises: :class:`~cryptography.exceptions.NotYetFinalized` if called 668 before the context is finalized. 669 670.. class:: AEADDecryptionContext 671 672 .. versionadded:: 1.9 673 674 When creating an encryption context using ``decryptor`` on a ``Cipher`` 675 object with an AEAD mode such as 676 :class:`~cryptography.hazmat.primitives.ciphers.modes.GCM` an object 677 conforming to both the ``AEADDecryptionContext`` and ``AEADCipherContext`` 678 interfaces will be returned. This interface provides one additional method 679 :meth:`finalize_with_tag` that allows passing the authentication tag for 680 validation after the ciphertext has been decrypted. 681 682 .. method:: finalize_with_tag(tag) 683 684 .. note:: 685 686 This method is not supported when compiled against OpenSSL 1.0.1. 687 688 :param bytes tag: The tag bytes to verify after decryption. 689 :return bytes: Returns the remainder of the data. 690 :raises ValueError: This is raised when the data provided isn't 691 a multiple of the algorithm's block size, if ``min_tag_length`` is 692 less than 4, or if ``len(tag) < min_tag_length``. 693 ``min_tag_length`` is an argument to the ``GCM`` constructor. 694 :raises NotImplementedError: This is raised if the version of the 695 OpenSSL backend used is 1.0.1 or earlier. 696 697 If the authentication tag was not already supplied to the constructor 698 of the :class:`~cryptography.hazmat.primitives.ciphers.modes.GCM` mode 699 object, this method must be used instead of 700 :meth:`~cryptography.hazmat.primitives.ciphers.CipherContext.finalize`. 701 702.. class:: CipherAlgorithm 703 704 A named symmetric encryption algorithm. 705 706 .. attribute:: name 707 708 :type: str 709 710 The standard name for the mode, for example, "AES", "Camellia", or 711 "Blowfish". 712 713 .. attribute:: key_size 714 715 :type: int 716 717 The number of :term:`bits` in the key being used. 718 719 720.. class:: BlockCipherAlgorithm 721 722 A block cipher algorithm. 723 724 .. attribute:: block_size 725 726 :type: int 727 728 The number of :term:`bits` in a block. 729 730Interfaces used by the symmetric cipher modes described in 731:ref:`Symmetric Encryption Modes <symmetric-encryption-modes>`. 732 733.. currentmodule:: cryptography.hazmat.primitives.ciphers.modes 734 735.. class:: Mode 736 737 A named cipher mode. 738 739 .. attribute:: name 740 741 :type: str 742 743 This should be the standard shorthand name for the mode, for example 744 Cipher-Block Chaining mode is "CBC". 745 746 The name may be used by a backend to influence the operation of a 747 cipher in conjunction with the algorithm's name. 748 749 .. method:: validate_for_algorithm(algorithm) 750 751 :param cryptography.hazmat.primitives.ciphers.CipherAlgorithm algorithm: 752 753 Checks that the combination of this mode with the provided algorithm 754 meets any necessary invariants. This should raise an exception if they 755 are not met. 756 757 For example, the 758 :class:`~cryptography.hazmat.primitives.ciphers.modes.CBC` mode uses 759 this method to check that the provided initialization vector's length 760 matches the block size of the algorithm. 761 762 763.. class:: ModeWithInitializationVector 764 765 A cipher mode with an initialization vector. 766 767 .. attribute:: initialization_vector 768 769 :type: :term:`bytes-like` 770 771 Exact requirements of the initialization are described by the 772 documentation of individual modes. 773 774 775.. class:: ModeWithNonce 776 777 A cipher mode with a nonce. 778 779 .. attribute:: nonce 780 781 :type: :term:`bytes-like` 782 783 Exact requirements of the nonce are described by the documentation of 784 individual modes. 785 786 787.. class:: ModeWithAuthenticationTag 788 789 A cipher mode with an authentication tag. 790 791 .. attribute:: tag 792 793 :type: :term:`bytes-like` 794 795 Exact requirements of the tag are described by the documentation of 796 individual modes. 797 798 799.. class:: ModeWithTweak 800 801 .. versionadded:: 2.1 802 803 A cipher mode with a tweak. 804 805 .. attribute:: tweak 806 807 :type: :term:`bytes-like` 808 809 Exact requirements of the tweak are described by the documentation of 810 individual modes. 811 812Exceptions 813~~~~~~~~~~ 814 815.. currentmodule:: cryptography.exceptions 816 817 818.. class:: InvalidTag 819 820 This is raised if an authenticated encryption tag fails to verify during 821 decryption. 822 823 824 825.. _`described by Colin Percival`: https://www.daemonology.net/blog/2009-06-11-cryptographic-right-answers.html 826.. _`recommends a 96-bit IV length`: https://csrc.nist.gov/publications/detail/sp/800-38d/final 827.. _`NIST SP-800-38D`: https://csrc.nist.gov/publications/detail/sp/800-38d/final 828.. _`Communications Security Establishment`: https://www.cse-cst.gc.ca 829.. _`encrypt`: https://ssd.eff.org/en/module/what-should-i-know-about-encryption 830.. _`CRYPTREC`: https://www.cryptrec.go.jp/english/ 831.. _`significant patterns in the output`: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_Codebook_.28ECB.29 832.. _`International Data Encryption Algorithm`: https://en.wikipedia.org/wiki/International_Data_Encryption_Algorithm 833.. _`OpenPGP`: https://www.openpgp.org/ 834.. _`disk encryption`: https://en.wikipedia.org/wiki/Disk_encryption_theory#XTS 835