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