| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
""" |
| 24 |
Counter (CTR) mode. |
| 25 |
""" |
| 26 |
|
| 27 |
__all__ = ['CtrMode'] |
| 28 |
|
| 29 |
import struct |
| 30 |
|
| 31 |
from Crypto.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer, |
| 32 |
create_string_buffer, get_raw_buffer, |
| 33 |
SmartPointer, c_size_t, c_uint8_ptr, |
| 34 |
is_writeable_buffer) |
| 35 |
|
| 36 |
from Crypto.Random import get_random_bytes |
| 37 |
from Crypto.Util.py3compat import _copy_bytes, is_native_int |
| 38 |
from Crypto.Util.number import long_to_bytes |
| 39 |
|
| 40 |
raw_ctr_lib = load_pycryptodome_raw_lib("Crypto.Cipher._raw_ctr", """ |
| 41 |
int CTR_start_operation(void *cipher, |
| 42 |
uint8_t initialCounterBlock[], |
| 43 |
size_t initialCounterBlock_len, |
| 44 |
size_t prefix_len, |
| 45 |
unsigned counter_len, |
| 46 |
unsigned littleEndian, |
| 47 |
void **pResult); |
| 48 |
int CTR_encrypt(void *ctrState, |
| 49 |
const uint8_t *in, |
| 50 |
uint8_t *out, |
| 51 |
size_t data_len); |
| 52 |
int CTR_decrypt(void *ctrState, |
| 53 |
const uint8_t *in, |
| 54 |
uint8_t *out, |
| 55 |
size_t data_len); |
| 56 |
int CTR_stop_operation(void *ctrState);""" |
| 57 |
) |
| 58 |
|
| 59 |
|
| 60 |
class CtrMode(object): |
| 61 |
"""*CounTeR (CTR)* mode. |
| 62 |
|
| 63 |
This mode is very similar to ECB, in that |
| 64 |
encryption of one block is done independently of all other blocks. |
| 65 |
|
| 66 |
Unlike ECB, the block *position* contributes to the encryption |
| 67 |
and no information leaks about symbol frequency. |
| 68 |
|
| 69 |
Each message block is associated to a *counter* which |
| 70 |
must be unique across all messages that get encrypted |
| 71 |
with the same key (not just within the same message). |
| 72 |
The counter is as big as the block size. |
| 73 |
|
| 74 |
Counters can be generated in several ways. The most |
| 75 |
straightword one is to choose an *initial counter block* |
| 76 |
(which can be made public, similarly to the *IV* for the |
| 77 |
other modes) and increment its lowest **m** bits by one |
| 78 |
(modulo *2^m*) for each block. In most cases, **m** is |
| 79 |
chosen to be half the block size. |
| 80 |
|
| 81 |
See `NIST SP800-38A`_, Section 6.5 (for the mode) and |
| 82 |
Appendix B (for how to manage the *initial counter block*). |
| 83 |
|
| 84 |
.. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf |
| 85 |
|
| 86 |
:undocumented: __init__ |
| 87 |
""" |
| 88 |
|
| 89 |
def __init__(self, block_cipher, initial_counter_block, |
| 90 |
prefix_len, counter_len, little_endian): |
| 91 |
"""Create a new block cipher, configured in CTR mode. |
| 92 |
|
| 93 |
:Parameters: |
| 94 |
block_cipher : C pointer |
| 95 |
A smart pointer to the low-level block cipher instance. |
| 96 |
|
| 97 |
initial_counter_block : bytes/bytearray/memoryview |
| 98 |
The initial plaintext to use to generate the key stream. |
| 99 |
|
| 100 |
It is as large as the cipher block, and it embeds |
| 101 |
the initial value of the counter. |
| 102 |
|
| 103 |
This value must not be reused. |
| 104 |
It shall contain a nonce or a random component. |
| 105 |
Reusing the *initial counter block* for encryptions |
| 106 |
performed with the same key compromises confidentiality. |
| 107 |
|
| 108 |
prefix_len : integer |
| 109 |
The amount of bytes at the beginning of the counter block |
| 110 |
that never change. |
| 111 |
|
| 112 |
counter_len : integer |
| 113 |
The length in bytes of the counter embedded in the counter |
| 114 |
block. |
| 115 |
|
| 116 |
little_endian : boolean |
| 117 |
True if the counter in the counter block is an integer encoded |
| 118 |
in little endian mode. If False, it is big endian. |
| 119 |
""" |
| 120 |
|
| 121 |
if len(initial_counter_block) == prefix_len + counter_len: |
| 122 |
self.nonce = _copy_bytes(None, prefix_len, initial_counter_block) |
| 123 |
"""Nonce; not available if there is a fixed suffix""" |
| 124 |
|
| 125 |
self._state = VoidPointer() |
| 126 |
result = raw_ctr_lib.CTR_start_operation(block_cipher.get(), |
| 127 |
c_uint8_ptr(initial_counter_block), |
| 128 |
c_size_t(len(initial_counter_block)), |
| 129 |
c_size_t(prefix_len), |
| 130 |
counter_len, |
| 131 |
little_endian, |
| 132 |
self._state.address_of()) |
| 133 |
if result: |
| 134 |
raise ValueError("Error %X while instantiating the CTR mode" |
| 135 |
% result) |
| 136 |
|
| 137 |
|
| 138 |
|
| 139 |
self._state = SmartPointer(self._state.get(), |
| 140 |
raw_ctr_lib.CTR_stop_operation) |
| 141 |
|
| 142 |
|
| 143 |
|
| 144 |
block_cipher.release() |
| 145 |
|
| 146 |
self.block_size = len(initial_counter_block) |
| 147 |
"""The block size of the underlying cipher, in bytes.""" |
| 148 |
|
| 149 |
self._next = ["encrypt", "decrypt"] |
| 150 |
|
| 151 |
def encrypt(self, plaintext, output=None): |
| 152 |
"""Encrypt data with the key and the parameters set at initialization. |
| 153 |
|
| 154 |
A cipher object is stateful: once you have encrypted a message |
| 155 |
you cannot encrypt (or decrypt) another message using the same |
| 156 |
object. |
| 157 |
|
| 158 |
The data to encrypt can be broken up in two or |
| 159 |
more pieces and `encrypt` can be called multiple times. |
| 160 |
|
| 161 |
That is, the statement: |
| 162 |
|
| 163 |
>>> c.encrypt(a) + c.encrypt(b) |
| 164 |
|
| 165 |
is equivalent to: |
| 166 |
|
| 167 |
>>> c.encrypt(a+b) |
| 168 |
|
| 169 |
This function does not add any padding to the plaintext. |
| 170 |
|
| 171 |
:Parameters: |
| 172 |
plaintext : bytes/bytearray/memoryview |
| 173 |
The piece of data to encrypt. |
| 174 |
It can be of any length. |
| 175 |
:Keywords: |
| 176 |
output : bytearray/memoryview |
| 177 |
The location where the ciphertext must be written to. |
| 178 |
If ``None``, the ciphertext is returned. |
| 179 |
:Return: |
| 180 |
If ``output`` is ``None``, the ciphertext is returned as ``bytes``. |
| 181 |
Otherwise, ``None``. |
| 182 |
""" |
| 183 |
|
| 184 |
if "encrypt" not in self._next: |
| 185 |
raise TypeError("encrypt() cannot be called after decrypt()") |
| 186 |
self._next = ["encrypt"] |
| 187 |
|
| 188 |
if output is None: |
| 189 |
ciphertext = create_string_buffer(len(plaintext)) |
| 190 |
else: |
| 191 |
ciphertext = output |
| 192 |
|
| 193 |
if not is_writeable_buffer(output): |
| 194 |
raise TypeError("output must be a bytearray or a writeable memoryview") |
| 195 |
|
| 196 |
if len(plaintext) != len(output): |
| 197 |
raise ValueError("output must have the same length as the input" |
| 198 |
" (%d bytes)" % len(plaintext)) |
| 199 |
|
| 200 |
result = raw_ctr_lib.CTR_encrypt(self._state.get(), |
| 201 |
c_uint8_ptr(plaintext), |
| 202 |
c_uint8_ptr(ciphertext), |
| 203 |
c_size_t(len(plaintext))) |
| 204 |
if result: |
| 205 |
if result == 0x60002: |
| 206 |
raise OverflowError("The counter has wrapped around in" |
| 207 |
" CTR mode") |
| 208 |
raise ValueError("Error %X while encrypting in CTR mode" % result) |
| 209 |
|
| 210 |
if output is None: |
| 211 |
return get_raw_buffer(ciphertext) |
| 212 |
else: |
| 213 |
return None |
| 214 |
|
| 215 |
def decrypt(self, ciphertext, output=None): |
| 216 |
"""Decrypt data with the key and the parameters set at initialization. |
| 217 |
|
| 218 |
A cipher object is stateful: once you have decrypted a message |
| 219 |
you cannot decrypt (or encrypt) another message with the same |
| 220 |
object. |
| 221 |
|
| 222 |
The data to decrypt can be broken up in two or |
| 223 |
more pieces and `decrypt` can be called multiple times. |
| 224 |
|
| 225 |
That is, the statement: |
| 226 |
|
| 227 |
>>> c.decrypt(a) + c.decrypt(b) |
| 228 |
|
| 229 |
is equivalent to: |
| 230 |
|
| 231 |
>>> c.decrypt(a+b) |
| 232 |
|
| 233 |
This function does not remove any padding from the plaintext. |
| 234 |
|
| 235 |
:Parameters: |
| 236 |
ciphertext : bytes/bytearray/memoryview |
| 237 |
The piece of data to decrypt. |
| 238 |
It can be of any length. |
| 239 |
:Keywords: |
| 240 |
output : bytearray/memoryview |
| 241 |
The location where the plaintext must be written to. |
| 242 |
If ``None``, the plaintext is returned. |
| 243 |
:Return: |
| 244 |
If ``output`` is ``None``, the plaintext is returned as ``bytes``. |
| 245 |
Otherwise, ``None``. |
| 246 |
""" |
| 247 |
|
| 248 |
if "decrypt" not in self._next: |
| 249 |
raise TypeError("decrypt() cannot be called after encrypt()") |
| 250 |
self._next = ["decrypt"] |
| 251 |
|
| 252 |
if output is None: |
| 253 |
plaintext = create_string_buffer(len(ciphertext)) |
| 254 |
else: |
| 255 |
plaintext = output |
| 256 |
|
| 257 |
if not is_writeable_buffer(output): |
| 258 |
raise TypeError("output must be a bytearray or a writeable memoryview") |
| 259 |
|
| 260 |
if len(ciphertext) != len(output): |
| 261 |
raise ValueError("output must have the same length as the input" |
| 262 |
" (%d bytes)" % len(plaintext)) |
| 263 |
|
| 264 |
result = raw_ctr_lib.CTR_decrypt(self._state.get(), |
| 265 |
c_uint8_ptr(ciphertext), |
| 266 |
c_uint8_ptr(plaintext), |
| 267 |
c_size_t(len(ciphertext))) |
| 268 |
if result: |
| 269 |
if result == 0x60002: |
| 270 |
raise OverflowError("The counter has wrapped around in" |
| 271 |
" CTR mode") |
| 272 |
raise ValueError("Error %X while decrypting in CTR mode" % result) |
| 273 |
|
| 274 |
if output is None: |
| 275 |
return get_raw_buffer(plaintext) |
| 276 |
else: |
| 277 |
return None |
| 278 |
|
| 279 |
|
| 280 |
def _create_ctr_cipher(factory, **kwargs): |
| 281 |
"""Instantiate a cipher object that performs CTR encryption/decryption. |
| 282 |
|
| 283 |
:Parameters: |
| 284 |
factory : module |
| 285 |
The underlying block cipher, a module from ``Crypto.Cipher``. |
| 286 |
|
| 287 |
:Keywords: |
| 288 |
nonce : bytes/bytearray/memoryview |
| 289 |
The fixed part at the beginning of the counter block - the rest is |
| 290 |
the counter number that gets increased when processing the next block. |
| 291 |
The nonce must be such that no two messages are encrypted under the |
| 292 |
same key and the same nonce. |
| 293 |
|
| 294 |
The nonce must be shorter than the block size (it can have |
| 295 |
zero length; the counter is then as long as the block). |
| 296 |
|
| 297 |
If this parameter is not present, a random nonce will be created with |
| 298 |
length equal to half the block size. No random nonce shorter than |
| 299 |
64 bits will be created though - you must really think through all |
| 300 |
security consequences of using such a short block size. |
| 301 |
|
| 302 |
initial_value : posive integer or bytes/bytearray/memoryview |
| 303 |
The initial value for the counter. If not present, the cipher will |
| 304 |
start counting from 0. The value is incremented by one for each block. |
| 305 |
The counter number is encoded in big endian mode. |
| 306 |
|
| 307 |
counter : object |
| 308 |
Instance of ``Crypto.Util.Counter``, which allows full customization |
| 309 |
of the counter block. This parameter is incompatible to both ``nonce`` |
| 310 |
and ``initial_value``. |
| 311 |
|
| 312 |
Any other keyword will be passed to the underlying block cipher. |
| 313 |
See the relevant documentation for details (at least ``key`` will need |
| 314 |
to be present). |
| 315 |
""" |
| 316 |
|
| 317 |
cipher_state = factory._create_base_cipher(kwargs) |
| 318 |
|
| 319 |
counter = kwargs.pop("counter", None) |
| 320 |
nonce = kwargs.pop("nonce", None) |
| 321 |
initial_value = kwargs.pop("initial_value", None) |
| 322 |
if kwargs: |
| 323 |
raise TypeError("Invalid parameters for CTR mode: %s" % str(kwargs)) |
| 324 |
|
| 325 |
if counter is not None and (nonce, initial_value) != (None, None): |
| 326 |
raise TypeError("'counter' and 'nonce'/'initial_value'" |
| 327 |
" are mutually exclusive") |
| 328 |
|
| 329 |
if counter is None: |
| 330 |
|
| 331 |
if nonce is None: |
| 332 |
if factory.block_size < 16: |
| 333 |
raise TypeError("Impossible to create a safe nonce for short" |
| 334 |
" block sizes") |
| 335 |
nonce = get_random_bytes(factory.block_size // 2) |
| 336 |
else: |
| 337 |
if len(nonce) >= factory.block_size: |
| 338 |
raise ValueError("Nonce is too long") |
| 339 |
|
| 340 |
|
| 341 |
counter_len = factory.block_size - len(nonce) |
| 342 |
|
| 343 |
if initial_value is None: |
| 344 |
initial_value = 0 |
| 345 |
|
| 346 |
if is_native_int(initial_value): |
| 347 |
if (1 << (counter_len * 8)) - 1 < initial_value: |
| 348 |
raise ValueError("Initial counter value is too large") |
| 349 |
initial_counter_block = nonce + long_to_bytes(initial_value, counter_len) |
| 350 |
else: |
| 351 |
if len(initial_value) != counter_len: |
| 352 |
raise ValueError("Incorrect length for counter byte string (%d bytes, expected %d)" % |
| 353 |
(len(initial_value), counter_len)) |
| 354 |
initial_counter_block = nonce + initial_value |
| 355 |
|
| 356 |
return CtrMode(cipher_state, |
| 357 |
initial_counter_block, |
| 358 |
len(nonce), |
| 359 |
counter_len, |
| 360 |
False) |
| 361 |
|
| 362 |
|
| 363 |
|
| 364 |
|
| 365 |
|
| 366 |
_counter = dict(counter) |
| 367 |
try: |
| 368 |
counter_len = _counter.pop("counter_len") |
| 369 |
prefix = _counter.pop("prefix") |
| 370 |
suffix = _counter.pop("suffix") |
| 371 |
initial_value = _counter.pop("initial_value") |
| 372 |
little_endian = _counter.pop("little_endian") |
| 373 |
except KeyError: |
| 374 |
raise TypeError("Incorrect counter object" |
| 375 |
" (use Crypto.Util.Counter.new)") |
| 376 |
|
| 377 |
|
| 378 |
words = [] |
| 379 |
while initial_value > 0: |
| 380 |
words.append(struct.pack('B', initial_value & 255)) |
| 381 |
initial_value >>= 8 |
| 382 |
words += [b'\x00'] * max(0, counter_len - len(words)) |
| 383 |
if not little_endian: |
| 384 |
words.reverse() |
| 385 |
initial_counter_block = prefix + b"".join(words) + suffix |
| 386 |
|
| 387 |
if len(initial_counter_block) != factory.block_size: |
| 388 |
raise ValueError("Size of the counter block (%d bytes) must match" |
| 389 |
" block size (%d)" % (len(initial_counter_block), |
| 390 |
factory.block_size)) |
| 391 |
|
| 392 |
return CtrMode(cipher_state, initial_counter_block, |
| 393 |
len(prefix), counter_len, little_endian) |