| 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 |
def new(nbits, prefix=b"", suffix=b"", initial_value=1, little_endian=False, allow_wraparound=False): |
| 26 |
"""Create a stateful counter block function suitable for CTR encryption modes. |
| 27 |
|
| 28 |
Each call to the function returns the next counter block. |
| 29 |
Each counter block is made up by three parts: |
| 30 |
|
| 31 |
+------+--------------+-------+ |
| 32 |
|prefix| counter value|postfix| |
| 33 |
+------+--------------+-------+ |
| 34 |
|
| 35 |
The counter value is incremented by 1 at each call. |
| 36 |
|
| 37 |
Args: |
| 38 |
nbits (integer): |
| 39 |
Length of the desired counter value, in bits. It must be a multiple of 8. |
| 40 |
prefix (byte string): |
| 41 |
The constant prefix of the counter block. By default, no prefix is |
| 42 |
used. |
| 43 |
suffix (byte string): |
| 44 |
The constant postfix of the counter block. By default, no suffix is |
| 45 |
used. |
| 46 |
initial_value (integer): |
| 47 |
The initial value of the counter. Default value is 1. |
| 48 |
Its length in bits must not exceed the argument ``nbits``. |
| 49 |
little_endian (boolean): |
| 50 |
If ``True``, the counter number will be encoded in little endian format. |
| 51 |
If ``False`` (default), in big endian format. |
| 52 |
allow_wraparound (boolean): |
| 53 |
This parameter is ignored. |
| 54 |
An ``OverflowError`` exception is always raised when the counter wraps |
| 55 |
around to zero. |
| 56 |
Returns: |
| 57 |
An object that can be passed with the :data:`counter` parameter to a CTR mode |
| 58 |
cipher. |
| 59 |
|
| 60 |
It must hold that *len(prefix) + nbits//8 + len(suffix)* matches the |
| 61 |
block size of the underlying block cipher. |
| 62 |
""" |
| 63 |
|
| 64 |
if (nbits % 8) != 0: |
| 65 |
raise ValueError("'nbits' must be a multiple of 8") |
| 66 |
|
| 67 |
iv_bl = initial_value.bit_length() |
| 68 |
if iv_bl > nbits: |
| 69 |
raise ValueError("Initial value takes %d bits but it is longer than " |
| 70 |
"the counter (%d bits)" % |
| 71 |
(iv_bl, nbits)) |
| 72 |
|
| 73 |
|
| 74 |
return {"counter_len": nbits // 8, |
| 75 |
"prefix": prefix, |
| 76 |
"suffix": suffix, |
| 77 |
"initial_value": initial_value, |
| 78 |
"little_endian": little_endian |
| 79 |
} |