1
2:mod:`crcmod` -- CRC calculation
3================================
4
5.. module:: crcmod
6   :synopsis: CRC calculation
7.. moduleauthor:: Raymond L Buvel
8.. sectionauthor:: Craig McQueen
9
10This module provides a function factory :func:`mkCrcFun` and a class :class:`Crc`
11for calculating CRCs of byte strings using common CRC algorithms.
12
13.. note:: This documentation normally shows Python 2.x usage. Python 3.x usage is very similar,
14    with the main difference that input strings must be explicitly defined as
15    :keyword:`bytes` type, or an object that supports the buffer protocol. E.g.::
16
17       >>> crc_value = crc_function(b'123456789')
18
19       >>> crc_value = crc_function(bytearray((49, 50, 51, 52, 53, 54, 55, 56, 57)))
20
21
22:func:`mkCrcFun` -- CRC function factory
23----------------------------------------
24
25The function factory provides a simple interface for CRC calculation.
26
27.. function:: mkCrcFun(poly[, initCrc, rev, xorOut])
28
29   Function factory that returns a new function for calculating CRCs
30   using a specified CRC algorithm.
31
32   :param poly:     The generator polynomial to use in calculating the CRC.  The value
33                    is specified as a Python integer or long integer.  The bits in this integer
34                    are the coefficients of the polynomial.  The only polynomials allowed are
35                    those that generate 8, 16, 24, 32, or 64 bit CRCs.
36
37   :param initCrc:  Initial value used to start the CRC calculation.  This initial
38                    value should be the initial shift register value, reversed if it uses a
39                    reversed algorithm, and then XORed with the final XOR value.  That is
40                    equivalent to the CRC result the algorithm should return for a
41                    zero-length string.  Defaults to all bits set because that starting value
42                    will take leading zero bytes into account.  Starting with zero will ignore
43                    all leading zero bytes.
44
45   :param rev:      A flag that selects a bit reversed algorithm when :keyword:`True`.  Defaults to
46                    :keyword:`True` because the bit reversed algorithms are more efficient.
47
48   :param xorOut:   Final value to XOR with the calculated CRC value.  Used by some
49                    CRC algorithms.  Defaults to zero.
50
51   :return:         CRC calculation function
52   :rtype:          function
53
54   The function that is returned is as follows:
55
56   .. function:: .crc_function(data[, crc=initCrc])
57
58   :param data:     Data for which to calculate the CRC.
59   :type data:      byte string
60
61   :param crc:      Initial CRC value.
62
63   :return:         Calculated CRC value.
64   :rtype:          integer
65
66Examples
67^^^^^^^^
68
69**CRC-32** Example::
70
71   >>> import crcmod
72
73   >>> crc32_func = crcmod.mkCrcFun(0x104c11db7, initCrc=0, xorOut=0xFFFFFFFF)
74   >>> hex(crc32_func('123456789'))
75   '0xcbf43926L'
76
77The CRC-32 uses a "reversed" algorithm, used for many common CRC algorithms.
78Less common is the non-reversed algorithm, as used by the 16-bit **XMODEM** CRC::
79
80   >>> xmodem_crc_func = crcmod.mkCrcFun(0x11021, rev=False, initCrc=0x0000, xorOut=0x0000)
81   >>> hex(xmodem_crc_func('123456789'))
82   '0x31c3'
83
84The CRC function can be called multiple times. On subsequent calls, pass the
85CRC value previously calculated as a second parameter::
86
87   >>> crc_value = crc32_func('1234')
88   >>> crc_value = crc32_func('56789', crc_value)
89   >>> hex(crc_value)
90   '0xcbf43926L'
91
92Python 3.x example: Unicode strings are not accepted as input. Byte strings are acceptable.
93You may calculate a CRC for an object that implements the buffer protocol::
94
95   >>> import crcmod
96   >>> crc32_func = crcmod.mkCrcFun(0x104c11db7, initCrc=0, xorOut=0xFFFFFFFF)
97   >>> hex(crc32_func('123456789'))
98   ...
99   TypeError: Unicode-objects must be encoded before calculating a CRC
100   >>> hex(crc32_func(b'123456789'))
101   '0xcbf43926'
102   >>> hex(crc32_func(bytearray((49, 50, 51, 52, 53, 54, 55, 56, 57))))
103   '0xcbf43926'
104
105
106Class :class:`Crc`
107------------------
108
109The class provides an interface similar to the Python :mod:`hashlib`, :mod:`md5` and :mod:`sha` modules.
110
111.. class:: Crc(poly[, initCrc, rev, xorOut])
112
113   Returns a new :class:`Crc` object for calculating CRCs using a specified CRC algorithm.
114
115   The parameters are the same as those for the factory function :func:`mkCrcFun`.
116
117   :param poly:     The generator polynomial to use in calculating the CRC.  The value
118                    is specified as a Python integer or long integer.  The bits in this integer
119                    are the coefficients of the polynomial.  The only polynomials allowed are
120                    those that generate 8, 16, 24, 32, or 64 bit CRCs.
121
122   :param initCrc:  Initial value used to start the CRC calculation.  This initial
123                    value should be the initial shift register value, reversed if it uses a
124                    reversed algorithm, and then XORed with the final XOR value.  That is
125                    equivalent to the CRC result the algorithm should return for a
126                    zero-length string.  Defaults to all bits set because that starting value
127                    will take leading zero bytes into account.  Starting with zero will ignore
128                    all leading zero bytes.
129
130   :param rev:      A flag that selects a bit reversed algorithm when :keyword:`True`.  Defaults to
131                    :keyword:`True` because the bit reversed algorithms are more efficient.
132
133   :param xorOut:   Final value to XOR with the calculated CRC value.  Used by some
134                    CRC algorithms.  Defaults to zero.
135
136   :class:`Crc` objects contain the following constant values:
137
138   .. attribute:: digest_size
139
140      The size of the resulting digest in bytes. This depends on the width of the CRC polynomial.
141      E.g. for a 32-bit CRC, :data:`digest_size` will be ``4``.
142
143   .. attribute:: crcValue
144
145      The calculated CRC value, as an integer, for the data that has been input
146      using :meth:`update`. This value is updated after each call to :meth:`update`.
147
148   :class:`Crc` objects support the following methods:
149
150   .. method:: new([arg])
151
152      Create a new instance of the :class:`Crc` class initialized to the same
153      values as the original instance.  The CRC value is set to the initial
154      value.  If a string is provided in the optional ``arg`` parameter, it is
155      passed to the :meth:`update` method.
156
157   .. method:: copy()
158
159      Create a new instance of the :class:`Crc` class initialized to the same
160      values as the original instance.  The CRC value is copied from the current
161      value.  This allows multiple CRC calculations using a common initial
162      string.
163
164   .. method:: update(data)
165
166      :param data:     Data for which to calculate the CRC
167      :type data:      byte string
168
169      Update the calculated CRC value for the specified input data.
170
171   .. method:: digest()
172
173      Return the current CRC value as a string of bytes.  The length of
174      this string is specified in the :attr:`digest_size` attribute.
175
176   .. method:: hexdigest()
177
178      Return the current CRC value as a string of hex digits.  The length
179      of this string is twice the :attr:`digest_size` attribute.
180
181   .. method:: generateCode(functionName, out, [dataType, crcType])
182
183      Generate a C/C++ function.
184
185      :param functionName: String specifying the name of the function.
186
187      :param out:       An open file-like object with a write method.
188                        This specifies where the generated code is written.
189
190      :param dataType:  An optional parameter specifying the data type of the input
191                        data to the function.  Defaults to ``UINT8``.
192
193      :param crcType:   An optional parameter specifying the data type of the CRC value.
194                        Defaults to one of ``UINT8``, ``UINT16``, ``UINT32``, or ``UINT64`` depending
195                        on the size of the CRC value.
196
197Examples
198^^^^^^^^
199
200**CRC-32** Example::
201
202   >>> import crcmod
203
204   >>> crc32 = crcmod.Crc(0x104c11db7, initCrc=0, xorOut=0xFFFFFFFF)
205   >>> crc32.update('123456789')
206   >>> hex(crc32.crcValue)
207   '0xcbf43926L'
208   >>> crc32.hexdigest()
209   'CBF43926'
210
211The :meth:`Crc.update` method can be called multiple times, and the CRC value is updated with each call::
212
213   >>> crc32new = crc32.new()
214   >>> crc32new.update('1234')
215   >>> crc32new.hexdigest()
216   '9BE3E0A3'
217   >>> crc32new.update('56789')
218   >>> crc32new.hexdigest()
219   'CBF43926'
220