Debian Codegraph @

lib/Crypto/Cipher/ChaCha20_Poly1305.py

raw symbols SCIP
1 # ===================================================================
2 #
3 # Copyright (c) 2018, Helder Eijs <[email protected]>
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
8 # are met:
9 #
10 # 1. Redistributions of source code must retain the above copyright
11 # notice, this list of conditions and the following disclaimer.
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in
14 # the documentation and/or other materials provided with the
15 # distribution.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21 # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 # POSSIBILITY OF SUCH DAMAGE.
29 # ===================================================================
30
31 from binascii import unhexlify
32
33 from Crypto.Cipher import ChaCha20
34 from Crypto.Cipher.ChaCha20 import _HChaCha20
35 from Crypto.Hash import Poly1305, BLAKE2s
36
37 from Crypto.Random import get_random_bytes
38
39 from Crypto.Util.number import long_to_bytes
40 from Crypto.Util.py3compat import _copy_bytes, bord
41 from Crypto.Util._raw_api import is_buffer
42
43
44 def _enum(**enums):
45 return type('Enum', (), enums)
46
47
48 _CipherStatus = _enum(PROCESSING_AUTH_DATA=1,
49 PROCESSING_CIPHERTEXT=2,
50 PROCESSING_DONE=3)
51
52
53 class ChaCha20Poly1305Cipher(object):
54 """ChaCha20-Poly1305 and XChaCha20-Poly1305 cipher object.
55 Do not create it directly. Use :py:func:`new` instead.
56
57 :var nonce: The nonce with length 8, 12 or 24 bytes
58 :vartype nonce: byte string
59 """
60
61 def __init__(self, key, nonce):
62 """Initialize a ChaCha20-Poly1305 AEAD cipher object
63
64 See also `new()` at the module level."""
65
66 self._next = ("update", "encrypt", "decrypt", "digest",
67 "verify")
68
69 self._authenticator = Poly1305.new(key=key, nonce=nonce, cipher=ChaCha20)
70
71 self._cipher = ChaCha20.new(key=key, nonce=nonce)
72 self._cipher.seek(64) # Block counter starts at 1
73
74 self._len_aad = 0
75 self._len_ct = 0
76 self._mac_tag = None
77 self._status = _CipherStatus.PROCESSING_AUTH_DATA
78
79 def update(self, data):
80 """Protect the associated data.
81
82 Associated data (also known as *additional authenticated data* - AAD)
83 is the piece of the message that must stay in the clear, while
84 still allowing the receiver to verify its integrity.
85 An example is packet headers.
86
87 The associated data (possibly split into multiple segments) is
88 fed into :meth:`update` before any call to :meth:`decrypt` or :meth:`encrypt`.
89 If there is no associated data, :meth:`update` is not called.
90
91 :param bytes/bytearray/memoryview assoc_data:
92 A piece of associated data. There are no restrictions on its size.
93 """
94
95 if "update" not in self._next:
96 raise TypeError("update() method cannot be called")
97
98 self._len_aad += len(data)
99 self._authenticator.update(data)
100
101 def _pad_aad(self):
102
103 assert(self._status == _CipherStatus.PROCESSING_AUTH_DATA)
104 if self._len_aad & 0x0F:
105 self._authenticator.update(b'\x00' * (16 - (self._len_aad & 0x0F)))
106 self._status = _CipherStatus.PROCESSING_CIPHERTEXT
107
108 def encrypt(self, plaintext, output=None):
109 """Encrypt a piece of data.
110
111 Args:
112 plaintext(bytes/bytearray/memoryview): The data to encrypt, of any size.
113 Keyword Args:
114 output(bytes/bytearray/memoryview): The location where the ciphertext
115 is written to. If ``None``, the ciphertext is returned.
116 Returns:
117 If ``output`` is ``None``, the ciphertext is returned as ``bytes``.
118 Otherwise, ``None``.
119 """
120
121 if "encrypt" not in self._next:
122 raise TypeError("encrypt() method cannot be called")
123
124 if self._status == _CipherStatus.PROCESSING_AUTH_DATA:
125 self._pad_aad()
126
127 self._next = ("encrypt", "digest")
128
129 result = self._cipher.encrypt(plaintext, output=output)
130 self._len_ct += len(plaintext)
131 if output is None:
132 self._authenticator.update(result)
133 else:
134 self._authenticator.update(output)
135 return result
136
137 def decrypt(self, ciphertext, output=None):
138 """Decrypt a piece of data.
139
140 Args:
141 ciphertext(bytes/bytearray/memoryview): The data to decrypt, of any size.
142 Keyword Args:
143 output(bytes/bytearray/memoryview): The location where the plaintext
144 is written to. If ``None``, the plaintext is returned.
145 Returns:
146 If ``output`` is ``None``, the plaintext is returned as ``bytes``.
147 Otherwise, ``None``.
148 """
149
150 if "decrypt" not in self._next:
151 raise TypeError("decrypt() method cannot be called")
152
153 if self._status == _CipherStatus.PROCESSING_AUTH_DATA:
154 self._pad_aad()
155
156 self._next = ("decrypt", "verify")
157
158 self._len_ct += len(ciphertext)
159 self._authenticator.update(ciphertext)
160 return self._cipher.decrypt(ciphertext, output=output)
161
162 def _compute_mac(self):
163 """Finalize the cipher (if not done already) and return the MAC."""
164
165 if self._mac_tag:
166 assert(self._status == _CipherStatus.PROCESSING_DONE)
167 return self._mac_tag
168
169 assert(self._status != _CipherStatus.PROCESSING_DONE)
170
171 if self._status == _CipherStatus.PROCESSING_AUTH_DATA:
172 self._pad_aad()
173
174 if self._len_ct & 0x0F:
175 self._authenticator.update(b'\x00' * (16 - (self._len_ct & 0x0F)))
176
177 self._status = _CipherStatus.PROCESSING_DONE
178
179 self._authenticator.update(long_to_bytes(self._len_aad, 8)[::-1])
180 self._authenticator.update(long_to_bytes(self._len_ct, 8)[::-1])
181 self._mac_tag = self._authenticator.digest()
182 return self._mac_tag
183
184 def digest(self):
185 """Compute the *binary* authentication tag (MAC).
186
187 :Return: the MAC tag, as 16 ``bytes``.
188 """
189
190 if "digest" not in self._next:
191 raise TypeError("digest() method cannot be called")
192 self._next = ("digest",)
193
194 return self._compute_mac()
195
196 def hexdigest(self):
197 """Compute the *printable* authentication tag (MAC).
198
199 This method is like :meth:`digest`.
200
201 :Return: the MAC tag, as a hexadecimal string.
202 """
203 return "".join(["%02x" % bord(x) for x in self.digest()])
204
205 def verify(self, received_mac_tag):
206 """Validate the *binary* authentication tag (MAC).
207
208 The receiver invokes this method at the very end, to
209 check if the associated data (if any) and the decrypted
210 messages are valid.
211
212 :param bytes/bytearray/memoryview received_mac_tag:
213 This is the 16-byte *binary* MAC, as received from the sender.
214 :Raises ValueError:
215 if the MAC does not match. The message has been tampered with
216 or the key is incorrect.
217 """
218
219 if "verify" not in self._next:
220 raise TypeError("verify() cannot be called"
221 " when encrypting a message")
222 self._next = ("verify",)
223
224 secret = get_random_bytes(16)
225
226 self._compute_mac()
227
228 mac1 = BLAKE2s.new(digest_bits=160, key=secret,
229 data=self._mac_tag)
230 mac2 = BLAKE2s.new(digest_bits=160, key=secret,
231 data=received_mac_tag)
232
233 if mac1.digest() != mac2.digest():
234 raise ValueError("MAC check failed")
235
236 def hexverify(self, hex_mac_tag):
237 """Validate the *printable* authentication tag (MAC).
238
239 This method is like :meth:`verify`.
240
241 :param string hex_mac_tag:
242 This is the *printable* MAC.
243 :Raises ValueError:
244 if the MAC does not match. The message has been tampered with
245 or the key is incorrect.
246 """
247
248 self.verify(unhexlify(hex_mac_tag))
249
250 def encrypt_and_digest(self, plaintext):
251 """Perform :meth:`encrypt` and :meth:`digest` in one step.
252
253 :param plaintext: The data to encrypt, of any size.
254 :type plaintext: bytes/bytearray/memoryview
255 :return: a tuple with two ``bytes`` objects:
256
257 - the ciphertext, of equal length as the plaintext
258 - the 16-byte MAC tag
259 """
260
261 return self.encrypt(plaintext), self.digest()
262
263 def decrypt_and_verify(self, ciphertext, received_mac_tag):
264 """Perform :meth:`decrypt` and :meth:`verify` in one step.
265
266 :param ciphertext: The piece of data to decrypt.
267 :type ciphertext: bytes/bytearray/memoryview
268 :param bytes received_mac_tag:
269 This is the 16-byte *binary* MAC, as received from the sender.
270 :return: the decrypted data (as ``bytes``)
271 :raises ValueError:
272 if the MAC does not match. The message has been tampered with
273 or the key is incorrect.
274 """
275
276 plaintext = self.decrypt(ciphertext)
277 self.verify(received_mac_tag)
278 return plaintext
279
280
281 def new(**kwargs):
282 """Create a new ChaCha20-Poly1305 or XChaCha20-Poly1305 AEAD cipher.
283
284 :keyword key: The secret key to use. It must be 32 bytes long.
285 :type key: byte string
286
287 :keyword nonce:
288 A value that must never be reused for any other encryption
289 done with this key.
290
291 For ChaCha20-Poly1305, it must be 8 or 12 bytes long.
292
293 For XChaCha20-Poly1305, it must be 24 bytes long.
294
295 If not provided, 12 ``bytes`` will be generated randomly
296 (you can find them back in the ``nonce`` attribute).
297 :type nonce: bytes, bytearray, memoryview
298
299 :Return: a :class:`Crypto.Cipher.ChaCha20.ChaCha20Poly1305Cipher` object
300 """
301
302 try:
303 key = kwargs.pop("key")
304 except KeyError as e:
305 raise TypeError("Missing parameter %s" % e)
306
307 self._len_ct += len(plaintext)
308
309 if len(key) != 32:
310 raise ValueError("Key must be 32 bytes long")
311
312 nonce = kwargs.pop("nonce", None)
313 if nonce is None:
314 nonce = get_random_bytes(12)
315
316 if len(nonce) in (8, 12):
317 chacha20_poly1305_nonce = nonce
318 elif len(nonce) == 24:
319 key = _HChaCha20(key, nonce[:16])
320 chacha20_poly1305_nonce = b'\x00\x00\x00\x00' + nonce[16:]
321 else:
322 raise ValueError("Nonce must be 8, 12 or 24 bytes long")
323
324 if not is_buffer(nonce):
325 raise TypeError("nonce must be bytes, bytearray or memoryview")
326
327 if kwargs:
328 raise TypeError("Unknown parameters: " + str(kwargs))
329
330 cipher = ChaCha20Poly1305Cipher(key, chacha20_poly1305_nonce)
331 cipher.nonce = _copy_bytes(None, None, nonce)
332 return cipher
333
334
335 # Size of a key (in bytes)
336 key_size = 32