blob: 8323028779f6a234111830b2c320f4dbc4ecdadb [file] [log] [blame]
Alex Gaynor2724ff62013-12-20 13:51:42 -08001.. hazmat:: /fernet
Donald Stufftd8f01182013-10-27 16:59:56 -04002
3
Alex Stapletonc5fffd32014-03-18 15:29:00 +00004Symmetric encryption
Donald Stuffte51fb932013-10-27 17:26:17 -04005====================
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
Paul Kehrer006670c2014-05-09 11:12:43 -050023For this reason it is **strongly** recommended to combine encryption with a
Alex Gaynor969f18e2014-05-17 20:07:35 -070024message authentication code, such as :doc:`HMAC </hazmat/primitives/mac/hmac>`,
25in an "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
Gregory Haynes0f986112014-12-30 09:43:24 -080038 >>> import os
Paul Kehrer051099e2013-11-06 15:53:40 +080039 >>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
Alex Gaynorf8796b12013-12-13 20:28:55 -080040 >>> from cryptography.hazmat.backends import default_backend
Alex Gaynorf56444d2013-12-13 15:19:22 -080041 >>> backend = default_backend()
Gregory Haynes0f986112014-12-30 09:43:24 -080042 >>> key = os.urandom(24)
43 >>> cipher = Cipher(algorithms.AES(key), modes.CBC(os.urandom(16)), backend=backend)
Paul Kehrer3e0895c2013-10-21 22:19:29 -050044 >>> encryptor = cipher.encryptor()
45 >>> ct = encryptor.update(b"a secret message") + encryptor.finalize()
46 >>> decryptor = cipher.decryptor()
47 >>> decryptor.update(ct) + decryptor.finalize()
Paul Kehrerf6cf9562013-10-22 10:36:00 -050048 'a secret message'
Alex Gaynorf6c47e92013-08-08 07:16:01 -070049
David Reid663295d2013-11-20 13:55:08 -080050 :param algorithms: A
51 :class:`~cryptography.hazmat.primitives.interfaces.CipherAlgorithm`
52 provider such as those described
53 :ref:`below <symmetric-encryption-algorithms>`.
54 :param mode: A :class:`~cryptography.hazmat.primitives.interfaces.Mode`
55 provider such as those described
56 :ref:`below <symmetric-encryption-modes>`.
57 :param backend: A
Alex Gaynorf8796b12013-12-13 20:28:55 -080058 :class:`~cryptography.hazmat.backends.interfaces.CipherBackend`
David Reid663295d2013-11-20 13:55:08 -080059 provider.
Alex Gaynor0ca7fdb2013-08-08 07:35:26 -070060
Alex Gaynor7a489db2014-03-22 15:09:34 -070061 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if the
Ayrxf56c54e2014-03-16 14:36:17 +080062 provided ``backend`` does not implement
63 :class:`~cryptography.hazmat.backends.interfaces.CipherBackend`
64
Paul Kehrer5399fd02013-10-21 23:48:25 -050065 .. method:: encryptor()
Alex Gaynor09515f02013-08-08 15:26:55 -070066
David Reid63ba6652013-10-22 14:09:19 -070067 :return: An encrypting
Donald Stufftf04317a2013-10-27 16:44:30 -040068 :class:`~cryptography.hazmat.primitives.interfaces.CipherContext`
David Reid63ba6652013-10-22 14:09:19 -070069 provider.
Alex Gaynore62aa402013-08-08 15:23:11 -070070
Alex Gaynorf1a3fc02013-11-02 14:03:34 -070071 If the backend doesn't support the requested combination of ``cipher``
Alex Gaynor7a489db2014-03-22 15:09:34 -070072 and ``mode`` an :class:`~cryptography.exceptions.UnsupportedAlgorithm`
Alex Stapleton092351d2014-03-09 17:44:43 +000073 exception will be raised.
Alex Gaynorf1a3fc02013-11-02 14:03:34 -070074
Paul Kehrer5399fd02013-10-21 23:48:25 -050075 .. method:: decryptor()
76
David Reid63ba6652013-10-22 14:09:19 -070077 :return: A decrypting
Donald Stufftf04317a2013-10-27 16:44:30 -040078 :class:`~cryptography.hazmat.primitives.interfaces.CipherContext`
David Reid63ba6652013-10-22 14:09:19 -070079 provider.
Paul Kehrer5399fd02013-10-21 23:48:25 -050080
Alex Gaynorf1a3fc02013-11-02 14:03:34 -070081 If the backend doesn't support the requested combination of ``cipher``
Alex Gaynorfdf63302014-04-29 18:26:11 -070082 and ``mode`` an :class:`~cryptography.exceptions.UnsupportedAlgorithm`
Alex Stapleton092351d2014-03-09 17:44:43 +000083 exception will be raised.
Alex Gaynorf1a3fc02013-11-02 14:03:34 -070084
David Reid663295d2013-11-20 13:55:08 -080085.. _symmetric-encryption-algorithms:
86
Paul Kehrer051099e2013-11-06 15:53:40 +080087Algorithms
88~~~~~~~~~~
Alex Gaynord96d1002013-08-08 07:37:26 -070089
Paul Kehrer051099e2013-11-06 15:53:40 +080090.. currentmodule:: cryptography.hazmat.primitives.ciphers.algorithms
David Reid1f3d7182013-10-22 16:55:18 -070091
92.. class:: AES(key)
Alex Gaynor5ba2dfa2013-08-08 11:04:44 -070093
Alex Gaynor1e3f81f2013-08-08 11:31:43 -070094 AES (Advanced Encryption Standard) is a block cipher standardized by NIST.
Alex Gaynor5ba2dfa2013-08-08 11:04:44 -070095 AES is both fast, and cryptographically strong. It is a good default
96 choice for encryption.
97
Alex Stapleton092351d2014-03-09 17:44:43 +000098 :param bytes key: The secret key. This must be kept secret. Either ``128``,
99 ``192``, or ``256`` bits long.
Alex Gaynor5ba2dfa2013-08-08 11:04:44 -0700100
David Reid1f3d7182013-10-22 16:55:18 -0700101.. class:: Camellia(key)
Paul Kehrerdff22d42013-09-27 13:43:06 -0500102
Alex Stapleton092351d2014-03-09 17:44:43 +0000103 Camellia is a block cipher approved for use by `CRYPTREC`_ and ISO/IEC.
104 It is considered to have comparable security and performance to AES but
Paul Kehrerdff22d42013-09-27 13:43:06 -0500105 is not as widely studied or deployed.
106
Alex Stapleton092351d2014-03-09 17:44:43 +0000107 :param bytes key: The secret key. This must be kept secret. Either ``128``,
108 ``192``, or ``256`` bits long.
Paul Kehrerdff22d42013-09-27 13:43:06 -0500109
David Reid1f3d7182013-10-22 16:55:18 -0700110.. class:: TripleDES(key)
Alex Gaynoraeb714c2013-09-09 18:06:14 -0700111
Alex Gaynor9316f4c2013-11-15 16:38:42 -0800112 Triple DES (Data Encryption Standard), sometimes referred to as 3DES, is a
113 block cipher standardized by NIST. Triple DES has known crypto-analytic
Alex Gaynor17adce62013-10-16 17:04:40 -0700114 flaws, however none of them currently enable a practical attack.
Alex Gaynor9316f4c2013-11-15 16:38:42 -0800115 Nonetheless, Triples DES is not recommended for new applications because it
Alex Gaynorfbcc5642013-10-22 08:26:00 -0700116 is incredibly slow; old applications should consider moving away from it.
Alex Gaynoraeb714c2013-09-09 18:06:14 -0700117
Alex Stapleton092351d2014-03-09 17:44:43 +0000118 :param bytes key: The secret key. This must be kept secret. Either ``64``,
119 ``128``, or ``192`` bits long. DES only uses ``56``, ``112``, or ``168``
120 bits of the key as there is a parity byte in each component of the key.
121 Some writing refers to there being up to three separate keys that are each
122 ``56`` bits long, they can simply be concatenated to produce the full key.
Alex Gaynoraeb714c2013-09-09 18:06:14 -0700123
Paul Kehrerbab0e1a2014-02-09 10:51:59 -0600124.. class:: CAST5(key)
125
Paul Kehrera5011ec2014-02-13 12:33:34 -0600126 .. versionadded:: 0.2
127
Paul Kehrerbab0e1a2014-02-09 10:51:59 -0600128 CAST5 (also known as CAST-128) is a block cipher approved for use in the
129 Canadian government by the `Communications Security Establishment`_. It is
130 a variable key length cipher and supports keys from 40-128 bits in length.
131
Alex Stapleton092351d2014-03-09 17:44:43 +0000132 :param bytes key: The secret key, This must be kept secret. 40 to 128 bits
133 in length in increments of 8 bits.
Paul Kehrerbab0e1a2014-02-09 10:51:59 -0600134
Paul Kehrer7e914c92014-04-09 09:12:29 -0500135.. class:: SEED(key)
136
137 .. versionadded:: 0.4
138
Alex Stapleton19e97bd2014-05-02 21:57:59 +0100139 SEED is a block cipher developed by the Korea Information Security Agency
140 (KISA). It is defined in :rfc:`4269` and is used broadly throughout South
Paul Kehrer7e914c92014-04-09 09:12:29 -0500141 Korean industry, but rarely found elsewhere.
142
143 :param bytes key: The secret key. This must be kept secret. ``128`` bits in
144 length.
145
Alex Stapletonc5fffd32014-03-18 15:29:00 +0000146Weak ciphers
Paul Kehrer3446d812013-10-31 17:15:03 -0500147------------
148
149.. warning::
150
151 These ciphers are considered weak for a variety of reasons. New
152 applications should avoid their use and existing applications should
153 strongly consider migrating away.
154
Paul Kehrer5df0abe2013-10-30 16:57:04 -0500155.. class:: Blowfish(key)
156
157 Blowfish is a block cipher developed by Bruce Schneier. It is known to be
158 susceptible to attacks when using weak keys. The author has recommended
Alex Stapleton092351d2014-03-09 17:44:43 +0000159 that users of Blowfish move to newer algorithms such as :class:`AES`.
Paul Kehrer5df0abe2013-10-30 16:57:04 -0500160
Alex Stapleton092351d2014-03-09 17:44:43 +0000161 :param bytes key: The secret key. This must be kept secret. 32 to 448 bits
162 in length in increments of 8 bits.
Paul Kehrer5df0abe2013-10-30 16:57:04 -0500163
Paul Kehrer4da28c32013-11-07 07:50:17 +0800164.. class:: ARC4(key)
165
166 ARC4 (Alleged RC4) is a stream cipher with serious weaknesses in its
167 initial stream output. Its use is strongly discouraged. ARC4 does not use
168 mode constructions.
169
Alex Stapleton092351d2014-03-09 17:44:43 +0000170 :param bytes key: The secret key. This must be kept secret. Either ``40``,
171 ``56``, ``64``, ``80``, ``128``, ``192``, or ``256`` bits in length.
Paul Kehrer4da28c32013-11-07 07:50:17 +0800172
Paul Kehrer0994c562013-11-10 03:19:14 +0800173 .. doctest::
174
175 >>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
Alex Gaynorf8796b12013-12-13 20:28:55 -0800176 >>> from cryptography.hazmat.backends import default_backend
Paul Kehrer0994c562013-11-10 03:19:14 +0800177 >>> algorithm = algorithms.ARC4(key)
Alex Gaynorf56444d2013-12-13 15:19:22 -0800178 >>> cipher = Cipher(algorithm, mode=None, backend=default_backend())
Paul Kehrer0994c562013-11-10 03:19:14 +0800179 >>> encryptor = cipher.encryptor()
180 >>> ct = encryptor.update(b"a secret message")
181 >>> decryptor = cipher.decryptor()
182 >>> decryptor.update(ct)
183 'a secret message'
184
Paul Kehrere5dc1222014-02-20 16:19:32 -0600185.. class:: IDEA(key)
186
187 IDEA (`International Data Encryption Algorithm`_) is a block cipher created
188 in 1991. It is an optional component of the `OpenPGP`_ standard. This cipher
189 is susceptible to attacks when using weak keys. It is recommended that you
190 do not use this cipher for new applications.
191
Paul Kehrer7e914c92014-04-09 09:12:29 -0500192 :param bytes key: The secret key. This must be kept secret. ``128`` bits in
Paul Kehrer7ba0c012014-03-08 11:33:35 -0400193 length.
Paul Kehrere5dc1222014-02-20 16:19:32 -0600194
David Reid30722b92013-11-07 13:03:39 -0800195
196.. _symmetric-encryption-modes:
197
Alex Gaynord96d1002013-08-08 07:37:26 -0700198Modes
199~~~~~
200
Paul Kehrer051099e2013-11-06 15:53:40 +0800201.. currentmodule:: cryptography.hazmat.primitives.ciphers.modes
David Reid1f3d7182013-10-22 16:55:18 -0700202
203.. class:: CBC(initialization_vector)
Alex Gaynor48ec9a32013-08-08 11:13:46 -0700204
Alex Stapleton092351d2014-03-09 17:44:43 +0000205 CBC (Cipher Block Chaining) is a mode of operation for block ciphers. It is
Alex Gaynor48ec9a32013-08-08 11:13:46 -0700206 considered cryptographically strong.
207
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600208 **Padding is required when using this mode.**
209
Alex Gaynor9b6fd8e2014-12-19 10:29:56 -0800210 :param bytes initialization_vector: Must be :doc:`random bytes
211 </random-numbers>`. They do not need to be kept secret and they can be
212 included in a transmitted message. Must be the same number of bytes as
213 the ``block_size`` of the cipher. Each time something is encrypted a
214 new ``initialization_vector`` should be generated. Do not reuse an
215 ``initialization_vector`` with a given ``key``, and particularly do not
216 use a constant ``initialization_vector``.
Alex Gaynor8ed651e2013-11-07 13:24:31 -0800217
218 A good construction looks like:
219
Alex Gaynor989061d2013-12-13 20:22:14 -0800220 .. doctest::
Alex Gaynor8ed651e2013-11-07 13:24:31 -0800221
222 >>> import os
Alex Gaynord83c5902013-12-13 20:43:54 -0800223 >>> from cryptography.hazmat.primitives.ciphers.modes import CBC
Alex Gaynor8ed651e2013-11-07 13:24:31 -0800224 >>> iv = os.urandom(16)
225 >>> mode = CBC(iv)
226
227 While the following is bad and will leak information:
228
Alex Gaynor989061d2013-12-13 20:22:14 -0800229 .. doctest::
Alex Gaynor8ed651e2013-11-07 13:24:31 -0800230
Alex Gaynord83c5902013-12-13 20:43:54 -0800231 >>> from cryptography.hazmat.primitives.ciphers.modes import CBC
Alex Gaynor8ed651e2013-11-07 13:24:31 -0800232 >>> iv = "a" * 16
233 >>> mode = CBC(iv)
Paul Kehrer13f108f2013-09-09 21:41:03 -0500234
Paul Kehrer45064282013-10-17 13:41:53 -0500235
David Reid1f3d7182013-10-22 16:55:18 -0700236.. class:: CTR(nonce)
Paul Kehrerd0ec60e2013-10-16 08:46:50 -0500237
Paul Kehrer45064282013-10-17 13:41:53 -0500238 .. warning::
239
240 Counter mode is not recommended for use with block ciphers that have a
241 block size of less than 128-bits.
242
Paul Kehrerd0ec60e2013-10-16 08:46:50 -0500243 CTR (Counter) is a mode of operation for block ciphers. It is considered
Alex Gaynord1f02012013-11-01 14:12:35 -0700244 cryptographically strong. It transforms a block cipher into a stream
245 cipher.
Paul Kehrerd0ec60e2013-10-16 08:46:50 -0500246
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600247 **This mode does not require padding.**
248
Alex Gaynor9b6fd8e2014-12-19 10:29:56 -0800249 :param bytes nonce: Should be :doc:`random bytes </random-numbers>`. It is
250 critical to never reuse a ``nonce`` with a given key. Any reuse of a
251 nonce with the same key compromises the security of every message
252 encrypted with that key. Must be the same number of bytes as the
253 ``block_size`` of the cipher with a given key. The nonce does not need
254 to be kept secret and may be included with the ciphertext.
Paul Kehrerd0ec60e2013-10-16 08:46:50 -0500255
David Reid1f3d7182013-10-22 16:55:18 -0700256.. class:: OFB(initialization_vector)
Paul Kehrer6f412a02013-09-10 21:30:50 -0500257
258 OFB (Output Feedback) is a mode of operation for block ciphers. It
259 transforms a block cipher into a stream cipher.
260
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600261 **This mode does not require padding.**
262
Alex Gaynor9b6fd8e2014-12-19 10:29:56 -0800263 :param bytes initialization_vector: Must be :doc:`random bytes
264 </random-numbers>`. They do not need to be kept secret and they can be
265 included in a transmitted message. Must be the same number of bytes as
266 the ``block_size`` of the cipher. Do not reuse an
267 ``initialization_vector`` with a given ``key``.
Paul Kehrer6f412a02013-09-10 21:30:50 -0500268
David Reid1f3d7182013-10-22 16:55:18 -0700269.. class:: CFB(initialization_vector)
Paul Kehrer4223df72013-09-11 09:48:04 -0500270
271 CFB (Cipher Feedback) is a mode of operation for block ciphers. It
272 transforms a block cipher into a stream cipher.
273
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600274 **This mode does not require padding.**
275
Alex Gaynor9b6fd8e2014-12-19 10:29:56 -0800276 :param bytes initialization_vector: Must be :doc:`random bytes
277 </random-numbers>`. They do not need to be kept secret and they can be
278 included in a transmitted message. Must be the same number of bytes as
279 the ``block_size`` of the cipher. Do not reuse an
280 ``initialization_vector`` with a given ``key``.
Paul Kehrer4223df72013-09-11 09:48:04 -0500281
Paul Kehrer2a947c42014-05-15 17:22:08 -0400282.. class:: CFB8(initialization_vector)
283
284 CFB (Cipher Feedback) is a mode of operation for block ciphers. It
285 transforms a block cipher into a stream cipher. The CFB8 variant uses an
286 8-bit shift register.
287
288 **This mode does not require padding.**
289
Alex Gaynor9b6fd8e2014-12-19 10:29:56 -0800290 :param bytes initialization_vector: Must be :doc:`random bytes
291 </random-numbers>`. They do not need to be kept secret and they can be
292 included in a transmitted message. Must be the same number of bytes as
293 the ``block_size`` of the cipher. Do not reuse an
294 ``initialization_vector`` with a given ``key``.
Paul Kehrer2a947c42014-05-15 17:22:08 -0400295
Alex Gaynorcc5224f2014-06-30 09:25:48 -0700296.. class:: GCM(initialization_vector, tag=None, min_tag_length=16)
Paul Kehrer22e80cb2013-11-20 21:27:00 -0600297
Paul Kehrer5b828b12013-11-29 17:32:08 -0600298 .. danger::
Paul Kehrer26c8c6a2013-11-29 16:24:56 -0600299
Alex Stapleton092351d2014-03-09 17:44:43 +0000300 When using this mode you **must** not use the decrypted data until
Alex Gaynor0d23e942013-12-04 17:28:24 -0600301 :meth:`~cryptography.hazmat.primitives.interfaces.CipherContext.finalize`
Alex Stapleton092351d2014-03-09 17:44:43 +0000302 has been called. GCM provides **no** guarantees of ciphertext integrity
Alex Gaynord4f93832013-12-04 16:31:59 -0600303 until decryption is complete.
Paul Kehrer26c8c6a2013-11-29 16:24:56 -0600304
Paul Kehrer5578c662013-12-03 17:37:42 -0600305 GCM (Galois Counter Mode) is a mode of operation for block ciphers. An
306 AEAD (authenticated encryption with additional data) mode is a type of
Alex Stapleton092351d2014-03-09 17:44:43 +0000307 block cipher mode that simultaneously encrypts the message as well as
308 authenticating it. Additional unencrypted data may also be authenticated.
309 Additional means of verifying integrity such as
Ayrxfa4a6b22014-04-16 23:03:14 +0800310 :doc:`HMAC </hazmat/primitives/mac/hmac>` are not necessary.
Paul Kehrer22e80cb2013-11-20 21:27:00 -0600311
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600312 **This mode does not require padding.**
313
Alex Gaynor9b6fd8e2014-12-19 10:29:56 -0800314 :param bytes initialization_vector: Must be :doc:`random bytes
315 </random-numbers>`. They do not need to be kept secret and they can be
316 included in a transmitted message. NIST `recommends a 96-bit IV
317 length`_ for performance critical situations but it can be up to
318 2\ :sup:`64` - 1 bits. Do not reuse an ``initialization_vector`` with a
319 given ``key``.
Paul Kehrer22e80cb2013-11-20 21:27:00 -0600320
Paul Kehrerca735042013-12-21 17:31:48 -0600321 .. note::
322
Alex Stapleton092351d2014-03-09 17:44:43 +0000323 Cryptography will generate a 128-bit tag when finalizing encryption.
324 You can shorten a tag by truncating it to the desired length but this
Paul Kehrerfc73e2d2013-12-21 18:41:38 -0600325 is **not recommended** as it lowers the security margins of the
Alex Gaynorcc5224f2014-06-30 09:25:48 -0700326 authentication (`NIST SP-800-38D`_ recommends 96-bits or greater).
327 Applications wishing to allow truncation must pass the
Alex Gaynor8f1b8e82014-06-29 20:43:29 -0700328 ``min_tag_length`` parameter.
329
330 .. versionchanged:: 0.5
331
332 The ``min_tag_length`` parameter was added in ``0.5``, previously
Alex Gaynorcc5224f2014-06-30 09:25:48 -0700333 truncation down to ``4`` bytes was always allowed.
Paul Kehrerca735042013-12-21 17:31:48 -0600334
Alex Gaynorfb843aa2014-02-25 11:37:36 -0800335 :param bytes tag: The tag bytes to verify during decryption. When
336 encrypting this must be ``None``.
Paul Kehrer67abc862013-11-25 14:29:35 -0600337
Alex Gaynor8f1b8e82014-06-29 20:43:29 -0700338 :param bytes min_tag_length: The minimum length ``tag`` must be. By default
Alex Gaynorcc5224f2014-06-30 09:25:48 -0700339 this is ``16``, meaning tag truncation is not allowed. Allowing tag
340 truncation is strongly discouraged for most applications.
341
342 :raises ValueError: This is raised if ``len(tag) < min_tag_length``.
Alex Gaynor8f1b8e82014-06-29 20:43:29 -0700343
David Reidabb72d22014-01-07 16:06:18 -0800344 .. testcode::
Paul Kehrer22e80cb2013-11-20 21:27:00 -0600345
David Reidabb72d22014-01-07 16:06:18 -0800346 import os
347
348 from cryptography.hazmat.primitives.ciphers import (
349 Cipher, algorithms, modes
350 )
351
David Reid78569d62014-01-07 15:42:17 -0800352 def encrypt(key, plaintext, associated_data):
David Reidabb72d22014-01-07 16:06:18 -0800353 # Generate a random 96-bit IV.
David Reid78569d62014-01-07 15:42:17 -0800354 iv = os.urandom(12)
David Reidabb72d22014-01-07 16:06:18 -0800355
Alex Gaynorebb1cb92014-06-10 09:36:39 -0700356 # Construct an AES-GCM Cipher object with the given key and a
Alex Stapleton092351d2014-03-09 17:44:43 +0000357 # randomly generated IV.
David Reidabb72d22014-01-07 16:06:18 -0800358 encryptor = Cipher(
David Reid78569d62014-01-07 15:42:17 -0800359 algorithms.AES(key),
360 modes.GCM(iv),
361 backend=default_backend()
David Reidabb72d22014-01-07 16:06:18 -0800362 ).encryptor()
David Reid78569d62014-01-07 15:42:17 -0800363
David Reidabb72d22014-01-07 16:06:18 -0800364 # associated_data will be authenticated but not encrypted,
365 # it must also be passed in on decryption.
David Reid78569d62014-01-07 15:42:17 -0800366 encryptor.authenticate_additional_data(associated_data)
David Reid78569d62014-01-07 15:42:17 -0800367
David Reidabb72d22014-01-07 16:06:18 -0800368 # Encrypt the plaintext and get the associated ciphertext.
Paul Kehreraf0b9f52014-01-07 19:21:49 -0600369 # GCM does not require padding.
370 ciphertext = encryptor.update(plaintext) + encryptor.finalize()
David Reidabb72d22014-01-07 16:06:18 -0800371
372 return (iv, ciphertext, encryptor.tag)
David Reid78569d62014-01-07 15:42:17 -0800373
374 def decrypt(key, associated_data, iv, ciphertext, tag):
David Reidabb72d22014-01-07 16:06:18 -0800375 # Construct a Cipher object, with the key, iv, and additionally the
376 # GCM tag used for authenticating the message.
377 decryptor = Cipher(
David Reid78569d62014-01-07 15:42:17 -0800378 algorithms.AES(key),
379 modes.GCM(iv, tag),
380 backend=default_backend()
David Reidabb72d22014-01-07 16:06:18 -0800381 ).decryptor()
David Reid78569d62014-01-07 15:42:17 -0800382
David Reidabb72d22014-01-07 16:06:18 -0800383 # We put associated_data back in or the tag will fail to verify
384 # when we finalize the decryptor.
David Reid78569d62014-01-07 15:42:17 -0800385 decryptor.authenticate_additional_data(associated_data)
386
Paul Kehreraf0b9f52014-01-07 19:21:49 -0600387 # Decryption gets us the authenticated plaintext.
388 # If the tag does not match an InvalidTag exception will be raised.
389 return decryptor.update(ciphertext) + decryptor.finalize()
David Reidabb72d22014-01-07 16:06:18 -0800390
391 iv, ciphertext, tag = encrypt(
David Reid78569d62014-01-07 15:42:17 -0800392 key,
David Reidabb72d22014-01-07 16:06:18 -0800393 b"a secret message!",
David Reid78569d62014-01-07 15:42:17 -0800394 b"authenticated but not encrypted payload"
395 )
396
David Reidabb72d22014-01-07 16:06:18 -0800397 print(decrypt(
398 key,
399 b"authenticated but not encrypted payload",
400 iv,
401 ciphertext,
402 tag
403 ))
David Reid78569d62014-01-07 15:42:17 -0800404
405 .. testoutput::
406
David Reidabb72d22014-01-07 16:06:18 -0800407 a secret message!
Paul Kehrer22e80cb2013-11-20 21:27:00 -0600408
Paul Kehrer13f108f2013-09-09 21:41:03 -0500409
Alex Stapletonc5fffd32014-03-18 15:29:00 +0000410Insecure modes
Paul Kehrer13f108f2013-09-09 21:41:03 -0500411--------------
412
Alex Gaynorcd413a32013-09-10 18:59:43 -0700413.. warning::
414
415 These modes are insecure. New applications should never make use of them,
416 and existing applications should strongly consider migrating away.
417
418
David Reid1f3d7182013-10-22 16:55:18 -0700419.. class:: ECB()
Paul Kehrer13f108f2013-09-09 21:41:03 -0500420
421 ECB (Electronic Code Book) is the simplest mode of operation for block
Alex Gaynorcd413a32013-09-10 18:59:43 -0700422 ciphers. Each block of data is encrypted in the same way. This means
423 identical plaintext blocks will always result in identical ciphertext
Alex Stapleton092351d2014-03-09 17:44:43 +0000424 blocks, which can leave `significant patterns in the output`_.
Alex Gaynorab5f0112013-11-08 10:34:00 -0800425
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600426 **Padding is required when using this mode.**
427
Paul Kehrerad6d1642014-01-07 19:10:12 -0600428Interfaces
429----------
430
431.. class:: CipherContext
432
433 When calling ``encryptor()`` or ``decryptor()`` on a ``Cipher`` object
Alex Gaynorb4818892014-02-06 10:58:50 -0800434 the result will conform to the ``CipherContext`` interface. You can then
435 call ``update(data)`` with data until you have fed everything into the
436 context. Once that is done call ``finalize()`` to finish the operation and
437 obtain the remainder of the data.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600438
Alex Stapleton092351d2014-03-09 17:44:43 +0000439 Block ciphers require that the plaintext or ciphertext always be a multiple
440 of their block size. Because of that **padding** is sometimes required to
441 make a message the correct size. ``CipherContext`` will not automatically
442 apply any padding; you'll need to add your own. For block ciphers the
443 recommended padding is
Alex Gaynord99fc652014-06-25 10:24:03 -0700444 :class:`~cryptography.hazmat.primitives.padding.PKCS7`. If you are using a
Alex Stapleton092351d2014-03-09 17:44:43 +0000445 stream cipher mode (such as
Alex Gaynord99fc652014-06-25 10:24:03 -0700446 :class:`~cryptography.hazmat.primitives.modes.CTR`) you don't have to worry
Paul Kehrerad6d1642014-01-07 19:10:12 -0600447 about this.
448
449 .. method:: update(data)
450
451 :param bytes data: The data you wish to pass into the context.
452 :return bytes: Returns the data that was encrypted or decrypted.
453 :raises cryptography.exceptions.AlreadyFinalized: See :meth:`finalize`
454
455 When the ``Cipher`` was constructed in a mode that turns it into a
456 stream cipher (e.g.
Alex Gaynord99fc652014-06-25 10:24:03 -0700457 :class:`~cryptography.hazmat.primitives.ciphers.modes.CTR`), this will
Alex Stapleton092351d2014-03-09 17:44:43 +0000458 return bytes immediately, however in other modes it will return chunks
Paul Kehrerad6d1642014-01-07 19:10:12 -0600459 whose size is determined by the cipher's block size.
460
461 .. method:: finalize()
462
463 :return bytes: Returns the remainder of the data.
464 :raises ValueError: This is raised when the data provided isn't
Alex Stapleton092351d2014-03-09 17:44:43 +0000465 a multiple of the algorithm's block size.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600466
467 Once ``finalize`` is called this object can no longer be used and
Alex Stapleton092351d2014-03-09 17:44:43 +0000468 :meth:`update` and :meth:`finalize` will raise an
469 :class:`~cryptography.exceptions.AlreadyFinalized` exception.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600470
471.. class:: AEADCipherContext
472
Alex Stapleton092351d2014-03-09 17:44:43 +0000473 When calling ``encryptor`` or ``decryptor`` on a ``Cipher`` object
Paul Kehrerad6d1642014-01-07 19:10:12 -0600474 with an AEAD mode (e.g.
Alex Gaynorb4818892014-02-06 10:58:50 -0800475 :class:`~cryptography.hazmat.primitives.ciphers.modes.GCM`) the result will
476 conform to the ``AEADCipherContext`` and ``CipherContext`` interfaces. If
477 it is an encryption context it will additionally be an
Alex Stapleton092351d2014-03-09 17:44:43 +0000478 ``AEADEncryptionContext`` provider. ``AEADCipherContext`` contains an
479 additional method :meth:`authenticate_additional_data` for adding
480 additional authenticated but unencrypted data (see note below). You should
481 call this before calls to ``update``. When you are done call `finalize``
482 to finish the operation.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600483
484 .. note::
485
486 In AEAD modes all data passed to ``update()`` will be both encrypted
487 and authenticated. Do not pass encrypted data to the
488 ``authenticate_additional_data()`` method. It is meant solely for
489 additional data you may want to authenticate but leave unencrypted.
490
491 .. method:: authenticate_additional_data(data)
492
493 :param bytes data: Any data you wish to authenticate but not encrypt.
494 :raises: :class:`~cryptography.exceptions.AlreadyFinalized`
495
496.. class:: AEADEncryptionContext
497
Alex Stapleton092351d2014-03-09 17:44:43 +0000498 When creating an encryption context using ``encryptor`` on a ``Cipher``
499 object with an AEAD mode such as
500 :class:`~cryptography.hazmat.primitives.ciphers.modes.GCM` an object
501 conforming to both the ``AEADEncryptionContext`` and ``AEADCipherContext``
502 interfaces will be returned. This interface provides one
503 additional attribute ``tag``. ``tag`` can only be obtained after
504 ``finalize`` has been called.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600505
506 .. attribute:: tag
507
508 :return bytes: Returns the tag value as bytes.
509 :raises: :class:`~cryptography.exceptions.NotYetFinalized` if called
Alex Gaynorfb843aa2014-02-25 11:37:36 -0800510 before the context is finalized.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600511
Alex Gaynorab5f0112013-11-08 10:34:00 -0800512
513.. _`described by Colin Percival`: http://www.daemonology.net/blog/2009-06-11-cryptographic-right-answers.html
Alex Stapleton092351d2014-03-09 17:44:43 +0000514.. _`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 -0600515.. _`NIST SP-800-38D`: http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf
Paul Kehrerbab0e1a2014-02-09 10:51:59 -0600516.. _`Communications Security Establishment`: http://www.cse-cst.gc.ca
Alex Stapleton092351d2014-03-09 17:44:43 +0000517.. _`encrypt`: https://ssd.eff.org/tech/encryption
518.. _`CRYPTREC`: http://www.cryptrec.go.jp/english/
Alex Gaynore9df2942014-12-12 10:56:26 -0800519.. _`significant patterns in the output`: https://en.wikipedia.org/wiki/Cipher_block_chaining#Electronic_codebook_.28ECB.29
Paul Kehrere5dc1222014-02-20 16:19:32 -0600520.. _`International Data Encryption Algorithm`: https://en.wikipedia.org/wiki/International_Data_Encryption_Algorithm
521.. _`OpenPGP`: http://www.openpgp.org