| 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 Feedback (CFB) mode. |
| 25 |
""" |
| 26 |
|
| 27 |
__all__ = ['CfbMode'] |
| 28 |
|
| 29 |
from Crypto.Util.py3compat import _copy_bytes |
| 30 |
from Crypto.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer, |
| 31 |
create_string_buffer, get_raw_buffer, |
| 32 |
SmartPointer, c_size_t, c_uint8_ptr, |
| 33 |
is_writeable_buffer) |
| 34 |
|
| 35 |
from Crypto.Random import get_random_bytes |
| 36 |
|
| 37 |
raw_cfb_lib = load_pycryptodome_raw_lib("Crypto.Cipher._raw_cfb",""" |
| 38 |
int CFB_start_operation(void *cipher, |
| 39 |
const uint8_t iv[], |
| 40 |
size_t iv_len, |
| 41 |
size_t segment_len, /* In bytes */ |
| 42 |
void **pResult); |
| 43 |
int CFB_encrypt(void *cfbState, |
| 44 |
const uint8_t *in, |
| 45 |
uint8_t *out, |
| 46 |
size_t data_len); |
| 47 |
int CFB_decrypt(void *cfbState, |
| 48 |
const uint8_t *in, |
| 49 |
uint8_t *out, |
| 50 |
size_t data_len); |
| 51 |
int CFB_stop_operation(void *state);""" |
| 52 |
) |
| 53 |
|
| 54 |
|
| 55 |
class CfbMode(object): |
| 56 |
"""*Cipher FeedBack (CFB)*. |
| 57 |
|
| 58 |
This mode is similar to CFB, but it transforms |
| 59 |
the underlying block cipher into a stream cipher. |
| 60 |
|
| 61 |
Plaintext and ciphertext are processed in *segments* |
| 62 |
of **s** bits. The mode is therefore sometimes |
| 63 |
labelled **s**-bit CFB. |
| 64 |
|
| 65 |
An Initialization Vector (*IV*) is required. |
| 66 |
|
| 67 |
See `NIST SP800-38A`_ , Section 6.3. |
| 68 |
|
| 69 |
.. _`NIST SP800-38A` : http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf |
| 70 |
|
| 71 |
:undocumented: __init__ |
| 72 |
""" |
| 73 |
|
| 74 |
def __init__(self, block_cipher, iv, segment_size): |
| 75 |
"""Create a new block cipher, configured in CFB mode. |
| 76 |
|
| 77 |
:Parameters: |
| 78 |
block_cipher : C pointer |
| 79 |
A smart pointer to the low-level block cipher instance. |
| 80 |
|
| 81 |
iv : bytes/bytearray/memoryview |
| 82 |
The initialization vector to use for encryption or decryption. |
| 83 |
It is as long as the cipher block. |
| 84 |
|
| 85 |
**The IV must be unpredictable**. Ideally it is picked randomly. |
| 86 |
|
| 87 |
Reusing the *IV* for encryptions performed with the same key |
| 88 |
compromises confidentiality. |
| 89 |
|
| 90 |
segment_size : integer |
| 91 |
The number of bytes the plaintext and ciphertext are segmented in. |
| 92 |
""" |
| 93 |
|
| 94 |
self._state = VoidPointer() |
| 95 |
result = raw_cfb_lib.CFB_start_operation(block_cipher.get(), |
| 96 |
c_uint8_ptr(iv), |
| 97 |
c_size_t(len(iv)), |
| 98 |
c_size_t(segment_size), |
| 99 |
self._state.address_of()) |
| 100 |
if result: |
| 101 |
raise ValueError("Error %d while instantiating the CFB mode" % result) |
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
self._state = SmartPointer(self._state.get(), |
| 106 |
raw_cfb_lib.CFB_stop_operation) |
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
block_cipher.release() |
| 111 |
|
| 112 |
self.block_size = len(iv) |
| 113 |
"""The block size of the underlying cipher, in bytes.""" |
| 114 |
|
| 115 |
self.iv = _copy_bytes(None, None, iv) |
| 116 |
"""The Initialization Vector originally used to create the object. |
| 117 |
The value does not change.""" |
| 118 |
|
| 119 |
self.IV = self.iv |
| 120 |
"""Alias for `iv`""" |
| 121 |
|
| 122 |
self._next = ["encrypt", "decrypt"] |
| 123 |
|
| 124 |
def encrypt(self, plaintext, output=None): |
| 125 |
"""Encrypt data with the key and the parameters set at initialization. |
| 126 |
|
| 127 |
A cipher object is stateful: once you have encrypted a message |
| 128 |
you cannot encrypt (or decrypt) another message using the same |
| 129 |
object. |
| 130 |
|
| 131 |
The data to encrypt can be broken up in two or |
| 132 |
more pieces and `encrypt` can be called multiple times. |
| 133 |
|
| 134 |
That is, the statement: |
| 135 |
|
| 136 |
>>> c.encrypt(a) + c.encrypt(b) |
| 137 |
|
| 138 |
is equivalent to: |
| 139 |
|
| 140 |
>>> c.encrypt(a+b) |
| 141 |
|
| 142 |
This function does not add any padding to the plaintext. |
| 143 |
|
| 144 |
:Parameters: |
| 145 |
plaintext : bytes/bytearray/memoryview |
| 146 |
The piece of data to encrypt. |
| 147 |
It can be of any length. |
| 148 |
:Keywords: |
| 149 |
output : bytearray/memoryview |
| 150 |
The location where the ciphertext must be written to. |
| 151 |
If ``None``, the ciphertext is returned. |
| 152 |
:Return: |
| 153 |
If ``output`` is ``None``, the ciphertext is returned as ``bytes``. |
| 154 |
Otherwise, ``None``. |
| 155 |
""" |
| 156 |
|
| 157 |
if "encrypt" not in self._next: |
| 158 |
raise TypeError("encrypt() cannot be called after decrypt()") |
| 159 |
self._next = ["encrypt"] |
| 160 |
|
| 161 |
if output is None: |
| 162 |
ciphertext = create_string_buffer(len(plaintext)) |
| 163 |
else: |
| 164 |
ciphertext = output |
| 165 |
|
| 166 |
if not is_writeable_buffer(output): |
| 167 |
raise TypeError("output must be a bytearray or a writeable memoryview") |
| 168 |
|
| 169 |
if len(plaintext) != len(output): |
| 170 |
raise ValueError("output must have the same length as the input" |
| 171 |
" (%d bytes)" % len(plaintext)) |
| 172 |
|
| 173 |
result = raw_cfb_lib.CFB_encrypt(self._state.get(), |
| 174 |
c_uint8_ptr(plaintext), |
| 175 |
c_uint8_ptr(ciphertext), |
| 176 |
c_size_t(len(plaintext))) |
| 177 |
if result: |
| 178 |
raise ValueError("Error %d while encrypting in CFB mode" % result) |
| 179 |
|
| 180 |
if output is None: |
| 181 |
return get_raw_buffer(ciphertext) |
| 182 |
else: |
| 183 |
return None |
| 184 |
|
| 185 |
def decrypt(self, ciphertext, output=None): |
| 186 |
"""Decrypt data with the key and the parameters set at initialization. |
| 187 |
|
| 188 |
A cipher object is stateful: once you have decrypted a message |
| 189 |
you cannot decrypt (or encrypt) another message with the same |
| 190 |
object. |
| 191 |
|
| 192 |
The data to decrypt can be broken up in two or |
| 193 |
more pieces and `decrypt` can be called multiple times. |
| 194 |
|
| 195 |
That is, the statement: |
| 196 |
|
| 197 |
>>> c.decrypt(a) + c.decrypt(b) |
| 198 |
|
| 199 |
is equivalent to: |
| 200 |
|
| 201 |
>>> c.decrypt(a+b) |
| 202 |
|
| 203 |
This function does not remove any padding from the plaintext. |
| 204 |
|
| 205 |
:Parameters: |
| 206 |
ciphertext : bytes/bytearray/memoryview |
| 207 |
The piece of data to decrypt. |
| 208 |
It can be of any length. |
| 209 |
:Keywords: |
| 210 |
output : bytearray/memoryview |
| 211 |
The location where the plaintext must be written to. |
| 212 |
If ``None``, the plaintext is returned. |
| 213 |
:Return: |
| 214 |
If ``output`` is ``None``, the plaintext is returned as ``bytes``. |
| 215 |
Otherwise, ``None``. |
| 216 |
""" |
| 217 |
|
| 218 |
if "decrypt" not in self._next: |
| 219 |
raise TypeError("decrypt() cannot be called after encrypt()") |
| 220 |
self._next = ["decrypt"] |
| 221 |
|
| 222 |
if output is None: |
| 223 |
plaintext = create_string_buffer(len(ciphertext)) |
| 224 |
else: |
| 225 |
plaintext = output |
| 226 |
|
| 227 |
if not is_writeable_buffer(output): |
| 228 |
raise TypeError("output must be a bytearray or a writeable memoryview") |
| 229 |
|
| 230 |
if len(ciphertext) != len(output): |
| 231 |
raise ValueError("output must have the same length as the input" |
| 232 |
" (%d bytes)" % len(plaintext)) |
| 233 |
|
| 234 |
result = raw_cfb_lib.CFB_decrypt(self._state.get(), |
| 235 |
c_uint8_ptr(ciphertext), |
| 236 |
c_uint8_ptr(plaintext), |
| 237 |
c_size_t(len(ciphertext))) |
| 238 |
if result: |
| 239 |
raise ValueError("Error %d while decrypting in CFB mode" % result) |
| 240 |
|
| 241 |
if output is None: |
| 242 |
return get_raw_buffer(plaintext) |
| 243 |
else: |
| 244 |
return None |
| 245 |
|
| 246 |
|
| 247 |
def _create_cfb_cipher(factory, **kwargs): |
| 248 |
"""Instantiate a cipher object that performs CFB encryption/decryption. |
| 249 |
|
| 250 |
:Parameters: |
| 251 |
factory : module |
| 252 |
The underlying block cipher, a module from ``Crypto.Cipher``. |
| 253 |
|
| 254 |
:Keywords: |
| 255 |
iv : bytes/bytearray/memoryview |
| 256 |
The IV to use for CFB. |
| 257 |
|
| 258 |
IV : bytes/bytearray/memoryview |
| 259 |
Alias for ``iv``. |
| 260 |
|
| 261 |
segment_size : integer |
| 262 |
The number of bit the plaintext and ciphertext are segmented in. |
| 263 |
If not present, the default is 8. |
| 264 |
|
| 265 |
Any other keyword will be passed to the underlying block cipher. |
| 266 |
See the relevant documentation for details (at least ``key`` will need |
| 267 |
to be present). |
| 268 |
""" |
| 269 |
|
| 270 |
cipher_state = factory._create_base_cipher(kwargs) |
| 271 |
|
| 272 |
iv = kwargs.pop("IV", None) |
| 273 |
IV = kwargs.pop("iv", None) |
| 274 |
|
| 275 |
if (None, None) == (iv, IV): |
| 276 |
iv = get_random_bytes(factory.block_size) |
| 277 |
if iv is not None: |
| 278 |
if IV is not None: |
| 279 |
raise TypeError("You must either use 'iv' or 'IV', not both") |
| 280 |
else: |
| 281 |
iv = IV |
| 282 |
|
| 283 |
if len(iv) != factory.block_size: |
| 284 |
raise ValueError("Incorrect IV length (it must be %d bytes long)" % |
| 285 |
factory.block_size) |
| 286 |
|
| 287 |
segment_size_bytes, rem = divmod(kwargs.pop("segment_size", 8), 8) |
| 288 |
if segment_size_bytes == 0 or rem != 0: |
| 289 |
raise ValueError("'segment_size' must be positive and multiple of 8 bits") |
| 290 |
|
| 291 |
if kwargs: |
| 292 |
raise TypeError("Unknown parameters for CFB: %s" % str(kwargs)) |
| 293 |
return CfbMode(cipher_state, iv, segment_size_bytes) |