1 /**
2  * \file cipher.h
3  *
4  * \brief This file contains an abstraction interface for use with the cipher
5  * primitives provided by the library. It provides a common interface to all of
6  * the available cipher operations.
7  *
8  * \author Adriaan de Jong <dejong@fox-it.com>
9  */
10 /*
11  *  Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
12  *  SPDX-License-Identifier: Apache-2.0
13  *
14  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
15  *  not use this file except in compliance with the License.
16  *  You may obtain a copy of the License at
17  *
18  *  http://www.apache.org/licenses/LICENSE-2.0
19  *
20  *  Unless required by applicable law or agreed to in writing, software
21  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
22  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23  *  See the License for the specific language governing permissions and
24  *  limitations under the License.
25  *
26  *  This file is part of Mbed TLS (https://tls.mbed.org)
27  */
28 
29 #ifndef MBEDTLS_CIPHER_H
30 #define MBEDTLS_CIPHER_H
31 
32 #if !defined(MBEDTLS_CONFIG_FILE)
33 #include "config.h"
34 #else
35 #include MBEDTLS_CONFIG_FILE
36 #endif
37 
38 #include <stddef.h>
39 #include "mbedtls/platform_util.h"
40 
41 #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C) || defined(MBEDTLS_CHACHAPOLY_C)
42 #define MBEDTLS_CIPHER_MODE_AEAD
43 #endif
44 
45 #if defined(MBEDTLS_CIPHER_MODE_CBC)
46 #define MBEDTLS_CIPHER_MODE_WITH_PADDING
47 #endif
48 
49 #if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER) || \
50     defined(MBEDTLS_CHACHA20_C)
51 #define MBEDTLS_CIPHER_MODE_STREAM
52 #endif
53 
54 #if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
55     !defined(inline) && !defined(__cplusplus)
56 #define inline __inline
57 #endif
58 
59 #define MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE  -0x6080  /**< The selected feature is not available. */
60 #define MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA       -0x6100  /**< Bad input parameters. */
61 #define MBEDTLS_ERR_CIPHER_ALLOC_FAILED         -0x6180  /**< Failed to allocate memory. */
62 #define MBEDTLS_ERR_CIPHER_INVALID_PADDING      -0x6200  /**< Input data contains invalid padding and is rejected. */
63 #define MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED  -0x6280  /**< Decryption of block requires a full block. */
64 #define MBEDTLS_ERR_CIPHER_AUTH_FAILED          -0x6300  /**< Authentication failed (for AEAD modes). */
65 #define MBEDTLS_ERR_CIPHER_INVALID_CONTEXT      -0x6380  /**< The context is invalid. For example, because it was freed. */
66 
67 /* MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED is deprecated and should not be used. */
68 #define MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED      -0x6400  /**< Cipher hardware accelerator failed. */
69 
70 #define MBEDTLS_CIPHER_VARIABLE_IV_LEN     0x01    /**< Cipher accepts IVs of variable length. */
71 #define MBEDTLS_CIPHER_VARIABLE_KEY_LEN    0x02    /**< Cipher accepts keys of variable length. */
72 
73 #ifdef __cplusplus
74 extern "C" {
75 #endif
76 
77 /**
78  * \brief     Supported cipher types.
79  *
80  * \warning   RC4 and DES are considered weak ciphers and their use
81  *            constitutes a security risk. Arm recommends considering stronger
82  *            ciphers instead.
83  */
84 typedef enum {
85     MBEDTLS_CIPHER_ID_NONE = 0,  /**< Placeholder to mark the end of cipher ID lists. */
86     MBEDTLS_CIPHER_ID_NULL,      /**< The identity cipher, treated as a stream cipher. */
87     MBEDTLS_CIPHER_ID_AES,       /**< The AES cipher. */
88     MBEDTLS_CIPHER_ID_DES,       /**< The DES cipher. */
89     MBEDTLS_CIPHER_ID_3DES,      /**< The Triple DES cipher. */
90     MBEDTLS_CIPHER_ID_CAMELLIA,  /**< The Camellia cipher. */
91     MBEDTLS_CIPHER_ID_BLOWFISH,  /**< The Blowfish cipher. */
92     MBEDTLS_CIPHER_ID_ARC4,      /**< The RC4 cipher. */
93     MBEDTLS_CIPHER_ID_ARIA,      /**< The Aria cipher. */
94     MBEDTLS_CIPHER_ID_CHACHA20,  /**< The ChaCha20 cipher. */
95 } mbedtls_cipher_id_t;
96 
97 /**
98  * \brief     Supported {cipher type, cipher mode} pairs.
99  *
100  * \warning   RC4 and DES are considered weak ciphers and their use
101  *            constitutes a security risk. Arm recommends considering stronger
102  *            ciphers instead.
103  */
104 typedef enum {
105     MBEDTLS_CIPHER_NONE = 0,             /**< Placeholder to mark the end of cipher-pair lists. */
106     MBEDTLS_CIPHER_NULL,                 /**< The identity stream cipher. */
107     MBEDTLS_CIPHER_AES_128_ECB,          /**< AES cipher with 128-bit ECB mode. */
108     MBEDTLS_CIPHER_AES_192_ECB,          /**< AES cipher with 192-bit ECB mode. */
109     MBEDTLS_CIPHER_AES_256_ECB,          /**< AES cipher with 256-bit ECB mode. */
110     MBEDTLS_CIPHER_AES_128_CBC,          /**< AES cipher with 128-bit CBC mode. */
111     MBEDTLS_CIPHER_AES_192_CBC,          /**< AES cipher with 192-bit CBC mode. */
112     MBEDTLS_CIPHER_AES_256_CBC,          /**< AES cipher with 256-bit CBC mode. */
113     MBEDTLS_CIPHER_AES_128_CFB128,       /**< AES cipher with 128-bit CFB128 mode. */
114     MBEDTLS_CIPHER_AES_192_CFB128,       /**< AES cipher with 192-bit CFB128 mode. */
115     MBEDTLS_CIPHER_AES_256_CFB128,       /**< AES cipher with 256-bit CFB128 mode. */
116     MBEDTLS_CIPHER_AES_128_CTR,          /**< AES cipher with 128-bit CTR mode. */
117     MBEDTLS_CIPHER_AES_192_CTR,          /**< AES cipher with 192-bit CTR mode. */
118     MBEDTLS_CIPHER_AES_256_CTR,          /**< AES cipher with 256-bit CTR mode. */
119     MBEDTLS_CIPHER_AES_128_GCM,          /**< AES cipher with 128-bit GCM mode. */
120     MBEDTLS_CIPHER_AES_192_GCM,          /**< AES cipher with 192-bit GCM mode. */
121     MBEDTLS_CIPHER_AES_256_GCM,          /**< AES cipher with 256-bit GCM mode. */
122     MBEDTLS_CIPHER_CAMELLIA_128_ECB,     /**< Camellia cipher with 128-bit ECB mode. */
123     MBEDTLS_CIPHER_CAMELLIA_192_ECB,     /**< Camellia cipher with 192-bit ECB mode. */
124     MBEDTLS_CIPHER_CAMELLIA_256_ECB,     /**< Camellia cipher with 256-bit ECB mode. */
125     MBEDTLS_CIPHER_CAMELLIA_128_CBC,     /**< Camellia cipher with 128-bit CBC mode. */
126     MBEDTLS_CIPHER_CAMELLIA_192_CBC,     /**< Camellia cipher with 192-bit CBC mode. */
127     MBEDTLS_CIPHER_CAMELLIA_256_CBC,     /**< Camellia cipher with 256-bit CBC mode. */
128     MBEDTLS_CIPHER_CAMELLIA_128_CFB128,  /**< Camellia cipher with 128-bit CFB128 mode. */
129     MBEDTLS_CIPHER_CAMELLIA_192_CFB128,  /**< Camellia cipher with 192-bit CFB128 mode. */
130     MBEDTLS_CIPHER_CAMELLIA_256_CFB128,  /**< Camellia cipher with 256-bit CFB128 mode. */
131     MBEDTLS_CIPHER_CAMELLIA_128_CTR,     /**< Camellia cipher with 128-bit CTR mode. */
132     MBEDTLS_CIPHER_CAMELLIA_192_CTR,     /**< Camellia cipher with 192-bit CTR mode. */
133     MBEDTLS_CIPHER_CAMELLIA_256_CTR,     /**< Camellia cipher with 256-bit CTR mode. */
134     MBEDTLS_CIPHER_CAMELLIA_128_GCM,     /**< Camellia cipher with 128-bit GCM mode. */
135     MBEDTLS_CIPHER_CAMELLIA_192_GCM,     /**< Camellia cipher with 192-bit GCM mode. */
136     MBEDTLS_CIPHER_CAMELLIA_256_GCM,     /**< Camellia cipher with 256-bit GCM mode. */
137     MBEDTLS_CIPHER_DES_ECB,              /**< DES cipher with ECB mode. */
138     MBEDTLS_CIPHER_DES_CBC,              /**< DES cipher with CBC mode. */
139     MBEDTLS_CIPHER_DES_EDE_ECB,          /**< DES cipher with EDE ECB mode. */
140     MBEDTLS_CIPHER_DES_EDE_CBC,          /**< DES cipher with EDE CBC mode. */
141     MBEDTLS_CIPHER_DES_EDE3_ECB,         /**< DES cipher with EDE3 ECB mode. */
142     MBEDTLS_CIPHER_DES_EDE3_CBC,         /**< DES cipher with EDE3 CBC mode. */
143     MBEDTLS_CIPHER_BLOWFISH_ECB,         /**< Blowfish cipher with ECB mode. */
144     MBEDTLS_CIPHER_BLOWFISH_CBC,         /**< Blowfish cipher with CBC mode. */
145     MBEDTLS_CIPHER_BLOWFISH_CFB64,       /**< Blowfish cipher with CFB64 mode. */
146     MBEDTLS_CIPHER_BLOWFISH_CTR,         /**< Blowfish cipher with CTR mode. */
147     MBEDTLS_CIPHER_ARC4_128,             /**< RC4 cipher with 128-bit mode. */
148     MBEDTLS_CIPHER_AES_128_CCM,          /**< AES cipher with 128-bit CCM mode. */
149     MBEDTLS_CIPHER_AES_192_CCM,          /**< AES cipher with 192-bit CCM mode. */
150     MBEDTLS_CIPHER_AES_256_CCM,          /**< AES cipher with 256-bit CCM mode. */
151     MBEDTLS_CIPHER_CAMELLIA_128_CCM,     /**< Camellia cipher with 128-bit CCM mode. */
152     MBEDTLS_CIPHER_CAMELLIA_192_CCM,     /**< Camellia cipher with 192-bit CCM mode. */
153     MBEDTLS_CIPHER_CAMELLIA_256_CCM,     /**< Camellia cipher with 256-bit CCM mode. */
154     MBEDTLS_CIPHER_ARIA_128_ECB,         /**< Aria cipher with 128-bit key and ECB mode. */
155     MBEDTLS_CIPHER_ARIA_192_ECB,         /**< Aria cipher with 192-bit key and ECB mode. */
156     MBEDTLS_CIPHER_ARIA_256_ECB,         /**< Aria cipher with 256-bit key and ECB mode. */
157     MBEDTLS_CIPHER_ARIA_128_CBC,         /**< Aria cipher with 128-bit key and CBC mode. */
158     MBEDTLS_CIPHER_ARIA_192_CBC,         /**< Aria cipher with 192-bit key and CBC mode. */
159     MBEDTLS_CIPHER_ARIA_256_CBC,         /**< Aria cipher with 256-bit key and CBC mode. */
160     MBEDTLS_CIPHER_ARIA_128_CFB128,      /**< Aria cipher with 128-bit key and CFB-128 mode. */
161     MBEDTLS_CIPHER_ARIA_192_CFB128,      /**< Aria cipher with 192-bit key and CFB-128 mode. */
162     MBEDTLS_CIPHER_ARIA_256_CFB128,      /**< Aria cipher with 256-bit key and CFB-128 mode. */
163     MBEDTLS_CIPHER_ARIA_128_CTR,         /**< Aria cipher with 128-bit key and CTR mode. */
164     MBEDTLS_CIPHER_ARIA_192_CTR,         /**< Aria cipher with 192-bit key and CTR mode. */
165     MBEDTLS_CIPHER_ARIA_256_CTR,         /**< Aria cipher with 256-bit key and CTR mode. */
166     MBEDTLS_CIPHER_ARIA_128_GCM,         /**< Aria cipher with 128-bit key and GCM mode. */
167     MBEDTLS_CIPHER_ARIA_192_GCM,         /**< Aria cipher with 192-bit key and GCM mode. */
168     MBEDTLS_CIPHER_ARIA_256_GCM,         /**< Aria cipher with 256-bit key and GCM mode. */
169     MBEDTLS_CIPHER_ARIA_128_CCM,         /**< Aria cipher with 128-bit key and CCM mode. */
170     MBEDTLS_CIPHER_ARIA_192_CCM,         /**< Aria cipher with 192-bit key and CCM mode. */
171     MBEDTLS_CIPHER_ARIA_256_CCM,         /**< Aria cipher with 256-bit key and CCM mode. */
172     MBEDTLS_CIPHER_AES_128_OFB,          /**< AES 128-bit cipher in OFB mode. */
173     MBEDTLS_CIPHER_AES_192_OFB,          /**< AES 192-bit cipher in OFB mode. */
174     MBEDTLS_CIPHER_AES_256_OFB,          /**< AES 256-bit cipher in OFB mode. */
175     MBEDTLS_CIPHER_AES_128_XTS,          /**< AES 128-bit cipher in XTS block mode. */
176     MBEDTLS_CIPHER_AES_256_XTS,          /**< AES 256-bit cipher in XTS block mode. */
177     MBEDTLS_CIPHER_CHACHA20,             /**< ChaCha20 stream cipher. */
178     MBEDTLS_CIPHER_CHACHA20_POLY1305,    /**< ChaCha20-Poly1305 AEAD cipher. */
179 } mbedtls_cipher_type_t;
180 
181 /** Supported cipher modes. */
182 typedef enum {
183     MBEDTLS_MODE_NONE = 0,               /**< None. */
184     MBEDTLS_MODE_ECB,                    /**< The ECB cipher mode. */
185     MBEDTLS_MODE_CBC,                    /**< The CBC cipher mode. */
186     MBEDTLS_MODE_CFB,                    /**< The CFB cipher mode. */
187     MBEDTLS_MODE_OFB,                    /**< The OFB cipher mode. */
188     MBEDTLS_MODE_CTR,                    /**< The CTR cipher mode. */
189     MBEDTLS_MODE_GCM,                    /**< The GCM cipher mode. */
190     MBEDTLS_MODE_STREAM,                 /**< The stream cipher mode. */
191     MBEDTLS_MODE_CCM,                    /**< The CCM cipher mode. */
192     MBEDTLS_MODE_XTS,                    /**< The XTS cipher mode. */
193     MBEDTLS_MODE_CHACHAPOLY,             /**< The ChaCha-Poly cipher mode. */
194 } mbedtls_cipher_mode_t;
195 
196 /** Supported cipher padding types. */
197 typedef enum {
198     MBEDTLS_PADDING_PKCS7 = 0,     /**< PKCS7 padding (default).        */
199     MBEDTLS_PADDING_ONE_AND_ZEROS, /**< ISO/IEC 7816-4 padding.         */
200     MBEDTLS_PADDING_ZEROS_AND_LEN, /**< ANSI X.923 padding.             */
201     MBEDTLS_PADDING_ZEROS,         /**< Zero padding (not reversible). */
202     MBEDTLS_PADDING_NONE,          /**< Never pad (full blocks only).   */
203 } mbedtls_cipher_padding_t;
204 
205 /** Type of operation. */
206 typedef enum {
207     MBEDTLS_OPERATION_NONE = -1,
208     MBEDTLS_DECRYPT = 0,
209     MBEDTLS_ENCRYPT,
210 } mbedtls_operation_t;
211 
212 enum {
213     /** Undefined key length. */
214     MBEDTLS_KEY_LENGTH_NONE = 0,
215     /** Key length, in bits (including parity), for DES keys. */
216     MBEDTLS_KEY_LENGTH_DES  = 64,
217     /** Key length in bits, including parity, for DES in two-key EDE. */
218     MBEDTLS_KEY_LENGTH_DES_EDE = 128,
219     /** Key length in bits, including parity, for DES in three-key EDE. */
220     MBEDTLS_KEY_LENGTH_DES_EDE3 = 192,
221 };
222 
223 /** Maximum length of any IV, in Bytes. */
224 #define MBEDTLS_MAX_IV_LENGTH      16
225 /** Maximum block size of any cipher, in Bytes. */
226 #define MBEDTLS_MAX_BLOCK_LENGTH   16
227 
228 /**
229  * Base cipher information (opaque struct).
230  */
231 typedef struct mbedtls_cipher_base_t mbedtls_cipher_base_t;
232 
233 /**
234  * CMAC context (opaque struct).
235  */
236 typedef struct mbedtls_cmac_context_t mbedtls_cmac_context_t;
237 
238 /**
239  * Cipher information. Allows calling cipher functions
240  * in a generic way.
241  */
242 typedef struct mbedtls_cipher_info_t
243 {
244     /** Full cipher identifier. For example,
245      * MBEDTLS_CIPHER_AES_256_CBC.
246      */
247     mbedtls_cipher_type_t type;
248 
249     /** The cipher mode. For example, MBEDTLS_MODE_CBC. */
250     mbedtls_cipher_mode_t mode;
251 
252     /** The cipher key length, in bits. This is the
253      * default length for variable sized ciphers.
254      * Includes parity bits for ciphers like DES.
255      */
256     unsigned int key_bitlen;
257 
258     /** Name of the cipher. */
259     const char * name;
260 
261     /** IV or nonce size, in Bytes.
262      * For ciphers that accept variable IV sizes,
263      * this is the recommended size.
264      */
265     unsigned int iv_size;
266 
267     /** Bitflag comprised of MBEDTLS_CIPHER_VARIABLE_IV_LEN and
268      *  MBEDTLS_CIPHER_VARIABLE_KEY_LEN indicating whether the
269      *  cipher supports variable IV or variable key sizes, respectively.
270      */
271     int flags;
272 
273     /** The block size, in Bytes. */
274     unsigned int block_size;
275 
276     /** Struct for base cipher information and functions. */
277     const mbedtls_cipher_base_t *base;
278 
279 } mbedtls_cipher_info_t;
280 
281 /**
282  * Generic cipher context.
283  */
284 typedef struct mbedtls_cipher_context_t
285 {
286     /** Information about the associated cipher. */
287     const mbedtls_cipher_info_t *cipher_info;
288 
289     /** Key length to use. */
290     int key_bitlen;
291 
292     /** Operation that the key of the context has been
293      * initialized for.
294      */
295     mbedtls_operation_t operation;
296 
297 #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
298     /** Padding functions to use, if relevant for
299      * the specific cipher mode.
300      */
301     void (*add_padding)( unsigned char *output, size_t olen, size_t data_len );
302     int (*get_padding)( unsigned char *input, size_t ilen, size_t *data_len );
303 #endif
304 
305     /** Buffer for input that has not been processed yet. */
306     unsigned char unprocessed_data[MBEDTLS_MAX_BLOCK_LENGTH];
307 
308     /** Number of Bytes that have not been processed yet. */
309     size_t unprocessed_len;
310 
311     /** Current IV or NONCE_COUNTER for CTR-mode, data unit (or sector) number
312      * for XTS-mode. */
313     unsigned char iv[MBEDTLS_MAX_IV_LENGTH];
314 
315     /** IV size in Bytes, for ciphers with variable-length IVs. */
316     size_t iv_size;
317 
318     /** The cipher-specific context. */
319     void *cipher_ctx;
320 
321 #if defined(MBEDTLS_CMAC_C)
322     /** CMAC-specific context. */
323     mbedtls_cmac_context_t *cmac_ctx;
324 #endif
325 } mbedtls_cipher_context_t;
326 
327 /**
328  * \brief This function retrieves the list of ciphers supported by the generic
329  * cipher module.
330  *
331  * \return      A statically-allocated array of ciphers. The last entry
332  *              is zero.
333  */
334 const int *mbedtls_cipher_list( void );
335 
336 /**
337  * \brief               This function retrieves the cipher-information
338  *                      structure associated with the given cipher name.
339  *
340  * \param cipher_name   Name of the cipher to search for. This must not be
341  *                      \c NULL.
342  *
343  * \return              The cipher information structure associated with the
344  *                      given \p cipher_name.
345  * \return              \c NULL if the associated cipher information is not found.
346  */
347 const mbedtls_cipher_info_t *mbedtls_cipher_info_from_string( const char *cipher_name );
348 
349 /**
350  * \brief               This function retrieves the cipher-information
351  *                      structure associated with the given cipher type.
352  *
353  * \param cipher_type   Type of the cipher to search for.
354  *
355  * \return              The cipher information structure associated with the
356  *                      given \p cipher_type.
357  * \return              \c NULL if the associated cipher information is not found.
358  */
359 const mbedtls_cipher_info_t *mbedtls_cipher_info_from_type( const mbedtls_cipher_type_t cipher_type );
360 
361 /**
362  * \brief               This function retrieves the cipher-information
363  *                      structure associated with the given cipher ID,
364  *                      key size and mode.
365  *
366  * \param cipher_id     The ID of the cipher to search for. For example,
367  *                      #MBEDTLS_CIPHER_ID_AES.
368  * \param key_bitlen    The length of the key in bits.
369  * \param mode          The cipher mode. For example, #MBEDTLS_MODE_CBC.
370  *
371  * \return              The cipher information structure associated with the
372  *                      given \p cipher_id.
373  * \return              \c NULL if the associated cipher information is not found.
374  */
375 const mbedtls_cipher_info_t *mbedtls_cipher_info_from_values( const mbedtls_cipher_id_t cipher_id,
376                                               int key_bitlen,
377                                               const mbedtls_cipher_mode_t mode );
378 
379 /**
380  * \brief               This function initializes a \p cipher_context as NONE.
381  *
382  * \param ctx           The context to be initialized. This must not be \c NULL.
383  */
384 void mbedtls_cipher_init( mbedtls_cipher_context_t *ctx );
385 
386 /**
387  * \brief               This function frees and clears the cipher-specific
388  *                      context of \p ctx. Freeing \p ctx itself remains the
389  *                      responsibility of the caller.
390  *
391  * \param ctx           The context to be freed. If this is \c NULL, the
392  *                      function has no effect, otherwise this must point to an
393  *                      initialized context.
394  */
395 void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx );
396 
397 
398 /**
399  * \brief               This function initializes and fills the cipher-context
400  *                      structure with the appropriate values. It also clears
401  *                      the structure.
402  *
403  * \param ctx           The context to initialize. This must be initialized.
404  * \param cipher_info   The cipher to use.
405  *
406  * \return              \c 0 on success.
407  * \return              #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on
408  *                      parameter-verification failure.
409  * \return              #MBEDTLS_ERR_CIPHER_ALLOC_FAILED if allocation of the
410  *                      cipher-specific context fails.
411  *
412  * \internal Currently, the function also clears the structure.
413  * In future versions, the caller will be required to call
414  * mbedtls_cipher_init() on the structure first.
415  */
416 int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx,
417                           const mbedtls_cipher_info_t *cipher_info );
418 
419 /**
420  * \brief        This function returns the block size of the given cipher.
421  *
422  * \param ctx    The context of the cipher. This must be initialized.
423  *
424  * \return       The block size of the underlying cipher.
425  * \return       \c 0 if \p ctx has not been initialized.
426  */
mbedtls_cipher_get_block_size(const mbedtls_cipher_context_t * ctx)427 static inline unsigned int mbedtls_cipher_get_block_size(
428     const mbedtls_cipher_context_t *ctx )
429 {
430     MBEDTLS_INTERNAL_VALIDATE_RET( ctx != NULL, 0 );
431     if( ctx->cipher_info == NULL )
432         return 0;
433 
434     return ctx->cipher_info->block_size;
435 }
436 
437 /**
438  * \brief        This function returns the mode of operation for
439  *               the cipher. For example, MBEDTLS_MODE_CBC.
440  *
441  * \param ctx    The context of the cipher. This must be initialized.
442  *
443  * \return       The mode of operation.
444  * \return       #MBEDTLS_MODE_NONE if \p ctx has not been initialized.
445  */
mbedtls_cipher_get_cipher_mode(const mbedtls_cipher_context_t * ctx)446 static inline mbedtls_cipher_mode_t mbedtls_cipher_get_cipher_mode(
447     const mbedtls_cipher_context_t *ctx )
448 {
449     MBEDTLS_INTERNAL_VALIDATE_RET( ctx != NULL, MBEDTLS_MODE_NONE );
450     if( ctx->cipher_info == NULL )
451         return MBEDTLS_MODE_NONE;
452 
453     return ctx->cipher_info->mode;
454 }
455 
456 /**
457  * \brief       This function returns the size of the IV or nonce
458  *              of the cipher, in Bytes.
459  *
460  * \param ctx   The context of the cipher. This must be initialized.
461  *
462  * \return      The recommended IV size if no IV has been set.
463  * \return      \c 0 for ciphers not using an IV or a nonce.
464  * \return      The actual size if an IV has been set.
465  */
mbedtls_cipher_get_iv_size(const mbedtls_cipher_context_t * ctx)466 static inline int mbedtls_cipher_get_iv_size(
467     const mbedtls_cipher_context_t *ctx )
468 {
469     MBEDTLS_INTERNAL_VALIDATE_RET( ctx != NULL, 0 );
470     if( ctx->cipher_info == NULL )
471         return 0;
472 
473     if( ctx->iv_size != 0 )
474         return (int) ctx->iv_size;
475 
476     return (int) ctx->cipher_info->iv_size;
477 }
478 
479 /**
480  * \brief               This function returns the type of the given cipher.
481  *
482  * \param ctx           The context of the cipher. This must be initialized.
483  *
484  * \return              The type of the cipher.
485  * \return              #MBEDTLS_CIPHER_NONE if \p ctx has not been initialized.
486  */
mbedtls_cipher_get_type(const mbedtls_cipher_context_t * ctx)487 static inline mbedtls_cipher_type_t mbedtls_cipher_get_type(
488     const mbedtls_cipher_context_t *ctx )
489 {
490     MBEDTLS_INTERNAL_VALIDATE_RET(
491         ctx != NULL, MBEDTLS_CIPHER_NONE );
492     if( ctx->cipher_info == NULL )
493         return MBEDTLS_CIPHER_NONE;
494 
495     return ctx->cipher_info->type;
496 }
497 
498 /**
499  * \brief               This function returns the name of the given cipher
500  *                      as a string.
501  *
502  * \param ctx           The context of the cipher. This must be initialized.
503  *
504  * \return              The name of the cipher.
505  * \return              NULL if \p ctx has not been not initialized.
506  */
mbedtls_cipher_get_name(const mbedtls_cipher_context_t * ctx)507 static inline const char *mbedtls_cipher_get_name(
508     const mbedtls_cipher_context_t *ctx )
509 {
510     MBEDTLS_INTERNAL_VALIDATE_RET( ctx != NULL, 0 );
511     if( ctx->cipher_info == NULL )
512         return 0;
513 
514     return ctx->cipher_info->name;
515 }
516 
517 /**
518  * \brief               This function returns the key length of the cipher.
519  *
520  * \param ctx           The context of the cipher. This must be initialized.
521  *
522  * \return              The key length of the cipher in bits.
523  * \return              #MBEDTLS_KEY_LENGTH_NONE if ctx \p has not been
524  *                      initialized.
525  */
mbedtls_cipher_get_key_bitlen(const mbedtls_cipher_context_t * ctx)526 static inline int mbedtls_cipher_get_key_bitlen(
527     const mbedtls_cipher_context_t *ctx )
528 {
529     MBEDTLS_INTERNAL_VALIDATE_RET(
530         ctx != NULL, MBEDTLS_KEY_LENGTH_NONE );
531     if( ctx->cipher_info == NULL )
532         return MBEDTLS_KEY_LENGTH_NONE;
533 
534     return (int) ctx->cipher_info->key_bitlen;
535 }
536 
537 /**
538  * \brief          This function returns the operation of the given cipher.
539  *
540  * \param ctx      The context of the cipher. This must be initialized.
541  *
542  * \return         The type of operation: #MBEDTLS_ENCRYPT or #MBEDTLS_DECRYPT.
543  * \return         #MBEDTLS_OPERATION_NONE if \p ctx has not been initialized.
544  */
mbedtls_cipher_get_operation(const mbedtls_cipher_context_t * ctx)545 static inline mbedtls_operation_t mbedtls_cipher_get_operation(
546     const mbedtls_cipher_context_t *ctx )
547 {
548     MBEDTLS_INTERNAL_VALIDATE_RET(
549         ctx != NULL, MBEDTLS_OPERATION_NONE );
550     if( ctx->cipher_info == NULL )
551         return MBEDTLS_OPERATION_NONE;
552 
553     return ctx->operation;
554 }
555 
556 /**
557  * \brief               This function sets the key to use with the given context.
558  *
559  * \param ctx           The generic cipher context. This must be initialized and
560  *                      bound to a cipher information structure.
561  * \param key           The key to use. This must be a readable buffer of at
562  *                      least \p key_bitlen Bits.
563  * \param key_bitlen    The key length to use, in Bits.
564  * \param operation     The operation that the key will be used for:
565  *                      #MBEDTLS_ENCRYPT or #MBEDTLS_DECRYPT.
566  *
567  * \return              \c 0 on success.
568  * \return              #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on
569  *                      parameter-verification failure.
570  * \return              A cipher-specific error code on failure.
571  */
572 int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx,
573                            const unsigned char *key,
574                            int key_bitlen,
575                            const mbedtls_operation_t operation );
576 
577 #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
578 /**
579  * \brief               This function sets the padding mode, for cipher modes
580  *                      that use padding.
581  *
582  *                      The default passing mode is PKCS7 padding.
583  *
584  * \param ctx           The generic cipher context. This must be initialized and
585  *                      bound to a cipher information structure.
586  * \param mode          The padding mode.
587  *
588  * \return              \c 0 on success.
589  * \return              #MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE
590  *                      if the selected padding mode is not supported.
591  * \return              #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if the cipher mode
592  *                      does not support padding.
593  */
594 int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx,
595                                      mbedtls_cipher_padding_t mode );
596 #endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */
597 
598 /**
599  * \brief           This function sets the initialization vector (IV)
600  *                  or nonce.
601  *
602  * \note            Some ciphers do not use IVs nor nonce. For these
603  *                  ciphers, this function has no effect.
604  *
605  * \param ctx       The generic cipher context. This must be initialized and
606  *                  bound to a cipher information structure.
607  * \param iv        The IV to use, or NONCE_COUNTER for CTR-mode ciphers. This
608  *                  must be a readable buffer of at least \p iv_len Bytes.
609  * \param iv_len    The IV length for ciphers with variable-size IV.
610  *                  This parameter is discarded by ciphers with fixed-size IV.
611  *
612  * \return          \c 0 on success.
613  * \return          #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on
614  *                  parameter-verification failure.
615  */
616 int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx,
617                            const unsigned char *iv,
618                            size_t iv_len );
619 
620 /**
621  * \brief         This function resets the cipher state.
622  *
623  * \param ctx     The generic cipher context. This must be initialized.
624  *
625  * \return        \c 0 on success.
626  * \return        #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on
627  *                parameter-verification failure.
628  */
629 int mbedtls_cipher_reset( mbedtls_cipher_context_t *ctx );
630 
631 #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C)
632 /**
633  * \brief               This function adds additional data for AEAD ciphers.
634  *                      Currently supported with GCM and ChaCha20+Poly1305.
635  *                      This must be called exactly once, after
636  *                      mbedtls_cipher_reset().
637  *
638  * \param ctx           The generic cipher context. This must be initialized.
639  * \param ad            The additional data to use. This must be a readable
640  *                      buffer of at least \p ad_len Bytes.
641  * \param ad_len        the Length of \p ad Bytes.
642  *
643  * \return              \c 0 on success.
644  * \return              A specific error code on failure.
645  */
646 int mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx,
647                       const unsigned char *ad, size_t ad_len );
648 #endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */
649 
650 /**
651  * \brief               The generic cipher update function. It encrypts or
652  *                      decrypts using the given cipher context. Writes as
653  *                      many block-sized blocks of data as possible to output.
654  *                      Any data that cannot be written immediately is either
655  *                      added to the next block, or flushed when
656  *                      mbedtls_cipher_finish() is called.
657  *                      Exception: For MBEDTLS_MODE_ECB, expects a single block
658  *                      in size. For example, 16 Bytes for AES.
659  *
660  * \note                If the underlying cipher is used in GCM mode, all calls
661  *                      to this function, except for the last one before
662  *                      mbedtls_cipher_finish(), must have \p ilen as a
663  *                      multiple of the block size of the cipher.
664  *
665  * \param ctx           The generic cipher context. This must be initialized and
666  *                      bound to a key.
667  * \param input         The buffer holding the input data. This must be a
668  *                      readable buffer of at least \p ilen Bytes.
669  * \param ilen          The length of the input data.
670  * \param output        The buffer for the output data. This must be able to
671  *                      hold at least `ilen + block_size`. This must not be the
672  *                      same buffer as \p input.
673  * \param olen          The length of the output data, to be updated with the
674  *                      actual number of Bytes written. This must not be
675  *                      \c NULL.
676  *
677  * \return              \c 0 on success.
678  * \return              #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on
679  *                      parameter-verification failure.
680  * \return              #MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE on an
681  *                      unsupported mode for a cipher.
682  * \return              A cipher-specific error code on failure.
683  */
684 int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *input,
685                    size_t ilen, unsigned char *output, size_t *olen );
686 
687 /**
688  * \brief               The generic cipher finalization function. If data still
689  *                      needs to be flushed from an incomplete block, the data
690  *                      contained in it is padded to the size of
691  *                      the last block, and written to the \p output buffer.
692  *
693  * \param ctx           The generic cipher context. This must be initialized and
694  *                      bound to a key.
695  * \param output        The buffer to write data to. This needs to be a writable
696  *                      buffer of at least \p block_size Bytes.
697  * \param olen          The length of the data written to the \p output buffer.
698  *                      This may not be \c NULL.
699  *
700  * \return              \c 0 on success.
701  * \return              #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on
702  *                      parameter-verification failure.
703  * \return              #MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED on decryption
704  *                      expecting a full block but not receiving one.
705  * \return              #MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding
706  *                      while decrypting.
707  * \return              A cipher-specific error code on failure.
708  */
709 int mbedtls_cipher_finish( mbedtls_cipher_context_t *ctx,
710                    unsigned char *output, size_t *olen );
711 
712 #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C)
713 /**
714  * \brief               This function writes a tag for AEAD ciphers.
715  *                      Currently supported with GCM and ChaCha20+Poly1305.
716  *                      This must be called after mbedtls_cipher_finish().
717  *
718  * \param ctx           The generic cipher context. This must be initialized,
719  *                      bound to a key, and have just completed a cipher
720  *                      operation through mbedtls_cipher_finish() the tag for
721  *                      which should be written.
722  * \param tag           The buffer to write the tag to. This must be a writable
723  *                      buffer of at least \p tag_len Bytes.
724  * \param tag_len       The length of the tag to write.
725  *
726  * \return              \c 0 on success.
727  * \return              A specific error code on failure.
728  */
729 int mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx,
730                       unsigned char *tag, size_t tag_len );
731 
732 /**
733  * \brief               This function checks the tag for AEAD ciphers.
734  *                      Currently supported with GCM and ChaCha20+Poly1305.
735  *                      This must be called after mbedtls_cipher_finish().
736  *
737  * \param ctx           The generic cipher context. This must be initialized.
738  * \param tag           The buffer holding the tag. This must be a readable
739  *                      buffer of at least \p tag_len Bytes.
740  * \param tag_len       The length of the tag to check.
741  *
742  * \return              \c 0 on success.
743  * \return              A specific error code on failure.
744  */
745 int mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx,
746                       const unsigned char *tag, size_t tag_len );
747 #endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */
748 
749 /**
750  * \brief               The generic all-in-one encryption/decryption function,
751  *                      for all ciphers except AEAD constructs.
752  *
753  * \param ctx           The generic cipher context. This must be initialized.
754  * \param iv            The IV to use, or NONCE_COUNTER for CTR-mode ciphers.
755  *                      This must be a readable buffer of at least \p iv_len
756  *                      Bytes.
757  * \param iv_len        The IV length for ciphers with variable-size IV.
758  *                      This parameter is discarded by ciphers with fixed-size
759  *                      IV.
760  * \param input         The buffer holding the input data. This must be a
761  *                      readable buffer of at least \p ilen Bytes.
762  * \param ilen          The length of the input data in Bytes.
763  * \param output        The buffer for the output data. This must be able to
764  *                      hold at least `ilen + block_size`. This must not be the
765  *                      same buffer as \p input.
766  * \param olen          The length of the output data, to be updated with the
767  *                      actual number of Bytes written. This must not be
768  *                      \c NULL.
769  *
770  * \note                Some ciphers do not use IVs nor nonce. For these
771  *                      ciphers, use \p iv = NULL and \p iv_len = 0.
772  *
773  * \return              \c 0 on success.
774  * \return              #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on
775  *                      parameter-verification failure.
776  * \return              #MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED on decryption
777  *                      expecting a full block but not receiving one.
778  * \return              #MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding
779  *                      while decrypting.
780  * \return              A cipher-specific error code on failure.
781  */
782 int mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx,
783                   const unsigned char *iv, size_t iv_len,
784                   const unsigned char *input, size_t ilen,
785                   unsigned char *output, size_t *olen );
786 
787 #if defined(MBEDTLS_CIPHER_MODE_AEAD)
788 /**
789  * \brief               The generic autenticated encryption (AEAD) function.
790  *
791  * \param ctx           The generic cipher context. This must be initialized and
792  *                      bound to a key.
793  * \param iv            The IV to use, or NONCE_COUNTER for CTR-mode ciphers.
794  *                      This must be a readable buffer of at least \p iv_len
795  *                      Bytes.
796  * \param iv_len        The IV length for ciphers with variable-size IV.
797  *                      This parameter is discarded by ciphers with fixed-size IV.
798  * \param ad            The additional data to authenticate. This must be a
799  *                      readable buffer of at least \p ad_len Bytes.
800  * \param ad_len        The length of \p ad.
801  * \param input         The buffer holding the input data. This must be a
802  *                      readable buffer of at least \p ilen Bytes.
803  * \param ilen          The length of the input data.
804  * \param output        The buffer for the output data. This must be able to
805  *                      hold at least \p ilen Bytes.
806  * \param olen          The length of the output data, to be updated with the
807  *                      actual number of Bytes written. This must not be
808  *                      \c NULL.
809  * \param tag           The buffer for the authentication tag. This must be a
810  *                      writable buffer of at least \p tag_len Bytes.
811  * \param tag_len       The desired length of the authentication tag.
812  *
813  * \return              \c 0 on success.
814  * \return              #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on
815  *                      parameter-verification failure.
816  * \return              A cipher-specific error code on failure.
817  */
818 int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx,
819                          const unsigned char *iv, size_t iv_len,
820                          const unsigned char *ad, size_t ad_len,
821                          const unsigned char *input, size_t ilen,
822                          unsigned char *output, size_t *olen,
823                          unsigned char *tag, size_t tag_len );
824 
825 /**
826  * \brief               The generic autenticated decryption (AEAD) function.
827  *
828  * \note                If the data is not authentic, then the output buffer
829  *                      is zeroed out to prevent the unauthentic plaintext being
830  *                      used, making this interface safer.
831  *
832  * \param ctx           The generic cipher context. This must be initialized and
833  *                      and bound to a key.
834  * \param iv            The IV to use, or NONCE_COUNTER for CTR-mode ciphers.
835  *                      This must be a readable buffer of at least \p iv_len
836  *                      Bytes.
837  * \param iv_len        The IV length for ciphers with variable-size IV.
838  *                      This parameter is discarded by ciphers with fixed-size IV.
839  * \param ad            The additional data to be authenticated. This must be a
840  *                      readable buffer of at least \p ad_len Bytes.
841  * \param ad_len        The length of \p ad.
842  * \param input         The buffer holding the input data. This must be a
843  *                      readable buffer of at least \p ilen Bytes.
844  * \param ilen          The length of the input data.
845  * \param output        The buffer for the output data.
846  *                      This must be able to hold at least \p ilen Bytes.
847  * \param olen          The length of the output data, to be updated with the
848  *                      actual number of Bytes written. This must not be
849  *                      \c NULL.
850  * \param tag           The buffer holding the authentication tag. This must be
851  *                      a readable buffer of at least \p tag_len Bytes.
852  * \param tag_len       The length of the authentication tag.
853  *
854  * \return              \c 0 on success.
855  * \return              #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on
856  *                      parameter-verification failure.
857  * \return              #MBEDTLS_ERR_CIPHER_AUTH_FAILED if data is not authentic.
858  * \return              A cipher-specific error code on failure.
859  */
860 int mbedtls_cipher_auth_decrypt( mbedtls_cipher_context_t *ctx,
861                          const unsigned char *iv, size_t iv_len,
862                          const unsigned char *ad, size_t ad_len,
863                          const unsigned char *input, size_t ilen,
864                          unsigned char *output, size_t *olen,
865                          const unsigned char *tag, size_t tag_len );
866 #endif /* MBEDTLS_CIPHER_MODE_AEAD */
867 
868 #ifdef __cplusplus
869 }
870 #endif
871 
872 #endif /* MBEDTLS_CIPHER_H */
873