blob: a3b9feaee0961b7b7abe4e5be212c4e22ce536dd [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 Kehrer7c5c9fe2015-02-14 10:27:14 -06007.. module:: cryptography.hazmat.primitives.ciphers
David Reid1f3d7182013-10-22 16:55:18 -07008
Alex Stapleton092351d2014-03-09 17:44:43 +00009Symmetric encryption is a way to `encrypt`_ or hide the contents of material
10where the sender and receiver both use the same secret key. Note that symmetric
11encryption is **not** sufficient for most applications because it only
12provides secrecy but not authenticity. That means an attacker can't see the
13message but an attacker can create bogus messages and force the application to
14decrypt them.
15
Paul Kehrer006670c2014-05-09 11:12:43 -050016For this reason it is **strongly** recommended to combine encryption with a
Alex Gaynor969f18e2014-05-17 20:07:35 -070017message authentication code, such as :doc:`HMAC </hazmat/primitives/mac/hmac>`,
18in an "encrypt-then-MAC" formulation as `described by Colin Percival`_.
Alex Gaynorf6c47e92013-08-08 07:16:01 -070019
David Reidef0fcf22013-11-06 11:12:45 -080020.. class:: Cipher(algorithm, mode, backend)
Alex Gaynorf6c47e92013-08-08 07:16:01 -070021
Alex Stapleton092351d2014-03-09 17:44:43 +000022 Cipher objects combine an algorithm such as
23 :class:`~cryptography.hazmat.primitives.ciphers.algorithms.AES` with a
24 mode like
Alex Gaynorab5f0112013-11-08 10:34:00 -080025 :class:`~cryptography.hazmat.primitives.ciphers.modes.CBC` or
Alex Stapleton092351d2014-03-09 17:44:43 +000026 :class:`~cryptography.hazmat.primitives.ciphers.modes.CTR`. A simple
27 example of encrypting and then decrypting content with AES is:
Alex Gaynorf6c47e92013-08-08 07:16:01 -070028
Donald Stufft173de982013-08-12 07:34:39 -040029 .. doctest::
Alex Gaynorf6c47e92013-08-08 07:16:01 -070030
Gregory Haynes0f986112014-12-30 09:43:24 -080031 >>> import os
Paul Kehrer051099e2013-11-06 15:53:40 +080032 >>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
Alex Gaynorf8796b12013-12-13 20:28:55 -080033 >>> from cryptography.hazmat.backends import default_backend
Alex Gaynorf56444d2013-12-13 15:19:22 -080034 >>> backend = default_backend()
Gregory Haynese261d942015-01-03 09:17:41 -080035 >>> key = os.urandom(32)
Gregory Haynese5917782015-01-03 21:58:25 -080036 >>> iv = os.urandom(16)
Gregory Haynese261d942015-01-03 09:17:41 -080037 >>> cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
Paul Kehrer3e0895c2013-10-21 22:19:29 -050038 >>> encryptor = cipher.encryptor()
39 >>> ct = encryptor.update(b"a secret message") + encryptor.finalize()
40 >>> decryptor = cipher.decryptor()
41 >>> decryptor.update(ct) + decryptor.finalize()
Paul Kehrerf6cf9562013-10-22 10:36:00 -050042 'a secret message'
Alex Gaynorf6c47e92013-08-08 07:16:01 -070043
David Reid663295d2013-11-20 13:55:08 -080044 :param algorithms: A
Paul Kehrer7c5c9fe2015-02-14 10:27:14 -060045 :class:`~cryptography.hazmat.primitives.ciphers.CipherAlgorithm`
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -030046 instance such as those described
David Reid663295d2013-11-20 13:55:08 -080047 :ref:`below <symmetric-encryption-algorithms>`.
Paul Kehrer513b7cb2015-02-12 17:31:24 -060048 :param mode: A :class:`~cryptography.hazmat.primitives.ciphers.modes.Mode`
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -030049 instance such as those described
David Reid663295d2013-11-20 13:55:08 -080050 :ref:`below <symmetric-encryption-modes>`.
51 :param backend: A
Alex Gaynorf8796b12013-12-13 20:28:55 -080052 :class:`~cryptography.hazmat.backends.interfaces.CipherBackend`
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -030053 instance.
Alex Gaynor0ca7fdb2013-08-08 07:35:26 -070054
Alex Gaynor7a489db2014-03-22 15:09:34 -070055 :raises cryptography.exceptions.UnsupportedAlgorithm: This is raised if the
Ayrxf56c54e2014-03-16 14:36:17 +080056 provided ``backend`` does not implement
57 :class:`~cryptography.hazmat.backends.interfaces.CipherBackend`
58
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
Paul Kehrer7c5c9fe2015-02-14 10:27:14 -060062 :class:`~cryptography.hazmat.primitives.ciphers.CipherContext`
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -030063 instance.
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 Gaynor7a489db2014-03-22 15:09:34 -070066 and ``mode`` an :class:`~cryptography.exceptions.UnsupportedAlgorithm`
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
Paul Kehrer7c5c9fe2015-02-14 10:27:14 -060072 :class:`~cryptography.hazmat.primitives.ciphers.CipherContext`
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -030073 instance.
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 Gaynorfdf63302014-04-29 18:26:11 -070076 and ``mode`` an :class:`~cryptography.exceptions.UnsupportedAlgorithm`
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 Chanee9710f2016-09-04 17:40:06 +0100109 Nonetheless, Triple 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 Kehrer7e914c92014-04-09 09:12:29 -0500129.. class:: SEED(key)
130
131 .. versionadded:: 0.4
132
Alex Stapleton19e97bd2014-05-02 21:57:59 +0100133 SEED is a block cipher developed by the Korea Information Security Agency
134 (KISA). It is defined in :rfc:`4269` and is used broadly throughout South
Paul Kehrer7e914c92014-04-09 09:12:29 -0500135 Korean industry, but rarely found elsewhere.
136
137 :param bytes key: The secret key. This must be kept secret. ``128`` bits in
138 length.
139
Alex Stapletonc5fffd32014-03-18 15:29:00 +0000140Weak ciphers
Paul Kehrer3446d812013-10-31 17:15:03 -0500141------------
142
143.. warning::
144
145 These ciphers are considered weak for a variety of reasons. New
146 applications should avoid their use and existing applications should
147 strongly consider migrating away.
148
Paul Kehrer5df0abe2013-10-30 16:57:04 -0500149.. class:: Blowfish(key)
150
151 Blowfish is a block cipher developed by Bruce Schneier. It is known to be
152 susceptible to attacks when using weak keys. The author has recommended
Alex Stapleton092351d2014-03-09 17:44:43 +0000153 that users of Blowfish move to newer algorithms such as :class:`AES`.
Paul Kehrer5df0abe2013-10-30 16:57:04 -0500154
Alex Stapleton092351d2014-03-09 17:44:43 +0000155 :param bytes key: The secret key. This must be kept secret. 32 to 448 bits
156 in length in increments of 8 bits.
Paul Kehrer5df0abe2013-10-30 16:57:04 -0500157
Paul Kehrer4da28c32013-11-07 07:50:17 +0800158.. class:: ARC4(key)
159
160 ARC4 (Alleged RC4) is a stream cipher with serious weaknesses in its
161 initial stream output. Its use is strongly discouraged. ARC4 does not use
162 mode constructions.
163
Alex Stapleton092351d2014-03-09 17:44:43 +0000164 :param bytes key: The secret key. This must be kept secret. Either ``40``,
165 ``56``, ``64``, ``80``, ``128``, ``192``, or ``256`` bits in length.
Paul Kehrer4da28c32013-11-07 07:50:17 +0800166
Paul Kehrer0994c562013-11-10 03:19:14 +0800167 .. doctest::
168
169 >>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
Alex Gaynorf8796b12013-12-13 20:28:55 -0800170 >>> from cryptography.hazmat.backends import default_backend
Paul Kehrer0994c562013-11-10 03:19:14 +0800171 >>> algorithm = algorithms.ARC4(key)
Alex Gaynorf56444d2013-12-13 15:19:22 -0800172 >>> cipher = Cipher(algorithm, mode=None, backend=default_backend())
Paul Kehrer0994c562013-11-10 03:19:14 +0800173 >>> encryptor = cipher.encryptor()
174 >>> ct = encryptor.update(b"a secret message")
175 >>> decryptor = cipher.decryptor()
176 >>> decryptor.update(ct)
177 'a secret message'
178
Paul Kehrere5dc1222014-02-20 16:19:32 -0600179.. class:: IDEA(key)
180
181 IDEA (`International Data Encryption Algorithm`_) is a block cipher created
182 in 1991. It is an optional component of the `OpenPGP`_ standard. This cipher
183 is susceptible to attacks when using weak keys. It is recommended that you
184 do not use this cipher for new applications.
185
Paul Kehrer7e914c92014-04-09 09:12:29 -0500186 :param bytes key: The secret key. This must be kept secret. ``128`` bits in
Paul Kehrer7ba0c012014-03-08 11:33:35 -0400187 length.
Paul Kehrere5dc1222014-02-20 16:19:32 -0600188
David Reid30722b92013-11-07 13:03:39 -0800189
190.. _symmetric-encryption-modes:
191
Alex Gaynord96d1002013-08-08 07:37:26 -0700192Modes
193~~~~~
194
Paul Kehrer2129d502015-02-13 12:37:34 -0600195.. module:: cryptography.hazmat.primitives.ciphers.modes
David Reid1f3d7182013-10-22 16:55:18 -0700196
197.. class:: CBC(initialization_vector)
Alex Gaynor48ec9a32013-08-08 11:13:46 -0700198
Alex Stapleton092351d2014-03-09 17:44:43 +0000199 CBC (Cipher Block Chaining) is a mode of operation for block ciphers. It is
Alex Gaynor48ec9a32013-08-08 11:13:46 -0700200 considered cryptographically strong.
201
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600202 **Padding is required when using this mode.**
203
Alex Gaynor9b6fd8e2014-12-19 10:29:56 -0800204 :param bytes initialization_vector: Must be :doc:`random bytes
205 </random-numbers>`. They do not need to be kept secret and they can be
206 included in a transmitted message. Must be the same number of bytes as
207 the ``block_size`` of the cipher. Each time something is encrypted a
208 new ``initialization_vector`` should be generated. Do not reuse an
209 ``initialization_vector`` with a given ``key``, and particularly do not
210 use a constant ``initialization_vector``.
Alex Gaynor8ed651e2013-11-07 13:24:31 -0800211
212 A good construction looks like:
213
Alex Gaynor989061d2013-12-13 20:22:14 -0800214 .. doctest::
Alex Gaynor8ed651e2013-11-07 13:24:31 -0800215
216 >>> import os
Alex Gaynord83c5902013-12-13 20:43:54 -0800217 >>> from cryptography.hazmat.primitives.ciphers.modes import CBC
Alex Gaynor8ed651e2013-11-07 13:24:31 -0800218 >>> iv = os.urandom(16)
219 >>> mode = CBC(iv)
220
221 While the following is bad and will leak information:
222
Alex Gaynor989061d2013-12-13 20:22:14 -0800223 .. doctest::
Alex Gaynor8ed651e2013-11-07 13:24:31 -0800224
Alex Gaynord83c5902013-12-13 20:43:54 -0800225 >>> from cryptography.hazmat.primitives.ciphers.modes import CBC
Alex Gaynor8ed651e2013-11-07 13:24:31 -0800226 >>> iv = "a" * 16
227 >>> mode = CBC(iv)
Paul Kehrer13f108f2013-09-09 21:41:03 -0500228
Paul Kehrer45064282013-10-17 13:41:53 -0500229
David Reid1f3d7182013-10-22 16:55:18 -0700230.. class:: CTR(nonce)
Paul Kehrerd0ec60e2013-10-16 08:46:50 -0500231
Paul Kehrer45064282013-10-17 13:41:53 -0500232 .. warning::
233
234 Counter mode is not recommended for use with block ciphers that have a
235 block size of less than 128-bits.
236
Paul Kehrerd0ec60e2013-10-16 08:46:50 -0500237 CTR (Counter) is a mode of operation for block ciphers. It is considered
Alex Gaynord1f02012013-11-01 14:12:35 -0700238 cryptographically strong. It transforms a block cipher into a stream
239 cipher.
Paul Kehrerd0ec60e2013-10-16 08:46:50 -0500240
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600241 **This mode does not require padding.**
242
Eeshan Garg94759002015-05-20 20:35:33 +0530243 :param bytes nonce: Should be unique, a :term:`nonce`. It is
Alex Gaynor9b6fd8e2014-12-19 10:29:56 -0800244 critical to never reuse a ``nonce`` with a given key. Any reuse of a
245 nonce with the same key compromises the security of every message
246 encrypted with that key. Must be the same number of bytes as the
247 ``block_size`` of the cipher with a given key. The nonce does not need
248 to be kept secret and may be included with the ciphertext.
Paul Kehrerd0ec60e2013-10-16 08:46:50 -0500249
David Reid1f3d7182013-10-22 16:55:18 -0700250.. class:: OFB(initialization_vector)
Paul Kehrer6f412a02013-09-10 21:30:50 -0500251
252 OFB (Output Feedback) is a mode of operation for block ciphers. It
253 transforms a block cipher into a stream cipher.
254
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600255 **This mode does not require padding.**
256
Alex Gaynor9b6fd8e2014-12-19 10:29:56 -0800257 :param bytes initialization_vector: Must be :doc:`random bytes
258 </random-numbers>`. They do not need to be kept secret and they can be
259 included in a transmitted message. Must be the same number of bytes as
260 the ``block_size`` of the cipher. Do not reuse an
261 ``initialization_vector`` with a given ``key``.
Paul Kehrer6f412a02013-09-10 21:30:50 -0500262
David Reid1f3d7182013-10-22 16:55:18 -0700263.. class:: CFB(initialization_vector)
Paul Kehrer4223df72013-09-11 09:48:04 -0500264
265 CFB (Cipher Feedback) is a mode of operation for block ciphers. It
266 transforms a block cipher into a stream cipher.
267
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600268 **This mode does not require padding.**
269
Alex Gaynor9b6fd8e2014-12-19 10:29:56 -0800270 :param bytes initialization_vector: Must be :doc:`random bytes
271 </random-numbers>`. They do not need to be kept secret and they can be
272 included in a transmitted message. Must be the same number of bytes as
273 the ``block_size`` of the cipher. Do not reuse an
274 ``initialization_vector`` with a given ``key``.
Paul Kehrer4223df72013-09-11 09:48:04 -0500275
Paul Kehrer2a947c42014-05-15 17:22:08 -0400276.. class:: CFB8(initialization_vector)
277
278 CFB (Cipher Feedback) is a mode of operation for block ciphers. It
279 transforms a block cipher into a stream cipher. The CFB8 variant uses an
280 8-bit shift register.
281
282 **This mode does not require padding.**
283
Alex Gaynor9b6fd8e2014-12-19 10:29:56 -0800284 :param bytes initialization_vector: Must be :doc:`random bytes
285 </random-numbers>`. They do not need to be kept secret and they can be
286 included in a transmitted message. Must be the same number of bytes as
287 the ``block_size`` of the cipher. Do not reuse an
288 ``initialization_vector`` with a given ``key``.
Paul Kehrer2a947c42014-05-15 17:22:08 -0400289
Alex Gaynorcc5224f2014-06-30 09:25:48 -0700290.. class:: GCM(initialization_vector, tag=None, min_tag_length=16)
Paul Kehrer22e80cb2013-11-20 21:27:00 -0600291
Paul Kehrer5b828b12013-11-29 17:32:08 -0600292 .. danger::
Paul Kehrer26c8c6a2013-11-29 16:24:56 -0600293
Alex Stapleton092351d2014-03-09 17:44:43 +0000294 When using this mode you **must** not use the decrypted data until
Paul Kehrer7c5c9fe2015-02-14 10:27:14 -0600295 :meth:`~cryptography.hazmat.primitives.ciphers.CipherContext.finalize`
Alex Stapleton092351d2014-03-09 17:44:43 +0000296 has been called. GCM provides **no** guarantees of ciphertext integrity
Alex Gaynord4f93832013-12-04 16:31:59 -0600297 until decryption is complete.
Paul Kehrer26c8c6a2013-11-29 16:24:56 -0600298
Paul Kehrer5578c662013-12-03 17:37:42 -0600299 GCM (Galois Counter Mode) is a mode of operation for block ciphers. An
300 AEAD (authenticated encryption with additional data) mode is a type of
Alex Stapleton092351d2014-03-09 17:44:43 +0000301 block cipher mode that simultaneously encrypts the message as well as
302 authenticating it. Additional unencrypted data may also be authenticated.
303 Additional means of verifying integrity such as
Ayrxfa4a6b22014-04-16 23:03:14 +0800304 :doc:`HMAC </hazmat/primitives/mac/hmac>` are not necessary.
Paul Kehrer22e80cb2013-11-20 21:27:00 -0600305
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600306 **This mode does not require padding.**
307
Eeshan Garg94759002015-05-20 20:35:33 +0530308 :param bytes initialization_vector: Must be unique, a :term:`nonce`.
309 They do not need to be kept secret and they can be included in a
310 transmitted message. NIST `recommends a 96-bit IV length`_ for
311 performance critical situations but it can be up to 2\ :sup:`64` - 1
312 bits. Do not reuse an ``initialization_vector`` with a given ``key``.
Paul Kehrer22e80cb2013-11-20 21:27:00 -0600313
Paul Kehrerca735042013-12-21 17:31:48 -0600314 .. note::
315
Alex Stapleton092351d2014-03-09 17:44:43 +0000316 Cryptography will generate a 128-bit tag when finalizing encryption.
317 You can shorten a tag by truncating it to the desired length but this
Paul Kehrerfc73e2d2013-12-21 18:41:38 -0600318 is **not recommended** as it lowers the security margins of the
Alex Gaynorcc5224f2014-06-30 09:25:48 -0700319 authentication (`NIST SP-800-38D`_ recommends 96-bits or greater).
320 Applications wishing to allow truncation must pass the
Alex Gaynor8f1b8e82014-06-29 20:43:29 -0700321 ``min_tag_length`` parameter.
322
323 .. versionchanged:: 0.5
324
325 The ``min_tag_length`` parameter was added in ``0.5``, previously
Alex Gaynorcc5224f2014-06-30 09:25:48 -0700326 truncation down to ``4`` bytes was always allowed.
Paul Kehrerca735042013-12-21 17:31:48 -0600327
Alex Gaynorfb843aa2014-02-25 11:37:36 -0800328 :param bytes tag: The tag bytes to verify during decryption. When
329 encrypting this must be ``None``.
Paul Kehrer67abc862013-11-25 14:29:35 -0600330
Alex Gaynor8f1b8e82014-06-29 20:43:29 -0700331 :param bytes min_tag_length: The minimum length ``tag`` must be. By default
Alex Gaynorcc5224f2014-06-30 09:25:48 -0700332 this is ``16``, meaning tag truncation is not allowed. Allowing tag
333 truncation is strongly discouraged for most applications.
334
335 :raises ValueError: This is raised if ``len(tag) < min_tag_length``.
Alex Gaynor8f1b8e82014-06-29 20:43:29 -0700336
Alex Gaynor09828cd2016-02-10 15:21:36 -0500337 An example of securely encrypting and decrypting data with ``AES`` in the
338 ``GCM`` mode looks like:
339
David Reidabb72d22014-01-07 16:06:18 -0800340 .. testcode::
Paul Kehrer22e80cb2013-11-20 21:27:00 -0600341
David Reidabb72d22014-01-07 16:06:18 -0800342 import os
343
344 from cryptography.hazmat.primitives.ciphers import (
345 Cipher, algorithms, modes
346 )
347
David Reid78569d62014-01-07 15:42:17 -0800348 def encrypt(key, plaintext, associated_data):
David Reidabb72d22014-01-07 16:06:18 -0800349 # Generate a random 96-bit IV.
David Reid78569d62014-01-07 15:42:17 -0800350 iv = os.urandom(12)
David Reidabb72d22014-01-07 16:06:18 -0800351
Alex Gaynorebb1cb92014-06-10 09:36:39 -0700352 # Construct an AES-GCM Cipher object with the given key and a
Alex Stapleton092351d2014-03-09 17:44:43 +0000353 # randomly generated IV.
David Reidabb72d22014-01-07 16:06:18 -0800354 encryptor = Cipher(
David Reid78569d62014-01-07 15:42:17 -0800355 algorithms.AES(key),
356 modes.GCM(iv),
357 backend=default_backend()
David Reidabb72d22014-01-07 16:06:18 -0800358 ).encryptor()
David Reid78569d62014-01-07 15:42:17 -0800359
David Reidabb72d22014-01-07 16:06:18 -0800360 # associated_data will be authenticated but not encrypted,
361 # it must also be passed in on decryption.
David Reid78569d62014-01-07 15:42:17 -0800362 encryptor.authenticate_additional_data(associated_data)
David Reid78569d62014-01-07 15:42:17 -0800363
David Reidabb72d22014-01-07 16:06:18 -0800364 # Encrypt the plaintext and get the associated ciphertext.
Paul Kehreraf0b9f52014-01-07 19:21:49 -0600365 # GCM does not require padding.
366 ciphertext = encryptor.update(plaintext) + encryptor.finalize()
David Reidabb72d22014-01-07 16:06:18 -0800367
368 return (iv, ciphertext, encryptor.tag)
David Reid78569d62014-01-07 15:42:17 -0800369
370 def decrypt(key, associated_data, iv, ciphertext, tag):
David Reidabb72d22014-01-07 16:06:18 -0800371 # Construct a Cipher object, with the key, iv, and additionally the
372 # GCM tag used for authenticating the message.
373 decryptor = Cipher(
David Reid78569d62014-01-07 15:42:17 -0800374 algorithms.AES(key),
375 modes.GCM(iv, tag),
376 backend=default_backend()
David Reidabb72d22014-01-07 16:06:18 -0800377 ).decryptor()
David Reid78569d62014-01-07 15:42:17 -0800378
David Reidabb72d22014-01-07 16:06:18 -0800379 # We put associated_data back in or the tag will fail to verify
380 # when we finalize the decryptor.
David Reid78569d62014-01-07 15:42:17 -0800381 decryptor.authenticate_additional_data(associated_data)
382
Paul Kehreraf0b9f52014-01-07 19:21:49 -0600383 # Decryption gets us the authenticated plaintext.
384 # If the tag does not match an InvalidTag exception will be raised.
385 return decryptor.update(ciphertext) + decryptor.finalize()
David Reidabb72d22014-01-07 16:06:18 -0800386
387 iv, ciphertext, tag = encrypt(
David Reid78569d62014-01-07 15:42:17 -0800388 key,
David Reidabb72d22014-01-07 16:06:18 -0800389 b"a secret message!",
David Reid78569d62014-01-07 15:42:17 -0800390 b"authenticated but not encrypted payload"
391 )
392
David Reidabb72d22014-01-07 16:06:18 -0800393 print(decrypt(
394 key,
395 b"authenticated but not encrypted payload",
396 iv,
397 ciphertext,
398 tag
399 ))
David Reid78569d62014-01-07 15:42:17 -0800400
401 .. testoutput::
402
David Reidabb72d22014-01-07 16:06:18 -0800403 a secret message!
Paul Kehrer22e80cb2013-11-20 21:27:00 -0600404
Paul Kehrer13f108f2013-09-09 21:41:03 -0500405
Alex Stapletonc5fffd32014-03-18 15:29:00 +0000406Insecure modes
Paul Kehrer13f108f2013-09-09 21:41:03 -0500407--------------
408
Alex Gaynorcd413a32013-09-10 18:59:43 -0700409.. warning::
410
411 These modes are insecure. New applications should never make use of them,
412 and existing applications should strongly consider migrating away.
413
414
David Reid1f3d7182013-10-22 16:55:18 -0700415.. class:: ECB()
Paul Kehrer13f108f2013-09-09 21:41:03 -0500416
417 ECB (Electronic Code Book) is the simplest mode of operation for block
Alex Gaynorcd413a32013-09-10 18:59:43 -0700418 ciphers. Each block of data is encrypted in the same way. This means
419 identical plaintext blocks will always result in identical ciphertext
Alex Stapleton092351d2014-03-09 17:44:43 +0000420 blocks, which can leave `significant patterns in the output`_.
Alex Gaynorab5f0112013-11-08 10:34:00 -0800421
Paul Kehrerfe2e3c22014-01-07 20:55:20 -0600422 **Padding is required when using this mode.**
423
Paul Kehrerad6d1642014-01-07 19:10:12 -0600424Interfaces
425----------
Paul Kehrer513b7cb2015-02-12 17:31:24 -0600426
Paul Kehrer7c5c9fe2015-02-14 10:27:14 -0600427.. currentmodule:: cryptography.hazmat.primitives.ciphers
Paul Kehrerad6d1642014-01-07 19:10:12 -0600428
429.. class:: CipherContext
430
431 When calling ``encryptor()`` or ``decryptor()`` on a ``Cipher`` object
Alex Gaynorb4818892014-02-06 10:58:50 -0800432 the result will conform to the ``CipherContext`` interface. You can then
433 call ``update(data)`` with data until you have fed everything into the
434 context. Once that is done call ``finalize()`` to finish the operation and
435 obtain the remainder of the data.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600436
Alex Stapleton092351d2014-03-09 17:44:43 +0000437 Block ciphers require that the plaintext or ciphertext always be a multiple
438 of their block size. Because of that **padding** is sometimes required to
439 make a message the correct size. ``CipherContext`` will not automatically
440 apply any padding; you'll need to add your own. For block ciphers the
441 recommended padding is
Alex Gaynord99fc652014-06-25 10:24:03 -0700442 :class:`~cryptography.hazmat.primitives.padding.PKCS7`. If you are using a
Alex Stapleton092351d2014-03-09 17:44:43 +0000443 stream cipher mode (such as
Paul Kehrer45efdbc2015-02-12 10:58:22 -0600444 :class:`~cryptography.hazmat.primitives.ciphers.modes.CTR`) you don't have
445 to worry about this.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600446
447 .. method:: update(data)
448
449 :param bytes data: The data you wish to pass into the context.
450 :return bytes: Returns the data that was encrypted or decrypted.
451 :raises cryptography.exceptions.AlreadyFinalized: See :meth:`finalize`
452
453 When the ``Cipher`` was constructed in a mode that turns it into a
454 stream cipher (e.g.
Alex Gaynord99fc652014-06-25 10:24:03 -0700455 :class:`~cryptography.hazmat.primitives.ciphers.modes.CTR`), this will
Alex Stapleton092351d2014-03-09 17:44:43 +0000456 return bytes immediately, however in other modes it will return chunks
Paul Kehrerad6d1642014-01-07 19:10:12 -0600457 whose size is determined by the cipher's block size.
458
Paul Kehrer9b34ca92017-02-16 22:20:38 -0600459 .. method:: update_into(data, buf)
460
461 .. versionadded:: 1.8
462
463 .. warning::
464
465 This method allows you to avoid a memory copy by passing a writable
466 buffer and reading the resulting data. You are responsible for
467 correctly sizing the buffer and properly handling the data. This
468 method should only be used when extremely high performance is a
469 requirement and you will be making many small calls to
470 ``update_into``.
471
472 :param bytes data: The data you wish to pass into the context.
473 :param buf: A writable Python buffer that the data will be written
474 into. This buffer should be ``len(data) + n - 1`` bytes where ``n``
475 is the block size (in bytes) of the cipher and mode combination.
476 :return int: Number of bytes written.
477 :raises NotImplementedError: This is raised if the version of ``cffi``
478 used is too old (this can happen on older PyPy releases).
479 :raises ValueError: This is raised if the supplied buffer is too small.
480
481 .. doctest::
482
483 >>> import os
484 >>> from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
485 >>> from cryptography.hazmat.backends import default_backend
486 >>> backend = default_backend()
487 >>> key = os.urandom(32)
488 >>> iv = os.urandom(16)
489 >>> cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
490 >>> encryptor = cipher.encryptor()
491 >>> # the buffer needs to be at least len(data) + n - 1 where n is cipher/mode block size in bytes
492 >>> buf = bytearray(31)
493 >>> len_encrypted = encryptor.update_into(b"a secret message", buf)
494 >>> # get the ciphertext from the buffer reading only the bytes written to it (len_encrypted)
495 >>> ct = bytes(buf[:len_encrypted]) + encryptor.finalize()
496 >>> decryptor = cipher.decryptor()
497 >>> len_decrypted = decryptor.update_into(ct, buf)
498 >>> # get the plaintext from the buffer reading only the bytes written (len_decrypted)
499 >>> bytes(buf[:len_decrypted]) + decryptor.finalize()
500 'a secret message'
501
Paul Kehrerad6d1642014-01-07 19:10:12 -0600502 .. method:: finalize()
503
504 :return bytes: Returns the remainder of the data.
505 :raises ValueError: This is raised when the data provided isn't
Alex Stapleton092351d2014-03-09 17:44:43 +0000506 a multiple of the algorithm's block size.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600507
508 Once ``finalize`` is called this object can no longer be used and
Alex Stapleton092351d2014-03-09 17:44:43 +0000509 :meth:`update` and :meth:`finalize` will raise an
510 :class:`~cryptography.exceptions.AlreadyFinalized` exception.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600511
512.. class:: AEADCipherContext
513
Alex Stapleton092351d2014-03-09 17:44:43 +0000514 When calling ``encryptor`` or ``decryptor`` on a ``Cipher`` object
Paul Kehrerad6d1642014-01-07 19:10:12 -0600515 with an AEAD mode (e.g.
Alex Gaynorb4818892014-02-06 10:58:50 -0800516 :class:`~cryptography.hazmat.primitives.ciphers.modes.GCM`) the result will
517 conform to the ``AEADCipherContext`` and ``CipherContext`` interfaces. If
518 it is an encryption context it will additionally be an
Gabriel Orisaka617fe4b2016-07-31 10:49:59 -0300519 ``AEADEncryptionContext`` instance. ``AEADCipherContext`` contains an
Alex Stapleton092351d2014-03-09 17:44:43 +0000520 additional method :meth:`authenticate_additional_data` for adding
521 additional authenticated but unencrypted data (see note below). You should
Alex Gaynorb7bf3d52015-02-24 10:47:21 -0800522 call this before calls to ``update``. When you are done call ``finalize``
Alex Stapleton092351d2014-03-09 17:44:43 +0000523 to finish the operation.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600524
525 .. note::
526
527 In AEAD modes all data passed to ``update()`` will be both encrypted
528 and authenticated. Do not pass encrypted data to the
529 ``authenticate_additional_data()`` method. It is meant solely for
530 additional data you may want to authenticate but leave unencrypted.
531
532 .. method:: authenticate_additional_data(data)
533
534 :param bytes data: Any data you wish to authenticate but not encrypt.
535 :raises: :class:`~cryptography.exceptions.AlreadyFinalized`
536
537.. class:: AEADEncryptionContext
538
Alex Stapleton092351d2014-03-09 17:44:43 +0000539 When creating an encryption context using ``encryptor`` on a ``Cipher``
540 object with an AEAD mode such as
541 :class:`~cryptography.hazmat.primitives.ciphers.modes.GCM` an object
542 conforming to both the ``AEADEncryptionContext`` and ``AEADCipherContext``
543 interfaces will be returned. This interface provides one
544 additional attribute ``tag``. ``tag`` can only be obtained after
545 ``finalize`` has been called.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600546
547 .. attribute:: tag
548
549 :return bytes: Returns the tag value as bytes.
550 :raises: :class:`~cryptography.exceptions.NotYetFinalized` if called
Alex Gaynorfb843aa2014-02-25 11:37:36 -0800551 before the context is finalized.
Paul Kehrerad6d1642014-01-07 19:10:12 -0600552
Paul Kehrer513b7cb2015-02-12 17:31:24 -0600553.. class:: CipherAlgorithm
554
555 A named symmetric encryption algorithm.
556
557 .. attribute:: name
558
559 :type: str
560
561 The standard name for the mode, for example, "AES", "Camellia", or
562 "Blowfish".
563
564 .. attribute:: key_size
565
566 :type: int
567
568 The number of bits in the key being used.
569
570
571.. class:: BlockCipherAlgorithm
572
573 A block cipher algorithm.
574
575 .. attribute:: block_size
576
577 :type: int
578
579 The number of bits in a block.
580
581Interfaces used by the symmetric cipher modes described in
582:ref:`Symmetric Encryption Modes <symmetric-encryption-modes>`.
583
584.. currentmodule:: cryptography.hazmat.primitives.ciphers.modes
585
586.. class:: Mode
587
588 A named cipher mode.
589
590 .. attribute:: name
591
592 :type: str
593
594 This should be the standard shorthand name for the mode, for example
595 Cipher-Block Chaining mode is "CBC".
596
597 The name may be used by a backend to influence the operation of a
598 cipher in conjunction with the algorithm's name.
599
600 .. method:: validate_for_algorithm(algorithm)
601
Alex Gaynor2c526052015-02-24 10:55:28 -0800602 :param cryptography.hazmat.primitives.ciphers.CipherAlgorithm algorithm:
Paul Kehrer513b7cb2015-02-12 17:31:24 -0600603
604 Checks that the combination of this mode with the provided algorithm
605 meets any necessary invariants. This should raise an exception if they
606 are not met.
607
608 For example, the
609 :class:`~cryptography.hazmat.primitives.ciphers.modes.CBC` mode uses
610 this method to check that the provided initialization vector's length
611 matches the block size of the algorithm.
612
613
614.. class:: ModeWithInitializationVector
615
616 A cipher mode with an initialization vector.
617
618 .. attribute:: initialization_vector
619
620 :type: bytes
621
622 Exact requirements of the initialization are described by the
623 documentation of individual modes.
624
625
626.. class:: ModeWithNonce
627
628 A cipher mode with a nonce.
629
630 .. attribute:: nonce
631
632 :type: bytes
633
634 Exact requirements of the nonce are described by the documentation of
635 individual modes.
636
637
Paul Kehrer4ab60592015-02-13 09:06:48 -0600638.. class:: ModeWithAuthenticationTag
639
640 A cipher mode with an authentication tag.
641
642 .. attribute:: tag
643
644 :type: bytes
645
646 Exact requirements of the tag are described by the documentation of
647 individual modes.
648
649
Alex Gaynorab5f0112013-11-08 10:34:00 -0800650
651.. _`described by Colin Percival`: http://www.daemonology.net/blog/2009-06-11-cryptographic-right-answers.html
Alex Stapleton092351d2014-03-09 17:44:43 +0000652.. _`recommends a 96-bit IV length`: http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-spec.pdf
Alex Gaynor64f1f422017-02-27 22:25:37 -0500653.. _`NIST SP-800-38D`: http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38D.pdf
Alex Gaynor111aff22015-02-17 14:47:49 -0800654.. _`Communications Security Establishment`: https://www.cse-cst.gc.ca
Alex Gaynor62012302015-02-17 10:49:22 -0800655.. _`encrypt`: https://ssd.eff.org/en/module/what-encryption
Alex Gaynor6422d832016-03-06 21:40:57 -0500656.. _`CRYPTREC`: https://www.cryptrec.go.jp/english/
Alex Gaynor543031a2015-02-16 20:27:35 -0800657.. _`significant patterns in the output`: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_Codebook_.28ECB.29
Paul Kehrere5dc1222014-02-20 16:19:32 -0600658.. _`International Data Encryption Algorithm`: https://en.wikipedia.org/wiki/International_Data_Encryption_Algorithm
Alex Gaynore51236d2016-11-06 10:13:35 -0500659.. _`OpenPGP`: http://openpgp.org