| 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 |
from Crypto.Random import get_random_bytes |
| 32 |
|
| 33 |
from Crypto.Util.py3compat import _copy_bytes |
| 34 |
from Crypto.Util._raw_api import (load_pycryptodome_raw_lib, |
| 35 |
create_string_buffer, |
| 36 |
get_raw_buffer, VoidPointer, |
| 37 |
SmartPointer, c_size_t, |
| 38 |
c_uint8_ptr, c_ulong, |
| 39 |
is_writeable_buffer) |
| 40 |
|
| 41 |
_raw_chacha20_lib = load_pycryptodome_raw_lib("Crypto.Cipher._chacha20", |
| 42 |
""" |
| 43 |
int chacha20_init(void **pState, |
| 44 |
const uint8_t *key, |
| 45 |
size_t keySize, |
| 46 |
const uint8_t *nonce, |
| 47 |
size_t nonceSize); |
| 48 |
|
| 49 |
int chacha20_destroy(void *state); |
| 50 |
|
| 51 |
int chacha20_encrypt(void *state, |
| 52 |
const uint8_t in[], |
| 53 |
uint8_t out[], |
| 54 |
size_t len); |
| 55 |
|
| 56 |
int chacha20_seek(void *state, |
| 57 |
unsigned long block_high, |
| 58 |
unsigned long block_low, |
| 59 |
unsigned offset); |
| 60 |
int hchacha20( const uint8_t key[32], |
| 61 |
const uint8_t nonce16[16], |
| 62 |
uint8_t subkey[32]); |
| 63 |
""") |
| 64 |
|
| 65 |
|
| 66 |
def _HChaCha20(key, nonce): |
| 67 |
|
| 68 |
assert(len(key) == 32) |
| 69 |
assert(len(nonce) == 16) |
| 70 |
|
| 71 |
subkey = bytearray(32) |
| 72 |
result = _raw_chacha20_lib.hchacha20( |
| 73 |
c_uint8_ptr(key), |
| 74 |
c_uint8_ptr(nonce), |
| 75 |
c_uint8_ptr(subkey)) |
| 76 |
if result: |
| 77 |
raise ValueError("Error %d when deriving subkey with HChaCha20" % result) |
| 78 |
|
| 79 |
return subkey |
| 80 |
|
| 81 |
|
| 82 |
class ChaCha20Cipher(object): |
| 83 |
"""ChaCha20 (or XChaCha20) cipher object. |
| 84 |
Do not create it directly. Use :py:func:`new` instead. |
| 85 |
|
| 86 |
:var nonce: The nonce with length 8, 12 or 24 bytes |
| 87 |
:vartype nonce: bytes |
| 88 |
""" |
| 89 |
|
| 90 |
block_size = 1 |
| 91 |
|
| 92 |
def __init__(self, key, nonce): |
| 93 |
"""Initialize a ChaCha20/XChaCha20 cipher object |
| 94 |
|
| 95 |
See also `new()` at the module level.""" |
| 96 |
|
| 97 |
self.nonce = _copy_bytes(None, None, nonce) |
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
if len(nonce) == 24: |
| 102 |
key = _HChaCha20(key, nonce[:16]) |
| 103 |
nonce = b'\x00' * 4 + nonce[16:] |
| 104 |
self._name = "XChaCha20" |
| 105 |
else: |
| 106 |
self._name = "ChaCha20" |
| 107 |
nonce = self.nonce |
| 108 |
|
| 109 |
self._next = ("encrypt", "decrypt") |
| 110 |
|
| 111 |
self._state = VoidPointer() |
| 112 |
result = _raw_chacha20_lib.chacha20_init( |
| 113 |
self._state.address_of(), |
| 114 |
c_uint8_ptr(key), |
| 115 |
c_size_t(len(key)), |
| 116 |
nonce, |
| 117 |
c_size_t(len(nonce))) |
| 118 |
if result: |
| 119 |
raise ValueError("Error %d instantiating a %s cipher" % (result, |
| 120 |
self._name)) |
| 121 |
self._state = SmartPointer(self._state.get(), |
| 122 |
_raw_chacha20_lib.chacha20_destroy) |
| 123 |
|
| 124 |
def encrypt(self, plaintext, output=None): |
| 125 |
"""Encrypt a piece of data. |
| 126 |
|
| 127 |
Args: |
| 128 |
plaintext(bytes/bytearray/memoryview): The data to encrypt, of any size. |
| 129 |
Keyword Args: |
| 130 |
output(bytes/bytearray/memoryview): The location where the ciphertext |
| 131 |
is written to. If ``None``, the ciphertext is returned. |
| 132 |
Returns: |
| 133 |
If ``output`` is ``None``, the ciphertext is returned as ``bytes``. |
| 134 |
Otherwise, ``None``. |
| 135 |
""" |
| 136 |
|
| 137 |
if "encrypt" not in self._next: |
| 138 |
raise TypeError("Cipher object can only be used for decryption") |
| 139 |
self._next = ("encrypt",) |
| 140 |
return self._encrypt(plaintext, output) |
| 141 |
|
| 142 |
def _encrypt(self, plaintext, output): |
| 143 |
"""Encrypt without FSM checks""" |
| 144 |
|
| 145 |
if output is None: |
| 146 |
ciphertext = create_string_buffer(len(plaintext)) |
| 147 |
else: |
| 148 |
ciphertext = output |
| 149 |
|
| 150 |
if not is_writeable_buffer(output): |
| 151 |
raise TypeError("output must be a bytearray or a writeable memoryview") |
| 152 |
|
| 153 |
if len(plaintext) != len(output): |
| 154 |
raise ValueError("output must have the same length as the input" |
| 155 |
" (%d bytes)" % len(plaintext)) |
| 156 |
|
| 157 |
result = _raw_chacha20_lib.chacha20_encrypt( |
| 158 |
self._state.get(), |
| 159 |
c_uint8_ptr(plaintext), |
| 160 |
c_uint8_ptr(ciphertext), |
| 161 |
c_size_t(len(plaintext))) |
| 162 |
if result: |
| 163 |
raise ValueError("Error %d while encrypting with %s" % (result, self._name)) |
| 164 |
|
| 165 |
if output is None: |
| 166 |
return get_raw_buffer(ciphertext) |
| 167 |
else: |
| 168 |
return None |
| 169 |
|
| 170 |
def decrypt(self, ciphertext, output=None): |
| 171 |
"""Decrypt a piece of data. |
| 172 |
|
| 173 |
Args: |
| 174 |
ciphertext(bytes/bytearray/memoryview): The data to decrypt, of any size. |
| 175 |
Keyword Args: |
| 176 |
output(bytes/bytearray/memoryview): The location where the plaintext |
| 177 |
is written to. If ``None``, the plaintext is returned. |
| 178 |
Returns: |
| 179 |
If ``output`` is ``None``, the plaintext is returned as ``bytes``. |
| 180 |
Otherwise, ``None``. |
| 181 |
""" |
| 182 |
|
| 183 |
if "decrypt" not in self._next: |
| 184 |
raise TypeError("Cipher object can only be used for encryption") |
| 185 |
self._next = ("decrypt",) |
| 186 |
|
| 187 |
try: |
| 188 |
return self._encrypt(ciphertext, output) |
| 189 |
except ValueError as e: |
| 190 |
raise ValueError(str(e).replace("enc", "dec")) |
| 191 |
|
| 192 |
def seek(self, position): |
| 193 |
"""Seek to a certain position in the key stream. |
| 194 |
|
| 195 |
Args: |
| 196 |
position (integer): |
| 197 |
The absolute position within the key stream, in bytes. |
| 198 |
""" |
| 199 |
|
| 200 |
position, offset = divmod(position, 64) |
| 201 |
block_low = position & 0xFFFFFFFF |
| 202 |
block_high = position >> 32 |
| 203 |
|
| 204 |
result = _raw_chacha20_lib.chacha20_seek( |
| 205 |
self._state.get(), |
| 206 |
c_ulong(block_high), |
| 207 |
c_ulong(block_low), |
| 208 |
offset |
| 209 |
) |
| 210 |
if result: |
| 211 |
raise ValueError("Error %d while seeking with %s" % (result, self._name)) |
| 212 |
|
| 213 |
|
| 214 |
def _derive_Poly1305_key_pair(key, nonce): |
| 215 |
"""Derive a tuple (r, s, nonce) for a Poly1305 MAC. |
| 216 |
|
| 217 |
If nonce is ``None``, a new 12-byte nonce is generated. |
| 218 |
""" |
| 219 |
|
| 220 |
if len(key) != 32: |
| 221 |
raise ValueError("Poly1305 with ChaCha20 requires a 32-byte key") |
| 222 |
|
| 223 |
if nonce is None: |
| 224 |
padded_nonce = nonce = get_random_bytes(12) |
| 225 |
elif len(nonce) == 8: |
| 226 |
|
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
padded_nonce = b'\x00\x00\x00\x00' + nonce |
| 234 |
elif len(nonce) == 12: |
| 235 |
padded_nonce = nonce |
| 236 |
else: |
| 237 |
raise ValueError("Poly1305 with ChaCha20 requires an 8- or 12-byte nonce") |
| 238 |
|
| 239 |
rs = new(key=key, nonce=padded_nonce).encrypt(b'\x00' * 32) |
| 240 |
return rs[:16], rs[16:], nonce |
| 241 |
|
| 242 |
|
| 243 |
def new(**kwargs): |
| 244 |
"""Create a new ChaCha20 or XChaCha20 cipher |
| 245 |
|
| 246 |
Keyword Args: |
| 247 |
key (bytes/bytearray/memoryview): The secret key to use. |
| 248 |
It must be 32 bytes long. |
| 249 |
nonce (bytes/bytearray/memoryview): A mandatory value that |
| 250 |
must never be reused for any other encryption |
| 251 |
done with this key. |
| 252 |
|
| 253 |
For ChaCha20, it must be 8 or 12 bytes long. |
| 254 |
|
| 255 |
For XChaCha20, it must be 24 bytes long. |
| 256 |
|
| 257 |
If not provided, 8 bytes will be randomly generated |
| 258 |
(you can find them back in the ``nonce`` attribute). |
| 259 |
|
| 260 |
:Return: a :class:`Crypto.Cipher.ChaCha20.ChaCha20Cipher` object |
| 261 |
""" |
| 262 |
|
| 263 |
try: |
| 264 |
key = kwargs.pop("key") |
| 265 |
except KeyError as e: |
| 266 |
raise TypeError("Missing parameter %s" % e) |
| 267 |
|
| 268 |
nonce = kwargs.pop("nonce", None) |
| 269 |
if nonce is None: |
| 270 |
nonce = get_random_bytes(8) |
| 271 |
|
| 272 |
if len(key) != 32: |
| 273 |
raise ValueError("ChaCha20/XChaCha20 key must be 32 bytes long") |
| 274 |
|
| 275 |
if len(nonce) not in (8, 12, 24): |
| 276 |
raise ValueError("Nonce must be 8/12 bytes(ChaCha20) or 24 bytes (XChaCha20)") |
| 277 |
|
| 278 |
if kwargs: |
| 279 |
raise TypeError("Unknown parameters: " + str(kwargs)) |
| 280 |
|
| 281 |
return ChaCha20Cipher(key, nonce) |
| 282 |
|
| 283 |
|
| 284 |
block_size = 1 |
| 285 |
|
| 286 |
|
| 287 |
key_size = 32 |