Fix for x86_64 build fail
[platform/upstream/connectedhomeip.git] / third_party / mbedtls / repo / library / cipher.c
1 /**
2  * \file cipher.c
3  *
4  * \brief Generic cipher wrapper for mbed TLS
5  *
6  * \author Adriaan de Jong <dejong@fox-it.com>
7  *
8  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
9  *  SPDX-License-Identifier: Apache-2.0
10  *
11  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
12  *  not use this file except in compliance with the License.
13  *  You may obtain a copy of the License at
14  *
15  *  http://www.apache.org/licenses/LICENSE-2.0
16  *
17  *  Unless required by applicable law or agreed to in writing, software
18  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
19  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  *  See the License for the specific language governing permissions and
21  *  limitations under the License.
22  *
23  *  This file is part of mbed TLS (https://tls.mbed.org)
24  */
25
26 #if !defined(MBEDTLS_CONFIG_FILE)
27 #include "mbedtls/config.h"
28 #else
29 #include MBEDTLS_CONFIG_FILE
30 #endif
31
32 #if defined(MBEDTLS_CIPHER_C)
33
34 #include "mbedtls/cipher.h"
35 #include "mbedtls/cipher_internal.h"
36 #include "mbedtls/platform_util.h"
37
38 #include <stdlib.h>
39 #include <string.h>
40
41 #if defined(MBEDTLS_CHACHAPOLY_C)
42 #include "mbedtls/chachapoly.h"
43 #endif
44
45 #if defined(MBEDTLS_GCM_C)
46 #include "mbedtls/gcm.h"
47 #endif
48
49 #if defined(MBEDTLS_CCM_C)
50 #include "mbedtls/ccm.h"
51 #endif
52
53 #if defined(MBEDTLS_CHACHA20_C)
54 #include "mbedtls/chacha20.h"
55 #endif
56
57 #if defined(MBEDTLS_CMAC_C)
58 #include "mbedtls/cmac.h"
59 #endif
60
61 #if defined(MBEDTLS_USE_PSA_CRYPTO)
62 #include "psa/crypto.h"
63 #include "mbedtls/psa_util.h"
64 #endif /* MBEDTLS_USE_PSA_CRYPTO */
65
66 #if defined(MBEDTLS_NIST_KW_C)
67 #include "mbedtls/nist_kw.h"
68 #endif
69
70 #if defined(MBEDTLS_PLATFORM_C)
71 #include "mbedtls/platform.h"
72 #else
73 #define mbedtls_calloc calloc
74 #define mbedtls_free   free
75 #endif
76
77 #define CIPHER_VALIDATE_RET( cond )    \
78     MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA )
79 #define CIPHER_VALIDATE( cond )        \
80     MBEDTLS_INTERNAL_VALIDATE( cond )
81
82 #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C)
83 /* Compare the contents of two buffers in constant time.
84  * Returns 0 if the contents are bitwise identical, otherwise returns
85  * a non-zero value.
86  * This is currently only used by GCM and ChaCha20+Poly1305.
87  */
88 static int mbedtls_constant_time_memcmp( const void *v1, const void *v2,
89                                          size_t len )
90 {
91     const unsigned char *p1 = (const unsigned char*) v1;
92     const unsigned char *p2 = (const unsigned char*) v2;
93     size_t i;
94     unsigned char diff;
95
96     for( diff = 0, i = 0; i < len; i++ )
97         diff |= p1[i] ^ p2[i];
98
99     return( (int)diff );
100 }
101 #endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */
102
103 static int supported_init = 0;
104
105 const int *mbedtls_cipher_list( void )
106 {
107     const mbedtls_cipher_definition_t *def;
108     int *type;
109
110     if( ! supported_init )
111     {
112         def = mbedtls_cipher_definitions;
113         type = mbedtls_cipher_supported;
114
115         while( def->type != 0 )
116             *type++ = (*def++).type;
117
118         *type = 0;
119
120         supported_init = 1;
121     }
122
123     return( mbedtls_cipher_supported );
124 }
125
126 const mbedtls_cipher_info_t *mbedtls_cipher_info_from_type(
127     const mbedtls_cipher_type_t cipher_type )
128 {
129     const mbedtls_cipher_definition_t *def;
130
131     for( def = mbedtls_cipher_definitions; def->info != NULL; def++ )
132         if( def->type == cipher_type )
133             return( def->info );
134
135     return( NULL );
136 }
137
138 const mbedtls_cipher_info_t *mbedtls_cipher_info_from_string(
139     const char *cipher_name )
140 {
141     const mbedtls_cipher_definition_t *def;
142
143     if( NULL == cipher_name )
144         return( NULL );
145
146     for( def = mbedtls_cipher_definitions; def->info != NULL; def++ )
147         if( !  strcmp( def->info->name, cipher_name ) )
148             return( def->info );
149
150     return( NULL );
151 }
152
153 const mbedtls_cipher_info_t *mbedtls_cipher_info_from_values(
154     const mbedtls_cipher_id_t cipher_id,
155     int key_bitlen,
156     const mbedtls_cipher_mode_t mode )
157 {
158     const mbedtls_cipher_definition_t *def;
159
160     for( def = mbedtls_cipher_definitions; def->info != NULL; def++ )
161         if( def->info->base->cipher == cipher_id &&
162             def->info->key_bitlen == (unsigned) key_bitlen &&
163             def->info->mode == mode )
164             return( def->info );
165
166     return( NULL );
167 }
168
169 void mbedtls_cipher_init( mbedtls_cipher_context_t *ctx )
170 {
171     CIPHER_VALIDATE( ctx != NULL );
172     memset( ctx, 0, sizeof( mbedtls_cipher_context_t ) );
173 }
174
175 void mbedtls_cipher_free( mbedtls_cipher_context_t *ctx )
176 {
177     if( ctx == NULL )
178         return;
179
180 #if defined(MBEDTLS_USE_PSA_CRYPTO)
181     if( ctx->psa_enabled == 1 )
182     {
183         if( ctx->cipher_ctx != NULL )
184         {
185             mbedtls_cipher_context_psa * const cipher_psa =
186                 (mbedtls_cipher_context_psa *) ctx->cipher_ctx;
187
188             if( cipher_psa->slot_state == MBEDTLS_CIPHER_PSA_KEY_OWNED )
189             {
190                 /* xxx_free() doesn't allow to return failures. */
191                 (void) psa_destroy_key( cipher_psa->slot );
192             }
193
194             mbedtls_platform_zeroize( cipher_psa, sizeof( *cipher_psa ) );
195             mbedtls_free( cipher_psa );
196         }
197
198         mbedtls_platform_zeroize( ctx, sizeof(mbedtls_cipher_context_t) );
199         return;
200     }
201 #endif /* MBEDTLS_USE_PSA_CRYPTO */
202
203 #if defined(MBEDTLS_CMAC_C)
204     if( ctx->cmac_ctx )
205     {
206        mbedtls_platform_zeroize( ctx->cmac_ctx,
207                                  sizeof( mbedtls_cmac_context_t ) );
208        mbedtls_free( ctx->cmac_ctx );
209     }
210 #endif
211
212     if( ctx->cipher_ctx )
213         ctx->cipher_info->base->ctx_free_func( ctx->cipher_ctx );
214
215     mbedtls_platform_zeroize( ctx, sizeof(mbedtls_cipher_context_t) );
216 }
217
218 int mbedtls_cipher_setup( mbedtls_cipher_context_t *ctx,
219                           const mbedtls_cipher_info_t *cipher_info )
220 {
221     CIPHER_VALIDATE_RET( ctx != NULL );
222     if( cipher_info == NULL )
223         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
224
225     memset( ctx, 0, sizeof( mbedtls_cipher_context_t ) );
226
227     if( NULL == ( ctx->cipher_ctx = cipher_info->base->ctx_alloc_func() ) )
228         return( MBEDTLS_ERR_CIPHER_ALLOC_FAILED );
229
230     ctx->cipher_info = cipher_info;
231
232 #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
233     /*
234      * Ignore possible errors caused by a cipher mode that doesn't use padding
235      */
236 #if defined(MBEDTLS_CIPHER_PADDING_PKCS7)
237     (void) mbedtls_cipher_set_padding_mode( ctx, MBEDTLS_PADDING_PKCS7 );
238 #else
239     (void) mbedtls_cipher_set_padding_mode( ctx, MBEDTLS_PADDING_NONE );
240 #endif
241 #endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */
242
243     return( 0 );
244 }
245
246 #if defined(MBEDTLS_USE_PSA_CRYPTO)
247 int mbedtls_cipher_setup_psa( mbedtls_cipher_context_t *ctx,
248                               const mbedtls_cipher_info_t *cipher_info,
249                               size_t taglen )
250 {
251     psa_algorithm_t alg;
252     mbedtls_cipher_context_psa *cipher_psa;
253
254     if( NULL == cipher_info || NULL == ctx )
255         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
256
257     /* Check that the underlying cipher mode and cipher type are
258      * supported by the underlying PSA Crypto implementation. */
259     alg = mbedtls_psa_translate_cipher_mode( cipher_info->mode, taglen );
260     if( alg == 0 )
261         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
262     if( mbedtls_psa_translate_cipher_type( cipher_info->type ) == 0 )
263         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
264
265     memset( ctx, 0, sizeof( mbedtls_cipher_context_t ) );
266
267     cipher_psa = mbedtls_calloc( 1, sizeof(mbedtls_cipher_context_psa ) );
268     if( cipher_psa == NULL )
269         return( MBEDTLS_ERR_CIPHER_ALLOC_FAILED );
270     cipher_psa->alg  = alg;
271     ctx->cipher_ctx  = cipher_psa;
272     ctx->cipher_info = cipher_info;
273     ctx->psa_enabled = 1;
274     return( 0 );
275 }
276 #endif /* MBEDTLS_USE_PSA_CRYPTO */
277
278 int mbedtls_cipher_setkey( mbedtls_cipher_context_t *ctx,
279                            const unsigned char *key,
280                            int key_bitlen,
281                            const mbedtls_operation_t operation )
282 {
283     CIPHER_VALIDATE_RET( ctx != NULL );
284     CIPHER_VALIDATE_RET( key != NULL );
285     CIPHER_VALIDATE_RET( operation == MBEDTLS_ENCRYPT ||
286                          operation == MBEDTLS_DECRYPT );
287     if( ctx->cipher_info == NULL )
288         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
289
290 #if defined(MBEDTLS_USE_PSA_CRYPTO)
291     if( ctx->psa_enabled == 1 )
292     {
293         mbedtls_cipher_context_psa * const cipher_psa =
294             (mbedtls_cipher_context_psa *) ctx->cipher_ctx;
295
296         size_t const key_bytelen = ( (size_t) key_bitlen + 7 ) / 8;
297
298         psa_status_t status;
299         psa_key_type_t key_type;
300         psa_key_usage_t key_usage;
301         psa_key_policy_t key_policy;
302
303         /* PSA Crypto API only accepts byte-aligned keys. */
304         if( key_bitlen % 8 != 0 )
305             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
306
307         /* Don't allow keys to be set multiple times. */
308         if( cipher_psa->slot_state != MBEDTLS_CIPHER_PSA_KEY_UNSET )
309             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
310
311         key_type = mbedtls_psa_translate_cipher_type(
312             ctx->cipher_info->type );
313         if( key_type == 0 )
314             return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
315
316         /* Allocate a key slot to use. */
317         status = psa_allocate_key( &cipher_psa->slot );
318         if( status != PSA_SUCCESS )
319             return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED );
320
321         /* Indicate that we own the key slot and need to
322          * destroy it in mbedtls_cipher_free(). */
323         cipher_psa->slot_state = MBEDTLS_CIPHER_PSA_KEY_OWNED;
324
325         /* From that point on, the responsibility for destroying the
326          * key slot is on mbedtls_cipher_free(). This includes the case
327          * where the policy setup or key import below fail, as
328          * mbedtls_cipher_free() needs to be called in any case. */
329
330         /* Setup policy for the new key slot. */
331         key_policy = psa_key_policy_init();
332
333         /* Mbed TLS' cipher layer doesn't enforce the mode of operation
334          * (encrypt vs. decrypt): it is possible to setup a key for encryption
335          * and use it for AEAD decryption. Until tests relying on this
336          * are changed, allow any usage in PSA. */
337         /* key_usage = mbedtls_psa_translate_cipher_operation( operation ); */
338         key_usage = PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT;
339         psa_key_policy_set_usage( &key_policy, key_usage, cipher_psa->alg );
340         status = psa_set_key_policy( cipher_psa->slot, &key_policy );
341         if( status != PSA_SUCCESS )
342             return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED );
343
344         /* Populate new key slot. */
345         status = psa_import_key( cipher_psa->slot,
346                                  key_type, key, key_bytelen );
347         if( status != PSA_SUCCESS )
348             return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED );
349
350         ctx->key_bitlen = key_bitlen;
351         ctx->operation = operation;
352         return( 0 );
353     }
354 #endif /* MBEDTLS_USE_PSA_CRYPTO */
355
356     if( ( ctx->cipher_info->flags & MBEDTLS_CIPHER_VARIABLE_KEY_LEN ) == 0 &&
357         (int) ctx->cipher_info->key_bitlen != key_bitlen )
358     {
359         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
360     }
361
362     ctx->key_bitlen = key_bitlen;
363     ctx->operation = operation;
364
365     /*
366      * For OFB, CFB and CTR mode always use the encryption key schedule
367      */
368     if( MBEDTLS_ENCRYPT == operation ||
369         MBEDTLS_MODE_CFB == ctx->cipher_info->mode ||
370         MBEDTLS_MODE_OFB == ctx->cipher_info->mode ||
371         MBEDTLS_MODE_CTR == ctx->cipher_info->mode )
372     {
373         return( ctx->cipher_info->base->setkey_enc_func( ctx->cipher_ctx, key,
374                                                          ctx->key_bitlen ) );
375     }
376
377     if( MBEDTLS_DECRYPT == operation )
378         return( ctx->cipher_info->base->setkey_dec_func( ctx->cipher_ctx, key,
379                                                          ctx->key_bitlen ) );
380
381     return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
382 }
383
384 int mbedtls_cipher_set_iv( mbedtls_cipher_context_t *ctx,
385                            const unsigned char *iv,
386                            size_t iv_len )
387 {
388     size_t actual_iv_size;
389
390     CIPHER_VALIDATE_RET( ctx != NULL );
391     CIPHER_VALIDATE_RET( iv_len == 0 || iv != NULL );
392     if( ctx->cipher_info == NULL )
393         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
394 #if defined(MBEDTLS_USE_PSA_CRYPTO)
395     if( ctx->psa_enabled == 1 )
396     {
397         /* While PSA Crypto has an API for multipart
398          * operations, we currently don't make it
399          * accessible through the cipher layer. */
400         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
401     }
402 #endif /* MBEDTLS_USE_PSA_CRYPTO */
403
404     /* avoid buffer overflow in ctx->iv */
405     if( iv_len > MBEDTLS_MAX_IV_LENGTH )
406         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
407
408     if( ( ctx->cipher_info->flags & MBEDTLS_CIPHER_VARIABLE_IV_LEN ) != 0 )
409         actual_iv_size = iv_len;
410     else
411     {
412         actual_iv_size = ctx->cipher_info->iv_size;
413
414         /* avoid reading past the end of input buffer */
415         if( actual_iv_size > iv_len )
416             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
417     }
418
419 #if defined(MBEDTLS_CHACHA20_C)
420     if ( ctx->cipher_info->type == MBEDTLS_CIPHER_CHACHA20 )
421     {
422         if ( 0 != mbedtls_chacha20_starts( (mbedtls_chacha20_context*)ctx->cipher_ctx,
423                                            iv,
424                                            0U ) ) /* Initial counter value */
425         {
426             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
427         }
428     }
429 #endif
430
431     if ( actual_iv_size != 0 )
432     {
433         memcpy( ctx->iv, iv, actual_iv_size );
434         ctx->iv_size = actual_iv_size;
435     }
436
437     return( 0 );
438 }
439
440 int mbedtls_cipher_reset( mbedtls_cipher_context_t *ctx )
441 {
442     CIPHER_VALIDATE_RET( ctx != NULL );
443     if( ctx->cipher_info == NULL )
444         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
445
446 #if defined(MBEDTLS_USE_PSA_CRYPTO)
447     if( ctx->psa_enabled == 1 )
448     {
449         /* We don't support resetting PSA-based
450          * cipher contexts, yet. */
451         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
452     }
453 #endif /* MBEDTLS_USE_PSA_CRYPTO */
454
455     ctx->unprocessed_len = 0;
456
457     return( 0 );
458 }
459
460 #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C)
461 int mbedtls_cipher_update_ad( mbedtls_cipher_context_t *ctx,
462                       const unsigned char *ad, size_t ad_len )
463 {
464     CIPHER_VALIDATE_RET( ctx != NULL );
465     CIPHER_VALIDATE_RET( ad_len == 0 || ad != NULL );
466     if( ctx->cipher_info == NULL )
467         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
468
469 #if defined(MBEDTLS_USE_PSA_CRYPTO)
470     if( ctx->psa_enabled == 1 )
471     {
472         /* While PSA Crypto has an API for multipart
473          * operations, we currently don't make it
474          * accessible through the cipher layer. */
475         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
476     }
477 #endif /* MBEDTLS_USE_PSA_CRYPTO */
478
479 #if defined(MBEDTLS_GCM_C)
480     if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )
481     {
482         return( mbedtls_gcm_starts( (mbedtls_gcm_context *) ctx->cipher_ctx, ctx->operation,
483                                     ctx->iv, ctx->iv_size, ad, ad_len ) );
484     }
485 #endif
486
487 #if defined(MBEDTLS_CHACHAPOLY_C)
488     if (MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )
489     {
490         int result;
491         mbedtls_chachapoly_mode_t mode;
492
493         mode = ( ctx->operation == MBEDTLS_ENCRYPT )
494                 ? MBEDTLS_CHACHAPOLY_ENCRYPT
495                 : MBEDTLS_CHACHAPOLY_DECRYPT;
496
497         result = mbedtls_chachapoly_starts( (mbedtls_chachapoly_context*) ctx->cipher_ctx,
498                                                         ctx->iv,
499                                                         mode );
500         if ( result != 0 )
501             return( result );
502
503         return( mbedtls_chachapoly_update_aad( (mbedtls_chachapoly_context*) ctx->cipher_ctx,
504                                                ad, ad_len ) );
505     }
506 #endif
507
508     return( 0 );
509 }
510 #endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */
511
512 int mbedtls_cipher_update( mbedtls_cipher_context_t *ctx, const unsigned char *input,
513                    size_t ilen, unsigned char *output, size_t *olen )
514 {
515     int ret;
516     size_t block_size;
517
518     CIPHER_VALIDATE_RET( ctx != NULL );
519     CIPHER_VALIDATE_RET( ilen == 0 || input != NULL );
520     CIPHER_VALIDATE_RET( output != NULL );
521     CIPHER_VALIDATE_RET( olen != NULL );
522     if( ctx->cipher_info == NULL )
523         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
524
525 #if defined(MBEDTLS_USE_PSA_CRYPTO)
526     if( ctx->psa_enabled == 1 )
527     {
528         /* While PSA Crypto has an API for multipart
529          * operations, we currently don't make it
530          * accessible through the cipher layer. */
531         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
532     }
533 #endif /* MBEDTLS_USE_PSA_CRYPTO */
534
535     *olen = 0;
536     block_size = mbedtls_cipher_get_block_size( ctx );
537
538     if( ctx->cipher_info->mode == MBEDTLS_MODE_ECB )
539     {
540         if( ilen != block_size )
541             return( MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED );
542
543         *olen = ilen;
544
545         if( 0 != ( ret = ctx->cipher_info->base->ecb_func( ctx->cipher_ctx,
546                     ctx->operation, input, output ) ) )
547         {
548             return( ret );
549         }
550
551         return( 0 );
552     }
553
554 #if defined(MBEDTLS_GCM_C)
555     if( ctx->cipher_info->mode == MBEDTLS_MODE_GCM )
556     {
557         *olen = ilen;
558         return( mbedtls_gcm_update( (mbedtls_gcm_context *) ctx->cipher_ctx, ilen, input,
559                                     output ) );
560     }
561 #endif
562
563 #if defined(MBEDTLS_CHACHAPOLY_C)
564     if ( ctx->cipher_info->type == MBEDTLS_CIPHER_CHACHA20_POLY1305 )
565     {
566         *olen = ilen;
567         return( mbedtls_chachapoly_update( (mbedtls_chachapoly_context*) ctx->cipher_ctx,
568                                            ilen, input, output ) );
569     }
570 #endif
571
572     if ( 0 == block_size )
573     {
574         return( MBEDTLS_ERR_CIPHER_INVALID_CONTEXT );
575     }
576
577     if( input == output &&
578        ( ctx->unprocessed_len != 0 || ilen % block_size ) )
579     {
580         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
581     }
582
583 #if defined(MBEDTLS_CIPHER_MODE_CBC)
584     if( ctx->cipher_info->mode == MBEDTLS_MODE_CBC )
585     {
586         size_t copy_len = 0;
587
588         /*
589          * If there is not enough data for a full block, cache it.
590          */
591         if( ( ctx->operation == MBEDTLS_DECRYPT && NULL != ctx->add_padding &&
592                 ilen <= block_size - ctx->unprocessed_len ) ||
593             ( ctx->operation == MBEDTLS_DECRYPT && NULL == ctx->add_padding &&
594                 ilen < block_size - ctx->unprocessed_len ) ||
595              ( ctx->operation == MBEDTLS_ENCRYPT &&
596                 ilen < block_size - ctx->unprocessed_len ) )
597         {
598             memcpy( &( ctx->unprocessed_data[ctx->unprocessed_len] ), input,
599                     ilen );
600
601             ctx->unprocessed_len += ilen;
602             return( 0 );
603         }
604
605         /*
606          * Process cached data first
607          */
608         if( 0 != ctx->unprocessed_len )
609         {
610             copy_len = block_size - ctx->unprocessed_len;
611
612             memcpy( &( ctx->unprocessed_data[ctx->unprocessed_len] ), input,
613                     copy_len );
614
615             if( 0 != ( ret = ctx->cipher_info->base->cbc_func( ctx->cipher_ctx,
616                     ctx->operation, block_size, ctx->iv,
617                     ctx->unprocessed_data, output ) ) )
618             {
619                 return( ret );
620             }
621
622             *olen += block_size;
623             output += block_size;
624             ctx->unprocessed_len = 0;
625
626             input += copy_len;
627             ilen -= copy_len;
628         }
629
630         /*
631          * Cache final, incomplete block
632          */
633         if( 0 != ilen )
634         {
635             if( 0 == block_size )
636             {
637                 return( MBEDTLS_ERR_CIPHER_INVALID_CONTEXT );
638             }
639
640             /* Encryption: only cache partial blocks
641              * Decryption w/ padding: always keep at least one whole block
642              * Decryption w/o padding: only cache partial blocks
643              */
644             copy_len = ilen % block_size;
645             if( copy_len == 0 &&
646                 ctx->operation == MBEDTLS_DECRYPT &&
647                 NULL != ctx->add_padding)
648             {
649                 copy_len = block_size;
650             }
651
652             memcpy( ctx->unprocessed_data, &( input[ilen - copy_len] ),
653                     copy_len );
654
655             ctx->unprocessed_len += copy_len;
656             ilen -= copy_len;
657         }
658
659         /*
660          * Process remaining full blocks
661          */
662         if( ilen )
663         {
664             if( 0 != ( ret = ctx->cipher_info->base->cbc_func( ctx->cipher_ctx,
665                     ctx->operation, ilen, ctx->iv, input, output ) ) )
666             {
667                 return( ret );
668             }
669
670             *olen += ilen;
671         }
672
673         return( 0 );
674     }
675 #endif /* MBEDTLS_CIPHER_MODE_CBC */
676
677 #if defined(MBEDTLS_CIPHER_MODE_CFB)
678     if( ctx->cipher_info->mode == MBEDTLS_MODE_CFB )
679     {
680         if( 0 != ( ret = ctx->cipher_info->base->cfb_func( ctx->cipher_ctx,
681                 ctx->operation, ilen, &ctx->unprocessed_len, ctx->iv,
682                 input, output ) ) )
683         {
684             return( ret );
685         }
686
687         *olen = ilen;
688
689         return( 0 );
690     }
691 #endif /* MBEDTLS_CIPHER_MODE_CFB */
692
693 #if defined(MBEDTLS_CIPHER_MODE_OFB)
694     if( ctx->cipher_info->mode == MBEDTLS_MODE_OFB )
695     {
696         if( 0 != ( ret = ctx->cipher_info->base->ofb_func( ctx->cipher_ctx,
697                 ilen, &ctx->unprocessed_len, ctx->iv, input, output ) ) )
698         {
699             return( ret );
700         }
701
702         *olen = ilen;
703
704         return( 0 );
705     }
706 #endif /* MBEDTLS_CIPHER_MODE_OFB */
707
708 #if defined(MBEDTLS_CIPHER_MODE_CTR)
709     if( ctx->cipher_info->mode == MBEDTLS_MODE_CTR )
710     {
711         if( 0 != ( ret = ctx->cipher_info->base->ctr_func( ctx->cipher_ctx,
712                 ilen, &ctx->unprocessed_len, ctx->iv,
713                 ctx->unprocessed_data, input, output ) ) )
714         {
715             return( ret );
716         }
717
718         *olen = ilen;
719
720         return( 0 );
721     }
722 #endif /* MBEDTLS_CIPHER_MODE_CTR */
723
724 #if defined(MBEDTLS_CIPHER_MODE_XTS)
725     if( ctx->cipher_info->mode == MBEDTLS_MODE_XTS )
726     {
727         if( ctx->unprocessed_len > 0 ) {
728             /* We can only process an entire data unit at a time. */
729             return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
730         }
731
732         ret = ctx->cipher_info->base->xts_func( ctx->cipher_ctx,
733                 ctx->operation, ilen, ctx->iv, input, output );
734         if( ret != 0 )
735         {
736             return( ret );
737         }
738
739         *olen = ilen;
740
741         return( 0 );
742     }
743 #endif /* MBEDTLS_CIPHER_MODE_XTS */
744
745 #if defined(MBEDTLS_CIPHER_MODE_STREAM)
746     if( ctx->cipher_info->mode == MBEDTLS_MODE_STREAM )
747     {
748         if( 0 != ( ret = ctx->cipher_info->base->stream_func( ctx->cipher_ctx,
749                                                     ilen, input, output ) ) )
750         {
751             return( ret );
752         }
753
754         *olen = ilen;
755
756         return( 0 );
757     }
758 #endif /* MBEDTLS_CIPHER_MODE_STREAM */
759
760     return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
761 }
762
763 #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
764 #if defined(MBEDTLS_CIPHER_PADDING_PKCS7)
765 /*
766  * PKCS7 (and PKCS5) padding: fill with ll bytes, with ll = padding_len
767  */
768 static void add_pkcs_padding( unsigned char *output, size_t output_len,
769         size_t data_len )
770 {
771     size_t padding_len = output_len - data_len;
772     unsigned char i;
773
774     for( i = 0; i < padding_len; i++ )
775         output[data_len + i] = (unsigned char) padding_len;
776 }
777
778 static int get_pkcs_padding( unsigned char *input, size_t input_len,
779         size_t *data_len )
780 {
781     size_t i, pad_idx;
782     unsigned char padding_len, bad = 0;
783
784     if( NULL == input || NULL == data_len )
785         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
786
787     padding_len = input[input_len - 1];
788     *data_len = input_len - padding_len;
789
790     /* Avoid logical || since it results in a branch */
791     bad |= padding_len > input_len;
792     bad |= padding_len == 0;
793
794     /* The number of bytes checked must be independent of padding_len,
795      * so pick input_len, which is usually 8 or 16 (one block) */
796     pad_idx = input_len - padding_len;
797     for( i = 0; i < input_len; i++ )
798         bad |= ( input[i] ^ padding_len ) * ( i >= pad_idx );
799
800     return( MBEDTLS_ERR_CIPHER_INVALID_PADDING * ( bad != 0 ) );
801 }
802 #endif /* MBEDTLS_CIPHER_PADDING_PKCS7 */
803
804 #if defined(MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS)
805 /*
806  * One and zeros padding: fill with 80 00 ... 00
807  */
808 static void add_one_and_zeros_padding( unsigned char *output,
809                                        size_t output_len, size_t data_len )
810 {
811     size_t padding_len = output_len - data_len;
812     unsigned char i = 0;
813
814     output[data_len] = 0x80;
815     for( i = 1; i < padding_len; i++ )
816         output[data_len + i] = 0x00;
817 }
818
819 static int get_one_and_zeros_padding( unsigned char *input, size_t input_len,
820                                       size_t *data_len )
821 {
822     size_t i;
823     unsigned char done = 0, prev_done, bad;
824
825     if( NULL == input || NULL == data_len )
826         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
827
828     bad = 0x80;
829     *data_len = 0;
830     for( i = input_len; i > 0; i-- )
831     {
832         prev_done = done;
833         done |= ( input[i - 1] != 0 );
834         *data_len |= ( i - 1 ) * ( done != prev_done );
835         bad ^= input[i - 1] * ( done != prev_done );
836     }
837
838     return( MBEDTLS_ERR_CIPHER_INVALID_PADDING * ( bad != 0 ) );
839
840 }
841 #endif /* MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS */
842
843 #if defined(MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN)
844 /*
845  * Zeros and len padding: fill with 00 ... 00 ll, where ll is padding length
846  */
847 static void add_zeros_and_len_padding( unsigned char *output,
848                                        size_t output_len, size_t data_len )
849 {
850     size_t padding_len = output_len - data_len;
851     unsigned char i = 0;
852
853     for( i = 1; i < padding_len; i++ )
854         output[data_len + i - 1] = 0x00;
855     output[output_len - 1] = (unsigned char) padding_len;
856 }
857
858 static int get_zeros_and_len_padding( unsigned char *input, size_t input_len,
859                                       size_t *data_len )
860 {
861     size_t i, pad_idx;
862     unsigned char padding_len, bad = 0;
863
864     if( NULL == input || NULL == data_len )
865         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
866
867     padding_len = input[input_len - 1];
868     *data_len = input_len - padding_len;
869
870     /* Avoid logical || since it results in a branch */
871     bad |= padding_len > input_len;
872     bad |= padding_len == 0;
873
874     /* The number of bytes checked must be independent of padding_len */
875     pad_idx = input_len - padding_len;
876     for( i = 0; i < input_len - 1; i++ )
877         bad |= input[i] * ( i >= pad_idx );
878
879     return( MBEDTLS_ERR_CIPHER_INVALID_PADDING * ( bad != 0 ) );
880 }
881 #endif /* MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN */
882
883 #if defined(MBEDTLS_CIPHER_PADDING_ZEROS)
884 /*
885  * Zero padding: fill with 00 ... 00
886  */
887 static void add_zeros_padding( unsigned char *output,
888                                size_t output_len, size_t data_len )
889 {
890     size_t i;
891
892     for( i = data_len; i < output_len; i++ )
893         output[i] = 0x00;
894 }
895
896 static int get_zeros_padding( unsigned char *input, size_t input_len,
897                               size_t *data_len )
898 {
899     size_t i;
900     unsigned char done = 0, prev_done;
901
902     if( NULL == input || NULL == data_len )
903         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
904
905     *data_len = 0;
906     for( i = input_len; i > 0; i-- )
907     {
908         prev_done = done;
909         done |= ( input[i-1] != 0 );
910         *data_len |= i * ( done != prev_done );
911     }
912
913     return( 0 );
914 }
915 #endif /* MBEDTLS_CIPHER_PADDING_ZEROS */
916
917 /*
918  * No padding: don't pad :)
919  *
920  * There is no add_padding function (check for NULL in mbedtls_cipher_finish)
921  * but a trivial get_padding function
922  */
923 static int get_no_padding( unsigned char *input, size_t input_len,
924                               size_t *data_len )
925 {
926     if( NULL == input || NULL == data_len )
927         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
928
929     *data_len = input_len;
930
931     return( 0 );
932 }
933 #endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */
934
935 int mbedtls_cipher_finish( mbedtls_cipher_context_t *ctx,
936                    unsigned char *output, size_t *olen )
937 {
938     CIPHER_VALIDATE_RET( ctx != NULL );
939     CIPHER_VALIDATE_RET( output != NULL );
940     CIPHER_VALIDATE_RET( olen != NULL );
941     if( ctx->cipher_info == NULL )
942         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
943
944 #if defined(MBEDTLS_USE_PSA_CRYPTO)
945     if( ctx->psa_enabled == 1 )
946     {
947         /* While PSA Crypto has an API for multipart
948          * operations, we currently don't make it
949          * accessible through the cipher layer. */
950         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
951     }
952 #endif /* MBEDTLS_USE_PSA_CRYPTO */
953
954     *olen = 0;
955
956     if( MBEDTLS_MODE_CFB == ctx->cipher_info->mode ||
957         MBEDTLS_MODE_OFB == ctx->cipher_info->mode ||
958         MBEDTLS_MODE_CTR == ctx->cipher_info->mode ||
959         MBEDTLS_MODE_GCM == ctx->cipher_info->mode ||
960         MBEDTLS_MODE_XTS == ctx->cipher_info->mode ||
961         MBEDTLS_MODE_STREAM == ctx->cipher_info->mode )
962     {
963         return( 0 );
964     }
965
966     if ( ( MBEDTLS_CIPHER_CHACHA20          == ctx->cipher_info->type ) ||
967          ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type ) )
968     {
969         return( 0 );
970     }
971
972     if( MBEDTLS_MODE_ECB == ctx->cipher_info->mode )
973     {
974         if( ctx->unprocessed_len != 0 )
975             return( MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED );
976
977         return( 0 );
978     }
979
980 #if defined(MBEDTLS_CIPHER_MODE_CBC)
981     if( MBEDTLS_MODE_CBC == ctx->cipher_info->mode )
982     {
983         int ret = 0;
984
985         if( MBEDTLS_ENCRYPT == ctx->operation )
986         {
987             /* check for 'no padding' mode */
988             if( NULL == ctx->add_padding )
989             {
990                 if( 0 != ctx->unprocessed_len )
991                     return( MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED );
992
993                 return( 0 );
994             }
995
996             ctx->add_padding( ctx->unprocessed_data, mbedtls_cipher_get_iv_size( ctx ),
997                     ctx->unprocessed_len );
998         }
999         else if( mbedtls_cipher_get_block_size( ctx ) != ctx->unprocessed_len )
1000         {
1001             /*
1002              * For decrypt operations, expect a full block,
1003              * or an empty block if no padding
1004              */
1005             if( NULL == ctx->add_padding && 0 == ctx->unprocessed_len )
1006                 return( 0 );
1007
1008             return( MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED );
1009         }
1010
1011         /* cipher block */
1012         if( 0 != ( ret = ctx->cipher_info->base->cbc_func( ctx->cipher_ctx,
1013                 ctx->operation, mbedtls_cipher_get_block_size( ctx ), ctx->iv,
1014                 ctx->unprocessed_data, output ) ) )
1015         {
1016             return( ret );
1017         }
1018
1019         /* Set output size for decryption */
1020         if( MBEDTLS_DECRYPT == ctx->operation )
1021             return( ctx->get_padding( output, mbedtls_cipher_get_block_size( ctx ),
1022                                       olen ) );
1023
1024         /* Set output size for encryption */
1025         *olen = mbedtls_cipher_get_block_size( ctx );
1026         return( 0 );
1027     }
1028 #else
1029     ((void) output);
1030 #endif /* MBEDTLS_CIPHER_MODE_CBC */
1031
1032     return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1033 }
1034
1035 #if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
1036 int mbedtls_cipher_set_padding_mode( mbedtls_cipher_context_t *ctx,
1037                                      mbedtls_cipher_padding_t mode )
1038 {
1039     CIPHER_VALIDATE_RET( ctx != NULL );
1040
1041     if( NULL == ctx->cipher_info || MBEDTLS_MODE_CBC != ctx->cipher_info->mode )
1042     {
1043         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1044     }
1045
1046 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1047     if( ctx->psa_enabled == 1 )
1048     {
1049         /* While PSA Crypto knows about CBC padding
1050          * schemes, we currently don't make them
1051          * accessible through the cipher layer. */
1052         if( mode != MBEDTLS_PADDING_NONE )
1053             return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1054
1055         return( 0 );
1056     }
1057 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1058
1059     switch( mode )
1060     {
1061 #if defined(MBEDTLS_CIPHER_PADDING_PKCS7)
1062     case MBEDTLS_PADDING_PKCS7:
1063         ctx->add_padding = add_pkcs_padding;
1064         ctx->get_padding = get_pkcs_padding;
1065         break;
1066 #endif
1067 #if defined(MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS)
1068     case MBEDTLS_PADDING_ONE_AND_ZEROS:
1069         ctx->add_padding = add_one_and_zeros_padding;
1070         ctx->get_padding = get_one_and_zeros_padding;
1071         break;
1072 #endif
1073 #if defined(MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN)
1074     case MBEDTLS_PADDING_ZEROS_AND_LEN:
1075         ctx->add_padding = add_zeros_and_len_padding;
1076         ctx->get_padding = get_zeros_and_len_padding;
1077         break;
1078 #endif
1079 #if defined(MBEDTLS_CIPHER_PADDING_ZEROS)
1080     case MBEDTLS_PADDING_ZEROS:
1081         ctx->add_padding = add_zeros_padding;
1082         ctx->get_padding = get_zeros_padding;
1083         break;
1084 #endif
1085     case MBEDTLS_PADDING_NONE:
1086         ctx->add_padding = NULL;
1087         ctx->get_padding = get_no_padding;
1088         break;
1089
1090     default:
1091         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1092     }
1093
1094     return( 0 );
1095 }
1096 #endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */
1097
1098 #if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C)
1099 int mbedtls_cipher_write_tag( mbedtls_cipher_context_t *ctx,
1100                       unsigned char *tag, size_t tag_len )
1101 {
1102     CIPHER_VALIDATE_RET( ctx != NULL );
1103     CIPHER_VALIDATE_RET( tag_len == 0 || tag != NULL );
1104     if( ctx->cipher_info == NULL )
1105         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1106
1107     if( MBEDTLS_ENCRYPT != ctx->operation )
1108         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1109
1110 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1111     if( ctx->psa_enabled == 1 )
1112     {
1113         /* While PSA Crypto has an API for multipart
1114          * operations, we currently don't make it
1115          * accessible through the cipher layer. */
1116         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1117
1118         return( 0 );
1119     }
1120 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1121
1122 #if defined(MBEDTLS_GCM_C)
1123     if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )
1124         return( mbedtls_gcm_finish( (mbedtls_gcm_context *) ctx->cipher_ctx,
1125                                     tag, tag_len ) );
1126 #endif
1127
1128 #if defined(MBEDTLS_CHACHAPOLY_C)
1129     if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )
1130     {
1131         /* Don't allow truncated MAC for Poly1305 */
1132         if ( tag_len != 16U )
1133             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1134
1135         return( mbedtls_chachapoly_finish(
1136                     (mbedtls_chachapoly_context*) ctx->cipher_ctx, tag ) );
1137     }
1138 #endif
1139
1140     return( 0 );
1141 }
1142
1143 int mbedtls_cipher_check_tag( mbedtls_cipher_context_t *ctx,
1144                       const unsigned char *tag, size_t tag_len )
1145 {
1146     unsigned char check_tag[16];
1147     int ret;
1148
1149     CIPHER_VALIDATE_RET( ctx != NULL );
1150     CIPHER_VALIDATE_RET( tag_len == 0 || tag != NULL );
1151     if( ctx->cipher_info == NULL )
1152         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1153
1154     if( MBEDTLS_DECRYPT != ctx->operation )
1155     {
1156         return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1157     }
1158
1159 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1160     if( ctx->psa_enabled == 1 )
1161     {
1162         /* While PSA Crypto has an API for multipart
1163          * operations, we currently don't make it
1164          * accessible through the cipher layer. */
1165         return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1166     }
1167 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1168
1169 #if defined(MBEDTLS_GCM_C)
1170     if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )
1171     {
1172         if( tag_len > sizeof( check_tag ) )
1173             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1174
1175         if( 0 != ( ret = mbedtls_gcm_finish(
1176                        (mbedtls_gcm_context *) ctx->cipher_ctx,
1177                        check_tag, tag_len ) ) )
1178         {
1179             return( ret );
1180         }
1181
1182         /* Check the tag in "constant-time" */
1183         if( mbedtls_constant_time_memcmp( tag, check_tag, tag_len ) != 0 )
1184             return( MBEDTLS_ERR_CIPHER_AUTH_FAILED );
1185
1186         return( 0 );
1187     }
1188 #endif /* MBEDTLS_GCM_C */
1189
1190 #if defined(MBEDTLS_CHACHAPOLY_C)
1191     if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )
1192     {
1193         /* Don't allow truncated MAC for Poly1305 */
1194         if ( tag_len != sizeof( check_tag ) )
1195             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1196
1197         ret = mbedtls_chachapoly_finish(
1198             (mbedtls_chachapoly_context*) ctx->cipher_ctx, check_tag );
1199         if ( ret != 0 )
1200         {
1201             return( ret );
1202         }
1203
1204         /* Check the tag in "constant-time" */
1205         if( mbedtls_constant_time_memcmp( tag, check_tag, tag_len ) != 0 )
1206             return( MBEDTLS_ERR_CIPHER_AUTH_FAILED );
1207
1208         return( 0 );
1209     }
1210 #endif /* MBEDTLS_CHACHAPOLY_C */
1211
1212     return( 0 );
1213 }
1214 #endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */
1215
1216 /*
1217  * Packet-oriented wrapper for non-AEAD modes
1218  */
1219 int mbedtls_cipher_crypt( mbedtls_cipher_context_t *ctx,
1220                   const unsigned char *iv, size_t iv_len,
1221                   const unsigned char *input, size_t ilen,
1222                   unsigned char *output, size_t *olen )
1223 {
1224     int ret;
1225     size_t finish_olen;
1226
1227     CIPHER_VALIDATE_RET( ctx != NULL );
1228     CIPHER_VALIDATE_RET( iv_len == 0 || iv != NULL );
1229     CIPHER_VALIDATE_RET( ilen == 0 || input != NULL );
1230     CIPHER_VALIDATE_RET( output != NULL );
1231     CIPHER_VALIDATE_RET( olen != NULL );
1232
1233 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1234     if( ctx->psa_enabled == 1 )
1235     {
1236         /* As in the non-PSA case, we don't check that
1237          * a key has been set. If not, the key slot will
1238          * still be in its default state of 0, which is
1239          * guaranteed to be invalid, hence the PSA-call
1240          * below will gracefully fail. */
1241         mbedtls_cipher_context_psa * const cipher_psa =
1242             (mbedtls_cipher_context_psa *) ctx->cipher_ctx;
1243
1244         psa_status_t status;
1245         psa_cipher_operation_t cipher_op = PSA_CIPHER_OPERATION_INIT;
1246         size_t part_len;
1247
1248         if( ctx->operation == MBEDTLS_DECRYPT )
1249         {
1250             status = psa_cipher_decrypt_setup( &cipher_op,
1251                                                cipher_psa->slot,
1252                                                cipher_psa->alg );
1253         }
1254         else if( ctx->operation == MBEDTLS_ENCRYPT )
1255         {
1256             status = psa_cipher_encrypt_setup( &cipher_op,
1257                                                cipher_psa->slot,
1258                                                cipher_psa->alg );
1259         }
1260         else
1261             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1262
1263         /* In the following, we can immediately return on an error,
1264          * because the PSA Crypto API guarantees that cipher operations
1265          * are terminated by unsuccessful calls to psa_cipher_update(),
1266          * and by any call to psa_cipher_finish(). */
1267         if( status != PSA_SUCCESS )
1268             return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED );
1269
1270         status = psa_cipher_set_iv( &cipher_op, iv, iv_len );
1271         if( status != PSA_SUCCESS )
1272             return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED );
1273
1274         status = psa_cipher_update( &cipher_op,
1275                                     input, ilen,
1276                                     output, ilen, olen );
1277         if( status != PSA_SUCCESS )
1278             return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED );
1279
1280         status = psa_cipher_finish( &cipher_op,
1281                                     output + *olen, ilen - *olen,
1282                                     &part_len );
1283         if( status != PSA_SUCCESS )
1284             return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED );
1285
1286         *olen += part_len;
1287         return( 0 );
1288     }
1289 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1290
1291     if( ( ret = mbedtls_cipher_set_iv( ctx, iv, iv_len ) ) != 0 )
1292         return( ret );
1293
1294     if( ( ret = mbedtls_cipher_reset( ctx ) ) != 0 )
1295         return( ret );
1296
1297     if( ( ret = mbedtls_cipher_update( ctx, input, ilen,
1298                                        output, olen ) ) != 0 )
1299         return( ret );
1300
1301     if( ( ret = mbedtls_cipher_finish( ctx, output + *olen,
1302                                        &finish_olen ) ) != 0 )
1303         return( ret );
1304
1305     *olen += finish_olen;
1306
1307     return( 0 );
1308 }
1309
1310 #if defined(MBEDTLS_CIPHER_MODE_AEAD)
1311 /*
1312  * Packet-oriented encryption for AEAD modes
1313  */
1314 int mbedtls_cipher_auth_encrypt( mbedtls_cipher_context_t *ctx,
1315                          const unsigned char *iv, size_t iv_len,
1316                          const unsigned char *ad, size_t ad_len,
1317                          const unsigned char *input, size_t ilen,
1318                          unsigned char *output, size_t *olen,
1319                          unsigned char *tag, size_t tag_len )
1320 {
1321     CIPHER_VALIDATE_RET( ctx != NULL );
1322     CIPHER_VALIDATE_RET( iv != NULL );
1323     CIPHER_VALIDATE_RET( ad_len == 0 || ad != NULL );
1324     CIPHER_VALIDATE_RET( ilen == 0 || input != NULL );
1325     CIPHER_VALIDATE_RET( output != NULL );
1326     CIPHER_VALIDATE_RET( olen != NULL );
1327     CIPHER_VALIDATE_RET( tag_len == 0 || tag != NULL );
1328
1329 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1330     if( ctx->psa_enabled == 1 )
1331     {
1332         /* As in the non-PSA case, we don't check that
1333          * a key has been set. If not, the key slot will
1334          * still be in its default state of 0, which is
1335          * guaranteed to be invalid, hence the PSA-call
1336          * below will gracefully fail. */
1337         mbedtls_cipher_context_psa * const cipher_psa =
1338             (mbedtls_cipher_context_psa *) ctx->cipher_ctx;
1339
1340         psa_status_t status;
1341
1342         /* PSA Crypto API always writes the authentication tag
1343          * at the end of the encrypted message. */
1344         if( tag != output + ilen )
1345             return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1346
1347         status = psa_aead_encrypt( cipher_psa->slot,
1348                                    cipher_psa->alg,
1349                                    iv, iv_len,
1350                                    ad, ad_len,
1351                                    input, ilen,
1352                                    output, ilen + tag_len, olen );
1353         if( status != PSA_SUCCESS )
1354             return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED );
1355
1356         *olen -= tag_len;
1357         return( 0 );
1358     }
1359 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1360
1361 #if defined(MBEDTLS_GCM_C)
1362     if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )
1363     {
1364         *olen = ilen;
1365         return( mbedtls_gcm_crypt_and_tag( ctx->cipher_ctx, MBEDTLS_GCM_ENCRYPT,
1366                                            ilen, iv, iv_len, ad, ad_len,
1367                                            input, output, tag_len, tag ) );
1368     }
1369 #endif /* MBEDTLS_GCM_C */
1370 #if defined(MBEDTLS_CCM_C)
1371     if( MBEDTLS_MODE_CCM == ctx->cipher_info->mode )
1372     {
1373         *olen = ilen;
1374         return( mbedtls_ccm_encrypt_and_tag( ctx->cipher_ctx, ilen,
1375                                      iv, iv_len, ad, ad_len, input, output,
1376                                      tag, tag_len ) );
1377     }
1378 #endif /* MBEDTLS_CCM_C */
1379 #if defined(MBEDTLS_CHACHAPOLY_C)
1380     if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )
1381     {
1382         /* ChachaPoly has fixed length nonce and MAC (tag) */
1383         if ( ( iv_len != ctx->cipher_info->iv_size ) ||
1384              ( tag_len != 16U ) )
1385         {
1386             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1387         }
1388
1389         *olen = ilen;
1390         return( mbedtls_chachapoly_encrypt_and_tag( ctx->cipher_ctx,
1391                                 ilen, iv, ad, ad_len, input, output, tag ) );
1392     }
1393 #endif /* MBEDTLS_CHACHAPOLY_C */
1394 #if defined(MBEDTLS_NIST_KW_C)
1395    if( MBEDTLS_MODE_KW == ctx->cipher_info->mode ||
1396        MBEDTLS_MODE_KWP == ctx->cipher_info->mode )
1397     {
1398         mbedtls_nist_kw_mode_t mode = ( MBEDTLS_MODE_KW == ctx->cipher_info->mode ) ?
1399                                         MBEDTLS_KW_MODE_KW : MBEDTLS_KW_MODE_KWP;
1400
1401         /* There is no iv, tag or ad associated with KW and KWP, these length should be 0 */
1402         if( iv_len != 0 || tag_len != 0 || ad_len != 0 )
1403         {
1404             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1405         }
1406
1407         return( mbedtls_nist_kw_wrap( ctx->cipher_ctx, mode, input, ilen, output, olen, SIZE_MAX ) );
1408     }
1409 #endif /* MBEDTLS_NIST_KW_C */
1410
1411     return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1412 }
1413
1414 /*
1415  * Packet-oriented decryption for AEAD modes
1416  */
1417 int mbedtls_cipher_auth_decrypt( mbedtls_cipher_context_t *ctx,
1418                          const unsigned char *iv, size_t iv_len,
1419                          const unsigned char *ad, size_t ad_len,
1420                          const unsigned char *input, size_t ilen,
1421                          unsigned char *output, size_t *olen,
1422                          const unsigned char *tag, size_t tag_len )
1423 {
1424     CIPHER_VALIDATE_RET( ctx != NULL );
1425     CIPHER_VALIDATE_RET( iv != NULL );
1426     CIPHER_VALIDATE_RET( ad_len == 0 || ad != NULL );
1427     CIPHER_VALIDATE_RET( ilen == 0 || input != NULL );
1428     CIPHER_VALIDATE_RET( output != NULL );
1429     CIPHER_VALIDATE_RET( olen != NULL );
1430     CIPHER_VALIDATE_RET( tag_len == 0 || tag != NULL );
1431
1432 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1433     if( ctx->psa_enabled == 1 )
1434     {
1435         /* As in the non-PSA case, we don't check that
1436          * a key has been set. If not, the key slot will
1437          * still be in its default state of 0, which is
1438          * guaranteed to be invalid, hence the PSA-call
1439          * below will gracefully fail. */
1440         mbedtls_cipher_context_psa * const cipher_psa =
1441             (mbedtls_cipher_context_psa *) ctx->cipher_ctx;
1442
1443         psa_status_t status;
1444
1445         /* PSA Crypto API always writes the authentication tag
1446          * at the end of the encrypted message. */
1447         if( tag != input + ilen )
1448             return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1449
1450         status = psa_aead_decrypt( cipher_psa->slot,
1451                                    cipher_psa->alg,
1452                                    iv, iv_len,
1453                                    ad, ad_len,
1454                                    input, ilen + tag_len,
1455                                    output, ilen, olen );
1456         if( status == PSA_ERROR_INVALID_SIGNATURE )
1457             return( MBEDTLS_ERR_CIPHER_AUTH_FAILED );
1458         else if( status != PSA_SUCCESS )
1459             return( MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED );
1460
1461         return( 0 );
1462     }
1463 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1464
1465 #if defined(MBEDTLS_GCM_C)
1466     if( MBEDTLS_MODE_GCM == ctx->cipher_info->mode )
1467     {
1468         int ret;
1469
1470         *olen = ilen;
1471         ret = mbedtls_gcm_auth_decrypt( ctx->cipher_ctx, ilen,
1472                                 iv, iv_len, ad, ad_len,
1473                                 tag, tag_len, input, output );
1474
1475         if( ret == MBEDTLS_ERR_GCM_AUTH_FAILED )
1476             ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;
1477
1478         return( ret );
1479     }
1480 #endif /* MBEDTLS_GCM_C */
1481 #if defined(MBEDTLS_CCM_C)
1482     if( MBEDTLS_MODE_CCM == ctx->cipher_info->mode )
1483     {
1484         int ret;
1485
1486         *olen = ilen;
1487         ret = mbedtls_ccm_auth_decrypt( ctx->cipher_ctx, ilen,
1488                                 iv, iv_len, ad, ad_len,
1489                                 input, output, tag, tag_len );
1490
1491         if( ret == MBEDTLS_ERR_CCM_AUTH_FAILED )
1492             ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;
1493
1494         return( ret );
1495     }
1496 #endif /* MBEDTLS_CCM_C */
1497 #if defined(MBEDTLS_CHACHAPOLY_C)
1498     if ( MBEDTLS_CIPHER_CHACHA20_POLY1305 == ctx->cipher_info->type )
1499     {
1500         int ret;
1501
1502         /* ChachaPoly has fixed length nonce and MAC (tag) */
1503         if ( ( iv_len != ctx->cipher_info->iv_size ) ||
1504              ( tag_len != 16U ) )
1505         {
1506             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1507         }
1508
1509         *olen = ilen;
1510         ret = mbedtls_chachapoly_auth_decrypt( ctx->cipher_ctx, ilen,
1511                                 iv, ad, ad_len, tag, input, output );
1512
1513         if( ret == MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED )
1514             ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;
1515
1516         return( ret );
1517     }
1518 #endif /* MBEDTLS_CHACHAPOLY_C */
1519 #if defined(MBEDTLS_NIST_KW_C)
1520     if( MBEDTLS_MODE_KW == ctx->cipher_info->mode ||
1521         MBEDTLS_MODE_KWP == ctx->cipher_info->mode )
1522     {
1523         mbedtls_nist_kw_mode_t mode = ( MBEDTLS_MODE_KW == ctx->cipher_info->mode ) ?
1524                                         MBEDTLS_KW_MODE_KW : MBEDTLS_KW_MODE_KWP;
1525
1526         /* There is no iv, tag or ad associated with KW and KWP, these length should be 0 */
1527         if( iv_len != 0 || tag_len != 0 || ad_len != 0 )
1528         {
1529             return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
1530         }
1531
1532         return( mbedtls_nist_kw_unwrap( ctx->cipher_ctx, mode, input, ilen, output, olen, SIZE_MAX ) );
1533     }
1534 #endif /* MBEDTLS_NIST_KW_C */
1535
1536     return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
1537 }
1538 #endif /* MBEDTLS_CIPHER_MODE_AEAD */
1539
1540 #endif /* MBEDTLS_CIPHER_C */