aboutsummaryrefslogtreecommitdiff
path: root/tests/psa-client-server/psasim/src/psa_sim_generate.pl
blob: 15f57949df63a2e65fb71df3a5efdec797c6b449 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
#!/usr/bin/env perl
#
# This is a proof-of-concept script to show that the client and server wrappers
# can be created by a script. It is not hooked into the build, so is run
# manually and the output files are what are to be reviewed. In due course
# this will be replaced by a Python script.
#
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
#
use strict;
use Data::Dumper;
use JSON qw(encode_json);

my $debug = 0;

# Globals (sorry!)
my %functions = get_functions();
my @functions = sort keys %functions;

# get_functions(), called above, returns a data structure for each function
# that we need to create client and server stubs for. In this example Perl script,
# the function declarations we want are in the data section (after __END__ at
# the bottom of this file), but a production Python version should process
# psa_crypto.h.
#
# In this script, the data for psa_crypto_init() looks like:
#
#   "psa_crypto_init": {
#     "return": {               # Info on return type
#       "type": "psa_status_t", # Return type
#       "name": "status",       # Name to be used for this in C code
#       "default": "PSA_ERROR_CORRUPTION_DETECTED"      # Default value
#     },
#     "args": [],               # void function, so args empty
#   }
#
# The data for psa_hash_compute() looks like:
#
#  "psa_hash_compute": {
#    "return": {                # Information on return type
#      "type": "psa_status_t",
#      "name": "status",
#      "default": "PSA_ERROR_CORRUPTION_DETECTED"
#    },
#    "args": [{
#        "type": "psa_algorithm_t",             # Type of first argument
#        "ctypename": "psa_algorithm_t ",       # C type with trailing spaces
#                                               # (so that e.g. `char *` looks ok)
#        "name": "alg",
#        "is_output": 0
#      }, {
#        "type": "const buffer",                # Specially created
#        "ctypename": "",                       # (so no C type)
#        "name": "input, input_length",         # A pair of arguments
#        "is_output": 0                         # const, so not an output argument
#      }, {
#        "type": "buffer",                      # Specially created
#        "ctypename": "",
#        "name": "hash, hash_size",
#        "is_output": 1                         # Not const, so output argument
#      }, {
#        "type": "size_t",                      # size_t *hash_length
#        "ctypename": "size_t ",
#        "name": "*hash_length",                # * comes into the name
#        "is_output": 1
#      }
#    ],
#  },
#
# It's possible that a production version might not need both type and ctypename;
# that was done for convenience and future-proofing during development.

# We'll do psa_crypto_init() first
put_crypto_init_first(\@functions);

write_function_codes("psa_functions_codes.h");

write_client_calls("psa_sim_crypto_client.c");

write_server_implementations("psa_sim_crypto_server.c");

sub write_function_codes
{
    my ($file) = @_;

    open(my $fh, ">", $file) || die("$0: $file: $!\n");

    # NOTE: psa_crypto_init() is written manually

    print $fh <<EOF;
/* THIS FILE WAS AUTO-GENERATED BY psa_sim_generate.pl. DO NOT EDIT!! */

/*
 *  Copyright The Mbed TLS Contributors
 *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
 */

#ifndef _PSA_FUNCTIONS_CODES_H_
#define  _PSA_FUNCTIONS_CODES_H_

enum {
    /* Start here to avoid overlap with PSA_IPC_CONNECT, PSA_IPC_DISCONNECT
     * and VERSION_REQUEST */
    PSA_CRYPTO_INIT = 100,
EOF

    for my $function (@functions) {
        my $enum = uc($function);
        if ($enum ne "PSA_CRYPTO_INIT") {
            print $fh <<EOF;
    $enum,
EOF
        }
    }

    print $fh <<EOF;
};

#endif /*  _PSA_FUNCTIONS_CODES_H_ */
EOF

    close($fh);
}

sub write_client_calls
{
    my ($file) = @_;

    open(my $fh, ">", $file) || die("$0: $file: $!\n");

    print $fh client_calls_header();

    for my $function (@functions) {
        # psa_crypto_init() is hand written to establish connection to server
        if ($function ne "psa_crypto_init") {
            my $f = $functions{$function};
            output_client($fh, $f, $function);
        }
    }

    close($fh);
}

sub write_server_implementations
{
    my ($file) = @_;

    open(my $fh, ">", $file) || die("$0: $file: $!\n");

    print $fh server_implementations_header();

    print $fh debug_functions() if $debug;

    for my $function (@functions) {
        my $f = $functions{$function};
        output_server_wrapper($fh, $f, $function);
    }

    # Now output a switch statement that calls each of the wrappers

    print $fh <<EOF;

psa_status_t psa_crypto_call(psa_msg_t msg)
{
    int ok = 0;

    int func = msg.type;

    /* We only expect a single input buffer, with everything serialised in it */
    if (msg.in_size[1] != 0 || msg.in_size[2] != 0 || msg.in_size[3] != 0) {
        return PSA_ERROR_INVALID_ARGUMENT;
    }

    /* We expect exactly 2 output buffers, one for size, the other for data */
    if (msg.out_size[0] != sizeof(size_t) || msg.out_size[1] == 0 ||
        msg.out_size[2] != 0 || msg.out_size[3] != 0) {
        return PSA_ERROR_INVALID_ARGUMENT;
    }

    uint8_t *in_params = NULL;
    size_t in_params_len = 0;
    uint8_t *out_params = NULL;
    size_t out_params_len = 0;

    in_params_len = msg.in_size[0];
    in_params = malloc(in_params_len);
    if (in_params == NULL) {
        return PSA_ERROR_INSUFFICIENT_MEMORY;
    }

    /* Read the bytes from the client */
    size_t actual = psa_read(msg.handle, 0, in_params, in_params_len);
    if (actual != in_params_len) {
        free(in_params);
        return PSA_ERROR_CORRUPTION_DETECTED;
    }

    switch (func) {
EOF

    for my $function (@functions) {
        my $f = $functions{$function};
        my $enum = uc($function);

        # Create this call, in a way acceptable to uncustify:
        #            ok = ${function}_wrapper(in_params, in_params_len,
        #                                     &out_params, &out_params_len);
        my $first_line = "            ok = ${function}_wrapper(in_params, in_params_len,";
        my $idx = index($first_line, "(");
        die("can't find (") if $idx < 0;
        my $indent = " " x ($idx + 1);

        print $fh <<EOF;
        case $enum:
$first_line
$indent&out_params, &out_params_len);
            break;
EOF
    }

    print $fh <<EOF;
    }

    free(in_params);

    if (out_params_len > msg.out_size[1]) {
        fprintf(stderr, "unable to write %zu bytes into buffer of %zu bytes\\n",
                out_params_len, msg.out_size[1]);
        exit(1);
    }

    /* Write the exact amount of data we're returning */
    psa_write(msg.handle, 0, &out_params_len, sizeof(out_params_len));

    /* And write the data itself */
    if (out_params_len) {
        psa_write(msg.handle, 1, out_params, out_params_len);
    }

    free(out_params);

    return ok ? PSA_SUCCESS : PSA_ERROR_GENERIC_ERROR;
}
EOF

    close($fh);
}

sub server_implementations_header
{
    return <<'EOF';
/* THIS FILE WAS AUTO-GENERATED BY psa_sim_generate.pl. DO NOT EDIT!! */

/* server implementations */

/*
 *  Copyright The Mbed TLS Contributors
 *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
 */

#include <stdio.h>
#include <stdlib.h>

#include <psa/crypto.h>

#include "psa_functions_codes.h"
#include "psa_sim_serialise.h"

#include "service.h"

#if !defined(MBEDTLS_PSA_CRYPTO_C)
#error "Error: MBEDTLS_PSA_CRYPTO_C must be enabled on server build"
#endif
EOF
}

sub client_calls_header
{
    my $code = <<'EOF';
/* THIS FILE WAS AUTO-GENERATED BY psa_sim_generate.pl. DO NOT EDIT!! */

/* client calls */

/*
 *  Copyright The Mbed TLS Contributors
 *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
 */

#include <stdio.h>
#include <unistd.h>

/* Includes from psasim */
#include <client.h>
#include <util.h>
#include "psa_manifest/sid.h"
#include "psa_functions_codes.h"
#include "psa_sim_serialise.h"

/* Includes from mbedtls */
#include "mbedtls/version.h"
#include "psa/crypto.h"

#define CLIENT_PRINT(fmt, ...) \
    INFO("Client: " fmt, ##__VA_ARGS__)

static psa_handle_t handle = -1;

#if defined(MBEDTLS_PSA_CRYPTO_C)
#error "Error: MBEDTLS_PSA_CRYPTO_C must be disabled on client build"
#endif
EOF

    $code .= debug_functions() if $debug;

    $code .= <<'EOF';

int psa_crypto_call(int function,
                    uint8_t *in_params, size_t in_params_len,
                    uint8_t **out_params, size_t *out_params_len)
{
    // psa_outvec outvecs[1];
    if (handle < 0) {
        fprintf(stderr, "NOT CONNECTED\n");
        exit(1);
    }

    psa_invec invec;
    invec.base = in_params;
    invec.len = in_params_len;

    size_t max_receive = 8192;
    uint8_t *receive = malloc(max_receive);
    if (receive == NULL) {
        fprintf(stderr, "FAILED to allocate %u bytes\n", (unsigned) max_receive);
        exit(1);
    }

    size_t actual_received = 0;

    psa_outvec outvecs[2];
    outvecs[0].base = &actual_received;
    outvecs[0].len = sizeof(actual_received);
    outvecs[1].base = receive;
    outvecs[1].len = max_receive;

    psa_status_t status = psa_call(handle, function, &invec, 1, outvecs, 2);
    if (status != PSA_SUCCESS) {
        free(receive);
        return 0;
    }

    *out_params = receive;
    *out_params_len = actual_received;

    return 1;   // success
}

psa_status_t psa_crypto_init(void)
{
    char mbedtls_version[18];
    uint8_t *result = NULL;
    size_t result_length;
    psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;

    mbedtls_version_get_string_full(mbedtls_version);
    CLIENT_PRINT("%s", mbedtls_version);

    CLIENT_PRINT("My PID: %d", getpid());

    CLIENT_PRINT("PSA version: %u", psa_version(PSA_SID_CRYPTO_SID));
    handle = psa_connect(PSA_SID_CRYPTO_SID, 1);

    if (handle < 0) {
        CLIENT_PRINT("Couldn't connect %d", handle);
        return PSA_ERROR_COMMUNICATION_FAILURE;
    }

    int ok = psa_crypto_call(PSA_CRYPTO_INIT, NULL, 0, &result, &result_length);
    CLIENT_PRINT("PSA_CRYPTO_INIT returned: %d", ok);

    if (!ok) {
        goto fail;
    }

    uint8_t *rpos = result;
    size_t rremain = result_length;

    ok = psasim_deserialise_begin(&rpos, &rremain);
    if (!ok) {
        goto fail;
    }

    ok = psasim_deserialise_psa_status_t(&rpos, &rremain, &status);
    if (!ok) {
        goto fail;
    }

fail:
    free(result);

    return status;
}

void mbedtls_psa_crypto_free(void)
{
    CLIENT_PRINT("Closing handle");
    psa_close(handle);
    handle = -1;
}
EOF
}

sub debug_functions
{
    return <<EOF;

static inline char hex_digit(char nibble) {
    return (nibble < 10) ? (nibble + '0') : (nibble + 'a' - 10);
}

int hex_byte(char *p, uint8_t b)
{
    p[0] = hex_digit(b >> 4);
    p[1] = hex_digit(b & 0x0F);

    return 2;
}

int hex_uint16(char *p, uint16_t b)
{
    hex_byte(p, b >> 8);
    hex_byte(p + 2, b & 0xFF);

    return 4;
}

char human_char(uint8_t c)
{
    return (c >= ' ' && c <= '~') ? (char)c : '.';
}

void dump_buffer(const uint8_t *buffer, size_t len)
{
    char line[80];

    const uint8_t *p = buffer;

    size_t max = (len > 0xFFFF) ? 0xFFFF : len;

    for (size_t i = 0; i < max; i += 16) {

        char *q = line;

        q += hex_uint16(q, (uint16_t)i);
        *q++ = ' ';
        *q++ = ' ';

        size_t ll = (i + 16 > max) ? (max % 16) : 16;

        size_t j;
        for (j = 0; j < ll; j++) {
            q += hex_byte(q, p[i + j]);
            *q++ = ' ';
        }

        while (j++ < 16) {
            *q++ = ' ';
            *q++ = ' ';
            *q++ = ' ';
        }

        *q++ = ' ';

        for (j = 0; j < ll; j++) {
            *q++ = human_char(p[i + j]);
        }

        *q = '\\0';

        printf("%s\\n", line);
    }
}

void hex_dump(uint8_t *p, size_t n)
{
    for (size_t i = 0; i < n; i++) {
        printf("0x%02X ", p[i]);
    }
    printf("\\n");
}
EOF
}

sub output_server_wrapper
{
    my ($fh, $f, $name) = @_;

    my $ret_type = $f->{return}->{type};
    my $ret_name = $f->{return}->{name};
    my $ret_default = $f->{return}->{default};

    my @buffers = ();           # We need to free() these on exit

    print $fh <<EOF;

// Returns 1 for success, 0 for failure
int ${name}_wrapper(
    uint8_t *in_params, size_t in_params_len,
    uint8_t **out_params, size_t *out_params_len)
{
    $ret_type $ret_name = $ret_default;
EOF
    # Output the variables we will need when we call the target function

    my $args = $f->{args};

    for my $i (0 .. $#$args) {
        my $arg = $args->[$i];
        my $argtype = $arg->{type};     # e.g. int, psa_algorithm_t, or "buffer"
        my $argname = $arg->{name};
        $argtype =~ s/^const //;

        if ($argtype =~ /^(const )?buffer$/) {
            my ($n1, $n2) = split(/,\s*/, $argname);
            print $fh <<EOF;
    uint8_t *$n1 = NULL;
    size_t $n2;
EOF
            push(@buffers, $n1);        # Add to the list to be free()d at end
        } else {
            $argname =~ s/^\*//;        # Remove any leading *
            my $pointer = ($argtype =~ /^psa_\w+_operation_t/) ? "*" : "";
            print $fh <<EOF;
    $argtype $pointer$argname;
EOF
        }
    }

    print $fh "\n";

    if ($#$args >= 0) {          # If we have any args (>= 0)
        print $fh <<EOF;
    uint8_t *pos = in_params;
    size_t remaining = in_params_len;
EOF
    }

    print $fh <<EOF;
    uint8_t *result = NULL;
    int ok;
EOF

    print $fh <<EOF if $debug;

    printf("$name: server\\n");
EOF
    if ($#$args >= 0) {          # If we have any args (>= 0)
        print $fh <<EOF;

    ok = psasim_deserialise_begin(&pos, &remaining);
    if (!ok) {
        goto fail;
    }
EOF
    }

    for my $i (0 .. $#$args) {
        my $arg = $args->[$i];
        my $argtype = $arg->{type};     # e.g. int, psa_algorithm_t, or "buffer"
        my $argname = $arg->{name};
        my $sep = ($i == $#$args) ? ";" : " +";
        $argtype =~ s/^const //;

        if ($argtype =~ /^(const )?buffer$/) {
            my ($n1, $n2) = split(/,\s*/, $argname);
            print $fh <<EOF;

    ok = psasim_deserialise_${argtype}(&pos, &remaining, &$n1, &$n2);
    if (!ok) {
        goto fail;
    }
EOF
        } else {
            $argname =~ s/^\*//;        # Remove any leading *
            my $server_specific = ($argtype =~ /^psa_\w+_operation_t/) ? "server_" : "";
            print $fh <<EOF;

    ok = psasim_${server_specific}deserialise_${argtype}(&pos, &remaining, &$argname);
    if (!ok) {
        goto fail;
    }
EOF
        }
    }

    print $fh <<EOF;

    // Now we call the actual target function
EOF
    output_call($fh, $f, $name, 1);

    my @outputs = grep($_->{is_output}, @$args);

    my $sep1 = ($ret_type eq "void") ? ";" : " +";

    print $fh <<EOF;

    // NOTE: Should really check there is no overflow as we go along.
    size_t result_size =
        psasim_serialise_begin_needs()$sep1
EOF

    if ($ret_type ne "void") {
        my $sep = ($#outputs < 0) ? ";" : " +";
        print $fh <<EOF;
        psasim_serialise_${ret_type}_needs($ret_name)$sep
EOF
    }

    for my $i (0 .. $#outputs) {
        my $arg = $outputs[$i];
        die("$i: this should have been filtered out by grep") unless $arg->{is_output};
        my $argtype = $arg->{type};     # e.g. int, psa_algorithm_t, or "buffer"
        my $argname = $arg->{name};
        my $sep = ($i == $#outputs) ? ";" : " +";
        $argtype =~ s/^const //;
        $argname =~ s/^\*//;        # Remove any leading *
        my $server_specific = ($argtype =~ /^psa_\w+_operation_t/) ? "server_" : "";

        print $fh <<EOF;
        psasim_${server_specific}serialise_${argtype}_needs($argname)$sep
EOF
    }

    print $fh <<EOF;

    result = malloc(result_size);
    if (result == NULL) {
        goto fail;
    }

    uint8_t *rpos = result;
    size_t rremain = result_size;

    ok = psasim_serialise_begin(&rpos, &rremain);
    if (!ok) {
        goto fail;
    }
EOF

    if ($ret_type ne "void") {
        print $fh <<EOF;

    ok = psasim_serialise_${ret_type}(&rpos, &rremain, $ret_name);
    if (!ok) {
        goto fail;
    }
EOF
    }

    my @outputs = grep($_->{is_output}, @$args);

    for my $i (0 .. $#outputs) {
        my $arg = $outputs[$i];
        die("$i: this should have been filtered out by grep") unless $arg->{is_output};
        my $argtype = $arg->{type};     # e.g. int, psa_algorithm_t, or "buffer"
        my $argname = $arg->{name};
        my $sep = ($i == $#outputs) ? ";" : " +";
        $argtype =~ s/^const //;

        if ($argtype eq "buffer") {
            print $fh <<EOF;

    ok = psasim_serialise_buffer(&rpos, &rremain, $argname);
    if (!ok) {
        goto fail;
    }
EOF
        } else {
            if ($argname =~ /^\*/) {
                $argname =~ s/^\*//;    # since it's already a pointer
            } else {
                die("$0: $argname: HOW TO OUTPUT?\n");
            }

            my $server_specific = ($argtype =~ /^psa_\w+_operation_t/) ? "server_" : "";

            print $fh <<EOF;

    ok = psasim_${server_specific}serialise_${argtype}(&rpos, &rremain, $argname);
    if (!ok) {
        goto fail;
    }
EOF
        }
    }

    my $free_buffers = join("", map { "    free($_);\n" } @buffers);
    $free_buffers = "\n" . $free_buffers if length($free_buffers);

    print $fh <<EOF;

    *out_params = result;
    *out_params_len = result_size;
$free_buffers
    return 1;   // success

fail:
    free(result);
$free_buffers
    return 0;       // This shouldn't happen!
}
EOF
}

sub output_client
{
    my ($fh, $f, $name) = @_;

    print $fh "\n";

    output_definition_begin($fh, $f, $name);

    my $ret_type = $f->{return}->{type};
    my $ret_name = $f->{return}->{name};
    my $ret_default = $f->{return}->{default};

    print $fh <<EOF;
{
    uint8_t *params = NULL;
    uint8_t *result = NULL;
    size_t result_length;
    $ret_type $ret_name = $ret_default;
EOF

    print $fh <<EOF if $debug;

    printf("$name: client\\n");
EOF

    print $fh <<EOF;

    size_t needed = psasim_serialise_begin_needs() +
EOF

    my $args = $f->{args};

    for my $i (0 .. $#$args) {
        my $arg = $args->[$i];
        my $argtype = $arg->{type};     # e.g. int, psa_algorithm_t, or "buffer"
        my $argname = $arg->{name};
        my $sep = ($i == $#$args) ? ";" : " +";
        $argtype =~ s/^const //;

        print $fh <<EOF;
                    psasim_serialise_${argtype}_needs($argname)$sep
EOF
    }

    print $fh <<EOF;

    params = malloc(needed);
    if (params == NULL) {
        status = PSA_ERROR_INSUFFICIENT_MEMORY;
        goto fail;
    }

    uint8_t *pos = params;
    size_t remaining = needed;
    int ok;
    ok = psasim_serialise_begin(&pos, &remaining);
    if (!ok) {
        goto fail;
    }
EOF

    for my $i (0 .. $#$args) {
        my $arg = $args->[$i];
        my $argtype = $arg->{type};     # e.g. int, psa_algorithm_t, or "buffer"
        my $argname = $arg->{name};
        my $sep = ($i == $#$args) ? ";" : " +";
        $argtype =~ s/^const //;

        print $fh <<EOF;
    ok = psasim_serialise_${argtype}(&pos, &remaining, $argname);
    if (!ok) {
        goto fail;
    }
EOF
    }

    print $fh <<EOF if $debug;

    printf("client sending %d:\\n", (int)(pos - params));
    dump_buffer(params, (size_t)(pos - params));
EOF

    my $enum = uc($name);

    print $fh <<EOF;

    ok = psa_crypto_call($enum,
                         params, (size_t) (pos - params), &result, &result_length);
    if (!ok) {
        printf("$enum server call failed\\n");
        goto fail;
    }
EOF

    print $fh <<EOF if $debug;

    printf("client receiving %d:\\n", (int)result_length);
    dump_buffer(result, result_length);
EOF

    print $fh <<EOF;

    uint8_t *rpos = result;
    size_t rremain = result_length;

    ok = psasim_deserialise_begin(&rpos, &rremain);
    if (!ok) {
        goto fail;
    }
EOF

    print $fh <<EOF;

    ok = psasim_deserialise_$ret_type(&rpos, &rremain, &$ret_name);
    if (!ok) {
        goto fail;
    }
EOF

    my @outputs = grep($_->{is_output}, @$args);

    for my $i (0 .. $#outputs) {
        my $arg = $outputs[$i];
        die("$i: this should have been filtered out by grep") unless $arg->{is_output};
        my $argtype = $arg->{type};     # e.g. int, psa_algorithm_t, or "buffer"
        my $argname = $arg->{name};
        my $sep = ($i == $#outputs) ? ";" : " +";
        $argtype =~ s/^const //;

        if ($argtype eq "buffer") {
            print $fh <<EOF;

    ok = psasim_deserialise_return_buffer(&rpos, &rremain, $argname);
    if (!ok) {
        goto fail;
    }
EOF
        } else {
            if ($argname =~ /^\*/) {
                $argname =~ s/^\*//;    # since it's already a pointer
            } else {
                die("$0: $argname: HOW TO OUTPUT?\n");
            }

            print $fh <<EOF;

    ok = psasim_deserialise_${argtype}(&rpos, &rremain, $argname);
    if (!ok) {
        goto fail;
    }
EOF
        }
    }
    print $fh <<EOF;

fail:
    free(params);
    free(result);

    return $ret_name;
}
EOF
}

sub output_declaration
{
    my ($f, $name) = @_;

    output_signature($f, $name, "declaration");
}

sub output_definition_begin
{
    my ($fh, $f, $name) = @_;

    output_signature($fh, $f, $name, "definition");
}

sub output_call
{
    my ($fh, $f, $name, $is_server) = @_;

    my $ret_name = $f->{return}->{name};
    my $args = $f->{args};

    print $fh "\n    $ret_name = $name(\n";

    print $fh "        );\n" if $#$args < 0; # If no arguments, empty arg list

    for my $i (0 .. $#$args) {
        my $arg = $args->[$i];
        my $argtype = $arg->{type};     # e.g. int, psa_algorithm_t, or "buffer"
        my $argname = $arg->{name};

        if ($argtype =~ /^(const )?buffer$/) {
            my ($n1, $n2) = split(/,\s*/, $argname);
            print $fh "        $n1, $n2";
        } else {
            $argname =~ s/^\*/\&/;      # Replace leading * with &
            if ($is_server && $argtype =~ /^psa_\w+_operation_t/) {
                $argname =~ s/^\&//;    # Actually, for psa_XXX_operation_t, don't do this on the server side
            }
            print $fh "        $argname";
        }
        my $sep = ($i == $#$args) ? "\n        );" : ",";
        print $fh "$sep\n";
    }
}

sub output_signature
{
    my ($fh, $f, $name, $what) = @_;

    my $ret_type = $f->{return}->{type};
    my $args = $f->{args};

    my $final_sep = ($what eq "declaration") ? "\n);" : "\n    )";

    print $fh "\n$ret_type $name(\n";

    print $fh "    void\n)\n" if $#$args < 0;   # No arguments

    for my $i (0 .. $#$args) {
        my $arg = $args->[$i];
        my $argtype = $arg->{type};             # e.g. int, psa_algorithm_t, or "buffer"
        my $ctypename = $arg->{ctypename};      # e.g. "int ", "char *"; empty for buffer
        my $argname = $arg->{name};

        if ($argtype =~ /^(const )?buffer$/) {
            my $const = length($1) ? "const " : "";
            my ($n1, $n2) = split(/,/, $argname);
            print $fh "    ${const}uint8_t *$n1, size_t $n2";
        } else {
            print $fh "    $ctypename$argname";
        }
        my $sep = ($i == $#$args) ? $final_sep : ",";
        print $fh "$sep\n";
    }
}

sub get_functions
{
    my $src = "";
    while (<DATA>) {
        chomp;
        s/\/\/.*//;
        s/\s+^//;
        s/\s+/ /g;
        $_ .= "\n";
        $src .= $_;
    }

    $src =~ s/\/\*.*?\*\///gs;

    my @src = split(/\n+/, $src);

    my @rebuild = ();
    my %funcs = ();
    for (my $i = 0; $i <= $#src; $i++) {
        my $line = $src[$i];
        if ($line =~ /^psa_status_t (psa_\w*)\(/) { # begin function definition
            #print "have one $line\n";
            while ($line !~ /;/) {
                $line .= $src[$i + 1];
                $i++;
            }
            $line =~ s/\s+/ /g;
            if ($line =~ /(\w+)\s+\b(\w+)\s*\(\s*(.*\S)\s*\)\s*[;{]/s) {
                my ($ret_type, $func, $args) = ($1, $2, $3);
                my $copy = $line;
                $copy =~ s/{$//;
                my $f = {
                    "orig" => $copy,
                };

                my @args = split(/\s*,\s*/, $args);

                my $ret_name = "";
                $ret_name = "status" if $ret_type eq "psa_status_t";
                die("ret_name for $ret_type?") unless length($ret_name);
                my $ret_default = "";
                $ret_default = "PSA_ERROR_CORRUPTION_DETECTED" if $ret_type eq "psa_status_t";
                die("ret_default for $ret_type?") unless length($ret_default);

                #print "FUNC $func RET_NAME $ret_name RET_TYPE $ret_type ARGS (", join("; ", @args), ")\n";

                $f->{return} = {
                    "type" => $ret_type,
                    "default" => $ret_default,
                    "name" => $ret_name,
                };
                $f->{args} = [];
                # psa_algorithm_t alg; const uint8_t *input; size_t input_length; uint8_t *hash; size_t hash_size; size_t *hash_length
                for (my $i = 0; $i <= $#args; $i++) {
                    my $arg = $args[$i];
                    # "type" => "psa_algorithm_t",
                    # "ctypename" => "psa_algorithm_t ",
                    # "name" => "alg",
                    # "is_output" => 0,
                    my ($type, $ctype, $name, $is_output);
                    if ($arg =~ /^(\w+)\s+(\w+)$/) {    # e.g. psa_algorithm_t alg
                        ($type, $name) = ($1, $2);
                        $ctype = $type . " ";
                        $is_output = 0;
                    } elsif ($arg =~ /^((const)\s+)?uint8_t\s*\*\s*(\w+)$/) {
                        $type = "buffer";
                        $is_output = (length($1) == 0) ? 1 : 0;
                        $type = "const buffer" if !$is_output;
                        $ctype = "";
                        $name = $3;
                        #print("$arg: $name: might be a buffer?\n");
                        die("$arg: not a buffer 1!\n") if $i == $#args;
                        my $next = $args[$i + 1];
                        die("$arg: not a buffer 2!\n") if $next !~ /^size_t\s+(${name}_\w+)$/;
                        $i++;                   # We're using the next param here
                        my $nname = $1;
                        $name .= ", " . $nname;
                    } elsif ($arg =~ /^((const)\s+)?(\w+)\s*\*(\w+)$/) {
                        ($type, $name) = ($3, "*" . $4);
                        $ctype = $1 . $type . " ";
                        $is_output = (length($1) == 0) ? 1 : 0;
                    } elsif ($arg eq "void") {
                         # we'll just ignore this one
                    } else {
                        die("ARG HELP $arg\n");
                    }
                    #print "$arg => <$type><$ctype><$name><$is_output>\n";
                    if ($arg ne "void") {
                        push(@{$f->{args}}, {
                            "type" => $type,
                            "ctypename" => $ctype,
                            "name" => $name,
                            "is_output" => $is_output,
                        });
                    }
                }
                $funcs{$func} = $f;
            } else {
                die("FAILED");
            }
            push(@rebuild, $line);
        } elsif ($line =~ /^static psa_\w+_t (psa_\w*)\(/) { # begin function definition
             # IGNORE static functions
        } else {
            if ($line =~ /psa_/) {
                print "NOT PARSED: $line\n";
            }
            push(@rebuild, $line);
        }
    }

    #print ::Dumper(\%funcs);
    #exit;

    return %funcs;
}

sub put_crypto_init_first
{
    my ($functions) = @_;

    my $want_first = "psa_crypto_init";

    my $idx = undef;
    for my $i (0 .. $#$functions) {
        if ($functions->[$i] eq $want_first) {
            $idx = $i;
            last;
        }
    }

    if (defined($idx) && $idx != 0) {   # Do nothing if already first
        splice(@$functions, $idx, 1);
        unshift(@$functions, $want_first);
    }
}

__END__
/**
 * \brief Library initialization.
 *
 * Applications must call this function before calling any other
 * function in this module.
 *
 * Applications may call this function more than once. Once a call
 * succeeds, subsequent calls are guaranteed to succeed.
 *
 * If the application calls other functions before calling psa_crypto_init(),
 * the behavior is undefined. Implementations are encouraged to either perform
 * the operation as if the library had been initialized or to return
 * #PSA_ERROR_BAD_STATE or some other applicable error. In particular,
 * implementations should not return a success status if the lack of
 * initialization may have security implications, for example due to improper
 * seeding of the random number generator.
 *
 * \retval #PSA_SUCCESS \emptydescription
 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
 * \retval #PSA_ERROR_INSUFFICIENT_STORAGE \emptydescription
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY \emptydescription
 * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
 * \retval #PSA_ERROR_DATA_INVALID \emptydescription
 * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
 */
psa_status_t psa_crypto_init(void);

/** Calculate the hash (digest) of a message.
 *
 * \note To verify the hash of a message against an
 *       expected value, use psa_hash_compare() instead.
 *
 * \param alg               The hash algorithm to compute (\c PSA_ALG_XXX value
 *                          such that #PSA_ALG_IS_HASH(\p alg) is true).
 * \param[in] input         Buffer containing the message to hash.
 * \param input_length      Size of the \p input buffer in bytes.
 * \param[out] hash         Buffer where the hash is to be written.
 * \param hash_size         Size of the \p hash buffer in bytes.
 * \param[out] hash_length  On success, the number of bytes
 *                          that make up the hash value. This is always
 *                          #PSA_HASH_LENGTH(\p alg).
 *
 * \retval #PSA_SUCCESS
 *         Success.
 * \retval #PSA_ERROR_NOT_SUPPORTED
 *         \p alg is not supported or is not a hash algorithm.
 * \retval #PSA_ERROR_INVALID_ARGUMENT \emptydescription
 * \retval #PSA_ERROR_BUFFER_TOO_SMALL
 *         \p hash_size is too small
 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_BAD_STATE
 *         The library has not been previously initialized by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_hash_compute(psa_algorithm_t alg,
                              const uint8_t *input,
                              size_t input_length,
                              uint8_t *hash,
                              size_t hash_size,
                              size_t *hash_length);

/* XXX We put this next one in place to check we ignore static functions
 *     when we eventually read all this from a real header file
 */

/** Return an initial value for a hash operation object.
 */
static psa_hash_operation_t psa_hash_operation_init(void);

/* XXX Back to normal function declarations */

/** Set up a multipart hash operation.
 *
 * The sequence of operations to calculate a hash (message digest)
 * is as follows:
 * -# Allocate an operation object which will be passed to all the functions
 *    listed here.
 * -# Initialize the operation object with one of the methods described in the
 *    documentation for #psa_hash_operation_t, e.g. #PSA_HASH_OPERATION_INIT.
 * -# Call psa_hash_setup() to specify the algorithm.
 * -# Call psa_hash_update() zero, one or more times, passing a fragment
 *    of the message each time. The hash that is calculated is the hash
 *    of the concatenation of these messages in order.
 * -# To calculate the hash, call psa_hash_finish().
 *    To compare the hash with an expected value, call psa_hash_verify().
 *
 * If an error occurs at any step after a call to psa_hash_setup(), the
 * operation will need to be reset by a call to psa_hash_abort(). The
 * application may call psa_hash_abort() at any time after the operation
 * has been initialized.
 *
 * After a successful call to psa_hash_setup(), the application must
 * eventually terminate the operation. The following events terminate an
 * operation:
 * - A successful call to psa_hash_finish() or psa_hash_verify().
 * - A call to psa_hash_abort().
 *
 * \param[in,out] operation The operation object to set up. It must have
 *                          been initialized as per the documentation for
 *                          #psa_hash_operation_t and not yet in use.
 * \param alg               The hash algorithm to compute (\c PSA_ALG_XXX value
 *                          such that #PSA_ALG_IS_HASH(\p alg) is true).
 *
 * \retval #PSA_SUCCESS
 *         Success.
 * \retval #PSA_ERROR_NOT_SUPPORTED
 *         \p alg is not a supported hash algorithm.
 * \retval #PSA_ERROR_INVALID_ARGUMENT
 *         \p alg is not a hash algorithm.
 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_BAD_STATE
 *         The operation state is not valid (it must be inactive), or
 *         the library has not been previously initialized by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_hash_setup(psa_hash_operation_t *operation,
                            psa_algorithm_t alg);

/** Add a message fragment to a multipart hash operation.
 *
 * The application must call psa_hash_setup() before calling this function.
 *
 * If this function returns an error status, the operation enters an error
 * state and must be aborted by calling psa_hash_abort().
 *
 * \param[in,out] operation Active hash operation.
 * \param[in] input         Buffer containing the message fragment to hash.
 * \param input_length      Size of the \p input buffer in bytes.
 *
 * \retval #PSA_SUCCESS
 *         Success.
 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_BAD_STATE
 *         The operation state is not valid (it must be active), or
 *         the library has not been previously initialized by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_hash_update(psa_hash_operation_t *operation,
                             const uint8_t *input,
                             size_t input_length);

/** Finish the calculation of the hash of a message.
 *
 * The application must call psa_hash_setup() before calling this function.
 * This function calculates the hash of the message formed by concatenating
 * the inputs passed to preceding calls to psa_hash_update().
 *
 * When this function returns successfully, the operation becomes inactive.
 * If this function returns an error status, the operation enters an error
 * state and must be aborted by calling psa_hash_abort().
 *
 * \warning Applications should not call this function if they expect
 *          a specific value for the hash. Call psa_hash_verify() instead.
 *          Beware that comparing integrity or authenticity data such as
 *          hash values with a function such as \c memcmp is risky
 *          because the time taken by the comparison may leak information
 *          about the hashed data which could allow an attacker to guess
 *          a valid hash and thereby bypass security controls.
 *
 * \param[in,out] operation     Active hash operation.
 * \param[out] hash             Buffer where the hash is to be written.
 * \param hash_size             Size of the \p hash buffer in bytes.
 * \param[out] hash_length      On success, the number of bytes
 *                              that make up the hash value. This is always
 *                              #PSA_HASH_LENGTH(\c alg) where \c alg is the
 *                              hash algorithm that is calculated.
 *
 * \retval #PSA_SUCCESS
 *         Success.
 * \retval #PSA_ERROR_BUFFER_TOO_SMALL
 *         The size of the \p hash buffer is too small. You can determine a
 *         sufficient buffer size by calling #PSA_HASH_LENGTH(\c alg)
 *         where \c alg is the hash algorithm that is calculated.
 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_BAD_STATE
 *         The operation state is not valid (it must be active), or
 *         the library has not been previously initialized by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_hash_finish(psa_hash_operation_t *operation,
                             uint8_t *hash,
                             size_t hash_size,
                             size_t *hash_length);

/** Finish the calculation of the hash of a message and compare it with
 * an expected value.
 *
 * The application must call psa_hash_setup() before calling this function.
 * This function calculates the hash of the message formed by concatenating
 * the inputs passed to preceding calls to psa_hash_update(). It then
 * compares the calculated hash with the expected hash passed as a
 * parameter to this function.
 *
 * When this function returns successfully, the operation becomes inactive.
 * If this function returns an error status, the operation enters an error
 * state and must be aborted by calling psa_hash_abort().
 *
 * \note Implementations shall make the best effort to ensure that the
 * comparison between the actual hash and the expected hash is performed
 * in constant time.
 *
 * \param[in,out] operation     Active hash operation.
 * \param[in] hash              Buffer containing the expected hash value.
 * \param hash_length           Size of the \p hash buffer in bytes.
 *
 * \retval #PSA_SUCCESS
 *         The expected hash is identical to the actual hash of the message.
 * \retval #PSA_ERROR_INVALID_SIGNATURE
 *         The hash of the message was calculated successfully, but it
 *         differs from the expected hash.
 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_BAD_STATE
 *         The operation state is not valid (it must be active), or
 *         the library has not been previously initialized by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_hash_verify(psa_hash_operation_t *operation,
                             const uint8_t *hash,
                             size_t hash_length);

/** Abort a hash operation.
 *
 * Aborting an operation frees all associated resources except for the
 * \p operation structure itself. Once aborted, the operation object
 * can be reused for another operation by calling
 * psa_hash_setup() again.
 *
 * You may call this function any time after the operation object has
 * been initialized by one of the methods described in #psa_hash_operation_t.
 *
 * In particular, calling psa_hash_abort() after the operation has been
 * terminated by a call to psa_hash_abort(), psa_hash_finish() or
 * psa_hash_verify() is safe and has no effect.
 *
 * \param[in,out] operation     Initialized hash operation.
 *
 * \retval #PSA_SUCCESS \emptydescription
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_BAD_STATE
 *         The library has not been previously initialized by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_hash_abort(psa_hash_operation_t *operation);

/** Clone a hash operation.
 *
 * This function copies the state of an ongoing hash operation to
 * a new operation object. In other words, this function is equivalent
 * to calling psa_hash_setup() on \p target_operation with the same
 * algorithm that \p source_operation was set up for, then
 * psa_hash_update() on \p target_operation with the same input that
 * that was passed to \p source_operation. After this function returns, the
 * two objects are independent, i.e. subsequent calls involving one of
 * the objects do not affect the other object.
 *
 * \param[in] source_operation      The active hash operation to clone.
 * \param[in,out] target_operation  The operation object to set up.
 *                                  It must be initialized but not active.
 *
 * \retval #PSA_SUCCESS \emptydescription
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
 * \retval #PSA_ERROR_BAD_STATE
 *         The \p source_operation state is not valid (it must be active), or
 *         the \p target_operation state is not valid (it must be inactive), or
 *         the library has not been previously initialized by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_hash_clone(const psa_hash_operation_t *source_operation,
                            psa_hash_operation_t *target_operation);

/** Calculate the hash (digest) of a message and compare it with a
 * reference value.
 *
 * \param alg               The hash algorithm to compute (\c PSA_ALG_XXX value
 *                          such that #PSA_ALG_IS_HASH(\p alg) is true).
 * \param[in] input         Buffer containing the message to hash.
 * \param input_length      Size of the \p input buffer in bytes.
 * \param[out] hash         Buffer containing the expected hash value.
 * \param hash_length       Size of the \p hash buffer in bytes.
 *
 * \retval #PSA_SUCCESS
 *         The expected hash is identical to the actual hash of the input.
 * \retval #PSA_ERROR_INVALID_SIGNATURE
 *         The hash of the message was calculated successfully, but it
 *         differs from the expected hash.
 * \retval #PSA_ERROR_NOT_SUPPORTED
 *         \p alg is not supported or is not a hash algorithm.
 * \retval #PSA_ERROR_INVALID_ARGUMENT
 *         \p input_length or \p hash_length do not match the hash size for \p alg
 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_BAD_STATE
 *         The library has not been previously initialized by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_hash_compare(psa_algorithm_t alg,
                              const uint8_t *input,
                              size_t input_length,
                              const uint8_t *hash,
                              size_t hash_length);

/** Process an authenticated encryption operation.
 *
 * \param key                     Identifier of the key to use for the
 *                                operation. It must allow the usage
 *                                #PSA_KEY_USAGE_ENCRYPT.
 * \param alg                     The AEAD algorithm to compute
 *                                (\c PSA_ALG_XXX value such that
 *                                #PSA_ALG_IS_AEAD(\p alg) is true).
 * \param[in] nonce               Nonce or IV to use.
 * \param nonce_length            Size of the \p nonce buffer in bytes.
 * \param[in] additional_data     Additional data that will be authenticated
 *                                but not encrypted.
 * \param additional_data_length  Size of \p additional_data in bytes.
 * \param[in] plaintext           Data that will be authenticated and
 *                                encrypted.
 * \param plaintext_length        Size of \p plaintext in bytes.
 * \param[out] ciphertext         Output buffer for the authenticated and
 *                                encrypted data. The additional data is not
 *                                part of this output. For algorithms where the
 *                                encrypted data and the authentication tag
 *                                are defined as separate outputs, the
 *                                authentication tag is appended to the
 *                                encrypted data.
 * \param ciphertext_size         Size of the \p ciphertext buffer in bytes.
 *                                This must be appropriate for the selected
 *                                algorithm and key:
 *                                - A sufficient output size is
 *                                  #PSA_AEAD_ENCRYPT_OUTPUT_SIZE(\c key_type,
 *                                  \p alg, \p plaintext_length) where
 *                                  \c key_type is the type of \p key.
 *                                - #PSA_AEAD_ENCRYPT_OUTPUT_MAX_SIZE(\p
 *                                  plaintext_length) evaluates to the maximum
 *                                  ciphertext size of any supported AEAD
 *                                  encryption.
 * \param[out] ciphertext_length  On success, the size of the output
 *                                in the \p ciphertext buffer.
 *
 * \retval #PSA_SUCCESS
 *         Success.
 * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
 * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
 * \retval #PSA_ERROR_INVALID_ARGUMENT
 *         \p key is not compatible with \p alg.
 * \retval #PSA_ERROR_NOT_SUPPORTED
 *         \p alg is not supported or is not an AEAD algorithm.
 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
 * \retval #PSA_ERROR_BUFFER_TOO_SMALL
 *         \p ciphertext_size is too small.
 *         #PSA_AEAD_ENCRYPT_OUTPUT_SIZE(\c key_type, \p alg,
 *         \p plaintext_length) or
 *         #PSA_AEAD_ENCRYPT_OUTPUT_MAX_SIZE(\p plaintext_length) can be used to
 *         determine the required buffer size.
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
 * \retval #PSA_ERROR_BAD_STATE
 *         The library has not been previously initialized by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_aead_encrypt(mbedtls_svc_key_id_t key,
                              psa_algorithm_t alg,
                              const uint8_t *nonce,
                              size_t nonce_length,
                              const uint8_t *additional_data,
                              size_t additional_data_length,
                              const uint8_t *plaintext,
                              size_t plaintext_length,
                              uint8_t *ciphertext,
                              size_t ciphertext_size,
                              size_t *ciphertext_length);

/** Process an authenticated decryption operation.
 *
 * \param key                     Identifier of the key to use for the
 *                                operation. It must allow the usage
 *                                #PSA_KEY_USAGE_DECRYPT.
 * \param alg                     The AEAD algorithm to compute
 *                                (\c PSA_ALG_XXX value such that
 *                                #PSA_ALG_IS_AEAD(\p alg) is true).
 * \param[in] nonce               Nonce or IV to use.
 * \param nonce_length            Size of the \p nonce buffer in bytes.
 * \param[in] additional_data     Additional data that has been authenticated
 *                                but not encrypted.
 * \param additional_data_length  Size of \p additional_data in bytes.
 * \param[in] ciphertext          Data that has been authenticated and
 *                                encrypted. For algorithms where the
 *                                encrypted data and the authentication tag
 *                                are defined as separate inputs, the buffer
 *                                must contain the encrypted data followed
 *                                by the authentication tag.
 * \param ciphertext_length       Size of \p ciphertext in bytes.
 * \param[out] plaintext          Output buffer for the decrypted data.
 * \param plaintext_size          Size of the \p plaintext buffer in bytes.
 *                                This must be appropriate for the selected
 *                                algorithm and key:
 *                                - A sufficient output size is
 *                                  #PSA_AEAD_DECRYPT_OUTPUT_SIZE(\c key_type,
 *                                  \p alg, \p ciphertext_length) where
 *                                  \c key_type is the type of \p key.
 *                                - #PSA_AEAD_DECRYPT_OUTPUT_MAX_SIZE(\p
 *                                  ciphertext_length) evaluates to the maximum
 *                                  plaintext size of any supported AEAD
 *                                  decryption.
 * \param[out] plaintext_length   On success, the size of the output
 *                                in the \p plaintext buffer.
 *
 * \retval #PSA_SUCCESS
 *         Success.
 * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
 * \retval #PSA_ERROR_INVALID_SIGNATURE
 *         The ciphertext is not authentic.
 * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
 * \retval #PSA_ERROR_INVALID_ARGUMENT
 *         \p key is not compatible with \p alg.
 * \retval #PSA_ERROR_NOT_SUPPORTED
 *         \p alg is not supported or is not an AEAD algorithm.
 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
 * \retval #PSA_ERROR_BUFFER_TOO_SMALL
 *         \p plaintext_size is too small.
 *         #PSA_AEAD_DECRYPT_OUTPUT_SIZE(\c key_type, \p alg,
 *         \p ciphertext_length) or
 *         #PSA_AEAD_DECRYPT_OUTPUT_MAX_SIZE(\p ciphertext_length) can be used
 *         to determine the required buffer size.
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
 * \retval #PSA_ERROR_BAD_STATE
 *         The library has not been previously initialized by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_aead_decrypt(mbedtls_svc_key_id_t key,
                              psa_algorithm_t alg,
                              const uint8_t *nonce,
                              size_t nonce_length,
                              const uint8_t *additional_data,
                              size_t additional_data_length,
                              const uint8_t *ciphertext,
                              size_t ciphertext_length,
                              uint8_t *plaintext,
                              size_t plaintext_size,
                              size_t *plaintext_length);

/** The type of the state data structure for multipart AEAD operations.
 *
 * Before calling any function on an AEAD operation object, the application
 * must initialize it by any of the following means:
 * - Set the structure to all-bits-zero, for example:
 *   \code
 *   psa_aead_operation_t operation;
 *   memset(&operation, 0, sizeof(operation));
 *   \endcode
 * - Initialize the structure to logical zero values, for example:
 *   \code
 *   psa_aead_operation_t operation = {0};
 *   \endcode
 * - Initialize the structure to the initializer #PSA_AEAD_OPERATION_INIT,
 *   for example:
 *   \code
 *   psa_aead_operation_t operation = PSA_AEAD_OPERATION_INIT;
 *   \endcode
 * - Assign the result of the function psa_aead_operation_init()
 *   to the structure, for example:
 *   \code
 *   psa_aead_operation_t operation;
 *   operation = psa_aead_operation_init();
 *   \endcode
 *
 * This is an implementation-defined \c struct. Applications should not
 * make any assumptions about the content of this structure.
 * Implementation details can change in future versions without notice. */
typedef struct psa_aead_operation_s psa_aead_operation_t;

/** \def PSA_AEAD_OPERATION_INIT
 *
 * This macro returns a suitable initializer for an AEAD operation object of
 * type #psa_aead_operation_t.
 */

/** Return an initial value for an AEAD operation object.
 */
static psa_aead_operation_t psa_aead_operation_init(void);

/** Set the key for a multipart authenticated encryption operation.
 *
 * The sequence of operations to encrypt a message with authentication
 * is as follows:
 * -# Allocate an operation object which will be passed to all the functions
 *    listed here.
 * -# Initialize the operation object with one of the methods described in the
 *    documentation for #psa_aead_operation_t, e.g.
 *    #PSA_AEAD_OPERATION_INIT.
 * -# Call psa_aead_encrypt_setup() to specify the algorithm and key.
 * -# If needed, call psa_aead_set_lengths() to specify the length of the
 *    inputs to the subsequent calls to psa_aead_update_ad() and
 *    psa_aead_update(). See the documentation of psa_aead_set_lengths()
 *    for details.
 * -# Call either psa_aead_generate_nonce() or psa_aead_set_nonce() to
 *    generate or set the nonce. You should use
 *    psa_aead_generate_nonce() unless the protocol you are implementing
 *    requires a specific nonce value.
 * -# Call psa_aead_update_ad() zero, one or more times, passing a fragment
 *    of the non-encrypted additional authenticated data each time.
 * -# Call psa_aead_update() zero, one or more times, passing a fragment
 *    of the message to encrypt each time.
 * -# Call psa_aead_finish().
 *
 * If an error occurs at any step after a call to psa_aead_encrypt_setup(),
 * the operation will need to be reset by a call to psa_aead_abort(). The
 * application may call psa_aead_abort() at any time after the operation
 * has been initialized.
 *
 * After a successful call to psa_aead_encrypt_setup(), the application must
 * eventually terminate the operation. The following events terminate an
 * operation:
 * - A successful call to psa_aead_finish().
 * - A call to psa_aead_abort().
 *
 * \param[in,out] operation     The operation object to set up. It must have
 *                              been initialized as per the documentation for
 *                              #psa_aead_operation_t and not yet in use.
 * \param key                   Identifier of the key to use for the operation.
 *                              It must remain valid until the operation
 *                              terminates. It must allow the usage
 *                              #PSA_KEY_USAGE_ENCRYPT.
 * \param alg                   The AEAD algorithm to compute
 *                              (\c PSA_ALG_XXX value such that
 *                              #PSA_ALG_IS_AEAD(\p alg) is true).
 *
 * \retval #PSA_SUCCESS
 *         Success.
 * \retval #PSA_ERROR_BAD_STATE
 *         The operation state is not valid (it must be inactive), or
 *         the library has not been previously initialized by psa_crypto_init().
 * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
 * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
 * \retval #PSA_ERROR_INVALID_ARGUMENT
 *         \p key is not compatible with \p alg.
 * \retval #PSA_ERROR_NOT_SUPPORTED
 *         \p alg is not supported or is not an AEAD algorithm.
 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_STORAGE_FAILURE
 *         The library has not been previously initialized by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_aead_encrypt_setup(psa_aead_operation_t *operation,
                                    mbedtls_svc_key_id_t key,
                                    psa_algorithm_t alg);

/** Set the key for a multipart authenticated decryption operation.
 *
 * The sequence of operations to decrypt a message with authentication
 * is as follows:
 * -# Allocate an operation object which will be passed to all the functions
 *    listed here.
 * -# Initialize the operation object with one of the methods described in the
 *    documentation for #psa_aead_operation_t, e.g.
 *    #PSA_AEAD_OPERATION_INIT.
 * -# Call psa_aead_decrypt_setup() to specify the algorithm and key.
 * -# If needed, call psa_aead_set_lengths() to specify the length of the
 *    inputs to the subsequent calls to psa_aead_update_ad() and
 *    psa_aead_update(). See the documentation of psa_aead_set_lengths()
 *    for details.
 * -# Call psa_aead_set_nonce() with the nonce for the decryption.
 * -# Call psa_aead_update_ad() zero, one or more times, passing a fragment
 *    of the non-encrypted additional authenticated data each time.
 * -# Call psa_aead_update() zero, one or more times, passing a fragment
 *    of the ciphertext to decrypt each time.
 * -# Call psa_aead_verify().
 *
 * If an error occurs at any step after a call to psa_aead_decrypt_setup(),
 * the operation will need to be reset by a call to psa_aead_abort(). The
 * application may call psa_aead_abort() at any time after the operation
 * has been initialized.
 *
 * After a successful call to psa_aead_decrypt_setup(), the application must
 * eventually terminate the operation. The following events terminate an
 * operation:
 * - A successful call to psa_aead_verify().
 * - A call to psa_aead_abort().
 *
 * \param[in,out] operation     The operation object to set up. It must have
 *                              been initialized as per the documentation for
 *                              #psa_aead_operation_t and not yet in use.
 * \param key                   Identifier of the key to use for the operation.
 *                              It must remain valid until the operation
 *                              terminates. It must allow the usage
 *                              #PSA_KEY_USAGE_DECRYPT.
 * \param alg                   The AEAD algorithm to compute
 *                              (\c PSA_ALG_XXX value such that
 *                              #PSA_ALG_IS_AEAD(\p alg) is true).
 *
 * \retval #PSA_SUCCESS
 *         Success.
 * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
 * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
 * \retval #PSA_ERROR_INVALID_ARGUMENT
 *         \p key is not compatible with \p alg.
 * \retval #PSA_ERROR_NOT_SUPPORTED
 *         \p alg is not supported or is not an AEAD algorithm.
 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
 * \retval #PSA_ERROR_BAD_STATE
 *         The operation state is not valid (it must be inactive), or the
 *         library has not been previously initialized by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_aead_decrypt_setup(psa_aead_operation_t *operation,
                                    mbedtls_svc_key_id_t key,
                                    psa_algorithm_t alg);

/** Generate a random nonce for an authenticated encryption operation.
 *
 * This function generates a random nonce for the authenticated encryption
 * operation with an appropriate size for the chosen algorithm, key type
 * and key size.
 *
 * The application must call psa_aead_encrypt_setup() before
 * calling this function.
 *
 * If this function returns an error status, the operation enters an error
 * state and must be aborted by calling psa_aead_abort().
 *
 * \param[in,out] operation     Active AEAD operation.
 * \param[out] nonce            Buffer where the generated nonce is to be
 *                              written.
 * \param nonce_size            Size of the \p nonce buffer in bytes.
 * \param[out] nonce_length     On success, the number of bytes of the
 *                              generated nonce.
 *
 * \retval #PSA_SUCCESS
 *         Success.
 * \retval #PSA_ERROR_BUFFER_TOO_SMALL
 *         The size of the \p nonce buffer is too small.
 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
 * \retval #PSA_ERROR_BAD_STATE
 *         The operation state is not valid (it must be an active aead encrypt
 *         operation, with no nonce set), or the library has not been
 *         previously initialized by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_aead_generate_nonce(psa_aead_operation_t *operation,
                                     uint8_t *nonce,
                                     size_t nonce_size,
                                     size_t *nonce_length);

/** Set the nonce for an authenticated encryption or decryption operation.
 *
 * This function sets the nonce for the authenticated
 * encryption or decryption operation.
 *
 * The application must call psa_aead_encrypt_setup() or
 * psa_aead_decrypt_setup() before calling this function.
 *
 * If this function returns an error status, the operation enters an error
 * state and must be aborted by calling psa_aead_abort().
 *
 * \note When encrypting, applications should use psa_aead_generate_nonce()
 * instead of this function, unless implementing a protocol that requires
 * a non-random IV.
 *
 * \param[in,out] operation     Active AEAD operation.
 * \param[in] nonce             Buffer containing the nonce to use.
 * \param nonce_length          Size of the nonce in bytes.
 *
 * \retval #PSA_SUCCESS
 *         Success.
 * \retval #PSA_ERROR_INVALID_ARGUMENT
 *         The size of \p nonce is not acceptable for the chosen algorithm.
 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
 * \retval #PSA_ERROR_BAD_STATE
 *         The operation state is not valid (it must be active, with no nonce
 *         set), or the library has not been previously initialized
 *         by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_aead_set_nonce(psa_aead_operation_t *operation,
                                const uint8_t *nonce,
                                size_t nonce_length);

/** Declare the lengths of the message and additional data for AEAD.
 *
 * The application must call this function before calling
 * psa_aead_update_ad() or psa_aead_update() if the algorithm for
 * the operation requires it. If the algorithm does not require it,
 * calling this function is optional, but if this function is called
 * then the implementation must enforce the lengths.
 *
 * You may call this function before or after setting the nonce with
 * psa_aead_set_nonce() or psa_aead_generate_nonce().
 *
 * - For #PSA_ALG_CCM, calling this function is required.
 * - For the other AEAD algorithms defined in this specification, calling
 *   this function is not required.
 * - For vendor-defined algorithm, refer to the vendor documentation.
 *
 * If this function returns an error status, the operation enters an error
 * state and must be aborted by calling psa_aead_abort().
 *
 * \param[in,out] operation     Active AEAD operation.
 * \param ad_length             Size of the non-encrypted additional
 *                              authenticated data in bytes.
 * \param plaintext_length      Size of the plaintext to encrypt in bytes.
 *
 * \retval #PSA_SUCCESS
 *         Success.
 * \retval #PSA_ERROR_INVALID_ARGUMENT
 *         At least one of the lengths is not acceptable for the chosen
 *         algorithm.
 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_BAD_STATE
 *         The operation state is not valid (it must be active, and
 *         psa_aead_update_ad() and psa_aead_update() must not have been
 *         called yet), or the library has not been previously initialized
 *         by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_aead_set_lengths(psa_aead_operation_t *operation,
                                  size_t ad_length,
                                  size_t plaintext_length);

/** Pass additional data to an active AEAD operation.
 *
 * Additional data is authenticated, but not encrypted.
 *
 * You may call this function multiple times to pass successive fragments
 * of the additional data. You may not call this function after passing
 * data to encrypt or decrypt with psa_aead_update().
 *
 * Before calling this function, you must:
 * 1. Call either psa_aead_encrypt_setup() or psa_aead_decrypt_setup().
 * 2. Set the nonce with psa_aead_generate_nonce() or psa_aead_set_nonce().
 *
 * If this function returns an error status, the operation enters an error
 * state and must be aborted by calling psa_aead_abort().
 *
 * \warning When decrypting, until psa_aead_verify() has returned #PSA_SUCCESS,
 *          there is no guarantee that the input is valid. Therefore, until
 *          you have called psa_aead_verify() and it has returned #PSA_SUCCESS,
 *          treat the input as untrusted and prepare to undo any action that
 *          depends on the input if psa_aead_verify() returns an error status.
 *
 * \param[in,out] operation     Active AEAD operation.
 * \param[in] input             Buffer containing the fragment of
 *                              additional data.
 * \param input_length          Size of the \p input buffer in bytes.
 *
 * \retval #PSA_SUCCESS
 *         Success.
 * \retval #PSA_ERROR_INVALID_ARGUMENT
 *         The total input length overflows the additional data length that
 *         was previously specified with psa_aead_set_lengths().
 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
 * \retval #PSA_ERROR_BAD_STATE
 *         The operation state is not valid (it must be active, have a nonce
 *         set, have lengths set if required by the algorithm, and
 *         psa_aead_update() must not have been called yet), or the library
 *         has not been previously initialized by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_aead_update_ad(psa_aead_operation_t *operation,
                                const uint8_t *input,
                                size_t input_length);

/** Encrypt or decrypt a message fragment in an active AEAD operation.
 *
 * Before calling this function, you must:
 * 1. Call either psa_aead_encrypt_setup() or psa_aead_decrypt_setup().
 *    The choice of setup function determines whether this function
 *    encrypts or decrypts its input.
 * 2. Set the nonce with psa_aead_generate_nonce() or psa_aead_set_nonce().
 * 3. Call psa_aead_update_ad() to pass all the additional data.
 *
 * If this function returns an error status, the operation enters an error
 * state and must be aborted by calling psa_aead_abort().
 *
 * \warning When decrypting, until psa_aead_verify() has returned #PSA_SUCCESS,
 *          there is no guarantee that the input is valid. Therefore, until
 *          you have called psa_aead_verify() and it has returned #PSA_SUCCESS:
 *          - Do not use the output in any way other than storing it in a
 *            confidential location. If you take any action that depends
 *            on the tentative decrypted data, this action will need to be
 *            undone if the input turns out not to be valid. Furthermore,
 *            if an adversary can observe that this action took place
 *            (for example through timing), they may be able to use this
 *            fact as an oracle to decrypt any message encrypted with the
 *            same key.
 *          - In particular, do not copy the output anywhere but to a
 *            memory or storage space that you have exclusive access to.
 *
 * This function does not require the input to be aligned to any
 * particular block boundary. If the implementation can only process
 * a whole block at a time, it must consume all the input provided, but
 * it may delay the end of the corresponding output until a subsequent
 * call to psa_aead_update(), psa_aead_finish() or psa_aead_verify()
 * provides sufficient input. The amount of data that can be delayed
 * in this way is bounded by #PSA_AEAD_UPDATE_OUTPUT_SIZE.
 *
 * \param[in,out] operation     Active AEAD operation.
 * \param[in] input             Buffer containing the message fragment to
 *                              encrypt or decrypt.
 * \param input_length          Size of the \p input buffer in bytes.
 * \param[out] output           Buffer where the output is to be written.
 * \param output_size           Size of the \p output buffer in bytes.
 *                              This must be appropriate for the selected
 *                                algorithm and key:
 *                                - A sufficient output size is
 *                                  #PSA_AEAD_UPDATE_OUTPUT_SIZE(\c key_type,
 *                                  \c alg, \p input_length) where
 *                                  \c key_type is the type of key and \c alg is
 *                                  the algorithm that were used to set up the
 *                                  operation.
 *                                - #PSA_AEAD_UPDATE_OUTPUT_MAX_SIZE(\p
 *                                  input_length) evaluates to the maximum
 *                                  output size of any supported AEAD
 *                                  algorithm.
 * \param[out] output_length    On success, the number of bytes
 *                              that make up the returned output.
 *
 * \retval #PSA_SUCCESS
 *         Success.
 * \retval #PSA_ERROR_BUFFER_TOO_SMALL
 *         The size of the \p output buffer is too small.
 *         #PSA_AEAD_UPDATE_OUTPUT_SIZE(\c key_type, \c alg, \p input_length) or
 *         #PSA_AEAD_UPDATE_OUTPUT_MAX_SIZE(\p input_length) can be used to
 *         determine the required buffer size.
 * \retval #PSA_ERROR_INVALID_ARGUMENT
 *         The total length of input to psa_aead_update_ad() so far is
 *         less than the additional data length that was previously
 *         specified with psa_aead_set_lengths(), or
 *         the total input length overflows the plaintext length that
 *         was previously specified with psa_aead_set_lengths().
 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
 * \retval #PSA_ERROR_BAD_STATE
 *         The operation state is not valid (it must be active, have a nonce
 *         set, and have lengths set if required by the algorithm), or the
 *         library has not been previously initialized by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_aead_update(psa_aead_operation_t *operation,
                             const uint8_t *input,
                             size_t input_length,
                             uint8_t *output,
                             size_t output_size,
                             size_t *output_length);

/** Finish encrypting a message in an AEAD operation.
 *
 * The operation must have been set up with psa_aead_encrypt_setup().
 *
 * This function finishes the authentication of the additional data
 * formed by concatenating the inputs passed to preceding calls to
 * psa_aead_update_ad() with the plaintext formed by concatenating the
 * inputs passed to preceding calls to psa_aead_update().
 *
 * This function has two output buffers:
 * - \p ciphertext contains trailing ciphertext that was buffered from
 *   preceding calls to psa_aead_update().
 * - \p tag contains the authentication tag.
 *
 * When this function returns successfully, the operation becomes inactive.
 * If this function returns an error status, the operation enters an error
 * state and must be aborted by calling psa_aead_abort().
 *
 * \param[in,out] operation     Active AEAD operation.
 * \param[out] ciphertext       Buffer where the last part of the ciphertext
 *                              is to be written.
 * \param ciphertext_size       Size of the \p ciphertext buffer in bytes.
 *                              This must be appropriate for the selected
 *                              algorithm and key:
 *                              - A sufficient output size is
 *                                #PSA_AEAD_FINISH_OUTPUT_SIZE(\c key_type,
 *                                \c alg) where \c key_type is the type of key
 *                                and \c alg is the algorithm that were used to
 *                                set up the operation.
 *                              - #PSA_AEAD_FINISH_OUTPUT_MAX_SIZE evaluates to
 *                                the maximum output size of any supported AEAD
 *                                algorithm.
 * \param[out] ciphertext_length On success, the number of bytes of
 *                              returned ciphertext.
 * \param[out] tag              Buffer where the authentication tag is
 *                              to be written.
 * \param tag_size              Size of the \p tag buffer in bytes.
 *                              This must be appropriate for the selected
 *                              algorithm and key:
 *                              - The exact tag size is #PSA_AEAD_TAG_LENGTH(\c
 *                                key_type, \c key_bits, \c alg) where
 *                                \c key_type and \c key_bits are the type and
 *                                bit-size of the key, and \c alg is the
 *                                algorithm that were used in the call to
 *                                psa_aead_encrypt_setup().
 *                              - #PSA_AEAD_TAG_MAX_SIZE evaluates to the
 *                                maximum tag size of any supported AEAD
 *                                algorithm.
 * \param[out] tag_length       On success, the number of bytes
 *                              that make up the returned tag.
 *
 * \retval #PSA_SUCCESS
 *         Success.
 * \retval #PSA_ERROR_BUFFER_TOO_SMALL
 *         The size of the \p ciphertext or \p tag buffer is too small.
 *         #PSA_AEAD_FINISH_OUTPUT_SIZE(\c key_type, \c alg) or
 *         #PSA_AEAD_FINISH_OUTPUT_MAX_SIZE can be used to determine the
 *         required \p ciphertext buffer size. #PSA_AEAD_TAG_LENGTH(\c key_type,
 *         \c key_bits, \c alg) or #PSA_AEAD_TAG_MAX_SIZE can be used to
 *         determine the required \p tag buffer size.
 * \retval #PSA_ERROR_INVALID_ARGUMENT
 *         The total length of input to psa_aead_update_ad() so far is
 *         less than the additional data length that was previously
 *         specified with psa_aead_set_lengths(), or
 *         the total length of input to psa_aead_update() so far is
 *         less than the plaintext length that was previously
 *         specified with psa_aead_set_lengths().
 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
 * \retval #PSA_ERROR_BAD_STATE
 *         The operation state is not valid (it must be an active encryption
 *         operation with a nonce set), or the library has not been previously
 *         initialized by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_aead_finish(psa_aead_operation_t *operation,
                             uint8_t *ciphertext,
                             size_t ciphertext_size,
                             size_t *ciphertext_length,
                             uint8_t *tag,
                             size_t tag_size,
                             size_t *tag_length);

/** Finish authenticating and decrypting a message in an AEAD operation.
 *
 * The operation must have been set up with psa_aead_decrypt_setup().
 *
 * This function finishes the authenticated decryption of the message
 * components:
 *
 * -  The additional data consisting of the concatenation of the inputs
 *    passed to preceding calls to psa_aead_update_ad().
 * -  The ciphertext consisting of the concatenation of the inputs passed to
 *    preceding calls to psa_aead_update().
 * -  The tag passed to this function call.
 *
 * If the authentication tag is correct, this function outputs any remaining
 * plaintext and reports success. If the authentication tag is not correct,
 * this function returns #PSA_ERROR_INVALID_SIGNATURE.
 *
 * When this function returns successfully, the operation becomes inactive.
 * If this function returns an error status, the operation enters an error
 * state and must be aborted by calling psa_aead_abort().
 *
 * \note Implementations shall make the best effort to ensure that the
 * comparison between the actual tag and the expected tag is performed
 * in constant time.
 *
 * \param[in,out] operation     Active AEAD operation.
 * \param[out] plaintext        Buffer where the last part of the plaintext
 *                              is to be written. This is the remaining data
 *                              from previous calls to psa_aead_update()
 *                              that could not be processed until the end
 *                              of the input.
 * \param plaintext_size        Size of the \p plaintext buffer in bytes.
 *                              This must be appropriate for the selected algorithm and key:
 *                              - A sufficient output size is
 *                                #PSA_AEAD_VERIFY_OUTPUT_SIZE(\c key_type,
 *                                \c alg) where \c key_type is the type of key
 *                                and \c alg is the algorithm that were used to
 *                                set up the operation.
 *                              - #PSA_AEAD_VERIFY_OUTPUT_MAX_SIZE evaluates to
 *                                the maximum output size of any supported AEAD
 *                                algorithm.
 * \param[out] plaintext_length On success, the number of bytes of
 *                              returned plaintext.
 * \param[in] tag               Buffer containing the authentication tag.
 * \param tag_length            Size of the \p tag buffer in bytes.
 *
 * \retval #PSA_SUCCESS
 *         Success.
 * \retval #PSA_ERROR_INVALID_SIGNATURE
 *         The calculations were successful, but the authentication tag is
 *         not correct.
 * \retval #PSA_ERROR_BUFFER_TOO_SMALL
 *         The size of the \p plaintext buffer is too small.
 *         #PSA_AEAD_VERIFY_OUTPUT_SIZE(\c key_type, \c alg) or
 *         #PSA_AEAD_VERIFY_OUTPUT_MAX_SIZE can be used to determine the
 *         required buffer size.
 * \retval #PSA_ERROR_INVALID_ARGUMENT
 *         The total length of input to psa_aead_update_ad() so far is
 *         less than the additional data length that was previously
 *         specified with psa_aead_set_lengths(), or
 *         the total length of input to psa_aead_update() so far is
 *         less than the plaintext length that was previously
 *         specified with psa_aead_set_lengths().
 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
 * \retval #PSA_ERROR_BAD_STATE
 *         The operation state is not valid (it must be an active decryption
 *         operation with a nonce set), or the library has not been previously
 *         initialized by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_aead_verify(psa_aead_operation_t *operation,
                             uint8_t *plaintext,
                             size_t plaintext_size,
                             size_t *plaintext_length,
                             const uint8_t *tag,
                             size_t tag_length);

/** Abort an AEAD operation.
 *
 * Aborting an operation frees all associated resources except for the
 * \p operation structure itself. Once aborted, the operation object
 * can be reused for another operation by calling
 * psa_aead_encrypt_setup() or psa_aead_decrypt_setup() again.
 *
 * You may call this function any time after the operation object has
 * been initialized as described in #psa_aead_operation_t.
 *
 * In particular, calling psa_aead_abort() after the operation has been
 * terminated by a call to psa_aead_abort(), psa_aead_finish() or
 * psa_aead_verify() is safe and has no effect.
 *
 * \param[in,out] operation     Initialized AEAD operation.
 *
 * \retval #PSA_SUCCESS \emptydescription
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_BAD_STATE
 *         The library has not been previously initialized by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_aead_abort(psa_aead_operation_t *operation);

/**
 * \brief Import a key in binary format.
 *
 * This function supports any output from psa_export_key(). Refer to the
 * documentation of psa_export_public_key() for the format of public keys
 * and to the documentation of psa_export_key() for the format for
 * other key types.
 *
 * The key data determines the key size. The attributes may optionally
 * specify a key size; in this case it must match the size determined
 * from the key data. A key size of 0 in \p attributes indicates that
 * the key size is solely determined by the key data.
 *
 * Implementations must reject an attempt to import a key of size 0.
 *
 * This specification supports a single format for each key type.
 * Implementations may support other formats as long as the standard
 * format is supported. Implementations that support other formats
 * should ensure that the formats are clearly unambiguous so as to
 * minimize the risk that an invalid input is accidentally interpreted
 * according to a different format.
 *
 * \param[in] attributes    The attributes for the new key.
 *                          The key size is always determined from the
 *                          \p data buffer.
 *                          If the key size in \p attributes is nonzero,
 *                          it must be equal to the size from \p data.
 * \param[out] key          On success, an identifier to the newly created key.
 *                          For persistent keys, this is the key identifier
 *                          defined in \p attributes.
 *                          \c 0 on failure.
 * \param[in] data    Buffer containing the key data. The content of this
 *                    buffer is interpreted according to the type declared
 *                    in \p attributes.
 *                    All implementations must support at least the format
 *                    described in the documentation
 *                    of psa_export_key() or psa_export_public_key() for
 *                    the chosen type. Implementations may allow other
 *                    formats, but should be conservative: implementations
 *                    should err on the side of rejecting content if it
 *                    may be erroneous (e.g. wrong type or truncated data).
 * \param data_length Size of the \p data buffer in bytes.
 *
 * \retval #PSA_SUCCESS
 *         Success.
 *         If the key is persistent, the key material and the key's metadata
 *         have been saved to persistent storage.
 * \retval #PSA_ERROR_ALREADY_EXISTS
 *         This is an attempt to create a persistent key, and there is
 *         already a persistent key with the given identifier.
 * \retval #PSA_ERROR_NOT_SUPPORTED
 *         The key type or key size is not supported, either by the
 *         implementation in general or in this particular persistent location.
 * \retval #PSA_ERROR_INVALID_ARGUMENT
 *         The key attributes, as a whole, are invalid, or
 *         the key data is not correctly formatted, or
 *         the size in \p attributes is nonzero and does not match the size
 *         of the key data.
 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
 * \retval #PSA_ERROR_INSUFFICIENT_STORAGE \emptydescription
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
 * \retval #PSA_ERROR_DATA_INVALID \emptydescription
 * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
 * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_BAD_STATE
 *         The library has not been previously initialized by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_import_key(const psa_key_attributes_t *attributes,
                            const uint8_t *data,
                            size_t data_length,
                            mbedtls_svc_key_id_t *key);

/** Retrieve the attributes of a key.
 *
 * This function first resets the attribute structure as with
 * psa_reset_key_attributes(). It then copies the attributes of
 * the given key into the given attribute structure.
 *
 * \note This function may allocate memory or other resources.
 *       Once you have called this function on an attribute structure,
 *       you must call psa_reset_key_attributes() to free these resources.
 *
 * \param[in] key               Identifier of the key to query.
 * \param[in,out] attributes    On success, the attributes of the key.
 *                              On failure, equivalent to a
 *                              freshly-initialized structure.
 *
 * \retval #PSA_SUCCESS \emptydescription
 * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
 * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
 * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
 * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
 * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
 * \retval #PSA_ERROR_DATA_INVALID \emptydescription
 * \retval #PSA_ERROR_BAD_STATE
 *         The library has not been previously initialized by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_get_key_attributes(mbedtls_svc_key_id_t key,
                                    psa_key_attributes_t *attributes);

/**
 * \brief Destroy a key.
 *
 * This function destroys a key from both volatile
 * memory and, if applicable, non-volatile storage. Implementations shall
 * make a best effort to ensure that the key material cannot be recovered.
 *
 * This function also erases any metadata such as policies and frees
 * resources associated with the key.
 *
 * If a key is currently in use in a multipart operation, then destroying the
 * key will cause the multipart operation to fail.
 *
 * \warning    We can only guarantee that the the key material will
 *             eventually be wiped from memory. With threading enabled
 *             and during concurrent execution, copies of the key material may
 *             still exist until all threads have finished using the key.
 *
 * \param key  Identifier of the key to erase. If this is \c 0, do nothing and
 *             return #PSA_SUCCESS.
 *
 * \retval #PSA_SUCCESS
 *         \p key was a valid identifier and the key material that it
 *         referred to has been erased. Alternatively, \p key is \c 0.
 * \retval #PSA_ERROR_NOT_PERMITTED
 *         The key cannot be erased because it is
 *         read-only, either due to a policy or due to physical restrictions.
 * \retval #PSA_ERROR_INVALID_HANDLE
 *         \p key is not a valid identifier nor \c 0.
 * \retval #PSA_ERROR_COMMUNICATION_FAILURE
 *         There was a failure in communication with the cryptoprocessor.
 *         The key material may still be present in the cryptoprocessor.
 * \retval #PSA_ERROR_DATA_INVALID
 *         This error is typically a result of either storage corruption on a
 *         cleartext storage backend, or an attempt to read data that was
 *         written by an incompatible version of the library.
 * \retval #PSA_ERROR_STORAGE_FAILURE
 *         The storage is corrupted. Implementations shall make a best effort
 *         to erase key material even in this stage, however applications
 *         should be aware that it may be impossible to guarantee that the
 *         key material is not recoverable in such cases.
 * \retval #PSA_ERROR_CORRUPTION_DETECTED
 *         An unexpected condition which is not a storage corruption or
 *         a communication failure occurred. The cryptoprocessor may have
 *         been compromised.
 * \retval #PSA_ERROR_BAD_STATE
 *         The library has not been previously initialized by psa_crypto_init().
 *         It is implementation-dependent whether a failure to initialize
 *         results in this error code.
 */
psa_status_t psa_destroy_key(mbedtls_svc_key_id_t key);