blob: 741091b270fce91f9ca6bcfa62a61b9a35663e31 [file] [log] [blame]
Alex Gaynor2724ff62013-12-20 13:51:42 -08001.. hazmat:: /fernet
Donald Stufftd8f01182013-10-27 16:59:56 -04002
3
Donald Stuffte51fb932013-10-27 17:26:17 -04004Symmetric Encryption
5====================
6
Paul Kehrer051099e2013-11-06 15:53:40 +08007.. currentmodule:: cryptography.hazmat.primitives.ciphers
David Reid1f3d7182013-10-22 16:55:18 -07008
Donald Stufft173de982013-08-12 07:34:39 -04009.. testsetup::
10
11 import binascii
12 key = binascii.unhexlify(b"0" * 32)
13 iv = binascii.unhexlify(b"0" * 32)
14
15
Alex Stapleton092351d2014-03-09 17:44:43 +000016Symmetric encryption is a way to `encrypt`_ or hide the contents of material
17where the sender and receiver both use the same secret key. Note that symmetric
18encryption is **not** sufficient for most applications because it only
19provides secrecy but not authenticity. That means an attacker can't see the
20message but an attacker can create bogus messages and force the application to
21decrypt them.
22
Alex Gaynor9316f4c2013-11-15 16:38:42 -080023For this reason it is *strongly* recommended to combine encryption with a
Alex Gaynorab5f0112013-11-08 10:34:00 -080024message authentication code, such as :doc:`HMAC </hazmat/primitives/hmac>`, in
25an "encrypt-then-MAC" formulation as `described by Colin Percival`_.
Alex Gaynorf6c47e92013-08-08 07:16:01 -070026
David Reidef0fcf22013-11-06 11:12:45 -080027.. class:: Cipher(algorithm, mode, backend)
Alex Gaynorf6c47e92013-08-08 07:16:01 -070028
Alex Stapleton092351d2014-03-09 17:44:43 +000029 Cipher objects combine an algorithm such as
30 :class:`~cryptography.hazmat.primitives.ciphers.algorithms.AES` with a
31 mode like
Alex Gaynorab5f0112013-11-08 10:34:00 -080032 :class:`~cryptography.hazmat.primitives.ciphers.modes.CBC` or
Alex Stapleton092351d2014-03-09 17:44:43 +000033 :class:`~cryptography.hazmat.primitives.ciphers.modes.CTR`. A simple
34 example of encrypting and then decrypting content with AES is:
Alex Gaynorf6c47e92013-08-08 07:16:01 -070035
Donald Stufft173de982013-08-12 07:34:39 -040036 .. doctest::
Alex Gaynorf6c47e92013-08-08 07:16:01 -070037
Paul Kehrer051099e2013-11-06 15:53:40 +080038 >>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
Alex Gaynorf8796b12013-12-13 20:28:55 -080039 >>> from cryptography.hazmat.backends import default_backend
Alex Gaynorf56444d2013-12-13 15:19:22 -080040 >>> backend = default_backend()
David Reid63fa19a2013-11-20 10:49:13 -080041 >>> cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
Paul Kehrer3e0895c2013-10-21 22:19:29 -050042 >>> encryptor = cipher.encryptor()
43 >>> ct = encryptor.update(b"a secret message") + encryptor.finalize()
44 >>> decryptor = cipher.decryptor()
45 >>> decryptor.update(ct) + decryptor.finalize()
Paul Kehrerf6cf9562013-10-22 10:36:00 -050046 'a secret message'
Alex Gaynorf6c47e92013-08-08 07:16:01 -070047
David Reid663295d2013-11-20 13:55:08 -080048 :param algorithms: A
49 :class:`~cryptography.hazmat.primitives.interfaces.CipherAlgorithm`
50 provider such as those described
51 :ref:`below <symmetric-encryption-algorithms>`.
52 :param mode: A :class:`~cryptography.hazmat.primitives.interfaces.Mode`
53 provider such as those described
54 :ref:`below <symmetric-encryption-modes>`.
55 :param backend: A
Alex Gaynorf8796b12013-12-13 20:28:55 -080056 :class:`~cryptography.hazmat.backends.interfaces.CipherBackend`
David Reid663295d2013-11-20 13:55:08 -080057 provider.
Alex Gaynor0ca7fdb2013-08-08 07:35:26 -070058
Paul Kehrer5399fd02013-10-21 23:48:25 -050059 .. method:: encryptor()
Alex Gaynor09515f02013-08-08 15:26:55 -070060
David Reid63ba6652013-10-22 14:09:19 -070061 :return: An encrypting
Donald Stufftf04317a2013-10-27 16:44:30 -040062 :class:`~cryptography.hazmat.primitives.interfaces.CipherContext`
David Reid63ba6652013-10-22 14:09:19 -070063 provider.
Alex Gaynore62aa402013-08-08 15:23:11 -070064
Alex Gaynorf1a3fc02013-11-02 14:03:34 -070065 If the backend doesn't support the requested combination of ``cipher``
Alex Gaynorc6a6f312014-03-06 14:22:56 -080066 and ``mode`` an :class:`~cryptography.exceptions.UnsupportedCipher`
Alex Stapleton092351d2014-03-09 17:44:43 +000067 exception will be raised.
Alex Gaynorf1a3fc02013-11-02 14:03:34 -070068
Paul Kehrer5399fd02013-10-21 23:48:25 -050069 .. method:: decryptor()
70
David Reid63ba6652013-10-22 14:09:19 -070071 :return: A decrypting
Donald Stufftf04317a2013-10-27 16:44:30 -040072 :class:`~cryptography.hazmat.primitives.interfaces.CipherContext`
David Reid63ba6652013-10-22 14:09:19 -070073 provider.
Paul Kehrer5399fd02013-10-21 23:48:25 -050074
Alex Gaynorf1a3fc02013-11-02 14:03:34 -070075 If the backend doesn't support the requested combination of ``cipher``
Alex Gaynorc6a6f312014-03-06 14:22:56 -080076 and ``mode`` an :class:`cryptography.exceptions.UnsupportedCipher`
Alex Stapleton092351d2014-03-09 17:44:43 +000077 exception will be raised.
Alex Gaynorf1a3fc02013-11-02 14:03:34 -070078
David Reid663295d2013-11-20 13:55:08 -080079.. _symmetric-encryption-algorithms:
80
Paul Kehrer051099e2013-11-06 15:53:40 +080081Algorithms
82~~~~~~~~~~
Alex Gaynord96d1002013-08-08 07:37:26 -070083
Paul Kehrer051099e2013-11-06 15:53:40 +080084.. currentmodule:: cryptography.hazmat.primitives.ciphers.algorithms
David Reid1f3d7182013-10-22 16:55:18 -070085
86.. class:: AES(key)
Alex Gaynor5ba2dfa2013-08-08 11:04:44 -070087
Alex Gaynor1e3f81f2013-08-08 11:31:43 -070088 AES (Advanced Encryption Standard) is a block cipher standardized by NIST.
Alex Gaynor5ba2dfa2013-08-08 11:04:44 -070089 AES is both fast, and cryptographically strong. It is a good default
90 choice for encryption.
91
Alex Stapleton092351d2014-03-09 17:44:43 +000092 :param bytes key: The secret key. This must be kept secret. Either ``128``,
93 ``192``, or ``256`` bits long.
Alex Gaynor5ba2dfa2013-08-08 11:04:44 -070094
David Reid1f3d7182013-10-22 16:55:18 -070095.. class:: Camellia(key)
Paul Kehrerdff22d42013-09-27 13:43:06 -050096
Alex Stapleton092351d2014-03-09 17:44:43 +000097 Camellia is a block cipher approved for use by `CRYPTREC`_ and ISO/IEC.
98 It is considered to have comparable security and performance to AES but
Paul Kehrerdff22d42013-09-27 13:43:06 -050099 is not as widely studied or deployed.
100
Alex Stapleton092351d2014-03-09 17:44:43 +0000101 :param bytes key: The secret key. This must be kept secret. Either ``128``,
102 ``192``, or ``256`` bits long.
Paul Kehrerdff22d42013-09-27 13:43:06 -0500103
David Reid1f3d7182013-10-22 16:55:18 -0700104.. class:: TripleDES(key)
Alex Gaynoraeb714c2013-09-09 18:06:14 -0700105
Alex Gaynor9316f4c2013-11-15 16:38:42 -0800106 Triple DES (Data Encryption Standard), sometimes referred to as 3DES, is a
107 block cipher standardized by NIST. Triple DES has known crypto-analytic
Alex Gaynor17adce62013-10-16 17:04:40 -0700108 flaws, however none of them currently enable a practical attack.
Alex Gaynor9316f4c2013-11-15 16:38:42 -0800109 Nonetheless, Triples DES is not recommended for new applications because it
Alex Gaynorfbcc5642013-10-22 08:26:00 -0700110 is incredibly slow; old applications should consider moving away from it.
Alex Gaynoraeb714c2013-09-09 18:06:14 -0700111
Alex Stapleton092351d2014-03-09 17:44:43 +0000112 :param bytes key: The secret key. This must be kept secret. Either ``64``,
113 ``128``, or ``192`` bits long. DES only uses ``56``, ``112``, or ``168``
114 bits of the key as there is a parity byte in each component of the key.
115 Some writing refers to there being up to three separate keys that are each
116 ``56`` bits long, they can simply be concatenated to produce the full key.
Alex Gaynoraeb714c2013-09-09 18:06:14 -0700117
Paul Kehrerbab0e1a2014-02-09 10:51:59 -0600118.. class:: CAST5(key)
119
Paul Kehrera5011ec2014-02-13 12:33:34 -0600120 .. versionadded:: 0.2
121
Paul Kehrerbab0e1a2014-02-09 10:51:59 -0600122 CAST5 (also known as CAST-128) is a block cipher approved for use in the
123 Canadian government by the `Communications Security Establishment`_. It is
124 a variable key length cipher and supports keys from 40-128 bits in length.
125
Alex Stapleton092351d2014-03-09 17:44:43 +0000126 :param bytes key: The secret key, This must be kept secret. 40 to 128 bits
127 in length in increments of 8 bits.
Paul Kehrerbab0e1a2014-02-09 10:51:59 -0600128
Paul Kehrer3446d812013-10-31 17:15:03 -0500129Weak Ciphers
130------------
131
132.. warning::
133
134 These ciphers are considered weak for a variety of reasons. New
135 applications should avoid their use and existing applications should
136 strongly consider migrating away.
137
Paul Kehrer5df0abe2013-10-30 16:57:04 -0500138.. class:: Blowfish(key)
139
140 Blowfish is a block cipher developed by Bruce Schneier. It is known to be
141 susceptible to attacks when using weak keys. The author has recommended
Alex Stapleton092351d2014-03-09 17:44:43 +0000142 that users of Blowfish move to newer algorithms such as :class:`AES`.
Paul Kehrer5df0abe2013-10-30 16:57:04 -0500143
Alex Stapleton092351d2014-03-09 17:44:43 +0000144 :param bytes key: The secret key. This must be kept secret. 32 to 448 bits
145 in length in increments of 8 bits.
Paul Kehrer5df0abe2013-10-30 16:57:04 -0500146
Paul Kehrer4da28c32013-11-07 07:50:17 +0800147.. class:: ARC4(key)
148
149 ARC4 (Alleged RC4) is a stream cipher with serious weaknesses in its
150 initial stream output. Its use is strongly discouraged. ARC4 does not use
151 mode constructions.
152
Alex Stapleton092351d2014-03-09 17:44:43 +0000153 :param bytes key: The secret key. This must be kept secret. Either ``40``,
154 ``56``, ``64``, ``80``, ``128``, ``192``, or ``256`` bits in length.
Paul Kehrer4da28c32013-11-07 07:50:17 +0800155
Paul Kehrer0994c562013-11-10 03:19:14 +0800156 .. doctest::
157
158 >>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
Alex Gaynorf8796b12013-12-13 20:28:55 -0800159 >>> from cryptography.hazmat.backends import default_backend
Paul Kehrer0994c562013-11-10 03:19:14 +0800160 >>> algorithm = algorithms.ARC4(key)
Alex Gaynorf56444d2013-12-13 15:19:22 -0800161 >>> cipher = Cipher(algorithm, mode=None, backend=default_backend())
Paul Kehrer0994c562013-11-10 03:19:14 +0800162 >>> encryptor = cipher.encryptor()
163 >>> ct = encryptor.update(b"a secret message")
164 >>> decryptor = cipher.decryptor()
165 >>> decryptor.update(ct)
166 'a secret message'
167
Paul Kehrere5dc1222014-02-20 16:19:32 -0600168.. class:: IDEA(key)
169
170 IDEA (`International Data Encryption Algorithm`_) is a block cipher created
171 in 1991. It is an optional component of the `OpenPGP`_ standard. This cipher
172 is susceptible to attacks when using weak keys. It is recommended that you
173 do not use this cipher for new applications.
174
Paul Kehrer7ba0c012014-03-08 11:33:35 -0400175 :param bytes key: The secret key This must be kept secret. ``128`` bits in
176 length.
Paul Kehrere5dc1222014-02-20 16:19:32 -0600177
David Reid30722b92013-11-07 13:03:39 -0800178
179.. _symmetric-encryption-modes:
180
Alex Gaynord96d1002013-08-08 07:37:26 -0700181Modes
182~~~~~
183
Paul Kehrer051099e2013-11-06 15:53:40 +0800184.. currentmodule:: cryptography.hazmat.primitives.ciphers.modes
David Reid1f3d7182013-10-22 16:55:18 -0700185
186.. class:: CBC(initialization_vector)
Alex Gaynor48ec9a32013-08-08 11:13:46 -0700187
Alex Stapleton092351d2014-03-09 17:44:43 +0000188 CBC (Cipher Block Chaining) is a mode of operation for block ciphers. It is
Alex Gaynor48ec9a32013-08-08 11:13:46 -0700189 considered cryptographically strong.
190
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600191 **Padding is required when using this mode.**
192
Alex Gaynor48ec9a32013-08-08 11:13:46 -0700193 :param bytes initialization_vector: Must be random bytes. They do not need
Alex Stapleton092351d2014-03-09 17:44:43 +0000194 to be kept secret and they can be included in a transmitted message.
195 Must be the same number of bytes as the ``block_size`` of the cipher.
196 Each time something is encrypted a new ``initialization_vector`` should
197 be generated. Do not reuse an ``initialization_vector`` with a given
Alex Gaynorfb843aa2014-02-25 11:37:36 -0800198 ``key``, and particularly do not use a constant
199 ``initialization_vector``.
Alex Gaynor8ed651e2013-11-07 13:24:31 -0800200
201 A good construction looks like:
202
Alex Gaynor989061d2013-12-13 20:22:14 -0800203 .. doctest::
Alex Gaynor8ed651e2013-11-07 13:24:31 -0800204
205 >>> import os
Alex Gaynord83c5902013-12-13 20:43:54 -0800206 >>> from cryptography.hazmat.primitives.ciphers.modes import CBC
Alex Gaynor8ed651e2013-11-07 13:24:31 -0800207 >>> iv = os.urandom(16)
208 >>> mode = CBC(iv)
209
210 While the following is bad and will leak information:
211
Alex Gaynor989061d2013-12-13 20:22:14 -0800212 .. doctest::
Alex Gaynor8ed651e2013-11-07 13:24:31 -0800213
Alex Gaynord83c5902013-12-13 20:43:54 -0800214 >>> from cryptography.hazmat.primitives.ciphers.modes import CBC
Alex Gaynor8ed651e2013-11-07 13:24:31 -0800215 >>> iv = "a" * 16
216 >>> mode = CBC(iv)
Paul Kehrer13f108f2013-09-09 21:41:03 -0500217
Paul Kehrer45064282013-10-17 13:41:53 -0500218
David Reid1f3d7182013-10-22 16:55:18 -0700219.. class:: CTR(nonce)
Paul Kehrerd0ec60e2013-10-16 08:46:50 -0500220
Paul Kehrer45064282013-10-17 13:41:53 -0500221 .. warning::
222
223 Counter mode is not recommended for use with block ciphers that have a
224 block size of less than 128-bits.
225
Paul Kehrerd0ec60e2013-10-16 08:46:50 -0500226 CTR (Counter) is a mode of operation for block ciphers. It is considered
Alex Gaynord1f02012013-11-01 14:12:35 -0700227 cryptographically strong. It transforms a block cipher into a stream
228 cipher.
Paul Kehrerd0ec60e2013-10-16 08:46:50 -0500229
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600230 **This mode does not require padding.**
231
Paul Kehrer89b3dd32013-10-17 14:02:45 -0500232 :param bytes nonce: Should be random bytes. It is critical to never reuse a
Alex Gaynorfb843aa2014-02-25 11:37:36 -0800233 ``nonce`` with a given key. Any reuse of a nonce with the same key
234 compromises the security of every message encrypted with that key. Must
235 be the same number of bytes as the ``block_size`` of the cipher with a
236 given key. The nonce does not need to be kept secret and may be
Alex Stapleton092351d2014-03-09 17:44:43 +0000237 included with the ciphertext.
Paul Kehrerd0ec60e2013-10-16 08:46:50 -0500238
David Reid1f3d7182013-10-22 16:55:18 -0700239.. class:: OFB(initialization_vector)
Paul Kehrer6f412a02013-09-10 21:30:50 -0500240
241 OFB (Output Feedback) is a mode of operation for block ciphers. It
242 transforms a block cipher into a stream cipher.
243
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600244 **This mode does not require padding.**
245
David Reidf1a39bd2013-09-11 16:28:42 -0700246 :param bytes initialization_vector: Must be random bytes. They do not need
Alex Stapleton092351d2014-03-09 17:44:43 +0000247 to be kept secret and they can be included in a transmitted message.
248 Must be the same number of bytes as the ``block_size`` of the cipher.
249 Do not reuse an ``initialization_vector`` with a given ``key``.
Paul Kehrer6f412a02013-09-10 21:30:50 -0500250
David Reid1f3d7182013-10-22 16:55:18 -0700251.. class:: CFB(initialization_vector)
Paul Kehrer4223df72013-09-11 09:48:04 -0500252
253 CFB (Cipher Feedback) is a mode of operation for block ciphers. It
254 transforms a block cipher into a stream cipher.
255
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600256 **This mode does not require padding.**
257
Paul Kehrer4223df72013-09-11 09:48:04 -0500258 :param bytes initialization_vector: Must be random bytes. They do not need
Alex Stapleton092351d2014-03-09 17:44:43 +0000259 to be kept secret and they can be included in a transmitted message.
260 Must be the same number of bytes as the ``block_size`` of the cipher.
261 Do not reuse an ``initialization_vector`` with a given ``key``.
Paul Kehrer4223df72013-09-11 09:48:04 -0500262
Paul Kehrer22e80cb2013-11-20 21:27:00 -0600263.. class:: GCM(initialization_vector, tag=None)
264
Paul Kehrer5b828b12013-11-29 17:32:08 -0600265 .. danger::
Paul Kehrer26c8c6a2013-11-29 16:24:56 -0600266
Alex Stapleton092351d2014-03-09 17:44:43 +0000267 When using this mode you **must** not use the decrypted data until
Alex Gaynor0d23e942013-12-04 17:28:24 -0600268 :meth:`~cryptography.hazmat.primitives.interfaces.CipherContext.finalize`
Alex Stapleton092351d2014-03-09 17:44:43 +0000269 has been called. GCM provides **no** guarantees of ciphertext integrity
Alex Gaynord4f93832013-12-04 16:31:59 -0600270 until decryption is complete.
Paul Kehrer26c8c6a2013-11-29 16:24:56 -0600271
Paul Kehrer5578c662013-12-03 17:37:42 -0600272 GCM (Galois Counter Mode) is a mode of operation for block ciphers. An
273 AEAD (authenticated encryption with additional data) mode is a type of
Alex Stapleton092351d2014-03-09 17:44:43 +0000274 block cipher mode that simultaneously encrypts the message as well as
275 authenticating it. Additional unencrypted data may also be authenticated.
276 Additional means of verifying integrity such as
277 :doc:`HMAC </hazmat/primitives/hmac>` are not necessary.
Paul Kehrer22e80cb2013-11-20 21:27:00 -0600278
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600279 **This mode does not require padding.**
280
Paul Kehrer22e80cb2013-11-20 21:27:00 -0600281 :param bytes initialization_vector: Must be random bytes. They do not need
Alex Stapleton092351d2014-03-09 17:44:43 +0000282 to be kept secret and they can be included in a transmitted message.
283 NIST `recommends a 96-bit IV length`_ for performance critical
284 situations but it can be up to 2\ :sup:`64` - 1 bits. Do not reuse an
Alex Gaynorfb843aa2014-02-25 11:37:36 -0800285 ``initialization_vector`` with a given ``key``.
Paul Kehrer22e80cb2013-11-20 21:27:00 -0600286
Paul Kehrerca735042013-12-21 17:31:48 -0600287 .. note::
288
Alex Stapleton092351d2014-03-09 17:44:43 +0000289 Cryptography will generate a 128-bit tag when finalizing encryption.
290 You can shorten a tag by truncating it to the desired length but this
Paul Kehrerfc73e2d2013-12-21 18:41:38 -0600291 is **not recommended** as it lowers the security margins of the
Paul Kehrer048d6cb2013-12-21 18:53:19 -0600292 authentication (`NIST SP-800-38D`_ recommends 96-bits or greater).
Paul Kehrerfc73e2d2013-12-21 18:41:38 -0600293 If you must shorten the tag the minimum allowed length is 4 bytes
Paul Kehrer048d6cb2013-12-21 18:53:19 -0600294 (32-bits). Applications **must** verify the tag is the expected length
295 to guarantee the expected security margin.
Paul Kehrerca735042013-12-21 17:31:48 -0600296
Alex Gaynorfb843aa2014-02-25 11:37:36 -0800297 :param bytes tag: The tag bytes to verify during decryption. When
298 encrypting this must be ``None``.
Paul Kehrer67abc862013-11-25 14:29:35 -0600299
David Reidabb72d22014-01-07 16:06:18 -0800300 .. testcode::
Paul Kehrer22e80cb2013-11-20 21:27:00 -0600301
David Reidabb72d22014-01-07 16:06:18 -0800302 import os
303
304 from cryptography.hazmat.primitives.ciphers import (
305 Cipher, algorithms, modes
306 )
307
David Reid78569d62014-01-07 15:42:17 -0800308 def encrypt(key, plaintext, associated_data):
David Reidabb72d22014-01-07 16:06:18 -0800309 # Generate a random 96-bit IV.
David Reid78569d62014-01-07 15:42:17 -0800310 iv = os.urandom(12)
David Reidabb72d22014-01-07 16:06:18 -0800311
Alex Stapleton092351d2014-03-09 17:44:43 +0000312 # Construct a AES-GCM Cipher object with the given key and a
313 # randomly generated IV.
David Reidabb72d22014-01-07 16:06:18 -0800314 encryptor = Cipher(
David Reid78569d62014-01-07 15:42:17 -0800315 algorithms.AES(key),
316 modes.GCM(iv),
317 backend=default_backend()
David Reidabb72d22014-01-07 16:06:18 -0800318 ).encryptor()
David Reid78569d62014-01-07 15:42:17 -0800319
David Reidabb72d22014-01-07 16:06:18 -0800320 # associated_data will be authenticated but not encrypted,
321 # it must also be passed in on decryption.
David Reid78569d62014-01-07 15:42:17 -0800322 encryptor.authenticate_additional_data(associated_data)
David Reid78569d62014-01-07 15:42:17 -0800323
David Reidabb72d22014-01-07 16:06:18 -0800324 # Encrypt the plaintext and get the associated ciphertext.
Paul Kehreraf0b9f52014-01-07 19:21:49 -0600325 # GCM does not require padding.
326 ciphertext = encryptor.update(plaintext) + encryptor.finalize()
David Reidabb72d22014-01-07 16:06:18 -0800327
328 return (iv, ciphertext, encryptor.tag)
David Reid78569d62014-01-07 15:42:17 -0800329
330 def decrypt(key, associated_data, iv, ciphertext, tag):
Alex Gaynor007e5e12014-01-12 14:25:49 -0800331 if len(tag) != 16:
332 raise ValueError(
333 "tag must be 16 bytes -- truncation not supported"
334 )
335
David Reidabb72d22014-01-07 16:06:18 -0800336 # Construct a Cipher object, with the key, iv, and additionally the
337 # GCM tag used for authenticating the message.
338 decryptor = Cipher(
David Reid78569d62014-01-07 15:42:17 -0800339 algorithms.AES(key),
340 modes.GCM(iv, tag),
341 backend=default_backend()
David Reidabb72d22014-01-07 16:06:18 -0800342 ).decryptor()
David Reid78569d62014-01-07 15:42:17 -0800343
David Reidabb72d22014-01-07 16:06:18 -0800344 # We put associated_data back in or the tag will fail to verify
345 # when we finalize the decryptor.
David Reid78569d62014-01-07 15:42:17 -0800346 decryptor.authenticate_additional_data(associated_data)
347
Paul Kehreraf0b9f52014-01-07 19:21:49 -0600348 # Decryption gets us the authenticated plaintext.
349 # If the tag does not match an InvalidTag exception will be raised.
350 return decryptor.update(ciphertext) + decryptor.finalize()
David Reidabb72d22014-01-07 16:06:18 -0800351
352 iv, ciphertext, tag = encrypt(
David Reid78569d62014-01-07 15:42:17 -0800353 key,
David Reidabb72d22014-01-07 16:06:18 -0800354 b"a secret message!",
David Reid78569d62014-01-07 15:42:17 -0800355 b"authenticated but not encrypted payload"
356 )
357
David Reidabb72d22014-01-07 16:06:18 -0800358 print(decrypt(
359 key,
360 b"authenticated but not encrypted payload",
361 iv,
362 ciphertext,
363 tag
364 ))
David Reid78569d62014-01-07 15:42:17 -0800365
366 .. testoutput::
367
David Reidabb72d22014-01-07 16:06:18 -0800368 a secret message!
Paul Kehrer22e80cb2013-11-20 21:27:00 -0600369
Paul Kehrer13f108f2013-09-09 21:41:03 -0500370
371Insecure Modes
372--------------
373
Alex Gaynorcd413a32013-09-10 18:59:43 -0700374.. warning::
375
376 These modes are insecure. New applications should never make use of them,
377 and existing applications should strongly consider migrating away.
378
379
David Reid1f3d7182013-10-22 16:55:18 -0700380.. class:: ECB()
Paul Kehrer13f108f2013-09-09 21:41:03 -0500381
382 ECB (Electronic Code Book) is the simplest mode of operation for block
Alex Gaynorcd413a32013-09-10 18:59:43 -0700383 ciphers. Each block of data is encrypted in the same way. This means
384 identical plaintext blocks will always result in identical ciphertext
Alex Stapleton092351d2014-03-09 17:44:43 +0000385 blocks, which can leave `significant patterns in the output`_.
Alex Gaynorab5f0112013-11-08 10:34:00 -0800386
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600387 **Padding is required when using this mode.**
388
Paul Kehrerad6d1642014-01-07 19:10:12 -0600389Interfaces
390----------
391
392.. class:: CipherContext
393
394 When calling ``encryptor()`` or ``decryptor()`` on a ``Cipher`` object
Alex Gaynorb4818892014-02-06 10:58:50 -0800395 the result will conform to the ``CipherContext`` interface. You can then
396 call ``update(data)`` with data until you have fed everything into the
397 context. Once that is done call ``finalize()`` to finish the operation and
398 obtain the remainder of the data.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600399
Alex Stapleton092351d2014-03-09 17:44:43 +0000400 Block ciphers require that the plaintext or ciphertext always be a multiple
401 of their block size. Because of that **padding** is sometimes required to
402 make a message the correct size. ``CipherContext`` will not automatically
403 apply any padding; you'll need to add your own. For block ciphers the
404 recommended padding is
405 :class:`cryptography.hazmat.primitives.padding.PKCS7`. If you are using a
406 stream cipher mode (such as
Paul Kehrerad6d1642014-01-07 19:10:12 -0600407 :class:`cryptography.hazmat.primitives.modes.CTR`) you don't have to worry
408 about this.
409
410 .. method:: update(data)
411
412 :param bytes data: The data you wish to pass into the context.
413 :return bytes: Returns the data that was encrypted or decrypted.
414 :raises cryptography.exceptions.AlreadyFinalized: See :meth:`finalize`
415
416 When the ``Cipher`` was constructed in a mode that turns it into a
417 stream cipher (e.g.
418 :class:`cryptography.hazmat.primitives.ciphers.modes.CTR`), this will
Alex Stapleton092351d2014-03-09 17:44:43 +0000419 return bytes immediately, however in other modes it will return chunks
Paul Kehrerad6d1642014-01-07 19:10:12 -0600420 whose size is determined by the cipher's block size.
421
422 .. method:: finalize()
423
424 :return bytes: Returns the remainder of the data.
425 :raises ValueError: This is raised when the data provided isn't
Alex Stapleton092351d2014-03-09 17:44:43 +0000426 a multiple of the algorithm's block size.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600427
428 Once ``finalize`` is called this object can no longer be used and
Alex Stapleton092351d2014-03-09 17:44:43 +0000429 :meth:`update` and :meth:`finalize` will raise an
430 :class:`~cryptography.exceptions.AlreadyFinalized` exception.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600431
432.. class:: AEADCipherContext
433
Alex Stapleton092351d2014-03-09 17:44:43 +0000434 When calling ``encryptor`` or ``decryptor`` on a ``Cipher`` object
Paul Kehrerad6d1642014-01-07 19:10:12 -0600435 with an AEAD mode (e.g.
Alex Gaynorb4818892014-02-06 10:58:50 -0800436 :class:`~cryptography.hazmat.primitives.ciphers.modes.GCM`) the result will
437 conform to the ``AEADCipherContext`` and ``CipherContext`` interfaces. If
438 it is an encryption context it will additionally be an
Alex Stapleton092351d2014-03-09 17:44:43 +0000439 ``AEADEncryptionContext`` provider. ``AEADCipherContext`` contains an
440 additional method :meth:`authenticate_additional_data` for adding
441 additional authenticated but unencrypted data (see note below). You should
442 call this before calls to ``update``. When you are done call `finalize``
443 to finish the operation.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600444
445 .. note::
446
447 In AEAD modes all data passed to ``update()`` will be both encrypted
448 and authenticated. Do not pass encrypted data to the
449 ``authenticate_additional_data()`` method. It is meant solely for
450 additional data you may want to authenticate but leave unencrypted.
451
452 .. method:: authenticate_additional_data(data)
453
454 :param bytes data: Any data you wish to authenticate but not encrypt.
455 :raises: :class:`~cryptography.exceptions.AlreadyFinalized`
456
457.. class:: AEADEncryptionContext
458
Alex Stapleton092351d2014-03-09 17:44:43 +0000459 When creating an encryption context using ``encryptor`` on a ``Cipher``
460 object with an AEAD mode such as
461 :class:`~cryptography.hazmat.primitives.ciphers.modes.GCM` an object
462 conforming to both the ``AEADEncryptionContext`` and ``AEADCipherContext``
463 interfaces will be returned. This interface provides one
464 additional attribute ``tag``. ``tag`` can only be obtained after
465 ``finalize`` has been called.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600466
467 .. attribute:: tag
468
469 :return bytes: Returns the tag value as bytes.
470 :raises: :class:`~cryptography.exceptions.NotYetFinalized` if called
Alex Gaynorfb843aa2014-02-25 11:37:36 -0800471 before the context is finalized.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600472
Alex Gaynorab5f0112013-11-08 10:34:00 -0800473
474.. _`described by Colin Percival`: http://www.daemonology.net/blog/2009-06-11-cryptographic-right-answers.html
Alex Stapleton092351d2014-03-09 17:44:43 +0000475.. _`recommends a 96-bit IV length`: http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-spec.pdf
Paul Kehrera7fbf072013-12-21 18:12:25 -0600476.. _`NIST SP-800-38D`: http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf
Paul Kehrerbab0e1a2014-02-09 10:51:59 -0600477.. _`Communications Security Establishment`: http://www.cse-cst.gc.ca
Alex Stapleton092351d2014-03-09 17:44:43 +0000478.. _`encrypt`: https://ssd.eff.org/tech/encryption
479.. _`CRYPTREC`: http://www.cryptrec.go.jp/english/
480.. _`significant patterns in the output`: http://en.wikipedia.org/wiki/Cipher_block_chaining#Electronic_codebook_.28ECB.29
Paul Kehrere5dc1222014-02-20 16:19:32 -0600481.. _`International Data Encryption Algorithm`: https://en.wikipedia.org/wiki/International_Data_Encryption_Algorithm
482.. _`OpenPGP`: http://www.openpgp.org