| 1 |
.. _modern_cipher_modes: |
| 2 |
|
| 3 |
Modern modes of operation for symmetric block ciphers |
| 4 |
===================================================== |
| 5 |
|
| 6 |
Classic modes of operation such as CBC only provide guarantees over |
| 7 |
the *confidentiality* of the message but not over its *integrity*. |
| 8 |
In other words, they don't allow the receiver to establish if the |
| 9 |
ciphertext was modified in transit or if it really originates |
| 10 |
from a certain source. |
| 11 |
|
| 12 |
For that reason, classic modes of operation have been often paired with |
| 13 |
a MAC primitive (such as :mod:`Crypto.Hash.HMAC`), but the |
| 14 |
combination is not always straightforward, efficient or secure. |
| 15 |
|
| 16 |
Recently, new modes of operations (AEAD, for `Authenticated Encryption |
| 17 |
with Associated Data <https://en.wikipedia.org/wiki/Authenticated_encryption>`_) |
| 18 |
have been designed to combine *encryption* and *authentication* into a single, |
| 19 |
efficient primitive. Optionally, some part of the message can also be left in the |
| 20 |
clear (non-confidential *associated data*, such as headers), |
| 21 |
while the whole message remains fully authenticated. |
| 22 |
|
| 23 |
In addition to the **ciphertext** and a **nonce** (or **IV** - Initialization |
| 24 |
Vector), AEAD modes require the additional delivery of a **MAC tag**. |
| 25 |
|
| 26 |
This is the state machine for a cipher object: |
| 27 |
|
| 28 |
.. figure:: aead.png |
| 29 |
:align: center |
| 30 |
:figwidth: 80% |
| 31 |
|
| 32 |
Generic state diagram for a AEAD cipher mode |
| 33 |
|
| 34 |
Beside the usual :meth:`encrypt()` and :meth:`decrypt()` already |
| 35 |
available for classic modes of operation, several other methods are present: |
| 36 |
|
| 37 |
.. method:: update(data) |
| 38 |
|
| 39 |
Authenticate those parts of the message that get delivered as is, |
| 40 |
without any encryption (like headers). |
| 41 |
It is similar to the ``update()`` method of a MAC object. |
| 42 |
Note that all data passed to ``encrypt()`` and ``decrypt()`` get |
| 43 |
automatically authenticated already. |
| 44 |
|
| 45 |
:param bytes data: the extra data to authenticate |
| 46 |
|
| 47 |
.. method:: digest() |
| 48 |
|
| 49 |
Create the final authentication tag (MAC tag) for a message. |
| 50 |
|
| 51 |
:return bytes: the MAC tag |
| 52 |
|
| 53 |
.. method:: hexdigest() |
| 54 |
|
| 55 |
Equivalent to ``digest()``, with the output encoded in hexadecimal. |
| 56 |
|
| 57 |
:return str: the MAC tag as a hexadecimal string |
| 58 |
|
| 59 |
.. method:: verify(mac_tag) |
| 60 |
|
| 61 |
Check if the provided authentication tag (MAC tag) is valid, that is, if the message |
| 62 |
has been decrypted using the right key and if no modification has taken |
| 63 |
place in transit. |
| 64 |
|
| 65 |
:param bytes mac_tag: the MAC tag |
| 66 |
:raise ValueError: if the MAC tag is not valid, that is, if the entire message |
| 67 |
should not be trusted. |
| 68 |
|
| 69 |
.. method:: hexverify(mac_tag_hex) |
| 70 |
|
| 71 |
Same as ``verify()`` but accepts the MAC tag encoded as an hexadecimal |
| 72 |
string. |
| 73 |
|
| 74 |
:param str mac_tag_hex: the MAC tag as a hexadecimal string |
| 75 |
:raise ValueError: if the MAC tag is not valid, that is, if the entire message |
| 76 |
should not be trusted. |
| 77 |
|
| 78 |
.. method:: encrypt_and_digest(plaintext, output=None) |
| 79 |
|
| 80 |
Perform ``encrypt()`` and ``digest()`` in one go. |
| 81 |
|
| 82 |
:param bytes plaintext: the last piece of plaintext to encrypt |
| 83 |
:keyword bytes/bytearray/memoryview output: the pre-allocated buffer |
| 84 |
where the ciphertext must be stored (as opposed to being returned). |
| 85 |
:return: a tuple with two items |
| 86 |
|
| 87 |
- the ciphertext, as ``bytes`` |
| 88 |
- the MAC tag, as ``bytes`` |
| 89 |
|
| 90 |
The first item becomes ``None`` when the ``output`` parameter |
| 91 |
specified a location for the result. |
| 92 |
|
| 93 |
.. method:: decrypt_and_verify(ciphertext, mac_tag, output=None) |
| 94 |
|
| 95 |
Perform ``decrypt()`` and ``verify()`` in one go. |
| 96 |
|
| 97 |
:param bytes ciphertext: the last piece of ciphertext to decrypt |
| 98 |
:keyword bytes/bytearray/memoryview output: the pre-allocated buffer |
| 99 |
where the plaintext must be stored (as opposed to being returned). |
| 100 |
:raise ValueError: if the MAC tag is not valid, that is, if the entire message |
| 101 |
should not be trusted. |
| 102 |
|
| 103 |
.. _ccm_mode: |
| 104 |
|
| 105 |
CCM mode |
| 106 |
-------- |
| 107 |
`Counter with CBC-MAC <https://en.wikipedia.org/wiki/CCM_mode>`_, defined in |
| 108 |
`RFC3610 <https://tools.ietf.org/html/rfc3610>`_ or |
| 109 |
`NIST SP 800-38C <http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C.pdf>`_. |
| 110 |
It only works with ciphers having block size 128 bits (like AES). |
| 111 |
|
| 112 |
The :func:`new` function at the module level under ``Crypto.Cipher`` instantiates |
| 113 |
a new CCM cipher object for the relevant base algorithm. |
| 114 |
In the following definition, ``<algorithm>`` can only be ``AES`` today: |
| 115 |
|
| 116 |
.. function:: Crypto.Cipher.<algorithm>.new(key, mode, *, nonce=None, mac_len=None, msg_len=None, assoc_len=None) |
| 117 |
|
| 118 |
Create a new CCM object, using <algorithm> as the base block cipher. |
| 119 |
|
| 120 |
:param bytes key: the cryptographic key |
| 121 |
:param mode: the constant ``Crypto.Cipher.<algorithm>.MODE_CCM`` |
| 122 |
:param bytes nonce: the value of the fixed nonce. |
| 123 |
It must be unique for the combination message/key. |
| 124 |
For AES, its length varies from 7 to 13 bytes. |
| 125 |
The longer the nonce, the smaller the allowed message size |
| 126 |
(with a nonce of 13 bytes, the message cannot exceed 64KB). |
| 127 |
If not present, the library creates a 11 bytes random nonce (the maximum |
| 128 |
message size is 8GB). |
| 129 |
:param integer mac_len: the desired length of the |
| 130 |
MAC tag (default if not present: 16 bytes). |
| 131 |
:param integer msg_len: pre-declaration of the length of the |
| 132 |
message to encipher. If not specified, :func:`encrypt` and :func:`decrypt` |
| 133 |
can only be called once. |
| 134 |
:param integer assoc_len: pre-declaration of the length of the |
| 135 |
associated data. If not specified, some extra buffering will take place |
| 136 |
internally. |
| 137 |
:return: a CTR cipher object |
| 138 |
|
| 139 |
The cipher object has a read-only attribute :attr:`nonce`. |
| 140 |
|
| 141 |
Example (encryption):: |
| 142 |
|
| 143 |
>>> import json |
| 144 |
>>> from base64 import b64encode |
| 145 |
>>> from Crypto.Cipher import AES |
| 146 |
>>> from Crypto.Random import get_random_bytes |
| 147 |
>>> |
| 148 |
>>> header = b"header" |
| 149 |
>>> data = b"secret" |
| 150 |
>>> key = get_random_bytes(16) |
| 151 |
>>> cipher = AES.new(key, AES.MODE_CCM) |
| 152 |
>>> cipher.update(header) |
| 153 |
>>> ciphertext, tag = cipher.encrypt_and_digest(data) |
| 154 |
>>> |
| 155 |
>>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ] |
| 156 |
>>> json_v = [ b64encode(x).decode('utf-8') for x in (cipher.nonce, header, ciphertext, tag) ] |
| 157 |
>>> result = json.dumps(dict(zip(json_k, json_v))) |
| 158 |
>>> print(result) |
| 159 |
{"nonce": "p6ffzcKw+6xopVQ=", "header": "aGVhZGVy", "ciphertext": "860kZo/G", "tag": "Ck5YpVCM6fdWnFkFxw8K6A=="} |
| 160 |
|
| 161 |
Example (decryption):: |
| 162 |
|
| 163 |
>>> import json |
| 164 |
>>> from base64 import b64decode |
| 165 |
>>> from Crypto.Cipher import AES |
| 166 |
>>> |
| 167 |
>>> # We assume that the key was securely shared beforehand |
| 168 |
>>> try: |
| 169 |
>>> b64 = json.loads(json_input) |
| 170 |
>>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ] |
| 171 |
>>> jv = {k:b64decode(b64[k]) for k in json_k} |
| 172 |
>>> |
| 173 |
>>> cipher = AES.new(key, AES.MODE_CCM, nonce=jv['nonce']) |
| 174 |
>>> cipher.update(jv['header']) |
| 175 |
>>> plaintext = cipher.decrypt_and_verify(jv['ciphertext'], jv['tag']) |
| 176 |
>>> print("The message was: " + plaintext.decode('utf-8')) |
| 177 |
>>> except (ValueError, KeyError): |
| 178 |
>>> print("Incorrect decryption") |
| 179 |
|
| 180 |
.. _eax_mode: |
| 181 |
|
| 182 |
EAX mode |
| 183 |
-------- |
| 184 |
An AEAD mode designed for NIST by |
| 185 |
`Bellare, Rogaway, and Wagner in 2003 <http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/eax/eax-spec.pdf>`_. |
| 186 |
|
| 187 |
The :func:`new` function at the module level under ``Crypto.Cipher`` instantiates |
| 188 |
a new EAX cipher object for the relevant base algorithm. |
| 189 |
|
| 190 |
.. function:: Crypto.Cipher.<algorithm>.new(key, mode, *, nonce=None, mac_len=None) |
| 191 |
|
| 192 |
Create a new EAX object, using <algorithm> as the base block cipher. |
| 193 |
|
| 194 |
:param bytes key: the cryptographic key |
| 195 |
:param mode: the constant ``Crypto.Cipher.<algorithm>.MODE_EAX`` |
| 196 |
:param bytes nonce: the value of the fixed nonce. |
| 197 |
It must be unique for the combination message/key. |
| 198 |
If not present, the library creates a random nonce (16 bytes long for AES). |
| 199 |
:param integer mac_len: the length of the MAC tag, in bytes. |
| 200 |
At least 2, and not larger than the cipher's block size (default), |
| 201 |
which is 16 bytes for AES. |
| 202 |
:return: an EAX cipher object |
| 203 |
|
| 204 |
The cipher object has a read-only attribute :attr:`nonce`. |
| 205 |
|
| 206 |
Example (encryption):: |
| 207 |
|
| 208 |
>>> import json |
| 209 |
>>> from base64 import b64encode |
| 210 |
>>> from Crypto.Cipher import AES |
| 211 |
>>> from Crypto.Random import get_random_bytes |
| 212 |
>>> |
| 213 |
>>> header = b"header" |
| 214 |
>>> data = b"secret" |
| 215 |
>>> key = get_random_bytes(16) |
| 216 |
>>> cipher = AES.new(key, AES.MODE_EAX) |
| 217 |
>>> cipher.update(header) |
| 218 |
>>> ciphertext, tag = cipher.encrypt_and_digest(data) |
| 219 |
>>> |
| 220 |
>>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ] |
| 221 |
>>> json_v = [ b64encode(x).decode('utf-8') for x in (cipher.nonce, header, ciphertext, tag) ] |
| 222 |
>>> result = json.dumps(dict(zip(json_k, json_v))) |
| 223 |
>>> print(result) |
| 224 |
{"nonce": "CSIJ+e8KP7HJo+hC4RXIyQ==", "header": "aGVhZGVy", "ciphertext": "9YYjuAn6", "tag": "kXHrs9ZwYmjDkmfEJx7Clg=="} |
| 225 |
|
| 226 |
Example (decryption):: |
| 227 |
|
| 228 |
>>> import json |
| 229 |
>>> from base64 import b64decode |
| 230 |
>>> from Crypto.Cipher import AES |
| 231 |
>>> |
| 232 |
>>> # We assume that the key was securely shared beforehand |
| 233 |
>>> try: |
| 234 |
>>> b64 = json.loads(json_input) |
| 235 |
>>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ] |
| 236 |
>>> jv = {k:b64decode(b64[k]) for k in json_k} |
| 237 |
>>> |
| 238 |
>>> cipher = AES.new(key, AES.MODE_EAX, nonce=jv['nonce']) |
| 239 |
>>> cipher.update(jv['header']) |
| 240 |
>>> plaintext = cipher.decrypt_and_verify(jv['ciphertext'], jv['tag']) |
| 241 |
>>> print("The message was: " + plaintext.decode('utf-8')) |
| 242 |
>>> except (ValueError, KeyError): |
| 243 |
>>> print("Incorrect decryption") |
| 244 |
|
| 245 |
.. _gcm_mode: |
| 246 |
|
| 247 |
GCM mode |
| 248 |
-------- |
| 249 |
`Galois/Counter Mode <https://en.wikipedia.org/wiki/Galois/Counter_Mode>`_, |
| 250 |
defined in `NIST SP 800-38D <http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf>`_. |
| 251 |
It only works in combination with a 128 bits cipher like AES. |
| 252 |
|
| 253 |
The :func:`new` function at the module level under ``Crypto.Cipher`` instantiates |
| 254 |
a new GCM cipher object for the relevant base algorithm. |
| 255 |
|
| 256 |
.. function:: Crypto.Cipher.<algorithm>.new(key, mode, *, nonce=None, mac_len=None) |
| 257 |
|
| 258 |
Create a new GCM object, using <algorithm> as the base block cipher. |
| 259 |
|
| 260 |
:param bytes key: the cryptographic key |
| 261 |
:param mode: the constant ``Crypto.Cipher.<algorithm>.MODE_GCM`` |
| 262 |
:param bytes nonce: the value of the fixed nonce. |
| 263 |
It must be unique for the combination message/key. |
| 264 |
If not present, the library creates a random nonce (16 bytes long for AES). |
| 265 |
:param integer mac_len: the desired length of the |
| 266 |
MAC tag, from 4 to 16 bytes (default: 16). |
| 267 |
:return: a GCM cipher object |
| 268 |
|
| 269 |
The cipher object has a read-only attribute :attr:`nonce`. |
| 270 |
|
| 271 |
Example (encryption):: |
| 272 |
|
| 273 |
>>> import json |
| 274 |
>>> from base64 import b64encode |
| 275 |
>>> from Crypto.Cipher import AES |
| 276 |
>>> from Crypto.Random import get_random_bytes |
| 277 |
>>> |
| 278 |
>>> header = b"header" |
| 279 |
>>> data = b"secret" |
| 280 |
>>> key = get_random_bytes(16) |
| 281 |
>>> cipher = AES.new(key, AES.MODE_GCM) |
| 282 |
>>> cipher.update(header) |
| 283 |
>>> ciphertext, tag = cipher.encrypt_and_digest(data) |
| 284 |
>>> |
| 285 |
>>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ] |
| 286 |
>>> json_v = [ b64encode(x).decode('utf-8') for x in (cipher.nonce, header, ciphertext, tag) ] |
| 287 |
>>> result = json.dumps(dict(zip(json_k, json_v))) |
| 288 |
>>> print(result) |
| 289 |
{"nonce": "DpOK8NIOuSOQlTq+BphKWw==", "header": "aGVhZGVy", "ciphertext": "CZVqyacc", "tag": "B2tBgICbyw+Wji9KpLVa8w=="} |
| 290 |
|
| 291 |
Example (decryption):: |
| 292 |
|
| 293 |
>>> import json |
| 294 |
>>> from base64 import b64decode |
| 295 |
>>> from Crypto.Cipher import AES |
| 296 |
>>> |
| 297 |
>>> # We assume that the key was securely shared beforehand |
| 298 |
>>> try: |
| 299 |
>>> b64 = json.loads(json_input) |
| 300 |
>>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ] |
| 301 |
>>> jv = {k:b64decode(b64[k]) for k in json_k} |
| 302 |
>>> |
| 303 |
>>> cipher = AES.new(key, AES.MODE_GCM, nonce=jv['nonce']) |
| 304 |
>>> cipher.update(jv['header']) |
| 305 |
>>> plaintext = cipher.decrypt_and_verify(jv['ciphertext'], jv['tag']) |
| 306 |
>>> print("The message was: " + plaintext.decode('utf-8')) |
| 307 |
>>> except (ValueError, KeyError): |
| 308 |
>>> print("Incorrect decryption") |
| 309 |
|
| 310 |
.. note:: |
| 311 |
GCM is most commonly used with 96-bit (12-byte) nonces, which is also the length recommended by NIST SP 800-38D. |
| 312 |
|
| 313 |
If interoperability is important, one should take into account that the library default |
| 314 |
of a 128-bit random nonce may not be (easily) supported by other implementations. |
| 315 |
A 96-bit nonce can be explicitly generated for a new encryption cipher:: |
| 316 |
|
| 317 |
>>> key = get_random_bytes(16) |
| 318 |
>>> nonce = get_random_bytes(12) |
| 319 |
>>> cipher = AES.new(key, AES.MODE_GCM, nonce=nonce) |
| 320 |
|
| 321 |
.. _siv_mode: |
| 322 |
|
| 323 |
SIV mode |
| 324 |
-------- |
| 325 |
Synthetic Initialization Vector (SIV), defined in `RFC5297 <https://tools.ietf.org/html/rfc5297>`_. |
| 326 |
It only works with ciphers with a block size of 128 bits (like AES). |
| 327 |
|
| 328 |
Although less efficient than other modes, SIV is *nonce misuse-resistant*: |
| 329 |
accidental reuse of the nonce does not jeopardize the security as it happens with CCM or GCM. |
| 330 |
As a matter of fact, operating **without** a nonce is not an error per se: the cipher |
| 331 |
simply becomes **deterministic**. In other words, a message gets always encrypted into |
| 332 |
the same ciphertext. |
| 333 |
|
| 334 |
The :func:`new` function at the module level under ``Crypto.Cipher`` instantiates |
| 335 |
a new SIV cipher object for the relevant base algorithm. |
| 336 |
|
| 337 |
.. function:: Crypto.Cipher.<algorithm>.new(key, mode, *, nonce=None) |
| 338 |
|
| 339 |
Create a new SIV object, using <algorithm> as the base block cipher. |
| 340 |
|
| 341 |
:param bytes key: the cryptographic key; it must be twice the size of the key |
| 342 |
required by the underlying cipher (e.g. 32 bytes for |
| 343 |
AES-128). |
| 344 |
:param mode: the constant ``Crypto.Cipher.<algorithm>.MODE_SIV`` |
| 345 |
:param bytes nonce: the value of the fixed nonce. |
| 346 |
It must be unique for the combination message/key. |
| 347 |
If not present, the encryption will be deterministic. |
| 348 |
:return: a SIV cipher object |
| 349 |
|
| 350 |
If the `nonce` parameter was provided to :func:`new`, the resulting cipher object has a read-only attribute :attr:`nonce`. |
| 351 |
|
| 352 |
Example (encryption):: |
| 353 |
|
| 354 |
>>> import json |
| 355 |
>>> from base64 import b64encode |
| 356 |
>>> from Crypto.Cipher import AES |
| 357 |
>>> from Crypto.Random import get_random_bytes |
| 358 |
>>> |
| 359 |
>>> header = b"header" |
| 360 |
>>> data = b"secret" |
| 361 |
>>> key = get_random_bytes(16 * 2) |
| 362 |
>>> nonce = get_random_bytes(16) |
| 363 |
>>> cipher = AES.new(key, AES.MODE_SIV, nonce=nonce) # Without nonce, the encryption |
| 364 |
>>> # becomes deterministic |
| 365 |
>>> cipher.update(header) |
| 366 |
>>> ciphertext, tag = cipher.encrypt_and_digest(data) |
| 367 |
>>> |
| 368 |
>>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ] |
| 369 |
>>> json_v = [ b64encode(x).decode('utf-8') for x in (nonce, header, ciphertext, tag) ] |
| 370 |
>>> result = json.dumps(dict(zip(json_k, json_v))) |
| 371 |
>>> print(result) |
| 372 |
{"nonce": "zMiifAVvDpMS8hnGK/z+iw==", "header": "aGVhZGVy", "ciphertext": "Q7lReEAF", "tag": "KgdnBVbCee6B/wGmMf/wQA=="} |
| 373 |
|
| 374 |
Example (decryption):: |
| 375 |
|
| 376 |
>>> import json |
| 377 |
>>> from base64 import b64decode |
| 378 |
>>> from Crypto.Cipher import AES |
| 379 |
>>> |
| 380 |
>>> # We assume that the key was securely shared beforehand |
| 381 |
>>> try: |
| 382 |
>>> b64 = json.loads(json_input) |
| 383 |
>>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ] |
| 384 |
>>> jv = {k:b64decode(b64[k]) for k in json_k} |
| 385 |
>>> |
| 386 |
>>> cipher = AES.new(key, AES.MODE_SIV, nonce=jv['nonce']) |
| 387 |
>>> cipher.update(jv['header']) |
| 388 |
>>> plaintext = cipher.decrypt_and_verify(jv['ciphertext'], jv['tag']) |
| 389 |
>>> print("The message was: " + plaintext.decode('utf-8')) |
| 390 |
>>> except (ValueError, KeyError): |
| 391 |
>>> print("Incorrect decryption") |
| 392 |
|
| 393 |
One side-effect is that encryption (or decryption) must take place in one go |
| 394 |
with the method ``encrypt_and_digest()`` (or ``decrypt_and_verify()``). |
| 395 |
You cannot use ``encrypt()`` or ``decrypt()``. The state diagram is therefore: |
| 396 |
|
| 397 |
.. figure:: siv.png |
| 398 |
:align: center |
| 399 |
:figwidth: 60% |
| 400 |
|
| 401 |
State diagram for the SIV cipher mode |
| 402 |
|
| 403 |
The length of the key passed to ``new()`` must be twice |
| 404 |
as required by the underlying block cipher (e.g. 32 bytes for AES-128). |
| 405 |
|
| 406 |
Each call to the method ``update()`` consumes an full piece of associated data. |
| 407 |
That is, the sequence:: |
| 408 |
|
| 409 |
>>> siv_cipher.update(b"builtin") |
| 410 |
>>> siv_cipher.update(b"securely") |
| 411 |
|
| 412 |
is **not** equivalent to:: |
| 413 |
|
| 414 |
>>> siv_cipher.update(b"built") |
| 415 |
>>> siv_cipher.update(b"insecurely") |
| 416 |
|
| 417 |
.. _ocb_mode: |
| 418 |
|
| 419 |
OCB mode |
| 420 |
-------- |
| 421 |
`Offset CodeBook mode <https://en.wikipedia.org/wiki/OCB_mode>`_, |
| 422 |
a cipher designed by Rogaway and specified in `RFC7253 <http://www.rfc-editor.org/info/rfc7253>`_ |
| 423 |
(more specifically, this module implements the last variant, OCB3). |
| 424 |
It only works in combination with a 128 bits cipher like AES. |
| 425 |
|
| 426 |
OCB was patented in USA but the author eventually `abandoned the patents <https://mailarchive.ietf.org/arch/msg/cfrg/qLTveWOdTJcLn4HP3ev-vrj05Vg/>`_. |
| 427 |
|
| 428 |
The :func:`new` function at the module level under ``Crypto.Cipher`` instantiates |
| 429 |
a new OCB cipher object for the relevant base algorithm. |
| 430 |
|
| 431 |
.. note:: |
| 432 |
|
| 433 |
The OCB state machine is slightly different compared to other modes: |
| 434 |
if you encrypt (or decrypt) multiple chunks, |
| 435 |
at the end you MUST call the method ``encrypt`` (or ``decrypt``) with no parameters. |
| 436 |
This last call will return any piece of internally cached ciphertext (or plaintext). |
| 437 |
|
| 438 |
.. figure:: ocb_mode.png |
| 439 |
:align: center |
| 440 |
:figwidth: 80% |
| 441 |
|
| 442 |
State diagram for the OCB mode |
| 443 |
|
| 444 |
|
| 445 |
.. function:: Crypto.Cipher.<algorithm>.new(key, mode, *, nonce=None, mac_len=None) |
| 446 |
|
| 447 |
Create a new OCB object, using <algorithm> as the base block cipher. |
| 448 |
|
| 449 |
:param bytes key: the cryptographic key |
| 450 |
:param mode: the constant ``Crypto.Cipher.<algorithm>.MODE_OCB`` |
| 451 |
:param bytes nonce: the value of the fixed nonce, |
| 452 |
with length between 1 and 15 bytes. |
| 453 |
It must be unique for the combination message/key. |
| 454 |
If not present, the library creates a 15 bytes random nonce. |
| 455 |
:param integer mac_len: the desired length of the |
| 456 |
MAC tag (default if not present: 16 bytes). |
| 457 |
:return: an OCB cipher object |
| 458 |
|
| 459 |
The cipher object has two read-only attributes: :attr:`nonce` and :attr:`block_size`. |
| 460 |
|
| 461 |
Example (encryption as a once-off operation):: |
| 462 |
|
| 463 |
>>> import json |
| 464 |
>>> from base64 import b64encode |
| 465 |
>>> from Crypto.Cipher import AES |
| 466 |
>>> from Crypto.Random import get_random_bytes |
| 467 |
>>> |
| 468 |
>>> header = b"header" |
| 469 |
>>> data = b"secret" |
| 470 |
>>> key = get_random_bytes(16) |
| 471 |
>>> cipher = AES.new(key, AES.MODE_OCB) |
| 472 |
>>> cipher.update(header) |
| 473 |
>>> ciphertext, tag = cipher.encrypt_and_digest(data) |
| 474 |
>>> |
| 475 |
>>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ] |
| 476 |
>>> json_v = [ b64encode(x).decode('utf-8') for x in (cipher.nonce, header, ciphertext, tag) ] |
| 477 |
>>> result = json.dumps(dict(zip(json_k, json_v))) |
| 478 |
>>> print(result) |
| 479 |
{"nonce": "I7E6PKxHNYo2i9sz8W98", "header": "aGVhZGVy", "ciphertext": "nYJnJ8jC", "tag": "0UbFcmO9lqGknCIDWRLALA=="} |
| 480 |
|
| 481 |
Example (decryption as a once-off operation):: |
| 482 |
|
| 483 |
>>> import json |
| 484 |
>>> from base64 import b64decode |
| 485 |
>>> from Crypto.Cipher import AES |
| 486 |
>>> |
| 487 |
>>> # We assume that the key was securely shared beforehand |
| 488 |
>>> try: |
| 489 |
>>> b64 = json.loads(json_input) |
| 490 |
>>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ] |
| 491 |
>>> jv = {k:b64decode(b64[k]) for k in json_k} |
| 492 |
>>> |
| 493 |
>>> cipher = AES.new(key, AES.MODE_OCB, nonce=jv['nonce']) |
| 494 |
>>> cipher.update(jv['header']) |
| 495 |
>>> plaintext = cipher.decrypt_and_verify(jv['ciphertext'], jv['tag']) |
| 496 |
>>> print("The message was: " + plaintext.decode('utf-8')) |
| 497 |
>>> except (ValueError, KeyError): |
| 498 |
>>> print("Incorrect decryption") |
| 499 |
|
| 500 |
Example (encryption with multiple chunks):: |
| 501 |
|
| 502 |
>>> import json |
| 503 |
>>> from base64 import b64encode |
| 504 |
>>> from Crypto.Cipher import AES |
| 505 |
>>> from Crypto.Random import get_random_bytes |
| 506 |
>>> |
| 507 |
>>> header = b'header' |
| 508 |
>>> data = [b'chunk1', b'chunk2', b'chunk3'] |
| 509 |
>>> key = get_random_bytes(16) |
| 510 |
>>> cipher = AES.new(key, AES.MODE_OCB) |
| 511 |
>>> cipher.update(header) |
| 512 |
>>> ciphertext = b'' |
| 513 |
>>> for chunk in data: |
| 514 |
>>> ciphertext += cipher.encrypt(chunk) |
| 515 |
>>> ciphertext += cipher.encrypt() |
| 516 |
>>> tag = cipher.digest() |
| 517 |
>>> |
| 518 |
>>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ] |
| 519 |
>>> json_v = [ b64encode(x).decode('utf-8') for x in (cipher.nonce, header, ciphertext, tag) ] |
| 520 |
>>> result = json.dumps(dict(zip(json_k, json_v))) |
| 521 |
>>> print(result) |
| 522 |
{"nonce": "IABQ/ww8vGsu7F4sbHXK", "header": "aGVhZGVy", "ciphertext": "7Amm2DoiMHVkYC8dY7NEX86M", "tag": "qOPnjAxF63MOAx6xjwRvJQ=="} |
| 523 |
|
| 524 |
Example (decryption with multiple chunks):: |
| 525 |
|
| 526 |
>>> import json |
| 527 |
>>> from base64 import b64decode |
| 528 |
>>> from Crypto.Cipher import AES |
| 529 |
>>> |
| 530 |
>>> # We assume that the key was securely shared beforehand |
| 531 |
>>> try: |
| 532 |
>>> b64 = json.loads(json_input) |
| 533 |
>>> json_k = [ 'nonce', 'header', 'ciphertext', 'tag' ] |
| 534 |
>>> jv = {k:b64decode(b64[k]) for k in json_k} |
| 535 |
>>> |
| 536 |
>>> cipher = AES.new(key, AES.MODE_OCB, nonce=jv['nonce']) |
| 537 |
>>> cipher.update(jv['header']) |
| 538 |
>>> ciphertext = jv['ciphertext'] |
| 539 |
>>> |
| 540 |
>>> # Split into small chunks, just for demo purposes |
| 541 |
>>> chunks = [ ciphertext[i:i+2] for i in range(0, len(ciphertext), 2) ] |
| 542 |
>>> |
| 543 |
>>> plaintext = b'' |
| 544 |
>>> for chunk in chunks: |
| 545 |
>>> plaintext += cipher.decrypt(chunk) |
| 546 |
>>> plaintext += cipher.decrypt() |
| 547 |
>>> cipher.verify(jv['tag']) |
| 548 |
>>> |
| 549 |
>>> print("The message was: " + plaintext.decode('utf-8')) |
| 550 |
>>> except (ValueError, KeyError): |
| 551 |
>>> print("Incorrect decryption") |
| 552 |
|