• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/* BEGIN_HEADER */
2#include <stdint.h>
3
4#include "mbedtls/asn1.h"
5#include "mbedtls/asn1write.h"
6#include "mbedtls/oid.h"
7#include "common.h"
8
9/* For MBEDTLS_CTR_DRBG_MAX_REQUEST, knowing that psa_generate_random()
10 * uses mbedtls_ctr_drbg internally. */
11#include "mbedtls/ctr_drbg.h"
12
13#include "psa/crypto.h"
14#include "psa_crypto_slot_management.h"
15
16/* For psa_can_do_hash() */
17#include "psa_crypto_core.h"
18
19#include "test/asn1_helpers.h"
20#include "test/psa_crypto_helpers.h"
21#include "test/psa_exercise_key.h"
22#if defined(PSA_CRYPTO_DRIVER_TEST)
23#include "test/drivers/test_driver.h"
24#define TEST_DRIVER_LOCATION PSA_CRYPTO_TEST_DRIVER_LOCATION
25#else
26#define TEST_DRIVER_LOCATION 0x7fffff
27#endif
28#include "mbedtls/legacy_or_psa.h"
29
30/* If this comes up, it's a bug in the test code or in the test data. */
31#define UNUSED 0xdeadbeef
32
33/* Assert that an operation is (not) active.
34 * This serves as a proxy for checking if the operation is aborted. */
35#define ASSERT_OPERATION_IS_ACTIVE(operation) TEST_ASSERT(operation.id != 0)
36#define ASSERT_OPERATION_IS_INACTIVE(operation) TEST_ASSERT(operation.id == 0)
37
38#if defined(PSA_WANT_ALG_JPAKE)
39int ecjpake_operation_setup(psa_pake_operation_t *operation,
40                            psa_pake_cipher_suite_t *cipher_suite,
41                            psa_pake_role_t role,
42                            mbedtls_svc_key_id_t key,
43                            size_t key_available)
44{
45    PSA_ASSERT(psa_pake_abort(operation));
46
47    PSA_ASSERT(psa_pake_setup(operation, cipher_suite));
48
49    PSA_ASSERT(psa_pake_set_role(operation, role));
50
51    if (key_available) {
52        PSA_ASSERT(psa_pake_set_password_key(operation, key));
53    }
54    return 0;
55exit:
56    return 1;
57}
58#endif
59
60/** An invalid export length that will never be set by psa_export_key(). */
61static const size_t INVALID_EXPORT_LENGTH = ~0U;
62
63/** Test if a buffer contains a constant byte value.
64 *
65 * `mem_is_char(buffer, c, size)` is true after `memset(buffer, c, size)`.
66 *
67 * \param buffer    Pointer to the beginning of the buffer.
68 * \param c         Expected value of every byte.
69 * \param size      Size of the buffer in bytes.
70 *
71 * \return          1 if the buffer is all-bits-zero.
72 * \return          0 if there is at least one nonzero byte.
73 */
74static int mem_is_char(void *buffer, unsigned char c, size_t size)
75{
76    size_t i;
77    for (i = 0; i < size; i++) {
78        if (((unsigned char *) buffer)[i] != c) {
79            return 0;
80        }
81    }
82    return 1;
83}
84#if defined(MBEDTLS_ASN1_WRITE_C)
85/* Write the ASN.1 INTEGER with the value 2^(bits-1)+x backwards from *p. */
86static int asn1_write_10x(unsigned char **p,
87                          unsigned char *start,
88                          size_t bits,
89                          unsigned char x)
90{
91    int ret;
92    int len = bits / 8 + 1;
93    if (bits == 0) {
94        return MBEDTLS_ERR_ASN1_INVALID_DATA;
95    }
96    if (bits <= 8 && x >= 1 << (bits - 1)) {
97        return MBEDTLS_ERR_ASN1_INVALID_DATA;
98    }
99    if (*p < start || *p - start < (ptrdiff_t) len) {
100        return MBEDTLS_ERR_ASN1_BUF_TOO_SMALL;
101    }
102    *p -= len;
103    (*p)[len-1] = x;
104    if (bits % 8 == 0) {
105        (*p)[1] |= 1;
106    } else {
107        (*p)[0] |= 1 << (bits % 8);
108    }
109    MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(p, start, len));
110    MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(p, start,
111                                                     MBEDTLS_ASN1_INTEGER));
112    return len;
113}
114
115static int construct_fake_rsa_key(unsigned char *buffer,
116                                  size_t buffer_size,
117                                  unsigned char **p,
118                                  size_t bits,
119                                  int keypair)
120{
121    size_t half_bits = (bits + 1) / 2;
122    int ret;
123    int len = 0;
124    /* Construct something that looks like a DER encoding of
125     * as defined by PKCS#1 v2.2 (RFC 8017) section A.1.2:
126     *   RSAPrivateKey ::= SEQUENCE {
127     *       version           Version,
128     *       modulus           INTEGER,  -- n
129     *       publicExponent    INTEGER,  -- e
130     *       privateExponent   INTEGER,  -- d
131     *       prime1            INTEGER,  -- p
132     *       prime2            INTEGER,  -- q
133     *       exponent1         INTEGER,  -- d mod (p-1)
134     *       exponent2         INTEGER,  -- d mod (q-1)
135     *       coefficient       INTEGER,  -- (inverse of q) mod p
136     *       otherPrimeInfos   OtherPrimeInfos OPTIONAL
137     *   }
138     * Or, for a public key, the same structure with only
139     * version, modulus and publicExponent.
140     */
141    *p = buffer + buffer_size;
142    if (keypair) {
143        MBEDTLS_ASN1_CHK_ADD(len,  /* pq */
144                             asn1_write_10x(p, buffer, half_bits, 1));
145        MBEDTLS_ASN1_CHK_ADD(len,  /* dq */
146                             asn1_write_10x(p, buffer, half_bits, 1));
147        MBEDTLS_ASN1_CHK_ADD(len,  /* dp */
148                             asn1_write_10x(p, buffer, half_bits, 1));
149        MBEDTLS_ASN1_CHK_ADD(len,  /* q */
150                             asn1_write_10x(p, buffer, half_bits, 1));
151        MBEDTLS_ASN1_CHK_ADD(len,  /* p != q to pass mbedtls sanity checks */
152                             asn1_write_10x(p, buffer, half_bits, 3));
153        MBEDTLS_ASN1_CHK_ADD(len,  /* d */
154                             asn1_write_10x(p, buffer, bits, 1));
155    }
156    MBEDTLS_ASN1_CHK_ADD(len,  /* e = 65537 */
157                         asn1_write_10x(p, buffer, 17, 1));
158    MBEDTLS_ASN1_CHK_ADD(len,  /* n */
159                         asn1_write_10x(p, buffer, bits, 1));
160    if (keypair) {
161        MBEDTLS_ASN1_CHK_ADD(len,  /* version = 0 */
162                             mbedtls_asn1_write_int(p, buffer, 0));
163    }
164    MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(p, buffer, len));
165    {
166        const unsigned char tag =
167            MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE;
168        MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(p, buffer, tag));
169    }
170    return len;
171}
172#endif /* MBEDTLS_ASN1_WRITE_C */
173
174int exercise_mac_setup(psa_key_type_t key_type,
175                       const unsigned char *key_bytes,
176                       size_t key_length,
177                       psa_algorithm_t alg,
178                       psa_mac_operation_t *operation,
179                       psa_status_t *status)
180{
181    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
182    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
183
184    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH);
185    psa_set_key_algorithm(&attributes, alg);
186    psa_set_key_type(&attributes, key_type);
187    PSA_ASSERT(psa_import_key(&attributes, key_bytes, key_length, &key));
188
189    *status = psa_mac_sign_setup(operation, key, alg);
190    /* Whether setup succeeded or failed, abort must succeed. */
191    PSA_ASSERT(psa_mac_abort(operation));
192    /* If setup failed, reproduce the failure, so that the caller can
193     * test the resulting state of the operation object. */
194    if (*status != PSA_SUCCESS) {
195        TEST_EQUAL(psa_mac_sign_setup(operation, key, alg), *status);
196    }
197
198    psa_destroy_key(key);
199    return 1;
200
201exit:
202    psa_destroy_key(key);
203    return 0;
204}
205
206int exercise_cipher_setup(psa_key_type_t key_type,
207                          const unsigned char *key_bytes,
208                          size_t key_length,
209                          psa_algorithm_t alg,
210                          psa_cipher_operation_t *operation,
211                          psa_status_t *status)
212{
213    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
214    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
215
216    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
217    psa_set_key_algorithm(&attributes, alg);
218    psa_set_key_type(&attributes, key_type);
219    PSA_ASSERT(psa_import_key(&attributes, key_bytes, key_length, &key));
220
221    *status = psa_cipher_encrypt_setup(operation, key, alg);
222    /* Whether setup succeeded or failed, abort must succeed. */
223    PSA_ASSERT(psa_cipher_abort(operation));
224    /* If setup failed, reproduce the failure, so that the caller can
225     * test the resulting state of the operation object. */
226    if (*status != PSA_SUCCESS) {
227        TEST_EQUAL(psa_cipher_encrypt_setup(operation, key, alg),
228                   *status);
229    }
230
231    psa_destroy_key(key);
232    return 1;
233
234exit:
235    psa_destroy_key(key);
236    return 0;
237}
238
239static int test_operations_on_invalid_key(mbedtls_svc_key_id_t key)
240{
241    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
242    mbedtls_svc_key_id_t key_id = mbedtls_svc_key_id_make(1, 0x6964);
243    uint8_t buffer[1];
244    size_t length;
245    int ok = 0;
246
247    psa_set_key_id(&attributes, key_id);
248    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
249    psa_set_key_algorithm(&attributes, PSA_ALG_CTR);
250    psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
251    TEST_EQUAL(psa_get_key_attributes(key, &attributes),
252               PSA_ERROR_INVALID_HANDLE);
253    TEST_EQUAL(
254        MBEDTLS_SVC_KEY_ID_GET_KEY_ID(psa_get_key_id(&attributes)), 0);
255    TEST_EQUAL(
256        MBEDTLS_SVC_KEY_ID_GET_OWNER_ID(psa_get_key_id(&attributes)), 0);
257    TEST_EQUAL(psa_get_key_lifetime(&attributes), 0);
258    TEST_EQUAL(psa_get_key_usage_flags(&attributes), 0);
259    TEST_EQUAL(psa_get_key_algorithm(&attributes), 0);
260    TEST_EQUAL(psa_get_key_type(&attributes), 0);
261    TEST_EQUAL(psa_get_key_bits(&attributes), 0);
262
263    TEST_EQUAL(psa_export_key(key, buffer, sizeof(buffer), &length),
264               PSA_ERROR_INVALID_HANDLE);
265    TEST_EQUAL(psa_export_public_key(key,
266                                     buffer, sizeof(buffer), &length),
267               PSA_ERROR_INVALID_HANDLE);
268
269    ok = 1;
270
271exit:
272    /*
273     * Key attributes may have been returned by psa_get_key_attributes()
274     * thus reset them as required.
275     */
276    psa_reset_key_attributes(&attributes);
277
278    return ok;
279}
280
281/* Assert that a key isn't reported as having a slot number. */
282#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
283#define ASSERT_NO_SLOT_NUMBER(attributes)                             \
284    do                                                                  \
285    {                                                                   \
286        psa_key_slot_number_t ASSERT_NO_SLOT_NUMBER_slot_number;        \
287        TEST_EQUAL(psa_get_key_slot_number(                            \
288                       attributes,                                     \
289                       &ASSERT_NO_SLOT_NUMBER_slot_number),           \
290                   PSA_ERROR_INVALID_ARGUMENT);                       \
291    }                                                                   \
292    while (0)
293#else /* MBEDTLS_PSA_CRYPTO_SE_C */
294#define ASSERT_NO_SLOT_NUMBER(attributes)     \
295    ((void) 0)
296#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
297
298/* An overapproximation of the amount of storage needed for a key of the
299 * given type and with the given content. The API doesn't make it easy
300 * to find a good value for the size. The current implementation doesn't
301 * care about the value anyway. */
302#define KEY_BITS_FROM_DATA(type, data)        \
303    (data)->len
304
305typedef enum {
306    IMPORT_KEY = 0,
307    GENERATE_KEY = 1,
308    DERIVE_KEY = 2
309} generate_method;
310
311typedef enum {
312    DO_NOT_SET_LENGTHS = 0,
313    SET_LENGTHS_BEFORE_NONCE = 1,
314    SET_LENGTHS_AFTER_NONCE = 2
315} set_lengths_method_t;
316
317typedef enum {
318    USE_NULL_TAG = 0,
319    USE_GIVEN_TAG = 1,
320} tag_usage_method_t;
321
322/*!
323 * \brief                           Internal Function for AEAD multipart tests.
324 * \param key_type_arg              Type of key passed in
325 * \param key_data                  The encryption / decryption key data
326 * \param alg_arg                   The type of algorithm used
327 * \param nonce                     Nonce data
328 * \param additional_data           Additional data
329 * \param ad_part_len_arg           If not -1, the length of chunks to
330 *                                  feed additional data in to be encrypted /
331 *                                  decrypted. If -1, no chunking.
332 * \param input_data                Data to encrypt / decrypt
333 * \param data_part_len_arg         If not -1, the length of chunks to feed
334 *                                  the data in to be encrypted / decrypted. If
335 *                                  -1, no chunking
336 * \param set_lengths_method        A member of the set_lengths_method_t enum is
337 *                                  expected here, this controls whether or not
338 *                                  to set lengths, and in what order with
339 *                                  respect to set nonce.
340 * \param expected_output           Expected output
341 * \param is_encrypt                If non-zero this is an encryption operation.
342 * \param do_zero_parts             If non-zero, interleave zero length chunks
343 *                                  with normal length chunks.
344 * \return int                      Zero on failure, non-zero on success.
345 */
346static int aead_multipart_internal_func(int key_type_arg, data_t *key_data,
347                                        int alg_arg,
348                                        data_t *nonce,
349                                        data_t *additional_data,
350                                        int ad_part_len_arg,
351                                        data_t *input_data,
352                                        int data_part_len_arg,
353                                        set_lengths_method_t set_lengths_method,
354                                        data_t *expected_output,
355                                        int is_encrypt,
356                                        int do_zero_parts)
357{
358    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
359    psa_key_type_t key_type = key_type_arg;
360    psa_algorithm_t alg = alg_arg;
361    psa_aead_operation_t operation = PSA_AEAD_OPERATION_INIT;
362    unsigned char *output_data = NULL;
363    unsigned char *part_data = NULL;
364    unsigned char *final_data = NULL;
365    size_t data_true_size = 0;
366    size_t part_data_size = 0;
367    size_t output_size = 0;
368    size_t final_output_size = 0;
369    size_t output_length = 0;
370    size_t key_bits = 0;
371    size_t tag_length = 0;
372    size_t part_offset = 0;
373    size_t part_length = 0;
374    size_t output_part_length = 0;
375    size_t tag_size = 0;
376    size_t ad_part_len = 0;
377    size_t data_part_len = 0;
378    uint8_t tag_buffer[PSA_AEAD_TAG_MAX_SIZE];
379    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
380    psa_status_t status = PSA_ERROR_GENERIC_ERROR;
381
382    int test_ok = 0;
383    size_t part_count = 0;
384
385    PSA_ASSERT(psa_crypto_init());
386
387    if (is_encrypt) {
388        psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
389    } else {
390        psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DECRYPT);
391    }
392
393    psa_set_key_algorithm(&attributes, alg);
394    psa_set_key_type(&attributes, key_type);
395
396    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
397                              &key));
398
399    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
400    key_bits = psa_get_key_bits(&attributes);
401
402    tag_length = PSA_AEAD_TAG_LENGTH(key_type, key_bits, alg);
403
404    if (is_encrypt) {
405        /* Tag gets written at end of buffer. */
406        output_size = PSA_AEAD_UPDATE_OUTPUT_SIZE(key_type, alg,
407                                                  (input_data->len +
408                                                   tag_length));
409        data_true_size = input_data->len;
410    } else {
411        output_size = PSA_AEAD_UPDATE_OUTPUT_SIZE(key_type, alg,
412                                                  (input_data->len -
413                                                   tag_length));
414
415        /* Do not want to attempt to decrypt tag. */
416        data_true_size = input_data->len - tag_length;
417    }
418
419    ASSERT_ALLOC(output_data, output_size);
420
421    if (is_encrypt) {
422        final_output_size = PSA_AEAD_FINISH_OUTPUT_SIZE(key_type, alg);
423        TEST_LE_U(final_output_size, PSA_AEAD_FINISH_OUTPUT_MAX_SIZE);
424    } else {
425        final_output_size = PSA_AEAD_VERIFY_OUTPUT_SIZE(key_type, alg);
426        TEST_LE_U(final_output_size, PSA_AEAD_VERIFY_OUTPUT_MAX_SIZE);
427    }
428
429    ASSERT_ALLOC(final_data, final_output_size);
430
431    if (is_encrypt) {
432        status = psa_aead_encrypt_setup(&operation, key, alg);
433    } else {
434        status = psa_aead_decrypt_setup(&operation, key, alg);
435    }
436
437    /* If the operation is not supported, just skip and not fail in case the
438     * encryption involves a common limitation of cryptography hardwares and
439     * an alternative implementation. */
440    if (status == PSA_ERROR_NOT_SUPPORTED) {
441        MBEDTLS_TEST_PSA_SKIP_IF_ALT_AES_192(key_type, key_data->len * 8);
442        MBEDTLS_TEST_PSA_SKIP_IF_ALT_GCM_NOT_12BYTES_NONCE(alg, nonce->len);
443    }
444
445    PSA_ASSERT(status);
446
447    if (set_lengths_method ==  DO_NOT_SET_LENGTHS) {
448        PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
449    } else if (set_lengths_method == SET_LENGTHS_BEFORE_NONCE) {
450        PSA_ASSERT(psa_aead_set_lengths(&operation, additional_data->len,
451                                        data_true_size));
452        PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
453    } else if (set_lengths_method ==  SET_LENGTHS_AFTER_NONCE) {
454        PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
455
456        PSA_ASSERT(psa_aead_set_lengths(&operation, additional_data->len,
457                                        data_true_size));
458    }
459
460    if (ad_part_len_arg != -1) {
461        /* Pass additional data in parts */
462        ad_part_len = (size_t) ad_part_len_arg;
463
464        for (part_offset = 0, part_count = 0;
465             part_offset < additional_data->len;
466             part_offset += part_length, part_count++) {
467            if (do_zero_parts && (part_count & 0x01)) {
468                part_length = 0;
469            } else if (additional_data->len - part_offset < ad_part_len) {
470                part_length = additional_data->len - part_offset;
471            } else {
472                part_length = ad_part_len;
473            }
474
475            PSA_ASSERT(psa_aead_update_ad(&operation,
476                                          additional_data->x + part_offset,
477                                          part_length));
478
479        }
480    } else {
481        /* Pass additional data in one go. */
482        PSA_ASSERT(psa_aead_update_ad(&operation, additional_data->x,
483                                      additional_data->len));
484    }
485
486    if (data_part_len_arg != -1) {
487        /* Pass data in parts */
488        data_part_len = (size_t) data_part_len_arg;
489        part_data_size = PSA_AEAD_UPDATE_OUTPUT_SIZE(key_type, alg,
490                                                     (size_t) data_part_len);
491
492        ASSERT_ALLOC(part_data, part_data_size);
493
494        for (part_offset = 0, part_count = 0;
495             part_offset < data_true_size;
496             part_offset += part_length, part_count++) {
497            if (do_zero_parts && (part_count & 0x01)) {
498                part_length = 0;
499            } else if ((data_true_size - part_offset) < data_part_len) {
500                part_length = (data_true_size - part_offset);
501            } else {
502                part_length = data_part_len;
503            }
504
505            PSA_ASSERT(psa_aead_update(&operation,
506                                       (input_data->x + part_offset),
507                                       part_length, part_data,
508                                       part_data_size,
509                                       &output_part_length));
510
511            if (output_data && output_part_length) {
512                memcpy((output_data + output_length), part_data,
513                       output_part_length);
514            }
515
516            output_length += output_part_length;
517        }
518    } else {
519        /* Pass all data in one go. */
520        PSA_ASSERT(psa_aead_update(&operation, input_data->x,
521                                   data_true_size, output_data,
522                                   output_size, &output_length));
523    }
524
525    if (is_encrypt) {
526        PSA_ASSERT(psa_aead_finish(&operation, final_data,
527                                   final_output_size,
528                                   &output_part_length,
529                                   tag_buffer, tag_length,
530                                   &tag_size));
531    } else {
532        PSA_ASSERT(psa_aead_verify(&operation, final_data,
533                                   final_output_size,
534                                   &output_part_length,
535                                   (input_data->x + data_true_size),
536                                   tag_length));
537    }
538
539    if (output_data && output_part_length) {
540        memcpy((output_data + output_length), final_data,
541               output_part_length);
542    }
543
544    output_length += output_part_length;
545
546
547    /* For all currently defined algorithms, PSA_AEAD_xxx_OUTPUT_SIZE
548     * should be exact.*/
549    if (is_encrypt) {
550        TEST_EQUAL(tag_length, tag_size);
551
552        if (output_data && tag_length) {
553            memcpy((output_data + output_length), tag_buffer,
554                   tag_length);
555        }
556
557        output_length += tag_length;
558
559        TEST_EQUAL(output_length,
560                   PSA_AEAD_ENCRYPT_OUTPUT_SIZE(key_type, alg,
561                                                input_data->len));
562        TEST_LE_U(output_length,
563                  PSA_AEAD_ENCRYPT_OUTPUT_MAX_SIZE(input_data->len));
564    } else {
565        TEST_EQUAL(output_length,
566                   PSA_AEAD_DECRYPT_OUTPUT_SIZE(key_type, alg,
567                                                input_data->len));
568        TEST_LE_U(output_length,
569                  PSA_AEAD_DECRYPT_OUTPUT_MAX_SIZE(input_data->len));
570    }
571
572
573    ASSERT_COMPARE(expected_output->x, expected_output->len,
574                   output_data, output_length);
575
576
577    test_ok = 1;
578
579exit:
580    psa_destroy_key(key);
581    psa_aead_abort(&operation);
582    mbedtls_free(output_data);
583    mbedtls_free(part_data);
584    mbedtls_free(final_data);
585    PSA_DONE();
586
587    return test_ok;
588}
589
590/*!
591 * \brief                           Internal Function for MAC multipart tests.
592 * \param key_type_arg              Type of key passed in
593 * \param key_data                  The encryption / decryption key data
594 * \param alg_arg                   The type of algorithm used
595 * \param input_data                Data to encrypt / decrypt
596 * \param data_part_len_arg         If not -1, the length of chunks to feed
597 *                                  the data in to be encrypted / decrypted. If
598 *                                  -1, no chunking
599 * \param expected_output           Expected output
600 * \param is_verify                 If non-zero this is a verify operation.
601 * \param do_zero_parts             If non-zero, interleave zero length chunks
602 *                                  with normal length chunks.
603 * \return int                      Zero on failure, non-zero on success.
604 */
605static int mac_multipart_internal_func(int key_type_arg, data_t *key_data,
606                                       int alg_arg,
607                                       data_t *input_data,
608                                       int data_part_len_arg,
609                                       data_t *expected_output,
610                                       int is_verify,
611                                       int do_zero_parts)
612{
613    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
614    psa_key_type_t key_type = key_type_arg;
615    psa_algorithm_t alg = alg_arg;
616    psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT;
617    unsigned char mac[PSA_MAC_MAX_SIZE];
618    size_t part_offset = 0;
619    size_t part_length = 0;
620    size_t data_part_len = 0;
621    size_t mac_len = 0;
622    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
623    psa_status_t status = PSA_ERROR_GENERIC_ERROR;
624
625    int test_ok = 0;
626    size_t part_count = 0;
627
628    PSA_INIT();
629
630    if (is_verify) {
631        psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_VERIFY_HASH);
632    } else {
633        psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH);
634    }
635
636    psa_set_key_algorithm(&attributes, alg);
637    psa_set_key_type(&attributes, key_type);
638
639    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
640                              &key));
641
642    if (is_verify) {
643        status = psa_mac_verify_setup(&operation, key, alg);
644    } else {
645        status = psa_mac_sign_setup(&operation, key, alg);
646    }
647
648    PSA_ASSERT(status);
649
650    if (data_part_len_arg != -1) {
651        /* Pass data in parts */
652        data_part_len = (size_t) data_part_len_arg;
653
654        for (part_offset = 0, part_count = 0;
655             part_offset < input_data->len;
656             part_offset += part_length, part_count++) {
657            if (do_zero_parts && (part_count & 0x01)) {
658                part_length = 0;
659            } else if ((input_data->len - part_offset) < data_part_len) {
660                part_length = (input_data->len - part_offset);
661            } else {
662                part_length = data_part_len;
663            }
664
665            PSA_ASSERT(psa_mac_update(&operation,
666                                      (input_data->x + part_offset),
667                                      part_length));
668        }
669    } else {
670        /* Pass all data in one go. */
671        PSA_ASSERT(psa_mac_update(&operation, input_data->x,
672                                  input_data->len));
673    }
674
675    if (is_verify) {
676        PSA_ASSERT(psa_mac_verify_finish(&operation, expected_output->x,
677                                         expected_output->len));
678    } else {
679        PSA_ASSERT(psa_mac_sign_finish(&operation, mac,
680                                       PSA_MAC_MAX_SIZE, &mac_len));
681
682        ASSERT_COMPARE(expected_output->x, expected_output->len,
683                       mac, mac_len);
684    }
685
686    test_ok = 1;
687
688exit:
689    psa_destroy_key(key);
690    psa_mac_abort(&operation);
691    PSA_DONE();
692
693    return test_ok;
694}
695
696#if defined(PSA_WANT_ALG_JPAKE)
697static void ecjpake_do_round(psa_algorithm_t alg, unsigned int primitive,
698                             psa_pake_operation_t *server,
699                             psa_pake_operation_t *client,
700                             int client_input_first,
701                             int round, int inject_error)
702{
703    unsigned char *buffer0 = NULL, *buffer1 = NULL;
704    size_t buffer_length = (
705        PSA_PAKE_OUTPUT_SIZE(alg, primitive, PSA_PAKE_STEP_KEY_SHARE) +
706        PSA_PAKE_OUTPUT_SIZE(alg, primitive, PSA_PAKE_STEP_ZK_PUBLIC) +
707        PSA_PAKE_OUTPUT_SIZE(alg, primitive, PSA_PAKE_STEP_ZK_PROOF)) * 2;
708    /* The output should be exactly this size according to the spec */
709    const size_t expected_size_key_share =
710        PSA_PAKE_OUTPUT_SIZE(alg, primitive, PSA_PAKE_STEP_KEY_SHARE);
711    /* The output should be exactly this size according to the spec */
712    const size_t expected_size_zk_public =
713        PSA_PAKE_OUTPUT_SIZE(alg, primitive, PSA_PAKE_STEP_ZK_PUBLIC);
714    /* The output can be smaller: the spec allows stripping leading zeroes */
715    const size_t max_expected_size_zk_proof =
716        PSA_PAKE_OUTPUT_SIZE(alg, primitive, PSA_PAKE_STEP_ZK_PROOF);
717    size_t buffer0_off = 0;
718    size_t buffer1_off = 0;
719    size_t s_g1_len, s_g2_len, s_a_len;
720    size_t s_g1_off, s_g2_off, s_a_off;
721    size_t s_x1_pk_len, s_x2_pk_len, s_x2s_pk_len;
722    size_t s_x1_pk_off, s_x2_pk_off, s_x2s_pk_off;
723    size_t s_x1_pr_len, s_x2_pr_len, s_x2s_pr_len;
724    size_t s_x1_pr_off, s_x2_pr_off, s_x2s_pr_off;
725    size_t c_g1_len, c_g2_len, c_a_len;
726    size_t c_g1_off, c_g2_off, c_a_off;
727    size_t c_x1_pk_len, c_x2_pk_len, c_x2s_pk_len;
728    size_t c_x1_pk_off, c_x2_pk_off, c_x2s_pk_off;
729    size_t c_x1_pr_len, c_x2_pr_len, c_x2s_pr_len;
730    size_t c_x1_pr_off, c_x2_pr_off, c_x2s_pr_off;
731    psa_status_t expected_status = PSA_SUCCESS;
732    psa_status_t status;
733
734    ASSERT_ALLOC(buffer0, buffer_length);
735    ASSERT_ALLOC(buffer1, buffer_length);
736
737    switch (round) {
738        case 1:
739            /* Server first round Output */
740            PSA_ASSERT(psa_pake_output(server, PSA_PAKE_STEP_KEY_SHARE,
741                                       buffer0 + buffer0_off,
742                                       512 - buffer0_off, &s_g1_len));
743            TEST_EQUAL(s_g1_len, expected_size_key_share);
744            s_g1_off = buffer0_off;
745            buffer0_off += s_g1_len;
746            PSA_ASSERT(psa_pake_output(server, PSA_PAKE_STEP_ZK_PUBLIC,
747                                       buffer0 + buffer0_off,
748                                       512 - buffer0_off, &s_x1_pk_len));
749            TEST_EQUAL(s_x1_pk_len, expected_size_zk_public);
750            s_x1_pk_off = buffer0_off;
751            buffer0_off += s_x1_pk_len;
752            PSA_ASSERT(psa_pake_output(server, PSA_PAKE_STEP_ZK_PROOF,
753                                       buffer0 + buffer0_off,
754                                       512 - buffer0_off, &s_x1_pr_len));
755            TEST_LE_U(s_x1_pr_len, max_expected_size_zk_proof);
756            s_x1_pr_off = buffer0_off;
757            buffer0_off += s_x1_pr_len;
758            PSA_ASSERT(psa_pake_output(server, PSA_PAKE_STEP_KEY_SHARE,
759                                       buffer0 + buffer0_off,
760                                       512 - buffer0_off, &s_g2_len));
761            TEST_EQUAL(s_g2_len, expected_size_key_share);
762            s_g2_off = buffer0_off;
763            buffer0_off += s_g2_len;
764            PSA_ASSERT(psa_pake_output(server, PSA_PAKE_STEP_ZK_PUBLIC,
765                                       buffer0 + buffer0_off,
766                                       512 - buffer0_off, &s_x2_pk_len));
767            TEST_EQUAL(s_x2_pk_len, expected_size_zk_public);
768            s_x2_pk_off = buffer0_off;
769            buffer0_off += s_x2_pk_len;
770            PSA_ASSERT(psa_pake_output(server, PSA_PAKE_STEP_ZK_PROOF,
771                                       buffer0 + buffer0_off,
772                                       512 - buffer0_off, &s_x2_pr_len));
773            TEST_LE_U(s_x2_pr_len, max_expected_size_zk_proof);
774            s_x2_pr_off = buffer0_off;
775            buffer0_off += s_x2_pr_len;
776
777            if (inject_error == 1) {
778                buffer0[s_x1_pr_off + 8] ^= 1;
779                buffer0[s_x2_pr_off + 7] ^= 1;
780                expected_status = PSA_ERROR_DATA_INVALID;
781            }
782
783            /*
784             * When injecting errors in inputs, the implementation is
785             * free to detect it right away of with a delay.
786             * This permits delaying the error until the end of the input
787             * sequence, if no error appears then, this will be treated
788             * as an error.
789             */
790
791            if (client_input_first == 1) {
792                /* Client first round Input */
793                status = psa_pake_input(client, PSA_PAKE_STEP_KEY_SHARE,
794                                        buffer0 + s_g1_off, s_g1_len);
795                if (inject_error == 1 && status != PSA_SUCCESS) {
796                    TEST_EQUAL(status, expected_status);
797                    break;
798                } else {
799                    TEST_EQUAL(status, PSA_SUCCESS);
800                }
801
802                status = psa_pake_input(client, PSA_PAKE_STEP_ZK_PUBLIC,
803                                        buffer0 + s_x1_pk_off,
804                                        s_x1_pk_len);
805                if (inject_error == 1 && status != PSA_SUCCESS) {
806                    TEST_EQUAL(status, expected_status);
807                    break;
808                } else {
809                    TEST_EQUAL(status, PSA_SUCCESS);
810                }
811
812                status = psa_pake_input(client, PSA_PAKE_STEP_ZK_PROOF,
813                                        buffer0 + s_x1_pr_off,
814                                        s_x1_pr_len);
815                if (inject_error == 1 && status != PSA_SUCCESS) {
816                    TEST_EQUAL(status, expected_status);
817                    break;
818                } else {
819                    TEST_EQUAL(status, PSA_SUCCESS);
820                }
821
822                status = psa_pake_input(client, PSA_PAKE_STEP_KEY_SHARE,
823                                        buffer0 + s_g2_off,
824                                        s_g2_len);
825                if (inject_error == 1 && status != PSA_SUCCESS) {
826                    TEST_EQUAL(status, expected_status);
827                    break;
828                } else {
829                    TEST_EQUAL(status, PSA_SUCCESS);
830                }
831
832                status = psa_pake_input(client, PSA_PAKE_STEP_ZK_PUBLIC,
833                                        buffer0 + s_x2_pk_off,
834                                        s_x2_pk_len);
835                if (inject_error == 1 && status != PSA_SUCCESS) {
836                    TEST_EQUAL(status, expected_status);
837                    break;
838                } else {
839                    TEST_EQUAL(status, PSA_SUCCESS);
840                }
841
842                status = psa_pake_input(client, PSA_PAKE_STEP_ZK_PROOF,
843                                        buffer0 + s_x2_pr_off,
844                                        s_x2_pr_len);
845                if (inject_error == 1 && status != PSA_SUCCESS) {
846                    TEST_EQUAL(status, expected_status);
847                    break;
848                } else {
849                    TEST_EQUAL(status, PSA_SUCCESS);
850                }
851
852                /* Error didn't trigger, make test fail */
853                if (inject_error == 1) {
854                    TEST_ASSERT(
855                        !"One of the last psa_pake_input() calls should have returned the expected error.");
856                }
857            }
858
859            /* Client first round Output */
860            PSA_ASSERT(psa_pake_output(client, PSA_PAKE_STEP_KEY_SHARE,
861                                       buffer1 + buffer1_off,
862                                       512 - buffer1_off, &c_g1_len));
863            TEST_EQUAL(c_g1_len, expected_size_key_share);
864            c_g1_off = buffer1_off;
865            buffer1_off += c_g1_len;
866            PSA_ASSERT(psa_pake_output(client, PSA_PAKE_STEP_ZK_PUBLIC,
867                                       buffer1 + buffer1_off,
868                                       512 - buffer1_off, &c_x1_pk_len));
869            TEST_EQUAL(c_x1_pk_len, expected_size_zk_public);
870            c_x1_pk_off = buffer1_off;
871            buffer1_off += c_x1_pk_len;
872            PSA_ASSERT(psa_pake_output(client, PSA_PAKE_STEP_ZK_PROOF,
873                                       buffer1 + buffer1_off,
874                                       512 - buffer1_off, &c_x1_pr_len));
875            TEST_LE_U(c_x1_pr_len, max_expected_size_zk_proof);
876            c_x1_pr_off = buffer1_off;
877            buffer1_off += c_x1_pr_len;
878            PSA_ASSERT(psa_pake_output(client, PSA_PAKE_STEP_KEY_SHARE,
879                                       buffer1 + buffer1_off,
880                                       512 - buffer1_off, &c_g2_len));
881            TEST_EQUAL(c_g2_len, expected_size_key_share);
882            c_g2_off = buffer1_off;
883            buffer1_off += c_g2_len;
884            PSA_ASSERT(psa_pake_output(client, PSA_PAKE_STEP_ZK_PUBLIC,
885                                       buffer1 + buffer1_off,
886                                       512 - buffer1_off, &c_x2_pk_len));
887            TEST_EQUAL(c_x2_pk_len, expected_size_zk_public);
888            c_x2_pk_off = buffer1_off;
889            buffer1_off += c_x2_pk_len;
890            PSA_ASSERT(psa_pake_output(client, PSA_PAKE_STEP_ZK_PROOF,
891                                       buffer1 + buffer1_off,
892                                       512 - buffer1_off, &c_x2_pr_len));
893            TEST_LE_U(c_x2_pr_len, max_expected_size_zk_proof);
894            c_x2_pr_off = buffer1_off;
895            buffer1_off += c_x2_pr_len;
896
897            if (client_input_first == 0) {
898                /* Client first round Input */
899                status = psa_pake_input(client, PSA_PAKE_STEP_KEY_SHARE,
900                                        buffer0 + s_g1_off, s_g1_len);
901                if (inject_error == 1 && status != PSA_SUCCESS) {
902                    TEST_EQUAL(status, expected_status);
903                    break;
904                } else {
905                    TEST_EQUAL(status, PSA_SUCCESS);
906                }
907
908                status = psa_pake_input(client, PSA_PAKE_STEP_ZK_PUBLIC,
909                                        buffer0 + s_x1_pk_off,
910                                        s_x1_pk_len);
911                if (inject_error == 1 && status != PSA_SUCCESS) {
912                    TEST_EQUAL(status, expected_status);
913                    break;
914                } else {
915                    TEST_EQUAL(status, PSA_SUCCESS);
916                }
917
918                status = psa_pake_input(client, PSA_PAKE_STEP_ZK_PROOF,
919                                        buffer0 + s_x1_pr_off,
920                                        s_x1_pr_len);
921                if (inject_error == 1 && status != PSA_SUCCESS) {
922                    TEST_EQUAL(status, expected_status);
923                    break;
924                } else {
925                    TEST_EQUAL(status, PSA_SUCCESS);
926                }
927
928                status = psa_pake_input(client, PSA_PAKE_STEP_KEY_SHARE,
929                                        buffer0 + s_g2_off,
930                                        s_g2_len);
931                if (inject_error == 1 && status != PSA_SUCCESS) {
932                    TEST_EQUAL(status, expected_status);
933                    break;
934                } else {
935                    TEST_EQUAL(status, PSA_SUCCESS);
936                }
937
938                status = psa_pake_input(client, PSA_PAKE_STEP_ZK_PUBLIC,
939                                        buffer0 + s_x2_pk_off,
940                                        s_x2_pk_len);
941                if (inject_error == 1 && status != PSA_SUCCESS) {
942                    TEST_EQUAL(status, expected_status);
943                    break;
944                } else {
945                    TEST_EQUAL(status, PSA_SUCCESS);
946                }
947
948                status = psa_pake_input(client, PSA_PAKE_STEP_ZK_PROOF,
949                                        buffer0 + s_x2_pr_off,
950                                        s_x2_pr_len);
951                if (inject_error == 1 && status != PSA_SUCCESS) {
952                    TEST_EQUAL(status, expected_status);
953                    break;
954                } else {
955                    TEST_EQUAL(status, PSA_SUCCESS);
956                }
957
958                /* Error didn't trigger, make test fail */
959                if (inject_error == 1) {
960                    TEST_ASSERT(
961                        !"One of the last psa_pake_input() calls should have returned the expected error.");
962                }
963            }
964
965            if (inject_error == 2) {
966                buffer1[c_x1_pr_off + 12] ^= 1;
967                buffer1[c_x2_pr_off + 7] ^= 1;
968                expected_status = PSA_ERROR_DATA_INVALID;
969            }
970
971            /* Server first round Input */
972            status = psa_pake_input(server, PSA_PAKE_STEP_KEY_SHARE,
973                                    buffer1 + c_g1_off, c_g1_len);
974            if (inject_error == 2 && status != PSA_SUCCESS) {
975                TEST_EQUAL(status, expected_status);
976                break;
977            } else {
978                TEST_EQUAL(status, PSA_SUCCESS);
979            }
980
981            status = psa_pake_input(server, PSA_PAKE_STEP_ZK_PUBLIC,
982                                    buffer1 + c_x1_pk_off, c_x1_pk_len);
983            if (inject_error == 2 && status != PSA_SUCCESS) {
984                TEST_EQUAL(status, expected_status);
985                break;
986            } else {
987                TEST_EQUAL(status, PSA_SUCCESS);
988            }
989
990            status = psa_pake_input(server, PSA_PAKE_STEP_ZK_PROOF,
991                                    buffer1 + c_x1_pr_off, c_x1_pr_len);
992            if (inject_error == 2 && status != PSA_SUCCESS) {
993                TEST_EQUAL(status, expected_status);
994                break;
995            } else {
996                TEST_EQUAL(status, PSA_SUCCESS);
997            }
998
999            status = psa_pake_input(server, PSA_PAKE_STEP_KEY_SHARE,
1000                                    buffer1 + c_g2_off, c_g2_len);
1001            if (inject_error == 2 && status != PSA_SUCCESS) {
1002                TEST_EQUAL(status, expected_status);
1003                break;
1004            } else {
1005                TEST_EQUAL(status, PSA_SUCCESS);
1006            }
1007
1008            status = psa_pake_input(server, PSA_PAKE_STEP_ZK_PUBLIC,
1009                                    buffer1 + c_x2_pk_off, c_x2_pk_len);
1010            if (inject_error == 2 && status != PSA_SUCCESS) {
1011                TEST_EQUAL(status, expected_status);
1012                break;
1013            } else {
1014                TEST_EQUAL(status, PSA_SUCCESS);
1015            }
1016
1017            status = psa_pake_input(server, PSA_PAKE_STEP_ZK_PROOF,
1018                                    buffer1 + c_x2_pr_off, c_x2_pr_len);
1019            if (inject_error == 2 && status != PSA_SUCCESS) {
1020                TEST_EQUAL(status, expected_status);
1021                break;
1022            } else {
1023                TEST_EQUAL(status, PSA_SUCCESS);
1024            }
1025
1026            /* Error didn't trigger, make test fail */
1027            if (inject_error == 2) {
1028                TEST_ASSERT(
1029                    !"One of the last psa_pake_input() calls should have returned the expected error.");
1030            }
1031
1032            break;
1033
1034        case 2:
1035            /* Server second round Output */
1036            buffer0_off = 0;
1037
1038            PSA_ASSERT(psa_pake_output(server, PSA_PAKE_STEP_KEY_SHARE,
1039                                       buffer0 + buffer0_off,
1040                                       512 - buffer0_off, &s_a_len));
1041            TEST_EQUAL(s_a_len, expected_size_key_share);
1042            s_a_off = buffer0_off;
1043            buffer0_off += s_a_len;
1044            PSA_ASSERT(psa_pake_output(server, PSA_PAKE_STEP_ZK_PUBLIC,
1045                                       buffer0 + buffer0_off,
1046                                       512 - buffer0_off, &s_x2s_pk_len));
1047            TEST_EQUAL(s_x2s_pk_len, expected_size_zk_public);
1048            s_x2s_pk_off = buffer0_off;
1049            buffer0_off += s_x2s_pk_len;
1050            PSA_ASSERT(psa_pake_output(server, PSA_PAKE_STEP_ZK_PROOF,
1051                                       buffer0 + buffer0_off,
1052                                       512 - buffer0_off, &s_x2s_pr_len));
1053            TEST_LE_U(s_x2s_pr_len, max_expected_size_zk_proof);
1054            s_x2s_pr_off = buffer0_off;
1055            buffer0_off += s_x2s_pr_len;
1056
1057            if (inject_error == 3) {
1058                buffer0[s_x2s_pk_off + 12] += 0x33;
1059                expected_status = PSA_ERROR_DATA_INVALID;
1060            }
1061
1062            if (client_input_first == 1) {
1063                /* Client second round Input */
1064                status = psa_pake_input(client, PSA_PAKE_STEP_KEY_SHARE,
1065                                        buffer0 + s_a_off, s_a_len);
1066                if (inject_error == 3 && status != PSA_SUCCESS) {
1067                    TEST_EQUAL(status, expected_status);
1068                    break;
1069                } else {
1070                    TEST_EQUAL(status, PSA_SUCCESS);
1071                }
1072
1073                status = psa_pake_input(client, PSA_PAKE_STEP_ZK_PUBLIC,
1074                                        buffer0 + s_x2s_pk_off,
1075                                        s_x2s_pk_len);
1076                if (inject_error == 3 && status != PSA_SUCCESS) {
1077                    TEST_EQUAL(status, expected_status);
1078                    break;
1079                } else {
1080                    TEST_EQUAL(status, PSA_SUCCESS);
1081                }
1082
1083                status = psa_pake_input(client, PSA_PAKE_STEP_ZK_PROOF,
1084                                        buffer0 + s_x2s_pr_off,
1085                                        s_x2s_pr_len);
1086                if (inject_error == 3 && status != PSA_SUCCESS) {
1087                    TEST_EQUAL(status, expected_status);
1088                    break;
1089                } else {
1090                    TEST_EQUAL(status, PSA_SUCCESS);
1091                }
1092
1093                /* Error didn't trigger, make test fail */
1094                if (inject_error == 3) {
1095                    TEST_ASSERT(
1096                        !"One of the last psa_pake_input() calls should have returned the expected error.");
1097                }
1098            }
1099
1100            /* Client second round Output */
1101            buffer1_off = 0;
1102
1103            PSA_ASSERT(psa_pake_output(client, PSA_PAKE_STEP_KEY_SHARE,
1104                                       buffer1 + buffer1_off,
1105                                       512 - buffer1_off, &c_a_len));
1106            TEST_EQUAL(c_a_len, expected_size_key_share);
1107            c_a_off = buffer1_off;
1108            buffer1_off += c_a_len;
1109            PSA_ASSERT(psa_pake_output(client, PSA_PAKE_STEP_ZK_PUBLIC,
1110                                       buffer1 + buffer1_off,
1111                                       512 - buffer1_off, &c_x2s_pk_len));
1112            TEST_EQUAL(c_x2s_pk_len, expected_size_zk_public);
1113            c_x2s_pk_off = buffer1_off;
1114            buffer1_off += c_x2s_pk_len;
1115            PSA_ASSERT(psa_pake_output(client, PSA_PAKE_STEP_ZK_PROOF,
1116                                       buffer1 + buffer1_off,
1117                                       512 - buffer1_off, &c_x2s_pr_len));
1118            TEST_LE_U(c_x2s_pr_len, max_expected_size_zk_proof);
1119            c_x2s_pr_off = buffer1_off;
1120            buffer1_off += c_x2s_pr_len;
1121
1122            if (client_input_first == 0) {
1123                /* Client second round Input */
1124                status = psa_pake_input(client, PSA_PAKE_STEP_KEY_SHARE,
1125                                        buffer0 + s_a_off, s_a_len);
1126                if (inject_error == 3 && status != PSA_SUCCESS) {
1127                    TEST_EQUAL(status, expected_status);
1128                    break;
1129                } else {
1130                    TEST_EQUAL(status, PSA_SUCCESS);
1131                }
1132
1133                status = psa_pake_input(client, PSA_PAKE_STEP_ZK_PUBLIC,
1134                                        buffer0 + s_x2s_pk_off,
1135                                        s_x2s_pk_len);
1136                if (inject_error == 3 && status != PSA_SUCCESS) {
1137                    TEST_EQUAL(status, expected_status);
1138                    break;
1139                } else {
1140                    TEST_EQUAL(status, PSA_SUCCESS);
1141                }
1142
1143                status = psa_pake_input(client, PSA_PAKE_STEP_ZK_PROOF,
1144                                        buffer0 + s_x2s_pr_off,
1145                                        s_x2s_pr_len);
1146                if (inject_error == 3 && status != PSA_SUCCESS) {
1147                    TEST_EQUAL(status, expected_status);
1148                    break;
1149                } else {
1150                    TEST_EQUAL(status, PSA_SUCCESS);
1151                }
1152
1153                /* Error didn't trigger, make test fail */
1154                if (inject_error == 3) {
1155                    TEST_ASSERT(
1156                        !"One of the last psa_pake_input() calls should have returned the expected error.");
1157                }
1158            }
1159
1160            if (inject_error == 4) {
1161                buffer1[c_x2s_pk_off + 7] += 0x28;
1162                expected_status = PSA_ERROR_DATA_INVALID;
1163            }
1164
1165            /* Server second round Input */
1166            status = psa_pake_input(server, PSA_PAKE_STEP_KEY_SHARE,
1167                                    buffer1 + c_a_off, c_a_len);
1168            if (inject_error == 4 && status != PSA_SUCCESS) {
1169                TEST_EQUAL(status, expected_status);
1170                break;
1171            } else {
1172                TEST_EQUAL(status, PSA_SUCCESS);
1173            }
1174
1175            status = psa_pake_input(server, PSA_PAKE_STEP_ZK_PUBLIC,
1176                                    buffer1 + c_x2s_pk_off, c_x2s_pk_len);
1177            if (inject_error == 4 && status != PSA_SUCCESS) {
1178                TEST_EQUAL(status, expected_status);
1179                break;
1180            } else {
1181                TEST_EQUAL(status, PSA_SUCCESS);
1182            }
1183
1184            status = psa_pake_input(server, PSA_PAKE_STEP_ZK_PROOF,
1185                                    buffer1 + c_x2s_pr_off, c_x2s_pr_len);
1186            if (inject_error == 4 && status != PSA_SUCCESS) {
1187                TEST_EQUAL(status, expected_status);
1188                break;
1189            } else {
1190                TEST_EQUAL(status, PSA_SUCCESS);
1191            }
1192
1193            /* Error didn't trigger, make test fail */
1194            if (inject_error == 4) {
1195                TEST_ASSERT(
1196                    !"One of the last psa_pake_input() calls should have returned the expected error.");
1197            }
1198
1199            break;
1200
1201    }
1202
1203exit:
1204    mbedtls_free(buffer0);
1205    mbedtls_free(buffer1);
1206}
1207#endif /* PSA_WANT_ALG_JPAKE */
1208
1209typedef enum {
1210    INJECT_ERR_NONE = 0,
1211    INJECT_ERR_UNINITIALIZED_ACCESS,
1212    INJECT_ERR_DUPLICATE_SETUP,
1213    INJECT_ERR_INVALID_USER,
1214    INJECT_ERR_INVALID_PEER,
1215    INJECT_ERR_SET_USER,
1216    INJECT_ERR_SET_PEER,
1217    INJECT_EMPTY_IO_BUFFER,
1218    INJECT_UNKNOWN_STEP,
1219    INJECT_INVALID_FIRST_STEP,
1220    INJECT_WRONG_BUFFER_SIZE,
1221    INJECT_VALID_OPERATION_AFTER_FAILURE,
1222    INJECT_ANTICIPATE_KEY_DERIVATION_1,
1223    INJECT_ANTICIPATE_KEY_DERIVATION_2,
1224} ecjpake_injected_failure_t;
1225
1226#if defined(MBEDTLS_ECP_RESTARTABLE)
1227
1228static void interruptible_signverify_get_minmax_completes(uint32_t max_ops,
1229                                                          psa_status_t expected_status,
1230                                                          size_t *min_completes,
1231                                                          size_t *max_completes)
1232{
1233
1234    /* This is slightly contrived, but we only really know that with a minimum
1235       value of max_ops that a successful operation should take more than one op
1236       to complete, and likewise that with a max_ops of
1237       PSA_INTERRUPTIBLE_MAX_OPS_UNLIMITED, it should complete in one go. */
1238    if (max_ops == 0 || max_ops == 1) {
1239
1240        if (expected_status == PSA_SUCCESS) {
1241            *min_completes = 2;
1242        } else {
1243            *min_completes = 1;
1244        }
1245
1246        *max_completes = PSA_INTERRUPTIBLE_MAX_OPS_UNLIMITED;
1247    } else {
1248        *min_completes = 1;
1249        *max_completes = 1;
1250    }
1251}
1252#endif /* MBEDTLS_ECP_RESTARTABLE */
1253
1254/* END_HEADER */
1255
1256/* BEGIN_DEPENDENCIES
1257 * depends_on:MBEDTLS_PSA_CRYPTO_C
1258 * END_DEPENDENCIES
1259 */
1260
1261/* BEGIN_CASE */
1262void psa_can_do_hash()
1263{
1264    /* We can't test that this is specific to drivers until partial init has
1265     * been implemented, but we can at least test before/after full init. */
1266    TEST_EQUAL(0, psa_can_do_hash(PSA_ALG_NONE));
1267    PSA_INIT();
1268    TEST_EQUAL(1, psa_can_do_hash(PSA_ALG_NONE));
1269    PSA_DONE();
1270}
1271/* END_CASE */
1272
1273/* BEGIN_CASE */
1274void static_checks()
1275{
1276    size_t max_truncated_mac_size =
1277        PSA_ALG_MAC_TRUNCATION_MASK >> PSA_MAC_TRUNCATION_OFFSET;
1278
1279    /* Check that the length for a truncated MAC always fits in the algorithm
1280     * encoding. The shifted mask is the maximum truncated value. The
1281     * untruncated algorithm may be one byte larger. */
1282    TEST_LE_U(PSA_MAC_MAX_SIZE, 1 + max_truncated_mac_size);
1283}
1284/* END_CASE */
1285
1286/* BEGIN_CASE */
1287void import_with_policy(int type_arg,
1288                        int usage_arg, int alg_arg,
1289                        int expected_status_arg)
1290{
1291    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
1292    psa_key_attributes_t got_attributes = PSA_KEY_ATTRIBUTES_INIT;
1293    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
1294    psa_key_type_t type = type_arg;
1295    psa_key_usage_t usage = usage_arg;
1296    psa_algorithm_t alg = alg_arg;
1297    psa_status_t expected_status = expected_status_arg;
1298    const uint8_t key_material[16] = { 0 };
1299    psa_status_t status;
1300
1301    PSA_ASSERT(psa_crypto_init());
1302
1303    psa_set_key_type(&attributes, type);
1304    psa_set_key_usage_flags(&attributes, usage);
1305    psa_set_key_algorithm(&attributes, alg);
1306
1307    status = psa_import_key(&attributes,
1308                            key_material, sizeof(key_material),
1309                            &key);
1310    TEST_EQUAL(status, expected_status);
1311    if (status != PSA_SUCCESS) {
1312        goto exit;
1313    }
1314
1315    PSA_ASSERT(psa_get_key_attributes(key, &got_attributes));
1316    TEST_EQUAL(psa_get_key_type(&got_attributes), type);
1317    TEST_EQUAL(psa_get_key_usage_flags(&got_attributes),
1318               mbedtls_test_update_key_usage_flags(usage));
1319    TEST_EQUAL(psa_get_key_algorithm(&got_attributes), alg);
1320    ASSERT_NO_SLOT_NUMBER(&got_attributes);
1321
1322    PSA_ASSERT(psa_destroy_key(key));
1323    test_operations_on_invalid_key(key);
1324
1325exit:
1326    /*
1327     * Key attributes may have been returned by psa_get_key_attributes()
1328     * thus reset them as required.
1329     */
1330    psa_reset_key_attributes(&got_attributes);
1331
1332    psa_destroy_key(key);
1333    PSA_DONE();
1334}
1335/* END_CASE */
1336
1337/* BEGIN_CASE */
1338void import_with_data(data_t *data, int type_arg,
1339                      int attr_bits_arg,
1340                      int expected_status_arg)
1341{
1342    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
1343    psa_key_attributes_t got_attributes = PSA_KEY_ATTRIBUTES_INIT;
1344    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
1345    psa_key_type_t type = type_arg;
1346    size_t attr_bits = attr_bits_arg;
1347    psa_status_t expected_status = expected_status_arg;
1348    psa_status_t status;
1349
1350    PSA_ASSERT(psa_crypto_init());
1351
1352    psa_set_key_type(&attributes, type);
1353    psa_set_key_bits(&attributes, attr_bits);
1354
1355    status = psa_import_key(&attributes, data->x, data->len, &key);
1356    TEST_EQUAL(status, expected_status);
1357    if (status != PSA_SUCCESS) {
1358        goto exit;
1359    }
1360
1361    PSA_ASSERT(psa_get_key_attributes(key, &got_attributes));
1362    TEST_EQUAL(psa_get_key_type(&got_attributes), type);
1363    if (attr_bits != 0) {
1364        TEST_EQUAL(attr_bits, psa_get_key_bits(&got_attributes));
1365    }
1366    ASSERT_NO_SLOT_NUMBER(&got_attributes);
1367
1368    PSA_ASSERT(psa_destroy_key(key));
1369    test_operations_on_invalid_key(key);
1370
1371exit:
1372    /*
1373     * Key attributes may have been returned by psa_get_key_attributes()
1374     * thus reset them as required.
1375     */
1376    psa_reset_key_attributes(&got_attributes);
1377
1378    psa_destroy_key(key);
1379    PSA_DONE();
1380}
1381/* END_CASE */
1382
1383/* BEGIN_CASE */
1384/* Construct and attempt to import a large unstructured key. */
1385void import_large_key(int type_arg, int byte_size_arg,
1386                      int expected_status_arg)
1387{
1388    psa_key_type_t type = type_arg;
1389    size_t byte_size = byte_size_arg;
1390    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
1391    psa_status_t expected_status = expected_status_arg;
1392    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
1393    psa_status_t status;
1394    uint8_t *buffer = NULL;
1395    size_t buffer_size = byte_size + 1;
1396    size_t n;
1397
1398    /* Skip the test case if the target running the test cannot
1399     * accommodate large keys due to heap size constraints */
1400    ASSERT_ALLOC_WEAK(buffer, buffer_size);
1401    memset(buffer, 'K', byte_size);
1402
1403    PSA_ASSERT(psa_crypto_init());
1404
1405    /* Try importing the key */
1406    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_EXPORT);
1407    psa_set_key_type(&attributes, type);
1408    status = psa_import_key(&attributes, buffer, byte_size, &key);
1409    TEST_ASSUME(status != PSA_ERROR_INSUFFICIENT_MEMORY);
1410    TEST_EQUAL(status, expected_status);
1411
1412    if (status == PSA_SUCCESS) {
1413        PSA_ASSERT(psa_get_key_attributes(key, &attributes));
1414        TEST_EQUAL(psa_get_key_type(&attributes), type);
1415        TEST_EQUAL(psa_get_key_bits(&attributes),
1416                   PSA_BYTES_TO_BITS(byte_size));
1417        ASSERT_NO_SLOT_NUMBER(&attributes);
1418        memset(buffer, 0, byte_size + 1);
1419        PSA_ASSERT(psa_export_key(key, buffer, byte_size, &n));
1420        for (n = 0; n < byte_size; n++) {
1421            TEST_EQUAL(buffer[n], 'K');
1422        }
1423        for (n = byte_size; n < buffer_size; n++) {
1424            TEST_EQUAL(buffer[n], 0);
1425        }
1426    }
1427
1428exit:
1429    /*
1430     * Key attributes may have been returned by psa_get_key_attributes()
1431     * thus reset them as required.
1432     */
1433    psa_reset_key_attributes(&attributes);
1434
1435    psa_destroy_key(key);
1436    PSA_DONE();
1437    mbedtls_free(buffer);
1438}
1439/* END_CASE */
1440
1441/* BEGIN_CASE depends_on:MBEDTLS_ASN1_WRITE_C */
1442/* Import an RSA key with a valid structure (but not valid numbers
1443 * inside, beyond having sensible size and parity). This is expected to
1444 * fail for large keys. */
1445void import_rsa_made_up(int bits_arg, int keypair, int expected_status_arg)
1446{
1447    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
1448    size_t bits = bits_arg;
1449    psa_status_t expected_status = expected_status_arg;
1450    psa_status_t status;
1451    psa_key_type_t type =
1452        keypair ? PSA_KEY_TYPE_RSA_KEY_PAIR : PSA_KEY_TYPE_RSA_PUBLIC_KEY;
1453    size_t buffer_size = /* Slight overapproximations */
1454                         keypair ? bits * 9 / 16 + 80 : bits / 8 + 20;
1455    unsigned char *buffer = NULL;
1456    unsigned char *p;
1457    int ret;
1458    size_t length;
1459    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
1460
1461    PSA_ASSERT(psa_crypto_init());
1462    ASSERT_ALLOC(buffer, buffer_size);
1463
1464    TEST_ASSERT((ret = construct_fake_rsa_key(buffer, buffer_size, &p,
1465                                              bits, keypair)) >= 0);
1466    length = ret;
1467
1468    /* Try importing the key */
1469    psa_set_key_type(&attributes, type);
1470    status = psa_import_key(&attributes, p, length, &key);
1471    TEST_EQUAL(status, expected_status);
1472
1473    if (status == PSA_SUCCESS) {
1474        PSA_ASSERT(psa_destroy_key(key));
1475    }
1476
1477exit:
1478    mbedtls_free(buffer);
1479    PSA_DONE();
1480}
1481/* END_CASE */
1482
1483/* BEGIN_CASE */
1484void import_export(data_t *data,
1485                   int type_arg,
1486                   int usage_arg, int alg_arg,
1487                   int lifetime_arg,
1488                   int expected_bits,
1489                   int export_size_delta,
1490                   int expected_export_status_arg,
1491                   /*whether reexport must give the original input exactly*/
1492                   int canonical_input)
1493{
1494    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
1495    psa_key_type_t type = type_arg;
1496    psa_algorithm_t alg = alg_arg;
1497    psa_status_t expected_export_status = expected_export_status_arg;
1498    psa_status_t status;
1499    psa_key_lifetime_t lifetime = lifetime_arg;
1500    unsigned char *exported = NULL;
1501    unsigned char *reexported = NULL;
1502    size_t export_size;
1503    size_t exported_length = INVALID_EXPORT_LENGTH;
1504    size_t reexported_length;
1505    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
1506    psa_key_attributes_t got_attributes = PSA_KEY_ATTRIBUTES_INIT;
1507
1508    export_size = (ptrdiff_t) data->len + export_size_delta;
1509    ASSERT_ALLOC(exported, export_size);
1510    if (!canonical_input) {
1511        ASSERT_ALLOC(reexported, export_size);
1512    }
1513    PSA_ASSERT(psa_crypto_init());
1514
1515    psa_set_key_lifetime(&attributes, lifetime);
1516    psa_set_key_usage_flags(&attributes, usage_arg);
1517    psa_set_key_algorithm(&attributes, alg);
1518    psa_set_key_type(&attributes, type);
1519
1520    /* Import the key */
1521    PSA_ASSERT(psa_import_key(&attributes, data->x, data->len, &key));
1522
1523    /* Test the key information */
1524    PSA_ASSERT(psa_get_key_attributes(key, &got_attributes));
1525    TEST_EQUAL(psa_get_key_type(&got_attributes), type);
1526    TEST_EQUAL(psa_get_key_bits(&got_attributes), (size_t) expected_bits);
1527    ASSERT_NO_SLOT_NUMBER(&got_attributes);
1528
1529    /* Export the key */
1530    status = psa_export_key(key, exported, export_size, &exported_length);
1531    TEST_EQUAL(status, expected_export_status);
1532
1533    /* The exported length must be set by psa_export_key() to a value between 0
1534     * and export_size. On errors, the exported length must be 0. */
1535    TEST_ASSERT(exported_length != INVALID_EXPORT_LENGTH);
1536    TEST_ASSERT(status == PSA_SUCCESS || exported_length == 0);
1537    TEST_LE_U(exported_length, export_size);
1538
1539    TEST_ASSERT(mem_is_char(exported + exported_length, 0,
1540                            export_size - exported_length));
1541    if (status != PSA_SUCCESS) {
1542        TEST_EQUAL(exported_length, 0);
1543        goto destroy;
1544    }
1545
1546    /* Run sanity checks on the exported key. For non-canonical inputs,
1547     * this validates the canonical representations. For canonical inputs,
1548     * this doesn't directly validate the implementation, but it still helps
1549     * by cross-validating the test data with the sanity check code. */
1550    if (!psa_key_lifetime_is_external(lifetime)) {
1551        if (!mbedtls_test_psa_exercise_key(key, usage_arg, 0)) {
1552            goto exit;
1553        }
1554    }
1555
1556    if (canonical_input) {
1557        ASSERT_COMPARE(data->x, data->len, exported, exported_length);
1558    } else {
1559        mbedtls_svc_key_id_t key2 = MBEDTLS_SVC_KEY_ID_INIT;
1560        PSA_ASSERT(psa_import_key(&attributes, exported, exported_length,
1561                                  &key2));
1562        PSA_ASSERT(psa_export_key(key2,
1563                                  reexported,
1564                                  export_size,
1565                                  &reexported_length));
1566        ASSERT_COMPARE(exported, exported_length,
1567                       reexported, reexported_length);
1568        PSA_ASSERT(psa_destroy_key(key2));
1569    }
1570    TEST_LE_U(exported_length,
1571              PSA_EXPORT_KEY_OUTPUT_SIZE(type,
1572                                         psa_get_key_bits(&got_attributes)));
1573    TEST_LE_U(exported_length, PSA_EXPORT_KEY_PAIR_MAX_SIZE);
1574
1575destroy:
1576    /* Destroy the key */
1577    PSA_ASSERT(psa_destroy_key(key));
1578    test_operations_on_invalid_key(key);
1579
1580exit:
1581    /*
1582     * Key attributes may have been returned by psa_get_key_attributes()
1583     * thus reset them as required.
1584     */
1585    psa_reset_key_attributes(&got_attributes);
1586    psa_destroy_key(key);
1587    mbedtls_free(exported);
1588    mbedtls_free(reexported);
1589    PSA_DONE();
1590}
1591/* END_CASE */
1592
1593/* BEGIN_CASE */
1594void import_export_public_key(data_t *data,
1595                              int type_arg,  // key pair or public key
1596                              int alg_arg,
1597                              int lifetime_arg,
1598                              int export_size_delta,
1599                              int expected_export_status_arg,
1600                              data_t *expected_public_key)
1601{
1602    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
1603    psa_key_type_t type = type_arg;
1604    psa_algorithm_t alg = alg_arg;
1605    psa_status_t expected_export_status = expected_export_status_arg;
1606    psa_status_t status;
1607    psa_key_lifetime_t lifetime = lifetime_arg;
1608    unsigned char *exported = NULL;
1609    size_t export_size = expected_public_key->len + export_size_delta;
1610    size_t exported_length = INVALID_EXPORT_LENGTH;
1611    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
1612
1613    PSA_ASSERT(psa_crypto_init());
1614
1615    psa_set_key_lifetime(&attributes, lifetime);
1616    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_EXPORT);
1617    psa_set_key_algorithm(&attributes, alg);
1618    psa_set_key_type(&attributes, type);
1619
1620    /* Import the key */
1621    PSA_ASSERT(psa_import_key(&attributes, data->x, data->len, &key));
1622
1623    /* Export the public key */
1624    ASSERT_ALLOC(exported, export_size);
1625    status = psa_export_public_key(key,
1626                                   exported, export_size,
1627                                   &exported_length);
1628    TEST_EQUAL(status, expected_export_status);
1629    if (status == PSA_SUCCESS) {
1630        psa_key_type_t public_type = PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(type);
1631        size_t bits;
1632        PSA_ASSERT(psa_get_key_attributes(key, &attributes));
1633        bits = psa_get_key_bits(&attributes);
1634        TEST_LE_U(expected_public_key->len,
1635                  PSA_EXPORT_KEY_OUTPUT_SIZE(public_type, bits));
1636        TEST_LE_U(expected_public_key->len,
1637                  PSA_EXPORT_PUBLIC_KEY_OUTPUT_SIZE(public_type, bits));
1638        TEST_LE_U(expected_public_key->len,
1639                  PSA_EXPORT_PUBLIC_KEY_MAX_SIZE);
1640        ASSERT_COMPARE(expected_public_key->x, expected_public_key->len,
1641                       exported, exported_length);
1642    }
1643exit:
1644    /*
1645     * Key attributes may have been returned by psa_get_key_attributes()
1646     * thus reset them as required.
1647     */
1648    psa_reset_key_attributes(&attributes);
1649
1650    mbedtls_free(exported);
1651    psa_destroy_key(key);
1652    PSA_DONE();
1653}
1654/* END_CASE */
1655
1656/* BEGIN_CASE */
1657void import_and_exercise_key(data_t *data,
1658                             int type_arg,
1659                             int bits_arg,
1660                             int alg_arg)
1661{
1662    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
1663    psa_key_type_t type = type_arg;
1664    size_t bits = bits_arg;
1665    psa_algorithm_t alg = alg_arg;
1666    psa_key_usage_t usage = mbedtls_test_psa_usage_to_exercise(type, alg);
1667    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
1668    psa_key_attributes_t got_attributes = PSA_KEY_ATTRIBUTES_INIT;
1669
1670    PSA_ASSERT(psa_crypto_init());
1671
1672    psa_set_key_usage_flags(&attributes, usage);
1673    psa_set_key_algorithm(&attributes, alg);
1674    psa_set_key_type(&attributes, type);
1675
1676    /* Import the key */
1677    PSA_ASSERT(psa_import_key(&attributes, data->x, data->len, &key));
1678
1679    /* Test the key information */
1680    PSA_ASSERT(psa_get_key_attributes(key, &got_attributes));
1681    TEST_EQUAL(psa_get_key_type(&got_attributes), type);
1682    TEST_EQUAL(psa_get_key_bits(&got_attributes), bits);
1683
1684    /* Do something with the key according to its type and permitted usage. */
1685    if (!mbedtls_test_psa_exercise_key(key, usage, alg)) {
1686        goto exit;
1687    }
1688
1689    PSA_ASSERT(psa_destroy_key(key));
1690    test_operations_on_invalid_key(key);
1691
1692exit:
1693    /*
1694     * Key attributes may have been returned by psa_get_key_attributes()
1695     * thus reset them as required.
1696     */
1697    psa_reset_key_attributes(&got_attributes);
1698
1699    psa_reset_key_attributes(&attributes);
1700    psa_destroy_key(key);
1701    PSA_DONE();
1702}
1703/* END_CASE */
1704
1705/* BEGIN_CASE */
1706void effective_key_attributes(int type_arg, int expected_type_arg,
1707                              int bits_arg, int expected_bits_arg,
1708                              int usage_arg, int expected_usage_arg,
1709                              int alg_arg, int expected_alg_arg)
1710{
1711    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
1712    psa_key_type_t key_type = type_arg;
1713    psa_key_type_t expected_key_type = expected_type_arg;
1714    size_t bits = bits_arg;
1715    size_t expected_bits = expected_bits_arg;
1716    psa_algorithm_t alg = alg_arg;
1717    psa_algorithm_t expected_alg = expected_alg_arg;
1718    psa_key_usage_t usage = usage_arg;
1719    psa_key_usage_t expected_usage = expected_usage_arg;
1720    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
1721
1722    PSA_ASSERT(psa_crypto_init());
1723
1724    psa_set_key_usage_flags(&attributes, usage);
1725    psa_set_key_algorithm(&attributes, alg);
1726    psa_set_key_type(&attributes, key_type);
1727    psa_set_key_bits(&attributes, bits);
1728
1729    PSA_ASSERT(psa_generate_key(&attributes, &key));
1730    psa_reset_key_attributes(&attributes);
1731
1732    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
1733    TEST_EQUAL(psa_get_key_type(&attributes), expected_key_type);
1734    TEST_EQUAL(psa_get_key_bits(&attributes), expected_bits);
1735    TEST_EQUAL(psa_get_key_usage_flags(&attributes), expected_usage);
1736    TEST_EQUAL(psa_get_key_algorithm(&attributes), expected_alg);
1737
1738exit:
1739    /*
1740     * Key attributes may have been returned by psa_get_key_attributes()
1741     * thus reset them as required.
1742     */
1743    psa_reset_key_attributes(&attributes);
1744
1745    psa_destroy_key(key);
1746    PSA_DONE();
1747}
1748/* END_CASE */
1749
1750/* BEGIN_CASE */
1751void check_key_policy(int type_arg, int bits_arg,
1752                      int usage_arg, int alg_arg)
1753{
1754    test_effective_key_attributes(type_arg, type_arg, bits_arg, bits_arg,
1755                                  usage_arg,
1756                                  mbedtls_test_update_key_usage_flags(usage_arg),
1757                                  alg_arg, alg_arg);
1758    goto exit;
1759}
1760/* END_CASE */
1761
1762/* BEGIN_CASE */
1763void key_attributes_init()
1764{
1765    /* Test each valid way of initializing the object, except for `= {0}`, as
1766     * Clang 5 complains when `-Wmissing-field-initializers` is used, even
1767     * though it's OK by the C standard. We could test for this, but we'd need
1768     * to suppress the Clang warning for the test. */
1769    psa_key_attributes_t func = psa_key_attributes_init();
1770    psa_key_attributes_t init = PSA_KEY_ATTRIBUTES_INIT;
1771    psa_key_attributes_t zero;
1772
1773    memset(&zero, 0, sizeof(zero));
1774
1775    TEST_EQUAL(psa_get_key_lifetime(&func), PSA_KEY_LIFETIME_VOLATILE);
1776    TEST_EQUAL(psa_get_key_lifetime(&init), PSA_KEY_LIFETIME_VOLATILE);
1777    TEST_EQUAL(psa_get_key_lifetime(&zero), PSA_KEY_LIFETIME_VOLATILE);
1778
1779    TEST_EQUAL(psa_get_key_type(&func), 0);
1780    TEST_EQUAL(psa_get_key_type(&init), 0);
1781    TEST_EQUAL(psa_get_key_type(&zero), 0);
1782
1783    TEST_EQUAL(psa_get_key_bits(&func), 0);
1784    TEST_EQUAL(psa_get_key_bits(&init), 0);
1785    TEST_EQUAL(psa_get_key_bits(&zero), 0);
1786
1787    TEST_EQUAL(psa_get_key_usage_flags(&func), 0);
1788    TEST_EQUAL(psa_get_key_usage_flags(&init), 0);
1789    TEST_EQUAL(psa_get_key_usage_flags(&zero), 0);
1790
1791    TEST_EQUAL(psa_get_key_algorithm(&func), 0);
1792    TEST_EQUAL(psa_get_key_algorithm(&init), 0);
1793    TEST_EQUAL(psa_get_key_algorithm(&zero), 0);
1794}
1795/* END_CASE */
1796
1797/* BEGIN_CASE */
1798void mac_key_policy(int policy_usage_arg,
1799                    int policy_alg_arg,
1800                    int key_type_arg,
1801                    data_t *key_data,
1802                    int exercise_alg_arg,
1803                    int expected_status_sign_arg,
1804                    int expected_status_verify_arg)
1805{
1806    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
1807    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
1808    psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT;
1809    psa_key_type_t key_type = key_type_arg;
1810    psa_algorithm_t policy_alg = policy_alg_arg;
1811    psa_algorithm_t exercise_alg = exercise_alg_arg;
1812    psa_key_usage_t policy_usage = policy_usage_arg;
1813    psa_status_t status;
1814    psa_status_t expected_status_sign = expected_status_sign_arg;
1815    psa_status_t expected_status_verify = expected_status_verify_arg;
1816    unsigned char mac[PSA_MAC_MAX_SIZE];
1817
1818    PSA_ASSERT(psa_crypto_init());
1819
1820    psa_set_key_usage_flags(&attributes, policy_usage);
1821    psa_set_key_algorithm(&attributes, policy_alg);
1822    psa_set_key_type(&attributes, key_type);
1823
1824    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
1825                              &key));
1826
1827    TEST_EQUAL(psa_get_key_usage_flags(&attributes),
1828               mbedtls_test_update_key_usage_flags(policy_usage));
1829
1830    status = psa_mac_sign_setup(&operation, key, exercise_alg);
1831    TEST_EQUAL(status, expected_status_sign);
1832
1833    /* Calculate the MAC, one-shot case. */
1834    uint8_t input[128] = { 0 };
1835    size_t mac_len;
1836    TEST_EQUAL(psa_mac_compute(key, exercise_alg,
1837                               input, 128,
1838                               mac, PSA_MAC_MAX_SIZE, &mac_len),
1839               expected_status_sign);
1840
1841    /* Calculate the MAC, multi-part case. */
1842    PSA_ASSERT(psa_mac_abort(&operation));
1843    status = psa_mac_sign_setup(&operation, key, exercise_alg);
1844    if (status == PSA_SUCCESS) {
1845        status = psa_mac_update(&operation, input, 128);
1846        if (status == PSA_SUCCESS) {
1847            TEST_EQUAL(psa_mac_sign_finish(&operation, mac, PSA_MAC_MAX_SIZE,
1848                                           &mac_len),
1849                       expected_status_sign);
1850        } else {
1851            TEST_EQUAL(status, expected_status_sign);
1852        }
1853    } else {
1854        TEST_EQUAL(status, expected_status_sign);
1855    }
1856    PSA_ASSERT(psa_mac_abort(&operation));
1857
1858    /* Verify correct MAC, one-shot case. */
1859    status = psa_mac_verify(key, exercise_alg, input, 128,
1860                            mac, mac_len);
1861
1862    if (expected_status_sign != PSA_SUCCESS && expected_status_verify == PSA_SUCCESS) {
1863        TEST_EQUAL(status, PSA_ERROR_INVALID_SIGNATURE);
1864    } else {
1865        TEST_EQUAL(status, expected_status_verify);
1866    }
1867
1868    /* Verify correct MAC, multi-part case. */
1869    status = psa_mac_verify_setup(&operation, key, exercise_alg);
1870    if (status == PSA_SUCCESS) {
1871        status = psa_mac_update(&operation, input, 128);
1872        if (status == PSA_SUCCESS) {
1873            status = psa_mac_verify_finish(&operation, mac, mac_len);
1874            if (expected_status_sign != PSA_SUCCESS && expected_status_verify == PSA_SUCCESS) {
1875                TEST_EQUAL(status, PSA_ERROR_INVALID_SIGNATURE);
1876            } else {
1877                TEST_EQUAL(status, expected_status_verify);
1878            }
1879        } else {
1880            TEST_EQUAL(status, expected_status_verify);
1881        }
1882    } else {
1883        TEST_EQUAL(status, expected_status_verify);
1884    }
1885
1886    psa_mac_abort(&operation);
1887
1888    memset(mac, 0, sizeof(mac));
1889    status = psa_mac_verify_setup(&operation, key, exercise_alg);
1890    TEST_EQUAL(status, expected_status_verify);
1891
1892exit:
1893    psa_mac_abort(&operation);
1894    psa_destroy_key(key);
1895    PSA_DONE();
1896}
1897/* END_CASE */
1898
1899/* BEGIN_CASE */
1900void cipher_key_policy(int policy_usage_arg,
1901                       int policy_alg,
1902                       int key_type,
1903                       data_t *key_data,
1904                       int exercise_alg)
1905{
1906    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
1907    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
1908    psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT;
1909    psa_key_usage_t policy_usage = policy_usage_arg;
1910    size_t output_buffer_size = 0;
1911    size_t input_buffer_size = 0;
1912    size_t output_length = 0;
1913    uint8_t *output = NULL;
1914    uint8_t *input = NULL;
1915    psa_status_t status;
1916
1917    input_buffer_size = PSA_BLOCK_CIPHER_BLOCK_LENGTH(exercise_alg);
1918    output_buffer_size = PSA_CIPHER_ENCRYPT_OUTPUT_SIZE(key_type, exercise_alg,
1919                                                        input_buffer_size);
1920
1921    ASSERT_ALLOC(input, input_buffer_size);
1922    ASSERT_ALLOC(output, output_buffer_size);
1923
1924    PSA_ASSERT(psa_crypto_init());
1925
1926    psa_set_key_usage_flags(&attributes, policy_usage);
1927    psa_set_key_algorithm(&attributes, policy_alg);
1928    psa_set_key_type(&attributes, key_type);
1929
1930    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
1931                              &key));
1932
1933    /* Check if no key usage flag implication is done */
1934    TEST_EQUAL(policy_usage,
1935               mbedtls_test_update_key_usage_flags(policy_usage));
1936
1937    /* Encrypt check, one-shot */
1938    status = psa_cipher_encrypt(key, exercise_alg, input, input_buffer_size,
1939                                output, output_buffer_size,
1940                                &output_length);
1941    if (policy_alg == exercise_alg &&
1942        (policy_usage & PSA_KEY_USAGE_ENCRYPT) != 0) {
1943        PSA_ASSERT(status);
1944    } else {
1945        TEST_EQUAL(status, PSA_ERROR_NOT_PERMITTED);
1946    }
1947
1948    /* Encrypt check, multi-part */
1949    status = psa_cipher_encrypt_setup(&operation, key, exercise_alg);
1950    if (policy_alg == exercise_alg &&
1951        (policy_usage & PSA_KEY_USAGE_ENCRYPT) != 0) {
1952        PSA_ASSERT(status);
1953    } else {
1954        TEST_EQUAL(status, PSA_ERROR_NOT_PERMITTED);
1955    }
1956    psa_cipher_abort(&operation);
1957
1958    /* Decrypt check, one-shot */
1959    status = psa_cipher_decrypt(key, exercise_alg, output, output_buffer_size,
1960                                input, input_buffer_size,
1961                                &output_length);
1962    if (policy_alg == exercise_alg &&
1963        (policy_usage & PSA_KEY_USAGE_DECRYPT) != 0) {
1964        PSA_ASSERT(status);
1965    } else {
1966        TEST_EQUAL(status, PSA_ERROR_NOT_PERMITTED);
1967    }
1968
1969    /* Decrypt check, multi-part */
1970    status = psa_cipher_decrypt_setup(&operation, key, exercise_alg);
1971    if (policy_alg == exercise_alg &&
1972        (policy_usage & PSA_KEY_USAGE_DECRYPT) != 0) {
1973        PSA_ASSERT(status);
1974    } else {
1975        TEST_EQUAL(status, PSA_ERROR_NOT_PERMITTED);
1976    }
1977
1978exit:
1979    psa_cipher_abort(&operation);
1980    mbedtls_free(input);
1981    mbedtls_free(output);
1982    psa_destroy_key(key);
1983    PSA_DONE();
1984}
1985/* END_CASE */
1986
1987/* BEGIN_CASE */
1988void aead_key_policy(int policy_usage_arg,
1989                     int policy_alg,
1990                     int key_type,
1991                     data_t *key_data,
1992                     int nonce_length_arg,
1993                     int tag_length_arg,
1994                     int exercise_alg,
1995                     int expected_status_arg)
1996{
1997    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
1998    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
1999    psa_aead_operation_t operation = PSA_AEAD_OPERATION_INIT;
2000    psa_key_usage_t policy_usage = policy_usage_arg;
2001    psa_status_t status;
2002    psa_status_t expected_status = expected_status_arg;
2003    unsigned char nonce[16] = { 0 };
2004    size_t nonce_length = nonce_length_arg;
2005    unsigned char tag[16];
2006    size_t tag_length = tag_length_arg;
2007    size_t output_length;
2008
2009    TEST_LE_U(nonce_length, sizeof(nonce));
2010    TEST_LE_U(tag_length, sizeof(tag));
2011
2012    PSA_ASSERT(psa_crypto_init());
2013
2014    psa_set_key_usage_flags(&attributes, policy_usage);
2015    psa_set_key_algorithm(&attributes, policy_alg);
2016    psa_set_key_type(&attributes, key_type);
2017
2018    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
2019                              &key));
2020
2021    /* Check if no key usage implication is done */
2022    TEST_EQUAL(policy_usage,
2023               mbedtls_test_update_key_usage_flags(policy_usage));
2024
2025    /* Encrypt check, one-shot */
2026    status = psa_aead_encrypt(key, exercise_alg,
2027                              nonce, nonce_length,
2028                              NULL, 0,
2029                              NULL, 0,
2030                              tag, tag_length,
2031                              &output_length);
2032    if ((policy_usage & PSA_KEY_USAGE_ENCRYPT) != 0) {
2033        TEST_EQUAL(status, expected_status);
2034    } else {
2035        TEST_EQUAL(status, PSA_ERROR_NOT_PERMITTED);
2036    }
2037
2038    /* Encrypt check, multi-part */
2039    status = psa_aead_encrypt_setup(&operation, key, exercise_alg);
2040    if ((policy_usage & PSA_KEY_USAGE_ENCRYPT) != 0) {
2041        TEST_EQUAL(status, expected_status);
2042    } else {
2043        TEST_EQUAL(status, PSA_ERROR_NOT_PERMITTED);
2044    }
2045
2046    /* Decrypt check, one-shot */
2047    memset(tag, 0, sizeof(tag));
2048    status = psa_aead_decrypt(key, exercise_alg,
2049                              nonce, nonce_length,
2050                              NULL, 0,
2051                              tag, tag_length,
2052                              NULL, 0,
2053                              &output_length);
2054    if ((policy_usage & PSA_KEY_USAGE_DECRYPT) == 0) {
2055        TEST_EQUAL(status, PSA_ERROR_NOT_PERMITTED);
2056    } else if (expected_status == PSA_SUCCESS) {
2057        TEST_EQUAL(status, PSA_ERROR_INVALID_SIGNATURE);
2058    } else {
2059        TEST_EQUAL(status, expected_status);
2060    }
2061
2062    /* Decrypt check, multi-part */
2063    PSA_ASSERT(psa_aead_abort(&operation));
2064    status = psa_aead_decrypt_setup(&operation, key, exercise_alg);
2065    if ((policy_usage & PSA_KEY_USAGE_DECRYPT) == 0) {
2066        TEST_EQUAL(status, PSA_ERROR_NOT_PERMITTED);
2067    } else {
2068        TEST_EQUAL(status, expected_status);
2069    }
2070
2071exit:
2072    PSA_ASSERT(psa_aead_abort(&operation));
2073    psa_destroy_key(key);
2074    PSA_DONE();
2075}
2076/* END_CASE */
2077
2078/* BEGIN_CASE */
2079void asymmetric_encryption_key_policy(int policy_usage_arg,
2080                                      int policy_alg,
2081                                      int key_type,
2082                                      data_t *key_data,
2083                                      int exercise_alg)
2084{
2085    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
2086    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
2087    psa_key_usage_t policy_usage = policy_usage_arg;
2088    psa_status_t status;
2089    size_t key_bits;
2090    size_t buffer_length;
2091    unsigned char *buffer = NULL;
2092    size_t output_length;
2093
2094    PSA_ASSERT(psa_crypto_init());
2095
2096    psa_set_key_usage_flags(&attributes, policy_usage);
2097    psa_set_key_algorithm(&attributes, policy_alg);
2098    psa_set_key_type(&attributes, key_type);
2099
2100    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
2101                              &key));
2102
2103    /* Check if no key usage implication is done */
2104    TEST_EQUAL(policy_usage,
2105               mbedtls_test_update_key_usage_flags(policy_usage));
2106
2107    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
2108    key_bits = psa_get_key_bits(&attributes);
2109    buffer_length = PSA_ASYMMETRIC_ENCRYPT_OUTPUT_SIZE(key_type, key_bits,
2110                                                       exercise_alg);
2111    ASSERT_ALLOC(buffer, buffer_length);
2112
2113    status = psa_asymmetric_encrypt(key, exercise_alg,
2114                                    NULL, 0,
2115                                    NULL, 0,
2116                                    buffer, buffer_length,
2117                                    &output_length);
2118    if (policy_alg == exercise_alg &&
2119        (policy_usage & PSA_KEY_USAGE_ENCRYPT) != 0) {
2120        PSA_ASSERT(status);
2121    } else {
2122        TEST_EQUAL(status, PSA_ERROR_NOT_PERMITTED);
2123    }
2124
2125    if (buffer_length != 0) {
2126        memset(buffer, 0, buffer_length);
2127    }
2128    status = psa_asymmetric_decrypt(key, exercise_alg,
2129                                    buffer, buffer_length,
2130                                    NULL, 0,
2131                                    buffer, buffer_length,
2132                                    &output_length);
2133    if (policy_alg == exercise_alg &&
2134        (policy_usage & PSA_KEY_USAGE_DECRYPT) != 0) {
2135        TEST_EQUAL(status, PSA_ERROR_INVALID_PADDING);
2136    } else {
2137        TEST_EQUAL(status, PSA_ERROR_NOT_PERMITTED);
2138    }
2139
2140exit:
2141    /*
2142     * Key attributes may have been returned by psa_get_key_attributes()
2143     * thus reset them as required.
2144     */
2145    psa_reset_key_attributes(&attributes);
2146
2147    psa_destroy_key(key);
2148    PSA_DONE();
2149    mbedtls_free(buffer);
2150}
2151/* END_CASE */
2152
2153/* BEGIN_CASE */
2154void asymmetric_signature_key_policy(int policy_usage_arg,
2155                                     int policy_alg,
2156                                     int key_type,
2157                                     data_t *key_data,
2158                                     int exercise_alg,
2159                                     int payload_length_arg,
2160                                     int expected_usage_arg)
2161{
2162    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
2163    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
2164    psa_key_usage_t policy_usage = policy_usage_arg;
2165    psa_key_usage_t expected_usage = expected_usage_arg;
2166    psa_status_t status;
2167    unsigned char payload[PSA_HASH_MAX_SIZE] = { 1 };
2168    /* If `payload_length_arg > 0`, `exercise_alg` is supposed to be
2169     * compatible with the policy and `payload_length_arg` is supposed to be
2170     * a valid input length to sign. If `payload_length_arg <= 0`,
2171     * `exercise_alg` is supposed to be forbidden by the policy. */
2172    int compatible_alg = payload_length_arg > 0;
2173    size_t payload_length = compatible_alg ? payload_length_arg : 0;
2174    unsigned char signature[PSA_SIGNATURE_MAX_SIZE] = { 0 };
2175    size_t signature_length;
2176
2177    /* Check if all implicit usage flags are deployed
2178       in the expected usage flags. */
2179    TEST_EQUAL(expected_usage,
2180               mbedtls_test_update_key_usage_flags(policy_usage));
2181
2182    PSA_ASSERT(psa_crypto_init());
2183
2184    psa_set_key_usage_flags(&attributes, policy_usage);
2185    psa_set_key_algorithm(&attributes, policy_alg);
2186    psa_set_key_type(&attributes, key_type);
2187
2188    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
2189                              &key));
2190
2191    TEST_EQUAL(psa_get_key_usage_flags(&attributes), expected_usage);
2192
2193    status = psa_sign_hash(key, exercise_alg,
2194                           payload, payload_length,
2195                           signature, sizeof(signature),
2196                           &signature_length);
2197    if (compatible_alg && (expected_usage & PSA_KEY_USAGE_SIGN_HASH) != 0) {
2198        PSA_ASSERT(status);
2199    } else {
2200        TEST_EQUAL(status, PSA_ERROR_NOT_PERMITTED);
2201    }
2202
2203    memset(signature, 0, sizeof(signature));
2204    status = psa_verify_hash(key, exercise_alg,
2205                             payload, payload_length,
2206                             signature, sizeof(signature));
2207    if (compatible_alg && (expected_usage & PSA_KEY_USAGE_VERIFY_HASH) != 0) {
2208        TEST_EQUAL(status, PSA_ERROR_INVALID_SIGNATURE);
2209    } else {
2210        TEST_EQUAL(status, PSA_ERROR_NOT_PERMITTED);
2211    }
2212
2213    if (PSA_ALG_IS_SIGN_HASH(exercise_alg) &&
2214        PSA_ALG_IS_HASH(PSA_ALG_SIGN_GET_HASH(exercise_alg))) {
2215        status = psa_sign_message(key, exercise_alg,
2216                                  payload, payload_length,
2217                                  signature, sizeof(signature),
2218                                  &signature_length);
2219        if (compatible_alg && (expected_usage & PSA_KEY_USAGE_SIGN_MESSAGE) != 0) {
2220            PSA_ASSERT(status);
2221        } else {
2222            TEST_EQUAL(status, PSA_ERROR_NOT_PERMITTED);
2223        }
2224
2225        memset(signature, 0, sizeof(signature));
2226        status = psa_verify_message(key, exercise_alg,
2227                                    payload, payload_length,
2228                                    signature, sizeof(signature));
2229        if (compatible_alg && (expected_usage & PSA_KEY_USAGE_VERIFY_MESSAGE) != 0) {
2230            TEST_EQUAL(status, PSA_ERROR_INVALID_SIGNATURE);
2231        } else {
2232            TEST_EQUAL(status, PSA_ERROR_NOT_PERMITTED);
2233        }
2234    }
2235
2236exit:
2237    psa_destroy_key(key);
2238    PSA_DONE();
2239}
2240/* END_CASE */
2241
2242/* BEGIN_CASE */
2243void derive_key_policy(int policy_usage,
2244                       int policy_alg,
2245                       int key_type,
2246                       data_t *key_data,
2247                       int exercise_alg)
2248{
2249    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
2250    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
2251    psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
2252    psa_status_t status;
2253
2254    PSA_ASSERT(psa_crypto_init());
2255
2256    psa_set_key_usage_flags(&attributes, policy_usage);
2257    psa_set_key_algorithm(&attributes, policy_alg);
2258    psa_set_key_type(&attributes, key_type);
2259
2260    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
2261                              &key));
2262
2263    PSA_ASSERT(psa_key_derivation_setup(&operation, exercise_alg));
2264
2265    if (PSA_ALG_IS_TLS12_PRF(exercise_alg) ||
2266        PSA_ALG_IS_TLS12_PSK_TO_MS(exercise_alg)) {
2267        PSA_ASSERT(psa_key_derivation_input_bytes(
2268                       &operation,
2269                       PSA_KEY_DERIVATION_INPUT_SEED,
2270                       (const uint8_t *) "", 0));
2271    }
2272
2273    status = psa_key_derivation_input_key(&operation,
2274                                          PSA_KEY_DERIVATION_INPUT_SECRET,
2275                                          key);
2276
2277    if (policy_alg == exercise_alg &&
2278        (policy_usage & PSA_KEY_USAGE_DERIVE) != 0) {
2279        PSA_ASSERT(status);
2280    } else {
2281        TEST_EQUAL(status, PSA_ERROR_NOT_PERMITTED);
2282    }
2283
2284exit:
2285    psa_key_derivation_abort(&operation);
2286    psa_destroy_key(key);
2287    PSA_DONE();
2288}
2289/* END_CASE */
2290
2291/* BEGIN_CASE */
2292void agreement_key_policy(int policy_usage,
2293                          int policy_alg,
2294                          int key_type_arg,
2295                          data_t *key_data,
2296                          int exercise_alg,
2297                          int expected_status_arg)
2298{
2299    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
2300    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
2301    psa_key_type_t key_type = key_type_arg;
2302    psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
2303    psa_status_t status;
2304    psa_status_t expected_status = expected_status_arg;
2305
2306    PSA_ASSERT(psa_crypto_init());
2307
2308    psa_set_key_usage_flags(&attributes, policy_usage);
2309    psa_set_key_algorithm(&attributes, policy_alg);
2310    psa_set_key_type(&attributes, key_type);
2311
2312    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
2313                              &key));
2314
2315    PSA_ASSERT(psa_key_derivation_setup(&operation, exercise_alg));
2316    status = mbedtls_test_psa_key_agreement_with_self(&operation, key);
2317
2318    TEST_EQUAL(status, expected_status);
2319
2320exit:
2321    psa_key_derivation_abort(&operation);
2322    psa_destroy_key(key);
2323    PSA_DONE();
2324}
2325/* END_CASE */
2326
2327/* BEGIN_CASE */
2328void key_policy_alg2(int key_type_arg, data_t *key_data,
2329                     int usage_arg, int alg_arg, int alg2_arg)
2330{
2331    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
2332    psa_key_type_t key_type = key_type_arg;
2333    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
2334    psa_key_attributes_t got_attributes = PSA_KEY_ATTRIBUTES_INIT;
2335    psa_key_usage_t usage = usage_arg;
2336    psa_algorithm_t alg = alg_arg;
2337    psa_algorithm_t alg2 = alg2_arg;
2338
2339    PSA_ASSERT(psa_crypto_init());
2340
2341    psa_set_key_usage_flags(&attributes, usage);
2342    psa_set_key_algorithm(&attributes, alg);
2343    psa_set_key_enrollment_algorithm(&attributes, alg2);
2344    psa_set_key_type(&attributes, key_type);
2345    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
2346                              &key));
2347
2348    /* Update the usage flags to obtain implicit usage flags */
2349    usage = mbedtls_test_update_key_usage_flags(usage);
2350    PSA_ASSERT(psa_get_key_attributes(key, &got_attributes));
2351    TEST_EQUAL(psa_get_key_usage_flags(&got_attributes), usage);
2352    TEST_EQUAL(psa_get_key_algorithm(&got_attributes), alg);
2353    TEST_EQUAL(psa_get_key_enrollment_algorithm(&got_attributes), alg2);
2354
2355    if (!mbedtls_test_psa_exercise_key(key, usage, alg)) {
2356        goto exit;
2357    }
2358    if (!mbedtls_test_psa_exercise_key(key, usage, alg2)) {
2359        goto exit;
2360    }
2361
2362exit:
2363    /*
2364     * Key attributes may have been returned by psa_get_key_attributes()
2365     * thus reset them as required.
2366     */
2367    psa_reset_key_attributes(&got_attributes);
2368
2369    psa_destroy_key(key);
2370    PSA_DONE();
2371}
2372/* END_CASE */
2373
2374/* BEGIN_CASE */
2375void raw_agreement_key_policy(int policy_usage,
2376                              int policy_alg,
2377                              int key_type_arg,
2378                              data_t *key_data,
2379                              int exercise_alg,
2380                              int expected_status_arg)
2381{
2382    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
2383    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
2384    psa_key_type_t key_type = key_type_arg;
2385    psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
2386    psa_status_t status;
2387    psa_status_t expected_status = expected_status_arg;
2388
2389    PSA_ASSERT(psa_crypto_init());
2390
2391    psa_set_key_usage_flags(&attributes, policy_usage);
2392    psa_set_key_algorithm(&attributes, policy_alg);
2393    psa_set_key_type(&attributes, key_type);
2394
2395    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
2396                              &key));
2397
2398    status = mbedtls_test_psa_raw_key_agreement_with_self(exercise_alg, key);
2399
2400    TEST_EQUAL(status, expected_status);
2401
2402exit:
2403    psa_key_derivation_abort(&operation);
2404    psa_destroy_key(key);
2405    PSA_DONE();
2406}
2407/* END_CASE */
2408
2409/* BEGIN_CASE */
2410void copy_success(int source_usage_arg,
2411                  int source_alg_arg, int source_alg2_arg,
2412                  unsigned int source_lifetime_arg,
2413                  int type_arg, data_t *material,
2414                  int copy_attributes,
2415                  int target_usage_arg,
2416                  int target_alg_arg, int target_alg2_arg,
2417                  unsigned int target_lifetime_arg,
2418                  int expected_usage_arg,
2419                  int expected_alg_arg, int expected_alg2_arg)
2420{
2421    psa_key_attributes_t source_attributes = PSA_KEY_ATTRIBUTES_INIT;
2422    psa_key_attributes_t target_attributes = PSA_KEY_ATTRIBUTES_INIT;
2423    psa_key_usage_t expected_usage = expected_usage_arg;
2424    psa_algorithm_t expected_alg = expected_alg_arg;
2425    psa_algorithm_t expected_alg2 = expected_alg2_arg;
2426    psa_key_lifetime_t source_lifetime = source_lifetime_arg;
2427    psa_key_lifetime_t target_lifetime = target_lifetime_arg;
2428    mbedtls_svc_key_id_t source_key = MBEDTLS_SVC_KEY_ID_INIT;
2429    mbedtls_svc_key_id_t target_key = MBEDTLS_SVC_KEY_ID_INIT;
2430    uint8_t *export_buffer = NULL;
2431
2432    PSA_ASSERT(psa_crypto_init());
2433
2434    /* Prepare the source key. */
2435    psa_set_key_usage_flags(&source_attributes, source_usage_arg);
2436    psa_set_key_algorithm(&source_attributes, source_alg_arg);
2437    psa_set_key_enrollment_algorithm(&source_attributes, source_alg2_arg);
2438    psa_set_key_type(&source_attributes, type_arg);
2439    psa_set_key_lifetime(&source_attributes, source_lifetime);
2440    PSA_ASSERT(psa_import_key(&source_attributes,
2441                              material->x, material->len,
2442                              &source_key));
2443    PSA_ASSERT(psa_get_key_attributes(source_key, &source_attributes));
2444
2445    /* Prepare the target attributes. */
2446    if (copy_attributes) {
2447        target_attributes = source_attributes;
2448    }
2449    psa_set_key_lifetime(&target_attributes, target_lifetime);
2450
2451    if (target_usage_arg != -1) {
2452        psa_set_key_usage_flags(&target_attributes, target_usage_arg);
2453    }
2454    if (target_alg_arg != -1) {
2455        psa_set_key_algorithm(&target_attributes, target_alg_arg);
2456    }
2457    if (target_alg2_arg != -1) {
2458        psa_set_key_enrollment_algorithm(&target_attributes, target_alg2_arg);
2459    }
2460
2461
2462    /* Copy the key. */
2463    PSA_ASSERT(psa_copy_key(source_key,
2464                            &target_attributes, &target_key));
2465
2466    /* Destroy the source to ensure that this doesn't affect the target. */
2467    PSA_ASSERT(psa_destroy_key(source_key));
2468
2469    /* Test that the target slot has the expected content and policy. */
2470    PSA_ASSERT(psa_get_key_attributes(target_key, &target_attributes));
2471    TEST_EQUAL(psa_get_key_type(&source_attributes),
2472               psa_get_key_type(&target_attributes));
2473    TEST_EQUAL(psa_get_key_bits(&source_attributes),
2474               psa_get_key_bits(&target_attributes));
2475    TEST_EQUAL(expected_usage, psa_get_key_usage_flags(&target_attributes));
2476    TEST_EQUAL(expected_alg, psa_get_key_algorithm(&target_attributes));
2477    TEST_EQUAL(expected_alg2,
2478               psa_get_key_enrollment_algorithm(&target_attributes));
2479    if (expected_usage & PSA_KEY_USAGE_EXPORT) {
2480        size_t length;
2481        ASSERT_ALLOC(export_buffer, material->len);
2482        PSA_ASSERT(psa_export_key(target_key, export_buffer,
2483                                  material->len, &length));
2484        ASSERT_COMPARE(material->x, material->len,
2485                       export_buffer, length);
2486    }
2487
2488    if (!psa_key_lifetime_is_external(target_lifetime)) {
2489        if (!mbedtls_test_psa_exercise_key(target_key, expected_usage, expected_alg)) {
2490            goto exit;
2491        }
2492        if (!mbedtls_test_psa_exercise_key(target_key, expected_usage, expected_alg2)) {
2493            goto exit;
2494        }
2495    }
2496
2497    PSA_ASSERT(psa_destroy_key(target_key));
2498
2499exit:
2500    /*
2501     * Source and target key attributes may have been returned by
2502     * psa_get_key_attributes() thus reset them as required.
2503     */
2504    psa_reset_key_attributes(&source_attributes);
2505    psa_reset_key_attributes(&target_attributes);
2506
2507    PSA_DONE();
2508    mbedtls_free(export_buffer);
2509}
2510/* END_CASE */
2511
2512/* BEGIN_CASE */
2513void copy_fail(int source_usage_arg,
2514               int source_alg_arg, int source_alg2_arg,
2515               int source_lifetime_arg,
2516               int type_arg, data_t *material,
2517               int target_type_arg, int target_bits_arg,
2518               int target_usage_arg,
2519               int target_alg_arg, int target_alg2_arg,
2520               int target_id_arg, int target_lifetime_arg,
2521               int expected_status_arg)
2522{
2523    psa_key_attributes_t source_attributes = PSA_KEY_ATTRIBUTES_INIT;
2524    psa_key_attributes_t target_attributes = PSA_KEY_ATTRIBUTES_INIT;
2525    mbedtls_svc_key_id_t source_key = MBEDTLS_SVC_KEY_ID_INIT;
2526    mbedtls_svc_key_id_t target_key = MBEDTLS_SVC_KEY_ID_INIT;
2527    mbedtls_svc_key_id_t key_id = mbedtls_svc_key_id_make(1, target_id_arg);
2528
2529    PSA_ASSERT(psa_crypto_init());
2530
2531    /* Prepare the source key. */
2532    psa_set_key_usage_flags(&source_attributes, source_usage_arg);
2533    psa_set_key_algorithm(&source_attributes, source_alg_arg);
2534    psa_set_key_enrollment_algorithm(&source_attributes, source_alg2_arg);
2535    psa_set_key_type(&source_attributes, type_arg);
2536    psa_set_key_lifetime(&source_attributes, source_lifetime_arg);
2537    PSA_ASSERT(psa_import_key(&source_attributes,
2538                              material->x, material->len,
2539                              &source_key));
2540
2541    /* Prepare the target attributes. */
2542    psa_set_key_id(&target_attributes, key_id);
2543    psa_set_key_lifetime(&target_attributes, target_lifetime_arg);
2544    psa_set_key_type(&target_attributes, target_type_arg);
2545    psa_set_key_bits(&target_attributes, target_bits_arg);
2546    psa_set_key_usage_flags(&target_attributes, target_usage_arg);
2547    psa_set_key_algorithm(&target_attributes, target_alg_arg);
2548    psa_set_key_enrollment_algorithm(&target_attributes, target_alg2_arg);
2549
2550    /* Try to copy the key. */
2551    TEST_EQUAL(psa_copy_key(source_key,
2552                            &target_attributes, &target_key),
2553               expected_status_arg);
2554
2555    PSA_ASSERT(psa_destroy_key(source_key));
2556
2557exit:
2558    psa_reset_key_attributes(&source_attributes);
2559    psa_reset_key_attributes(&target_attributes);
2560    PSA_DONE();
2561}
2562/* END_CASE */
2563
2564/* BEGIN_CASE */
2565void hash_operation_init()
2566{
2567    const uint8_t input[1] = { 0 };
2568    /* Test each valid way of initializing the object, except for `= {0}`, as
2569     * Clang 5 complains when `-Wmissing-field-initializers` is used, even
2570     * though it's OK by the C standard. We could test for this, but we'd need
2571     * to suppress the Clang warning for the test. */
2572    psa_hash_operation_t func = psa_hash_operation_init();
2573    psa_hash_operation_t init = PSA_HASH_OPERATION_INIT;
2574    psa_hash_operation_t zero;
2575
2576    memset(&zero, 0, sizeof(zero));
2577
2578    /* A freshly-initialized hash operation should not be usable. */
2579    TEST_EQUAL(psa_hash_update(&func, input, sizeof(input)),
2580               PSA_ERROR_BAD_STATE);
2581    TEST_EQUAL(psa_hash_update(&init, input, sizeof(input)),
2582               PSA_ERROR_BAD_STATE);
2583    TEST_EQUAL(psa_hash_update(&zero, input, sizeof(input)),
2584               PSA_ERROR_BAD_STATE);
2585
2586    /* A default hash operation should be abortable without error. */
2587    PSA_ASSERT(psa_hash_abort(&func));
2588    PSA_ASSERT(psa_hash_abort(&init));
2589    PSA_ASSERT(psa_hash_abort(&zero));
2590}
2591/* END_CASE */
2592
2593/* BEGIN_CASE */
2594void hash_setup(int alg_arg,
2595                int expected_status_arg)
2596{
2597    psa_algorithm_t alg = alg_arg;
2598    uint8_t *output = NULL;
2599    size_t output_size = 0;
2600    size_t output_length = 0;
2601    psa_status_t expected_status = expected_status_arg;
2602    psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
2603    psa_status_t status;
2604
2605    PSA_ASSERT(psa_crypto_init());
2606
2607    /* Hash Setup, one-shot */
2608    output_size = PSA_HASH_LENGTH(alg);
2609    ASSERT_ALLOC(output, output_size);
2610
2611    status = psa_hash_compute(alg, NULL, 0,
2612                              output, output_size, &output_length);
2613    TEST_EQUAL(status, expected_status);
2614
2615    /* Hash Setup, multi-part */
2616    status = psa_hash_setup(&operation, alg);
2617    TEST_EQUAL(status, expected_status);
2618
2619    /* Whether setup succeeded or failed, abort must succeed. */
2620    PSA_ASSERT(psa_hash_abort(&operation));
2621
2622    /* If setup failed, reproduce the failure, so as to
2623     * test the resulting state of the operation object. */
2624    if (status != PSA_SUCCESS) {
2625        TEST_EQUAL(psa_hash_setup(&operation, alg), status);
2626    }
2627
2628    /* Now the operation object should be reusable. */
2629#if defined(KNOWN_SUPPORTED_HASH_ALG)
2630    PSA_ASSERT(psa_hash_setup(&operation, KNOWN_SUPPORTED_HASH_ALG));
2631    PSA_ASSERT(psa_hash_abort(&operation));
2632#endif
2633
2634exit:
2635    mbedtls_free(output);
2636    PSA_DONE();
2637}
2638/* END_CASE */
2639
2640/* BEGIN_CASE */
2641void hash_compute_fail(int alg_arg, data_t *input,
2642                       int output_size_arg, int expected_status_arg)
2643{
2644    psa_algorithm_t alg = alg_arg;
2645    uint8_t *output = NULL;
2646    size_t output_size = output_size_arg;
2647    size_t output_length = INVALID_EXPORT_LENGTH;
2648    psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
2649    psa_status_t expected_status = expected_status_arg;
2650    psa_status_t status;
2651
2652    ASSERT_ALLOC(output, output_size);
2653
2654    PSA_ASSERT(psa_crypto_init());
2655
2656    /* Hash Compute, one-shot */
2657    status = psa_hash_compute(alg, input->x, input->len,
2658                              output, output_size, &output_length);
2659    TEST_EQUAL(status, expected_status);
2660    TEST_LE_U(output_length, output_size);
2661
2662    /* Hash Compute, multi-part */
2663    status = psa_hash_setup(&operation, alg);
2664    if (status == PSA_SUCCESS) {
2665        status = psa_hash_update(&operation, input->x, input->len);
2666        if (status == PSA_SUCCESS) {
2667            status = psa_hash_finish(&operation, output, output_size,
2668                                     &output_length);
2669            if (status == PSA_SUCCESS) {
2670                TEST_LE_U(output_length, output_size);
2671            } else {
2672                TEST_EQUAL(status, expected_status);
2673            }
2674        } else {
2675            TEST_EQUAL(status, expected_status);
2676        }
2677    } else {
2678        TEST_EQUAL(status, expected_status);
2679    }
2680
2681exit:
2682    PSA_ASSERT(psa_hash_abort(&operation));
2683    mbedtls_free(output);
2684    PSA_DONE();
2685}
2686/* END_CASE */
2687
2688/* BEGIN_CASE */
2689void hash_compare_fail(int alg_arg, data_t *input,
2690                       data_t *reference_hash,
2691                       int expected_status_arg)
2692{
2693    psa_algorithm_t alg = alg_arg;
2694    psa_status_t expected_status = expected_status_arg;
2695    psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
2696    psa_status_t status;
2697
2698    PSA_ASSERT(psa_crypto_init());
2699
2700    /* Hash Compare, one-shot */
2701    status = psa_hash_compare(alg, input->x, input->len,
2702                              reference_hash->x, reference_hash->len);
2703    TEST_EQUAL(status, expected_status);
2704
2705    /* Hash Compare, multi-part */
2706    status = psa_hash_setup(&operation, alg);
2707    if (status == PSA_SUCCESS) {
2708        status = psa_hash_update(&operation, input->x, input->len);
2709        if (status == PSA_SUCCESS) {
2710            status = psa_hash_verify(&operation, reference_hash->x,
2711                                     reference_hash->len);
2712            TEST_EQUAL(status, expected_status);
2713        } else {
2714            TEST_EQUAL(status, expected_status);
2715        }
2716    } else {
2717        TEST_EQUAL(status, expected_status);
2718    }
2719
2720exit:
2721    PSA_ASSERT(psa_hash_abort(&operation));
2722    PSA_DONE();
2723}
2724/* END_CASE */
2725
2726/* BEGIN_CASE */
2727void hash_compute_compare(int alg_arg, data_t *input,
2728                          data_t *expected_output)
2729{
2730    psa_algorithm_t alg = alg_arg;
2731    uint8_t output[PSA_HASH_MAX_SIZE + 1];
2732    size_t output_length = INVALID_EXPORT_LENGTH;
2733    psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
2734    size_t i;
2735
2736    PSA_ASSERT(psa_crypto_init());
2737
2738    /* Compute with tight buffer, one-shot */
2739    PSA_ASSERT(psa_hash_compute(alg, input->x, input->len,
2740                                output, PSA_HASH_LENGTH(alg),
2741                                &output_length));
2742    TEST_EQUAL(output_length, PSA_HASH_LENGTH(alg));
2743    ASSERT_COMPARE(output, output_length,
2744                   expected_output->x, expected_output->len);
2745
2746    /* Compute with tight buffer, multi-part */
2747    PSA_ASSERT(psa_hash_setup(&operation, alg));
2748    PSA_ASSERT(psa_hash_update(&operation, input->x, input->len));
2749    PSA_ASSERT(psa_hash_finish(&operation, output,
2750                               PSA_HASH_LENGTH(alg),
2751                               &output_length));
2752    TEST_EQUAL(output_length, PSA_HASH_LENGTH(alg));
2753    ASSERT_COMPARE(output, output_length,
2754                   expected_output->x, expected_output->len);
2755
2756    /* Compute with larger buffer, one-shot */
2757    PSA_ASSERT(psa_hash_compute(alg, input->x, input->len,
2758                                output, sizeof(output),
2759                                &output_length));
2760    TEST_EQUAL(output_length, PSA_HASH_LENGTH(alg));
2761    ASSERT_COMPARE(output, output_length,
2762                   expected_output->x, expected_output->len);
2763
2764    /* Compute with larger buffer, multi-part */
2765    PSA_ASSERT(psa_hash_setup(&operation, alg));
2766    PSA_ASSERT(psa_hash_update(&operation, input->x, input->len));
2767    PSA_ASSERT(psa_hash_finish(&operation, output,
2768                               sizeof(output), &output_length));
2769    TEST_EQUAL(output_length, PSA_HASH_LENGTH(alg));
2770    ASSERT_COMPARE(output, output_length,
2771                   expected_output->x, expected_output->len);
2772
2773    /* Compare with correct hash, one-shot */
2774    PSA_ASSERT(psa_hash_compare(alg, input->x, input->len,
2775                                output, output_length));
2776
2777    /* Compare with correct hash, multi-part */
2778    PSA_ASSERT(psa_hash_setup(&operation, alg));
2779    PSA_ASSERT(psa_hash_update(&operation, input->x, input->len));
2780    PSA_ASSERT(psa_hash_verify(&operation, output,
2781                               output_length));
2782
2783    /* Compare with trailing garbage, one-shot */
2784    TEST_EQUAL(psa_hash_compare(alg, input->x, input->len,
2785                                output, output_length + 1),
2786               PSA_ERROR_INVALID_SIGNATURE);
2787
2788    /* Compare with trailing garbage, multi-part */
2789    PSA_ASSERT(psa_hash_setup(&operation, alg));
2790    PSA_ASSERT(psa_hash_update(&operation, input->x, input->len));
2791    TEST_EQUAL(psa_hash_verify(&operation, output, output_length + 1),
2792               PSA_ERROR_INVALID_SIGNATURE);
2793
2794    /* Compare with truncated hash, one-shot */
2795    TEST_EQUAL(psa_hash_compare(alg, input->x, input->len,
2796                                output, output_length - 1),
2797               PSA_ERROR_INVALID_SIGNATURE);
2798
2799    /* Compare with truncated hash, multi-part */
2800    PSA_ASSERT(psa_hash_setup(&operation, alg));
2801    PSA_ASSERT(psa_hash_update(&operation, input->x, input->len));
2802    TEST_EQUAL(psa_hash_verify(&operation, output, output_length - 1),
2803               PSA_ERROR_INVALID_SIGNATURE);
2804
2805    /* Compare with corrupted value */
2806    for (i = 0; i < output_length; i++) {
2807        mbedtls_test_set_step(i);
2808        output[i] ^= 1;
2809
2810        /* One-shot */
2811        TEST_EQUAL(psa_hash_compare(alg, input->x, input->len,
2812                                    output, output_length),
2813                   PSA_ERROR_INVALID_SIGNATURE);
2814
2815        /* Multi-Part */
2816        PSA_ASSERT(psa_hash_setup(&operation, alg));
2817        PSA_ASSERT(psa_hash_update(&operation, input->x, input->len));
2818        TEST_EQUAL(psa_hash_verify(&operation, output, output_length),
2819                   PSA_ERROR_INVALID_SIGNATURE);
2820
2821        output[i] ^= 1;
2822    }
2823
2824exit:
2825    PSA_ASSERT(psa_hash_abort(&operation));
2826    PSA_DONE();
2827}
2828/* END_CASE */
2829
2830/* BEGIN_CASE depends_on:PSA_WANT_ALG_SHA_256 */
2831void hash_bad_order()
2832{
2833    psa_algorithm_t alg = PSA_ALG_SHA_256;
2834    unsigned char input[] = "";
2835    /* SHA-256 hash of an empty string */
2836    const unsigned char valid_hash[] = {
2837        0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8,
2838        0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c,
2839        0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55
2840    };
2841    unsigned char hash[sizeof(valid_hash)] = { 0 };
2842    size_t hash_len;
2843    psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
2844
2845    PSA_ASSERT(psa_crypto_init());
2846
2847    /* Call setup twice in a row. */
2848    PSA_ASSERT(psa_hash_setup(&operation, alg));
2849    ASSERT_OPERATION_IS_ACTIVE(operation);
2850    TEST_EQUAL(psa_hash_setup(&operation, alg),
2851               PSA_ERROR_BAD_STATE);
2852    ASSERT_OPERATION_IS_INACTIVE(operation);
2853    PSA_ASSERT(psa_hash_abort(&operation));
2854    ASSERT_OPERATION_IS_INACTIVE(operation);
2855
2856    /* Call update without calling setup beforehand. */
2857    TEST_EQUAL(psa_hash_update(&operation, input, sizeof(input)),
2858               PSA_ERROR_BAD_STATE);
2859    PSA_ASSERT(psa_hash_abort(&operation));
2860
2861    /* Check that update calls abort on error. */
2862    PSA_ASSERT(psa_hash_setup(&operation, alg));
2863    operation.id = UINT_MAX;
2864    ASSERT_OPERATION_IS_ACTIVE(operation);
2865    TEST_EQUAL(psa_hash_update(&operation, input, sizeof(input)),
2866               PSA_ERROR_BAD_STATE);
2867    ASSERT_OPERATION_IS_INACTIVE(operation);
2868    PSA_ASSERT(psa_hash_abort(&operation));
2869    ASSERT_OPERATION_IS_INACTIVE(operation);
2870
2871    /* Call update after finish. */
2872    PSA_ASSERT(psa_hash_setup(&operation, alg));
2873    PSA_ASSERT(psa_hash_finish(&operation,
2874                               hash, sizeof(hash), &hash_len));
2875    TEST_EQUAL(psa_hash_update(&operation, input, sizeof(input)),
2876               PSA_ERROR_BAD_STATE);
2877    PSA_ASSERT(psa_hash_abort(&operation));
2878
2879    /* Call verify without calling setup beforehand. */
2880    TEST_EQUAL(psa_hash_verify(&operation,
2881                               valid_hash, sizeof(valid_hash)),
2882               PSA_ERROR_BAD_STATE);
2883    PSA_ASSERT(psa_hash_abort(&operation));
2884
2885    /* Call verify after finish. */
2886    PSA_ASSERT(psa_hash_setup(&operation, alg));
2887    PSA_ASSERT(psa_hash_finish(&operation,
2888                               hash, sizeof(hash), &hash_len));
2889    TEST_EQUAL(psa_hash_verify(&operation,
2890                               valid_hash, sizeof(valid_hash)),
2891               PSA_ERROR_BAD_STATE);
2892    PSA_ASSERT(psa_hash_abort(&operation));
2893
2894    /* Call verify twice in a row. */
2895    PSA_ASSERT(psa_hash_setup(&operation, alg));
2896    ASSERT_OPERATION_IS_ACTIVE(operation);
2897    PSA_ASSERT(psa_hash_verify(&operation,
2898                               valid_hash, sizeof(valid_hash)));
2899    ASSERT_OPERATION_IS_INACTIVE(operation);
2900    TEST_EQUAL(psa_hash_verify(&operation,
2901                               valid_hash, sizeof(valid_hash)),
2902               PSA_ERROR_BAD_STATE);
2903    ASSERT_OPERATION_IS_INACTIVE(operation);
2904    PSA_ASSERT(psa_hash_abort(&operation));
2905
2906    /* Call finish without calling setup beforehand. */
2907    TEST_EQUAL(psa_hash_finish(&operation,
2908                               hash, sizeof(hash), &hash_len),
2909               PSA_ERROR_BAD_STATE);
2910    PSA_ASSERT(psa_hash_abort(&operation));
2911
2912    /* Call finish twice in a row. */
2913    PSA_ASSERT(psa_hash_setup(&operation, alg));
2914    PSA_ASSERT(psa_hash_finish(&operation,
2915                               hash, sizeof(hash), &hash_len));
2916    TEST_EQUAL(psa_hash_finish(&operation,
2917                               hash, sizeof(hash), &hash_len),
2918               PSA_ERROR_BAD_STATE);
2919    PSA_ASSERT(psa_hash_abort(&operation));
2920
2921    /* Call finish after calling verify. */
2922    PSA_ASSERT(psa_hash_setup(&operation, alg));
2923    PSA_ASSERT(psa_hash_verify(&operation,
2924                               valid_hash, sizeof(valid_hash)));
2925    TEST_EQUAL(psa_hash_finish(&operation,
2926                               hash, sizeof(hash), &hash_len),
2927               PSA_ERROR_BAD_STATE);
2928    PSA_ASSERT(psa_hash_abort(&operation));
2929
2930exit:
2931    PSA_DONE();
2932}
2933/* END_CASE */
2934
2935/* BEGIN_CASE depends_on:PSA_WANT_ALG_SHA_256 */
2936void hash_verify_bad_args()
2937{
2938    psa_algorithm_t alg = PSA_ALG_SHA_256;
2939    /* SHA-256 hash of an empty string with 2 extra bytes (0xaa and 0xbb)
2940     * appended to it */
2941    unsigned char hash[] = {
2942        0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8,
2943        0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c,
2944        0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55, 0xaa, 0xbb
2945    };
2946    size_t expected_size = PSA_HASH_LENGTH(alg);
2947    psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
2948
2949    PSA_ASSERT(psa_crypto_init());
2950
2951    /* psa_hash_verify with a smaller hash than expected */
2952    PSA_ASSERT(psa_hash_setup(&operation, alg));
2953    ASSERT_OPERATION_IS_ACTIVE(operation);
2954    TEST_EQUAL(psa_hash_verify(&operation, hash, expected_size - 1),
2955               PSA_ERROR_INVALID_SIGNATURE);
2956    ASSERT_OPERATION_IS_INACTIVE(operation);
2957    PSA_ASSERT(psa_hash_abort(&operation));
2958    ASSERT_OPERATION_IS_INACTIVE(operation);
2959
2960    /* psa_hash_verify with a non-matching hash */
2961    PSA_ASSERT(psa_hash_setup(&operation, alg));
2962    TEST_EQUAL(psa_hash_verify(&operation, hash + 1, expected_size),
2963               PSA_ERROR_INVALID_SIGNATURE);
2964
2965    /* psa_hash_verify with a hash longer than expected */
2966    PSA_ASSERT(psa_hash_setup(&operation, alg));
2967    TEST_EQUAL(psa_hash_verify(&operation, hash, sizeof(hash)),
2968               PSA_ERROR_INVALID_SIGNATURE);
2969
2970exit:
2971    PSA_DONE();
2972}
2973/* END_CASE */
2974
2975/* BEGIN_CASE depends_on:PSA_WANT_ALG_SHA_256 */
2976void hash_finish_bad_args()
2977{
2978    psa_algorithm_t alg = PSA_ALG_SHA_256;
2979    unsigned char hash[PSA_HASH_MAX_SIZE];
2980    size_t expected_size = PSA_HASH_LENGTH(alg);
2981    psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
2982    size_t hash_len;
2983
2984    PSA_ASSERT(psa_crypto_init());
2985
2986    /* psa_hash_finish with a smaller hash buffer than expected */
2987    PSA_ASSERT(psa_hash_setup(&operation, alg));
2988    TEST_EQUAL(psa_hash_finish(&operation,
2989                               hash, expected_size - 1, &hash_len),
2990               PSA_ERROR_BUFFER_TOO_SMALL);
2991
2992exit:
2993    PSA_DONE();
2994}
2995/* END_CASE */
2996
2997/* BEGIN_CASE depends_on:PSA_WANT_ALG_SHA_256 */
2998void hash_clone_source_state()
2999{
3000    psa_algorithm_t alg = PSA_ALG_SHA_256;
3001    unsigned char hash[PSA_HASH_MAX_SIZE];
3002    psa_hash_operation_t op_source = PSA_HASH_OPERATION_INIT;
3003    psa_hash_operation_t op_init = PSA_HASH_OPERATION_INIT;
3004    psa_hash_operation_t op_setup = PSA_HASH_OPERATION_INIT;
3005    psa_hash_operation_t op_finished = PSA_HASH_OPERATION_INIT;
3006    psa_hash_operation_t op_aborted = PSA_HASH_OPERATION_INIT;
3007    size_t hash_len;
3008
3009    PSA_ASSERT(psa_crypto_init());
3010    PSA_ASSERT(psa_hash_setup(&op_source, alg));
3011
3012    PSA_ASSERT(psa_hash_setup(&op_setup, alg));
3013    PSA_ASSERT(psa_hash_setup(&op_finished, alg));
3014    PSA_ASSERT(psa_hash_finish(&op_finished,
3015                               hash, sizeof(hash), &hash_len));
3016    PSA_ASSERT(psa_hash_setup(&op_aborted, alg));
3017    PSA_ASSERT(psa_hash_abort(&op_aborted));
3018
3019    TEST_EQUAL(psa_hash_clone(&op_source, &op_setup),
3020               PSA_ERROR_BAD_STATE);
3021
3022    PSA_ASSERT(psa_hash_clone(&op_source, &op_init));
3023    PSA_ASSERT(psa_hash_finish(&op_init,
3024                               hash, sizeof(hash), &hash_len));
3025    PSA_ASSERT(psa_hash_clone(&op_source, &op_finished));
3026    PSA_ASSERT(psa_hash_finish(&op_finished,
3027                               hash, sizeof(hash), &hash_len));
3028    PSA_ASSERT(psa_hash_clone(&op_source, &op_aborted));
3029    PSA_ASSERT(psa_hash_finish(&op_aborted,
3030                               hash, sizeof(hash), &hash_len));
3031
3032exit:
3033    psa_hash_abort(&op_source);
3034    psa_hash_abort(&op_init);
3035    psa_hash_abort(&op_setup);
3036    psa_hash_abort(&op_finished);
3037    psa_hash_abort(&op_aborted);
3038    PSA_DONE();
3039}
3040/* END_CASE */
3041
3042/* BEGIN_CASE depends_on:PSA_WANT_ALG_SHA_256 */
3043void hash_clone_target_state()
3044{
3045    psa_algorithm_t alg = PSA_ALG_SHA_256;
3046    unsigned char hash[PSA_HASH_MAX_SIZE];
3047    psa_hash_operation_t op_init = PSA_HASH_OPERATION_INIT;
3048    psa_hash_operation_t op_setup = PSA_HASH_OPERATION_INIT;
3049    psa_hash_operation_t op_finished = PSA_HASH_OPERATION_INIT;
3050    psa_hash_operation_t op_aborted = PSA_HASH_OPERATION_INIT;
3051    psa_hash_operation_t op_target = PSA_HASH_OPERATION_INIT;
3052    size_t hash_len;
3053
3054    PSA_ASSERT(psa_crypto_init());
3055
3056    PSA_ASSERT(psa_hash_setup(&op_setup, alg));
3057    PSA_ASSERT(psa_hash_setup(&op_finished, alg));
3058    PSA_ASSERT(psa_hash_finish(&op_finished,
3059                               hash, sizeof(hash), &hash_len));
3060    PSA_ASSERT(psa_hash_setup(&op_aborted, alg));
3061    PSA_ASSERT(psa_hash_abort(&op_aborted));
3062
3063    PSA_ASSERT(psa_hash_clone(&op_setup, &op_target));
3064    PSA_ASSERT(psa_hash_finish(&op_target,
3065                               hash, sizeof(hash), &hash_len));
3066
3067    TEST_EQUAL(psa_hash_clone(&op_init, &op_target), PSA_ERROR_BAD_STATE);
3068    TEST_EQUAL(psa_hash_clone(&op_finished, &op_target),
3069               PSA_ERROR_BAD_STATE);
3070    TEST_EQUAL(psa_hash_clone(&op_aborted, &op_target),
3071               PSA_ERROR_BAD_STATE);
3072
3073exit:
3074    psa_hash_abort(&op_target);
3075    psa_hash_abort(&op_init);
3076    psa_hash_abort(&op_setup);
3077    psa_hash_abort(&op_finished);
3078    psa_hash_abort(&op_aborted);
3079    PSA_DONE();
3080}
3081/* END_CASE */
3082
3083/* BEGIN_CASE */
3084void mac_operation_init()
3085{
3086    const uint8_t input[1] = { 0 };
3087
3088    /* Test each valid way of initializing the object, except for `= {0}`, as
3089     * Clang 5 complains when `-Wmissing-field-initializers` is used, even
3090     * though it's OK by the C standard. We could test for this, but we'd need
3091     * to suppress the Clang warning for the test. */
3092    psa_mac_operation_t func = psa_mac_operation_init();
3093    psa_mac_operation_t init = PSA_MAC_OPERATION_INIT;
3094    psa_mac_operation_t zero;
3095
3096    memset(&zero, 0, sizeof(zero));
3097
3098    /* A freshly-initialized MAC operation should not be usable. */
3099    TEST_EQUAL(psa_mac_update(&func,
3100                              input, sizeof(input)),
3101               PSA_ERROR_BAD_STATE);
3102    TEST_EQUAL(psa_mac_update(&init,
3103                              input, sizeof(input)),
3104               PSA_ERROR_BAD_STATE);
3105    TEST_EQUAL(psa_mac_update(&zero,
3106                              input, sizeof(input)),
3107               PSA_ERROR_BAD_STATE);
3108
3109    /* A default MAC operation should be abortable without error. */
3110    PSA_ASSERT(psa_mac_abort(&func));
3111    PSA_ASSERT(psa_mac_abort(&init));
3112    PSA_ASSERT(psa_mac_abort(&zero));
3113}
3114/* END_CASE */
3115
3116/* BEGIN_CASE */
3117void mac_setup(int key_type_arg,
3118               data_t *key,
3119               int alg_arg,
3120               int expected_status_arg)
3121{
3122    psa_key_type_t key_type = key_type_arg;
3123    psa_algorithm_t alg = alg_arg;
3124    psa_status_t expected_status = expected_status_arg;
3125    psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT;
3126    psa_status_t status = PSA_ERROR_GENERIC_ERROR;
3127#if defined(KNOWN_SUPPORTED_MAC_ALG)
3128    const uint8_t smoke_test_key_data[16] = "kkkkkkkkkkkkkkkk";
3129#endif
3130
3131    PSA_ASSERT(psa_crypto_init());
3132
3133    if (!exercise_mac_setup(key_type, key->x, key->len, alg,
3134                            &operation, &status)) {
3135        goto exit;
3136    }
3137    TEST_EQUAL(status, expected_status);
3138
3139    /* The operation object should be reusable. */
3140#if defined(KNOWN_SUPPORTED_MAC_ALG)
3141    if (!exercise_mac_setup(KNOWN_SUPPORTED_MAC_KEY_TYPE,
3142                            smoke_test_key_data,
3143                            sizeof(smoke_test_key_data),
3144                            KNOWN_SUPPORTED_MAC_ALG,
3145                            &operation, &status)) {
3146        goto exit;
3147    }
3148    TEST_EQUAL(status, PSA_SUCCESS);
3149#endif
3150
3151exit:
3152    PSA_DONE();
3153}
3154/* END_CASE */
3155
3156/* BEGIN_CASE depends_on:PSA_WANT_KEY_TYPE_HMAC:PSA_WANT_ALG_HMAC:PSA_WANT_ALG_SHA_256 */
3157void mac_bad_order()
3158{
3159    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
3160    psa_key_type_t key_type = PSA_KEY_TYPE_HMAC;
3161    psa_algorithm_t alg = PSA_ALG_HMAC(PSA_ALG_SHA_256);
3162    const uint8_t key_data[] = {
3163        0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
3164        0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
3165        0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa
3166    };
3167    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
3168    psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT;
3169    uint8_t sign_mac[PSA_MAC_MAX_SIZE + 10] = { 0 };
3170    size_t sign_mac_length = 0;
3171    const uint8_t input[] = { 0xbb, 0xbb, 0xbb, 0xbb };
3172    const uint8_t verify_mac[] = {
3173        0x74, 0x65, 0x93, 0x8c, 0xeb, 0x1d, 0xb3, 0x76, 0x5a, 0x38, 0xe7, 0xdd,
3174        0x85, 0xc5, 0xad, 0x4f, 0x07, 0xe7, 0xd5, 0xb2, 0x64, 0xf0, 0x1a, 0x1a,
3175        0x2c, 0xf9, 0x18, 0xca, 0x59, 0x7e, 0x5d, 0xf6
3176    };
3177
3178    PSA_ASSERT(psa_crypto_init());
3179    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH | PSA_KEY_USAGE_VERIFY_HASH);
3180    psa_set_key_algorithm(&attributes, alg);
3181    psa_set_key_type(&attributes, key_type);
3182
3183    PSA_ASSERT(psa_import_key(&attributes, key_data, sizeof(key_data),
3184                              &key));
3185
3186    /* Call update without calling setup beforehand. */
3187    TEST_EQUAL(psa_mac_update(&operation, input, sizeof(input)),
3188               PSA_ERROR_BAD_STATE);
3189    PSA_ASSERT(psa_mac_abort(&operation));
3190
3191    /* Call sign finish without calling setup beforehand. */
3192    TEST_EQUAL(psa_mac_sign_finish(&operation, sign_mac, sizeof(sign_mac),
3193                                   &sign_mac_length),
3194               PSA_ERROR_BAD_STATE);
3195    PSA_ASSERT(psa_mac_abort(&operation));
3196
3197    /* Call verify finish without calling setup beforehand. */
3198    TEST_EQUAL(psa_mac_verify_finish(&operation,
3199                                     verify_mac, sizeof(verify_mac)),
3200               PSA_ERROR_BAD_STATE);
3201    PSA_ASSERT(psa_mac_abort(&operation));
3202
3203    /* Call setup twice in a row. */
3204    PSA_ASSERT(psa_mac_sign_setup(&operation, key, alg));
3205    ASSERT_OPERATION_IS_ACTIVE(operation);
3206    TEST_EQUAL(psa_mac_sign_setup(&operation, key, alg),
3207               PSA_ERROR_BAD_STATE);
3208    ASSERT_OPERATION_IS_INACTIVE(operation);
3209    PSA_ASSERT(psa_mac_abort(&operation));
3210    ASSERT_OPERATION_IS_INACTIVE(operation);
3211
3212    /* Call update after sign finish. */
3213    PSA_ASSERT(psa_mac_sign_setup(&operation, key, alg));
3214    PSA_ASSERT(psa_mac_update(&operation, input, sizeof(input)));
3215    PSA_ASSERT(psa_mac_sign_finish(&operation,
3216                                   sign_mac, sizeof(sign_mac),
3217                                   &sign_mac_length));
3218    TEST_EQUAL(psa_mac_update(&operation, input, sizeof(input)),
3219               PSA_ERROR_BAD_STATE);
3220    PSA_ASSERT(psa_mac_abort(&operation));
3221
3222    /* Call update after verify finish. */
3223    PSA_ASSERT(psa_mac_verify_setup(&operation, key, alg));
3224    PSA_ASSERT(psa_mac_update(&operation, input, sizeof(input)));
3225    PSA_ASSERT(psa_mac_verify_finish(&operation,
3226                                     verify_mac, sizeof(verify_mac)));
3227    TEST_EQUAL(psa_mac_update(&operation, input, sizeof(input)),
3228               PSA_ERROR_BAD_STATE);
3229    PSA_ASSERT(psa_mac_abort(&operation));
3230
3231    /* Call sign finish twice in a row. */
3232    PSA_ASSERT(psa_mac_sign_setup(&operation, key, alg));
3233    PSA_ASSERT(psa_mac_update(&operation, input, sizeof(input)));
3234    PSA_ASSERT(psa_mac_sign_finish(&operation,
3235                                   sign_mac, sizeof(sign_mac),
3236                                   &sign_mac_length));
3237    TEST_EQUAL(psa_mac_sign_finish(&operation,
3238                                   sign_mac, sizeof(sign_mac),
3239                                   &sign_mac_length),
3240               PSA_ERROR_BAD_STATE);
3241    PSA_ASSERT(psa_mac_abort(&operation));
3242
3243    /* Call verify finish twice in a row. */
3244    PSA_ASSERT(psa_mac_verify_setup(&operation, key, alg));
3245    PSA_ASSERT(psa_mac_update(&operation, input, sizeof(input)));
3246    PSA_ASSERT(psa_mac_verify_finish(&operation,
3247                                     verify_mac, sizeof(verify_mac)));
3248    TEST_EQUAL(psa_mac_verify_finish(&operation,
3249                                     verify_mac, sizeof(verify_mac)),
3250               PSA_ERROR_BAD_STATE);
3251    PSA_ASSERT(psa_mac_abort(&operation));
3252
3253    /* Setup sign but try verify. */
3254    PSA_ASSERT(psa_mac_sign_setup(&operation, key, alg));
3255    PSA_ASSERT(psa_mac_update(&operation, input, sizeof(input)));
3256    ASSERT_OPERATION_IS_ACTIVE(operation);
3257    TEST_EQUAL(psa_mac_verify_finish(&operation,
3258                                     verify_mac, sizeof(verify_mac)),
3259               PSA_ERROR_BAD_STATE);
3260    ASSERT_OPERATION_IS_INACTIVE(operation);
3261    PSA_ASSERT(psa_mac_abort(&operation));
3262    ASSERT_OPERATION_IS_INACTIVE(operation);
3263
3264    /* Setup verify but try sign. */
3265    PSA_ASSERT(psa_mac_verify_setup(&operation, key, alg));
3266    PSA_ASSERT(psa_mac_update(&operation, input, sizeof(input)));
3267    ASSERT_OPERATION_IS_ACTIVE(operation);
3268    TEST_EQUAL(psa_mac_sign_finish(&operation,
3269                                   sign_mac, sizeof(sign_mac),
3270                                   &sign_mac_length),
3271               PSA_ERROR_BAD_STATE);
3272    ASSERT_OPERATION_IS_INACTIVE(operation);
3273    PSA_ASSERT(psa_mac_abort(&operation));
3274    ASSERT_OPERATION_IS_INACTIVE(operation);
3275
3276    PSA_ASSERT(psa_destroy_key(key));
3277
3278exit:
3279    PSA_DONE();
3280}
3281/* END_CASE */
3282
3283/* BEGIN_CASE */
3284void mac_sign_verify_multi(int key_type_arg,
3285                           data_t *key_data,
3286                           int alg_arg,
3287                           data_t *input,
3288                           int is_verify,
3289                           data_t *expected_mac)
3290{
3291    size_t data_part_len = 0;
3292
3293    for (data_part_len = 1; data_part_len <= input->len; data_part_len++) {
3294        /* Split data into length(data_part_len) parts. */
3295        mbedtls_test_set_step(2000 + data_part_len);
3296
3297        if (mac_multipart_internal_func(key_type_arg, key_data,
3298                                        alg_arg,
3299                                        input, data_part_len,
3300                                        expected_mac,
3301                                        is_verify, 0) == 0) {
3302            break;
3303        }
3304
3305        /* length(0) part, length(data_part_len) part, length(0) part... */
3306        mbedtls_test_set_step(3000 + data_part_len);
3307
3308        if (mac_multipart_internal_func(key_type_arg, key_data,
3309                                        alg_arg,
3310                                        input, data_part_len,
3311                                        expected_mac,
3312                                        is_verify, 1) == 0) {
3313            break;
3314        }
3315    }
3316
3317    /* Goto is required to silence warnings about unused labels, as we
3318     * don't actually do any test assertions in this function. */
3319    goto exit;
3320}
3321/* END_CASE */
3322
3323/* BEGIN_CASE */
3324void mac_sign(int key_type_arg,
3325              data_t *key_data,
3326              int alg_arg,
3327              data_t *input,
3328              data_t *expected_mac)
3329{
3330    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
3331    psa_key_type_t key_type = key_type_arg;
3332    psa_algorithm_t alg = alg_arg;
3333    psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT;
3334    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
3335    uint8_t *actual_mac = NULL;
3336    size_t mac_buffer_size =
3337        PSA_MAC_LENGTH(key_type, PSA_BYTES_TO_BITS(key_data->len), alg);
3338    size_t mac_length = 0;
3339    const size_t output_sizes_to_test[] = {
3340        0,
3341        1,
3342        expected_mac->len - 1,
3343        expected_mac->len,
3344        expected_mac->len + 1,
3345    };
3346
3347    TEST_LE_U(mac_buffer_size, PSA_MAC_MAX_SIZE);
3348    /* We expect PSA_MAC_LENGTH to be exact. */
3349    TEST_ASSERT(expected_mac->len == mac_buffer_size);
3350
3351    PSA_ASSERT(psa_crypto_init());
3352
3353    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH);
3354    psa_set_key_algorithm(&attributes, alg);
3355    psa_set_key_type(&attributes, key_type);
3356
3357    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
3358                              &key));
3359
3360    for (size_t i = 0; i < ARRAY_LENGTH(output_sizes_to_test); i++) {
3361        const size_t output_size = output_sizes_to_test[i];
3362        psa_status_t expected_status =
3363            (output_size >= expected_mac->len ? PSA_SUCCESS :
3364             PSA_ERROR_BUFFER_TOO_SMALL);
3365
3366        mbedtls_test_set_step(output_size);
3367        ASSERT_ALLOC(actual_mac, output_size);
3368
3369        /* Calculate the MAC, one-shot case. */
3370        TEST_EQUAL(psa_mac_compute(key, alg,
3371                                   input->x, input->len,
3372                                   actual_mac, output_size, &mac_length),
3373                   expected_status);
3374        if (expected_status == PSA_SUCCESS) {
3375            ASSERT_COMPARE(expected_mac->x, expected_mac->len,
3376                           actual_mac, mac_length);
3377        }
3378
3379        if (output_size > 0) {
3380            memset(actual_mac, 0, output_size);
3381        }
3382
3383        /* Calculate the MAC, multi-part case. */
3384        PSA_ASSERT(psa_mac_sign_setup(&operation, key, alg));
3385        PSA_ASSERT(psa_mac_update(&operation,
3386                                  input->x, input->len));
3387        TEST_EQUAL(psa_mac_sign_finish(&operation,
3388                                       actual_mac, output_size,
3389                                       &mac_length),
3390                   expected_status);
3391        PSA_ASSERT(psa_mac_abort(&operation));
3392
3393        if (expected_status == PSA_SUCCESS) {
3394            ASSERT_COMPARE(expected_mac->x, expected_mac->len,
3395                           actual_mac, mac_length);
3396        }
3397        mbedtls_free(actual_mac);
3398        actual_mac = NULL;
3399    }
3400
3401exit:
3402    psa_mac_abort(&operation);
3403    psa_destroy_key(key);
3404    PSA_DONE();
3405    mbedtls_free(actual_mac);
3406}
3407/* END_CASE */
3408
3409/* BEGIN_CASE */
3410void mac_verify(int key_type_arg,
3411                data_t *key_data,
3412                int alg_arg,
3413                data_t *input,
3414                data_t *expected_mac)
3415{
3416    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
3417    psa_key_type_t key_type = key_type_arg;
3418    psa_algorithm_t alg = alg_arg;
3419    psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT;
3420    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
3421    uint8_t *perturbed_mac = NULL;
3422
3423    TEST_LE_U(expected_mac->len, PSA_MAC_MAX_SIZE);
3424
3425    PSA_ASSERT(psa_crypto_init());
3426
3427    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_VERIFY_HASH);
3428    psa_set_key_algorithm(&attributes, alg);
3429    psa_set_key_type(&attributes, key_type);
3430
3431    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
3432                              &key));
3433
3434    /* Verify correct MAC, one-shot case. */
3435    PSA_ASSERT(psa_mac_verify(key, alg, input->x, input->len,
3436                              expected_mac->x, expected_mac->len));
3437
3438    /* Verify correct MAC, multi-part case. */
3439    PSA_ASSERT(psa_mac_verify_setup(&operation, key, alg));
3440    PSA_ASSERT(psa_mac_update(&operation,
3441                              input->x, input->len));
3442    PSA_ASSERT(psa_mac_verify_finish(&operation,
3443                                     expected_mac->x,
3444                                     expected_mac->len));
3445
3446    /* Test a MAC that's too short, one-shot case. */
3447    TEST_EQUAL(psa_mac_verify(key, alg,
3448                              input->x, input->len,
3449                              expected_mac->x,
3450                              expected_mac->len - 1),
3451               PSA_ERROR_INVALID_SIGNATURE);
3452
3453    /* Test a MAC that's too short, multi-part case. */
3454    PSA_ASSERT(psa_mac_verify_setup(&operation, key, alg));
3455    PSA_ASSERT(psa_mac_update(&operation,
3456                              input->x, input->len));
3457    TEST_EQUAL(psa_mac_verify_finish(&operation,
3458                                     expected_mac->x,
3459                                     expected_mac->len - 1),
3460               PSA_ERROR_INVALID_SIGNATURE);
3461
3462    /* Test a MAC that's too long, one-shot case. */
3463    ASSERT_ALLOC(perturbed_mac, expected_mac->len + 1);
3464    memcpy(perturbed_mac, expected_mac->x, expected_mac->len);
3465    TEST_EQUAL(psa_mac_verify(key, alg,
3466                              input->x, input->len,
3467                              perturbed_mac, expected_mac->len + 1),
3468               PSA_ERROR_INVALID_SIGNATURE);
3469
3470    /* Test a MAC that's too long, multi-part case. */
3471    PSA_ASSERT(psa_mac_verify_setup(&operation, key, alg));
3472    PSA_ASSERT(psa_mac_update(&operation,
3473                              input->x, input->len));
3474    TEST_EQUAL(psa_mac_verify_finish(&operation,
3475                                     perturbed_mac,
3476                                     expected_mac->len + 1),
3477               PSA_ERROR_INVALID_SIGNATURE);
3478
3479    /* Test changing one byte. */
3480    for (size_t i = 0; i < expected_mac->len; i++) {
3481        mbedtls_test_set_step(i);
3482        perturbed_mac[i] ^= 1;
3483
3484        TEST_EQUAL(psa_mac_verify(key, alg,
3485                                  input->x, input->len,
3486                                  perturbed_mac, expected_mac->len),
3487                   PSA_ERROR_INVALID_SIGNATURE);
3488
3489        PSA_ASSERT(psa_mac_verify_setup(&operation, key, alg));
3490        PSA_ASSERT(psa_mac_update(&operation,
3491                                  input->x, input->len));
3492        TEST_EQUAL(psa_mac_verify_finish(&operation,
3493                                         perturbed_mac,
3494                                         expected_mac->len),
3495                   PSA_ERROR_INVALID_SIGNATURE);
3496        perturbed_mac[i] ^= 1;
3497    }
3498
3499exit:
3500    psa_mac_abort(&operation);
3501    psa_destroy_key(key);
3502    PSA_DONE();
3503    mbedtls_free(perturbed_mac);
3504}
3505/* END_CASE */
3506
3507/* BEGIN_CASE */
3508void cipher_operation_init()
3509{
3510    const uint8_t input[1] = { 0 };
3511    unsigned char output[1] = { 0 };
3512    size_t output_length;
3513    /* Test each valid way of initializing the object, except for `= {0}`, as
3514     * Clang 5 complains when `-Wmissing-field-initializers` is used, even
3515     * though it's OK by the C standard. We could test for this, but we'd need
3516     * to suppress the Clang warning for the test. */
3517    psa_cipher_operation_t func = psa_cipher_operation_init();
3518    psa_cipher_operation_t init = PSA_CIPHER_OPERATION_INIT;
3519    psa_cipher_operation_t zero;
3520
3521    memset(&zero, 0, sizeof(zero));
3522
3523    /* A freshly-initialized cipher operation should not be usable. */
3524    TEST_EQUAL(psa_cipher_update(&func,
3525                                 input, sizeof(input),
3526                                 output, sizeof(output),
3527                                 &output_length),
3528               PSA_ERROR_BAD_STATE);
3529    TEST_EQUAL(psa_cipher_update(&init,
3530                                 input, sizeof(input),
3531                                 output, sizeof(output),
3532                                 &output_length),
3533               PSA_ERROR_BAD_STATE);
3534    TEST_EQUAL(psa_cipher_update(&zero,
3535                                 input, sizeof(input),
3536                                 output, sizeof(output),
3537                                 &output_length),
3538               PSA_ERROR_BAD_STATE);
3539
3540    /* A default cipher operation should be abortable without error. */
3541    PSA_ASSERT(psa_cipher_abort(&func));
3542    PSA_ASSERT(psa_cipher_abort(&init));
3543    PSA_ASSERT(psa_cipher_abort(&zero));
3544}
3545/* END_CASE */
3546
3547/* BEGIN_CASE */
3548void cipher_setup(int key_type_arg,
3549                  data_t *key,
3550                  int alg_arg,
3551                  int expected_status_arg)
3552{
3553    psa_key_type_t key_type = key_type_arg;
3554    psa_algorithm_t alg = alg_arg;
3555    psa_status_t expected_status = expected_status_arg;
3556    psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT;
3557    psa_status_t status;
3558#if defined(KNOWN_SUPPORTED_CIPHER_ALG)
3559    const uint8_t smoke_test_key_data[16] = "kkkkkkkkkkkkkkkk";
3560#endif
3561
3562    PSA_ASSERT(psa_crypto_init());
3563
3564    if (!exercise_cipher_setup(key_type, key->x, key->len, alg,
3565                               &operation, &status)) {
3566        goto exit;
3567    }
3568    TEST_EQUAL(status, expected_status);
3569
3570    /* The operation object should be reusable. */
3571#if defined(KNOWN_SUPPORTED_CIPHER_ALG)
3572    if (!exercise_cipher_setup(KNOWN_SUPPORTED_CIPHER_KEY_TYPE,
3573                               smoke_test_key_data,
3574                               sizeof(smoke_test_key_data),
3575                               KNOWN_SUPPORTED_CIPHER_ALG,
3576                               &operation, &status)) {
3577        goto exit;
3578    }
3579    TEST_EQUAL(status, PSA_SUCCESS);
3580#endif
3581
3582exit:
3583    psa_cipher_abort(&operation);
3584    PSA_DONE();
3585}
3586/* END_CASE */
3587
3588/* BEGIN_CASE depends_on:PSA_WANT_KEY_TYPE_AES:PSA_WANT_ALG_CBC_PKCS7 */
3589void cipher_bad_order()
3590{
3591    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
3592    psa_key_type_t key_type = PSA_KEY_TYPE_AES;
3593    psa_algorithm_t alg = PSA_ALG_CBC_PKCS7;
3594    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
3595    psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT;
3596    unsigned char iv[PSA_BLOCK_CIPHER_BLOCK_LENGTH(PSA_KEY_TYPE_AES)] = { 0 };
3597    const uint8_t key_data[] = {
3598        0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa,
3599        0xaa, 0xaa, 0xaa, 0xaa
3600    };
3601    const uint8_t text[] = {
3602        0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb, 0xbb,
3603        0xbb, 0xbb, 0xbb, 0xbb
3604    };
3605    uint8_t buffer[PSA_BLOCK_CIPHER_BLOCK_LENGTH(PSA_KEY_TYPE_AES)] = { 0 };
3606    size_t length = 0;
3607
3608    PSA_ASSERT(psa_crypto_init());
3609    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT);
3610    psa_set_key_algorithm(&attributes, alg);
3611    psa_set_key_type(&attributes, key_type);
3612    PSA_ASSERT(psa_import_key(&attributes, key_data, sizeof(key_data),
3613                              &key));
3614
3615    /* Call encrypt setup twice in a row. */
3616    PSA_ASSERT(psa_cipher_encrypt_setup(&operation, key, alg));
3617    ASSERT_OPERATION_IS_ACTIVE(operation);
3618    TEST_EQUAL(psa_cipher_encrypt_setup(&operation, key, alg),
3619               PSA_ERROR_BAD_STATE);
3620    ASSERT_OPERATION_IS_INACTIVE(operation);
3621    PSA_ASSERT(psa_cipher_abort(&operation));
3622    ASSERT_OPERATION_IS_INACTIVE(operation);
3623
3624    /* Call decrypt setup twice in a row. */
3625    PSA_ASSERT(psa_cipher_decrypt_setup(&operation, key, alg));
3626    ASSERT_OPERATION_IS_ACTIVE(operation);
3627    TEST_EQUAL(psa_cipher_decrypt_setup(&operation, key, alg),
3628               PSA_ERROR_BAD_STATE);
3629    ASSERT_OPERATION_IS_INACTIVE(operation);
3630    PSA_ASSERT(psa_cipher_abort(&operation));
3631    ASSERT_OPERATION_IS_INACTIVE(operation);
3632
3633    /* Generate an IV without calling setup beforehand. */
3634    TEST_EQUAL(psa_cipher_generate_iv(&operation,
3635                                      buffer, sizeof(buffer),
3636                                      &length),
3637               PSA_ERROR_BAD_STATE);
3638    PSA_ASSERT(psa_cipher_abort(&operation));
3639
3640    /* Generate an IV twice in a row. */
3641    PSA_ASSERT(psa_cipher_encrypt_setup(&operation, key, alg));
3642    PSA_ASSERT(psa_cipher_generate_iv(&operation,
3643                                      buffer, sizeof(buffer),
3644                                      &length));
3645    ASSERT_OPERATION_IS_ACTIVE(operation);
3646    TEST_EQUAL(psa_cipher_generate_iv(&operation,
3647                                      buffer, sizeof(buffer),
3648                                      &length),
3649               PSA_ERROR_BAD_STATE);
3650    ASSERT_OPERATION_IS_INACTIVE(operation);
3651    PSA_ASSERT(psa_cipher_abort(&operation));
3652    ASSERT_OPERATION_IS_INACTIVE(operation);
3653
3654    /* Generate an IV after it's already set. */
3655    PSA_ASSERT(psa_cipher_encrypt_setup(&operation, key, alg));
3656    PSA_ASSERT(psa_cipher_set_iv(&operation,
3657                                 iv, sizeof(iv)));
3658    TEST_EQUAL(psa_cipher_generate_iv(&operation,
3659                                      buffer, sizeof(buffer),
3660                                      &length),
3661               PSA_ERROR_BAD_STATE);
3662    PSA_ASSERT(psa_cipher_abort(&operation));
3663
3664    /* Set an IV without calling setup beforehand. */
3665    TEST_EQUAL(psa_cipher_set_iv(&operation,
3666                                 iv, sizeof(iv)),
3667               PSA_ERROR_BAD_STATE);
3668    PSA_ASSERT(psa_cipher_abort(&operation));
3669
3670    /* Set an IV after it's already set. */
3671    PSA_ASSERT(psa_cipher_encrypt_setup(&operation, key, alg));
3672    PSA_ASSERT(psa_cipher_set_iv(&operation,
3673                                 iv, sizeof(iv)));
3674    ASSERT_OPERATION_IS_ACTIVE(operation);
3675    TEST_EQUAL(psa_cipher_set_iv(&operation,
3676                                 iv, sizeof(iv)),
3677               PSA_ERROR_BAD_STATE);
3678    ASSERT_OPERATION_IS_INACTIVE(operation);
3679    PSA_ASSERT(psa_cipher_abort(&operation));
3680    ASSERT_OPERATION_IS_INACTIVE(operation);
3681
3682    /* Set an IV after it's already generated. */
3683    PSA_ASSERT(psa_cipher_encrypt_setup(&operation, key, alg));
3684    PSA_ASSERT(psa_cipher_generate_iv(&operation,
3685                                      buffer, sizeof(buffer),
3686                                      &length));
3687    TEST_EQUAL(psa_cipher_set_iv(&operation,
3688                                 iv, sizeof(iv)),
3689               PSA_ERROR_BAD_STATE);
3690    PSA_ASSERT(psa_cipher_abort(&operation));
3691
3692    /* Call update without calling setup beforehand. */
3693    TEST_EQUAL(psa_cipher_update(&operation,
3694                                 text, sizeof(text),
3695                                 buffer, sizeof(buffer),
3696                                 &length),
3697               PSA_ERROR_BAD_STATE);
3698    PSA_ASSERT(psa_cipher_abort(&operation));
3699
3700    /* Call update without an IV where an IV is required. */
3701    PSA_ASSERT(psa_cipher_encrypt_setup(&operation, key, alg));
3702    ASSERT_OPERATION_IS_ACTIVE(operation);
3703    TEST_EQUAL(psa_cipher_update(&operation,
3704                                 text, sizeof(text),
3705                                 buffer, sizeof(buffer),
3706                                 &length),
3707               PSA_ERROR_BAD_STATE);
3708    ASSERT_OPERATION_IS_INACTIVE(operation);
3709    PSA_ASSERT(psa_cipher_abort(&operation));
3710    ASSERT_OPERATION_IS_INACTIVE(operation);
3711
3712    /* Call update after finish. */
3713    PSA_ASSERT(psa_cipher_encrypt_setup(&operation, key, alg));
3714    PSA_ASSERT(psa_cipher_set_iv(&operation,
3715                                 iv, sizeof(iv)));
3716    PSA_ASSERT(psa_cipher_finish(&operation,
3717                                 buffer, sizeof(buffer), &length));
3718    TEST_EQUAL(psa_cipher_update(&operation,
3719                                 text, sizeof(text),
3720                                 buffer, sizeof(buffer),
3721                                 &length),
3722               PSA_ERROR_BAD_STATE);
3723    PSA_ASSERT(psa_cipher_abort(&operation));
3724
3725    /* Call finish without calling setup beforehand. */
3726    TEST_EQUAL(psa_cipher_finish(&operation,
3727                                 buffer, sizeof(buffer), &length),
3728               PSA_ERROR_BAD_STATE);
3729    PSA_ASSERT(psa_cipher_abort(&operation));
3730
3731    /* Call finish without an IV where an IV is required. */
3732    PSA_ASSERT(psa_cipher_encrypt_setup(&operation, key, alg));
3733    /* Not calling update means we are encrypting an empty buffer, which is OK
3734     * for cipher modes with padding. */
3735    ASSERT_OPERATION_IS_ACTIVE(operation);
3736    TEST_EQUAL(psa_cipher_finish(&operation,
3737                                 buffer, sizeof(buffer), &length),
3738               PSA_ERROR_BAD_STATE);
3739    ASSERT_OPERATION_IS_INACTIVE(operation);
3740    PSA_ASSERT(psa_cipher_abort(&operation));
3741    ASSERT_OPERATION_IS_INACTIVE(operation);
3742
3743    /* Call finish twice in a row. */
3744    PSA_ASSERT(psa_cipher_encrypt_setup(&operation, key, alg));
3745    PSA_ASSERT(psa_cipher_set_iv(&operation,
3746                                 iv, sizeof(iv)));
3747    PSA_ASSERT(psa_cipher_finish(&operation,
3748                                 buffer, sizeof(buffer), &length));
3749    TEST_EQUAL(psa_cipher_finish(&operation,
3750                                 buffer, sizeof(buffer), &length),
3751               PSA_ERROR_BAD_STATE);
3752    PSA_ASSERT(psa_cipher_abort(&operation));
3753
3754    PSA_ASSERT(psa_destroy_key(key));
3755
3756exit:
3757    psa_cipher_abort(&operation);
3758    PSA_DONE();
3759}
3760/* END_CASE */
3761
3762/* BEGIN_CASE */
3763void cipher_encrypt_fail(int alg_arg,
3764                         int key_type_arg,
3765                         data_t *key_data,
3766                         data_t *input,
3767                         int expected_status_arg)
3768{
3769    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
3770    psa_status_t status;
3771    psa_key_type_t key_type = key_type_arg;
3772    psa_algorithm_t alg = alg_arg;
3773    psa_status_t expected_status = expected_status_arg;
3774    unsigned char iv[PSA_CIPHER_IV_MAX_SIZE] = { 0 };
3775    size_t iv_size = PSA_CIPHER_IV_MAX_SIZE;
3776    size_t iv_length = 0;
3777    unsigned char *output = NULL;
3778    size_t output_buffer_size = 0;
3779    size_t output_length = 0;
3780    size_t function_output_length;
3781    psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT;
3782    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
3783
3784    if (PSA_ERROR_BAD_STATE != expected_status) {
3785        PSA_ASSERT(psa_crypto_init());
3786
3787        psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
3788        psa_set_key_algorithm(&attributes, alg);
3789        psa_set_key_type(&attributes, key_type);
3790
3791        output_buffer_size = PSA_CIPHER_ENCRYPT_OUTPUT_SIZE(key_type, alg,
3792                                                            input->len);
3793        ASSERT_ALLOC(output, output_buffer_size);
3794
3795        PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
3796                                  &key));
3797    }
3798
3799    /* Encrypt, one-shot */
3800    status = psa_cipher_encrypt(key, alg, input->x, input->len, output,
3801                                output_buffer_size, &output_length);
3802
3803    TEST_EQUAL(status, expected_status);
3804
3805    /* Encrypt, multi-part */
3806    status = psa_cipher_encrypt_setup(&operation, key, alg);
3807    if (status == PSA_SUCCESS) {
3808        if (alg != PSA_ALG_ECB_NO_PADDING) {
3809            PSA_ASSERT(psa_cipher_generate_iv(&operation,
3810                                              iv, iv_size,
3811                                              &iv_length));
3812        }
3813
3814        status = psa_cipher_update(&operation, input->x, input->len,
3815                                   output, output_buffer_size,
3816                                   &function_output_length);
3817        if (status == PSA_SUCCESS) {
3818            output_length += function_output_length;
3819
3820            status = psa_cipher_finish(&operation, output + output_length,
3821                                       output_buffer_size - output_length,
3822                                       &function_output_length);
3823
3824            TEST_EQUAL(status, expected_status);
3825        } else {
3826            TEST_EQUAL(status, expected_status);
3827        }
3828    } else {
3829        TEST_EQUAL(status, expected_status);
3830    }
3831
3832exit:
3833    psa_cipher_abort(&operation);
3834    mbedtls_free(output);
3835    psa_destroy_key(key);
3836    PSA_DONE();
3837}
3838/* END_CASE */
3839
3840/* BEGIN_CASE */
3841void cipher_encrypt_validate_iv_length(int alg, int key_type, data_t *key_data,
3842                                       data_t *input, int iv_length,
3843                                       int expected_result)
3844{
3845    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
3846    psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT;
3847    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
3848    size_t output_buffer_size = 0;
3849    unsigned char *output = NULL;
3850
3851    output_buffer_size = PSA_CIPHER_ENCRYPT_OUTPUT_SIZE(key_type, alg, input->len);
3852    ASSERT_ALLOC(output, output_buffer_size);
3853
3854    PSA_ASSERT(psa_crypto_init());
3855
3856    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
3857    psa_set_key_algorithm(&attributes, alg);
3858    psa_set_key_type(&attributes, key_type);
3859
3860    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
3861                              &key));
3862    PSA_ASSERT(psa_cipher_encrypt_setup(&operation, key, alg));
3863    TEST_EQUAL(expected_result, psa_cipher_set_iv(&operation, output,
3864                                                  iv_length));
3865
3866exit:
3867    psa_cipher_abort(&operation);
3868    mbedtls_free(output);
3869    psa_destroy_key(key);
3870    PSA_DONE();
3871}
3872/* END_CASE */
3873
3874/* BEGIN_CASE */
3875void cipher_alg_without_iv(int alg_arg, int key_type_arg, data_t *key_data,
3876                           data_t *plaintext, data_t *ciphertext)
3877{
3878    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
3879    psa_key_type_t key_type = key_type_arg;
3880    psa_algorithm_t alg = alg_arg;
3881    psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT;
3882    uint8_t iv[1] = { 0x5a };
3883    unsigned char *output = NULL;
3884    size_t output_buffer_size = 0;
3885    size_t output_length, length;
3886    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
3887
3888    PSA_ASSERT(psa_crypto_init());
3889
3890    /* Validate size macros */
3891    TEST_LE_U(ciphertext->len,
3892              PSA_CIPHER_ENCRYPT_OUTPUT_SIZE(key_type, alg, plaintext->len));
3893    TEST_LE_U(PSA_CIPHER_ENCRYPT_OUTPUT_SIZE(key_type, alg, plaintext->len),
3894              PSA_CIPHER_ENCRYPT_OUTPUT_MAX_SIZE(plaintext->len));
3895    TEST_LE_U(plaintext->len,
3896              PSA_CIPHER_DECRYPT_OUTPUT_SIZE(key_type, alg, ciphertext->len));
3897    TEST_LE_U(PSA_CIPHER_DECRYPT_OUTPUT_SIZE(key_type, alg, ciphertext->len),
3898              PSA_CIPHER_DECRYPT_OUTPUT_MAX_SIZE(ciphertext->len));
3899
3900
3901    /* Set up key and output buffer */
3902    psa_set_key_usage_flags(&attributes,
3903                            PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT);
3904    psa_set_key_algorithm(&attributes, alg);
3905    psa_set_key_type(&attributes, key_type);
3906    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
3907                              &key));
3908    output_buffer_size = PSA_CIPHER_ENCRYPT_OUTPUT_SIZE(key_type, alg,
3909                                                        plaintext->len);
3910    ASSERT_ALLOC(output, output_buffer_size);
3911
3912    /* set_iv() is not allowed */
3913    PSA_ASSERT(psa_cipher_encrypt_setup(&operation, key, alg));
3914    TEST_EQUAL(psa_cipher_set_iv(&operation, iv, sizeof(iv)),
3915               PSA_ERROR_BAD_STATE);
3916    PSA_ASSERT(psa_cipher_decrypt_setup(&operation, key, alg));
3917    TEST_EQUAL(psa_cipher_set_iv(&operation, iv, sizeof(iv)),
3918               PSA_ERROR_BAD_STATE);
3919
3920    /* generate_iv() is not allowed */
3921    PSA_ASSERT(psa_cipher_encrypt_setup(&operation, key, alg));
3922    TEST_EQUAL(psa_cipher_generate_iv(&operation, iv, sizeof(iv),
3923                                      &length),
3924               PSA_ERROR_BAD_STATE);
3925    PSA_ASSERT(psa_cipher_decrypt_setup(&operation, key, alg));
3926    TEST_EQUAL(psa_cipher_generate_iv(&operation, iv, sizeof(iv),
3927                                      &length),
3928               PSA_ERROR_BAD_STATE);
3929
3930    /* Multipart encryption */
3931    PSA_ASSERT(psa_cipher_encrypt_setup(&operation, key, alg));
3932    output_length = 0;
3933    length = ~0;
3934    PSA_ASSERT(psa_cipher_update(&operation,
3935                                 plaintext->x, plaintext->len,
3936                                 output, output_buffer_size,
3937                                 &length));
3938    TEST_LE_U(length, output_buffer_size);
3939    output_length += length;
3940    PSA_ASSERT(psa_cipher_finish(&operation,
3941                                 mbedtls_buffer_offset(output, output_length),
3942                                 output_buffer_size - output_length,
3943                                 &length));
3944    output_length += length;
3945    ASSERT_COMPARE(ciphertext->x, ciphertext->len,
3946                   output, output_length);
3947
3948    /* Multipart encryption */
3949    PSA_ASSERT(psa_cipher_decrypt_setup(&operation, key, alg));
3950    output_length = 0;
3951    length = ~0;
3952    PSA_ASSERT(psa_cipher_update(&operation,
3953                                 ciphertext->x, ciphertext->len,
3954                                 output, output_buffer_size,
3955                                 &length));
3956    TEST_LE_U(length, output_buffer_size);
3957    output_length += length;
3958    PSA_ASSERT(psa_cipher_finish(&operation,
3959                                 mbedtls_buffer_offset(output, output_length),
3960                                 output_buffer_size - output_length,
3961                                 &length));
3962    output_length += length;
3963    ASSERT_COMPARE(plaintext->x, plaintext->len,
3964                   output, output_length);
3965
3966    /* One-shot encryption */
3967    output_length = ~0;
3968    PSA_ASSERT(psa_cipher_encrypt(key, alg, plaintext->x, plaintext->len,
3969                                  output, output_buffer_size,
3970                                  &output_length));
3971    ASSERT_COMPARE(ciphertext->x, ciphertext->len,
3972                   output, output_length);
3973
3974    /* One-shot decryption */
3975    output_length = ~0;
3976    PSA_ASSERT(psa_cipher_decrypt(key, alg, ciphertext->x, ciphertext->len,
3977                                  output, output_buffer_size,
3978                                  &output_length));
3979    ASSERT_COMPARE(plaintext->x, plaintext->len,
3980                   output, output_length);
3981
3982exit:
3983    PSA_ASSERT(psa_cipher_abort(&operation));
3984    mbedtls_free(output);
3985    psa_cipher_abort(&operation);
3986    psa_destroy_key(key);
3987    PSA_DONE();
3988}
3989/* END_CASE */
3990
3991/* BEGIN_CASE */
3992void cipher_bad_key(int alg_arg, int key_type_arg, data_t *key_data)
3993{
3994    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
3995    psa_algorithm_t alg = alg_arg;
3996    psa_key_type_t key_type = key_type_arg;
3997    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
3998    psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT;
3999    psa_status_t status;
4000
4001    PSA_ASSERT(psa_crypto_init());
4002
4003    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
4004    psa_set_key_algorithm(&attributes, alg);
4005    psa_set_key_type(&attributes, key_type);
4006
4007    /* Usage of either of these two size macros would cause divide by zero
4008     * with incorrect key types previously. Input length should be irrelevant
4009     * here. */
4010    TEST_EQUAL(PSA_CIPHER_ENCRYPT_OUTPUT_SIZE(key_type, alg, 16),
4011               0);
4012    TEST_EQUAL(PSA_CIPHER_UPDATE_OUTPUT_SIZE(key_type, alg, 16), 0);
4013
4014
4015    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
4016                              &key));
4017
4018    /* Should fail due to invalid alg type (to support invalid key type).
4019     * Encrypt or decrypt will end up in the same place. */
4020    status = psa_cipher_encrypt_setup(&operation, key, alg);
4021
4022    TEST_EQUAL(status, PSA_ERROR_INVALID_ARGUMENT);
4023
4024exit:
4025    psa_cipher_abort(&operation);
4026    psa_destroy_key(key);
4027    PSA_DONE();
4028}
4029/* END_CASE */
4030
4031/* BEGIN_CASE */
4032void cipher_encrypt_validation(int alg_arg,
4033                               int key_type_arg,
4034                               data_t *key_data,
4035                               data_t *input)
4036{
4037    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
4038    psa_key_type_t key_type = key_type_arg;
4039    psa_algorithm_t alg = alg_arg;
4040    size_t iv_size = PSA_CIPHER_IV_LENGTH(key_type, alg);
4041    unsigned char *output1 = NULL;
4042    size_t output1_buffer_size = 0;
4043    size_t output1_length = 0;
4044    unsigned char *output2 = NULL;
4045    size_t output2_buffer_size = 0;
4046    size_t output2_length = 0;
4047    size_t function_output_length = 0;
4048    psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT;
4049    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
4050
4051    PSA_ASSERT(psa_crypto_init());
4052
4053    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
4054    psa_set_key_algorithm(&attributes, alg);
4055    psa_set_key_type(&attributes, key_type);
4056
4057    output1_buffer_size = PSA_CIPHER_ENCRYPT_OUTPUT_SIZE(key_type, alg, input->len);
4058    output2_buffer_size = PSA_CIPHER_UPDATE_OUTPUT_SIZE(key_type, alg, input->len) +
4059                          PSA_CIPHER_FINISH_OUTPUT_SIZE(key_type, alg);
4060    ASSERT_ALLOC(output1, output1_buffer_size);
4061    ASSERT_ALLOC(output2, output2_buffer_size);
4062
4063    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
4064                              &key));
4065
4066    /* The one-shot cipher encryption uses generated iv so validating
4067       the output is not possible. Validating with multipart encryption. */
4068    PSA_ASSERT(psa_cipher_encrypt(key, alg, input->x, input->len, output1,
4069                                  output1_buffer_size, &output1_length));
4070    TEST_LE_U(output1_length,
4071              PSA_CIPHER_ENCRYPT_OUTPUT_SIZE(key_type, alg, input->len));
4072    TEST_LE_U(output1_length,
4073              PSA_CIPHER_ENCRYPT_OUTPUT_MAX_SIZE(input->len));
4074
4075    PSA_ASSERT(psa_cipher_encrypt_setup(&operation, key, alg));
4076    PSA_ASSERT(psa_cipher_set_iv(&operation, output1, iv_size));
4077
4078    PSA_ASSERT(psa_cipher_update(&operation,
4079                                 input->x, input->len,
4080                                 output2, output2_buffer_size,
4081                                 &function_output_length));
4082    TEST_LE_U(function_output_length,
4083              PSA_CIPHER_UPDATE_OUTPUT_SIZE(key_type, alg, input->len));
4084    TEST_LE_U(function_output_length,
4085              PSA_CIPHER_UPDATE_OUTPUT_MAX_SIZE(input->len));
4086    output2_length += function_output_length;
4087
4088    PSA_ASSERT(psa_cipher_finish(&operation,
4089                                 output2 + output2_length,
4090                                 output2_buffer_size - output2_length,
4091                                 &function_output_length));
4092    TEST_LE_U(function_output_length,
4093              PSA_CIPHER_FINISH_OUTPUT_SIZE(key_type, alg));
4094    TEST_LE_U(function_output_length,
4095              PSA_CIPHER_FINISH_OUTPUT_MAX_SIZE);
4096    output2_length += function_output_length;
4097
4098    PSA_ASSERT(psa_cipher_abort(&operation));
4099    ASSERT_COMPARE(output1 + iv_size, output1_length - iv_size,
4100                   output2, output2_length);
4101
4102exit:
4103    psa_cipher_abort(&operation);
4104    mbedtls_free(output1);
4105    mbedtls_free(output2);
4106    psa_destroy_key(key);
4107    PSA_DONE();
4108}
4109/* END_CASE */
4110
4111/* BEGIN_CASE */
4112void cipher_encrypt_multipart(int alg_arg, int key_type_arg,
4113                              data_t *key_data, data_t *iv,
4114                              data_t *input,
4115                              int first_part_size_arg,
4116                              int output1_length_arg, int output2_length_arg,
4117                              data_t *expected_output,
4118                              int expected_status_arg)
4119{
4120    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
4121    psa_key_type_t key_type = key_type_arg;
4122    psa_algorithm_t alg = alg_arg;
4123    psa_status_t status;
4124    psa_status_t expected_status = expected_status_arg;
4125    size_t first_part_size = first_part_size_arg;
4126    size_t output1_length = output1_length_arg;
4127    size_t output2_length = output2_length_arg;
4128    unsigned char *output = NULL;
4129    size_t output_buffer_size = 0;
4130    size_t function_output_length = 0;
4131    size_t total_output_length = 0;
4132    psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT;
4133    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
4134
4135    PSA_ASSERT(psa_crypto_init());
4136
4137    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
4138    psa_set_key_algorithm(&attributes, alg);
4139    psa_set_key_type(&attributes, key_type);
4140
4141    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
4142                              &key));
4143
4144    PSA_ASSERT(psa_cipher_encrypt_setup(&operation, key, alg));
4145
4146    if (iv->len > 0) {
4147        PSA_ASSERT(psa_cipher_set_iv(&operation, iv->x, iv->len));
4148    }
4149
4150    output_buffer_size = PSA_CIPHER_UPDATE_OUTPUT_SIZE(key_type, alg, input->len) +
4151                         PSA_CIPHER_FINISH_OUTPUT_SIZE(key_type, alg);
4152    ASSERT_ALLOC(output, output_buffer_size);
4153
4154    TEST_LE_U(first_part_size, input->len);
4155    PSA_ASSERT(psa_cipher_update(&operation, input->x, first_part_size,
4156                                 output, output_buffer_size,
4157                                 &function_output_length));
4158    TEST_ASSERT(function_output_length == output1_length);
4159    TEST_LE_U(function_output_length,
4160              PSA_CIPHER_UPDATE_OUTPUT_SIZE(key_type, alg, first_part_size));
4161    TEST_LE_U(function_output_length,
4162              PSA_CIPHER_UPDATE_OUTPUT_MAX_SIZE(first_part_size));
4163    total_output_length += function_output_length;
4164
4165    if (first_part_size < input->len) {
4166        PSA_ASSERT(psa_cipher_update(&operation,
4167                                     input->x + first_part_size,
4168                                     input->len - first_part_size,
4169                                     (output_buffer_size == 0 ? NULL :
4170                                      output + total_output_length),
4171                                     output_buffer_size - total_output_length,
4172                                     &function_output_length));
4173        TEST_ASSERT(function_output_length == output2_length);
4174        TEST_LE_U(function_output_length,
4175                  PSA_CIPHER_UPDATE_OUTPUT_SIZE(key_type,
4176                                                alg,
4177                                                input->len - first_part_size));
4178        TEST_LE_U(function_output_length,
4179                  PSA_CIPHER_UPDATE_OUTPUT_MAX_SIZE(input->len));
4180        total_output_length += function_output_length;
4181    }
4182
4183    status = psa_cipher_finish(&operation,
4184                               (output_buffer_size == 0 ? NULL :
4185                                output + total_output_length),
4186                               output_buffer_size - total_output_length,
4187                               &function_output_length);
4188    TEST_LE_U(function_output_length,
4189              PSA_CIPHER_FINISH_OUTPUT_SIZE(key_type, alg));
4190    TEST_LE_U(function_output_length,
4191              PSA_CIPHER_FINISH_OUTPUT_MAX_SIZE);
4192    total_output_length += function_output_length;
4193    TEST_EQUAL(status, expected_status);
4194
4195    if (expected_status == PSA_SUCCESS) {
4196        PSA_ASSERT(psa_cipher_abort(&operation));
4197
4198        ASSERT_COMPARE(expected_output->x, expected_output->len,
4199                       output, total_output_length);
4200    }
4201
4202exit:
4203    psa_cipher_abort(&operation);
4204    mbedtls_free(output);
4205    psa_destroy_key(key);
4206    PSA_DONE();
4207}
4208/* END_CASE */
4209
4210/* BEGIN_CASE */
4211void cipher_decrypt_multipart(int alg_arg, int key_type_arg,
4212                              data_t *key_data, data_t *iv,
4213                              data_t *input,
4214                              int first_part_size_arg,
4215                              int output1_length_arg, int output2_length_arg,
4216                              data_t *expected_output,
4217                              int expected_status_arg)
4218{
4219    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
4220    psa_key_type_t key_type = key_type_arg;
4221    psa_algorithm_t alg = alg_arg;
4222    psa_status_t status;
4223    psa_status_t expected_status = expected_status_arg;
4224    size_t first_part_size = first_part_size_arg;
4225    size_t output1_length = output1_length_arg;
4226    size_t output2_length = output2_length_arg;
4227    unsigned char *output = NULL;
4228    size_t output_buffer_size = 0;
4229    size_t function_output_length = 0;
4230    size_t total_output_length = 0;
4231    psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT;
4232    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
4233
4234    PSA_ASSERT(psa_crypto_init());
4235
4236    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DECRYPT);
4237    psa_set_key_algorithm(&attributes, alg);
4238    psa_set_key_type(&attributes, key_type);
4239
4240    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
4241                              &key));
4242
4243    PSA_ASSERT(psa_cipher_decrypt_setup(&operation, key, alg));
4244
4245    if (iv->len > 0) {
4246        PSA_ASSERT(psa_cipher_set_iv(&operation, iv->x, iv->len));
4247    }
4248
4249    output_buffer_size = PSA_CIPHER_UPDATE_OUTPUT_SIZE(key_type, alg, input->len) +
4250                         PSA_CIPHER_FINISH_OUTPUT_SIZE(key_type, alg);
4251    ASSERT_ALLOC(output, output_buffer_size);
4252
4253    TEST_LE_U(first_part_size, input->len);
4254    PSA_ASSERT(psa_cipher_update(&operation,
4255                                 input->x, first_part_size,
4256                                 output, output_buffer_size,
4257                                 &function_output_length));
4258    TEST_ASSERT(function_output_length == output1_length);
4259    TEST_LE_U(function_output_length,
4260              PSA_CIPHER_UPDATE_OUTPUT_SIZE(key_type, alg, first_part_size));
4261    TEST_LE_U(function_output_length,
4262              PSA_CIPHER_UPDATE_OUTPUT_MAX_SIZE(first_part_size));
4263    total_output_length += function_output_length;
4264
4265    if (first_part_size < input->len) {
4266        PSA_ASSERT(psa_cipher_update(&operation,
4267                                     input->x + first_part_size,
4268                                     input->len - first_part_size,
4269                                     (output_buffer_size == 0 ? NULL :
4270                                      output + total_output_length),
4271                                     output_buffer_size - total_output_length,
4272                                     &function_output_length));
4273        TEST_ASSERT(function_output_length == output2_length);
4274        TEST_LE_U(function_output_length,
4275                  PSA_CIPHER_UPDATE_OUTPUT_SIZE(key_type,
4276                                                alg,
4277                                                input->len - first_part_size));
4278        TEST_LE_U(function_output_length,
4279                  PSA_CIPHER_UPDATE_OUTPUT_MAX_SIZE(input->len));
4280        total_output_length += function_output_length;
4281    }
4282
4283    status = psa_cipher_finish(&operation,
4284                               (output_buffer_size == 0 ? NULL :
4285                                output + total_output_length),
4286                               output_buffer_size - total_output_length,
4287                               &function_output_length);
4288    TEST_LE_U(function_output_length,
4289              PSA_CIPHER_FINISH_OUTPUT_SIZE(key_type, alg));
4290    TEST_LE_U(function_output_length,
4291              PSA_CIPHER_FINISH_OUTPUT_MAX_SIZE);
4292    total_output_length += function_output_length;
4293    TEST_EQUAL(status, expected_status);
4294
4295    if (expected_status == PSA_SUCCESS) {
4296        PSA_ASSERT(psa_cipher_abort(&operation));
4297
4298        ASSERT_COMPARE(expected_output->x, expected_output->len,
4299                       output, total_output_length);
4300    }
4301
4302exit:
4303    psa_cipher_abort(&operation);
4304    mbedtls_free(output);
4305    psa_destroy_key(key);
4306    PSA_DONE();
4307}
4308/* END_CASE */
4309
4310/* BEGIN_CASE */
4311void cipher_decrypt_fail(int alg_arg,
4312                         int key_type_arg,
4313                         data_t *key_data,
4314                         data_t *iv,
4315                         data_t *input_arg,
4316                         int expected_status_arg)
4317{
4318    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
4319    psa_status_t status;
4320    psa_key_type_t key_type = key_type_arg;
4321    psa_algorithm_t alg = alg_arg;
4322    psa_status_t expected_status = expected_status_arg;
4323    unsigned char *input = NULL;
4324    size_t input_buffer_size = 0;
4325    unsigned char *output = NULL;
4326    unsigned char *output_multi = NULL;
4327    size_t output_buffer_size = 0;
4328    size_t output_length = 0;
4329    size_t function_output_length;
4330    psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT;
4331    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
4332
4333    if (PSA_ERROR_BAD_STATE != expected_status) {
4334        PSA_ASSERT(psa_crypto_init());
4335
4336        psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DECRYPT);
4337        psa_set_key_algorithm(&attributes, alg);
4338        psa_set_key_type(&attributes, key_type);
4339
4340        PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
4341                                  &key));
4342    }
4343
4344    /* Allocate input buffer and copy the iv and the plaintext */
4345    input_buffer_size = ((size_t) input_arg->len + (size_t) iv->len);
4346    if (input_buffer_size > 0) {
4347        ASSERT_ALLOC(input, input_buffer_size);
4348        memcpy(input, iv->x, iv->len);
4349        memcpy(input + iv->len, input_arg->x, input_arg->len);
4350    }
4351
4352    output_buffer_size = PSA_CIPHER_DECRYPT_OUTPUT_SIZE(key_type, alg, input_buffer_size);
4353    ASSERT_ALLOC(output, output_buffer_size);
4354
4355    /* Decrypt, one-short */
4356    status = psa_cipher_decrypt(key, alg, input, input_buffer_size, output,
4357                                output_buffer_size, &output_length);
4358    TEST_EQUAL(status, expected_status);
4359
4360    /* Decrypt, multi-part */
4361    status = psa_cipher_decrypt_setup(&operation, key, alg);
4362    if (status == PSA_SUCCESS) {
4363        output_buffer_size = PSA_CIPHER_UPDATE_OUTPUT_SIZE(key_type, alg,
4364                                                           input_arg->len) +
4365                             PSA_CIPHER_FINISH_OUTPUT_SIZE(key_type, alg);
4366        ASSERT_ALLOC(output_multi, output_buffer_size);
4367
4368        if (iv->len > 0) {
4369            status = psa_cipher_set_iv(&operation, iv->x, iv->len);
4370
4371            if (status != PSA_SUCCESS) {
4372                TEST_EQUAL(status, expected_status);
4373            }
4374        }
4375
4376        if (status == PSA_SUCCESS) {
4377            status = psa_cipher_update(&operation,
4378                                       input_arg->x, input_arg->len,
4379                                       output_multi, output_buffer_size,
4380                                       &function_output_length);
4381            if (status == PSA_SUCCESS) {
4382                output_length = function_output_length;
4383
4384                status = psa_cipher_finish(&operation,
4385                                           output_multi + output_length,
4386                                           output_buffer_size - output_length,
4387                                           &function_output_length);
4388
4389                TEST_EQUAL(status, expected_status);
4390            } else {
4391                TEST_EQUAL(status, expected_status);
4392            }
4393        } else {
4394            TEST_EQUAL(status, expected_status);
4395        }
4396    } else {
4397        TEST_EQUAL(status, expected_status);
4398    }
4399
4400exit:
4401    psa_cipher_abort(&operation);
4402    mbedtls_free(input);
4403    mbedtls_free(output);
4404    mbedtls_free(output_multi);
4405    psa_destroy_key(key);
4406    PSA_DONE();
4407}
4408/* END_CASE */
4409
4410/* BEGIN_CASE */
4411void cipher_decrypt(int alg_arg,
4412                    int key_type_arg,
4413                    data_t *key_data,
4414                    data_t *iv,
4415                    data_t *input_arg,
4416                    data_t *expected_output)
4417{
4418    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
4419    psa_key_type_t key_type = key_type_arg;
4420    psa_algorithm_t alg = alg_arg;
4421    unsigned char *input = NULL;
4422    size_t input_buffer_size = 0;
4423    unsigned char *output = NULL;
4424    size_t output_buffer_size = 0;
4425    size_t output_length = 0;
4426    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
4427
4428    PSA_ASSERT(psa_crypto_init());
4429
4430    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DECRYPT);
4431    psa_set_key_algorithm(&attributes, alg);
4432    psa_set_key_type(&attributes, key_type);
4433
4434    /* Allocate input buffer and copy the iv and the plaintext */
4435    input_buffer_size = ((size_t) input_arg->len + (size_t) iv->len);
4436    if (input_buffer_size > 0) {
4437        ASSERT_ALLOC(input, input_buffer_size);
4438        memcpy(input, iv->x, iv->len);
4439        memcpy(input + iv->len, input_arg->x, input_arg->len);
4440    }
4441
4442    output_buffer_size = PSA_CIPHER_DECRYPT_OUTPUT_SIZE(key_type, alg, input_buffer_size);
4443    ASSERT_ALLOC(output, output_buffer_size);
4444
4445    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
4446                              &key));
4447
4448    PSA_ASSERT(psa_cipher_decrypt(key, alg, input, input_buffer_size, output,
4449                                  output_buffer_size, &output_length));
4450    TEST_LE_U(output_length,
4451              PSA_CIPHER_DECRYPT_OUTPUT_SIZE(key_type, alg, input_buffer_size));
4452    TEST_LE_U(output_length,
4453              PSA_CIPHER_DECRYPT_OUTPUT_MAX_SIZE(input_buffer_size));
4454
4455    ASSERT_COMPARE(expected_output->x, expected_output->len,
4456                   output, output_length);
4457exit:
4458    mbedtls_free(input);
4459    mbedtls_free(output);
4460    psa_destroy_key(key);
4461    PSA_DONE();
4462}
4463/* END_CASE */
4464
4465/* BEGIN_CASE */
4466void cipher_verify_output(int alg_arg,
4467                          int key_type_arg,
4468                          data_t *key_data,
4469                          data_t *input)
4470{
4471    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
4472    psa_key_type_t key_type = key_type_arg;
4473    psa_algorithm_t alg = alg_arg;
4474    unsigned char *output1 = NULL;
4475    size_t output1_size = 0;
4476    size_t output1_length = 0;
4477    unsigned char *output2 = NULL;
4478    size_t output2_size = 0;
4479    size_t output2_length = 0;
4480    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
4481
4482    PSA_ASSERT(psa_crypto_init());
4483
4484    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT);
4485    psa_set_key_algorithm(&attributes, alg);
4486    psa_set_key_type(&attributes, key_type);
4487
4488    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
4489                              &key));
4490    output1_size = PSA_CIPHER_ENCRYPT_OUTPUT_SIZE(key_type, alg, input->len);
4491    ASSERT_ALLOC(output1, output1_size);
4492
4493    PSA_ASSERT(psa_cipher_encrypt(key, alg, input->x, input->len,
4494                                  output1, output1_size,
4495                                  &output1_length));
4496    TEST_LE_U(output1_length,
4497              PSA_CIPHER_ENCRYPT_OUTPUT_SIZE(key_type, alg, input->len));
4498    TEST_LE_U(output1_length,
4499              PSA_CIPHER_ENCRYPT_OUTPUT_MAX_SIZE(input->len));
4500
4501    output2_size = output1_length;
4502    ASSERT_ALLOC(output2, output2_size);
4503
4504    PSA_ASSERT(psa_cipher_decrypt(key, alg, output1, output1_length,
4505                                  output2, output2_size,
4506                                  &output2_length));
4507    TEST_LE_U(output2_length,
4508              PSA_CIPHER_DECRYPT_OUTPUT_SIZE(key_type, alg, output1_length));
4509    TEST_LE_U(output2_length,
4510              PSA_CIPHER_DECRYPT_OUTPUT_MAX_SIZE(output1_length));
4511
4512    ASSERT_COMPARE(input->x, input->len, output2, output2_length);
4513
4514exit:
4515    mbedtls_free(output1);
4516    mbedtls_free(output2);
4517    psa_destroy_key(key);
4518    PSA_DONE();
4519}
4520/* END_CASE */
4521
4522/* BEGIN_CASE */
4523void cipher_verify_output_multipart(int alg_arg,
4524                                    int key_type_arg,
4525                                    data_t *key_data,
4526                                    data_t *input,
4527                                    int first_part_size_arg)
4528{
4529    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
4530    psa_key_type_t key_type = key_type_arg;
4531    psa_algorithm_t alg = alg_arg;
4532    size_t first_part_size = first_part_size_arg;
4533    unsigned char iv[16] = { 0 };
4534    size_t iv_size = 16;
4535    size_t iv_length = 0;
4536    unsigned char *output1 = NULL;
4537    size_t output1_buffer_size = 0;
4538    size_t output1_length = 0;
4539    unsigned char *output2 = NULL;
4540    size_t output2_buffer_size = 0;
4541    size_t output2_length = 0;
4542    size_t function_output_length;
4543    psa_cipher_operation_t operation1 = PSA_CIPHER_OPERATION_INIT;
4544    psa_cipher_operation_t operation2 = PSA_CIPHER_OPERATION_INIT;
4545    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
4546
4547    PSA_ASSERT(psa_crypto_init());
4548
4549    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT);
4550    psa_set_key_algorithm(&attributes, alg);
4551    psa_set_key_type(&attributes, key_type);
4552
4553    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
4554                              &key));
4555
4556    PSA_ASSERT(psa_cipher_encrypt_setup(&operation1, key, alg));
4557    PSA_ASSERT(psa_cipher_decrypt_setup(&operation2, key, alg));
4558
4559    if (alg != PSA_ALG_ECB_NO_PADDING) {
4560        PSA_ASSERT(psa_cipher_generate_iv(&operation1,
4561                                          iv, iv_size,
4562                                          &iv_length));
4563    }
4564
4565    output1_buffer_size = PSA_CIPHER_ENCRYPT_OUTPUT_SIZE(key_type, alg, input->len);
4566    TEST_LE_U(output1_buffer_size,
4567              PSA_CIPHER_ENCRYPT_OUTPUT_MAX_SIZE(input->len));
4568    ASSERT_ALLOC(output1, output1_buffer_size);
4569
4570    TEST_LE_U(first_part_size, input->len);
4571
4572    PSA_ASSERT(psa_cipher_update(&operation1, input->x, first_part_size,
4573                                 output1, output1_buffer_size,
4574                                 &function_output_length));
4575    TEST_LE_U(function_output_length,
4576              PSA_CIPHER_UPDATE_OUTPUT_SIZE(key_type, alg, first_part_size));
4577    TEST_LE_U(function_output_length,
4578              PSA_CIPHER_UPDATE_OUTPUT_MAX_SIZE(first_part_size));
4579    output1_length += function_output_length;
4580
4581    PSA_ASSERT(psa_cipher_update(&operation1,
4582                                 input->x + first_part_size,
4583                                 input->len - first_part_size,
4584                                 output1, output1_buffer_size,
4585                                 &function_output_length));
4586    TEST_LE_U(function_output_length,
4587              PSA_CIPHER_UPDATE_OUTPUT_SIZE(key_type,
4588                                            alg,
4589                                            input->len - first_part_size));
4590    TEST_LE_U(function_output_length,
4591              PSA_CIPHER_UPDATE_OUTPUT_MAX_SIZE(input->len - first_part_size));
4592    output1_length += function_output_length;
4593
4594    PSA_ASSERT(psa_cipher_finish(&operation1,
4595                                 output1 + output1_length,
4596                                 output1_buffer_size - output1_length,
4597                                 &function_output_length));
4598    TEST_LE_U(function_output_length,
4599              PSA_CIPHER_FINISH_OUTPUT_SIZE(key_type, alg));
4600    TEST_LE_U(function_output_length,
4601              PSA_CIPHER_FINISH_OUTPUT_MAX_SIZE);
4602    output1_length += function_output_length;
4603
4604    PSA_ASSERT(psa_cipher_abort(&operation1));
4605
4606    output2_buffer_size = output1_length;
4607    TEST_LE_U(output2_buffer_size,
4608              PSA_CIPHER_DECRYPT_OUTPUT_SIZE(key_type, alg, output1_length));
4609    TEST_LE_U(output2_buffer_size,
4610              PSA_CIPHER_DECRYPT_OUTPUT_MAX_SIZE(output1_length));
4611    ASSERT_ALLOC(output2, output2_buffer_size);
4612
4613    if (iv_length > 0) {
4614        PSA_ASSERT(psa_cipher_set_iv(&operation2,
4615                                     iv, iv_length));
4616    }
4617
4618    PSA_ASSERT(psa_cipher_update(&operation2, output1, first_part_size,
4619                                 output2, output2_buffer_size,
4620                                 &function_output_length));
4621    TEST_LE_U(function_output_length,
4622              PSA_CIPHER_UPDATE_OUTPUT_SIZE(key_type, alg, first_part_size));
4623    TEST_LE_U(function_output_length,
4624              PSA_CIPHER_UPDATE_OUTPUT_MAX_SIZE(first_part_size));
4625    output2_length += function_output_length;
4626
4627    PSA_ASSERT(psa_cipher_update(&operation2,
4628                                 output1 + first_part_size,
4629                                 output1_length - first_part_size,
4630                                 output2, output2_buffer_size,
4631                                 &function_output_length));
4632    TEST_LE_U(function_output_length,
4633              PSA_CIPHER_UPDATE_OUTPUT_SIZE(key_type,
4634                                            alg,
4635                                            output1_length - first_part_size));
4636    TEST_LE_U(function_output_length,
4637              PSA_CIPHER_UPDATE_OUTPUT_MAX_SIZE(output1_length - first_part_size));
4638    output2_length += function_output_length;
4639
4640    PSA_ASSERT(psa_cipher_finish(&operation2,
4641                                 output2 + output2_length,
4642                                 output2_buffer_size - output2_length,
4643                                 &function_output_length));
4644    TEST_LE_U(function_output_length,
4645              PSA_CIPHER_FINISH_OUTPUT_SIZE(key_type, alg));
4646    TEST_LE_U(function_output_length,
4647              PSA_CIPHER_FINISH_OUTPUT_MAX_SIZE);
4648    output2_length += function_output_length;
4649
4650    PSA_ASSERT(psa_cipher_abort(&operation2));
4651
4652    ASSERT_COMPARE(input->x, input->len, output2, output2_length);
4653
4654exit:
4655    psa_cipher_abort(&operation1);
4656    psa_cipher_abort(&operation2);
4657    mbedtls_free(output1);
4658    mbedtls_free(output2);
4659    psa_destroy_key(key);
4660    PSA_DONE();
4661}
4662/* END_CASE */
4663
4664/* BEGIN_CASE */
4665void aead_encrypt_decrypt(int key_type_arg, data_t *key_data,
4666                          int alg_arg,
4667                          data_t *nonce,
4668                          data_t *additional_data,
4669                          data_t *input_data,
4670                          int expected_result_arg)
4671{
4672    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
4673    psa_key_type_t key_type = key_type_arg;
4674    psa_algorithm_t alg = alg_arg;
4675    size_t key_bits;
4676    unsigned char *output_data = NULL;
4677    size_t output_size = 0;
4678    size_t output_length = 0;
4679    unsigned char *output_data2 = NULL;
4680    size_t output_length2 = 0;
4681    psa_status_t status = PSA_ERROR_GENERIC_ERROR;
4682    psa_status_t expected_result = expected_result_arg;
4683    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
4684
4685    PSA_ASSERT(psa_crypto_init());
4686
4687    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT);
4688    psa_set_key_algorithm(&attributes, alg);
4689    psa_set_key_type(&attributes, key_type);
4690
4691    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
4692                              &key));
4693    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
4694    key_bits = psa_get_key_bits(&attributes);
4695
4696    output_size = input_data->len + PSA_AEAD_TAG_LENGTH(key_type, key_bits,
4697                                                        alg);
4698    /* For all currently defined algorithms, PSA_AEAD_ENCRYPT_OUTPUT_SIZE
4699     * should be exact. */
4700    if (expected_result != PSA_ERROR_INVALID_ARGUMENT &&
4701        expected_result != PSA_ERROR_NOT_SUPPORTED) {
4702        TEST_EQUAL(output_size,
4703                   PSA_AEAD_ENCRYPT_OUTPUT_SIZE(key_type, alg, input_data->len));
4704        TEST_LE_U(output_size,
4705                  PSA_AEAD_ENCRYPT_OUTPUT_MAX_SIZE(input_data->len));
4706    }
4707    ASSERT_ALLOC(output_data, output_size);
4708
4709    status = psa_aead_encrypt(key, alg,
4710                              nonce->x, nonce->len,
4711                              additional_data->x,
4712                              additional_data->len,
4713                              input_data->x, input_data->len,
4714                              output_data, output_size,
4715                              &output_length);
4716
4717    /* If the operation is not supported, just skip and not fail in case the
4718     * encryption involves a common limitation of cryptography hardwares and
4719     * an alternative implementation. */
4720    if (status == PSA_ERROR_NOT_SUPPORTED) {
4721        MBEDTLS_TEST_PSA_SKIP_IF_ALT_AES_192(key_type, key_data->len * 8);
4722        MBEDTLS_TEST_PSA_SKIP_IF_ALT_GCM_NOT_12BYTES_NONCE(alg, nonce->len);
4723    }
4724
4725    TEST_EQUAL(status, expected_result);
4726
4727    if (PSA_SUCCESS == expected_result) {
4728        ASSERT_ALLOC(output_data2, output_length);
4729
4730        /* For all currently defined algorithms, PSA_AEAD_DECRYPT_OUTPUT_SIZE
4731         * should be exact. */
4732        TEST_EQUAL(input_data->len,
4733                   PSA_AEAD_DECRYPT_OUTPUT_SIZE(key_type, alg, output_length));
4734
4735        TEST_LE_U(input_data->len,
4736                  PSA_AEAD_DECRYPT_OUTPUT_MAX_SIZE(output_length));
4737
4738        TEST_EQUAL(psa_aead_decrypt(key, alg,
4739                                    nonce->x, nonce->len,
4740                                    additional_data->x,
4741                                    additional_data->len,
4742                                    output_data, output_length,
4743                                    output_data2, output_length,
4744                                    &output_length2),
4745                   expected_result);
4746
4747        ASSERT_COMPARE(input_data->x, input_data->len,
4748                       output_data2, output_length2);
4749    }
4750
4751exit:
4752    psa_destroy_key(key);
4753    mbedtls_free(output_data);
4754    mbedtls_free(output_data2);
4755    PSA_DONE();
4756}
4757/* END_CASE */
4758
4759/* BEGIN_CASE */
4760void aead_encrypt(int key_type_arg, data_t *key_data,
4761                  int alg_arg,
4762                  data_t *nonce,
4763                  data_t *additional_data,
4764                  data_t *input_data,
4765                  data_t *expected_result)
4766{
4767    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
4768    psa_key_type_t key_type = key_type_arg;
4769    psa_algorithm_t alg = alg_arg;
4770    size_t key_bits;
4771    unsigned char *output_data = NULL;
4772    size_t output_size = 0;
4773    size_t output_length = 0;
4774    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
4775    psa_status_t status = PSA_ERROR_GENERIC_ERROR;
4776
4777    PSA_ASSERT(psa_crypto_init());
4778
4779    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
4780    psa_set_key_algorithm(&attributes, alg);
4781    psa_set_key_type(&attributes, key_type);
4782
4783    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
4784                              &key));
4785    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
4786    key_bits = psa_get_key_bits(&attributes);
4787
4788    output_size = input_data->len + PSA_AEAD_TAG_LENGTH(key_type, key_bits,
4789                                                        alg);
4790    /* For all currently defined algorithms, PSA_AEAD_ENCRYPT_OUTPUT_SIZE
4791     * should be exact. */
4792    TEST_EQUAL(output_size,
4793               PSA_AEAD_ENCRYPT_OUTPUT_SIZE(key_type, alg, input_data->len));
4794    TEST_LE_U(output_size,
4795              PSA_AEAD_ENCRYPT_OUTPUT_MAX_SIZE(input_data->len));
4796    ASSERT_ALLOC(output_data, output_size);
4797
4798    status = psa_aead_encrypt(key, alg,
4799                              nonce->x, nonce->len,
4800                              additional_data->x, additional_data->len,
4801                              input_data->x, input_data->len,
4802                              output_data, output_size,
4803                              &output_length);
4804
4805    /* If the operation is not supported, just skip and not fail in case the
4806     * encryption involves a common limitation of cryptography hardwares and
4807     * an alternative implementation. */
4808    if (status == PSA_ERROR_NOT_SUPPORTED) {
4809        MBEDTLS_TEST_PSA_SKIP_IF_ALT_AES_192(key_type, key_data->len * 8);
4810        MBEDTLS_TEST_PSA_SKIP_IF_ALT_GCM_NOT_12BYTES_NONCE(alg, nonce->len);
4811    }
4812
4813    PSA_ASSERT(status);
4814    ASSERT_COMPARE(expected_result->x, expected_result->len,
4815                   output_data, output_length);
4816
4817exit:
4818    psa_destroy_key(key);
4819    mbedtls_free(output_data);
4820    PSA_DONE();
4821}
4822/* END_CASE */
4823
4824/* BEGIN_CASE */
4825void aead_decrypt(int key_type_arg, data_t *key_data,
4826                  int alg_arg,
4827                  data_t *nonce,
4828                  data_t *additional_data,
4829                  data_t *input_data,
4830                  data_t *expected_data,
4831                  int expected_result_arg)
4832{
4833    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
4834    psa_key_type_t key_type = key_type_arg;
4835    psa_algorithm_t alg = alg_arg;
4836    size_t key_bits;
4837    unsigned char *output_data = NULL;
4838    size_t output_size = 0;
4839    size_t output_length = 0;
4840    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
4841    psa_status_t expected_result = expected_result_arg;
4842    psa_status_t status = PSA_ERROR_GENERIC_ERROR;
4843
4844    PSA_ASSERT(psa_crypto_init());
4845
4846    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DECRYPT);
4847    psa_set_key_algorithm(&attributes, alg);
4848    psa_set_key_type(&attributes, key_type);
4849
4850    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
4851                              &key));
4852    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
4853    key_bits = psa_get_key_bits(&attributes);
4854
4855    output_size = input_data->len - PSA_AEAD_TAG_LENGTH(key_type, key_bits,
4856                                                        alg);
4857    if (expected_result != PSA_ERROR_INVALID_ARGUMENT &&
4858        expected_result != PSA_ERROR_NOT_SUPPORTED) {
4859        /* For all currently defined algorithms, PSA_AEAD_DECRYPT_OUTPUT_SIZE
4860         * should be exact. */
4861        TEST_EQUAL(output_size,
4862                   PSA_AEAD_DECRYPT_OUTPUT_SIZE(key_type, alg, input_data->len));
4863        TEST_LE_U(output_size,
4864                  PSA_AEAD_DECRYPT_OUTPUT_MAX_SIZE(input_data->len));
4865    }
4866    ASSERT_ALLOC(output_data, output_size);
4867
4868    status = psa_aead_decrypt(key, alg,
4869                              nonce->x, nonce->len,
4870                              additional_data->x,
4871                              additional_data->len,
4872                              input_data->x, input_data->len,
4873                              output_data, output_size,
4874                              &output_length);
4875
4876    /* If the operation is not supported, just skip and not fail in case the
4877     * decryption involves a common limitation of cryptography hardwares and
4878     * an alternative implementation. */
4879    if (status == PSA_ERROR_NOT_SUPPORTED) {
4880        MBEDTLS_TEST_PSA_SKIP_IF_ALT_AES_192(key_type, key_data->len * 8);
4881        MBEDTLS_TEST_PSA_SKIP_IF_ALT_GCM_NOT_12BYTES_NONCE(alg, nonce->len);
4882    }
4883
4884    TEST_EQUAL(status, expected_result);
4885
4886    if (expected_result == PSA_SUCCESS) {
4887        ASSERT_COMPARE(expected_data->x, expected_data->len,
4888                       output_data, output_length);
4889    }
4890
4891exit:
4892    psa_destroy_key(key);
4893    mbedtls_free(output_data);
4894    PSA_DONE();
4895}
4896/* END_CASE */
4897
4898/* BEGIN_CASE */
4899void aead_multipart_encrypt(int key_type_arg, data_t *key_data,
4900                            int alg_arg,
4901                            data_t *nonce,
4902                            data_t *additional_data,
4903                            data_t *input_data,
4904                            int do_set_lengths,
4905                            data_t *expected_output)
4906{
4907    size_t ad_part_len = 0;
4908    size_t data_part_len = 0;
4909    set_lengths_method_t set_lengths_method = DO_NOT_SET_LENGTHS;
4910
4911    for (ad_part_len = 1; ad_part_len <= additional_data->len; ad_part_len++) {
4912        mbedtls_test_set_step(ad_part_len);
4913
4914        if (do_set_lengths) {
4915            if (ad_part_len & 0x01) {
4916                set_lengths_method = SET_LENGTHS_AFTER_NONCE;
4917            } else {
4918                set_lengths_method = SET_LENGTHS_BEFORE_NONCE;
4919            }
4920        }
4921
4922        /* Split ad into length(ad_part_len) parts. */
4923        if (!aead_multipart_internal_func(key_type_arg, key_data,
4924                                          alg_arg, nonce,
4925                                          additional_data,
4926                                          ad_part_len,
4927                                          input_data, -1,
4928                                          set_lengths_method,
4929                                          expected_output,
4930                                          1, 0)) {
4931            break;
4932        }
4933
4934        /* length(0) part, length(ad_part_len) part, length(0) part... */
4935        mbedtls_test_set_step(1000 + ad_part_len);
4936
4937        if (!aead_multipart_internal_func(key_type_arg, key_data,
4938                                          alg_arg, nonce,
4939                                          additional_data,
4940                                          ad_part_len,
4941                                          input_data, -1,
4942                                          set_lengths_method,
4943                                          expected_output,
4944                                          1, 1)) {
4945            break;
4946        }
4947    }
4948
4949    for (data_part_len = 1; data_part_len <= input_data->len; data_part_len++) {
4950        /* Split data into length(data_part_len) parts. */
4951        mbedtls_test_set_step(2000 + data_part_len);
4952
4953        if (do_set_lengths) {
4954            if (data_part_len & 0x01) {
4955                set_lengths_method = SET_LENGTHS_AFTER_NONCE;
4956            } else {
4957                set_lengths_method = SET_LENGTHS_BEFORE_NONCE;
4958            }
4959        }
4960
4961        if (!aead_multipart_internal_func(key_type_arg, key_data,
4962                                          alg_arg, nonce,
4963                                          additional_data, -1,
4964                                          input_data, data_part_len,
4965                                          set_lengths_method,
4966                                          expected_output,
4967                                          1, 0)) {
4968            break;
4969        }
4970
4971        /* length(0) part, length(data_part_len) part, length(0) part... */
4972        mbedtls_test_set_step(3000 + data_part_len);
4973
4974        if (!aead_multipart_internal_func(key_type_arg, key_data,
4975                                          alg_arg, nonce,
4976                                          additional_data, -1,
4977                                          input_data, data_part_len,
4978                                          set_lengths_method,
4979                                          expected_output,
4980                                          1, 1)) {
4981            break;
4982        }
4983    }
4984
4985    /* Goto is required to silence warnings about unused labels, as we
4986     * don't actually do any test assertions in this function. */
4987    goto exit;
4988}
4989/* END_CASE */
4990
4991/* BEGIN_CASE */
4992void aead_multipart_decrypt(int key_type_arg, data_t *key_data,
4993                            int alg_arg,
4994                            data_t *nonce,
4995                            data_t *additional_data,
4996                            data_t *input_data,
4997                            int do_set_lengths,
4998                            data_t *expected_output)
4999{
5000    size_t ad_part_len = 0;
5001    size_t data_part_len = 0;
5002    set_lengths_method_t set_lengths_method = DO_NOT_SET_LENGTHS;
5003
5004    for (ad_part_len = 1; ad_part_len <= additional_data->len; ad_part_len++) {
5005        /* Split ad into length(ad_part_len) parts. */
5006        mbedtls_test_set_step(ad_part_len);
5007
5008        if (do_set_lengths) {
5009            if (ad_part_len & 0x01) {
5010                set_lengths_method = SET_LENGTHS_AFTER_NONCE;
5011            } else {
5012                set_lengths_method = SET_LENGTHS_BEFORE_NONCE;
5013            }
5014        }
5015
5016        if (!aead_multipart_internal_func(key_type_arg, key_data,
5017                                          alg_arg, nonce,
5018                                          additional_data,
5019                                          ad_part_len,
5020                                          input_data, -1,
5021                                          set_lengths_method,
5022                                          expected_output,
5023                                          0, 0)) {
5024            break;
5025        }
5026
5027        /* length(0) part, length(ad_part_len) part, length(0) part... */
5028        mbedtls_test_set_step(1000 + ad_part_len);
5029
5030        if (!aead_multipart_internal_func(key_type_arg, key_data,
5031                                          alg_arg, nonce,
5032                                          additional_data,
5033                                          ad_part_len,
5034                                          input_data, -1,
5035                                          set_lengths_method,
5036                                          expected_output,
5037                                          0, 1)) {
5038            break;
5039        }
5040    }
5041
5042    for (data_part_len = 1; data_part_len <= input_data->len; data_part_len++) {
5043        /* Split data into length(data_part_len) parts. */
5044        mbedtls_test_set_step(2000 + data_part_len);
5045
5046        if (do_set_lengths) {
5047            if (data_part_len & 0x01) {
5048                set_lengths_method = SET_LENGTHS_AFTER_NONCE;
5049            } else {
5050                set_lengths_method = SET_LENGTHS_BEFORE_NONCE;
5051            }
5052        }
5053
5054        if (!aead_multipart_internal_func(key_type_arg, key_data,
5055                                          alg_arg, nonce,
5056                                          additional_data, -1,
5057                                          input_data, data_part_len,
5058                                          set_lengths_method,
5059                                          expected_output,
5060                                          0, 0)) {
5061            break;
5062        }
5063
5064        /* length(0) part, length(data_part_len) part, length(0) part... */
5065        mbedtls_test_set_step(3000 + data_part_len);
5066
5067        if (!aead_multipart_internal_func(key_type_arg, key_data,
5068                                          alg_arg, nonce,
5069                                          additional_data, -1,
5070                                          input_data, data_part_len,
5071                                          set_lengths_method,
5072                                          expected_output,
5073                                          0, 1)) {
5074            break;
5075        }
5076    }
5077
5078    /* Goto is required to silence warnings about unused labels, as we
5079     * don't actually do any test assertions in this function. */
5080    goto exit;
5081}
5082/* END_CASE */
5083
5084/* BEGIN_CASE */
5085void aead_multipart_generate_nonce(int key_type_arg, data_t *key_data,
5086                                   int alg_arg,
5087                                   int nonce_length,
5088                                   int expected_nonce_length_arg,
5089                                   data_t *additional_data,
5090                                   data_t *input_data,
5091                                   int expected_status_arg)
5092{
5093
5094    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
5095    psa_key_type_t key_type = key_type_arg;
5096    psa_algorithm_t alg = alg_arg;
5097    psa_aead_operation_t operation = PSA_AEAD_OPERATION_INIT;
5098    uint8_t nonce_buffer[PSA_AEAD_NONCE_MAX_SIZE];
5099    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
5100    psa_status_t status = PSA_ERROR_GENERIC_ERROR;
5101    psa_status_t expected_status = expected_status_arg;
5102    size_t actual_nonce_length = 0;
5103    size_t expected_nonce_length = expected_nonce_length_arg;
5104    unsigned char *output = NULL;
5105    unsigned char *ciphertext = NULL;
5106    size_t output_size = 0;
5107    size_t ciphertext_size = 0;
5108    size_t ciphertext_length = 0;
5109    size_t tag_length = 0;
5110    uint8_t tag_buffer[PSA_AEAD_TAG_MAX_SIZE];
5111
5112    PSA_ASSERT(psa_crypto_init());
5113
5114    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
5115    psa_set_key_algorithm(&attributes, alg);
5116    psa_set_key_type(&attributes, key_type);
5117
5118    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
5119                              &key));
5120
5121    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
5122
5123    output_size = PSA_AEAD_UPDATE_OUTPUT_SIZE(key_type, alg, input_data->len);
5124
5125    ASSERT_ALLOC(output, output_size);
5126
5127    ciphertext_size = PSA_AEAD_FINISH_OUTPUT_SIZE(key_type, alg);
5128
5129    TEST_LE_U(ciphertext_size, PSA_AEAD_FINISH_OUTPUT_MAX_SIZE);
5130
5131    ASSERT_ALLOC(ciphertext, ciphertext_size);
5132
5133    status = psa_aead_encrypt_setup(&operation, key, alg);
5134
5135    /* If the operation is not supported, just skip and not fail in case the
5136     * encryption involves a common limitation of cryptography hardwares and
5137     * an alternative implementation. */
5138    if (status == PSA_ERROR_NOT_SUPPORTED) {
5139        MBEDTLS_TEST_PSA_SKIP_IF_ALT_AES_192(key_type, key_data->len * 8);
5140        MBEDTLS_TEST_PSA_SKIP_IF_ALT_GCM_NOT_12BYTES_NONCE(alg, nonce_length);
5141    }
5142
5143    PSA_ASSERT(status);
5144
5145    status = psa_aead_generate_nonce(&operation, nonce_buffer,
5146                                     nonce_length,
5147                                     &actual_nonce_length);
5148
5149    TEST_EQUAL(status, expected_status);
5150
5151    TEST_EQUAL(actual_nonce_length, expected_nonce_length);
5152
5153    if (expected_status == PSA_SUCCESS) {
5154        TEST_EQUAL(actual_nonce_length, PSA_AEAD_NONCE_LENGTH(key_type,
5155                                                              alg));
5156    }
5157
5158    TEST_LE_U(actual_nonce_length, PSA_AEAD_NONCE_MAX_SIZE);
5159
5160    if (expected_status == PSA_SUCCESS) {
5161        /* Ensure we can still complete operation. */
5162        PSA_ASSERT(psa_aead_set_lengths(&operation, additional_data->len,
5163                                        input_data->len));
5164
5165        PSA_ASSERT(psa_aead_update_ad(&operation, additional_data->x,
5166                                      additional_data->len));
5167
5168        PSA_ASSERT(psa_aead_update(&operation, input_data->x, input_data->len,
5169                                   output, output_size,
5170                                   &ciphertext_length));
5171
5172        PSA_ASSERT(psa_aead_finish(&operation, ciphertext, ciphertext_size,
5173                                   &ciphertext_length, tag_buffer,
5174                                   PSA_AEAD_TAG_MAX_SIZE, &tag_length));
5175    }
5176
5177exit:
5178    psa_destroy_key(key);
5179    mbedtls_free(output);
5180    mbedtls_free(ciphertext);
5181    psa_aead_abort(&operation);
5182    PSA_DONE();
5183}
5184/* END_CASE */
5185
5186/* BEGIN_CASE */
5187void aead_multipart_set_nonce(int key_type_arg, data_t *key_data,
5188                              int alg_arg,
5189                              int nonce_length_arg,
5190                              int set_lengths_method_arg,
5191                              data_t *additional_data,
5192                              data_t *input_data,
5193                              int expected_status_arg)
5194{
5195
5196    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
5197    psa_key_type_t key_type = key_type_arg;
5198    psa_algorithm_t alg = alg_arg;
5199    psa_aead_operation_t operation = PSA_AEAD_OPERATION_INIT;
5200    uint8_t *nonce_buffer = NULL;
5201    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
5202    psa_status_t status = PSA_ERROR_GENERIC_ERROR;
5203    psa_status_t expected_status = expected_status_arg;
5204    unsigned char *output = NULL;
5205    unsigned char *ciphertext = NULL;
5206    size_t nonce_length;
5207    size_t output_size = 0;
5208    size_t ciphertext_size = 0;
5209    size_t ciphertext_length = 0;
5210    size_t tag_length = 0;
5211    uint8_t tag_buffer[PSA_AEAD_TAG_MAX_SIZE];
5212    size_t index = 0;
5213    set_lengths_method_t set_lengths_method = set_lengths_method_arg;
5214
5215    PSA_ASSERT(psa_crypto_init());
5216
5217    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
5218    psa_set_key_algorithm(&attributes, alg);
5219    psa_set_key_type(&attributes, key_type);
5220
5221    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
5222                              &key));
5223
5224    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
5225
5226    output_size = PSA_AEAD_UPDATE_OUTPUT_SIZE(key_type, alg, input_data->len);
5227
5228    ASSERT_ALLOC(output, output_size);
5229
5230    ciphertext_size = PSA_AEAD_FINISH_OUTPUT_SIZE(key_type, alg);
5231
5232    TEST_LE_U(ciphertext_size, PSA_AEAD_FINISH_OUTPUT_MAX_SIZE);
5233
5234    ASSERT_ALLOC(ciphertext, ciphertext_size);
5235
5236    status = psa_aead_encrypt_setup(&operation, key, alg);
5237
5238    /* If the operation is not supported, just skip and not fail in case the
5239     * encryption involves a common limitation of cryptography hardwares and
5240     * an alternative implementation. */
5241    if (status == PSA_ERROR_NOT_SUPPORTED) {
5242        MBEDTLS_TEST_PSA_SKIP_IF_ALT_AES_192(key_type, key_data->len * 8);
5243        MBEDTLS_TEST_PSA_SKIP_IF_ALT_GCM_NOT_12BYTES_NONCE(alg, nonce_length_arg);
5244    }
5245
5246    PSA_ASSERT(status);
5247
5248    /* -1 == zero length and valid buffer, 0 = zero length and NULL buffer. */
5249    if (nonce_length_arg == -1) {
5250        /* Arbitrary size buffer, to test zero length valid buffer. */
5251        ASSERT_ALLOC(nonce_buffer, 4);
5252        nonce_length = 0;
5253    } else {
5254        /* If length is zero, then this will return NULL. */
5255        nonce_length = (size_t) nonce_length_arg;
5256        ASSERT_ALLOC(nonce_buffer, nonce_length);
5257
5258        if (nonce_buffer) {
5259            for (index = 0; index < nonce_length - 1; ++index) {
5260                nonce_buffer[index] = 'a' + index;
5261            }
5262        }
5263    }
5264
5265    if (set_lengths_method == SET_LENGTHS_BEFORE_NONCE) {
5266        PSA_ASSERT(psa_aead_set_lengths(&operation, additional_data->len,
5267                                        input_data->len));
5268    }
5269
5270    status = psa_aead_set_nonce(&operation, nonce_buffer, nonce_length);
5271
5272    TEST_EQUAL(status, expected_status);
5273
5274    if (expected_status == PSA_SUCCESS) {
5275        if (set_lengths_method == SET_LENGTHS_AFTER_NONCE) {
5276            PSA_ASSERT(psa_aead_set_lengths(&operation, additional_data->len,
5277                                            input_data->len));
5278        }
5279        if (operation.alg == PSA_ALG_CCM && set_lengths_method == DO_NOT_SET_LENGTHS) {
5280            expected_status = PSA_ERROR_BAD_STATE;
5281        }
5282
5283        /* Ensure we can still complete operation, unless it's CCM and we didn't set lengths. */
5284        TEST_EQUAL(psa_aead_update_ad(&operation, additional_data->x,
5285                                      additional_data->len),
5286                   expected_status);
5287
5288        TEST_EQUAL(psa_aead_update(&operation, input_data->x, input_data->len,
5289                                   output, output_size,
5290                                   &ciphertext_length),
5291                   expected_status);
5292
5293        TEST_EQUAL(psa_aead_finish(&operation, ciphertext, ciphertext_size,
5294                                   &ciphertext_length, tag_buffer,
5295                                   PSA_AEAD_TAG_MAX_SIZE, &tag_length),
5296                   expected_status);
5297    }
5298
5299exit:
5300    psa_destroy_key(key);
5301    mbedtls_free(output);
5302    mbedtls_free(ciphertext);
5303    mbedtls_free(nonce_buffer);
5304    psa_aead_abort(&operation);
5305    PSA_DONE();
5306}
5307/* END_CASE */
5308
5309/* BEGIN_CASE */
5310void aead_multipart_update_buffer_test(int key_type_arg, data_t *key_data,
5311                                       int alg_arg,
5312                                       int output_size_arg,
5313                                       data_t *nonce,
5314                                       data_t *additional_data,
5315                                       data_t *input_data,
5316                                       int expected_status_arg)
5317{
5318
5319    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
5320    psa_key_type_t key_type = key_type_arg;
5321    psa_algorithm_t alg = alg_arg;
5322    psa_aead_operation_t operation = PSA_AEAD_OPERATION_INIT;
5323    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
5324    psa_status_t status = PSA_ERROR_GENERIC_ERROR;
5325    psa_status_t expected_status = expected_status_arg;
5326    unsigned char *output = NULL;
5327    unsigned char *ciphertext = NULL;
5328    size_t output_size = output_size_arg;
5329    size_t ciphertext_size = 0;
5330    size_t ciphertext_length = 0;
5331    size_t tag_length = 0;
5332    uint8_t tag_buffer[PSA_AEAD_TAG_MAX_SIZE];
5333
5334    PSA_ASSERT(psa_crypto_init());
5335
5336    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
5337    psa_set_key_algorithm(&attributes, alg);
5338    psa_set_key_type(&attributes, key_type);
5339
5340    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
5341                              &key));
5342
5343    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
5344
5345    ASSERT_ALLOC(output, output_size);
5346
5347    ciphertext_size = PSA_AEAD_FINISH_OUTPUT_SIZE(key_type, alg);
5348
5349    ASSERT_ALLOC(ciphertext, ciphertext_size);
5350
5351    status = psa_aead_encrypt_setup(&operation, key, alg);
5352
5353    /* If the operation is not supported, just skip and not fail in case the
5354     * encryption involves a common limitation of cryptography hardwares and
5355     * an alternative implementation. */
5356    if (status == PSA_ERROR_NOT_SUPPORTED) {
5357        MBEDTLS_TEST_PSA_SKIP_IF_ALT_AES_192(key_type, key_data->len * 8);
5358        MBEDTLS_TEST_PSA_SKIP_IF_ALT_GCM_NOT_12BYTES_NONCE(alg, nonce->len);
5359    }
5360
5361    PSA_ASSERT(status);
5362
5363    PSA_ASSERT(psa_aead_set_lengths(&operation, additional_data->len,
5364                                    input_data->len));
5365
5366    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
5367
5368    PSA_ASSERT(psa_aead_update_ad(&operation, additional_data->x,
5369                                  additional_data->len));
5370
5371    status = psa_aead_update(&operation, input_data->x, input_data->len,
5372                             output, output_size, &ciphertext_length);
5373
5374    TEST_EQUAL(status, expected_status);
5375
5376    if (expected_status == PSA_SUCCESS) {
5377        /* Ensure we can still complete operation. */
5378        PSA_ASSERT(psa_aead_finish(&operation, ciphertext, ciphertext_size,
5379                                   &ciphertext_length, tag_buffer,
5380                                   PSA_AEAD_TAG_MAX_SIZE, &tag_length));
5381    }
5382
5383exit:
5384    psa_destroy_key(key);
5385    mbedtls_free(output);
5386    mbedtls_free(ciphertext);
5387    psa_aead_abort(&operation);
5388    PSA_DONE();
5389}
5390/* END_CASE */
5391
5392/* BEGIN_CASE */
5393void aead_multipart_finish_buffer_test(int key_type_arg, data_t *key_data,
5394                                       int alg_arg,
5395                                       int finish_ciphertext_size_arg,
5396                                       int tag_size_arg,
5397                                       data_t *nonce,
5398                                       data_t *additional_data,
5399                                       data_t *input_data,
5400                                       int expected_status_arg)
5401{
5402
5403    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
5404    psa_key_type_t key_type = key_type_arg;
5405    psa_algorithm_t alg = alg_arg;
5406    psa_aead_operation_t operation = PSA_AEAD_OPERATION_INIT;
5407    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
5408    psa_status_t status = PSA_ERROR_GENERIC_ERROR;
5409    psa_status_t expected_status = expected_status_arg;
5410    unsigned char *ciphertext = NULL;
5411    unsigned char *finish_ciphertext = NULL;
5412    unsigned char *tag_buffer = NULL;
5413    size_t ciphertext_size = 0;
5414    size_t ciphertext_length = 0;
5415    size_t finish_ciphertext_size = (size_t) finish_ciphertext_size_arg;
5416    size_t tag_size = (size_t) tag_size_arg;
5417    size_t tag_length = 0;
5418
5419    PSA_ASSERT(psa_crypto_init());
5420
5421    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
5422    psa_set_key_algorithm(&attributes, alg);
5423    psa_set_key_type(&attributes, key_type);
5424
5425    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
5426                              &key));
5427
5428    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
5429
5430    ciphertext_size = PSA_AEAD_UPDATE_OUTPUT_SIZE(key_type, alg, input_data->len);
5431
5432    ASSERT_ALLOC(ciphertext, ciphertext_size);
5433
5434    ASSERT_ALLOC(finish_ciphertext, finish_ciphertext_size);
5435
5436    ASSERT_ALLOC(tag_buffer, tag_size);
5437
5438    status = psa_aead_encrypt_setup(&operation, key, alg);
5439
5440    /* If the operation is not supported, just skip and not fail in case the
5441     * encryption involves a common limitation of cryptography hardwares and
5442     * an alternative implementation. */
5443    if (status == PSA_ERROR_NOT_SUPPORTED) {
5444        MBEDTLS_TEST_PSA_SKIP_IF_ALT_AES_192(key_type, key_data->len * 8);
5445        MBEDTLS_TEST_PSA_SKIP_IF_ALT_GCM_NOT_12BYTES_NONCE(alg, nonce->len);
5446    }
5447
5448    PSA_ASSERT(status);
5449
5450    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
5451
5452    PSA_ASSERT(psa_aead_set_lengths(&operation, additional_data->len,
5453                                    input_data->len));
5454
5455    PSA_ASSERT(psa_aead_update_ad(&operation, additional_data->x,
5456                                  additional_data->len));
5457
5458    PSA_ASSERT(psa_aead_update(&operation, input_data->x, input_data->len,
5459                               ciphertext, ciphertext_size, &ciphertext_length));
5460
5461    /* Ensure we can still complete operation. */
5462    status = psa_aead_finish(&operation, finish_ciphertext,
5463                             finish_ciphertext_size,
5464                             &ciphertext_length, tag_buffer,
5465                             tag_size, &tag_length);
5466
5467    TEST_EQUAL(status, expected_status);
5468
5469exit:
5470    psa_destroy_key(key);
5471    mbedtls_free(ciphertext);
5472    mbedtls_free(finish_ciphertext);
5473    mbedtls_free(tag_buffer);
5474    psa_aead_abort(&operation);
5475    PSA_DONE();
5476}
5477/* END_CASE */
5478
5479/* BEGIN_CASE */
5480void aead_multipart_verify(int key_type_arg, data_t *key_data,
5481                           int alg_arg,
5482                           data_t *nonce,
5483                           data_t *additional_data,
5484                           data_t *input_data,
5485                           data_t *tag,
5486                           int tag_usage_arg,
5487                           int expected_setup_status_arg,
5488                           int expected_status_arg)
5489{
5490    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
5491    psa_key_type_t key_type = key_type_arg;
5492    psa_algorithm_t alg = alg_arg;
5493    psa_aead_operation_t operation = PSA_AEAD_OPERATION_INIT;
5494    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
5495    psa_status_t status = PSA_ERROR_GENERIC_ERROR;
5496    psa_status_t expected_status = expected_status_arg;
5497    psa_status_t expected_setup_status = expected_setup_status_arg;
5498    unsigned char *plaintext = NULL;
5499    unsigned char *finish_plaintext = NULL;
5500    size_t plaintext_size = 0;
5501    size_t plaintext_length = 0;
5502    size_t verify_plaintext_size = 0;
5503    tag_usage_method_t tag_usage = tag_usage_arg;
5504    unsigned char *tag_buffer = NULL;
5505    size_t tag_size = 0;
5506
5507    PSA_ASSERT(psa_crypto_init());
5508
5509    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DECRYPT);
5510    psa_set_key_algorithm(&attributes, alg);
5511    psa_set_key_type(&attributes, key_type);
5512
5513    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
5514                              &key));
5515
5516    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
5517
5518    plaintext_size = PSA_AEAD_UPDATE_OUTPUT_SIZE(key_type, alg,
5519                                                 input_data->len);
5520
5521    ASSERT_ALLOC(plaintext, plaintext_size);
5522
5523    verify_plaintext_size = PSA_AEAD_VERIFY_OUTPUT_SIZE(key_type, alg);
5524
5525    ASSERT_ALLOC(finish_plaintext, verify_plaintext_size);
5526
5527    status = psa_aead_decrypt_setup(&operation, key, alg);
5528
5529    /* If the operation is not supported, just skip and not fail in case the
5530     * encryption involves a common limitation of cryptography hardwares and
5531     * an alternative implementation. */
5532    if (status == PSA_ERROR_NOT_SUPPORTED) {
5533        MBEDTLS_TEST_PSA_SKIP_IF_ALT_AES_192(key_type, key_data->len * 8);
5534        MBEDTLS_TEST_PSA_SKIP_IF_ALT_GCM_NOT_12BYTES_NONCE(alg, nonce->len);
5535    }
5536    TEST_EQUAL(status, expected_setup_status);
5537
5538    if (status != PSA_SUCCESS) {
5539        goto exit;
5540    }
5541
5542    PSA_ASSERT(status);
5543
5544    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
5545
5546    status = psa_aead_set_lengths(&operation, additional_data->len,
5547                                  input_data->len);
5548    PSA_ASSERT(status);
5549
5550    PSA_ASSERT(psa_aead_update_ad(&operation, additional_data->x,
5551                                  additional_data->len));
5552
5553    PSA_ASSERT(psa_aead_update(&operation, input_data->x,
5554                               input_data->len,
5555                               plaintext, plaintext_size,
5556                               &plaintext_length));
5557
5558    if (tag_usage == USE_GIVEN_TAG) {
5559        tag_buffer = tag->x;
5560        tag_size = tag->len;
5561    }
5562
5563    status = psa_aead_verify(&operation, finish_plaintext,
5564                             verify_plaintext_size,
5565                             &plaintext_length,
5566                             tag_buffer, tag_size);
5567
5568    TEST_EQUAL(status, expected_status);
5569
5570exit:
5571    psa_destroy_key(key);
5572    mbedtls_free(plaintext);
5573    mbedtls_free(finish_plaintext);
5574    psa_aead_abort(&operation);
5575    PSA_DONE();
5576}
5577/* END_CASE */
5578
5579/* BEGIN_CASE */
5580void aead_multipart_setup(int key_type_arg, data_t *key_data,
5581                          int alg_arg, int expected_status_arg)
5582{
5583    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
5584    psa_key_type_t key_type = key_type_arg;
5585    psa_algorithm_t alg = alg_arg;
5586    psa_aead_operation_t operation = PSA_AEAD_OPERATION_INIT;
5587    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
5588    psa_status_t status = PSA_ERROR_GENERIC_ERROR;
5589    psa_status_t expected_status = expected_status_arg;
5590
5591    PSA_ASSERT(psa_crypto_init());
5592
5593    psa_set_key_usage_flags(&attributes,
5594                            PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT);
5595    psa_set_key_algorithm(&attributes, alg);
5596    psa_set_key_type(&attributes, key_type);
5597
5598    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
5599                              &key));
5600
5601    status = psa_aead_encrypt_setup(&operation, key, alg);
5602
5603    TEST_EQUAL(status, expected_status);
5604
5605    psa_aead_abort(&operation);
5606
5607    status = psa_aead_decrypt_setup(&operation, key, alg);
5608
5609    TEST_EQUAL(status, expected_status);
5610
5611exit:
5612    psa_destroy_key(key);
5613    psa_aead_abort(&operation);
5614    PSA_DONE();
5615}
5616/* END_CASE */
5617
5618/* BEGIN_CASE */
5619void aead_multipart_state_test(int key_type_arg, data_t *key_data,
5620                               int alg_arg,
5621                               data_t *nonce,
5622                               data_t *additional_data,
5623                               data_t *input_data)
5624{
5625    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
5626    psa_key_type_t key_type = key_type_arg;
5627    psa_algorithm_t alg = alg_arg;
5628    psa_aead_operation_t operation = PSA_AEAD_OPERATION_INIT;
5629    unsigned char *output_data = NULL;
5630    unsigned char *final_data = NULL;
5631    size_t output_size = 0;
5632    size_t finish_output_size = 0;
5633    size_t output_length = 0;
5634    size_t key_bits = 0;
5635    size_t tag_length = 0;
5636    size_t tag_size = 0;
5637    size_t nonce_length = 0;
5638    uint8_t nonce_buffer[PSA_AEAD_NONCE_MAX_SIZE];
5639    uint8_t tag_buffer[PSA_AEAD_TAG_MAX_SIZE];
5640    size_t output_part_length = 0;
5641    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
5642
5643    PSA_ASSERT(psa_crypto_init());
5644
5645    psa_set_key_usage_flags(&attributes,
5646                            PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT);
5647    psa_set_key_algorithm(&attributes, alg);
5648    psa_set_key_type(&attributes, key_type);
5649
5650    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
5651                              &key));
5652
5653    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
5654    key_bits = psa_get_key_bits(&attributes);
5655
5656    tag_length = PSA_AEAD_TAG_LENGTH(key_type, key_bits, alg);
5657
5658    TEST_LE_U(tag_length, PSA_AEAD_TAG_MAX_SIZE);
5659
5660    output_size = PSA_AEAD_UPDATE_OUTPUT_SIZE(key_type, alg, input_data->len);
5661
5662    ASSERT_ALLOC(output_data, output_size);
5663
5664    finish_output_size = PSA_AEAD_FINISH_OUTPUT_SIZE(key_type, alg);
5665
5666    TEST_LE_U(finish_output_size, PSA_AEAD_FINISH_OUTPUT_MAX_SIZE);
5667
5668    ASSERT_ALLOC(final_data, finish_output_size);
5669
5670    /* Test all operations error without calling setup first. */
5671
5672    TEST_EQUAL(psa_aead_set_nonce(&operation, nonce->x, nonce->len),
5673               PSA_ERROR_BAD_STATE);
5674
5675    psa_aead_abort(&operation);
5676
5677    TEST_EQUAL(psa_aead_generate_nonce(&operation, nonce_buffer,
5678                                       PSA_AEAD_NONCE_MAX_SIZE,
5679                                       &nonce_length),
5680               PSA_ERROR_BAD_STATE);
5681
5682    psa_aead_abort(&operation);
5683
5684    /* ------------------------------------------------------- */
5685
5686    TEST_EQUAL(psa_aead_set_lengths(&operation, additional_data->len,
5687                                    input_data->len),
5688               PSA_ERROR_BAD_STATE);
5689
5690    psa_aead_abort(&operation);
5691
5692    /* ------------------------------------------------------- */
5693
5694    TEST_EQUAL(psa_aead_update_ad(&operation, additional_data->x,
5695                                  additional_data->len),
5696               PSA_ERROR_BAD_STATE);
5697
5698    psa_aead_abort(&operation);
5699
5700    /* ------------------------------------------------------- */
5701
5702    TEST_EQUAL(psa_aead_update(&operation, input_data->x,
5703                               input_data->len, output_data,
5704                               output_size, &output_length),
5705               PSA_ERROR_BAD_STATE);
5706
5707    psa_aead_abort(&operation);
5708
5709    /* ------------------------------------------------------- */
5710
5711    TEST_EQUAL(psa_aead_finish(&operation, final_data,
5712                               finish_output_size,
5713                               &output_part_length,
5714                               tag_buffer, tag_length,
5715                               &tag_size),
5716               PSA_ERROR_BAD_STATE);
5717
5718    psa_aead_abort(&operation);
5719
5720    /* ------------------------------------------------------- */
5721
5722    TEST_EQUAL(psa_aead_verify(&operation, final_data,
5723                               finish_output_size,
5724                               &output_part_length,
5725                               tag_buffer,
5726                               tag_length),
5727               PSA_ERROR_BAD_STATE);
5728
5729    psa_aead_abort(&operation);
5730
5731    /* Test for double setups. */
5732
5733    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
5734
5735    TEST_EQUAL(psa_aead_encrypt_setup(&operation, key, alg),
5736               PSA_ERROR_BAD_STATE);
5737
5738    psa_aead_abort(&operation);
5739
5740    /* ------------------------------------------------------- */
5741
5742    PSA_ASSERT(psa_aead_decrypt_setup(&operation, key, alg));
5743
5744    TEST_EQUAL(psa_aead_decrypt_setup(&operation, key, alg),
5745               PSA_ERROR_BAD_STATE);
5746
5747    psa_aead_abort(&operation);
5748
5749    /* ------------------------------------------------------- */
5750
5751    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
5752
5753    TEST_EQUAL(psa_aead_decrypt_setup(&operation, key, alg),
5754               PSA_ERROR_BAD_STATE);
5755
5756    psa_aead_abort(&operation);
5757
5758    /* ------------------------------------------------------- */
5759
5760    PSA_ASSERT(psa_aead_decrypt_setup(&operation, key, alg));
5761
5762    TEST_EQUAL(psa_aead_encrypt_setup(&operation, key, alg),
5763               PSA_ERROR_BAD_STATE);
5764
5765    psa_aead_abort(&operation);
5766
5767    /* Test for not setting a nonce. */
5768
5769    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
5770
5771    TEST_EQUAL(psa_aead_update_ad(&operation, additional_data->x,
5772                                  additional_data->len),
5773               PSA_ERROR_BAD_STATE);
5774
5775    psa_aead_abort(&operation);
5776
5777    /* ------------------------------------------------------- */
5778
5779    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
5780
5781    TEST_EQUAL(psa_aead_update(&operation, input_data->x,
5782                               input_data->len, output_data,
5783                               output_size, &output_length),
5784               PSA_ERROR_BAD_STATE);
5785
5786    psa_aead_abort(&operation);
5787
5788    /* ------------------------------------------------------- */
5789
5790    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
5791
5792    TEST_EQUAL(psa_aead_finish(&operation, final_data,
5793                               finish_output_size,
5794                               &output_part_length,
5795                               tag_buffer, tag_length,
5796                               &tag_size),
5797               PSA_ERROR_BAD_STATE);
5798
5799    psa_aead_abort(&operation);
5800
5801    /* ------------------------------------------------------- */
5802
5803    PSA_ASSERT(psa_aead_decrypt_setup(&operation, key, alg));
5804
5805    TEST_EQUAL(psa_aead_verify(&operation, final_data,
5806                               finish_output_size,
5807                               &output_part_length,
5808                               tag_buffer,
5809                               tag_length),
5810               PSA_ERROR_BAD_STATE);
5811
5812    psa_aead_abort(&operation);
5813
5814    /* Test for double setting nonce. */
5815
5816    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
5817
5818    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
5819
5820    TEST_EQUAL(psa_aead_set_nonce(&operation, nonce->x, nonce->len),
5821               PSA_ERROR_BAD_STATE);
5822
5823    psa_aead_abort(&operation);
5824
5825    /* Test for double generating nonce. */
5826
5827    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
5828
5829    PSA_ASSERT(psa_aead_generate_nonce(&operation, nonce_buffer,
5830                                       PSA_AEAD_NONCE_MAX_SIZE,
5831                                       &nonce_length));
5832
5833    TEST_EQUAL(psa_aead_generate_nonce(&operation, nonce_buffer,
5834                                       PSA_AEAD_NONCE_MAX_SIZE,
5835                                       &nonce_length),
5836               PSA_ERROR_BAD_STATE);
5837
5838
5839    psa_aead_abort(&operation);
5840
5841    /* Test for generate nonce then set and vice versa */
5842
5843    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
5844
5845    PSA_ASSERT(psa_aead_generate_nonce(&operation, nonce_buffer,
5846                                       PSA_AEAD_NONCE_MAX_SIZE,
5847                                       &nonce_length));
5848
5849    TEST_EQUAL(psa_aead_set_nonce(&operation, nonce->x, nonce->len),
5850               PSA_ERROR_BAD_STATE);
5851
5852    psa_aead_abort(&operation);
5853
5854    /* Test for generating nonce after calling set lengths */
5855
5856    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
5857
5858    PSA_ASSERT(psa_aead_set_lengths(&operation, additional_data->len,
5859                                    input_data->len));
5860
5861    PSA_ASSERT(psa_aead_generate_nonce(&operation, nonce_buffer,
5862                                       PSA_AEAD_NONCE_MAX_SIZE,
5863                                       &nonce_length));
5864
5865    psa_aead_abort(&operation);
5866
5867    /* Test for generating nonce after calling set lengths with UINT32_MAX ad_data length */
5868
5869    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
5870
5871    if (operation.alg == PSA_ALG_CCM) {
5872        TEST_EQUAL(psa_aead_set_lengths(&operation, UINT32_MAX,
5873                                        input_data->len),
5874                   PSA_ERROR_INVALID_ARGUMENT);
5875        TEST_EQUAL(psa_aead_generate_nonce(&operation, nonce_buffer,
5876                                           PSA_AEAD_NONCE_MAX_SIZE,
5877                                           &nonce_length),
5878                   PSA_ERROR_BAD_STATE);
5879    } else {
5880        PSA_ASSERT(psa_aead_set_lengths(&operation, UINT32_MAX,
5881                                        input_data->len));
5882        PSA_ASSERT(psa_aead_generate_nonce(&operation, nonce_buffer,
5883                                           PSA_AEAD_NONCE_MAX_SIZE,
5884                                           &nonce_length));
5885    }
5886
5887    psa_aead_abort(&operation);
5888
5889    /* Test for generating nonce after calling set lengths with SIZE_MAX ad_data length */
5890#if SIZE_MAX > UINT32_MAX
5891    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
5892
5893    if (operation.alg == PSA_ALG_CCM || operation.alg == PSA_ALG_GCM) {
5894        TEST_EQUAL(psa_aead_set_lengths(&operation, SIZE_MAX,
5895                                        input_data->len),
5896                   PSA_ERROR_INVALID_ARGUMENT);
5897        TEST_EQUAL(psa_aead_generate_nonce(&operation, nonce_buffer,
5898                                           PSA_AEAD_NONCE_MAX_SIZE,
5899                                           &nonce_length),
5900                   PSA_ERROR_BAD_STATE);
5901    } else {
5902        PSA_ASSERT(psa_aead_set_lengths(&operation, SIZE_MAX,
5903                                        input_data->len));
5904        PSA_ASSERT(psa_aead_generate_nonce(&operation, nonce_buffer,
5905                                           PSA_AEAD_NONCE_MAX_SIZE,
5906                                           &nonce_length));
5907    }
5908
5909    psa_aead_abort(&operation);
5910#endif
5911
5912    /* Test for calling set lengths with a UINT32_MAX ad_data length, after generating nonce */
5913
5914    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
5915
5916    PSA_ASSERT(psa_aead_generate_nonce(&operation, nonce_buffer,
5917                                       PSA_AEAD_NONCE_MAX_SIZE,
5918                                       &nonce_length));
5919
5920    if (operation.alg == PSA_ALG_CCM) {
5921        TEST_EQUAL(psa_aead_set_lengths(&operation, UINT32_MAX,
5922                                        input_data->len),
5923                   PSA_ERROR_INVALID_ARGUMENT);
5924    } else {
5925        PSA_ASSERT(psa_aead_set_lengths(&operation, UINT32_MAX,
5926                                        input_data->len));
5927    }
5928
5929    psa_aead_abort(&operation);
5930
5931    /* ------------------------------------------------------- */
5932    /* Test for setting nonce after calling set lengths */
5933
5934    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
5935
5936    PSA_ASSERT(psa_aead_set_lengths(&operation, additional_data->len,
5937                                    input_data->len));
5938
5939    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
5940
5941    psa_aead_abort(&operation);
5942
5943    /* Test for setting nonce after calling set lengths with UINT32_MAX ad_data length */
5944
5945    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
5946
5947    if (operation.alg == PSA_ALG_CCM) {
5948        TEST_EQUAL(psa_aead_set_lengths(&operation, UINT32_MAX,
5949                                        input_data->len),
5950                   PSA_ERROR_INVALID_ARGUMENT);
5951        TEST_EQUAL(psa_aead_set_nonce(&operation, nonce->x, nonce->len),
5952                   PSA_ERROR_BAD_STATE);
5953    } else {
5954        PSA_ASSERT(psa_aead_set_lengths(&operation, UINT32_MAX,
5955                                        input_data->len));
5956        PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
5957    }
5958
5959    psa_aead_abort(&operation);
5960
5961    /* Test for setting nonce after calling set lengths with SIZE_MAX ad_data length */
5962#if SIZE_MAX > UINT32_MAX
5963    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
5964
5965    if (operation.alg == PSA_ALG_CCM || operation.alg == PSA_ALG_GCM) {
5966        TEST_EQUAL(psa_aead_set_lengths(&operation, SIZE_MAX,
5967                                        input_data->len),
5968                   PSA_ERROR_INVALID_ARGUMENT);
5969        TEST_EQUAL(psa_aead_set_nonce(&operation, nonce->x, nonce->len),
5970                   PSA_ERROR_BAD_STATE);
5971    } else {
5972        PSA_ASSERT(psa_aead_set_lengths(&operation, SIZE_MAX,
5973                                        input_data->len));
5974        PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
5975    }
5976
5977    psa_aead_abort(&operation);
5978#endif
5979
5980    /* Test for calling set lengths with an ad_data length of UINT32_MAX, after setting nonce */
5981
5982    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
5983
5984    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
5985
5986    if (operation.alg == PSA_ALG_CCM) {
5987        TEST_EQUAL(psa_aead_set_lengths(&operation, UINT32_MAX,
5988                                        input_data->len),
5989                   PSA_ERROR_INVALID_ARGUMENT);
5990    } else {
5991        PSA_ASSERT(psa_aead_set_lengths(&operation, UINT32_MAX,
5992                                        input_data->len));
5993    }
5994
5995    psa_aead_abort(&operation);
5996
5997    /* Test for setting nonce after calling set lengths with plaintext length of SIZE_MAX */
5998#if SIZE_MAX > UINT32_MAX
5999    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
6000
6001    if (operation.alg == PSA_ALG_GCM) {
6002        TEST_EQUAL(psa_aead_set_lengths(&operation, additional_data->len,
6003                                        SIZE_MAX),
6004                   PSA_ERROR_INVALID_ARGUMENT);
6005        TEST_EQUAL(psa_aead_set_nonce(&operation, nonce->x, nonce->len),
6006                   PSA_ERROR_BAD_STATE);
6007    } else if (operation.alg != PSA_ALG_CCM) {
6008        PSA_ASSERT(psa_aead_set_lengths(&operation, additional_data->len,
6009                                        SIZE_MAX));
6010        PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
6011    }
6012
6013    psa_aead_abort(&operation);
6014#endif
6015
6016    /* Test for calling set lengths with a plaintext length of SIZE_MAX, after setting nonce */
6017#if SIZE_MAX > UINT32_MAX
6018    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
6019
6020    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
6021
6022    if (operation.alg == PSA_ALG_GCM) {
6023        TEST_EQUAL(psa_aead_set_lengths(&operation, additional_data->len,
6024                                        SIZE_MAX),
6025                   PSA_ERROR_INVALID_ARGUMENT);
6026    } else if (operation.alg != PSA_ALG_CCM) {
6027        PSA_ASSERT(psa_aead_set_lengths(&operation, additional_data->len,
6028                                        SIZE_MAX));
6029    }
6030
6031    psa_aead_abort(&operation);
6032#endif
6033
6034    /* ------------------------------------------------------- */
6035
6036    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
6037
6038    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
6039
6040    TEST_EQUAL(psa_aead_generate_nonce(&operation, nonce_buffer,
6041                                       PSA_AEAD_NONCE_MAX_SIZE,
6042                                       &nonce_length),
6043               PSA_ERROR_BAD_STATE);
6044
6045    psa_aead_abort(&operation);
6046
6047    /* Test for generating nonce in decrypt setup. */
6048
6049    PSA_ASSERT(psa_aead_decrypt_setup(&operation, key, alg));
6050
6051    TEST_EQUAL(psa_aead_generate_nonce(&operation, nonce_buffer,
6052                                       PSA_AEAD_NONCE_MAX_SIZE,
6053                                       &nonce_length),
6054               PSA_ERROR_BAD_STATE);
6055
6056    psa_aead_abort(&operation);
6057
6058    /* Test for setting lengths twice. */
6059
6060    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
6061
6062    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
6063
6064    PSA_ASSERT(psa_aead_set_lengths(&operation, additional_data->len,
6065                                    input_data->len));
6066
6067    TEST_EQUAL(psa_aead_set_lengths(&operation, additional_data->len,
6068                                    input_data->len),
6069               PSA_ERROR_BAD_STATE);
6070
6071    psa_aead_abort(&operation);
6072
6073    /* Test for setting lengths after setting nonce + already starting data. */
6074
6075    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
6076
6077    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
6078
6079    if (operation.alg == PSA_ALG_CCM) {
6080
6081        TEST_EQUAL(psa_aead_update_ad(&operation, additional_data->x,
6082                                      additional_data->len),
6083                   PSA_ERROR_BAD_STATE);
6084    } else {
6085        PSA_ASSERT(psa_aead_update_ad(&operation, additional_data->x,
6086                                      additional_data->len));
6087
6088        TEST_EQUAL(psa_aead_set_lengths(&operation, additional_data->len,
6089                                        input_data->len),
6090                   PSA_ERROR_BAD_STATE);
6091    }
6092    psa_aead_abort(&operation);
6093
6094    /* ------------------------------------------------------- */
6095
6096    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
6097
6098    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
6099
6100    if (operation.alg == PSA_ALG_CCM) {
6101        TEST_EQUAL(psa_aead_update(&operation, input_data->x,
6102                                   input_data->len, output_data,
6103                                   output_size, &output_length),
6104                   PSA_ERROR_BAD_STATE);
6105
6106    } else {
6107        PSA_ASSERT(psa_aead_update(&operation, input_data->x,
6108                                   input_data->len, output_data,
6109                                   output_size, &output_length));
6110
6111        TEST_EQUAL(psa_aead_set_lengths(&operation, additional_data->len,
6112                                        input_data->len),
6113                   PSA_ERROR_BAD_STATE);
6114    }
6115    psa_aead_abort(&operation);
6116
6117    /* ------------------------------------------------------- */
6118
6119    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
6120
6121    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
6122
6123    if (operation.alg == PSA_ALG_CCM) {
6124        PSA_ASSERT(psa_aead_finish(&operation, final_data,
6125                                   finish_output_size,
6126                                   &output_part_length,
6127                                   tag_buffer, tag_length,
6128                                   &tag_size));
6129    } else {
6130        PSA_ASSERT(psa_aead_finish(&operation, final_data,
6131                                   finish_output_size,
6132                                   &output_part_length,
6133                                   tag_buffer, tag_length,
6134                                   &tag_size));
6135
6136        TEST_EQUAL(psa_aead_set_lengths(&operation, additional_data->len,
6137                                        input_data->len),
6138                   PSA_ERROR_BAD_STATE);
6139    }
6140    psa_aead_abort(&operation);
6141
6142    /* Test for setting lengths after generating nonce + already starting data. */
6143
6144    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
6145
6146    PSA_ASSERT(psa_aead_generate_nonce(&operation, nonce_buffer,
6147                                       PSA_AEAD_NONCE_MAX_SIZE,
6148                                       &nonce_length));
6149    if (operation.alg == PSA_ALG_CCM) {
6150
6151        TEST_EQUAL(psa_aead_update_ad(&operation, additional_data->x,
6152                                      additional_data->len),
6153                   PSA_ERROR_BAD_STATE);
6154    } else {
6155        PSA_ASSERT(psa_aead_update_ad(&operation, additional_data->x,
6156                                      additional_data->len));
6157
6158        TEST_EQUAL(psa_aead_set_lengths(&operation, additional_data->len,
6159                                        input_data->len),
6160                   PSA_ERROR_BAD_STATE);
6161    }
6162    psa_aead_abort(&operation);
6163
6164    /* ------------------------------------------------------- */
6165
6166    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
6167
6168    PSA_ASSERT(psa_aead_generate_nonce(&operation, nonce_buffer,
6169                                       PSA_AEAD_NONCE_MAX_SIZE,
6170                                       &nonce_length));
6171    if (operation.alg == PSA_ALG_CCM) {
6172        TEST_EQUAL(psa_aead_update(&operation, input_data->x,
6173                                   input_data->len, output_data,
6174                                   output_size, &output_length),
6175                   PSA_ERROR_BAD_STATE);
6176
6177    } else {
6178        PSA_ASSERT(psa_aead_update(&operation, input_data->x,
6179                                   input_data->len, output_data,
6180                                   output_size, &output_length));
6181
6182        TEST_EQUAL(psa_aead_set_lengths(&operation, additional_data->len,
6183                                        input_data->len),
6184                   PSA_ERROR_BAD_STATE);
6185    }
6186    psa_aead_abort(&operation);
6187
6188    /* ------------------------------------------------------- */
6189
6190    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
6191
6192    PSA_ASSERT(psa_aead_generate_nonce(&operation, nonce_buffer,
6193                                       PSA_AEAD_NONCE_MAX_SIZE,
6194                                       &nonce_length));
6195    if (operation.alg == PSA_ALG_CCM) {
6196        PSA_ASSERT(psa_aead_finish(&operation, final_data,
6197                                   finish_output_size,
6198                                   &output_part_length,
6199                                   tag_buffer, tag_length,
6200                                   &tag_size));
6201    } else {
6202        PSA_ASSERT(psa_aead_finish(&operation, final_data,
6203                                   finish_output_size,
6204                                   &output_part_length,
6205                                   tag_buffer, tag_length,
6206                                   &tag_size));
6207
6208        TEST_EQUAL(psa_aead_set_lengths(&operation, additional_data->len,
6209                                        input_data->len),
6210                   PSA_ERROR_BAD_STATE);
6211    }
6212    psa_aead_abort(&operation);
6213
6214    /* Test for not sending any additional data or data after setting non zero
6215     * lengths for them. (encrypt) */
6216
6217    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
6218
6219    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
6220
6221    PSA_ASSERT(psa_aead_set_lengths(&operation, additional_data->len,
6222                                    input_data->len));
6223
6224    TEST_EQUAL(psa_aead_finish(&operation, final_data,
6225                               finish_output_size,
6226                               &output_part_length,
6227                               tag_buffer, tag_length,
6228                               &tag_size),
6229               PSA_ERROR_INVALID_ARGUMENT);
6230
6231    psa_aead_abort(&operation);
6232
6233    /* Test for not sending any additional data or data after setting non-zero
6234     * lengths for them. (decrypt) */
6235
6236    PSA_ASSERT(psa_aead_decrypt_setup(&operation, key, alg));
6237
6238    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
6239
6240    PSA_ASSERT(psa_aead_set_lengths(&operation, additional_data->len,
6241                                    input_data->len));
6242
6243    TEST_EQUAL(psa_aead_verify(&operation, final_data,
6244                               finish_output_size,
6245                               &output_part_length,
6246                               tag_buffer,
6247                               tag_length),
6248               PSA_ERROR_INVALID_ARGUMENT);
6249
6250    psa_aead_abort(&operation);
6251
6252    /* Test for not sending any additional data after setting a non-zero length
6253     * for it. */
6254
6255    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
6256
6257    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
6258
6259    PSA_ASSERT(psa_aead_set_lengths(&operation, additional_data->len,
6260                                    input_data->len));
6261
6262    TEST_EQUAL(psa_aead_update(&operation, input_data->x,
6263                               input_data->len, output_data,
6264                               output_size, &output_length),
6265               PSA_ERROR_INVALID_ARGUMENT);
6266
6267    psa_aead_abort(&operation);
6268
6269    /* Test for not sending any data after setting a non-zero length for it.*/
6270
6271    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
6272
6273    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
6274
6275    PSA_ASSERT(psa_aead_set_lengths(&operation, additional_data->len,
6276                                    input_data->len));
6277
6278    PSA_ASSERT(psa_aead_update_ad(&operation, additional_data->x,
6279                                  additional_data->len));
6280
6281    TEST_EQUAL(psa_aead_finish(&operation, final_data,
6282                               finish_output_size,
6283                               &output_part_length,
6284                               tag_buffer, tag_length,
6285                               &tag_size),
6286               PSA_ERROR_INVALID_ARGUMENT);
6287
6288    psa_aead_abort(&operation);
6289
6290    /* Test for sending too much additional data after setting lengths. */
6291
6292    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
6293
6294    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
6295
6296    PSA_ASSERT(psa_aead_set_lengths(&operation, 0, 0));
6297
6298
6299    TEST_EQUAL(psa_aead_update_ad(&operation, additional_data->x,
6300                                  additional_data->len),
6301               PSA_ERROR_INVALID_ARGUMENT);
6302
6303    psa_aead_abort(&operation);
6304
6305    /* ------------------------------------------------------- */
6306
6307    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
6308
6309    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
6310
6311    PSA_ASSERT(psa_aead_set_lengths(&operation, additional_data->len,
6312                                    input_data->len));
6313
6314    PSA_ASSERT(psa_aead_update_ad(&operation, additional_data->x,
6315                                  additional_data->len));
6316
6317    TEST_EQUAL(psa_aead_update_ad(&operation, additional_data->x,
6318                                  1),
6319               PSA_ERROR_INVALID_ARGUMENT);
6320
6321    psa_aead_abort(&operation);
6322
6323    /* Test for sending too much data after setting lengths. */
6324
6325    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
6326
6327    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
6328
6329    PSA_ASSERT(psa_aead_set_lengths(&operation, 0, 0));
6330
6331    TEST_EQUAL(psa_aead_update(&operation, input_data->x,
6332                               input_data->len, output_data,
6333                               output_size, &output_length),
6334               PSA_ERROR_INVALID_ARGUMENT);
6335
6336    psa_aead_abort(&operation);
6337
6338    /* ------------------------------------------------------- */
6339
6340    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
6341
6342    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
6343
6344    PSA_ASSERT(psa_aead_set_lengths(&operation, additional_data->len,
6345                                    input_data->len));
6346
6347    PSA_ASSERT(psa_aead_update_ad(&operation, additional_data->x,
6348                                  additional_data->len));
6349
6350    PSA_ASSERT(psa_aead_update(&operation, input_data->x,
6351                               input_data->len, output_data,
6352                               output_size, &output_length));
6353
6354    TEST_EQUAL(psa_aead_update(&operation, input_data->x,
6355                               1, output_data,
6356                               output_size, &output_length),
6357               PSA_ERROR_INVALID_ARGUMENT);
6358
6359    psa_aead_abort(&operation);
6360
6361    /* Test sending additional data after data. */
6362
6363    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
6364
6365    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
6366
6367    if (operation.alg != PSA_ALG_CCM) {
6368        PSA_ASSERT(psa_aead_update(&operation, input_data->x,
6369                                   input_data->len, output_data,
6370                                   output_size, &output_length));
6371
6372        TEST_EQUAL(psa_aead_update_ad(&operation, additional_data->x,
6373                                      additional_data->len),
6374                   PSA_ERROR_BAD_STATE);
6375    }
6376    psa_aead_abort(&operation);
6377
6378    /* Test calling finish on decryption. */
6379
6380    PSA_ASSERT(psa_aead_decrypt_setup(&operation, key, alg));
6381
6382    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
6383
6384    TEST_EQUAL(psa_aead_finish(&operation, final_data,
6385                               finish_output_size,
6386                               &output_part_length,
6387                               tag_buffer, tag_length,
6388                               &tag_size),
6389               PSA_ERROR_BAD_STATE);
6390
6391    psa_aead_abort(&operation);
6392
6393    /* Test calling verify on encryption. */
6394
6395    PSA_ASSERT(psa_aead_encrypt_setup(&operation, key, alg));
6396
6397    PSA_ASSERT(psa_aead_set_nonce(&operation, nonce->x, nonce->len));
6398
6399    TEST_EQUAL(psa_aead_verify(&operation, final_data,
6400                               finish_output_size,
6401                               &output_part_length,
6402                               tag_buffer,
6403                               tag_length),
6404               PSA_ERROR_BAD_STATE);
6405
6406    psa_aead_abort(&operation);
6407
6408
6409exit:
6410    psa_destroy_key(key);
6411    psa_aead_abort(&operation);
6412    mbedtls_free(output_data);
6413    mbedtls_free(final_data);
6414    PSA_DONE();
6415}
6416/* END_CASE */
6417
6418/* BEGIN_CASE */
6419void signature_size(int type_arg,
6420                    int bits,
6421                    int alg_arg,
6422                    int expected_size_arg)
6423{
6424    psa_key_type_t type = type_arg;
6425    psa_algorithm_t alg = alg_arg;
6426    size_t actual_size = PSA_SIGN_OUTPUT_SIZE(type, bits, alg);
6427
6428    TEST_EQUAL(actual_size, (size_t) expected_size_arg);
6429
6430exit:
6431    ;
6432}
6433/* END_CASE */
6434
6435/* BEGIN_CASE */
6436void sign_hash_deterministic(int key_type_arg, data_t *key_data,
6437                             int alg_arg, data_t *input_data,
6438                             data_t *output_data)
6439{
6440    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
6441    psa_key_type_t key_type = key_type_arg;
6442    psa_algorithm_t alg = alg_arg;
6443    size_t key_bits;
6444    unsigned char *signature = NULL;
6445    size_t signature_size;
6446    size_t signature_length = 0xdeadbeef;
6447    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
6448
6449    PSA_ASSERT(psa_crypto_init());
6450
6451    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH);
6452    psa_set_key_algorithm(&attributes, alg);
6453    psa_set_key_type(&attributes, key_type);
6454
6455    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
6456                              &key));
6457    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
6458    key_bits = psa_get_key_bits(&attributes);
6459
6460    /* Allocate a buffer which has the size advertised by the
6461     * library. */
6462    signature_size = PSA_SIGN_OUTPUT_SIZE(key_type,
6463                                          key_bits, alg);
6464    TEST_ASSERT(signature_size != 0);
6465    TEST_LE_U(signature_size, PSA_SIGNATURE_MAX_SIZE);
6466    ASSERT_ALLOC(signature, signature_size);
6467
6468    /* Perform the signature. */
6469    PSA_ASSERT(psa_sign_hash(key, alg,
6470                             input_data->x, input_data->len,
6471                             signature, signature_size,
6472                             &signature_length));
6473    /* Verify that the signature is what is expected. */
6474    ASSERT_COMPARE(output_data->x, output_data->len,
6475                   signature, signature_length);
6476
6477exit:
6478    /*
6479     * Key attributes may have been returned by psa_get_key_attributes()
6480     * thus reset them as required.
6481     */
6482    psa_reset_key_attributes(&attributes);
6483
6484    psa_destroy_key(key);
6485    mbedtls_free(signature);
6486    PSA_DONE();
6487}
6488/* END_CASE */
6489
6490/* BEGIN_CASE depends_on:MBEDTLS_ECP_RESTARTABLE */
6491/**
6492 * sign_hash_interruptible() test intentions:
6493 *
6494 * Note: This test can currently only handle ECDSA.
6495 *
6496 * 1. Test interruptible sign hash with known outcomes (deterministic ECDSA
6497 *    and private keys / keypairs only).
6498 *
6499 * 2. Test the number of calls to psa_sign_hash_complete() required are as
6500 *    expected for different max_ops values.
6501 *
6502 * 3. Test that the number of ops done prior to start and after abort is zero
6503 *    and that each successful stage completes some ops (this is not mandated by
6504 *    the PSA specification, but is currently the case).
6505 *
6506 * 4. Test that calling psa_sign_hash_get_num_ops() multiple times between
6507 *    complete() calls does not alter the number of ops returned.
6508 */
6509void sign_hash_interruptible(int key_type_arg, data_t *key_data,
6510                             int alg_arg, data_t *input_data,
6511                             data_t *output_data, int max_ops_arg)
6512{
6513    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
6514    psa_key_type_t key_type = key_type_arg;
6515    psa_algorithm_t alg = alg_arg;
6516    size_t key_bits;
6517    unsigned char *signature = NULL;
6518    size_t signature_size;
6519    size_t signature_length = 0xdeadbeef;
6520    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
6521    psa_status_t status = PSA_OPERATION_INCOMPLETE;
6522    uint32_t num_ops = 0;
6523    uint32_t max_ops = max_ops_arg;
6524    size_t num_ops_prior = 0;
6525    size_t num_completes = 0;
6526    size_t min_completes = 0;
6527    size_t max_completes = 0;
6528
6529    psa_sign_hash_interruptible_operation_t operation =
6530        psa_sign_hash_interruptible_operation_init();
6531
6532    PSA_ASSERT(psa_crypto_init());
6533
6534    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH);
6535    psa_set_key_algorithm(&attributes, alg);
6536    psa_set_key_type(&attributes, key_type);
6537
6538    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
6539                              &key));
6540    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
6541    key_bits = psa_get_key_bits(&attributes);
6542
6543    /* Allocate a buffer which has the size advertised by the
6544     * library. */
6545    signature_size = PSA_SIGN_OUTPUT_SIZE(key_type,
6546                                          key_bits, alg);
6547    TEST_ASSERT(signature_size != 0);
6548    TEST_LE_U(signature_size, PSA_SIGNATURE_MAX_SIZE);
6549    ASSERT_ALLOC(signature, signature_size);
6550
6551    psa_interruptible_set_max_ops(max_ops);
6552
6553    interruptible_signverify_get_minmax_completes(max_ops, PSA_SUCCESS,
6554                                                  &min_completes, &max_completes);
6555
6556    num_ops_prior = psa_sign_hash_get_num_ops(&operation);
6557    TEST_ASSERT(num_ops_prior == 0);
6558
6559    /* Start performing the signature. */
6560    PSA_ASSERT(psa_sign_hash_start(&operation, key, alg,
6561                                   input_data->x, input_data->len));
6562
6563    num_ops_prior = psa_sign_hash_get_num_ops(&operation);
6564    TEST_ASSERT(num_ops_prior == 0);
6565
6566    /* Continue performing the signature until complete. */
6567    do {
6568        status = psa_sign_hash_complete(&operation, signature, signature_size,
6569                                        &signature_length);
6570
6571        num_completes++;
6572
6573        if (status == PSA_SUCCESS || status == PSA_OPERATION_INCOMPLETE) {
6574            num_ops = psa_sign_hash_get_num_ops(&operation);
6575            /* We are asserting here that every complete makes progress
6576             * (completes some ops), which is true of the internal
6577             * implementation and probably any implementation, however this is
6578             * not mandated by the PSA specification. */
6579            TEST_ASSERT(num_ops > num_ops_prior);
6580
6581            num_ops_prior = num_ops;
6582
6583            /* Ensure calling get_num_ops() twice still returns the same
6584             * number of ops as previously reported. */
6585            num_ops = psa_sign_hash_get_num_ops(&operation);
6586
6587            TEST_EQUAL(num_ops, num_ops_prior);
6588        }
6589    } while (status == PSA_OPERATION_INCOMPLETE);
6590
6591    TEST_ASSERT(status == PSA_SUCCESS);
6592
6593    TEST_LE_U(min_completes, num_completes);
6594    TEST_LE_U(num_completes, max_completes);
6595
6596    /* Verify that the signature is what is expected. */
6597    ASSERT_COMPARE(output_data->x, output_data->len,
6598                   signature, signature_length);
6599
6600    PSA_ASSERT(psa_sign_hash_abort(&operation));
6601
6602    num_ops = psa_sign_hash_get_num_ops(&operation);
6603    TEST_ASSERT(num_ops == 0);
6604
6605exit:
6606
6607    /*
6608     * Key attributes may have been returned by psa_get_key_attributes()
6609     * thus reset them as required.
6610     */
6611    psa_reset_key_attributes(&attributes);
6612
6613    psa_destroy_key(key);
6614    mbedtls_free(signature);
6615    PSA_DONE();
6616}
6617/* END_CASE */
6618
6619/* BEGIN_CASE */
6620void sign_hash_fail(int key_type_arg, data_t *key_data,
6621                    int alg_arg, data_t *input_data,
6622                    int signature_size_arg, int expected_status_arg)
6623{
6624    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
6625    psa_key_type_t key_type = key_type_arg;
6626    psa_algorithm_t alg = alg_arg;
6627    size_t signature_size = signature_size_arg;
6628    psa_status_t actual_status;
6629    psa_status_t expected_status = expected_status_arg;
6630    unsigned char *signature = NULL;
6631    size_t signature_length = 0xdeadbeef;
6632    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
6633
6634    ASSERT_ALLOC(signature, signature_size);
6635
6636    PSA_ASSERT(psa_crypto_init());
6637
6638    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH);
6639    psa_set_key_algorithm(&attributes, alg);
6640    psa_set_key_type(&attributes, key_type);
6641
6642    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
6643                              &key));
6644
6645    actual_status = psa_sign_hash(key, alg,
6646                                  input_data->x, input_data->len,
6647                                  signature, signature_size,
6648                                  &signature_length);
6649    TEST_EQUAL(actual_status, expected_status);
6650    /* The value of *signature_length is unspecified on error, but
6651     * whatever it is, it should be less than signature_size, so that
6652     * if the caller tries to read *signature_length bytes without
6653     * checking the error code then they don't overflow a buffer. */
6654    TEST_LE_U(signature_length, signature_size);
6655
6656exit:
6657    psa_reset_key_attributes(&attributes);
6658    psa_destroy_key(key);
6659    mbedtls_free(signature);
6660    PSA_DONE();
6661}
6662/* END_CASE */
6663
6664/* BEGIN_CASE depends_on:MBEDTLS_ECP_RESTARTABLE */
6665/**
6666 * sign_hash_fail_interruptible() test intentions:
6667 *
6668 * Note: This test can currently only handle ECDSA.
6669 *
6670 * 1. Test that various failure cases for interruptible sign hash fail with the
6671 *    correct error codes, and at the correct point (at start or during
6672 *    complete).
6673 *
6674 * 2. Test the number of calls to psa_sign_hash_complete() required are as
6675 *    expected for different max_ops values.
6676 *
6677 * 3. Test that the number of ops done prior to start and after abort is zero
6678 *    and that each successful stage completes some ops (this is not mandated by
6679 *    the PSA specification, but is currently the case).
6680 *
6681 * 4. Check that calling complete() when start() fails and complete()
6682 *    after completion results in a BAD_STATE error.
6683 *
6684 * 5. Check that calling start() again after start fails results in a BAD_STATE
6685 *    error.
6686 */
6687void sign_hash_fail_interruptible(int key_type_arg, data_t *key_data,
6688                                  int alg_arg, data_t *input_data,
6689                                  int signature_size_arg,
6690                                  int expected_start_status_arg,
6691                                  int expected_complete_status_arg,
6692                                  int max_ops_arg)
6693{
6694    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
6695    psa_key_type_t key_type = key_type_arg;
6696    psa_algorithm_t alg = alg_arg;
6697    size_t signature_size = signature_size_arg;
6698    psa_status_t actual_status;
6699    psa_status_t expected_start_status = expected_start_status_arg;
6700    psa_status_t expected_complete_status = expected_complete_status_arg;
6701    unsigned char *signature = NULL;
6702    size_t signature_length = 0xdeadbeef;
6703    uint32_t num_ops = 0;
6704    uint32_t max_ops = max_ops_arg;
6705    size_t num_ops_prior = 0;
6706    size_t num_completes = 0;
6707    size_t min_completes = 0;
6708    size_t max_completes = 0;
6709
6710    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
6711    psa_sign_hash_interruptible_operation_t operation =
6712        psa_sign_hash_interruptible_operation_init();
6713
6714    ASSERT_ALLOC(signature, signature_size);
6715
6716    PSA_ASSERT(psa_crypto_init());
6717
6718    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH);
6719    psa_set_key_algorithm(&attributes, alg);
6720    psa_set_key_type(&attributes, key_type);
6721
6722    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
6723                              &key));
6724
6725    psa_interruptible_set_max_ops(max_ops);
6726
6727    interruptible_signverify_get_minmax_completes(max_ops,
6728                                                  expected_complete_status,
6729                                                  &min_completes,
6730                                                  &max_completes);
6731
6732    num_ops_prior = psa_sign_hash_get_num_ops(&operation);
6733    TEST_ASSERT(num_ops_prior == 0);
6734
6735    /* Start performing the signature. */
6736    actual_status = psa_sign_hash_start(&operation, key, alg,
6737                                        input_data->x, input_data->len);
6738
6739    TEST_EQUAL(actual_status, expected_start_status);
6740
6741    if (expected_start_status != PSA_SUCCESS) {
6742        /* Emulate poor application code, and call complete anyway, even though
6743         * start failed. */
6744        actual_status = psa_sign_hash_complete(&operation, signature,
6745                                               signature_size,
6746                                               &signature_length);
6747
6748        TEST_EQUAL(actual_status, PSA_ERROR_BAD_STATE);
6749
6750        /* Test that calling start again after failure also causes BAD_STATE. */
6751        actual_status = psa_sign_hash_start(&operation, key, alg,
6752                                            input_data->x, input_data->len);
6753
6754        TEST_EQUAL(actual_status, PSA_ERROR_BAD_STATE);
6755    }
6756
6757    num_ops_prior = psa_sign_hash_get_num_ops(&operation);
6758    TEST_ASSERT(num_ops_prior == 0);
6759
6760    /* Continue performing the signature until complete. */
6761    do {
6762        actual_status = psa_sign_hash_complete(&operation, signature,
6763                                               signature_size,
6764                                               &signature_length);
6765
6766        num_completes++;
6767
6768        if (actual_status == PSA_SUCCESS ||
6769            actual_status == PSA_OPERATION_INCOMPLETE) {
6770            num_ops = psa_sign_hash_get_num_ops(&operation);
6771            /* We are asserting here that every complete makes progress
6772             * (completes some ops), which is true of the internal
6773             * implementation and probably any implementation, however this is
6774             * not mandated by the PSA specification. */
6775            TEST_ASSERT(num_ops > num_ops_prior);
6776
6777            num_ops_prior = num_ops;
6778        }
6779    } while (actual_status == PSA_OPERATION_INCOMPLETE);
6780
6781    TEST_EQUAL(actual_status, expected_complete_status);
6782
6783    /* Check that another complete returns BAD_STATE. */
6784    actual_status = psa_sign_hash_complete(&operation, signature,
6785                                           signature_size,
6786                                           &signature_length);
6787
6788    TEST_EQUAL(actual_status, PSA_ERROR_BAD_STATE);
6789
6790    PSA_ASSERT(psa_sign_hash_abort(&operation));
6791
6792    num_ops = psa_sign_hash_get_num_ops(&operation);
6793    TEST_ASSERT(num_ops == 0);
6794
6795    /* The value of *signature_length is unspecified on error, but
6796     * whatever it is, it should be less than signature_size, so that
6797     * if the caller tries to read *signature_length bytes without
6798     * checking the error code then they don't overflow a buffer. */
6799    TEST_LE_U(signature_length, signature_size);
6800
6801    TEST_LE_U(min_completes, num_completes);
6802    TEST_LE_U(num_completes, max_completes);
6803
6804exit:
6805    psa_reset_key_attributes(&attributes);
6806    psa_destroy_key(key);
6807    mbedtls_free(signature);
6808    PSA_DONE();
6809}
6810/* END_CASE */
6811
6812/* BEGIN_CASE */
6813void sign_verify_hash(int key_type_arg, data_t *key_data,
6814                      int alg_arg, data_t *input_data)
6815{
6816    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
6817    psa_key_type_t key_type = key_type_arg;
6818    psa_algorithm_t alg = alg_arg;
6819    size_t key_bits;
6820    unsigned char *signature = NULL;
6821    size_t signature_size;
6822    size_t signature_length = 0xdeadbeef;
6823    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
6824
6825    PSA_ASSERT(psa_crypto_init());
6826
6827    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH | PSA_KEY_USAGE_VERIFY_HASH);
6828    psa_set_key_algorithm(&attributes, alg);
6829    psa_set_key_type(&attributes, key_type);
6830
6831    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
6832                              &key));
6833    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
6834    key_bits = psa_get_key_bits(&attributes);
6835
6836    /* Allocate a buffer which has the size advertised by the
6837     * library. */
6838    signature_size = PSA_SIGN_OUTPUT_SIZE(key_type,
6839                                          key_bits, alg);
6840    TEST_ASSERT(signature_size != 0);
6841    TEST_LE_U(signature_size, PSA_SIGNATURE_MAX_SIZE);
6842    ASSERT_ALLOC(signature, signature_size);
6843
6844    /* Perform the signature. */
6845    PSA_ASSERT(psa_sign_hash(key, alg,
6846                             input_data->x, input_data->len,
6847                             signature, signature_size,
6848                             &signature_length));
6849    /* Check that the signature length looks sensible. */
6850    TEST_LE_U(signature_length, signature_size);
6851    TEST_ASSERT(signature_length > 0);
6852
6853    /* Use the library to verify that the signature is correct. */
6854    PSA_ASSERT(psa_verify_hash(key, alg,
6855                               input_data->x, input_data->len,
6856                               signature, signature_length));
6857
6858    if (input_data->len != 0) {
6859        /* Flip a bit in the input and verify that the signature is now
6860         * detected as invalid. Flip a bit at the beginning, not at the end,
6861         * because ECDSA may ignore the last few bits of the input. */
6862        input_data->x[0] ^= 1;
6863        TEST_EQUAL(psa_verify_hash(key, alg,
6864                                   input_data->x, input_data->len,
6865                                   signature, signature_length),
6866                   PSA_ERROR_INVALID_SIGNATURE);
6867    }
6868
6869exit:
6870    /*
6871     * Key attributes may have been returned by psa_get_key_attributes()
6872     * thus reset them as required.
6873     */
6874    psa_reset_key_attributes(&attributes);
6875
6876    psa_destroy_key(key);
6877    mbedtls_free(signature);
6878    PSA_DONE();
6879}
6880/* END_CASE */
6881
6882/* BEGIN_CASE depends_on:MBEDTLS_ECP_RESTARTABLE */
6883/**
6884 * sign_verify_hash_interruptible() test intentions:
6885 *
6886 * Note: This test can currently only handle ECDSA.
6887 *
6888 * 1. Test that we can sign an input hash with the given keypair and then
6889 *    afterwards verify that signature. This is currently the only way to test
6890 *    non deterministic ECDSA, but this test can also handle deterministic.
6891 *
6892 * 2. Test that after corrupting the hash, the verification detects an invalid
6893 *    signature.
6894 *
6895 * 3. Test the number of calls to psa_sign_hash_complete() required are as
6896 *    expected for different max_ops values.
6897 *
6898 * 4. Test that the number of ops done prior to starting signing and after abort
6899 *    is zero and that each successful signing stage completes some ops (this is
6900 *    not mandated by the PSA specification, but is currently the case).
6901 */
6902void sign_verify_hash_interruptible(int key_type_arg, data_t *key_data,
6903                                    int alg_arg, data_t *input_data,
6904                                    int max_ops_arg)
6905{
6906    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
6907    psa_key_type_t key_type = key_type_arg;
6908    psa_algorithm_t alg = alg_arg;
6909    size_t key_bits;
6910    unsigned char *signature = NULL;
6911    size_t signature_size;
6912    size_t signature_length = 0xdeadbeef;
6913    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
6914    psa_status_t status = PSA_OPERATION_INCOMPLETE;
6915    uint32_t max_ops = max_ops_arg;
6916    uint32_t num_ops = 0;
6917    uint32_t num_ops_prior = 0;
6918    size_t num_completes = 0;
6919    size_t min_completes = 0;
6920    size_t max_completes = 0;
6921
6922    psa_sign_hash_interruptible_operation_t sign_operation =
6923        psa_sign_hash_interruptible_operation_init();
6924    psa_verify_hash_interruptible_operation_t verify_operation =
6925        psa_verify_hash_interruptible_operation_init();
6926
6927    PSA_ASSERT(psa_crypto_init());
6928
6929    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH |
6930                            PSA_KEY_USAGE_VERIFY_HASH);
6931    psa_set_key_algorithm(&attributes, alg);
6932    psa_set_key_type(&attributes, key_type);
6933
6934    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
6935                              &key));
6936    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
6937    key_bits = psa_get_key_bits(&attributes);
6938
6939    /* Allocate a buffer which has the size advertised by the
6940     * library. */
6941    signature_size = PSA_SIGN_OUTPUT_SIZE(key_type,
6942                                          key_bits, alg);
6943    TEST_ASSERT(signature_size != 0);
6944    TEST_LE_U(signature_size, PSA_SIGNATURE_MAX_SIZE);
6945    ASSERT_ALLOC(signature, signature_size);
6946
6947    psa_interruptible_set_max_ops(max_ops);
6948
6949    interruptible_signverify_get_minmax_completes(max_ops, PSA_SUCCESS,
6950                                                  &min_completes, &max_completes);
6951
6952    num_ops_prior = psa_sign_hash_get_num_ops(&sign_operation);
6953    TEST_ASSERT(num_ops_prior == 0);
6954
6955    /* Start performing the signature. */
6956    PSA_ASSERT(psa_sign_hash_start(&sign_operation, key, alg,
6957                                   input_data->x, input_data->len));
6958
6959    num_ops_prior = psa_sign_hash_get_num_ops(&sign_operation);
6960    TEST_ASSERT(num_ops_prior == 0);
6961
6962    /* Continue performing the signature until complete. */
6963    do {
6964
6965        status = psa_sign_hash_complete(&sign_operation, signature,
6966                                        signature_size,
6967                                        &signature_length);
6968
6969        num_completes++;
6970
6971        if (status == PSA_SUCCESS || status == PSA_OPERATION_INCOMPLETE) {
6972            num_ops = psa_sign_hash_get_num_ops(&sign_operation);
6973            /* We are asserting here that every complete makes progress
6974             * (completes some ops), which is true of the internal
6975             * implementation and probably any implementation, however this is
6976             * not mandated by the PSA specification. */
6977            TEST_ASSERT(num_ops > num_ops_prior);
6978
6979            num_ops_prior = num_ops;
6980        }
6981    } while (status == PSA_OPERATION_INCOMPLETE);
6982
6983    TEST_ASSERT(status == PSA_SUCCESS);
6984
6985    TEST_LE_U(min_completes, num_completes);
6986    TEST_LE_U(num_completes, max_completes);
6987
6988    PSA_ASSERT(psa_sign_hash_abort(&sign_operation));
6989
6990    num_ops = psa_sign_hash_get_num_ops(&sign_operation);
6991    TEST_ASSERT(num_ops == 0);
6992
6993    /* Check that the signature length looks sensible. */
6994    TEST_LE_U(signature_length, signature_size);
6995    TEST_ASSERT(signature_length > 0);
6996
6997    num_completes = 0;
6998
6999    /* Start verification. */
7000    PSA_ASSERT(psa_verify_hash_start(&verify_operation, key, alg,
7001                                     input_data->x, input_data->len,
7002                                     signature, signature_length));
7003
7004    /* Continue performing the signature until complete. */
7005    do {
7006        status = psa_verify_hash_complete(&verify_operation);
7007
7008        num_completes++;
7009    } while (status == PSA_OPERATION_INCOMPLETE);
7010
7011    TEST_ASSERT(status == PSA_SUCCESS);
7012
7013    TEST_LE_U(min_completes, num_completes);
7014    TEST_LE_U(num_completes, max_completes);
7015
7016    PSA_ASSERT(psa_verify_hash_abort(&verify_operation));
7017
7018    verify_operation = psa_verify_hash_interruptible_operation_init();
7019
7020    if (input_data->len != 0) {
7021        /* Flip a bit in the input and verify that the signature is now
7022         * detected as invalid. Flip a bit at the beginning, not at the end,
7023         * because ECDSA may ignore the last few bits of the input. */
7024        input_data->x[0] ^= 1;
7025
7026        /* Start verification. */
7027        PSA_ASSERT(psa_verify_hash_start(&verify_operation, key, alg,
7028                                         input_data->x, input_data->len,
7029                                         signature, signature_length));
7030
7031        /* Continue performing the signature until complete. */
7032        do {
7033            status = psa_verify_hash_complete(&verify_operation);
7034        } while (status == PSA_OPERATION_INCOMPLETE);
7035
7036        TEST_ASSERT(status ==  PSA_ERROR_INVALID_SIGNATURE);
7037    }
7038
7039    PSA_ASSERT(psa_verify_hash_abort(&verify_operation));
7040
7041exit:
7042    /*
7043     * Key attributes may have been returned by psa_get_key_attributes()
7044     * thus reset them as required.
7045     */
7046    psa_reset_key_attributes(&attributes);
7047
7048    psa_destroy_key(key);
7049    mbedtls_free(signature);
7050    PSA_DONE();
7051}
7052/* END_CASE */
7053
7054/* BEGIN_CASE */
7055void verify_hash(int key_type_arg, data_t *key_data,
7056                 int alg_arg, data_t *hash_data,
7057                 data_t *signature_data)
7058{
7059    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
7060    psa_key_type_t key_type = key_type_arg;
7061    psa_algorithm_t alg = alg_arg;
7062    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
7063
7064    TEST_LE_U(signature_data->len, PSA_SIGNATURE_MAX_SIZE);
7065
7066    PSA_ASSERT(psa_crypto_init());
7067
7068    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_VERIFY_HASH);
7069    psa_set_key_algorithm(&attributes, alg);
7070    psa_set_key_type(&attributes, key_type);
7071
7072    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
7073                              &key));
7074
7075    PSA_ASSERT(psa_verify_hash(key, alg,
7076                               hash_data->x, hash_data->len,
7077                               signature_data->x, signature_data->len));
7078
7079exit:
7080    psa_reset_key_attributes(&attributes);
7081    psa_destroy_key(key);
7082    PSA_DONE();
7083}
7084/* END_CASE */
7085
7086/* BEGIN_CASE depends_on:MBEDTLS_ECP_RESTARTABLE */
7087/**
7088 * verify_hash_interruptible() test intentions:
7089 *
7090 * Note: This test can currently only handle ECDSA.
7091 *
7092 * 1. Test interruptible verify hash with known outcomes (deterministic ECDSA
7093 *    only). Given this test only does verification it can accept public keys as
7094 *    well as private keys / keypairs.
7095 *
7096 * 2. Test the number of calls to psa_verify_hash_complete() required are as
7097 *    expected for different max_ops values.
7098 *
7099 * 3. Test that the number of ops done prior to start and after abort is zero
7100 *    and that each successful stage completes some ops (this is not mandated by
7101 *    the PSA specification, but is currently the case).
7102 *
7103 * 4. Test that calling psa_sign_hash_get_num_ops() multiple times between
7104 *    complete() calls does not alter the number of ops returned.
7105 *
7106 * 5. Test that after corrupting the hash, the verification detects an invalid
7107 *    signature.
7108 */
7109void verify_hash_interruptible(int key_type_arg, data_t *key_data,
7110                               int alg_arg, data_t *hash_data,
7111                               data_t *signature_data, int max_ops_arg)
7112{
7113    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
7114    psa_key_type_t key_type = key_type_arg;
7115    psa_algorithm_t alg = alg_arg;
7116    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
7117    psa_status_t status = PSA_OPERATION_INCOMPLETE;
7118    uint32_t num_ops = 0;
7119    uint32_t max_ops = max_ops_arg;
7120    size_t num_ops_prior = 0;
7121    size_t num_completes = 0;
7122    size_t min_completes = 0;
7123    size_t max_completes = 0;
7124
7125    psa_verify_hash_interruptible_operation_t operation =
7126        psa_verify_hash_interruptible_operation_init();
7127
7128    TEST_LE_U(signature_data->len, PSA_SIGNATURE_MAX_SIZE);
7129
7130    PSA_ASSERT(psa_crypto_init());
7131
7132    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_VERIFY_HASH);
7133    psa_set_key_algorithm(&attributes, alg);
7134    psa_set_key_type(&attributes, key_type);
7135
7136    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
7137                              &key));
7138
7139    psa_interruptible_set_max_ops(max_ops);
7140
7141    interruptible_signverify_get_minmax_completes(max_ops, PSA_SUCCESS,
7142                                                  &min_completes, &max_completes);
7143
7144    num_ops_prior = psa_verify_hash_get_num_ops(&operation);
7145
7146    TEST_ASSERT(num_ops_prior == 0);
7147
7148    /* Start verification. */
7149    PSA_ASSERT(psa_verify_hash_start(&operation, key, alg,
7150                                     hash_data->x, hash_data->len,
7151                                     signature_data->x, signature_data->len)
7152               );
7153
7154    num_ops_prior = psa_verify_hash_get_num_ops(&operation);
7155
7156    TEST_ASSERT(num_ops_prior == 0);
7157
7158    /* Continue performing the signature until complete. */
7159    do {
7160        status = psa_verify_hash_complete(&operation);
7161
7162        num_completes++;
7163
7164        if (status == PSA_SUCCESS || status == PSA_OPERATION_INCOMPLETE) {
7165            num_ops = psa_verify_hash_get_num_ops(&operation);
7166            /* We are asserting here that every complete makes progress
7167             * (completes some ops), which is true of the internal
7168             * implementation and probably any implementation, however this is
7169             * not mandated by the PSA specification. */
7170            TEST_ASSERT(num_ops > num_ops_prior);
7171
7172            num_ops_prior = num_ops;
7173
7174            /* Ensure calling get_num_ops() twice still returns the same
7175             * number of ops as previously reported. */
7176            num_ops = psa_verify_hash_get_num_ops(&operation);
7177
7178            TEST_EQUAL(num_ops, num_ops_prior);
7179        }
7180    } while (status == PSA_OPERATION_INCOMPLETE);
7181
7182    TEST_ASSERT(status == PSA_SUCCESS);
7183
7184    TEST_LE_U(min_completes, num_completes);
7185    TEST_LE_U(num_completes, max_completes);
7186
7187    PSA_ASSERT(psa_verify_hash_abort(&operation));
7188
7189    num_ops = psa_verify_hash_get_num_ops(&operation);
7190    TEST_ASSERT(num_ops == 0);
7191
7192    if (hash_data->len != 0) {
7193        /* Flip a bit in the hash and verify that the signature is now detected
7194         * as invalid. Flip a bit at the beginning, not at the end, because
7195         * ECDSA may ignore the last few bits of the input. */
7196        hash_data->x[0] ^= 1;
7197
7198        /* Start verification. */
7199        PSA_ASSERT(psa_verify_hash_start(&operation, key, alg,
7200                                         hash_data->x, hash_data->len,
7201                                         signature_data->x, signature_data->len));
7202
7203        /* Continue performing the signature until complete. */
7204        do {
7205            status = psa_verify_hash_complete(&operation);
7206        } while (status == PSA_OPERATION_INCOMPLETE);
7207
7208        TEST_ASSERT(status ==  PSA_ERROR_INVALID_SIGNATURE);
7209    }
7210
7211exit:
7212    psa_reset_key_attributes(&attributes);
7213    psa_destroy_key(key);
7214    PSA_DONE();
7215}
7216/* END_CASE */
7217
7218/* BEGIN_CASE */
7219void verify_hash_fail(int key_type_arg, data_t *key_data,
7220                      int alg_arg, data_t *hash_data,
7221                      data_t *signature_data,
7222                      int expected_status_arg)
7223{
7224    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
7225    psa_key_type_t key_type = key_type_arg;
7226    psa_algorithm_t alg = alg_arg;
7227    psa_status_t actual_status;
7228    psa_status_t expected_status = expected_status_arg;
7229    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
7230
7231    PSA_ASSERT(psa_crypto_init());
7232
7233    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_VERIFY_HASH);
7234    psa_set_key_algorithm(&attributes, alg);
7235    psa_set_key_type(&attributes, key_type);
7236
7237    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
7238                              &key));
7239
7240    actual_status = psa_verify_hash(key, alg,
7241                                    hash_data->x, hash_data->len,
7242                                    signature_data->x, signature_data->len);
7243    TEST_EQUAL(actual_status, expected_status);
7244
7245exit:
7246    psa_reset_key_attributes(&attributes);
7247    psa_destroy_key(key);
7248    PSA_DONE();
7249}
7250/* END_CASE */
7251
7252/* BEGIN_CASE depends_on:MBEDTLS_ECP_RESTARTABLE */
7253/**
7254 * verify_hash_fail_interruptible() test intentions:
7255 *
7256 * Note: This test can currently only handle ECDSA.
7257 *
7258 * 1. Test that various failure cases for interruptible verify hash fail with
7259 *    the correct error codes, and at the correct point (at start or during
7260 *    complete).
7261 *
7262 * 2. Test the number of calls to psa_verify_hash_complete() required are as
7263 *    expected for different max_ops values.
7264 *
7265 * 3. Test that the number of ops done prior to start and after abort is zero
7266 *    and that each successful stage completes some ops (this is not mandated by
7267 *    the PSA specification, but is currently the case).
7268 *
7269 * 4. Check that calling complete() when start() fails and complete()
7270 *    after completion results in a BAD_STATE error.
7271 *
7272 * 5. Check that calling start() again after start fails results in a BAD_STATE
7273 *    error.
7274 */
7275void verify_hash_fail_interruptible(int key_type_arg, data_t *key_data,
7276                                    int alg_arg, data_t *hash_data,
7277                                    data_t *signature_data,
7278                                    int expected_start_status_arg,
7279                                    int expected_complete_status_arg,
7280                                    int max_ops_arg)
7281{
7282    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
7283    psa_key_type_t key_type = key_type_arg;
7284    psa_algorithm_t alg = alg_arg;
7285    psa_status_t actual_status;
7286    psa_status_t expected_start_status = expected_start_status_arg;
7287    psa_status_t expected_complete_status = expected_complete_status_arg;
7288    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
7289    uint32_t num_ops = 0;
7290    uint32_t max_ops = max_ops_arg;
7291    size_t num_ops_prior = 0;
7292    size_t num_completes = 0;
7293    size_t min_completes = 0;
7294    size_t max_completes = 0;
7295    psa_verify_hash_interruptible_operation_t operation =
7296        psa_verify_hash_interruptible_operation_init();
7297
7298    PSA_ASSERT(psa_crypto_init());
7299
7300    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_VERIFY_HASH);
7301    psa_set_key_algorithm(&attributes, alg);
7302    psa_set_key_type(&attributes, key_type);
7303
7304    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
7305                              &key));
7306
7307    psa_interruptible_set_max_ops(max_ops);
7308
7309    interruptible_signverify_get_minmax_completes(max_ops,
7310                                                  expected_complete_status,
7311                                                  &min_completes,
7312                                                  &max_completes);
7313
7314    num_ops_prior = psa_verify_hash_get_num_ops(&operation);
7315    TEST_ASSERT(num_ops_prior == 0);
7316
7317    /* Start verification. */
7318    actual_status = psa_verify_hash_start(&operation, key, alg,
7319                                          hash_data->x, hash_data->len,
7320                                          signature_data->x,
7321                                          signature_data->len);
7322
7323    TEST_EQUAL(actual_status, expected_start_status);
7324
7325    if (expected_start_status != PSA_SUCCESS) {
7326        /* Emulate poor application code, and call complete anyway, even though
7327         * start failed. */
7328        actual_status = psa_verify_hash_complete(&operation);
7329
7330        TEST_EQUAL(actual_status, PSA_ERROR_BAD_STATE);
7331
7332        /* Test that calling start again after failure also causes BAD_STATE. */
7333        actual_status = psa_verify_hash_start(&operation, key, alg,
7334                                              hash_data->x, hash_data->len,
7335                                              signature_data->x,
7336                                              signature_data->len);
7337
7338        TEST_EQUAL(actual_status, PSA_ERROR_BAD_STATE);
7339    }
7340
7341    num_ops_prior = psa_verify_hash_get_num_ops(&operation);
7342    TEST_ASSERT(num_ops_prior == 0);
7343
7344    /* Continue performing the signature until complete. */
7345    do {
7346        actual_status = psa_verify_hash_complete(&operation);
7347
7348        num_completes++;
7349
7350        if (actual_status == PSA_SUCCESS ||
7351            actual_status == PSA_OPERATION_INCOMPLETE) {
7352            num_ops = psa_verify_hash_get_num_ops(&operation);
7353            /* We are asserting here that every complete makes progress
7354             * (completes some ops), which is true of the internal
7355             * implementation and probably any implementation, however this is
7356             * not mandated by the PSA specification. */
7357            TEST_ASSERT(num_ops > num_ops_prior);
7358
7359            num_ops_prior = num_ops;
7360        }
7361    } while (actual_status == PSA_OPERATION_INCOMPLETE);
7362
7363    TEST_EQUAL(actual_status, expected_complete_status);
7364
7365    /* Check that another complete returns BAD_STATE. */
7366    actual_status = psa_verify_hash_complete(&operation);
7367    TEST_EQUAL(actual_status, PSA_ERROR_BAD_STATE);
7368
7369    TEST_LE_U(min_completes, num_completes);
7370    TEST_LE_U(num_completes, max_completes);
7371
7372    PSA_ASSERT(psa_verify_hash_abort(&operation));
7373
7374    num_ops = psa_verify_hash_get_num_ops(&operation);
7375    TEST_ASSERT(num_ops == 0);
7376
7377exit:
7378    psa_reset_key_attributes(&attributes);
7379    psa_destroy_key(key);
7380    PSA_DONE();
7381}
7382/* END_CASE */
7383
7384/* BEGIN_CASE depends_on:MBEDTLS_ECP_RESTARTABLE */
7385/**
7386 * interruptible_signverify_hash_state_test() test intentions:
7387 *
7388 * Note: This test can currently only handle ECDSA.
7389 *
7390 * 1. Test that calling the various interruptible sign and verify hash functions
7391 *    in incorrect orders returns BAD_STATE errors.
7392 */
7393void interruptible_signverify_hash_state_test(int key_type_arg,
7394                                              data_t *key_data, int alg_arg, data_t *input_data)
7395{
7396    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
7397    psa_key_type_t key_type = key_type_arg;
7398    psa_algorithm_t alg = alg_arg;
7399    size_t key_bits;
7400    unsigned char *signature = NULL;
7401    size_t signature_size;
7402    size_t signature_length = 0xdeadbeef;
7403    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
7404    psa_sign_hash_interruptible_operation_t sign_operation =
7405        psa_sign_hash_interruptible_operation_init();
7406    psa_verify_hash_interruptible_operation_t verify_operation =
7407        psa_verify_hash_interruptible_operation_init();
7408
7409    PSA_ASSERT(psa_crypto_init());
7410
7411    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH |
7412                            PSA_KEY_USAGE_VERIFY_HASH);
7413    psa_set_key_algorithm(&attributes, alg);
7414    psa_set_key_type(&attributes, key_type);
7415
7416    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
7417                              &key));
7418    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
7419    key_bits = psa_get_key_bits(&attributes);
7420
7421    /* Allocate a buffer which has the size advertised by the
7422     * library. */
7423    signature_size = PSA_SIGN_OUTPUT_SIZE(key_type,
7424                                          key_bits, alg);
7425    TEST_ASSERT(signature_size != 0);
7426    TEST_LE_U(signature_size, PSA_SIGNATURE_MAX_SIZE);
7427    ASSERT_ALLOC(signature, signature_size);
7428
7429    psa_interruptible_set_max_ops(PSA_INTERRUPTIBLE_MAX_OPS_UNLIMITED);
7430
7431    /* --- Attempt completes prior to starts --- */
7432    TEST_EQUAL(psa_sign_hash_complete(&sign_operation, signature,
7433                                      signature_size,
7434                                      &signature_length),
7435               PSA_ERROR_BAD_STATE);
7436
7437    PSA_ASSERT(psa_sign_hash_abort(&sign_operation));
7438
7439    TEST_EQUAL(psa_verify_hash_complete(&verify_operation),
7440               PSA_ERROR_BAD_STATE);
7441
7442    PSA_ASSERT(psa_verify_hash_abort(&verify_operation));
7443
7444    /* --- Aborts in all other places. --- */
7445    psa_sign_hash_abort(&sign_operation);
7446
7447    PSA_ASSERT(psa_sign_hash_start(&sign_operation, key, alg,
7448                                   input_data->x, input_data->len));
7449
7450    PSA_ASSERT(psa_sign_hash_abort(&sign_operation));
7451
7452    psa_interruptible_set_max_ops(1);
7453
7454    PSA_ASSERT(psa_sign_hash_start(&sign_operation, key, alg,
7455                                   input_data->x, input_data->len));
7456
7457    TEST_EQUAL(psa_sign_hash_complete(&sign_operation, signature,
7458                                      signature_size,
7459                                      &signature_length),
7460               PSA_OPERATION_INCOMPLETE);
7461
7462    PSA_ASSERT(psa_sign_hash_abort(&sign_operation));
7463
7464    psa_interruptible_set_max_ops(PSA_INTERRUPTIBLE_MAX_OPS_UNLIMITED);
7465
7466    PSA_ASSERT(psa_sign_hash_start(&sign_operation, key, alg,
7467                                   input_data->x, input_data->len));
7468
7469    PSA_ASSERT(psa_sign_hash_complete(&sign_operation, signature,
7470                                      signature_size,
7471                                      &signature_length));
7472
7473    PSA_ASSERT(psa_sign_hash_abort(&sign_operation));
7474
7475    PSA_ASSERT(psa_verify_hash_abort(&verify_operation));
7476
7477    PSA_ASSERT(psa_verify_hash_start(&verify_operation, key, alg,
7478                                     input_data->x, input_data->len,
7479                                     signature, signature_length));
7480
7481    PSA_ASSERT(psa_verify_hash_abort(&verify_operation));
7482
7483    psa_interruptible_set_max_ops(1);
7484
7485    PSA_ASSERT(psa_verify_hash_start(&verify_operation, key, alg,
7486                                     input_data->x, input_data->len,
7487                                     signature, signature_length));
7488
7489    TEST_EQUAL(psa_verify_hash_complete(&verify_operation),
7490               PSA_OPERATION_INCOMPLETE);
7491
7492    PSA_ASSERT(psa_verify_hash_abort(&verify_operation));
7493
7494    psa_interruptible_set_max_ops(PSA_INTERRUPTIBLE_MAX_OPS_UNLIMITED);
7495
7496    PSA_ASSERT(psa_verify_hash_start(&verify_operation, key, alg,
7497                                     input_data->x, input_data->len,
7498                                     signature, signature_length));
7499
7500    PSA_ASSERT(psa_verify_hash_complete(&verify_operation));
7501
7502    PSA_ASSERT(psa_verify_hash_abort(&verify_operation));
7503
7504    /* --- Attempt double starts. --- */
7505
7506    PSA_ASSERT(psa_sign_hash_start(&sign_operation, key, alg,
7507                                   input_data->x, input_data->len));
7508
7509    TEST_EQUAL(psa_sign_hash_start(&sign_operation, key, alg,
7510                                   input_data->x, input_data->len),
7511               PSA_ERROR_BAD_STATE);
7512
7513    PSA_ASSERT(psa_sign_hash_abort(&sign_operation));
7514
7515    PSA_ASSERT(psa_verify_hash_start(&verify_operation, key, alg,
7516                                     input_data->x, input_data->len,
7517                                     signature, signature_length));
7518
7519    TEST_EQUAL(psa_verify_hash_start(&verify_operation, key, alg,
7520                                     input_data->x, input_data->len,
7521                                     signature, signature_length),
7522               PSA_ERROR_BAD_STATE);
7523
7524    PSA_ASSERT(psa_verify_hash_abort(&verify_operation));
7525
7526exit:
7527    /*
7528     * Key attributes may have been returned by psa_get_key_attributes()
7529     * thus reset them as required.
7530     */
7531    psa_reset_key_attributes(&attributes);
7532
7533    psa_destroy_key(key);
7534    mbedtls_free(signature);
7535    PSA_DONE();
7536}
7537/* END_CASE */
7538
7539/* BEGIN_CASE depends_on:MBEDTLS_ECP_RESTARTABLE */
7540/**
7541 * interruptible_signverify_hash_edgecase_tests() test intentions:
7542 *
7543 * Note: This test can currently only handle ECDSA.
7544 *
7545 * 1. Test various edge cases in the interruptible sign and verify hash
7546 *    interfaces.
7547 */
7548void interruptible_signverify_hash_edgecase_tests(int key_type_arg,
7549                                                  data_t *key_data, int alg_arg, data_t *input_data)
7550{
7551    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
7552    psa_key_type_t key_type = key_type_arg;
7553    psa_algorithm_t alg = alg_arg;
7554    size_t key_bits;
7555    unsigned char *signature = NULL;
7556    size_t signature_size;
7557    size_t signature_length = 0xdeadbeef;
7558    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
7559    uint8_t *input_buffer = NULL;
7560    psa_sign_hash_interruptible_operation_t sign_operation =
7561        psa_sign_hash_interruptible_operation_init();
7562    psa_verify_hash_interruptible_operation_t verify_operation =
7563        psa_verify_hash_interruptible_operation_init();
7564
7565    PSA_ASSERT(psa_crypto_init());
7566
7567    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH |
7568                            PSA_KEY_USAGE_VERIFY_HASH);
7569    psa_set_key_algorithm(&attributes, alg);
7570    psa_set_key_type(&attributes, key_type);
7571
7572    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
7573                              &key));
7574    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
7575    key_bits = psa_get_key_bits(&attributes);
7576
7577    /* Allocate a buffer which has the size advertised by the
7578     * library. */
7579    signature_size = PSA_SIGN_OUTPUT_SIZE(key_type,
7580                                          key_bits, alg);
7581    TEST_ASSERT(signature_size != 0);
7582    TEST_LE_U(signature_size, PSA_SIGNATURE_MAX_SIZE);
7583    ASSERT_ALLOC(signature, signature_size);
7584
7585    /* --- Change function inputs mid run, to cause an error (sign only,
7586     *     verify passes all inputs to start. --- */
7587
7588    psa_interruptible_set_max_ops(1);
7589
7590    PSA_ASSERT(psa_sign_hash_start(&sign_operation, key, alg,
7591                                   input_data->x, input_data->len));
7592
7593    TEST_EQUAL(psa_sign_hash_complete(&sign_operation, signature,
7594                                      signature_size,
7595                                      &signature_length),
7596               PSA_OPERATION_INCOMPLETE);
7597
7598    TEST_EQUAL(psa_sign_hash_complete(&sign_operation, signature,
7599                                      0,
7600                                      &signature_length),
7601               PSA_ERROR_BUFFER_TOO_SMALL);
7602
7603    /* And test that this invalidates the operation. */
7604    TEST_EQUAL(psa_sign_hash_complete(&sign_operation, signature,
7605                                      0,
7606                                      &signature_length),
7607               PSA_ERROR_BAD_STATE);
7608
7609    PSA_ASSERT(psa_sign_hash_abort(&sign_operation));
7610
7611    /* Trash the hash buffer in between start and complete, to ensure
7612     * no reliance on external buffers. */
7613    psa_interruptible_set_max_ops(PSA_INTERRUPTIBLE_MAX_OPS_UNLIMITED);
7614
7615    input_buffer = mbedtls_calloc(1, input_data->len);
7616    TEST_ASSERT(input_buffer != NULL);
7617
7618    memcpy(input_buffer, input_data->x, input_data->len);
7619
7620    PSA_ASSERT(psa_sign_hash_start(&sign_operation, key, alg,
7621                                   input_buffer, input_data->len));
7622
7623    memset(input_buffer, '!', input_data->len);
7624    mbedtls_free(input_buffer);
7625    input_buffer = NULL;
7626
7627    PSA_ASSERT(psa_sign_hash_complete(&sign_operation, signature,
7628                                      signature_size,
7629                                      &signature_length));
7630
7631    PSA_ASSERT(psa_sign_hash_abort(&sign_operation));
7632
7633    input_buffer = mbedtls_calloc(1, input_data->len);
7634    TEST_ASSERT(input_buffer != NULL);
7635
7636    memcpy(input_buffer, input_data->x, input_data->len);
7637
7638    PSA_ASSERT(psa_verify_hash_start(&verify_operation, key, alg,
7639                                     input_buffer, input_data->len,
7640                                     signature, signature_length));
7641
7642    memset(input_buffer, '!', input_data->len);
7643    mbedtls_free(input_buffer);
7644    input_buffer = NULL;
7645
7646    PSA_ASSERT(psa_verify_hash_complete(&verify_operation));
7647
7648    PSA_ASSERT(psa_verify_hash_abort(&verify_operation));
7649
7650exit:
7651    /*
7652     * Key attributes may have been returned by psa_get_key_attributes()
7653     * thus reset them as required.
7654     */
7655    psa_reset_key_attributes(&attributes);
7656
7657    psa_destroy_key(key);
7658    mbedtls_free(signature);
7659    PSA_DONE();
7660}
7661/* END_CASE */
7662
7663/* BEGIN_CASE depends_on:MBEDTLS_ECP_RESTARTABLE */
7664/**
7665 * interruptible_signverify_hash_ops_tests() test intentions:
7666 *
7667 * Note: This test can currently only handle ECDSA.
7668 *
7669 * 1. Test that setting max ops is reflected in both interruptible sign and
7670 *    verify hash
7671 * 2. Test that changing the value of max_ops to unlimited during an operation
7672 *    causes that operation to complete in the next call.
7673 *
7674 * 3. Test that calling get_num_ops() between complete calls gives the same
7675 *    result as calling get_num_ops() once at the end of the operation.
7676 */
7677void interruptible_signverify_hash_ops_tests(int key_type_arg,
7678                                             data_t *key_data, int alg_arg,
7679                                             data_t *input_data)
7680{
7681    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
7682    psa_key_type_t key_type = key_type_arg;
7683    psa_algorithm_t alg = alg_arg;
7684    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
7685    size_t key_bits;
7686    unsigned char *signature = NULL;
7687    size_t signature_size;
7688    size_t signature_length = 0xdeadbeef;
7689    uint32_t num_ops = 0;
7690    psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
7691
7692    psa_sign_hash_interruptible_operation_t sign_operation =
7693        psa_sign_hash_interruptible_operation_init();
7694    psa_verify_hash_interruptible_operation_t verify_operation =
7695        psa_verify_hash_interruptible_operation_init();
7696
7697    PSA_ASSERT(psa_crypto_init());
7698
7699    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH |
7700                            PSA_KEY_USAGE_VERIFY_HASH);
7701    psa_set_key_algorithm(&attributes, alg);
7702    psa_set_key_type(&attributes, key_type);
7703
7704    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len, &key));
7705    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
7706    key_bits = psa_get_key_bits(&attributes);
7707
7708    /* Allocate a buffer which has the size advertised by the
7709     * library. */
7710    signature_size = PSA_SIGN_OUTPUT_SIZE(key_type, key_bits, alg);
7711
7712    TEST_ASSERT(signature_size != 0);
7713    TEST_LE_U(signature_size, PSA_SIGNATURE_MAX_SIZE);
7714    ASSERT_ALLOC(signature, signature_size);
7715
7716    /* Check that default max ops gets set if we don't set it. */
7717    PSA_ASSERT(psa_sign_hash_start(&sign_operation, key, alg,
7718                                   input_data->x, input_data->len));
7719
7720    TEST_EQUAL(psa_interruptible_get_max_ops(),
7721               PSA_INTERRUPTIBLE_MAX_OPS_UNLIMITED);
7722
7723    PSA_ASSERT(psa_sign_hash_abort(&sign_operation));
7724
7725    PSA_ASSERT(psa_verify_hash_start(&verify_operation, key, alg,
7726                                     input_data->x, input_data->len,
7727                                     signature, signature_size));
7728
7729    TEST_EQUAL(psa_interruptible_get_max_ops(),
7730               PSA_INTERRUPTIBLE_MAX_OPS_UNLIMITED);
7731
7732    PSA_ASSERT(psa_verify_hash_abort(&verify_operation));
7733
7734    /* Check that max ops gets set properly. */
7735
7736    psa_interruptible_set_max_ops(0xbeef);
7737
7738    TEST_EQUAL(psa_interruptible_get_max_ops(), 0xbeef);
7739
7740    /* --- Ensure changing the max ops mid operation works (operation should
7741     *     complete successfully after setting max ops to unlimited --- */
7742    psa_interruptible_set_max_ops(1);
7743
7744    PSA_ASSERT(psa_sign_hash_start(&sign_operation, key, alg,
7745                                   input_data->x, input_data->len));
7746
7747    TEST_EQUAL(psa_sign_hash_complete(&sign_operation, signature,
7748                                      signature_size,
7749                                      &signature_length),
7750               PSA_OPERATION_INCOMPLETE);
7751
7752    psa_interruptible_set_max_ops(PSA_INTERRUPTIBLE_MAX_OPS_UNLIMITED);
7753
7754    PSA_ASSERT(psa_sign_hash_complete(&sign_operation, signature,
7755                                      signature_size,
7756                                      &signature_length));
7757
7758    PSA_ASSERT(psa_sign_hash_abort(&sign_operation));
7759
7760    psa_interruptible_set_max_ops(1);
7761
7762    PSA_ASSERT(psa_verify_hash_start(&verify_operation, key, alg,
7763                                     input_data->x, input_data->len,
7764                                     signature, signature_length));
7765
7766    TEST_EQUAL(psa_verify_hash_complete(&verify_operation),
7767               PSA_OPERATION_INCOMPLETE);
7768
7769    psa_interruptible_set_max_ops(PSA_INTERRUPTIBLE_MAX_OPS_UNLIMITED);
7770
7771    PSA_ASSERT(psa_verify_hash_complete(&verify_operation));
7772
7773    PSA_ASSERT(psa_verify_hash_abort(&verify_operation));
7774
7775    /* --- Test that not calling get_num_ops inbetween complete calls does not
7776     *     result in lost ops. ---*/
7777
7778    psa_interruptible_set_max_ops(1);
7779
7780    PSA_ASSERT(psa_sign_hash_start(&sign_operation, key, alg,
7781                                   input_data->x, input_data->len));
7782
7783    /* Continue performing the signature until complete. */
7784    do {
7785        status = psa_sign_hash_complete(&sign_operation, signature,
7786                                        signature_size,
7787                                        &signature_length);
7788
7789        num_ops = psa_sign_hash_get_num_ops(&sign_operation);
7790
7791    } while (status == PSA_OPERATION_INCOMPLETE);
7792
7793    PSA_ASSERT(status);
7794
7795    PSA_ASSERT(psa_sign_hash_abort(&sign_operation));
7796
7797    PSA_ASSERT(psa_sign_hash_start(&sign_operation, key, alg,
7798                                   input_data->x, input_data->len));
7799
7800    /* Continue performing the signature until complete. */
7801    do {
7802        status = psa_sign_hash_complete(&sign_operation, signature,
7803                                        signature_size,
7804                                        &signature_length);
7805    } while (status == PSA_OPERATION_INCOMPLETE);
7806
7807    PSA_ASSERT(status);
7808
7809    TEST_EQUAL(num_ops, psa_sign_hash_get_num_ops(&sign_operation));
7810
7811    PSA_ASSERT(psa_sign_hash_abort(&sign_operation));
7812
7813    PSA_ASSERT(psa_verify_hash_start(&verify_operation, key, alg,
7814                                     input_data->x, input_data->len,
7815                                     signature, signature_length));
7816
7817    /* Continue performing the verification until complete. */
7818    do {
7819        status = psa_verify_hash_complete(&verify_operation);
7820
7821        num_ops = psa_verify_hash_get_num_ops(&verify_operation);
7822
7823    } while (status == PSA_OPERATION_INCOMPLETE);
7824
7825    PSA_ASSERT(status);
7826
7827    PSA_ASSERT(psa_verify_hash_abort(&verify_operation));
7828
7829    PSA_ASSERT(psa_verify_hash_start(&verify_operation, key, alg,
7830                                     input_data->x, input_data->len,
7831                                     signature, signature_length));
7832
7833    /* Continue performing the verification until complete. */
7834    do {
7835        status = psa_verify_hash_complete(&verify_operation);
7836
7837    } while (status == PSA_OPERATION_INCOMPLETE);
7838
7839    PSA_ASSERT(status);
7840
7841    TEST_EQUAL(num_ops, psa_verify_hash_get_num_ops(&verify_operation));
7842
7843    PSA_ASSERT(psa_verify_hash_abort(&verify_operation));
7844
7845exit:
7846    /*
7847     * Key attributes may have been returned by psa_get_key_attributes()
7848     * thus reset them as required.
7849     */
7850    psa_reset_key_attributes(&attributes);
7851
7852    psa_destroy_key(key);
7853    mbedtls_free(signature);
7854    PSA_DONE();
7855}
7856/* END_CASE */
7857
7858/* BEGIN_CASE */
7859void sign_message_deterministic(int key_type_arg,
7860                                data_t *key_data,
7861                                int alg_arg,
7862                                data_t *input_data,
7863                                data_t *output_data)
7864{
7865    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
7866    psa_key_type_t key_type = key_type_arg;
7867    psa_algorithm_t alg = alg_arg;
7868    size_t key_bits;
7869    unsigned char *signature = NULL;
7870    size_t signature_size;
7871    size_t signature_length = 0xdeadbeef;
7872    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
7873
7874    PSA_ASSERT(psa_crypto_init());
7875
7876    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_MESSAGE);
7877    psa_set_key_algorithm(&attributes, alg);
7878    psa_set_key_type(&attributes, key_type);
7879
7880    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
7881                              &key));
7882    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
7883    key_bits = psa_get_key_bits(&attributes);
7884
7885    signature_size = PSA_SIGN_OUTPUT_SIZE(key_type, key_bits, alg);
7886    TEST_ASSERT(signature_size != 0);
7887    TEST_LE_U(signature_size, PSA_SIGNATURE_MAX_SIZE);
7888    ASSERT_ALLOC(signature, signature_size);
7889
7890    PSA_ASSERT(psa_sign_message(key, alg,
7891                                input_data->x, input_data->len,
7892                                signature, signature_size,
7893                                &signature_length));
7894
7895    ASSERT_COMPARE(output_data->x, output_data->len,
7896                   signature, signature_length);
7897
7898exit:
7899    psa_reset_key_attributes(&attributes);
7900
7901    psa_destroy_key(key);
7902    mbedtls_free(signature);
7903    PSA_DONE();
7904
7905}
7906/* END_CASE */
7907
7908/* BEGIN_CASE */
7909void sign_message_fail(int key_type_arg,
7910                       data_t *key_data,
7911                       int alg_arg,
7912                       data_t *input_data,
7913                       int signature_size_arg,
7914                       int expected_status_arg)
7915{
7916    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
7917    psa_key_type_t key_type = key_type_arg;
7918    psa_algorithm_t alg = alg_arg;
7919    size_t signature_size = signature_size_arg;
7920    psa_status_t actual_status;
7921    psa_status_t expected_status = expected_status_arg;
7922    unsigned char *signature = NULL;
7923    size_t signature_length = 0xdeadbeef;
7924    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
7925
7926    ASSERT_ALLOC(signature, signature_size);
7927
7928    PSA_ASSERT(psa_crypto_init());
7929
7930    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_MESSAGE);
7931    psa_set_key_algorithm(&attributes, alg);
7932    psa_set_key_type(&attributes, key_type);
7933
7934    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
7935                              &key));
7936
7937    actual_status = psa_sign_message(key, alg,
7938                                     input_data->x, input_data->len,
7939                                     signature, signature_size,
7940                                     &signature_length);
7941    TEST_EQUAL(actual_status, expected_status);
7942    /* The value of *signature_length is unspecified on error, but
7943     * whatever it is, it should be less than signature_size, so that
7944     * if the caller tries to read *signature_length bytes without
7945     * checking the error code then they don't overflow a buffer. */
7946    TEST_LE_U(signature_length, signature_size);
7947
7948exit:
7949    psa_reset_key_attributes(&attributes);
7950    psa_destroy_key(key);
7951    mbedtls_free(signature);
7952    PSA_DONE();
7953}
7954/* END_CASE */
7955
7956/* BEGIN_CASE */
7957void sign_verify_message(int key_type_arg,
7958                         data_t *key_data,
7959                         int alg_arg,
7960                         data_t *input_data)
7961{
7962    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
7963    psa_key_type_t key_type = key_type_arg;
7964    psa_algorithm_t alg = alg_arg;
7965    size_t key_bits;
7966    unsigned char *signature = NULL;
7967    size_t signature_size;
7968    size_t signature_length = 0xdeadbeef;
7969    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
7970
7971    PSA_ASSERT(psa_crypto_init());
7972
7973    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_MESSAGE |
7974                            PSA_KEY_USAGE_VERIFY_MESSAGE);
7975    psa_set_key_algorithm(&attributes, alg);
7976    psa_set_key_type(&attributes, key_type);
7977
7978    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
7979                              &key));
7980    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
7981    key_bits = psa_get_key_bits(&attributes);
7982
7983    signature_size = PSA_SIGN_OUTPUT_SIZE(key_type, key_bits, alg);
7984    TEST_ASSERT(signature_size != 0);
7985    TEST_LE_U(signature_size, PSA_SIGNATURE_MAX_SIZE);
7986    ASSERT_ALLOC(signature, signature_size);
7987
7988    PSA_ASSERT(psa_sign_message(key, alg,
7989                                input_data->x, input_data->len,
7990                                signature, signature_size,
7991                                &signature_length));
7992    TEST_LE_U(signature_length, signature_size);
7993    TEST_ASSERT(signature_length > 0);
7994
7995    PSA_ASSERT(psa_verify_message(key, alg,
7996                                  input_data->x, input_data->len,
7997                                  signature, signature_length));
7998
7999    if (input_data->len != 0) {
8000        /* Flip a bit in the input and verify that the signature is now
8001         * detected as invalid. Flip a bit at the beginning, not at the end,
8002         * because ECDSA may ignore the last few bits of the input. */
8003        input_data->x[0] ^= 1;
8004        TEST_EQUAL(psa_verify_message(key, alg,
8005                                      input_data->x, input_data->len,
8006                                      signature, signature_length),
8007                   PSA_ERROR_INVALID_SIGNATURE);
8008    }
8009
8010exit:
8011    psa_reset_key_attributes(&attributes);
8012
8013    psa_destroy_key(key);
8014    mbedtls_free(signature);
8015    PSA_DONE();
8016}
8017/* END_CASE */
8018
8019/* BEGIN_CASE */
8020void verify_message(int key_type_arg,
8021                    data_t *key_data,
8022                    int alg_arg,
8023                    data_t *input_data,
8024                    data_t *signature_data)
8025{
8026    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
8027    psa_key_type_t key_type = key_type_arg;
8028    psa_algorithm_t alg = alg_arg;
8029    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
8030
8031    TEST_LE_U(signature_data->len, PSA_SIGNATURE_MAX_SIZE);
8032
8033    PSA_ASSERT(psa_crypto_init());
8034
8035    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_VERIFY_MESSAGE);
8036    psa_set_key_algorithm(&attributes, alg);
8037    psa_set_key_type(&attributes, key_type);
8038
8039    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
8040                              &key));
8041
8042    PSA_ASSERT(psa_verify_message(key, alg,
8043                                  input_data->x, input_data->len,
8044                                  signature_data->x, signature_data->len));
8045
8046exit:
8047    psa_reset_key_attributes(&attributes);
8048    psa_destroy_key(key);
8049    PSA_DONE();
8050}
8051/* END_CASE */
8052
8053/* BEGIN_CASE */
8054void verify_message_fail(int key_type_arg,
8055                         data_t *key_data,
8056                         int alg_arg,
8057                         data_t *hash_data,
8058                         data_t *signature_data,
8059                         int expected_status_arg)
8060{
8061    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
8062    psa_key_type_t key_type = key_type_arg;
8063    psa_algorithm_t alg = alg_arg;
8064    psa_status_t actual_status;
8065    psa_status_t expected_status = expected_status_arg;
8066    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
8067
8068    PSA_ASSERT(psa_crypto_init());
8069
8070    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_VERIFY_MESSAGE);
8071    psa_set_key_algorithm(&attributes, alg);
8072    psa_set_key_type(&attributes, key_type);
8073
8074    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
8075                              &key));
8076
8077    actual_status = psa_verify_message(key, alg,
8078                                       hash_data->x, hash_data->len,
8079                                       signature_data->x,
8080                                       signature_data->len);
8081    TEST_EQUAL(actual_status, expected_status);
8082
8083exit:
8084    psa_reset_key_attributes(&attributes);
8085    psa_destroy_key(key);
8086    PSA_DONE();
8087}
8088/* END_CASE */
8089
8090/* BEGIN_CASE */
8091void asymmetric_encrypt(int key_type_arg,
8092                        data_t *key_data,
8093                        int alg_arg,
8094                        data_t *input_data,
8095                        data_t *label,
8096                        int expected_output_length_arg,
8097                        int expected_status_arg)
8098{
8099    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
8100    psa_key_type_t key_type = key_type_arg;
8101    psa_algorithm_t alg = alg_arg;
8102    size_t expected_output_length = expected_output_length_arg;
8103    size_t key_bits;
8104    unsigned char *output = NULL;
8105    size_t output_size;
8106    size_t output_length = ~0;
8107    psa_status_t actual_status;
8108    psa_status_t expected_status = expected_status_arg;
8109    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
8110
8111    PSA_ASSERT(psa_crypto_init());
8112
8113    /* Import the key */
8114    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
8115    psa_set_key_algorithm(&attributes, alg);
8116    psa_set_key_type(&attributes, key_type);
8117    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
8118                              &key));
8119
8120    /* Determine the maximum output length */
8121    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
8122    key_bits = psa_get_key_bits(&attributes);
8123
8124    output_size = PSA_ASYMMETRIC_ENCRYPT_OUTPUT_SIZE(key_type, key_bits, alg);
8125    TEST_LE_U(output_size, PSA_ASYMMETRIC_ENCRYPT_OUTPUT_MAX_SIZE);
8126    ASSERT_ALLOC(output, output_size);
8127
8128    /* Encrypt the input */
8129    actual_status = psa_asymmetric_encrypt(key, alg,
8130                                           input_data->x, input_data->len,
8131                                           label->x, label->len,
8132                                           output, output_size,
8133                                           &output_length);
8134    TEST_EQUAL(actual_status, expected_status);
8135    if (actual_status == PSA_SUCCESS) {
8136        TEST_EQUAL(output_length, expected_output_length);
8137    } else {
8138        TEST_LE_U(output_length, output_size);
8139    }
8140
8141    /* If the label is empty, the test framework puts a non-null pointer
8142     * in label->x. Test that a null pointer works as well. */
8143    if (label->len == 0) {
8144        output_length = ~0;
8145        if (output_size != 0) {
8146            memset(output, 0, output_size);
8147        }
8148        actual_status = psa_asymmetric_encrypt(key, alg,
8149                                               input_data->x, input_data->len,
8150                                               NULL, label->len,
8151                                               output, output_size,
8152                                               &output_length);
8153        TEST_EQUAL(actual_status, expected_status);
8154        if (actual_status == PSA_SUCCESS) {
8155            TEST_EQUAL(output_length, expected_output_length);
8156        } else {
8157            TEST_LE_U(output_length, output_size);
8158        }
8159    }
8160
8161exit:
8162    /*
8163     * Key attributes may have been returned by psa_get_key_attributes()
8164     * thus reset them as required.
8165     */
8166    psa_reset_key_attributes(&attributes);
8167
8168    psa_destroy_key(key);
8169    mbedtls_free(output);
8170    PSA_DONE();
8171}
8172/* END_CASE */
8173
8174/* BEGIN_CASE */
8175void asymmetric_encrypt_decrypt(int key_type_arg,
8176                                data_t *key_data,
8177                                int alg_arg,
8178                                data_t *input_data,
8179                                data_t *label)
8180{
8181    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
8182    psa_key_type_t key_type = key_type_arg;
8183    psa_algorithm_t alg = alg_arg;
8184    size_t key_bits;
8185    unsigned char *output = NULL;
8186    size_t output_size;
8187    size_t output_length = ~0;
8188    unsigned char *output2 = NULL;
8189    size_t output2_size;
8190    size_t output2_length = ~0;
8191    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
8192
8193    PSA_ASSERT(psa_crypto_init());
8194
8195    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT);
8196    psa_set_key_algorithm(&attributes, alg);
8197    psa_set_key_type(&attributes, key_type);
8198
8199    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
8200                              &key));
8201
8202    /* Determine the maximum ciphertext length */
8203    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
8204    key_bits = psa_get_key_bits(&attributes);
8205
8206    output_size = PSA_ASYMMETRIC_ENCRYPT_OUTPUT_SIZE(key_type, key_bits, alg);
8207    TEST_LE_U(output_size, PSA_ASYMMETRIC_ENCRYPT_OUTPUT_MAX_SIZE);
8208    ASSERT_ALLOC(output, output_size);
8209
8210    output2_size = input_data->len;
8211    TEST_LE_U(output2_size,
8212              PSA_ASYMMETRIC_DECRYPT_OUTPUT_SIZE(key_type, key_bits, alg));
8213    TEST_LE_U(output2_size, PSA_ASYMMETRIC_DECRYPT_OUTPUT_MAX_SIZE);
8214    ASSERT_ALLOC(output2, output2_size);
8215
8216    /* We test encryption by checking that encrypt-then-decrypt gives back
8217     * the original plaintext because of the non-optional random
8218     * part of encryption process which prevents using fixed vectors. */
8219    PSA_ASSERT(psa_asymmetric_encrypt(key, alg,
8220                                      input_data->x, input_data->len,
8221                                      label->x, label->len,
8222                                      output, output_size,
8223                                      &output_length));
8224    /* We don't know what ciphertext length to expect, but check that
8225     * it looks sensible. */
8226    TEST_LE_U(output_length, output_size);
8227
8228    PSA_ASSERT(psa_asymmetric_decrypt(key, alg,
8229                                      output, output_length,
8230                                      label->x, label->len,
8231                                      output2, output2_size,
8232                                      &output2_length));
8233    ASSERT_COMPARE(input_data->x, input_data->len,
8234                   output2, output2_length);
8235
8236exit:
8237    /*
8238     * Key attributes may have been returned by psa_get_key_attributes()
8239     * thus reset them as required.
8240     */
8241    psa_reset_key_attributes(&attributes);
8242
8243    psa_destroy_key(key);
8244    mbedtls_free(output);
8245    mbedtls_free(output2);
8246    PSA_DONE();
8247}
8248/* END_CASE */
8249
8250/* BEGIN_CASE */
8251void asymmetric_decrypt(int key_type_arg,
8252                        data_t *key_data,
8253                        int alg_arg,
8254                        data_t *input_data,
8255                        data_t *label,
8256                        data_t *expected_data)
8257{
8258    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
8259    psa_key_type_t key_type = key_type_arg;
8260    psa_algorithm_t alg = alg_arg;
8261    size_t key_bits;
8262    unsigned char *output = NULL;
8263    size_t output_size = 0;
8264    size_t output_length = ~0;
8265    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
8266
8267    PSA_ASSERT(psa_crypto_init());
8268
8269    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DECRYPT);
8270    psa_set_key_algorithm(&attributes, alg);
8271    psa_set_key_type(&attributes, key_type);
8272
8273    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
8274                              &key));
8275
8276    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
8277    key_bits = psa_get_key_bits(&attributes);
8278
8279    /* Determine the maximum ciphertext length */
8280    output_size = PSA_ASYMMETRIC_DECRYPT_OUTPUT_SIZE(key_type, key_bits, alg);
8281    TEST_LE_U(output_size, PSA_ASYMMETRIC_DECRYPT_OUTPUT_MAX_SIZE);
8282    ASSERT_ALLOC(output, output_size);
8283
8284    PSA_ASSERT(psa_asymmetric_decrypt(key, alg,
8285                                      input_data->x, input_data->len,
8286                                      label->x, label->len,
8287                                      output,
8288                                      output_size,
8289                                      &output_length));
8290    ASSERT_COMPARE(expected_data->x, expected_data->len,
8291                   output, output_length);
8292
8293    /* If the label is empty, the test framework puts a non-null pointer
8294     * in label->x. Test that a null pointer works as well. */
8295    if (label->len == 0) {
8296        output_length = ~0;
8297        if (output_size != 0) {
8298            memset(output, 0, output_size);
8299        }
8300        PSA_ASSERT(psa_asymmetric_decrypt(key, alg,
8301                                          input_data->x, input_data->len,
8302                                          NULL, label->len,
8303                                          output,
8304                                          output_size,
8305                                          &output_length));
8306        ASSERT_COMPARE(expected_data->x, expected_data->len,
8307                       output, output_length);
8308    }
8309
8310exit:
8311    psa_reset_key_attributes(&attributes);
8312    psa_destroy_key(key);
8313    mbedtls_free(output);
8314    PSA_DONE();
8315}
8316/* END_CASE */
8317
8318/* BEGIN_CASE */
8319void asymmetric_decrypt_fail(int key_type_arg,
8320                             data_t *key_data,
8321                             int alg_arg,
8322                             data_t *input_data,
8323                             data_t *label,
8324                             int output_size_arg,
8325                             int expected_status_arg)
8326{
8327    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
8328    psa_key_type_t key_type = key_type_arg;
8329    psa_algorithm_t alg = alg_arg;
8330    unsigned char *output = NULL;
8331    size_t output_size = output_size_arg;
8332    size_t output_length = ~0;
8333    psa_status_t actual_status;
8334    psa_status_t expected_status = expected_status_arg;
8335    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
8336
8337    ASSERT_ALLOC(output, output_size);
8338
8339    PSA_ASSERT(psa_crypto_init());
8340
8341    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DECRYPT);
8342    psa_set_key_algorithm(&attributes, alg);
8343    psa_set_key_type(&attributes, key_type);
8344
8345    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
8346                              &key));
8347
8348    actual_status = psa_asymmetric_decrypt(key, alg,
8349                                           input_data->x, input_data->len,
8350                                           label->x, label->len,
8351                                           output, output_size,
8352                                           &output_length);
8353    TEST_EQUAL(actual_status, expected_status);
8354    TEST_LE_U(output_length, output_size);
8355
8356    /* If the label is empty, the test framework puts a non-null pointer
8357     * in label->x. Test that a null pointer works as well. */
8358    if (label->len == 0) {
8359        output_length = ~0;
8360        if (output_size != 0) {
8361            memset(output, 0, output_size);
8362        }
8363        actual_status = psa_asymmetric_decrypt(key, alg,
8364                                               input_data->x, input_data->len,
8365                                               NULL, label->len,
8366                                               output, output_size,
8367                                               &output_length);
8368        TEST_EQUAL(actual_status, expected_status);
8369        TEST_LE_U(output_length, output_size);
8370    }
8371
8372exit:
8373    psa_reset_key_attributes(&attributes);
8374    psa_destroy_key(key);
8375    mbedtls_free(output);
8376    PSA_DONE();
8377}
8378/* END_CASE */
8379
8380/* BEGIN_CASE */
8381void key_derivation_init()
8382{
8383    /* Test each valid way of initializing the object, except for `= {0}`, as
8384     * Clang 5 complains when `-Wmissing-field-initializers` is used, even
8385     * though it's OK by the C standard. We could test for this, but we'd need
8386     * to suppress the Clang warning for the test. */
8387    size_t capacity;
8388    psa_key_derivation_operation_t func = psa_key_derivation_operation_init();
8389    psa_key_derivation_operation_t init = PSA_KEY_DERIVATION_OPERATION_INIT;
8390    psa_key_derivation_operation_t zero;
8391
8392    memset(&zero, 0, sizeof(zero));
8393
8394    /* A default operation should not be able to report its capacity. */
8395    TEST_EQUAL(psa_key_derivation_get_capacity(&func, &capacity),
8396               PSA_ERROR_BAD_STATE);
8397    TEST_EQUAL(psa_key_derivation_get_capacity(&init, &capacity),
8398               PSA_ERROR_BAD_STATE);
8399    TEST_EQUAL(psa_key_derivation_get_capacity(&zero, &capacity),
8400               PSA_ERROR_BAD_STATE);
8401
8402    /* A default operation should be abortable without error. */
8403    PSA_ASSERT(psa_key_derivation_abort(&func));
8404    PSA_ASSERT(psa_key_derivation_abort(&init));
8405    PSA_ASSERT(psa_key_derivation_abort(&zero));
8406}
8407/* END_CASE */
8408
8409/* BEGIN_CASE */
8410void derive_setup(int alg_arg, int expected_status_arg)
8411{
8412    psa_algorithm_t alg = alg_arg;
8413    psa_status_t expected_status = expected_status_arg;
8414    psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
8415
8416    PSA_ASSERT(psa_crypto_init());
8417
8418    TEST_EQUAL(psa_key_derivation_setup(&operation, alg),
8419               expected_status);
8420
8421exit:
8422    psa_key_derivation_abort(&operation);
8423    PSA_DONE();
8424}
8425/* END_CASE */
8426
8427/* BEGIN_CASE */
8428void derive_set_capacity(int alg_arg, int capacity_arg,
8429                         int expected_status_arg)
8430{
8431    psa_algorithm_t alg = alg_arg;
8432    size_t capacity = capacity_arg;
8433    psa_status_t expected_status = expected_status_arg;
8434    psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
8435
8436    PSA_ASSERT(psa_crypto_init());
8437
8438    PSA_ASSERT(psa_key_derivation_setup(&operation, alg));
8439
8440    TEST_EQUAL(psa_key_derivation_set_capacity(&operation, capacity),
8441               expected_status);
8442
8443exit:
8444    psa_key_derivation_abort(&operation);
8445    PSA_DONE();
8446}
8447/* END_CASE */
8448
8449/* BEGIN_CASE */
8450void derive_input(int alg_arg,
8451                  int step_arg1, int key_type_arg1, data_t *input1,
8452                  int expected_status_arg1,
8453                  int step_arg2, int key_type_arg2, data_t *input2,
8454                  int expected_status_arg2,
8455                  int step_arg3, int key_type_arg3, data_t *input3,
8456                  int expected_status_arg3,
8457                  int output_key_type_arg, int expected_output_status_arg)
8458{
8459    psa_algorithm_t alg = alg_arg;
8460    psa_key_derivation_step_t steps[] = { step_arg1, step_arg2, step_arg3 };
8461    psa_key_type_t key_types[] = { key_type_arg1, key_type_arg2, key_type_arg3 };
8462    psa_status_t expected_statuses[] = { expected_status_arg1,
8463                                         expected_status_arg2,
8464                                         expected_status_arg3 };
8465    data_t *inputs[] = { input1, input2, input3 };
8466    mbedtls_svc_key_id_t keys[] = { MBEDTLS_SVC_KEY_ID_INIT,
8467                                    MBEDTLS_SVC_KEY_ID_INIT,
8468                                    MBEDTLS_SVC_KEY_ID_INIT };
8469    psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
8470    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
8471    size_t i;
8472    psa_key_type_t output_key_type = output_key_type_arg;
8473    mbedtls_svc_key_id_t output_key = MBEDTLS_SVC_KEY_ID_INIT;
8474    psa_status_t expected_output_status = expected_output_status_arg;
8475    psa_status_t actual_output_status;
8476
8477    PSA_ASSERT(psa_crypto_init());
8478
8479    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DERIVE);
8480    psa_set_key_algorithm(&attributes, alg);
8481
8482    PSA_ASSERT(psa_key_derivation_setup(&operation, alg));
8483
8484    for (i = 0; i < ARRAY_LENGTH(steps); i++) {
8485        mbedtls_test_set_step(i);
8486        if (steps[i] == 0) {
8487            /* Skip this step */
8488        } else if (key_types[i] != PSA_KEY_TYPE_NONE) {
8489            psa_set_key_type(&attributes, key_types[i]);
8490            PSA_ASSERT(psa_import_key(&attributes,
8491                                      inputs[i]->x, inputs[i]->len,
8492                                      &keys[i]));
8493            if (PSA_KEY_TYPE_IS_KEY_PAIR(key_types[i]) &&
8494                steps[i] == PSA_KEY_DERIVATION_INPUT_SECRET) {
8495                // When taking a private key as secret input, use key agreement
8496                // to add the shared secret to the derivation
8497                TEST_EQUAL(mbedtls_test_psa_key_agreement_with_self(
8498                               &operation, keys[i]),
8499                           expected_statuses[i]);
8500            } else {
8501                TEST_EQUAL(psa_key_derivation_input_key(&operation, steps[i],
8502                                                        keys[i]),
8503                           expected_statuses[i]);
8504            }
8505        } else {
8506            TEST_EQUAL(psa_key_derivation_input_bytes(
8507                           &operation, steps[i],
8508                           inputs[i]->x, inputs[i]->len),
8509                       expected_statuses[i]);
8510        }
8511    }
8512
8513    if (output_key_type != PSA_KEY_TYPE_NONE) {
8514        psa_reset_key_attributes(&attributes);
8515        psa_set_key_type(&attributes, output_key_type);
8516        psa_set_key_bits(&attributes, 8);
8517        actual_output_status =
8518            psa_key_derivation_output_key(&attributes, &operation,
8519                                          &output_key);
8520    } else {
8521        uint8_t buffer[1];
8522        actual_output_status =
8523            psa_key_derivation_output_bytes(&operation,
8524                                            buffer, sizeof(buffer));
8525    }
8526    TEST_EQUAL(actual_output_status, expected_output_status);
8527
8528exit:
8529    psa_key_derivation_abort(&operation);
8530    for (i = 0; i < ARRAY_LENGTH(keys); i++) {
8531        psa_destroy_key(keys[i]);
8532    }
8533    psa_destroy_key(output_key);
8534    PSA_DONE();
8535}
8536/* END_CASE */
8537
8538/* BEGIN_CASE */
8539void derive_over_capacity(int alg_arg)
8540{
8541    psa_algorithm_t alg = alg_arg;
8542    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
8543    size_t key_type = PSA_KEY_TYPE_DERIVE;
8544    psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
8545    unsigned char input1[] = "Input 1";
8546    size_t input1_length = sizeof(input1);
8547    unsigned char input2[] = "Input 2";
8548    size_t input2_length = sizeof(input2);
8549    uint8_t buffer[42];
8550    size_t capacity = sizeof(buffer);
8551    const uint8_t key_data[22] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
8552                                   0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
8553                                   0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b };
8554    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
8555
8556    PSA_ASSERT(psa_crypto_init());
8557
8558    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DERIVE);
8559    psa_set_key_algorithm(&attributes, alg);
8560    psa_set_key_type(&attributes, key_type);
8561
8562    PSA_ASSERT(psa_import_key(&attributes,
8563                              key_data, sizeof(key_data),
8564                              &key));
8565
8566    /* valid key derivation */
8567    if (!mbedtls_test_psa_setup_key_derivation_wrap(&operation, key, alg,
8568                                                    input1, input1_length,
8569                                                    input2, input2_length,
8570                                                    capacity)) {
8571        goto exit;
8572    }
8573
8574    /* state of operation shouldn't allow additional generation */
8575    TEST_EQUAL(psa_key_derivation_setup(&operation, alg),
8576               PSA_ERROR_BAD_STATE);
8577
8578    PSA_ASSERT(psa_key_derivation_output_bytes(&operation, buffer, capacity));
8579
8580    TEST_EQUAL(psa_key_derivation_output_bytes(&operation, buffer, capacity),
8581               PSA_ERROR_INSUFFICIENT_DATA);
8582
8583exit:
8584    psa_key_derivation_abort(&operation);
8585    psa_destroy_key(key);
8586    PSA_DONE();
8587}
8588/* END_CASE */
8589
8590/* BEGIN_CASE */
8591void derive_actions_without_setup()
8592{
8593    uint8_t output_buffer[16];
8594    size_t buffer_size = 16;
8595    size_t capacity = 0;
8596    psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
8597
8598    TEST_ASSERT(psa_key_derivation_output_bytes(&operation,
8599                                                output_buffer, buffer_size)
8600                == PSA_ERROR_BAD_STATE);
8601
8602    TEST_ASSERT(psa_key_derivation_get_capacity(&operation, &capacity)
8603                == PSA_ERROR_BAD_STATE);
8604
8605    PSA_ASSERT(psa_key_derivation_abort(&operation));
8606
8607    TEST_ASSERT(psa_key_derivation_output_bytes(&operation,
8608                                                output_buffer, buffer_size)
8609                == PSA_ERROR_BAD_STATE);
8610
8611    TEST_ASSERT(psa_key_derivation_get_capacity(&operation, &capacity)
8612                == PSA_ERROR_BAD_STATE);
8613
8614exit:
8615    psa_key_derivation_abort(&operation);
8616}
8617/* END_CASE */
8618
8619/* BEGIN_CASE */
8620void derive_output(int alg_arg,
8621                   int step1_arg, data_t *input1, int expected_status_arg1,
8622                   int step2_arg, data_t *input2, int expected_status_arg2,
8623                   int step3_arg, data_t *input3, int expected_status_arg3,
8624                   int step4_arg, data_t *input4, int expected_status_arg4,
8625                   data_t *key_agreement_peer_key,
8626                   int requested_capacity_arg,
8627                   data_t *expected_output1,
8628                   data_t *expected_output2,
8629                   int other_key_input_type,
8630                   int key_input_type,
8631                   int derive_type)
8632{
8633    psa_algorithm_t alg = alg_arg;
8634    psa_key_derivation_step_t steps[] = { step1_arg, step2_arg, step3_arg, step4_arg };
8635    data_t *inputs[] = { input1, input2, input3, input4 };
8636    mbedtls_svc_key_id_t keys[] = { MBEDTLS_SVC_KEY_ID_INIT,
8637                                    MBEDTLS_SVC_KEY_ID_INIT,
8638                                    MBEDTLS_SVC_KEY_ID_INIT,
8639                                    MBEDTLS_SVC_KEY_ID_INIT };
8640    psa_status_t statuses[] = { expected_status_arg1, expected_status_arg2,
8641                                expected_status_arg3, expected_status_arg4 };
8642    size_t requested_capacity = requested_capacity_arg;
8643    psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
8644    uint8_t *expected_outputs[2] =
8645    { expected_output1->x, expected_output2->x };
8646    size_t output_sizes[2] =
8647    { expected_output1->len, expected_output2->len };
8648    size_t output_buffer_size = 0;
8649    uint8_t *output_buffer = NULL;
8650    size_t expected_capacity;
8651    size_t current_capacity;
8652    psa_key_attributes_t attributes1 = PSA_KEY_ATTRIBUTES_INIT;
8653    psa_key_attributes_t attributes2 = PSA_KEY_ATTRIBUTES_INIT;
8654    psa_key_attributes_t attributes3 = PSA_KEY_ATTRIBUTES_INIT;
8655    psa_key_attributes_t attributes4 = PSA_KEY_ATTRIBUTES_INIT;
8656    mbedtls_svc_key_id_t derived_key = MBEDTLS_SVC_KEY_ID_INIT;
8657    psa_status_t status;
8658    size_t i;
8659
8660    for (i = 0; i < ARRAY_LENGTH(expected_outputs); i++) {
8661        if (output_sizes[i] > output_buffer_size) {
8662            output_buffer_size = output_sizes[i];
8663        }
8664        if (output_sizes[i] == 0) {
8665            expected_outputs[i] = NULL;
8666        }
8667    }
8668    ASSERT_ALLOC(output_buffer, output_buffer_size);
8669    PSA_ASSERT(psa_crypto_init());
8670
8671    /* Extraction phase. */
8672    PSA_ASSERT(psa_key_derivation_setup(&operation, alg));
8673    PSA_ASSERT(psa_key_derivation_set_capacity(&operation,
8674                                               requested_capacity));
8675    for (i = 0; i < ARRAY_LENGTH(steps); i++) {
8676        switch (steps[i]) {
8677            case 0:
8678                break;
8679            case PSA_KEY_DERIVATION_INPUT_SECRET:
8680                switch (key_input_type) {
8681                    case 0: // input bytes
8682                        TEST_EQUAL(psa_key_derivation_input_bytes(
8683                                       &operation, steps[i],
8684                                       inputs[i]->x, inputs[i]->len),
8685                                   statuses[i]);
8686
8687                        if (statuses[i] != PSA_SUCCESS) {
8688                            goto exit;
8689                        }
8690                        break;
8691                    case 1: // input key
8692                        psa_set_key_usage_flags(&attributes1, PSA_KEY_USAGE_DERIVE);
8693                        psa_set_key_algorithm(&attributes1, alg);
8694                        psa_set_key_type(&attributes1, PSA_KEY_TYPE_DERIVE);
8695
8696                        PSA_ASSERT(psa_import_key(&attributes1,
8697                                                  inputs[i]->x, inputs[i]->len,
8698                                                  &keys[i]));
8699
8700                        if (PSA_ALG_IS_TLS12_PSK_TO_MS(alg)) {
8701                            PSA_ASSERT(psa_get_key_attributes(keys[i], &attributes1));
8702                            TEST_LE_U(PSA_BITS_TO_BYTES(psa_get_key_bits(&attributes1)),
8703                                      PSA_TLS12_PSK_TO_MS_PSK_MAX_SIZE);
8704                        }
8705
8706                        PSA_ASSERT(psa_key_derivation_input_key(&operation,
8707                                                                steps[i],
8708                                                                keys[i]));
8709                        break;
8710                    default:
8711                        TEST_ASSERT(!"default case not supported");
8712                        break;
8713                }
8714                break;
8715            case PSA_KEY_DERIVATION_INPUT_OTHER_SECRET:
8716                switch (other_key_input_type) {
8717                    case 0: // input bytes
8718                        TEST_EQUAL(psa_key_derivation_input_bytes(&operation,
8719                                                                  steps[i],
8720                                                                  inputs[i]->x,
8721                                                                  inputs[i]->len),
8722                                   statuses[i]);
8723                        break;
8724                    case 1: // input key, type DERIVE
8725                    case 11: // input key, type RAW
8726                        psa_set_key_usage_flags(&attributes2, PSA_KEY_USAGE_DERIVE);
8727                        psa_set_key_algorithm(&attributes2, alg);
8728                        psa_set_key_type(&attributes2, PSA_KEY_TYPE_DERIVE);
8729
8730                        // other secret of type RAW_DATA passed with input_key
8731                        if (other_key_input_type == 11) {
8732                            psa_set_key_type(&attributes2, PSA_KEY_TYPE_RAW_DATA);
8733                        }
8734
8735                        PSA_ASSERT(psa_import_key(&attributes2,
8736                                                  inputs[i]->x, inputs[i]->len,
8737                                                  &keys[i]));
8738
8739                        TEST_EQUAL(psa_key_derivation_input_key(&operation,
8740                                                                steps[i],
8741                                                                keys[i]),
8742                                   statuses[i]);
8743                        break;
8744                    case 2: // key agreement
8745                        psa_set_key_usage_flags(&attributes3, PSA_KEY_USAGE_DERIVE);
8746                        psa_set_key_algorithm(&attributes3, alg);
8747                        psa_set_key_type(&attributes3,
8748                                         PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1));
8749
8750                        PSA_ASSERT(psa_import_key(&attributes3,
8751                                                  inputs[i]->x, inputs[i]->len,
8752                                                  &keys[i]));
8753
8754                        TEST_EQUAL(psa_key_derivation_key_agreement(
8755                                       &operation,
8756                                       PSA_KEY_DERIVATION_INPUT_OTHER_SECRET,
8757                                       keys[i], key_agreement_peer_key->x,
8758                                       key_agreement_peer_key->len), statuses[i]);
8759                        break;
8760                    default:
8761                        TEST_ASSERT(!"default case not supported");
8762                        break;
8763                }
8764
8765                if (statuses[i] != PSA_SUCCESS) {
8766                    goto exit;
8767                }
8768                break;
8769            default:
8770                TEST_EQUAL(psa_key_derivation_input_bytes(
8771                               &operation, steps[i],
8772                               inputs[i]->x, inputs[i]->len), statuses[i]);
8773
8774                if (statuses[i] != PSA_SUCCESS) {
8775                    goto exit;
8776                }
8777                break;
8778        }
8779    }
8780
8781    PSA_ASSERT(psa_key_derivation_get_capacity(&operation,
8782                                               &current_capacity));
8783    TEST_EQUAL(current_capacity, requested_capacity);
8784    expected_capacity = requested_capacity;
8785
8786    if (derive_type == 1) { // output key
8787        psa_status_t expected_status = PSA_ERROR_NOT_PERMITTED;
8788
8789        /* For output key derivation secret must be provided using
8790           input key, otherwise operation is not permitted. */
8791        if (key_input_type == 1) {
8792            expected_status = PSA_SUCCESS;
8793        }
8794
8795        psa_set_key_usage_flags(&attributes4, PSA_KEY_USAGE_EXPORT);
8796        psa_set_key_algorithm(&attributes4, alg);
8797        psa_set_key_type(&attributes4, PSA_KEY_TYPE_DERIVE);
8798        psa_set_key_bits(&attributes4, PSA_BYTES_TO_BITS(requested_capacity));
8799
8800        TEST_EQUAL(psa_key_derivation_output_key(&attributes4, &operation,
8801                                                 &derived_key), expected_status);
8802    } else { // output bytes
8803        /* Expansion phase. */
8804        for (i = 0; i < ARRAY_LENGTH(expected_outputs); i++) {
8805            /* Read some bytes. */
8806            status = psa_key_derivation_output_bytes(&operation,
8807                                                     output_buffer, output_sizes[i]);
8808            if (expected_capacity == 0 && output_sizes[i] == 0) {
8809                /* Reading 0 bytes when 0 bytes are available can go either way. */
8810                TEST_ASSERT(status == PSA_SUCCESS ||
8811                            status == PSA_ERROR_INSUFFICIENT_DATA);
8812                continue;
8813            } else if (expected_capacity == 0 ||
8814                       output_sizes[i] > expected_capacity) {
8815                /* Capacity exceeded. */
8816                TEST_EQUAL(status, PSA_ERROR_INSUFFICIENT_DATA);
8817                expected_capacity = 0;
8818                continue;
8819            }
8820            /* Success. Check the read data. */
8821            PSA_ASSERT(status);
8822            if (output_sizes[i] != 0) {
8823                ASSERT_COMPARE(output_buffer, output_sizes[i],
8824                               expected_outputs[i], output_sizes[i]);
8825            }
8826            /* Check the operation status. */
8827            expected_capacity -= output_sizes[i];
8828            PSA_ASSERT(psa_key_derivation_get_capacity(&operation,
8829                                                       &current_capacity));
8830            TEST_EQUAL(expected_capacity, current_capacity);
8831        }
8832    }
8833    PSA_ASSERT(psa_key_derivation_abort(&operation));
8834
8835exit:
8836    mbedtls_free(output_buffer);
8837    psa_key_derivation_abort(&operation);
8838    for (i = 0; i < ARRAY_LENGTH(keys); i++) {
8839        psa_destroy_key(keys[i]);
8840    }
8841    psa_destroy_key(derived_key);
8842    PSA_DONE();
8843}
8844/* END_CASE */
8845
8846/* BEGIN_CASE */
8847void derive_full(int alg_arg,
8848                 data_t *key_data,
8849                 data_t *input1,
8850                 data_t *input2,
8851                 int requested_capacity_arg)
8852{
8853    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
8854    psa_algorithm_t alg = alg_arg;
8855    size_t requested_capacity = requested_capacity_arg;
8856    psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
8857    unsigned char output_buffer[16];
8858    size_t expected_capacity = requested_capacity;
8859    size_t current_capacity;
8860    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
8861
8862    PSA_ASSERT(psa_crypto_init());
8863
8864    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DERIVE);
8865    psa_set_key_algorithm(&attributes, alg);
8866    psa_set_key_type(&attributes, PSA_KEY_TYPE_DERIVE);
8867
8868    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
8869                              &key));
8870
8871    if (!mbedtls_test_psa_setup_key_derivation_wrap(&operation, key, alg,
8872                                                    input1->x, input1->len,
8873                                                    input2->x, input2->len,
8874                                                    requested_capacity)) {
8875        goto exit;
8876    }
8877
8878    PSA_ASSERT(psa_key_derivation_get_capacity(&operation,
8879                                               &current_capacity));
8880    TEST_EQUAL(current_capacity, expected_capacity);
8881
8882    /* Expansion phase. */
8883    while (current_capacity > 0) {
8884        size_t read_size = sizeof(output_buffer);
8885        if (read_size > current_capacity) {
8886            read_size = current_capacity;
8887        }
8888        PSA_ASSERT(psa_key_derivation_output_bytes(&operation,
8889                                                   output_buffer,
8890                                                   read_size));
8891        expected_capacity -= read_size;
8892        PSA_ASSERT(psa_key_derivation_get_capacity(&operation,
8893                                                   &current_capacity));
8894        TEST_EQUAL(current_capacity, expected_capacity);
8895    }
8896
8897    /* Check that the operation refuses to go over capacity. */
8898    TEST_EQUAL(psa_key_derivation_output_bytes(&operation, output_buffer, 1),
8899               PSA_ERROR_INSUFFICIENT_DATA);
8900
8901    PSA_ASSERT(psa_key_derivation_abort(&operation));
8902
8903exit:
8904    psa_key_derivation_abort(&operation);
8905    psa_destroy_key(key);
8906    PSA_DONE();
8907}
8908/* END_CASE */
8909
8910/* BEGIN_CASE depends_on:PSA_WANT_ALG_SHA_256:MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
8911void derive_ecjpake_to_pms(data_t *input, int expected_input_status_arg,
8912                           int derivation_step,
8913                           int capacity, int expected_capacity_status_arg,
8914                           data_t *expected_output,
8915                           int expected_output_status_arg)
8916{
8917    psa_algorithm_t alg = PSA_ALG_TLS12_ECJPAKE_TO_PMS;
8918    psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
8919    psa_key_derivation_step_t step = (psa_key_derivation_step_t) derivation_step;
8920    uint8_t *output_buffer = NULL;
8921    psa_status_t status;
8922    psa_status_t expected_input_status = (psa_status_t) expected_input_status_arg;
8923    psa_status_t expected_capacity_status = (psa_status_t) expected_capacity_status_arg;
8924    psa_status_t expected_output_status = (psa_status_t) expected_output_status_arg;
8925
8926    ASSERT_ALLOC(output_buffer, expected_output->len);
8927    PSA_ASSERT(psa_crypto_init());
8928
8929    PSA_ASSERT(psa_key_derivation_setup(&operation, alg));
8930    TEST_EQUAL(psa_key_derivation_set_capacity(&operation, capacity),
8931               expected_capacity_status);
8932
8933    TEST_EQUAL(psa_key_derivation_input_bytes(&operation,
8934                                              step, input->x, input->len),
8935               expected_input_status);
8936
8937    if (((psa_status_t) expected_input_status) != PSA_SUCCESS) {
8938        goto exit;
8939    }
8940
8941    status = psa_key_derivation_output_bytes(&operation, output_buffer,
8942                                             expected_output->len);
8943
8944    TEST_EQUAL(status, expected_output_status);
8945    if (expected_output->len != 0 && expected_output_status == PSA_SUCCESS) {
8946        ASSERT_COMPARE(output_buffer, expected_output->len, expected_output->x,
8947                       expected_output->len);
8948    }
8949
8950exit:
8951    mbedtls_free(output_buffer);
8952    psa_key_derivation_abort(&operation);
8953    PSA_DONE();
8954}
8955/* END_CASE */
8956
8957/* BEGIN_CASE */
8958void derive_key_exercise(int alg_arg,
8959                         data_t *key_data,
8960                         data_t *input1,
8961                         data_t *input2,
8962                         int derived_type_arg,
8963                         int derived_bits_arg,
8964                         int derived_usage_arg,
8965                         int derived_alg_arg)
8966{
8967    mbedtls_svc_key_id_t base_key = MBEDTLS_SVC_KEY_ID_INIT;
8968    mbedtls_svc_key_id_t derived_key = MBEDTLS_SVC_KEY_ID_INIT;
8969    psa_algorithm_t alg = alg_arg;
8970    psa_key_type_t derived_type = derived_type_arg;
8971    size_t derived_bits = derived_bits_arg;
8972    psa_key_usage_t derived_usage = derived_usage_arg;
8973    psa_algorithm_t derived_alg = derived_alg_arg;
8974    size_t capacity = PSA_BITS_TO_BYTES(derived_bits);
8975    psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
8976    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
8977    psa_key_attributes_t got_attributes = PSA_KEY_ATTRIBUTES_INIT;
8978
8979    PSA_ASSERT(psa_crypto_init());
8980
8981    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DERIVE);
8982    psa_set_key_algorithm(&attributes, alg);
8983    psa_set_key_type(&attributes, PSA_KEY_TYPE_DERIVE);
8984    PSA_ASSERT(psa_import_key(&attributes, key_data->x, key_data->len,
8985                              &base_key));
8986
8987    /* Derive a key. */
8988    if (!mbedtls_test_psa_setup_key_derivation_wrap(&operation, base_key, alg,
8989                                                    input1->x, input1->len,
8990                                                    input2->x, input2->len,
8991                                                    capacity)) {
8992        goto exit;
8993    }
8994
8995    psa_set_key_usage_flags(&attributes, derived_usage);
8996    psa_set_key_algorithm(&attributes, derived_alg);
8997    psa_set_key_type(&attributes, derived_type);
8998    psa_set_key_bits(&attributes, derived_bits);
8999    PSA_ASSERT(psa_key_derivation_output_key(&attributes, &operation,
9000                                             &derived_key));
9001
9002    /* Test the key information */
9003    PSA_ASSERT(psa_get_key_attributes(derived_key, &got_attributes));
9004    TEST_EQUAL(psa_get_key_type(&got_attributes), derived_type);
9005    TEST_EQUAL(psa_get_key_bits(&got_attributes), derived_bits);
9006
9007    /* Exercise the derived key. */
9008    if (!mbedtls_test_psa_exercise_key(derived_key, derived_usage, derived_alg)) {
9009        goto exit;
9010    }
9011
9012exit:
9013    /*
9014     * Key attributes may have been returned by psa_get_key_attributes()
9015     * thus reset them as required.
9016     */
9017    psa_reset_key_attributes(&got_attributes);
9018
9019    psa_key_derivation_abort(&operation);
9020    psa_destroy_key(base_key);
9021    psa_destroy_key(derived_key);
9022    PSA_DONE();
9023}
9024/* END_CASE */
9025
9026/* BEGIN_CASE */
9027void derive_key_export(int alg_arg,
9028                       data_t *key_data,
9029                       data_t *input1,
9030                       data_t *input2,
9031                       int bytes1_arg,
9032                       int bytes2_arg)
9033{
9034    mbedtls_svc_key_id_t base_key = MBEDTLS_SVC_KEY_ID_INIT;
9035    mbedtls_svc_key_id_t derived_key = MBEDTLS_SVC_KEY_ID_INIT;
9036    psa_algorithm_t alg = alg_arg;
9037    size_t bytes1 = bytes1_arg;
9038    size_t bytes2 = bytes2_arg;
9039    size_t capacity = bytes1 + bytes2;
9040    psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
9041    uint8_t *output_buffer = NULL;
9042    uint8_t *export_buffer = NULL;
9043    psa_key_attributes_t base_attributes = PSA_KEY_ATTRIBUTES_INIT;
9044    psa_key_attributes_t derived_attributes = PSA_KEY_ATTRIBUTES_INIT;
9045    size_t length;
9046
9047    ASSERT_ALLOC(output_buffer, capacity);
9048    ASSERT_ALLOC(export_buffer, capacity);
9049    PSA_ASSERT(psa_crypto_init());
9050
9051    psa_set_key_usage_flags(&base_attributes, PSA_KEY_USAGE_DERIVE);
9052    psa_set_key_algorithm(&base_attributes, alg);
9053    psa_set_key_type(&base_attributes, PSA_KEY_TYPE_DERIVE);
9054    PSA_ASSERT(psa_import_key(&base_attributes, key_data->x, key_data->len,
9055                              &base_key));
9056
9057    /* Derive some material and output it. */
9058    if (!mbedtls_test_psa_setup_key_derivation_wrap(&operation, base_key, alg,
9059                                                    input1->x, input1->len,
9060                                                    input2->x, input2->len,
9061                                                    capacity)) {
9062        goto exit;
9063    }
9064
9065    PSA_ASSERT(psa_key_derivation_output_bytes(&operation,
9066                                               output_buffer,
9067                                               capacity));
9068    PSA_ASSERT(psa_key_derivation_abort(&operation));
9069
9070    /* Derive the same output again, but this time store it in key objects. */
9071    if (!mbedtls_test_psa_setup_key_derivation_wrap(&operation, base_key, alg,
9072                                                    input1->x, input1->len,
9073                                                    input2->x, input2->len,
9074                                                    capacity)) {
9075        goto exit;
9076    }
9077
9078    psa_set_key_usage_flags(&derived_attributes, PSA_KEY_USAGE_EXPORT);
9079    psa_set_key_algorithm(&derived_attributes, 0);
9080    psa_set_key_type(&derived_attributes, PSA_KEY_TYPE_RAW_DATA);
9081    psa_set_key_bits(&derived_attributes, PSA_BYTES_TO_BITS(bytes1));
9082    PSA_ASSERT(psa_key_derivation_output_key(&derived_attributes, &operation,
9083                                             &derived_key));
9084    PSA_ASSERT(psa_export_key(derived_key,
9085                              export_buffer, bytes1,
9086                              &length));
9087    TEST_EQUAL(length, bytes1);
9088    PSA_ASSERT(psa_destroy_key(derived_key));
9089    psa_set_key_bits(&derived_attributes, PSA_BYTES_TO_BITS(bytes2));
9090    PSA_ASSERT(psa_key_derivation_output_key(&derived_attributes, &operation,
9091                                             &derived_key));
9092    PSA_ASSERT(psa_export_key(derived_key,
9093                              export_buffer + bytes1, bytes2,
9094                              &length));
9095    TEST_EQUAL(length, bytes2);
9096
9097    /* Compare the outputs from the two runs. */
9098    ASSERT_COMPARE(output_buffer, bytes1 + bytes2,
9099                   export_buffer, capacity);
9100
9101exit:
9102    mbedtls_free(output_buffer);
9103    mbedtls_free(export_buffer);
9104    psa_key_derivation_abort(&operation);
9105    psa_destroy_key(base_key);
9106    psa_destroy_key(derived_key);
9107    PSA_DONE();
9108}
9109/* END_CASE */
9110
9111/* BEGIN_CASE */
9112void derive_key_type(int alg_arg,
9113                     data_t *key_data,
9114                     data_t *input1,
9115                     data_t *input2,
9116                     int key_type_arg, int bits_arg,
9117                     data_t *expected_export)
9118{
9119    mbedtls_svc_key_id_t base_key = MBEDTLS_SVC_KEY_ID_INIT;
9120    mbedtls_svc_key_id_t derived_key = MBEDTLS_SVC_KEY_ID_INIT;
9121    const psa_algorithm_t alg = alg_arg;
9122    const psa_key_type_t key_type = key_type_arg;
9123    const size_t bits = bits_arg;
9124    psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
9125    const size_t export_buffer_size =
9126        PSA_EXPORT_KEY_OUTPUT_SIZE(key_type, bits);
9127    uint8_t *export_buffer = NULL;
9128    psa_key_attributes_t base_attributes = PSA_KEY_ATTRIBUTES_INIT;
9129    psa_key_attributes_t derived_attributes = PSA_KEY_ATTRIBUTES_INIT;
9130    size_t export_length;
9131
9132    ASSERT_ALLOC(export_buffer, export_buffer_size);
9133    PSA_ASSERT(psa_crypto_init());
9134
9135    psa_set_key_usage_flags(&base_attributes, PSA_KEY_USAGE_DERIVE);
9136    psa_set_key_algorithm(&base_attributes, alg);
9137    psa_set_key_type(&base_attributes, PSA_KEY_TYPE_DERIVE);
9138    PSA_ASSERT(psa_import_key(&base_attributes, key_data->x, key_data->len,
9139                              &base_key));
9140
9141    if (mbedtls_test_psa_setup_key_derivation_wrap(
9142            &operation, base_key, alg,
9143            input1->x, input1->len,
9144            input2->x, input2->len,
9145            PSA_KEY_DERIVATION_UNLIMITED_CAPACITY) == 0) {
9146        goto exit;
9147    }
9148
9149    psa_set_key_usage_flags(&derived_attributes, PSA_KEY_USAGE_EXPORT);
9150    psa_set_key_algorithm(&derived_attributes, 0);
9151    psa_set_key_type(&derived_attributes, key_type);
9152    psa_set_key_bits(&derived_attributes, bits);
9153    PSA_ASSERT(psa_key_derivation_output_key(&derived_attributes, &operation,
9154                                             &derived_key));
9155
9156    PSA_ASSERT(psa_export_key(derived_key,
9157                              export_buffer, export_buffer_size,
9158                              &export_length));
9159    ASSERT_COMPARE(export_buffer, export_length,
9160                   expected_export->x, expected_export->len);
9161
9162exit:
9163    mbedtls_free(export_buffer);
9164    psa_key_derivation_abort(&operation);
9165    psa_destroy_key(base_key);
9166    psa_destroy_key(derived_key);
9167    PSA_DONE();
9168}
9169/* END_CASE */
9170
9171/* BEGIN_CASE */
9172void derive_key(int alg_arg,
9173                data_t *key_data, data_t *input1, data_t *input2,
9174                int type_arg, int bits_arg,
9175                int expected_status_arg,
9176                int is_large_output)
9177{
9178    mbedtls_svc_key_id_t base_key = MBEDTLS_SVC_KEY_ID_INIT;
9179    mbedtls_svc_key_id_t derived_key = MBEDTLS_SVC_KEY_ID_INIT;
9180    psa_algorithm_t alg = alg_arg;
9181    psa_key_type_t type = type_arg;
9182    size_t bits = bits_arg;
9183    psa_status_t expected_status = expected_status_arg;
9184    psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
9185    psa_key_attributes_t base_attributes = PSA_KEY_ATTRIBUTES_INIT;
9186    psa_key_attributes_t derived_attributes = PSA_KEY_ATTRIBUTES_INIT;
9187
9188    PSA_ASSERT(psa_crypto_init());
9189
9190    psa_set_key_usage_flags(&base_attributes, PSA_KEY_USAGE_DERIVE);
9191    psa_set_key_algorithm(&base_attributes, alg);
9192    psa_set_key_type(&base_attributes, PSA_KEY_TYPE_DERIVE);
9193    PSA_ASSERT(psa_import_key(&base_attributes, key_data->x, key_data->len,
9194                              &base_key));
9195
9196    if (!mbedtls_test_psa_setup_key_derivation_wrap(&operation, base_key, alg,
9197                                                    input1->x, input1->len,
9198                                                    input2->x, input2->len,
9199                                                    SIZE_MAX)) {
9200        goto exit;
9201    }
9202
9203    psa_set_key_usage_flags(&derived_attributes, PSA_KEY_USAGE_EXPORT);
9204    psa_set_key_algorithm(&derived_attributes, 0);
9205    psa_set_key_type(&derived_attributes, type);
9206    psa_set_key_bits(&derived_attributes, bits);
9207
9208    psa_status_t status =
9209        psa_key_derivation_output_key(&derived_attributes,
9210                                      &operation,
9211                                      &derived_key);
9212    if (is_large_output > 0) {
9213        TEST_ASSUME(status != PSA_ERROR_INSUFFICIENT_MEMORY);
9214    }
9215    TEST_EQUAL(status, expected_status);
9216
9217exit:
9218    psa_key_derivation_abort(&operation);
9219    psa_destroy_key(base_key);
9220    psa_destroy_key(derived_key);
9221    PSA_DONE();
9222}
9223/* END_CASE */
9224
9225/* BEGIN_CASE */
9226void key_agreement_setup(int alg_arg,
9227                         int our_key_type_arg, int our_key_alg_arg,
9228                         data_t *our_key_data, data_t *peer_key_data,
9229                         int expected_status_arg)
9230{
9231    mbedtls_svc_key_id_t our_key = MBEDTLS_SVC_KEY_ID_INIT;
9232    psa_algorithm_t alg = alg_arg;
9233    psa_algorithm_t our_key_alg = our_key_alg_arg;
9234    psa_key_type_t our_key_type = our_key_type_arg;
9235    psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
9236    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
9237    psa_status_t expected_status = expected_status_arg;
9238    psa_status_t status;
9239
9240    PSA_ASSERT(psa_crypto_init());
9241
9242    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DERIVE);
9243    psa_set_key_algorithm(&attributes, our_key_alg);
9244    psa_set_key_type(&attributes, our_key_type);
9245    PSA_ASSERT(psa_import_key(&attributes,
9246                              our_key_data->x, our_key_data->len,
9247                              &our_key));
9248
9249    /* The tests currently include inputs that should fail at either step.
9250     * Test cases that fail at the setup step should be changed to call
9251     * key_derivation_setup instead, and this function should be renamed
9252     * to key_agreement_fail. */
9253    status = psa_key_derivation_setup(&operation, alg);
9254    if (status == PSA_SUCCESS) {
9255        TEST_EQUAL(psa_key_derivation_key_agreement(
9256                       &operation, PSA_KEY_DERIVATION_INPUT_SECRET,
9257                       our_key,
9258                       peer_key_data->x, peer_key_data->len),
9259                   expected_status);
9260    } else {
9261        TEST_ASSERT(status == expected_status);
9262    }
9263
9264exit:
9265    psa_key_derivation_abort(&operation);
9266    psa_destroy_key(our_key);
9267    PSA_DONE();
9268}
9269/* END_CASE */
9270
9271/* BEGIN_CASE */
9272void raw_key_agreement(int alg_arg,
9273                       int our_key_type_arg, data_t *our_key_data,
9274                       data_t *peer_key_data,
9275                       data_t *expected_output)
9276{
9277    mbedtls_svc_key_id_t our_key = MBEDTLS_SVC_KEY_ID_INIT;
9278    psa_algorithm_t alg = alg_arg;
9279    psa_key_type_t our_key_type = our_key_type_arg;
9280    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
9281    unsigned char *output = NULL;
9282    size_t output_length = ~0;
9283    size_t key_bits;
9284
9285    PSA_ASSERT(psa_crypto_init());
9286
9287    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DERIVE);
9288    psa_set_key_algorithm(&attributes, alg);
9289    psa_set_key_type(&attributes, our_key_type);
9290    PSA_ASSERT(psa_import_key(&attributes,
9291                              our_key_data->x, our_key_data->len,
9292                              &our_key));
9293
9294    PSA_ASSERT(psa_get_key_attributes(our_key, &attributes));
9295    key_bits = psa_get_key_bits(&attributes);
9296
9297    /* Validate size macros */
9298    TEST_LE_U(expected_output->len,
9299              PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE(our_key_type, key_bits));
9300    TEST_LE_U(PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE(our_key_type, key_bits),
9301              PSA_RAW_KEY_AGREEMENT_OUTPUT_MAX_SIZE);
9302
9303    /* Good case with exact output size */
9304    ASSERT_ALLOC(output, expected_output->len);
9305    PSA_ASSERT(psa_raw_key_agreement(alg, our_key,
9306                                     peer_key_data->x, peer_key_data->len,
9307                                     output, expected_output->len,
9308                                     &output_length));
9309    ASSERT_COMPARE(output, output_length,
9310                   expected_output->x, expected_output->len);
9311    mbedtls_free(output);
9312    output = NULL;
9313    output_length = ~0;
9314
9315    /* Larger buffer */
9316    ASSERT_ALLOC(output, expected_output->len + 1);
9317    PSA_ASSERT(psa_raw_key_agreement(alg, our_key,
9318                                     peer_key_data->x, peer_key_data->len,
9319                                     output, expected_output->len + 1,
9320                                     &output_length));
9321    ASSERT_COMPARE(output, output_length,
9322                   expected_output->x, expected_output->len);
9323    mbedtls_free(output);
9324    output = NULL;
9325    output_length = ~0;
9326
9327    /* Buffer too small */
9328    ASSERT_ALLOC(output, expected_output->len - 1);
9329    TEST_EQUAL(psa_raw_key_agreement(alg, our_key,
9330                                     peer_key_data->x, peer_key_data->len,
9331                                     output, expected_output->len - 1,
9332                                     &output_length),
9333               PSA_ERROR_BUFFER_TOO_SMALL);
9334    /* Not required by the spec, but good robustness */
9335    TEST_LE_U(output_length, expected_output->len - 1);
9336    mbedtls_free(output);
9337    output = NULL;
9338
9339exit:
9340    mbedtls_free(output);
9341    psa_destroy_key(our_key);
9342    PSA_DONE();
9343}
9344/* END_CASE */
9345
9346/* BEGIN_CASE */
9347void key_agreement_capacity(int alg_arg,
9348                            int our_key_type_arg, data_t *our_key_data,
9349                            data_t *peer_key_data,
9350                            int expected_capacity_arg)
9351{
9352    mbedtls_svc_key_id_t our_key = MBEDTLS_SVC_KEY_ID_INIT;
9353    psa_algorithm_t alg = alg_arg;
9354    psa_key_type_t our_key_type = our_key_type_arg;
9355    psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
9356    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
9357    size_t actual_capacity;
9358    unsigned char output[16];
9359
9360    PSA_ASSERT(psa_crypto_init());
9361
9362    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DERIVE);
9363    psa_set_key_algorithm(&attributes, alg);
9364    psa_set_key_type(&attributes, our_key_type);
9365    PSA_ASSERT(psa_import_key(&attributes,
9366                              our_key_data->x, our_key_data->len,
9367                              &our_key));
9368
9369    PSA_ASSERT(psa_key_derivation_setup(&operation, alg));
9370    PSA_ASSERT(psa_key_derivation_key_agreement(
9371                   &operation,
9372                   PSA_KEY_DERIVATION_INPUT_SECRET, our_key,
9373                   peer_key_data->x, peer_key_data->len));
9374    if (PSA_ALG_IS_HKDF(PSA_ALG_KEY_AGREEMENT_GET_KDF(alg))) {
9375        /* The test data is for info="" */
9376        PSA_ASSERT(psa_key_derivation_input_bytes(&operation,
9377                                                  PSA_KEY_DERIVATION_INPUT_INFO,
9378                                                  NULL, 0));
9379    }
9380
9381    /* Test the advertised capacity. */
9382    PSA_ASSERT(psa_key_derivation_get_capacity(
9383                   &operation, &actual_capacity));
9384    TEST_EQUAL(actual_capacity, (size_t) expected_capacity_arg);
9385
9386    /* Test the actual capacity by reading the output. */
9387    while (actual_capacity > sizeof(output)) {
9388        PSA_ASSERT(psa_key_derivation_output_bytes(&operation,
9389                                                   output, sizeof(output)));
9390        actual_capacity -= sizeof(output);
9391    }
9392    PSA_ASSERT(psa_key_derivation_output_bytes(&operation,
9393                                               output, actual_capacity));
9394    TEST_EQUAL(psa_key_derivation_output_bytes(&operation, output, 1),
9395               PSA_ERROR_INSUFFICIENT_DATA);
9396
9397exit:
9398    psa_key_derivation_abort(&operation);
9399    psa_destroy_key(our_key);
9400    PSA_DONE();
9401}
9402/* END_CASE */
9403
9404/* BEGIN_CASE */
9405void key_agreement_output(int alg_arg,
9406                          int our_key_type_arg, data_t *our_key_data,
9407                          data_t *peer_key_data,
9408                          data_t *expected_output1, data_t *expected_output2)
9409{
9410    mbedtls_svc_key_id_t our_key = MBEDTLS_SVC_KEY_ID_INIT;
9411    psa_algorithm_t alg = alg_arg;
9412    psa_key_type_t our_key_type = our_key_type_arg;
9413    psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
9414    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
9415    uint8_t *actual_output = NULL;
9416
9417    ASSERT_ALLOC(actual_output, MAX(expected_output1->len,
9418                                    expected_output2->len));
9419
9420    PSA_ASSERT(psa_crypto_init());
9421
9422    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DERIVE);
9423    psa_set_key_algorithm(&attributes, alg);
9424    psa_set_key_type(&attributes, our_key_type);
9425    PSA_ASSERT(psa_import_key(&attributes,
9426                              our_key_data->x, our_key_data->len,
9427                              &our_key));
9428
9429    PSA_ASSERT(psa_key_derivation_setup(&operation, alg));
9430    PSA_ASSERT(psa_key_derivation_key_agreement(
9431                   &operation,
9432                   PSA_KEY_DERIVATION_INPUT_SECRET, our_key,
9433                   peer_key_data->x, peer_key_data->len));
9434    if (PSA_ALG_IS_HKDF(PSA_ALG_KEY_AGREEMENT_GET_KDF(alg))) {
9435        /* The test data is for info="" */
9436        PSA_ASSERT(psa_key_derivation_input_bytes(&operation,
9437                                                  PSA_KEY_DERIVATION_INPUT_INFO,
9438                                                  NULL, 0));
9439    }
9440
9441    PSA_ASSERT(psa_key_derivation_output_bytes(&operation,
9442                                               actual_output,
9443                                               expected_output1->len));
9444    ASSERT_COMPARE(actual_output, expected_output1->len,
9445                   expected_output1->x, expected_output1->len);
9446    if (expected_output2->len != 0) {
9447        PSA_ASSERT(psa_key_derivation_output_bytes(&operation,
9448                                                   actual_output,
9449                                                   expected_output2->len));
9450        ASSERT_COMPARE(actual_output, expected_output2->len,
9451                       expected_output2->x, expected_output2->len);
9452    }
9453
9454exit:
9455    psa_key_derivation_abort(&operation);
9456    psa_destroy_key(our_key);
9457    PSA_DONE();
9458    mbedtls_free(actual_output);
9459}
9460/* END_CASE */
9461
9462/* BEGIN_CASE */
9463void generate_random(int bytes_arg)
9464{
9465    size_t bytes = bytes_arg;
9466    unsigned char *output = NULL;
9467    unsigned char *changed = NULL;
9468    size_t i;
9469    unsigned run;
9470
9471    TEST_ASSERT(bytes_arg >= 0);
9472
9473    ASSERT_ALLOC(output, bytes);
9474    ASSERT_ALLOC(changed, bytes);
9475
9476    PSA_ASSERT(psa_crypto_init());
9477
9478    /* Run several times, to ensure that every output byte will be
9479     * nonzero at least once with overwhelming probability
9480     * (2^(-8*number_of_runs)). */
9481    for (run = 0; run < 10; run++) {
9482        if (bytes != 0) {
9483            memset(output, 0, bytes);
9484        }
9485        PSA_ASSERT(psa_generate_random(output, bytes));
9486
9487        for (i = 0; i < bytes; i++) {
9488            if (output[i] != 0) {
9489                ++changed[i];
9490            }
9491        }
9492    }
9493
9494    /* Check that every byte was changed to nonzero at least once. This
9495     * validates that psa_generate_random is overwriting every byte of
9496     * the output buffer. */
9497    for (i = 0; i < bytes; i++) {
9498        TEST_ASSERT(changed[i] != 0);
9499    }
9500
9501exit:
9502    PSA_DONE();
9503    mbedtls_free(output);
9504    mbedtls_free(changed);
9505}
9506/* END_CASE */
9507
9508/* BEGIN_CASE */
9509void generate_key(int type_arg,
9510                  int bits_arg,
9511                  int usage_arg,
9512                  int alg_arg,
9513                  int expected_status_arg,
9514                  int is_large_key)
9515{
9516    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
9517    psa_key_type_t type = type_arg;
9518    psa_key_usage_t usage = usage_arg;
9519    size_t bits = bits_arg;
9520    psa_algorithm_t alg = alg_arg;
9521    psa_status_t expected_status = expected_status_arg;
9522    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
9523    psa_key_attributes_t got_attributes = PSA_KEY_ATTRIBUTES_INIT;
9524
9525    PSA_ASSERT(psa_crypto_init());
9526
9527    psa_set_key_usage_flags(&attributes, usage);
9528    psa_set_key_algorithm(&attributes, alg);
9529    psa_set_key_type(&attributes, type);
9530    psa_set_key_bits(&attributes, bits);
9531
9532    /* Generate a key */
9533    psa_status_t status = psa_generate_key(&attributes, &key);
9534
9535    if (is_large_key > 0) {
9536        TEST_ASSUME(status != PSA_ERROR_INSUFFICIENT_MEMORY);
9537    }
9538    TEST_EQUAL(status, expected_status);
9539    if (expected_status != PSA_SUCCESS) {
9540        goto exit;
9541    }
9542
9543    /* Test the key information */
9544    PSA_ASSERT(psa_get_key_attributes(key, &got_attributes));
9545    TEST_EQUAL(psa_get_key_type(&got_attributes), type);
9546    TEST_EQUAL(psa_get_key_bits(&got_attributes), bits);
9547
9548    /* Do something with the key according to its type and permitted usage. */
9549    if (!mbedtls_test_psa_exercise_key(key, usage, alg)) {
9550        goto exit;
9551    }
9552
9553exit:
9554    /*
9555     * Key attributes may have been returned by psa_get_key_attributes()
9556     * thus reset them as required.
9557     */
9558    psa_reset_key_attributes(&got_attributes);
9559
9560    psa_destroy_key(key);
9561    PSA_DONE();
9562}
9563/* END_CASE */
9564
9565/* BEGIN_CASE depends_on:PSA_WANT_KEY_TYPE_RSA_KEY_PAIR:PSA_WANT_ALG_RSA_PKCS1V15_CRYPT:PSA_WANT_ALG_RSA_PKCS1V15_SIGN:MBEDTLS_GENPRIME */
9566void generate_key_rsa(int bits_arg,
9567                      data_t *e_arg,
9568                      int expected_status_arg)
9569{
9570    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
9571    psa_key_type_t type = PSA_KEY_TYPE_RSA_KEY_PAIR;
9572    size_t bits = bits_arg;
9573    psa_key_usage_t usage = PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT;
9574    psa_algorithm_t alg = PSA_ALG_RSA_PKCS1V15_SIGN_RAW;
9575    psa_status_t expected_status = expected_status_arg;
9576    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
9577    uint8_t *exported = NULL;
9578    size_t exported_size =
9579        PSA_EXPORT_KEY_OUTPUT_SIZE(PSA_KEY_TYPE_RSA_PUBLIC_KEY, bits);
9580    size_t exported_length = SIZE_MAX;
9581    uint8_t *e_read_buffer = NULL;
9582    int is_default_public_exponent = 0;
9583    size_t e_read_size = PSA_KEY_DOMAIN_PARAMETERS_SIZE(type, bits);
9584    size_t e_read_length = SIZE_MAX;
9585
9586    if (e_arg->len == 0 ||
9587        (e_arg->len == 3 &&
9588         e_arg->x[0] == 1 && e_arg->x[1] == 0 && e_arg->x[2] == 1)) {
9589        is_default_public_exponent = 1;
9590        e_read_size = 0;
9591    }
9592    ASSERT_ALLOC(e_read_buffer, e_read_size);
9593    ASSERT_ALLOC(exported, exported_size);
9594
9595    PSA_ASSERT(psa_crypto_init());
9596
9597    psa_set_key_usage_flags(&attributes, usage);
9598    psa_set_key_algorithm(&attributes, alg);
9599    PSA_ASSERT(psa_set_key_domain_parameters(&attributes, type,
9600                                             e_arg->x, e_arg->len));
9601    psa_set_key_bits(&attributes, bits);
9602
9603    /* Generate a key */
9604    TEST_EQUAL(psa_generate_key(&attributes, &key), expected_status);
9605    if (expected_status != PSA_SUCCESS) {
9606        goto exit;
9607    }
9608
9609    /* Test the key information */
9610    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
9611    TEST_EQUAL(psa_get_key_type(&attributes), type);
9612    TEST_EQUAL(psa_get_key_bits(&attributes), bits);
9613    PSA_ASSERT(psa_get_key_domain_parameters(&attributes,
9614                                             e_read_buffer, e_read_size,
9615                                             &e_read_length));
9616    if (is_default_public_exponent) {
9617        TEST_EQUAL(e_read_length, 0);
9618    } else {
9619        ASSERT_COMPARE(e_read_buffer, e_read_length, e_arg->x, e_arg->len);
9620    }
9621
9622    /* Do something with the key according to its type and permitted usage. */
9623    if (!mbedtls_test_psa_exercise_key(key, usage, alg)) {
9624        goto exit;
9625    }
9626
9627    /* Export the key and check the public exponent. */
9628    PSA_ASSERT(psa_export_public_key(key,
9629                                     exported, exported_size,
9630                                     &exported_length));
9631    {
9632        uint8_t *p = exported;
9633        uint8_t *end = exported + exported_length;
9634        size_t len;
9635        /*   RSAPublicKey ::= SEQUENCE {
9636         *      modulus            INTEGER,    -- n
9637         *      publicExponent     INTEGER  }  -- e
9638         */
9639        TEST_EQUAL(0, mbedtls_asn1_get_tag(&p, end, &len,
9640                                           MBEDTLS_ASN1_SEQUENCE |
9641                                           MBEDTLS_ASN1_CONSTRUCTED));
9642        TEST_ASSERT(mbedtls_test_asn1_skip_integer(&p, end, bits, bits, 1));
9643        TEST_EQUAL(0, mbedtls_asn1_get_tag(&p, end, &len,
9644                                           MBEDTLS_ASN1_INTEGER));
9645        if (len >= 1 && p[0] == 0) {
9646            ++p;
9647            --len;
9648        }
9649        if (e_arg->len == 0) {
9650            TEST_EQUAL(len, 3);
9651            TEST_EQUAL(p[0], 1);
9652            TEST_EQUAL(p[1], 0);
9653            TEST_EQUAL(p[2], 1);
9654        } else {
9655            ASSERT_COMPARE(p, len, e_arg->x, e_arg->len);
9656        }
9657    }
9658
9659exit:
9660    /*
9661     * Key attributes may have been returned by psa_get_key_attributes() or
9662     * set by psa_set_key_domain_parameters() thus reset them as required.
9663     */
9664    psa_reset_key_attributes(&attributes);
9665
9666    psa_destroy_key(key);
9667    PSA_DONE();
9668    mbedtls_free(e_read_buffer);
9669    mbedtls_free(exported);
9670}
9671/* END_CASE */
9672
9673/* BEGIN_CASE depends_on:MBEDTLS_PSA_CRYPTO_STORAGE_C */
9674void persistent_key_load_key_from_storage(data_t *data,
9675                                          int type_arg, int bits_arg,
9676                                          int usage_flags_arg, int alg_arg,
9677                                          int generation_method)
9678{
9679    mbedtls_svc_key_id_t key_id = mbedtls_svc_key_id_make(1, 1);
9680    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
9681    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
9682    mbedtls_svc_key_id_t base_key = MBEDTLS_SVC_KEY_ID_INIT;
9683    psa_key_type_t type = type_arg;
9684    size_t bits = bits_arg;
9685    psa_key_usage_t usage_flags = usage_flags_arg;
9686    psa_algorithm_t alg = alg_arg;
9687    psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
9688    unsigned char *first_export = NULL;
9689    unsigned char *second_export = NULL;
9690    size_t export_size = PSA_EXPORT_KEY_OUTPUT_SIZE(type, bits);
9691    size_t first_exported_length;
9692    size_t second_exported_length;
9693
9694    if (usage_flags & PSA_KEY_USAGE_EXPORT) {
9695        ASSERT_ALLOC(first_export, export_size);
9696        ASSERT_ALLOC(second_export, export_size);
9697    }
9698
9699    PSA_ASSERT(psa_crypto_init());
9700
9701    psa_set_key_id(&attributes, key_id);
9702    psa_set_key_usage_flags(&attributes, usage_flags);
9703    psa_set_key_algorithm(&attributes, alg);
9704    psa_set_key_type(&attributes, type);
9705    psa_set_key_bits(&attributes, bits);
9706
9707    switch (generation_method) {
9708        case IMPORT_KEY:
9709            /* Import the key */
9710            PSA_ASSERT(psa_import_key(&attributes, data->x, data->len,
9711                                      &key));
9712            break;
9713
9714        case GENERATE_KEY:
9715            /* Generate a key */
9716            PSA_ASSERT(psa_generate_key(&attributes, &key));
9717            break;
9718
9719        case DERIVE_KEY:
9720#if defined(PSA_WANT_ALG_HKDF) && defined(PSA_WANT_ALG_SHA_256)
9721        {
9722            /* Create base key */
9723            psa_algorithm_t derive_alg = PSA_ALG_HKDF(PSA_ALG_SHA_256);
9724            psa_key_attributes_t base_attributes = PSA_KEY_ATTRIBUTES_INIT;
9725            psa_set_key_usage_flags(&base_attributes,
9726                                    PSA_KEY_USAGE_DERIVE);
9727            psa_set_key_algorithm(&base_attributes, derive_alg);
9728            psa_set_key_type(&base_attributes, PSA_KEY_TYPE_DERIVE);
9729            PSA_ASSERT(psa_import_key(&base_attributes,
9730                                      data->x, data->len,
9731                                      &base_key));
9732            /* Derive a key. */
9733            PSA_ASSERT(psa_key_derivation_setup(&operation, derive_alg));
9734            PSA_ASSERT(psa_key_derivation_input_key(
9735                           &operation,
9736                           PSA_KEY_DERIVATION_INPUT_SECRET, base_key));
9737            PSA_ASSERT(psa_key_derivation_input_bytes(
9738                           &operation, PSA_KEY_DERIVATION_INPUT_INFO,
9739                           NULL, 0));
9740            PSA_ASSERT(psa_key_derivation_output_key(&attributes,
9741                                                     &operation,
9742                                                     &key));
9743            PSA_ASSERT(psa_key_derivation_abort(&operation));
9744            PSA_ASSERT(psa_destroy_key(base_key));
9745            base_key = MBEDTLS_SVC_KEY_ID_INIT;
9746        }
9747#else
9748            TEST_ASSUME(!"KDF not supported in this configuration");
9749#endif
9750            break;
9751
9752        default:
9753            TEST_ASSERT(!"generation_method not implemented in test");
9754            break;
9755    }
9756    psa_reset_key_attributes(&attributes);
9757
9758    /* Export the key if permitted by the key policy. */
9759    if (usage_flags & PSA_KEY_USAGE_EXPORT) {
9760        PSA_ASSERT(psa_export_key(key,
9761                                  first_export, export_size,
9762                                  &first_exported_length));
9763        if (generation_method == IMPORT_KEY) {
9764            ASSERT_COMPARE(data->x, data->len,
9765                           first_export, first_exported_length);
9766        }
9767    }
9768
9769    /* Shutdown and restart */
9770    PSA_ASSERT(psa_purge_key(key));
9771    PSA_DONE();
9772    PSA_ASSERT(psa_crypto_init());
9773
9774    /* Check key slot still contains key data */
9775    PSA_ASSERT(psa_get_key_attributes(key, &attributes));
9776    TEST_ASSERT(mbedtls_svc_key_id_equal(
9777                    psa_get_key_id(&attributes), key_id));
9778    TEST_EQUAL(psa_get_key_lifetime(&attributes),
9779               PSA_KEY_LIFETIME_PERSISTENT);
9780    TEST_EQUAL(psa_get_key_type(&attributes), type);
9781    TEST_EQUAL(psa_get_key_bits(&attributes), bits);
9782    TEST_EQUAL(psa_get_key_usage_flags(&attributes),
9783               mbedtls_test_update_key_usage_flags(usage_flags));
9784    TEST_EQUAL(psa_get_key_algorithm(&attributes), alg);
9785
9786    /* Export the key again if permitted by the key policy. */
9787    if (usage_flags & PSA_KEY_USAGE_EXPORT) {
9788        PSA_ASSERT(psa_export_key(key,
9789                                  second_export, export_size,
9790                                  &second_exported_length));
9791        ASSERT_COMPARE(first_export, first_exported_length,
9792                       second_export, second_exported_length);
9793    }
9794
9795    /* Do something with the key according to its type and permitted usage. */
9796    if (!mbedtls_test_psa_exercise_key(key, usage_flags, alg)) {
9797        goto exit;
9798    }
9799
9800exit:
9801    /*
9802     * Key attributes may have been returned by psa_get_key_attributes()
9803     * thus reset them as required.
9804     */
9805    psa_reset_key_attributes(&attributes);
9806
9807    mbedtls_free(first_export);
9808    mbedtls_free(second_export);
9809    psa_key_derivation_abort(&operation);
9810    psa_destroy_key(base_key);
9811    psa_destroy_key(key);
9812    PSA_DONE();
9813}
9814/* END_CASE */
9815
9816/* BEGIN_CASE depends_on:PSA_WANT_ALG_JPAKE */
9817void ecjpake_setup(int alg_arg, int key_type_pw_arg, int key_usage_pw_arg,
9818                   int primitive_arg, int hash_arg, int role_arg,
9819                   int test_input, data_t *pw_data,
9820                   int inj_err_type_arg,
9821                   int expected_error_arg)
9822{
9823    psa_pake_cipher_suite_t cipher_suite = psa_pake_cipher_suite_init();
9824    psa_pake_operation_t operation = psa_pake_operation_init();
9825    psa_algorithm_t alg = alg_arg;
9826    psa_pake_primitive_t primitive = primitive_arg;
9827    psa_key_type_t key_type_pw = key_type_pw_arg;
9828    psa_key_usage_t key_usage_pw = key_usage_pw_arg;
9829    psa_algorithm_t hash_alg = hash_arg;
9830    psa_pake_role_t role = role_arg;
9831    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
9832    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
9833    ecjpake_injected_failure_t inj_err_type = inj_err_type_arg;
9834    psa_status_t expected_error = expected_error_arg;
9835    psa_status_t status;
9836    unsigned char *output_buffer = NULL;
9837    size_t output_len = 0;
9838
9839    PSA_INIT();
9840
9841    size_t buf_size = PSA_PAKE_OUTPUT_SIZE(alg, primitive_arg,
9842                                           PSA_PAKE_STEP_KEY_SHARE);
9843    ASSERT_ALLOC(output_buffer, buf_size);
9844
9845    if (pw_data->len > 0) {
9846        psa_set_key_usage_flags(&attributes, key_usage_pw);
9847        psa_set_key_algorithm(&attributes, alg);
9848        psa_set_key_type(&attributes, key_type_pw);
9849        PSA_ASSERT(psa_import_key(&attributes, pw_data->x, pw_data->len,
9850                                  &key));
9851    }
9852
9853    psa_pake_cs_set_algorithm(&cipher_suite, alg);
9854    psa_pake_cs_set_primitive(&cipher_suite, primitive);
9855    psa_pake_cs_set_hash(&cipher_suite, hash_alg);
9856
9857    PSA_ASSERT(psa_pake_abort(&operation));
9858
9859    if (inj_err_type == INJECT_ERR_UNINITIALIZED_ACCESS) {
9860        TEST_EQUAL(psa_pake_set_user(&operation, NULL, 0),
9861                   expected_error);
9862        PSA_ASSERT(psa_pake_abort(&operation));
9863        TEST_EQUAL(psa_pake_set_peer(&operation, NULL, 0),
9864                   expected_error);
9865        PSA_ASSERT(psa_pake_abort(&operation));
9866        TEST_EQUAL(psa_pake_set_password_key(&operation, key),
9867                   expected_error);
9868        PSA_ASSERT(psa_pake_abort(&operation));
9869        TEST_EQUAL(psa_pake_set_role(&operation, role),
9870                   expected_error);
9871        PSA_ASSERT(psa_pake_abort(&operation));
9872        TEST_EQUAL(psa_pake_output(&operation, PSA_PAKE_STEP_KEY_SHARE,
9873                                   NULL, 0, NULL),
9874                   expected_error);
9875        PSA_ASSERT(psa_pake_abort(&operation));
9876        TEST_EQUAL(psa_pake_input(&operation, PSA_PAKE_STEP_KEY_SHARE, NULL, 0),
9877                   expected_error);
9878        PSA_ASSERT(psa_pake_abort(&operation));
9879        goto exit;
9880    }
9881
9882    status = psa_pake_setup(&operation, &cipher_suite);
9883    if (status != PSA_SUCCESS) {
9884        TEST_EQUAL(status, expected_error);
9885        goto exit;
9886    }
9887
9888    if (inj_err_type == INJECT_ERR_DUPLICATE_SETUP) {
9889        TEST_EQUAL(psa_pake_setup(&operation, &cipher_suite),
9890                   expected_error);
9891        goto exit;
9892    }
9893
9894    status = psa_pake_set_role(&operation, role);
9895    if (status != PSA_SUCCESS) {
9896        TEST_EQUAL(status, expected_error);
9897        goto exit;
9898    }
9899
9900    if (pw_data->len > 0) {
9901        status = psa_pake_set_password_key(&operation, key);
9902        if (status != PSA_SUCCESS) {
9903            TEST_EQUAL(status, expected_error);
9904            goto exit;
9905        }
9906    }
9907
9908    if (inj_err_type == INJECT_ERR_INVALID_USER) {
9909        TEST_EQUAL(psa_pake_set_user(&operation, NULL, 0),
9910                   PSA_ERROR_INVALID_ARGUMENT);
9911        goto exit;
9912    }
9913
9914    if (inj_err_type == INJECT_ERR_INVALID_PEER) {
9915        TEST_EQUAL(psa_pake_set_peer(&operation, NULL, 0),
9916                   PSA_ERROR_INVALID_ARGUMENT);
9917        goto exit;
9918    }
9919
9920    if (inj_err_type == INJECT_ERR_SET_USER) {
9921        const uint8_t unsupported_id[] = "abcd";
9922        TEST_EQUAL(psa_pake_set_user(&operation, unsupported_id, 4),
9923                   PSA_ERROR_NOT_SUPPORTED);
9924        goto exit;
9925    }
9926
9927    if (inj_err_type == INJECT_ERR_SET_PEER) {
9928        const uint8_t unsupported_id[] = "abcd";
9929        TEST_EQUAL(psa_pake_set_peer(&operation, unsupported_id, 4),
9930                   PSA_ERROR_NOT_SUPPORTED);
9931        goto exit;
9932    }
9933
9934    const size_t size_key_share = PSA_PAKE_INPUT_SIZE(alg, primitive,
9935                                                      PSA_PAKE_STEP_KEY_SHARE);
9936    const size_t size_zk_public = PSA_PAKE_INPUT_SIZE(alg, primitive,
9937                                                      PSA_PAKE_STEP_ZK_PUBLIC);
9938    const size_t size_zk_proof = PSA_PAKE_INPUT_SIZE(alg, primitive,
9939                                                     PSA_PAKE_STEP_ZK_PROOF);
9940
9941    if (test_input) {
9942        if (inj_err_type == INJECT_EMPTY_IO_BUFFER) {
9943            TEST_EQUAL(psa_pake_input(&operation, PSA_PAKE_STEP_ZK_PROOF, NULL, 0),
9944                       PSA_ERROR_INVALID_ARGUMENT);
9945            goto exit;
9946        }
9947
9948        if (inj_err_type == INJECT_UNKNOWN_STEP) {
9949            TEST_EQUAL(psa_pake_input(&operation, PSA_PAKE_STEP_ZK_PROOF + 10,
9950                                      output_buffer, size_zk_proof),
9951                       PSA_ERROR_INVALID_ARGUMENT);
9952            goto exit;
9953        }
9954
9955        if (inj_err_type == INJECT_INVALID_FIRST_STEP) {
9956            TEST_EQUAL(psa_pake_input(&operation, PSA_PAKE_STEP_ZK_PROOF,
9957                                      output_buffer, size_zk_proof),
9958                       PSA_ERROR_BAD_STATE);
9959            goto exit;
9960        }
9961
9962        status = psa_pake_input(&operation, PSA_PAKE_STEP_KEY_SHARE,
9963                                output_buffer, size_key_share);
9964        if (status != PSA_SUCCESS) {
9965            TEST_EQUAL(status, expected_error);
9966            goto exit;
9967        }
9968
9969        if (inj_err_type == INJECT_WRONG_BUFFER_SIZE) {
9970            TEST_EQUAL(psa_pake_input(&operation, PSA_PAKE_STEP_ZK_PUBLIC,
9971                                      output_buffer, size_zk_public + 1),
9972                       PSA_ERROR_INVALID_ARGUMENT);
9973            goto exit;
9974        }
9975
9976        if (inj_err_type == INJECT_VALID_OPERATION_AFTER_FAILURE) {
9977            // Just trigger any kind of error. We don't care about the result here
9978            psa_pake_input(&operation, PSA_PAKE_STEP_ZK_PUBLIC,
9979                           output_buffer, size_zk_public + 1);
9980            TEST_EQUAL(psa_pake_input(&operation, PSA_PAKE_STEP_ZK_PUBLIC,
9981                                      output_buffer, size_zk_public),
9982                       PSA_ERROR_BAD_STATE);
9983            goto exit;
9984        }
9985    } else {
9986        if (inj_err_type == INJECT_EMPTY_IO_BUFFER) {
9987            TEST_EQUAL(psa_pake_output(&operation, PSA_PAKE_STEP_ZK_PROOF,
9988                                       NULL, 0, NULL),
9989                       PSA_ERROR_INVALID_ARGUMENT);
9990            goto exit;
9991        }
9992
9993        if (inj_err_type == INJECT_UNKNOWN_STEP) {
9994            TEST_EQUAL(psa_pake_output(&operation, PSA_PAKE_STEP_ZK_PROOF + 10,
9995                                       output_buffer, buf_size, &output_len),
9996                       PSA_ERROR_INVALID_ARGUMENT);
9997            goto exit;
9998        }
9999
10000        if (inj_err_type == INJECT_INVALID_FIRST_STEP) {
10001            TEST_EQUAL(psa_pake_output(&operation, PSA_PAKE_STEP_ZK_PROOF,
10002                                       output_buffer, buf_size, &output_len),
10003                       PSA_ERROR_BAD_STATE);
10004            goto exit;
10005        }
10006
10007        status = psa_pake_output(&operation, PSA_PAKE_STEP_KEY_SHARE,
10008                                 output_buffer, buf_size, &output_len);
10009        if (status != PSA_SUCCESS) {
10010            TEST_EQUAL(status, expected_error);
10011            goto exit;
10012        }
10013
10014        TEST_ASSERT(output_len > 0);
10015
10016        if (inj_err_type == INJECT_WRONG_BUFFER_SIZE) {
10017            TEST_EQUAL(psa_pake_output(&operation, PSA_PAKE_STEP_ZK_PUBLIC,
10018                                       output_buffer, size_zk_public - 1, &output_len),
10019                       PSA_ERROR_BUFFER_TOO_SMALL);
10020            goto exit;
10021        }
10022
10023        if (inj_err_type == INJECT_VALID_OPERATION_AFTER_FAILURE) {
10024            // Just trigger any kind of error. We don't care about the result here
10025            psa_pake_output(&operation, PSA_PAKE_STEP_ZK_PUBLIC,
10026                            output_buffer, size_zk_public - 1, &output_len);
10027            TEST_EQUAL(psa_pake_output(&operation, PSA_PAKE_STEP_ZK_PUBLIC,
10028                                       output_buffer, buf_size, &output_len),
10029                       PSA_ERROR_BAD_STATE);
10030            goto exit;
10031        }
10032    }
10033
10034exit:
10035    PSA_ASSERT(psa_destroy_key(key));
10036    PSA_ASSERT(psa_pake_abort(&operation));
10037    mbedtls_free(output_buffer);
10038    PSA_DONE();
10039}
10040/* END_CASE */
10041
10042/* BEGIN_CASE depends_on:PSA_WANT_ALG_JPAKE */
10043void ecjpake_rounds_inject(int alg_arg, int primitive_arg, int hash_arg,
10044                           int client_input_first, int inject_error,
10045                           data_t *pw_data)
10046{
10047    psa_pake_cipher_suite_t cipher_suite = psa_pake_cipher_suite_init();
10048    psa_pake_operation_t server = psa_pake_operation_init();
10049    psa_pake_operation_t client = psa_pake_operation_init();
10050    psa_algorithm_t alg = alg_arg;
10051    psa_algorithm_t hash_alg = hash_arg;
10052    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
10053    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
10054
10055    PSA_INIT();
10056
10057    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DERIVE);
10058    psa_set_key_algorithm(&attributes, alg);
10059    psa_set_key_type(&attributes, PSA_KEY_TYPE_PASSWORD);
10060    PSA_ASSERT(psa_import_key(&attributes, pw_data->x, pw_data->len,
10061                              &key));
10062
10063    psa_pake_cs_set_algorithm(&cipher_suite, alg);
10064    psa_pake_cs_set_primitive(&cipher_suite, primitive_arg);
10065    psa_pake_cs_set_hash(&cipher_suite, hash_alg);
10066
10067
10068    PSA_ASSERT(psa_pake_setup(&server, &cipher_suite));
10069    PSA_ASSERT(psa_pake_setup(&client, &cipher_suite));
10070
10071    PSA_ASSERT(psa_pake_set_role(&server, PSA_PAKE_ROLE_SERVER));
10072    PSA_ASSERT(psa_pake_set_role(&client, PSA_PAKE_ROLE_CLIENT));
10073
10074    PSA_ASSERT(psa_pake_set_password_key(&server, key));
10075    PSA_ASSERT(psa_pake_set_password_key(&client, key));
10076
10077    ecjpake_do_round(alg, primitive_arg, &server, &client,
10078                     client_input_first, 1, inject_error);
10079
10080    if (inject_error == 1 || inject_error == 2) {
10081        goto exit;
10082    }
10083
10084    ecjpake_do_round(alg, primitive_arg, &server, &client,
10085                     client_input_first, 2, inject_error);
10086
10087exit:
10088    psa_destroy_key(key);
10089    psa_pake_abort(&server);
10090    psa_pake_abort(&client);
10091    PSA_DONE();
10092}
10093/* END_CASE */
10094
10095/* BEGIN_CASE depends_on:PSA_WANT_ALG_JPAKE */
10096void ecjpake_rounds(int alg_arg, int primitive_arg, int hash_arg,
10097                    int derive_alg_arg, data_t *pw_data,
10098                    int client_input_first, int inj_err_type_arg)
10099{
10100    psa_pake_cipher_suite_t cipher_suite = psa_pake_cipher_suite_init();
10101    psa_pake_operation_t server = psa_pake_operation_init();
10102    psa_pake_operation_t client = psa_pake_operation_init();
10103    psa_algorithm_t alg = alg_arg;
10104    psa_algorithm_t hash_alg = hash_arg;
10105    psa_algorithm_t derive_alg = derive_alg_arg;
10106    mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
10107    psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
10108    psa_key_derivation_operation_t server_derive =
10109        PSA_KEY_DERIVATION_OPERATION_INIT;
10110    psa_key_derivation_operation_t client_derive =
10111        PSA_KEY_DERIVATION_OPERATION_INIT;
10112    ecjpake_injected_failure_t inj_err_type = inj_err_type_arg;
10113
10114    PSA_INIT();
10115
10116    psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DERIVE);
10117    psa_set_key_algorithm(&attributes, alg);
10118    psa_set_key_type(&attributes, PSA_KEY_TYPE_PASSWORD);
10119    PSA_ASSERT(psa_import_key(&attributes, pw_data->x, pw_data->len,
10120                              &key));
10121
10122    psa_pake_cs_set_algorithm(&cipher_suite, alg);
10123    psa_pake_cs_set_primitive(&cipher_suite, primitive_arg);
10124    psa_pake_cs_set_hash(&cipher_suite, hash_alg);
10125
10126    /* Get shared key */
10127    PSA_ASSERT(psa_key_derivation_setup(&server_derive, derive_alg));
10128    PSA_ASSERT(psa_key_derivation_setup(&client_derive, derive_alg));
10129
10130    if (PSA_ALG_IS_TLS12_PRF(derive_alg) ||
10131        PSA_ALG_IS_TLS12_PSK_TO_MS(derive_alg)) {
10132        PSA_ASSERT(psa_key_derivation_input_bytes(&server_derive,
10133                                                  PSA_KEY_DERIVATION_INPUT_SEED,
10134                                                  (const uint8_t *) "", 0));
10135        PSA_ASSERT(psa_key_derivation_input_bytes(&client_derive,
10136                                                  PSA_KEY_DERIVATION_INPUT_SEED,
10137                                                  (const uint8_t *) "", 0));
10138    }
10139
10140    PSA_ASSERT(psa_pake_setup(&server, &cipher_suite));
10141    PSA_ASSERT(psa_pake_setup(&client, &cipher_suite));
10142
10143    PSA_ASSERT(psa_pake_set_role(&server, PSA_PAKE_ROLE_SERVER));
10144    PSA_ASSERT(psa_pake_set_role(&client, PSA_PAKE_ROLE_CLIENT));
10145
10146    PSA_ASSERT(psa_pake_set_password_key(&server, key));
10147    PSA_ASSERT(psa_pake_set_password_key(&client, key));
10148
10149    if (inj_err_type == INJECT_ANTICIPATE_KEY_DERIVATION_1) {
10150        TEST_EQUAL(psa_pake_get_implicit_key(&server, &server_derive),
10151                   PSA_ERROR_BAD_STATE);
10152        TEST_EQUAL(psa_pake_get_implicit_key(&client, &client_derive),
10153                   PSA_ERROR_BAD_STATE);
10154        goto exit;
10155    }
10156
10157    /* First round */
10158    ecjpake_do_round(alg, primitive_arg, &server, &client,
10159                     client_input_first, 1, 0);
10160
10161    if (inj_err_type == INJECT_ANTICIPATE_KEY_DERIVATION_2) {
10162        TEST_EQUAL(psa_pake_get_implicit_key(&server, &server_derive),
10163                   PSA_ERROR_BAD_STATE);
10164        TEST_EQUAL(psa_pake_get_implicit_key(&client, &client_derive),
10165                   PSA_ERROR_BAD_STATE);
10166        goto exit;
10167    }
10168
10169    /* Second round */
10170    ecjpake_do_round(alg, primitive_arg, &server, &client,
10171                     client_input_first, 2, 0);
10172
10173    PSA_ASSERT(psa_pake_get_implicit_key(&server, &server_derive));
10174    PSA_ASSERT(psa_pake_get_implicit_key(&client, &client_derive));
10175
10176exit:
10177    psa_key_derivation_abort(&server_derive);
10178    psa_key_derivation_abort(&client_derive);
10179    psa_destroy_key(key);
10180    psa_pake_abort(&server);
10181    psa_pake_abort(&client);
10182    PSA_DONE();
10183}
10184/* END_CASE */
10185
10186/* BEGIN_CASE */
10187void ecjpake_size_macros()
10188{
10189    const psa_algorithm_t alg = PSA_ALG_JPAKE;
10190    const size_t bits = 256;
10191    const psa_pake_primitive_t prim = PSA_PAKE_PRIMITIVE(
10192        PSA_PAKE_PRIMITIVE_TYPE_ECC, PSA_ECC_FAMILY_SECP_R1, bits);
10193    const psa_key_type_t key_type = PSA_KEY_TYPE_ECC_KEY_PAIR(
10194        PSA_ECC_FAMILY_SECP_R1);
10195
10196    // https://armmbed.github.io/mbed-crypto/1.1_PAKE_Extension.0-bet.0/html/pake.html#pake-step-types
10197    /* The output for KEY_SHARE and ZK_PUBLIC is the same as a public key */
10198    TEST_EQUAL(PSA_PAKE_OUTPUT_SIZE(alg, prim, PSA_PAKE_STEP_KEY_SHARE),
10199               PSA_EXPORT_PUBLIC_KEY_OUTPUT_SIZE(key_type, bits));
10200    TEST_EQUAL(PSA_PAKE_OUTPUT_SIZE(alg, prim, PSA_PAKE_STEP_ZK_PUBLIC),
10201               PSA_EXPORT_PUBLIC_KEY_OUTPUT_SIZE(key_type, bits));
10202    /* The output for ZK_PROOF is the same bitsize as the curve */
10203    TEST_EQUAL(PSA_PAKE_OUTPUT_SIZE(alg, prim, PSA_PAKE_STEP_ZK_PROOF),
10204               PSA_BITS_TO_BYTES(bits));
10205
10206    /* Input sizes are the same as output sizes */
10207    TEST_EQUAL(PSA_PAKE_OUTPUT_SIZE(alg, prim, PSA_PAKE_STEP_KEY_SHARE),
10208               PSA_PAKE_INPUT_SIZE(alg, prim, PSA_PAKE_STEP_KEY_SHARE));
10209    TEST_EQUAL(PSA_PAKE_OUTPUT_SIZE(alg, prim, PSA_PAKE_STEP_ZK_PUBLIC),
10210               PSA_PAKE_INPUT_SIZE(alg, prim, PSA_PAKE_STEP_ZK_PUBLIC));
10211    TEST_EQUAL(PSA_PAKE_OUTPUT_SIZE(alg, prim, PSA_PAKE_STEP_ZK_PROOF),
10212               PSA_PAKE_INPUT_SIZE(alg, prim, PSA_PAKE_STEP_ZK_PROOF));
10213
10214    /* These inequalities will always hold even when other PAKEs are added */
10215    TEST_LE_U(PSA_PAKE_OUTPUT_SIZE(alg, prim, PSA_PAKE_STEP_KEY_SHARE),
10216              PSA_PAKE_OUTPUT_MAX_SIZE);
10217    TEST_LE_U(PSA_PAKE_OUTPUT_SIZE(alg, prim, PSA_PAKE_STEP_ZK_PUBLIC),
10218              PSA_PAKE_OUTPUT_MAX_SIZE);
10219    TEST_LE_U(PSA_PAKE_OUTPUT_SIZE(alg, prim, PSA_PAKE_STEP_ZK_PROOF),
10220              PSA_PAKE_OUTPUT_MAX_SIZE);
10221    TEST_LE_U(PSA_PAKE_INPUT_SIZE(alg, prim, PSA_PAKE_STEP_KEY_SHARE),
10222              PSA_PAKE_INPUT_MAX_SIZE);
10223    TEST_LE_U(PSA_PAKE_INPUT_SIZE(alg, prim, PSA_PAKE_STEP_ZK_PUBLIC),
10224              PSA_PAKE_INPUT_MAX_SIZE);
10225    TEST_LE_U(PSA_PAKE_INPUT_SIZE(alg, prim, PSA_PAKE_STEP_ZK_PROOF),
10226              PSA_PAKE_INPUT_MAX_SIZE);
10227}
10228/* END_CASE */
10229