1 /**
2  * \file chachapoly.h
3  *
4  * \brief   This file contains the AEAD-ChaCha20-Poly1305 definitions and
5  *          functions.
6  *
7  *          ChaCha20-Poly1305 is an algorithm for Authenticated Encryption
8  *          with Associated Data (AEAD) that can be used to encrypt and
9  *          authenticate data. It is based on ChaCha20 and Poly1305 by Daniel
10  *          Bernstein and was standardized in RFC 7539.
11  *
12  * \author Daniel King <damaki.gh@gmail.com>
13  */
14 
15 /*
16  *  Copyright The Mbed TLS Contributors
17  *  SPDX-License-Identifier: Apache-2.0
18  *
19  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
20  *  not use this file except in compliance with the License.
21  *  You may obtain a copy of the License at
22  *
23  *  http://www.apache.org/licenses/LICENSE-2.0
24  *
25  *  Unless required by applicable law or agreed to in writing, software
26  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
27  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
28  *  See the License for the specific language governing permissions and
29  *  limitations under the License.
30  */
31 
32 #ifndef MBEDTLS_CHACHAPOLY_H
33 #define MBEDTLS_CHACHAPOLY_H
34 
35 #if !defined(MBEDTLS_CONFIG_FILE)
36 #include "mbedtls/config.h"
37 #else
38 #include MBEDTLS_CONFIG_FILE
39 #endif
40 
41 /* for shared error codes */
42 #include "mbedtls/poly1305.h"
43 
44 #define MBEDTLS_ERR_CHACHAPOLY_BAD_STATE            -0x0054 /**< The requested operation is not permitted in the current state. */
45 #define MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED          -0x0056 /**< Authenticated decryption failed: data was not authentic. */
46 
47 #ifdef __cplusplus
48 extern "C" {
49 #endif
50 
51 typedef enum
52 {
53     MBEDTLS_CHACHAPOLY_ENCRYPT,     /**< The mode value for performing encryption. */
54     MBEDTLS_CHACHAPOLY_DECRYPT      /**< The mode value for performing decryption. */
55 }
56 mbedtls_chachapoly_mode_t;
57 
58 #if !defined(MBEDTLS_CHACHAPOLY_ALT)
59 
60 #include "mbedtls/chacha20.h"
61 
62 typedef struct mbedtls_chachapoly_context
63 {
64     mbedtls_chacha20_context chacha20_ctx;  /**< The ChaCha20 context. */
65     mbedtls_poly1305_context poly1305_ctx;  /**< The Poly1305 context. */
66     uint64_t aad_len;                       /**< The length (bytes) of the Additional Authenticated Data. */
67     uint64_t ciphertext_len;                /**< The length (bytes) of the ciphertext. */
68     int state;                              /**< The current state of the context. */
69     mbedtls_chachapoly_mode_t mode;         /**< Cipher mode (encrypt or decrypt). */
70 }
71 mbedtls_chachapoly_context;
72 
73 #else /* !MBEDTLS_CHACHAPOLY_ALT */
74 #include "chachapoly_alt.h"
75 #endif /* !MBEDTLS_CHACHAPOLY_ALT */
76 
77 /**
78  * \brief           This function initializes the specified ChaCha20-Poly1305 context.
79  *
80  *                  It must be the first API called before using
81  *                  the context. It must be followed by a call to
82  *                  \c mbedtls_chachapoly_setkey() before any operation can be
83  *                  done, and to \c mbedtls_chachapoly_free() once all
84  *                  operations with that context have been finished.
85  *
86  *                  In order to encrypt or decrypt full messages at once, for
87  *                  each message you should make a single call to
88  *                  \c mbedtls_chachapoly_crypt_and_tag() or
89  *                  \c mbedtls_chachapoly_auth_decrypt().
90  *
91  *                  In order to encrypt messages piecewise, for each
92  *                  message you should make a call to
93  *                  \c mbedtls_chachapoly_starts(), then 0 or more calls to
94  *                  \c mbedtls_chachapoly_update_aad(), then 0 or more calls to
95  *                  \c mbedtls_chachapoly_update(), then one call to
96  *                  \c mbedtls_chachapoly_finish().
97  *
98  * \warning         Decryption with the piecewise API is discouraged! Always
99  *                  use \c mbedtls_chachapoly_auth_decrypt() when possible!
100  *
101  *                  If however this is not possible because the data is too
102  *                  large to fit in memory, you need to:
103  *
104  *                  - call \c mbedtls_chachapoly_starts() and (if needed)
105  *                  \c mbedtls_chachapoly_update_aad() as above,
106  *                  - call \c mbedtls_chachapoly_update() multiple times and
107  *                  ensure its output (the plaintext) is NOT used in any other
108  *                  way than placing it in temporary storage at this point,
109  *                  - call \c mbedtls_chachapoly_finish() to compute the
110  *                  authentication tag and compared it in constant time to the
111  *                  tag received with the ciphertext.
112  *
113  *                  If the tags are not equal, you must immediately discard
114  *                  all previous outputs of \c mbedtls_chachapoly_update(),
115  *                  otherwise you can now safely use the plaintext.
116  *
117  * \param ctx       The ChachaPoly context to initialize. Must not be \c NULL.
118  */
119 void mbedtls_chachapoly_init( mbedtls_chachapoly_context *ctx );
120 
121 /**
122  * \brief           This function releases and clears the specified
123  *                  ChaCha20-Poly1305 context.
124  *
125  * \param ctx       The ChachaPoly context to clear. This may be \c NULL, in which
126  *                  case this function is a no-op.
127  */
128 void mbedtls_chachapoly_free( mbedtls_chachapoly_context *ctx );
129 
130 /**
131  * \brief           This function sets the ChaCha20-Poly1305
132  *                  symmetric encryption key.
133  *
134  * \param ctx       The ChaCha20-Poly1305 context to which the key should be
135  *                  bound. This must be initialized.
136  * \param key       The \c 256 Bit (\c 32 Bytes) key.
137  *
138  * \return          \c 0 on success.
139  * \return          A negative error code on failure.
140  */
141 int mbedtls_chachapoly_setkey( mbedtls_chachapoly_context *ctx,
142                                const unsigned char key[32] );
143 
144 /**
145  * \brief           This function starts a ChaCha20-Poly1305 encryption or
146  *                  decryption operation.
147  *
148  * \warning         You must never use the same nonce twice with the same key.
149  *                  This would void any confidentiality and authenticity
150  *                  guarantees for the messages encrypted with the same nonce
151  *                  and key.
152  *
153  * \note            If the context is being used for AAD only (no data to
154  *                  encrypt or decrypt) then \p mode can be set to any value.
155  *
156  * \warning         Decryption with the piecewise API is discouraged, see the
157  *                  warning on \c mbedtls_chachapoly_init().
158  *
159  * \param ctx       The ChaCha20-Poly1305 context. This must be initialized
160  *                  and bound to a key.
161  * \param nonce     The nonce/IV to use for the message.
162  *                  This must be a redable buffer of length \c 12 Bytes.
163  * \param mode      The operation to perform: #MBEDTLS_CHACHAPOLY_ENCRYPT or
164  *                  #MBEDTLS_CHACHAPOLY_DECRYPT (discouraged, see warning).
165  *
166  * \return          \c 0 on success.
167  * \return          A negative error code on failure.
168  */
169 int mbedtls_chachapoly_starts( mbedtls_chachapoly_context *ctx,
170                                const unsigned char nonce[12],
171                                mbedtls_chachapoly_mode_t mode );
172 
173 /**
174  * \brief           This function feeds additional data to be authenticated
175  *                  into an ongoing ChaCha20-Poly1305 operation.
176  *
177  *                  The Additional Authenticated Data (AAD), also called
178  *                  Associated Data (AD) is only authenticated but not
179  *                  encrypted nor included in the encrypted output. It is
180  *                  usually transmitted separately from the ciphertext or
181  *                  computed locally by each party.
182  *
183  * \note            This function is called before data is encrypted/decrypted.
184  *                  I.e. call this function to process the AAD before calling
185  *                  \c mbedtls_chachapoly_update().
186  *
187  *                  You may call this function multiple times to process
188  *                  an arbitrary amount of AAD. It is permitted to call
189  *                  this function 0 times, if no AAD is used.
190  *
191  *                  This function cannot be called any more if data has
192  *                  been processed by \c mbedtls_chachapoly_update(),
193  *                  or if the context has been finished.
194  *
195  * \warning         Decryption with the piecewise API is discouraged, see the
196  *                  warning on \c mbedtls_chachapoly_init().
197  *
198  * \param ctx       The ChaCha20-Poly1305 context. This must be initialized
199  *                  and bound to a key.
200  * \param aad_len   The length in Bytes of the AAD. The length has no
201  *                  restrictions.
202  * \param aad       Buffer containing the AAD.
203  *                  This pointer can be \c NULL if `aad_len == 0`.
204  *
205  * \return          \c 0 on success.
206  * \return          #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA
207  *                  if \p ctx or \p aad are NULL.
208  * \return          #MBEDTLS_ERR_CHACHAPOLY_BAD_STATE
209  *                  if the operations has not been started or has been
210  *                  finished, or if the AAD has been finished.
211  */
212 int mbedtls_chachapoly_update_aad( mbedtls_chachapoly_context *ctx,
213                                    const unsigned char *aad,
214                                    size_t aad_len );
215 
216 /**
217  * \brief           Thus function feeds data to be encrypted or decrypted
218  *                  into an on-going ChaCha20-Poly1305
219  *                  operation.
220  *
221  *                  The direction (encryption or decryption) depends on the
222  *                  mode that was given when calling
223  *                  \c mbedtls_chachapoly_starts().
224  *
225  *                  You may call this function multiple times to process
226  *                  an arbitrary amount of data. It is permitted to call
227  *                  this function 0 times, if no data is to be encrypted
228  *                  or decrypted.
229  *
230  * \warning         Decryption with the piecewise API is discouraged, see the
231  *                  warning on \c mbedtls_chachapoly_init().
232  *
233  * \param ctx       The ChaCha20-Poly1305 context to use. This must be initialized.
234  * \param len       The length (in bytes) of the data to encrypt or decrypt.
235  * \param input     The buffer containing the data to encrypt or decrypt.
236  *                  This pointer can be \c NULL if `len == 0`.
237  * \param output    The buffer to where the encrypted or decrypted data is
238  *                  written. This must be able to hold \p len bytes.
239  *                  This pointer can be \c NULL if `len == 0`.
240  *
241  * \return          \c 0 on success.
242  * \return          #MBEDTLS_ERR_CHACHAPOLY_BAD_STATE
243  *                  if the operation has not been started or has been
244  *                  finished.
245  * \return          Another negative error code on other kinds of failure.
246  */
247 int mbedtls_chachapoly_update( mbedtls_chachapoly_context *ctx,
248                                size_t len,
249                                const unsigned char *input,
250                                unsigned char *output );
251 
252 /**
253  * \brief           This function finished the ChaCha20-Poly1305 operation and
254  *                  generates the MAC (authentication tag).
255  *
256  * \param ctx       The ChaCha20-Poly1305 context to use. This must be initialized.
257  * \param mac       The buffer to where the 128-bit (16 bytes) MAC is written.
258  *
259  * \warning         Decryption with the piecewise API is discouraged, see the
260  *                  warning on \c mbedtls_chachapoly_init().
261  *
262  * \return          \c 0 on success.
263  * \return          #MBEDTLS_ERR_CHACHAPOLY_BAD_STATE
264  *                  if the operation has not been started or has been
265  *                  finished.
266  * \return          Another negative error code on other kinds of failure.
267  */
268 int mbedtls_chachapoly_finish( mbedtls_chachapoly_context *ctx,
269                                unsigned char mac[16] );
270 
271 /**
272  * \brief           This function performs a complete ChaCha20-Poly1305
273  *                  authenticated encryption with the previously-set key.
274  *
275  * \note            Before using this function, you must set the key with
276  *                  \c mbedtls_chachapoly_setkey().
277  *
278  * \warning         You must never use the same nonce twice with the same key.
279  *                  This would void any confidentiality and authenticity
280  *                  guarantees for the messages encrypted with the same nonce
281  *                  and key.
282  *
283  * \param ctx       The ChaCha20-Poly1305 context to use (holds the key).
284  *                  This must be initialized.
285  * \param length    The length (in bytes) of the data to encrypt or decrypt.
286  * \param nonce     The 96-bit (12 bytes) nonce/IV to use.
287  * \param aad       The buffer containing the additional authenticated
288  *                  data (AAD). This pointer can be \c NULL if `aad_len == 0`.
289  * \param aad_len   The length (in bytes) of the AAD data to process.
290  * \param input     The buffer containing the data to encrypt or decrypt.
291  *                  This pointer can be \c NULL if `ilen == 0`.
292  * \param output    The buffer to where the encrypted or decrypted data
293  *                  is written. This pointer can be \c NULL if `ilen == 0`.
294  * \param tag       The buffer to where the computed 128-bit (16 bytes) MAC
295  *                  is written. This must not be \c NULL.
296  *
297  * \return          \c 0 on success.
298  * \return          A negative error code on failure.
299  */
300 int mbedtls_chachapoly_encrypt_and_tag( mbedtls_chachapoly_context *ctx,
301                                         size_t length,
302                                         const unsigned char nonce[12],
303                                         const unsigned char *aad,
304                                         size_t aad_len,
305                                         const unsigned char *input,
306                                         unsigned char *output,
307                                         unsigned char tag[16] );
308 
309 /**
310  * \brief           This function performs a complete ChaCha20-Poly1305
311  *                  authenticated decryption with the previously-set key.
312  *
313  * \note            Before using this function, you must set the key with
314  *                  \c mbedtls_chachapoly_setkey().
315  *
316  * \param ctx       The ChaCha20-Poly1305 context to use (holds the key).
317  * \param length    The length (in Bytes) of the data to decrypt.
318  * \param nonce     The \c 96 Bit (\c 12 bytes) nonce/IV to use.
319  * \param aad       The buffer containing the additional authenticated data (AAD).
320  *                  This pointer can be \c NULL if `aad_len == 0`.
321  * \param aad_len   The length (in bytes) of the AAD data to process.
322  * \param tag       The buffer holding the authentication tag.
323  *                  This must be a readable buffer of length \c 16 Bytes.
324  * \param input     The buffer containing the data to decrypt.
325  *                  This pointer can be \c NULL if `ilen == 0`.
326  * \param output    The buffer to where the decrypted data is written.
327  *                  This pointer can be \c NULL if `ilen == 0`.
328  *
329  * \return          \c 0 on success.
330  * \return          #MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED
331  *                  if the data was not authentic.
332  * \return          Another negative error code on other kinds of failure.
333  */
334 int mbedtls_chachapoly_auth_decrypt( mbedtls_chachapoly_context *ctx,
335                                      size_t length,
336                                      const unsigned char nonce[12],
337                                      const unsigned char *aad,
338                                      size_t aad_len,
339                                      const unsigned char tag[16],
340                                      const unsigned char *input,
341                                      unsigned char *output );
342 
343 #if defined(MBEDTLS_SELF_TEST)
344 /**
345  * \brief           The ChaCha20-Poly1305 checkup routine.
346  *
347  * \return          \c 0 on success.
348  * \return          \c 1 on failure.
349  */
350 int mbedtls_chachapoly_self_test( int verbose );
351 #endif /* MBEDTLS_SELF_TEST */
352 
353 #ifdef __cplusplus
354 }
355 #endif
356 
357 #endif /* MBEDTLS_CHACHAPOLY_H */
358