blob: d47035d8b93ec99bfdee3503414076a6378dd3e8 [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
Alex Stapleton092351d2014-03-09 17:44:43 +000010Symmetric encryption is a way to `encrypt`_ or hide the contents of material
11where the sender and receiver both use the same secret key. Note that symmetric
12encryption is **not** sufficient for most applications because it only
13provides secrecy but not authenticity. That means an attacker can't see the
14message but an attacker can create bogus messages and force the application to
15decrypt them.
16
Paul Kehrer006670c2014-05-09 11:12:43 -050017For this reason it is **strongly** recommended to combine encryption with a
Alex Gaynor969f18e2014-05-17 20:07:35 -070018message authentication code, such as :doc:`HMAC </hazmat/primitives/mac/hmac>`,
19in an "encrypt-then-MAC" formulation as `described by Colin Percival`_.
Alex Gaynorf6c47e92013-08-08 07:16:01 -070020
David Reidef0fcf22013-11-06 11:12:45 -080021.. class:: Cipher(algorithm, mode, backend)
Alex Gaynorf6c47e92013-08-08 07:16:01 -070022
Alex Stapleton092351d2014-03-09 17:44:43 +000023 Cipher objects combine an algorithm such as
24 :class:`~cryptography.hazmat.primitives.ciphers.algorithms.AES` with a
25 mode like
Alex Gaynorab5f0112013-11-08 10:34:00 -080026 :class:`~cryptography.hazmat.primitives.ciphers.modes.CBC` or
Alex Stapleton092351d2014-03-09 17:44:43 +000027 :class:`~cryptography.hazmat.primitives.ciphers.modes.CTR`. A simple
28 example of encrypting and then decrypting content with AES is:
Alex Gaynorf6c47e92013-08-08 07:16:01 -070029
Donald Stufft173de982013-08-12 07:34:39 -040030 .. doctest::
Alex Gaynorf6c47e92013-08-08 07:16:01 -070031
Gregory Haynes0f986112014-12-30 09:43:24 -080032 >>> import os
Paul Kehrer051099e2013-11-06 15:53:40 +080033 >>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
Alex Gaynorf8796b12013-12-13 20:28:55 -080034 >>> from cryptography.hazmat.backends import default_backend
Alex Gaynorf56444d2013-12-13 15:19:22 -080035 >>> backend = default_backend()
Gregory Haynese261d942015-01-03 09:17:41 -080036 >>> key = os.urandom(32)
Gregory Haynese5917782015-01-03 21:58:25 -080037 >>> iv = os.urandom(16)
Gregory Haynese261d942015-01-03 09:17:41 -080038 >>> cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
Paul Kehrer3e0895c2013-10-21 22:19:29 -050039 >>> encryptor = cipher.encryptor()
40 >>> ct = encryptor.update(b"a secret message") + encryptor.finalize()
41 >>> decryptor = cipher.decryptor()
42 >>> decryptor.update(ct) + decryptor.finalize()
Paul Kehrerf6cf9562013-10-22 10:36:00 -050043 'a secret message'
Alex Gaynorf6c47e92013-08-08 07:16:01 -070044
David Reid663295d2013-11-20 13:55:08 -080045 :param algorithms: A
Paul Kehrer513b7cb2015-02-12 17:31:24 -060046 :class:`~cryptography.hazmat.primitives.ciphers.base.CipherAlgorithm`
David Reid663295d2013-11-20 13:55:08 -080047 provider such as those described
48 :ref:`below <symmetric-encryption-algorithms>`.
Paul Kehrer513b7cb2015-02-12 17:31:24 -060049 :param mode: A :class:`~cryptography.hazmat.primitives.ciphers.modes.Mode`
David Reid663295d2013-11-20 13:55:08 -080050 provider such as those described
51 :ref:`below <symmetric-encryption-modes>`.
52 :param backend: A
Alex Gaynorf8796b12013-12-13 20:28:55 -080053 :class:`~cryptography.hazmat.backends.interfaces.CipherBackend`
David Reid663295d2013-11-20 13:55:08 -080054 provider.
Alex Gaynor0ca7fdb2013-08-08 07:35:26 -070055
Alex Gaynor7a489db2014-03-22 15:09:34 -070056 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if the
Ayrxf56c54e2014-03-16 14:36:17 +080057 provided ``backend`` does not implement
58 :class:`~cryptography.hazmat.backends.interfaces.CipherBackend`
59
Paul Kehrer5399fd02013-10-21 23:48:25 -050060 .. method:: encryptor()
Alex Gaynor09515f02013-08-08 15:26:55 -070061
David Reid63ba6652013-10-22 14:09:19 -070062 :return: An encrypting
Paul Kehrer513b7cb2015-02-12 17:31:24 -060063 :class:`~cryptography.hazmat.primitives.ciphers.base.CipherContext`
David Reid63ba6652013-10-22 14:09:19 -070064 provider.
Alex Gaynore62aa402013-08-08 15:23:11 -070065
Alex Gaynorf1a3fc02013-11-02 14:03:34 -070066 If the backend doesn't support the requested combination of ``cipher``
Alex Gaynor7a489db2014-03-22 15:09:34 -070067 and ``mode`` an :class:`~cryptography.exceptions.UnsupportedAlgorithm`
Alex Stapleton092351d2014-03-09 17:44:43 +000068 exception will be raised.
Alex Gaynorf1a3fc02013-11-02 14:03:34 -070069
Paul Kehrer5399fd02013-10-21 23:48:25 -050070 .. method:: decryptor()
71
David Reid63ba6652013-10-22 14:09:19 -070072 :return: A decrypting
Paul Kehrer513b7cb2015-02-12 17:31:24 -060073 :class:`~cryptography.hazmat.primitives.ciphers.base.CipherContext`
David Reid63ba6652013-10-22 14:09:19 -070074 provider.
Paul Kehrer5399fd02013-10-21 23:48:25 -050075
Alex Gaynorf1a3fc02013-11-02 14:03:34 -070076 If the backend doesn't support the requested combination of ``cipher``
Alex Gaynorfdf63302014-04-29 18:26:11 -070077 and ``mode`` an :class:`~cryptography.exceptions.UnsupportedAlgorithm`
Alex Stapleton092351d2014-03-09 17:44:43 +000078 exception will be raised.
Alex Gaynorf1a3fc02013-11-02 14:03:34 -070079
David Reid663295d2013-11-20 13:55:08 -080080.. _symmetric-encryption-algorithms:
81
Paul Kehrer051099e2013-11-06 15:53:40 +080082Algorithms
83~~~~~~~~~~
Alex Gaynord96d1002013-08-08 07:37:26 -070084
Paul Kehrer051099e2013-11-06 15:53:40 +080085.. currentmodule:: cryptography.hazmat.primitives.ciphers.algorithms
David Reid1f3d7182013-10-22 16:55:18 -070086
87.. class:: AES(key)
Alex Gaynor5ba2dfa2013-08-08 11:04:44 -070088
Alex Gaynor1e3f81f2013-08-08 11:31:43 -070089 AES (Advanced Encryption Standard) is a block cipher standardized by NIST.
Alex Gaynor5ba2dfa2013-08-08 11:04:44 -070090 AES is both fast, and cryptographically strong. It is a good default
91 choice for encryption.
92
Alex Stapleton092351d2014-03-09 17:44:43 +000093 :param bytes key: The secret key. This must be kept secret. Either ``128``,
94 ``192``, or ``256`` bits long.
Alex Gaynor5ba2dfa2013-08-08 11:04:44 -070095
David Reid1f3d7182013-10-22 16:55:18 -070096.. class:: Camellia(key)
Paul Kehrerdff22d42013-09-27 13:43:06 -050097
Alex Stapleton092351d2014-03-09 17:44:43 +000098 Camellia is a block cipher approved for use by `CRYPTREC`_ and ISO/IEC.
99 It is considered to have comparable security and performance to AES but
Paul Kehrerdff22d42013-09-27 13:43:06 -0500100 is not as widely studied or deployed.
101
Alex Stapleton092351d2014-03-09 17:44:43 +0000102 :param bytes key: The secret key. This must be kept secret. Either ``128``,
103 ``192``, or ``256`` bits long.
Paul Kehrerdff22d42013-09-27 13:43:06 -0500104
David Reid1f3d7182013-10-22 16:55:18 -0700105.. class:: TripleDES(key)
Alex Gaynoraeb714c2013-09-09 18:06:14 -0700106
Alex Gaynor9316f4c2013-11-15 16:38:42 -0800107 Triple DES (Data Encryption Standard), sometimes referred to as 3DES, is a
108 block cipher standardized by NIST. Triple DES has known crypto-analytic
Alex Gaynor17adce62013-10-16 17:04:40 -0700109 flaws, however none of them currently enable a practical attack.
Alex Gaynor9316f4c2013-11-15 16:38:42 -0800110 Nonetheless, Triples DES is not recommended for new applications because it
Alex Gaynorfbcc5642013-10-22 08:26:00 -0700111 is incredibly slow; old applications should consider moving away from it.
Alex Gaynoraeb714c2013-09-09 18:06:14 -0700112
Alex Stapleton092351d2014-03-09 17:44:43 +0000113 :param bytes key: The secret key. This must be kept secret. Either ``64``,
114 ``128``, or ``192`` bits long. DES only uses ``56``, ``112``, or ``168``
115 bits of the key as there is a parity byte in each component of the key.
116 Some writing refers to there being up to three separate keys that are each
117 ``56`` bits long, they can simply be concatenated to produce the full key.
Alex Gaynoraeb714c2013-09-09 18:06:14 -0700118
Paul Kehrerbab0e1a2014-02-09 10:51:59 -0600119.. class:: CAST5(key)
120
Paul Kehrera5011ec2014-02-13 12:33:34 -0600121 .. versionadded:: 0.2
122
Paul Kehrerbab0e1a2014-02-09 10:51:59 -0600123 CAST5 (also known as CAST-128) is a block cipher approved for use in the
124 Canadian government by the `Communications Security Establishment`_. It is
125 a variable key length cipher and supports keys from 40-128 bits in length.
126
Alex Stapleton092351d2014-03-09 17:44:43 +0000127 :param bytes key: The secret key, This must be kept secret. 40 to 128 bits
128 in length in increments of 8 bits.
Paul Kehrerbab0e1a2014-02-09 10:51:59 -0600129
Paul Kehrer7e914c92014-04-09 09:12:29 -0500130.. class:: SEED(key)
131
132 .. versionadded:: 0.4
133
Alex Stapleton19e97bd2014-05-02 21:57:59 +0100134 SEED is a block cipher developed by the Korea Information Security Agency
135 (KISA). It is defined in :rfc:`4269` and is used broadly throughout South
Paul Kehrer7e914c92014-04-09 09:12:29 -0500136 Korean industry, but rarely found elsewhere.
137
138 :param bytes key: The secret key. This must be kept secret. ``128`` bits in
139 length.
140
Alex Stapletonc5fffd32014-03-18 15:29:00 +0000141Weak ciphers
Paul Kehrer3446d812013-10-31 17:15:03 -0500142------------
143
144.. warning::
145
146 These ciphers are considered weak for a variety of reasons. New
147 applications should avoid their use and existing applications should
148 strongly consider migrating away.
149
Paul Kehrer5df0abe2013-10-30 16:57:04 -0500150.. class:: Blowfish(key)
151
152 Blowfish is a block cipher developed by Bruce Schneier. It is known to be
153 susceptible to attacks when using weak keys. The author has recommended
Alex Stapleton092351d2014-03-09 17:44:43 +0000154 that users of Blowfish move to newer algorithms such as :class:`AES`.
Paul Kehrer5df0abe2013-10-30 16:57:04 -0500155
Alex Stapleton092351d2014-03-09 17:44:43 +0000156 :param bytes key: The secret key. This must be kept secret. 32 to 448 bits
157 in length in increments of 8 bits.
Paul Kehrer5df0abe2013-10-30 16:57:04 -0500158
Paul Kehrer4da28c32013-11-07 07:50:17 +0800159.. class:: ARC4(key)
160
161 ARC4 (Alleged RC4) is a stream cipher with serious weaknesses in its
162 initial stream output. Its use is strongly discouraged. ARC4 does not use
163 mode constructions.
164
Alex Stapleton092351d2014-03-09 17:44:43 +0000165 :param bytes key: The secret key. This must be kept secret. Either ``40``,
166 ``56``, ``64``, ``80``, ``128``, ``192``, or ``256`` bits in length.
Paul Kehrer4da28c32013-11-07 07:50:17 +0800167
Paul Kehrer0994c562013-11-10 03:19:14 +0800168 .. doctest::
169
170 >>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
Alex Gaynorf8796b12013-12-13 20:28:55 -0800171 >>> from cryptography.hazmat.backends import default_backend
Paul Kehrer0994c562013-11-10 03:19:14 +0800172 >>> algorithm = algorithms.ARC4(key)
Alex Gaynorf56444d2013-12-13 15:19:22 -0800173 >>> cipher = Cipher(algorithm, mode=None, backend=default_backend())
Paul Kehrer0994c562013-11-10 03:19:14 +0800174 >>> encryptor = cipher.encryptor()
175 >>> ct = encryptor.update(b"a secret message")
176 >>> decryptor = cipher.decryptor()
177 >>> decryptor.update(ct)
178 'a secret message'
179
Paul Kehrere5dc1222014-02-20 16:19:32 -0600180.. class:: IDEA(key)
181
182 IDEA (`International Data Encryption Algorithm`_) is a block cipher created
183 in 1991. It is an optional component of the `OpenPGP`_ standard. This cipher
184 is susceptible to attacks when using weak keys. It is recommended that you
185 do not use this cipher for new applications.
186
Paul Kehrer7e914c92014-04-09 09:12:29 -0500187 :param bytes key: The secret key. This must be kept secret. ``128`` bits in
Paul Kehrer7ba0c012014-03-08 11:33:35 -0400188 length.
Paul Kehrere5dc1222014-02-20 16:19:32 -0600189
David Reid30722b92013-11-07 13:03:39 -0800190
191.. _symmetric-encryption-modes:
192
Alex Gaynord96d1002013-08-08 07:37:26 -0700193Modes
194~~~~~
195
Paul Kehrer2129d502015-02-13 12:37:34 -0600196.. module:: cryptography.hazmat.primitives.ciphers.modes
David Reid1f3d7182013-10-22 16:55:18 -0700197
198.. class:: CBC(initialization_vector)
Alex Gaynor48ec9a32013-08-08 11:13:46 -0700199
Alex Stapleton092351d2014-03-09 17:44:43 +0000200 CBC (Cipher Block Chaining) is a mode of operation for block ciphers. It is
Alex Gaynor48ec9a32013-08-08 11:13:46 -0700201 considered cryptographically strong.
202
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600203 **Padding is required when using this mode.**
204
Alex Gaynor9b6fd8e2014-12-19 10:29:56 -0800205 :param bytes initialization_vector: Must be :doc:`random bytes
206 </random-numbers>`. They do not need to be kept secret and they can be
207 included in a transmitted message. Must be the same number of bytes as
208 the ``block_size`` of the cipher. Each time something is encrypted a
209 new ``initialization_vector`` should be generated. Do not reuse an
210 ``initialization_vector`` with a given ``key``, and particularly do not
211 use a constant ``initialization_vector``.
Alex Gaynor8ed651e2013-11-07 13:24:31 -0800212
213 A good construction looks like:
214
Alex Gaynor989061d2013-12-13 20:22:14 -0800215 .. doctest::
Alex Gaynor8ed651e2013-11-07 13:24:31 -0800216
217 >>> import os
Alex Gaynord83c5902013-12-13 20:43:54 -0800218 >>> from cryptography.hazmat.primitives.ciphers.modes import CBC
Alex Gaynor8ed651e2013-11-07 13:24:31 -0800219 >>> iv = os.urandom(16)
220 >>> mode = CBC(iv)
221
222 While the following is bad and will leak information:
223
Alex Gaynor989061d2013-12-13 20:22:14 -0800224 .. doctest::
Alex Gaynor8ed651e2013-11-07 13:24:31 -0800225
Alex Gaynord83c5902013-12-13 20:43:54 -0800226 >>> from cryptography.hazmat.primitives.ciphers.modes import CBC
Alex Gaynor8ed651e2013-11-07 13:24:31 -0800227 >>> iv = "a" * 16
228 >>> mode = CBC(iv)
Paul Kehrer13f108f2013-09-09 21:41:03 -0500229
Paul Kehrer45064282013-10-17 13:41:53 -0500230
David Reid1f3d7182013-10-22 16:55:18 -0700231.. class:: CTR(nonce)
Paul Kehrerd0ec60e2013-10-16 08:46:50 -0500232
Paul Kehrer45064282013-10-17 13:41:53 -0500233 .. warning::
234
235 Counter mode is not recommended for use with block ciphers that have a
236 block size of less than 128-bits.
237
Paul Kehrerd0ec60e2013-10-16 08:46:50 -0500238 CTR (Counter) is a mode of operation for block ciphers. It is considered
Alex Gaynord1f02012013-11-01 14:12:35 -0700239 cryptographically strong. It transforms a block cipher into a stream
240 cipher.
Paul Kehrerd0ec60e2013-10-16 08:46:50 -0500241
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600242 **This mode does not require padding.**
243
Alex Gaynor9b6fd8e2014-12-19 10:29:56 -0800244 :param bytes nonce: Should be :doc:`random bytes </random-numbers>`. It is
245 critical to never reuse a ``nonce`` with a given key. Any reuse of a
246 nonce with the same key compromises the security of every message
247 encrypted with that key. Must be the same number of bytes as the
248 ``block_size`` of the cipher with a given key. The nonce does not need
249 to be kept secret and may be included with the ciphertext.
Paul Kehrerd0ec60e2013-10-16 08:46:50 -0500250
David Reid1f3d7182013-10-22 16:55:18 -0700251.. class:: OFB(initialization_vector)
Paul Kehrer6f412a02013-09-10 21:30:50 -0500252
253 OFB (Output 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
Alex Gaynor9b6fd8e2014-12-19 10:29:56 -0800258 :param bytes initialization_vector: Must be :doc:`random bytes
259 </random-numbers>`. They do not need to be kept secret and they can be
260 included in a transmitted message. Must be the same number of bytes as
261 the ``block_size`` of the cipher. Do not reuse an
262 ``initialization_vector`` with a given ``key``.
Paul Kehrer6f412a02013-09-10 21:30:50 -0500263
David Reid1f3d7182013-10-22 16:55:18 -0700264.. class:: CFB(initialization_vector)
Paul Kehrer4223df72013-09-11 09:48:04 -0500265
266 CFB (Cipher Feedback) is a mode of operation for block ciphers. It
267 transforms a block cipher into a stream cipher.
268
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600269 **This mode does not require padding.**
270
Alex Gaynor9b6fd8e2014-12-19 10:29:56 -0800271 :param bytes initialization_vector: Must be :doc:`random bytes
272 </random-numbers>`. They do not need to be kept secret and they can be
273 included in a transmitted message. Must be the same number of bytes as
274 the ``block_size`` of the cipher. Do not reuse an
275 ``initialization_vector`` with a given ``key``.
Paul Kehrer4223df72013-09-11 09:48:04 -0500276
Paul Kehrer2a947c42014-05-15 17:22:08 -0400277.. class:: CFB8(initialization_vector)
278
279 CFB (Cipher Feedback) is a mode of operation for block ciphers. It
280 transforms a block cipher into a stream cipher. The CFB8 variant uses an
281 8-bit shift register.
282
283 **This mode does not require padding.**
284
Alex Gaynor9b6fd8e2014-12-19 10:29:56 -0800285 :param bytes initialization_vector: Must be :doc:`random bytes
286 </random-numbers>`. They do not need to be kept secret and they can be
287 included in a transmitted message. Must be the same number of bytes as
288 the ``block_size`` of the cipher. Do not reuse an
289 ``initialization_vector`` with a given ``key``.
Paul Kehrer2a947c42014-05-15 17:22:08 -0400290
Alex Gaynorcc5224f2014-06-30 09:25:48 -0700291.. class:: GCM(initialization_vector, tag=None, min_tag_length=16)
Paul Kehrer22e80cb2013-11-20 21:27:00 -0600292
Paul Kehrer5b828b12013-11-29 17:32:08 -0600293 .. danger::
Paul Kehrer26c8c6a2013-11-29 16:24:56 -0600294
Alex Stapleton092351d2014-03-09 17:44:43 +0000295 When using this mode you **must** not use the decrypted data until
Paul Kehrer513b7cb2015-02-12 17:31:24 -0600296 :meth:`~cryptography.hazmat.primitives.ciphers.base.CipherContext.finalize`
Alex Stapleton092351d2014-03-09 17:44:43 +0000297 has been called. GCM provides **no** guarantees of ciphertext integrity
Alex Gaynord4f93832013-12-04 16:31:59 -0600298 until decryption is complete.
Paul Kehrer26c8c6a2013-11-29 16:24:56 -0600299
Paul Kehrer5578c662013-12-03 17:37:42 -0600300 GCM (Galois Counter Mode) is a mode of operation for block ciphers. An
301 AEAD (authenticated encryption with additional data) mode is a type of
Alex Stapleton092351d2014-03-09 17:44:43 +0000302 block cipher mode that simultaneously encrypts the message as well as
303 authenticating it. Additional unencrypted data may also be authenticated.
304 Additional means of verifying integrity such as
Ayrxfa4a6b22014-04-16 23:03:14 +0800305 :doc:`HMAC </hazmat/primitives/mac/hmac>` are not necessary.
Paul Kehrer22e80cb2013-11-20 21:27:00 -0600306
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600307 **This mode does not require padding.**
308
Alex Gaynor9b6fd8e2014-12-19 10:29:56 -0800309 :param bytes initialization_vector: Must be :doc:`random bytes
310 </random-numbers>`. They do not need to be kept secret and they can be
311 included in a transmitted message. NIST `recommends a 96-bit IV
312 length`_ for performance critical situations but it can be up to
313 2\ :sup:`64` - 1 bits. Do not reuse an ``initialization_vector`` with a
314 given ``key``.
Paul Kehrer22e80cb2013-11-20 21:27:00 -0600315
Paul Kehrerca735042013-12-21 17:31:48 -0600316 .. note::
317
Alex Stapleton092351d2014-03-09 17:44:43 +0000318 Cryptography will generate a 128-bit tag when finalizing encryption.
319 You can shorten a tag by truncating it to the desired length but this
Paul Kehrerfc73e2d2013-12-21 18:41:38 -0600320 is **not recommended** as it lowers the security margins of the
Alex Gaynorcc5224f2014-06-30 09:25:48 -0700321 authentication (`NIST SP-800-38D`_ recommends 96-bits or greater).
322 Applications wishing to allow truncation must pass the
Alex Gaynor8f1b8e82014-06-29 20:43:29 -0700323 ``min_tag_length`` parameter.
324
325 .. versionchanged:: 0.5
326
327 The ``min_tag_length`` parameter was added in ``0.5``, previously
Alex Gaynorcc5224f2014-06-30 09:25:48 -0700328 truncation down to ``4`` bytes was always allowed.
Paul Kehrerca735042013-12-21 17:31:48 -0600329
Alex Gaynorfb843aa2014-02-25 11:37:36 -0800330 :param bytes tag: The tag bytes to verify during decryption. When
331 encrypting this must be ``None``.
Paul Kehrer67abc862013-11-25 14:29:35 -0600332
Alex Gaynor8f1b8e82014-06-29 20:43:29 -0700333 :param bytes min_tag_length: The minimum length ``tag`` must be. By default
Alex Gaynorcc5224f2014-06-30 09:25:48 -0700334 this is ``16``, meaning tag truncation is not allowed. Allowing tag
335 truncation is strongly discouraged for most applications.
336
337 :raises ValueError: This is raised if ``len(tag) < min_tag_length``.
Alex Gaynor8f1b8e82014-06-29 20:43:29 -0700338
David Reidabb72d22014-01-07 16:06:18 -0800339 .. testcode::
Paul Kehrer22e80cb2013-11-20 21:27:00 -0600340
David Reidabb72d22014-01-07 16:06:18 -0800341 import os
342
343 from cryptography.hazmat.primitives.ciphers import (
344 Cipher, algorithms, modes
345 )
346
David Reid78569d62014-01-07 15:42:17 -0800347 def encrypt(key, plaintext, associated_data):
David Reidabb72d22014-01-07 16:06:18 -0800348 # Generate a random 96-bit IV.
David Reid78569d62014-01-07 15:42:17 -0800349 iv = os.urandom(12)
David Reidabb72d22014-01-07 16:06:18 -0800350
Alex Gaynorebb1cb92014-06-10 09:36:39 -0700351 # Construct an AES-GCM Cipher object with the given key and a
Alex Stapleton092351d2014-03-09 17:44:43 +0000352 # randomly generated IV.
David Reidabb72d22014-01-07 16:06:18 -0800353 encryptor = Cipher(
David Reid78569d62014-01-07 15:42:17 -0800354 algorithms.AES(key),
355 modes.GCM(iv),
356 backend=default_backend()
David Reidabb72d22014-01-07 16:06:18 -0800357 ).encryptor()
David Reid78569d62014-01-07 15:42:17 -0800358
David Reidabb72d22014-01-07 16:06:18 -0800359 # associated_data will be authenticated but not encrypted,
360 # it must also be passed in on decryption.
David Reid78569d62014-01-07 15:42:17 -0800361 encryptor.authenticate_additional_data(associated_data)
David Reid78569d62014-01-07 15:42:17 -0800362
David Reidabb72d22014-01-07 16:06:18 -0800363 # Encrypt the plaintext and get the associated ciphertext.
Paul Kehreraf0b9f52014-01-07 19:21:49 -0600364 # GCM does not require padding.
365 ciphertext = encryptor.update(plaintext) + encryptor.finalize()
David Reidabb72d22014-01-07 16:06:18 -0800366
367 return (iv, ciphertext, encryptor.tag)
David Reid78569d62014-01-07 15:42:17 -0800368
369 def decrypt(key, associated_data, iv, ciphertext, tag):
David Reidabb72d22014-01-07 16:06:18 -0800370 # Construct a Cipher object, with the key, iv, and additionally the
371 # GCM tag used for authenticating the message.
372 decryptor = Cipher(
David Reid78569d62014-01-07 15:42:17 -0800373 algorithms.AES(key),
374 modes.GCM(iv, tag),
375 backend=default_backend()
David Reidabb72d22014-01-07 16:06:18 -0800376 ).decryptor()
David Reid78569d62014-01-07 15:42:17 -0800377
David Reidabb72d22014-01-07 16:06:18 -0800378 # We put associated_data back in or the tag will fail to verify
379 # when we finalize the decryptor.
David Reid78569d62014-01-07 15:42:17 -0800380 decryptor.authenticate_additional_data(associated_data)
381
Paul Kehreraf0b9f52014-01-07 19:21:49 -0600382 # Decryption gets us the authenticated plaintext.
383 # If the tag does not match an InvalidTag exception will be raised.
384 return decryptor.update(ciphertext) + decryptor.finalize()
David Reidabb72d22014-01-07 16:06:18 -0800385
386 iv, ciphertext, tag = encrypt(
David Reid78569d62014-01-07 15:42:17 -0800387 key,
David Reidabb72d22014-01-07 16:06:18 -0800388 b"a secret message!",
David Reid78569d62014-01-07 15:42:17 -0800389 b"authenticated but not encrypted payload"
390 )
391
David Reidabb72d22014-01-07 16:06:18 -0800392 print(decrypt(
393 key,
394 b"authenticated but not encrypted payload",
395 iv,
396 ciphertext,
397 tag
398 ))
David Reid78569d62014-01-07 15:42:17 -0800399
400 .. testoutput::
401
David Reidabb72d22014-01-07 16:06:18 -0800402 a secret message!
Paul Kehrer22e80cb2013-11-20 21:27:00 -0600403
Paul Kehrer13f108f2013-09-09 21:41:03 -0500404
Alex Stapletonc5fffd32014-03-18 15:29:00 +0000405Insecure modes
Paul Kehrer13f108f2013-09-09 21:41:03 -0500406--------------
407
Alex Gaynorcd413a32013-09-10 18:59:43 -0700408.. warning::
409
410 These modes are insecure. New applications should never make use of them,
411 and existing applications should strongly consider migrating away.
412
413
David Reid1f3d7182013-10-22 16:55:18 -0700414.. class:: ECB()
Paul Kehrer13f108f2013-09-09 21:41:03 -0500415
416 ECB (Electronic Code Book) is the simplest mode of operation for block
Alex Gaynorcd413a32013-09-10 18:59:43 -0700417 ciphers. Each block of data is encrypted in the same way. This means
418 identical plaintext blocks will always result in identical ciphertext
Alex Stapleton092351d2014-03-09 17:44:43 +0000419 blocks, which can leave `significant patterns in the output`_.
Alex Gaynorab5f0112013-11-08 10:34:00 -0800420
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600421 **Padding is required when using this mode.**
422
Paul Kehrerad6d1642014-01-07 19:10:12 -0600423Interfaces
424----------
Paul Kehrer513b7cb2015-02-12 17:31:24 -0600425
Paul Kehrer2129d502015-02-13 12:37:34 -0600426.. module:: cryptography.hazmat.primitives.ciphers.base
Paul Kehrerad6d1642014-01-07 19:10:12 -0600427
428.. class:: CipherContext
429
430 When calling ``encryptor()`` or ``decryptor()`` on a ``Cipher`` object
Alex Gaynorb4818892014-02-06 10:58:50 -0800431 the result will conform to the ``CipherContext`` interface. You can then
432 call ``update(data)`` with data until you have fed everything into the
433 context. Once that is done call ``finalize()`` to finish the operation and
434 obtain the remainder of the data.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600435
Alex Stapleton092351d2014-03-09 17:44:43 +0000436 Block ciphers require that the plaintext or ciphertext always be a multiple
437 of their block size. Because of that **padding** is sometimes required to
438 make a message the correct size. ``CipherContext`` will not automatically
439 apply any padding; you'll need to add your own. For block ciphers the
440 recommended padding is
Alex Gaynord99fc652014-06-25 10:24:03 -0700441 :class:`~cryptography.hazmat.primitives.padding.PKCS7`. If you are using a
Alex Stapleton092351d2014-03-09 17:44:43 +0000442 stream cipher mode (such as
Paul Kehrer45efdbc2015-02-12 10:58:22 -0600443 :class:`~cryptography.hazmat.primitives.ciphers.modes.CTR`) you don't have
444 to worry about this.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600445
446 .. method:: update(data)
447
448 :param bytes data: The data you wish to pass into the context.
449 :return bytes: Returns the data that was encrypted or decrypted.
450 :raises cryptography.exceptions.AlreadyFinalized: See :meth:`finalize`
451
452 When the ``Cipher`` was constructed in a mode that turns it into a
453 stream cipher (e.g.
Alex Gaynord99fc652014-06-25 10:24:03 -0700454 :class:`~cryptography.hazmat.primitives.ciphers.modes.CTR`), this will
Alex Stapleton092351d2014-03-09 17:44:43 +0000455 return bytes immediately, however in other modes it will return chunks
Paul Kehrerad6d1642014-01-07 19:10:12 -0600456 whose size is determined by the cipher's block size.
457
458 .. method:: finalize()
459
460 :return bytes: Returns the remainder of the data.
461 :raises ValueError: This is raised when the data provided isn't
Alex Stapleton092351d2014-03-09 17:44:43 +0000462 a multiple of the algorithm's block size.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600463
464 Once ``finalize`` is called this object can no longer be used and
Alex Stapleton092351d2014-03-09 17:44:43 +0000465 :meth:`update` and :meth:`finalize` will raise an
466 :class:`~cryptography.exceptions.AlreadyFinalized` exception.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600467
468.. class:: AEADCipherContext
469
Alex Stapleton092351d2014-03-09 17:44:43 +0000470 When calling ``encryptor`` or ``decryptor`` on a ``Cipher`` object
Paul Kehrerad6d1642014-01-07 19:10:12 -0600471 with an AEAD mode (e.g.
Alex Gaynorb4818892014-02-06 10:58:50 -0800472 :class:`~cryptography.hazmat.primitives.ciphers.modes.GCM`) the result will
473 conform to the ``AEADCipherContext`` and ``CipherContext`` interfaces. If
474 it is an encryption context it will additionally be an
Alex Stapleton092351d2014-03-09 17:44:43 +0000475 ``AEADEncryptionContext`` provider. ``AEADCipherContext`` contains an
476 additional method :meth:`authenticate_additional_data` for adding
477 additional authenticated but unencrypted data (see note below). You should
478 call this before calls to ``update``. When you are done call `finalize``
479 to finish the operation.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600480
481 .. note::
482
483 In AEAD modes all data passed to ``update()`` will be both encrypted
484 and authenticated. Do not pass encrypted data to the
485 ``authenticate_additional_data()`` method. It is meant solely for
486 additional data you may want to authenticate but leave unencrypted.
487
488 .. method:: authenticate_additional_data(data)
489
490 :param bytes data: Any data you wish to authenticate but not encrypt.
491 :raises: :class:`~cryptography.exceptions.AlreadyFinalized`
492
493.. class:: AEADEncryptionContext
494
Alex Stapleton092351d2014-03-09 17:44:43 +0000495 When creating an encryption context using ``encryptor`` on a ``Cipher``
496 object with an AEAD mode such as
497 :class:`~cryptography.hazmat.primitives.ciphers.modes.GCM` an object
498 conforming to both the ``AEADEncryptionContext`` and ``AEADCipherContext``
499 interfaces will be returned. This interface provides one
500 additional attribute ``tag``. ``tag`` can only be obtained after
501 ``finalize`` has been called.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600502
503 .. attribute:: tag
504
505 :return bytes: Returns the tag value as bytes.
506 :raises: :class:`~cryptography.exceptions.NotYetFinalized` if called
Alex Gaynorfb843aa2014-02-25 11:37:36 -0800507 before the context is finalized.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600508
Paul Kehrer513b7cb2015-02-12 17:31:24 -0600509.. class:: CipherAlgorithm
510
511 A named symmetric encryption algorithm.
512
513 .. attribute:: name
514
515 :type: str
516
517 The standard name for the mode, for example, "AES", "Camellia", or
518 "Blowfish".
519
520 .. attribute:: key_size
521
522 :type: int
523
524 The number of bits in the key being used.
525
526
527.. class:: BlockCipherAlgorithm
528
529 A block cipher algorithm.
530
531 .. attribute:: block_size
532
533 :type: int
534
535 The number of bits in a block.
536
537Interfaces used by the symmetric cipher modes described in
538:ref:`Symmetric Encryption Modes <symmetric-encryption-modes>`.
539
540.. currentmodule:: cryptography.hazmat.primitives.ciphers.modes
541
542.. class:: Mode
543
544 A named cipher mode.
545
546 .. attribute:: name
547
548 :type: str
549
550 This should be the standard shorthand name for the mode, for example
551 Cipher-Block Chaining mode is "CBC".
552
553 The name may be used by a backend to influence the operation of a
554 cipher in conjunction with the algorithm's name.
555
556 .. method:: validate_for_algorithm(algorithm)
557
558 :param CipherAlgorithm algorithm:
559
560 Checks that the combination of this mode with the provided algorithm
561 meets any necessary invariants. This should raise an exception if they
562 are not met.
563
564 For example, the
565 :class:`~cryptography.hazmat.primitives.ciphers.modes.CBC` mode uses
566 this method to check that the provided initialization vector's length
567 matches the block size of the algorithm.
568
569
570.. class:: ModeWithInitializationVector
571
572 A cipher mode with an initialization vector.
573
574 .. attribute:: initialization_vector
575
576 :type: bytes
577
578 Exact requirements of the initialization are described by the
579 documentation of individual modes.
580
581
582.. class:: ModeWithNonce
583
584 A cipher mode with a nonce.
585
586 .. attribute:: nonce
587
588 :type: bytes
589
590 Exact requirements of the nonce are described by the documentation of
591 individual modes.
592
593
Paul Kehrer4ab60592015-02-13 09:06:48 -0600594.. class:: ModeWithAuthenticationTag
595
596 A cipher mode with an authentication tag.
597
598 .. attribute:: tag
599
600 :type: bytes
601
602 Exact requirements of the tag are described by the documentation of
603 individual modes.
604
605
Alex Gaynorab5f0112013-11-08 10:34:00 -0800606
607.. _`described by Colin Percival`: http://www.daemonology.net/blog/2009-06-11-cryptographic-right-answers.html
Alex Stapleton092351d2014-03-09 17:44:43 +0000608.. _`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 -0600609.. _`NIST SP-800-38D`: http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf
Paul Kehrerbab0e1a2014-02-09 10:51:59 -0600610.. _`Communications Security Establishment`: http://www.cse-cst.gc.ca
Alex Stapleton092351d2014-03-09 17:44:43 +0000611.. _`encrypt`: https://ssd.eff.org/tech/encryption
612.. _`CRYPTREC`: http://www.cryptrec.go.jp/english/
Alex Gaynore9df2942014-12-12 10:56:26 -0800613.. _`significant patterns in the output`: https://en.wikipedia.org/wiki/Cipher_block_chaining#Electronic_codebook_.28ECB.29
Paul Kehrere5dc1222014-02-20 16:19:32 -0600614.. _`International Data Encryption Algorithm`: https://en.wikipedia.org/wiki/International_Data_Encryption_Algorithm
615.. _`OpenPGP`: http://www.openpgp.org