aboutsummaryrefslogtreecommitdiffstats
path: root/docs/hazmat/primitives/padding.rst
blob: 4b05acd145e05d85e22ce370dcd420c9a3689497 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
.. danger::

    This is a "Hazardous Materials" module. You should **ONLY** use it if
    you're 100% absolutely sure that you know what you're doing because this
    module is full of land mines, dragons, and dinosaurs with laser guns.


Padding
=======

.. currentmodule:: cryptography.hazmat.primitives.padding

Padding is a way to take data that may or may not be be a multiple of the block
size for a cipher and extend it out so that it is. This is required for many
block cipher modes as they require the data to be encrypted to be an exact
multiple of the block size.


.. class:: PKCS7(block_size)

    PKCS7 padding is a generalization of PKCS5 padding (also known as standard
    padding). PKCS7 padding works by appending ``N`` bytes with the value of
    ``chr(N)``, where ``N`` is the number of bytes required to make the final
    block of data the same size as the block size. A simple example of padding
    is:

    .. doctest::

        >>> from cryptography.hazmat.primitives import padding
        >>> padder = padding.PKCS7(128)
        >>> padder = padder.padder()
        >>> padder.update(b"1111111111")
        ''
        >>> padder.finalize()
        '1111111111\x06\x06\x06\x06\x06\x06'

    :param block_size: The size of the block in bits that the data is being
                       padded to.

    .. method:: padder()

        :returns: A padding
            :class:`~cryptography.hazmat.primitives.interfaces.PaddingContext`
            provider.

    .. method:: unpadder()

        :returns: An unpadding
            :class:`~cryptography.hazmat.primitives.interfaces.PaddingContext`
            provider.


.. currentmodule:: cryptography.hazmat.primitives.interfaces

.. class:: PaddingContext

    When calling ``padder()`` or ``unpadder()`` you will receive an a return
    object conforming to the ``PaddingContext`` interface. You can then call
    ``update(data)`` with data until you have fed everything into the context.
    Once that is done call ``finalize()`` to finish the operation and obtain
    the remainder of the data.

    .. method:: update(data)

        :param bytes data: The data you wish to pass into the context.
        :return bytes: Returns the data that was padded or unpadded.

    .. method:: finalize()

        :return bytes: Returns the remainder of the data.