blob: da5a95dd3f3e63abf60aa1b8209d7762b5cc69df [file] [log] [blame]
Alex Gaynoraf82d5e2013-10-29 17:07:24 -07001.. hazmat::
Alex Gaynor5f3db272013-10-29 10:56:35 -07002
3Padding
4=======
5
Alex Gaynorb2d5efd2013-10-29 11:15:30 -07006.. currentmodule:: cryptography.hazmat.primitives.padding
Alex Gaynor5f3db272013-10-29 10:56:35 -07007
8Padding is a way to take data that may or may not be be a multiple of the block
9size for a cipher and extend it out so that it is. This is required for many
10block cipher modes as they require the data to be encrypted to be an exact
11multiple of the block size.
12
13
Alex Gaynorb2d5efd2013-10-29 11:15:30 -070014.. class:: PKCS7(block_size)
Alex Gaynor5f3db272013-10-29 10:56:35 -070015
16 PKCS7 padding is a generalization of PKCS5 padding (also known as standard
17 padding). PKCS7 padding works by appending ``N`` bytes with the value of
18 ``chr(N)``, where ``N`` is the number of bytes required to make the final
19 block of data the same size as the block size. A simple example of padding
20 is:
21
22 .. doctest::
23
Alex Gaynor07082782013-10-29 11:18:23 -070024 >>> from cryptography.hazmat.primitives import padding
Alex Gaynor60ad3e12013-10-29 14:26:11 -070025 >>> padder = padding.PKCS7(128).padder()
Alex Gaynor22e2eae2013-10-29 11:42:14 -070026 >>> padder.update(b"1111111111")
27 ''
Alex Gaynorbae899a2013-11-22 16:54:55 -080028 >>> padded_data = padder.finalize()
29 >>> padded_data
Alex Gaynor5f3db272013-10-29 10:56:35 -070030 '1111111111\x06\x06\x06\x06\x06\x06'
Alex Gaynorbae899a2013-11-22 16:54:55 -080031 >>> unpadder = padding.PKCS7(128).unpadder()
32 >>> unpadder.update(padded_data)
33 ''
34 >>> unpadder.finalize()
35 '1111111111'
Alex Gaynor5f3db272013-10-29 10:56:35 -070036
37 :param block_size: The size of the block in bits that the data is being
38 padded to.
39
Alex Gaynorb2d5efd2013-10-29 11:15:30 -070040 .. method:: padder()
41
42 :returns: A padding
43 :class:`~cryptography.hazmat.primitives.interfaces.PaddingContext`
44 provider.
45
46 .. method:: unpadder()
47
48 :returns: An unpadding
49 :class:`~cryptography.hazmat.primitives.interfaces.PaddingContext`
50 provider.
51
52
53.. currentmodule:: cryptography.hazmat.primitives.interfaces
54
55.. class:: PaddingContext
56
Alex Gaynorb4818892014-02-06 10:58:50 -080057 When calling ``padder()`` or ``unpadder()`` the result will conform to the
58 ``PaddingContext`` interface. You can then call ``update(data)`` with data
59 until you have fed everything into the context. Once that is done call
60 ``finalize()`` to finish the operation and obtain the remainder of the
61 data.
Alex Gaynorb2d5efd2013-10-29 11:15:30 -070062
63 .. method:: update(data)
64
65 :param bytes data: The data you wish to pass into the context.
66 :return bytes: Returns the data that was padded or unpadded.
67
68 .. method:: finalize()
69
70 :return bytes: Returns the remainder of the data.