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