Debian Codegraph @

src/nacl/secret.py

raw
1 # Copyright 2013 Donald Stufft and individual contributors
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 from typing import ClassVar, Optional
15
16 import nacl.bindings
17 from nacl import encoding
18 from nacl import exceptions as exc
19 from nacl.utils import EncryptedMessage, StringFixer, random
20
21
22 class SecretBox(encoding.Encodable, StringFixer):
23 """
24 The SecretBox class encrypts and decrypts messages using the given secret
25 key.
26
27 The ciphertexts generated by :class:`~nacl.secret.Secretbox` include a 16
28 byte authenticator which is checked as part of the decryption. An invalid
29 authenticator will cause the decrypt function to raise an exception. The
30 authenticator is not a signature. Once you've decrypted the message you've
31 demonstrated the ability to create arbitrary valid message, so messages you
32 send are repudiable. For non-repudiable messages, sign them after
33 encryption.
34
35 Encryption is done using `XSalsa20-Poly1305`_, and there are no practical
36 limits on the number or size of messages (up to 2⁶⁴ messages, each up to 2⁶⁴
37 bytes).
38
39 .. _XSalsa20-Poly1305: https://doc.libsodium.org/secret-key_cryptography/secretbox#algorithm-details
40
41 :param key: The secret key used to encrypt and decrypt messages
42 :param encoder: The encoder class used to decode the given key
43
44 :cvar KEY_SIZE: The size that the key is required to be.
45 :cvar NONCE_SIZE: The size that the nonce is required to be.
46 :cvar MACBYTES: The size of the authentication MAC tag in bytes.
47 :cvar MESSAGEBYTES_MAX: The maximum size of a message which can be
48 safely encrypted with a single key/nonce
49 pair.
50 """
51
52 KEY_SIZE: ClassVar[int] = nacl.bindings.crypto_secretbox_KEYBYTES
53 NONCE_SIZE: ClassVar[int] = nacl.bindings.crypto_secretbox_NONCEBYTES
54 MACBYTES: ClassVar[int] = nacl.bindings.crypto_secretbox_MACBYTES
55 MESSAGEBYTES_MAX: ClassVar[int] = (
56 nacl.bindings.crypto_secretbox_MESSAGEBYTES_MAX
57 )
58
59 def __init__(
60 self, key: bytes, encoder: encoding.Encoder = encoding.RawEncoder
61 ):
62 key = encoder.decode(key)
63 if not isinstance(key, bytes):
64 raise exc.TypeError("SecretBox must be created from 32 bytes")
65
66 if len(key) != self.KEY_SIZE:
67 raise exc.ValueError(
68 "The key must be exactly %s bytes long" % self.KEY_SIZE,
69 )
70
71 self._key = key
72
73 def __bytes__(self) -> bytes:
74 return self._key
75
76 def encrypt(
77 self,
78 plaintext: bytes,
79 nonce: Optional[bytes] = None,
80 encoder: encoding.Encoder = encoding.RawEncoder,
81 ) -> EncryptedMessage:
82 """
83 Encrypts the plaintext message using the given `nonce` (or generates
84 one randomly if omitted) and returns the ciphertext encoded with the
85 encoder.
86
87 .. warning:: It is **VITALLY** important that the nonce is a nonce,
88 i.e. it is a number used only once for any given key. If you fail
89 to do this, you compromise the privacy of the messages encrypted.
90 Give your nonces a different prefix, or have one side use an odd
91 counter and one an even counter. Just make sure they are different.
92
93 :param plaintext: [:class:`bytes`] The plaintext message to encrypt
94 :param nonce: [:class:`bytes`] The nonce to use in the encryption
95 :param encoder: The encoder to use to encode the ciphertext
96 :rtype: [:class:`nacl.utils.EncryptedMessage`]
97 """
98 if nonce is None:
99 nonce = random(self.NONCE_SIZE)
100
101 if len(nonce) != self.NONCE_SIZE:
102 raise exc.ValueError(
103 "The nonce must be exactly %s bytes long" % self.NONCE_SIZE,
104 )
105
106 ciphertext = nacl.bindings.crypto_secretbox_easy(
107 plaintext, nonce, self._key
108 )
109
110 encoded_nonce = encoder.encode(nonce)
111 encoded_ciphertext = encoder.encode(ciphertext)
112
113 return EncryptedMessage._from_parts(
114 encoded_nonce,
115 encoded_ciphertext,
116 encoder.encode(nonce + ciphertext),
117 )
118
119 def decrypt(
120 self,
121 ciphertext: bytes,
122 nonce: Optional[bytes] = None,
123 encoder: encoding.Encoder = encoding.RawEncoder,
124 ) -> bytes:
125 """
126 Decrypts the ciphertext using the `nonce` (explicitly, when passed as a
127 parameter or implicitly, when omitted, as part of the ciphertext) and
128 returns the plaintext message.
129
130 :param ciphertext: [:class:`bytes`] The encrypted message to decrypt
131 :param nonce: [:class:`bytes`] The nonce used when encrypting the
132 ciphertext
133 :param encoder: The encoder used to decode the ciphertext.
134 :rtype: [:class:`bytes`]
135 """
136 # Decode our ciphertext
137 ciphertext = encoder.decode(ciphertext)
138
139 if nonce is None:
140 # If we were given the nonce and ciphertext combined, split them.
141 nonce = ciphertext[: self.NONCE_SIZE]
142 ciphertext = ciphertext[self.NONCE_SIZE :]
143
144 if len(nonce) != self.NONCE_SIZE:
145 raise exc.ValueError(
146 "The nonce must be exactly %s bytes long" % self.NONCE_SIZE,
147 )
148
149 plaintext = nacl.bindings.crypto_secretbox_open_easy(
150 ciphertext, nonce, self._key
151 )
152
153 return plaintext
154
155
156 class Aead(encoding.Encodable, StringFixer):
157 """
158 The AEAD class encrypts and decrypts messages using the given secret key.
159
160 Unlike :class:`~nacl.secret.SecretBox`, AEAD supports authenticating
161 non-confidential data received alongside the message, such as a length
162 or type tag.
163
164 Like :class:`~nacl.secret.Secretbox`, this class provides authenticated
165 encryption. An inauthentic message will cause the decrypt function to raise
166 an exception.
167
168 Likewise, the authenticator should not be mistaken for a (public-key)
169 signature: recipients (with the ability to decrypt messages) are capable of
170 creating arbitrary valid message; in particular, this means AEAD messages
171 are repudiable. For non-repudiable messages, sign them after encryption.
172
173 The cryptosystem used is `XChacha20-Poly1305`_ as specified for
174 `standardization`_. There are `no practical limits`_ to how much can safely
175 be encrypted under a given key (up to 2⁶⁴ messages each containing up
176 to 2⁶⁴ bytes).
177
178 .. _standardization: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha
179 .. _XChacha20-Poly1305: https://doc.libsodium.org/secret-key_cryptography/aead#xchacha-20-poly1305
180 .. _no practical limits: https://doc.libsodium.org/secret-key_cryptography/aead#limitations
181
182 :param key: The secret key used to encrypt and decrypt messages
183 :param encoder: The encoder class used to decode the given key
184
185 :cvar KEY_SIZE: The size that the key is required to be.
186 :cvar NONCE_SIZE: The size that the nonce is required to be.
187 :cvar MACBYTES: The size of the authentication MAC tag in bytes.
188 :cvar MESSAGEBYTES_MAX: The maximum size of a message which can be
189 safely encrypted with a single key/nonce
190 pair.
191 """
192
193 KEY_SIZE = nacl.bindings.crypto_aead_xchacha20poly1305_ietf_KEYBYTES
194 NONCE_SIZE = nacl.bindings.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES
195 MACBYTES = nacl.bindings.crypto_aead_xchacha20poly1305_ietf_ABYTES
196 MESSAGEBYTES_MAX = (
197 nacl.bindings.crypto_aead_xchacha20poly1305_ietf_MESSAGEBYTES_MAX
198 )
199
200 def __init__(
201 self,
202 key: bytes,
203 encoder: encoding.Encoder = encoding.RawEncoder,
204 ):
205 key = encoder.decode(key)
206 if not isinstance(key, bytes):
207 raise exc.TypeError("AEAD must be created from 32 bytes")
208
209 if len(key) != self.KEY_SIZE:
210 raise exc.ValueError(
211 "The key must be exactly %s bytes long" % self.KEY_SIZE,
212 )
213
214 self._key = key
215
216 def __bytes__(self) -> bytes:
217 return self._key
218
219 def encrypt(
220 self,
221 plaintext: bytes,
222 aad: bytes = b"",
223 nonce: Optional[bytes] = None,
224 encoder: encoding.Encoder = encoding.RawEncoder,
225 ) -> EncryptedMessage:
226 """
227 Encrypts the plaintext message using the given `nonce` (or generates
228 one randomly if omitted) and returns the ciphertext encoded with the
229 encoder.
230
231 .. warning:: It is vitally important for :param nonce: to be unique.
232 By default, it is generated randomly; [:class:`Aead`] uses XChacha20
233 for extended (192b) nonce size, so the risk of reusing random nonces
234 is negligible. It is *strongly recommended* to keep this behaviour,
235 as nonce reuse will compromise the privacy of encrypted messages.
236 Should implicit nonces be inadequate for your application, the
237 second best option is using split counters; e.g. if sending messages
238 encrypted under a shared key between 2 users, each user can use the
239 number of messages it sent so far, prefixed or suffixed with a 1bit
240 user id. Note that the counter must **never** be rolled back (due
241 to overflow, on-disk state being rolled back to an earlier backup,
242 ...)
243
244 :param plaintext: [:class:`bytes`] The plaintext message to encrypt
245 :param nonce: [:class:`bytes`] The nonce to use in the encryption
246 :param encoder: The encoder to use to encode the ciphertext
247 :rtype: [:class:`nacl.utils.EncryptedMessage`]
248 """
249 if nonce is None:
250 nonce = random(self.NONCE_SIZE)
251
252 if len(nonce) != self.NONCE_SIZE:
253 raise exc.ValueError(
254 "The nonce must be exactly %s bytes long" % self.NONCE_SIZE,
255 )
256
257 ciphertext = nacl.bindings.crypto_aead_xchacha20poly1305_ietf_encrypt(
258 plaintext, aad, nonce, self._key
259 )
260
261 encoded_nonce = encoder.encode(nonce)
262 encoded_ciphertext = encoder.encode(ciphertext)
263
264 return EncryptedMessage._from_parts(
265 encoded_nonce,
266 encoded_ciphertext,
267 encoder.encode(nonce + ciphertext),
268 )
269
270 def decrypt(
271 self,
272 ciphertext: bytes,
273 aad: bytes = b"",
274 nonce: Optional[bytes] = None,
275 encoder: encoding.Encoder = encoding.RawEncoder,
276 ) -> bytes:
277 """
278 Decrypts the ciphertext using the `nonce` (explicitly, when passed as a
279 parameter or implicitly, when omitted, as part of the ciphertext) and
280 returns the plaintext message.
281
282 :param ciphertext: [:class:`bytes`] The encrypted message to decrypt
283 :param nonce: [:class:`bytes`] The nonce used when encrypting the
284 ciphertext
285 :param encoder: The encoder used to decode the ciphertext.
286 :rtype: [:class:`bytes`]
287 """
288 # Decode our ciphertext
289 ciphertext = encoder.decode(ciphertext)
290
291 if nonce is None:
292 # If we were given the nonce and ciphertext combined, split them.
293 nonce = ciphertext[: self.NONCE_SIZE]
294 ciphertext = ciphertext[self.NONCE_SIZE :]
295
296 if len(nonce) != self.NONCE_SIZE:
297 raise exc.ValueError(
298 "The nonce must be exactly %s bytes long" % self.NONCE_SIZE,
299 )
300
301 plaintext = nacl.bindings.crypto_aead_xchacha20poly1305_ietf_decrypt(
302 ciphertext, aad, nonce, self._key
303 )
304
305 return plaintext