wolfssl-sys 4.0.0

System bindings for WolfSSL
Documentation
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
/* eccsi.c
 *
 * Copyright (C) 2006-2026 wolfSSL Inc.
 *
 * This file is part of wolfSSL.
 *
 * wolfSSL is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * wolfSSL is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
 */

#include <wolfssl/wolfcrypt/libwolfssl_sources.h>

#ifdef NO_INLINE
    #include <wolfssl/wolfcrypt/misc.h>
#else
    #define WOLFSSL_MISC_INCLUDED
    #include <wolfcrypt/src/misc.c>
#endif

#ifdef WOLFCRYPT_HAVE_ECCSI

#include <wolfssl/wolfcrypt/eccsi.h>
#include <wolfssl/wolfcrypt/asn_public.h>
#ifdef WOLFSSL_HAVE_SP_ECC
    #include <wolfssl/wolfcrypt/sp.h>
#endif

#if defined(WOLFSSL_USE_SAVE_VECTOR_REGISTERS) && !defined(WOLFSSL_SP_ASM)
    /* force off unneeded vector register save/restore. */
    #undef SAVE_VECTOR_REGISTERS
    #define SAVE_VECTOR_REGISTERS(fail_clause) SAVE_NO_VECTOR_REGISTERS(fail_clause)
    #undef RESTORE_VECTOR_REGISTERS
    #define RESTORE_VECTOR_REGISTERS() RESTORE_NO_VECTOR_REGISTERS()
#endif

#ifndef WOLFSSL_HAVE_ECC_KEY_GET_PRIV
    /* FIPS build has replaced ecc.h. */
    #define wc_ecc_key_get_priv(key) (&((key)->k))
    #define WOLFSSL_HAVE_ECC_KEY_GET_PRIV
#endif

/**
 * Initialize the components of the ECCSI key and use the specified curve.
 *
 * Must be called before performing any operations.
 * Free the ECCSI key with wc_FreeEccsiKey() when no longer needed.
 *
 * @param  [in]  key    ECCSI key to initialize.
 * @param  [in]  heap   Heap hint.
 * @param  [in]  devId  Device identifier.
 *                      Use INVALID_DEVID when no device used.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key is NULL.
 * @return  MEMORY_E when dynamic memory allocation fails.
 */
int wc_InitEccsiKey_ex(EccsiKey* key, int keySz, int curveId, void* heap,
        int devId)
{
    int err = 0;
    EccsiKeyParams* params = NULL;

    if (key == NULL) {
        err = BAD_FUNC_ARG;
    }

    if (err == 0) {
        XMEMSET(key, 0, sizeof(*key));
        key->heap = heap;
        params = &key->params;

        err = wc_ecc_init_ex(&key->ecc, heap, devId);
    }
    if (err == 0) {
        err = wc_ecc_init_ex(&key->pubkey, heap, devId);
    }
    if (err == 0) {
        key->pvt = wc_ecc_new_point_h(heap);
        if (key->pvt == NULL) {
            err = MEMORY_E;
        }
    }
    if (err == 0) {
        err = mp_init_multi(&params->order,
#ifdef WOLFCRYPT_ECCSI_CLIENT
                &params->a, &params->b, &params->prime, &key->tmp, &key->ssk
#else
                NULL, NULL, NULL, NULL, NULL
#endif
                );
    }
    if (err == 0) {
        err = wc_ecc_set_curve(&key->ecc, keySz, curveId);
    }
    if (err == 0) {
        err = wc_ecc_set_curve(&key->pubkey, keySz, curveId);
    }

    if (err != 0) {
        wc_FreeEccsiKey(key);
    }

    return err;
}

/**
 * Initialize the components of the ECCSI key.
 * Default curve used: NIST_P256 (ECC_SECP256R1)
 *
 * Must be called before performing any operations.
 * Free the ECCSI key with wc_FreeEccsiKey() when no longer needed.
 *
 * @param  [in]  key    ECCSI key to initialize.
 * @param  [in]  heap   Heap hint.
 * @param  [in]  devId  Device identifier.
 *                      Use INVALID_DEVID when no device used.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key is NULL.
 * @return  MEMORY_E when dynamic memory allocation fails.
 */
int wc_InitEccsiKey(EccsiKey* key, void* heap, int devId)
{
    return wc_InitEccsiKey_ex(key, 32, ECC_SECP256R1, heap, devId);
}

/**
 * Frees memory associated with components of the ECCIS key.
 *
 * Must be called when finished with the ECCIS key.
 *
 * @param  [in]  key  ECCIS key.
 */
void wc_FreeEccsiKey(EccsiKey* key)
{
    if (key != NULL) {
        EccsiKeyParams* params = &key->params;

        wc_ecc_del_point_h(params->base, key->heap);
#ifdef WOLFCRYPT_ECCSI_CLIENT
        mp_free(&key->ssk);
        mp_free(&key->tmp);
        mp_free(&params->prime);
        mp_free(&params->b);
        mp_free(&params->a);
#endif
        mp_free(&params->order);
        wc_ecc_del_point_h(key->pvt, key->heap);
        wc_ecc_free(&key->pubkey);
        wc_ecc_free(&key->ecc);
        XMEMSET(key, 0, sizeof(*key));
    }
}

/*
 * Order, as a hex string in the ECC object, loaded into mp_int in key.
 * Flags that the order is available so it isn't loaded multiple times.
 *
 * @param  [in]  key  ECCSI key.
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 */
static int eccsi_load_order(EccsiKey* key)
{
    int err = 0;

    if (!key->params.haveOrder) {
        err = mp_read_radix(&key->params.order, key->ecc.dp->order,
                MP_RADIX_HEX);
        if (err == 0) {
            key->params.haveOrder = 1;
        }
    }

    return err;
}

#ifdef WOLFCRYPT_ECCSI_CLIENT
/*
 * Parameters, as a hex strings in the ECC object, loaded into mp_ints in key.
 *
 * Parameters loaded: order, A, B, prime.
 * Flags that each parameter is available so they aren't loaded multiple times.
 *
 * @param  [in]  key  ECCSI key.
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 */
static int eccsi_load_ecc_params(EccsiKey* key)
{
    int err = 0;
    EccsiKeyParams* params = &key->params;

    err = eccsi_load_order(key);
    if ((err == 0) && (!params->haveA)) {
        err = mp_read_radix(&params->a, key->ecc.dp->Af, MP_RADIX_HEX);
        if (err == 0) {
            params->haveA = 1;
        }
    }
    if ((err == 0) && (!params->haveB)) {
        err = mp_read_radix(&params->b, key->ecc.dp->Bf, MP_RADIX_HEX);
        if (err == 0) {
            params->haveB = 1;
        }
    }
    if ((err == 0) && (!params->havePrime)) {
        err = mp_read_radix(&params->prime, key->ecc.dp->prime, MP_RADIX_HEX);
        if (err == 0) {
            params->havePrime = 1;
        }
    }

    return err;
}
#endif /* WOLFCRYPT_ECCSI_CLIENT */

/*
 * Get the base point, hex encoded in the ECC object, as an ecc_point.
 *
 * Flags that base is available so it isn't loaded multiple times.

 * @param  [in]   key   ECCSI key.
 * @param  [out]  base  Base point of curve.
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 */
static int eccsi_load_base(EccsiKey* key)
{
    int err = 0;
    EccsiKeyParams* params = &key->params;

    if (!params->haveBase) {
        if (params->base == NULL) {
            params->base = wc_ecc_new_point_h(key->heap);
            if (params->base == NULL) {
                err = MEMORY_E;
            }
        }
        if (err == 0) {
            err = mp_read_radix(params->base->x, key->ecc.dp->Gx, MP_RADIX_HEX);
        }
        if (err == 0) {
            err = mp_read_radix(params->base->y, key->ecc.dp->Gy, MP_RADIX_HEX);
        }
        if (err == 0) {
            err = mp_set(params->base->z, 1);
        }
        if (err == 0) {
            params->haveBase = 1;
        }
    }

    return err;
}

/*
 * Encode the base point of the curve.
 *
 * Base point is hex encoded in the ECC object or cached as an ECC point from
 * previous load calls.
 *
 * @param  [in]   key     ECCSI key.
 * @param  [out]  data    Buffer to encode base point into.
 * @param  [out]  dataSz  Length of base point in bytes.
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 * @return  Other -ve value when an internal operation fails.
 */
static int eccsi_encode_base(EccsiKey* key, byte* data, word32* dataSz)
{
    int err;
    int idx = wc_ecc_get_curve_idx(key->ecc.dp->id);

    err = eccsi_load_base(key);
    if (err == 0) {
        err = wc_ecc_export_point_der(idx, key->params.base, data, dataSz);
    }

    return err;
}

#ifndef WOLFSSL_HAVE_SP_ECC
/*
 * Convert the KPAK to montgomery form.
 *
 * The KPAK is needed in Montgomery form for verification.
 *
 * @param  [in]  key      ECCSI key.
 * @return  0 on success.
 * @return  MP_MEM or MEMORY_E when dynamic memory allocation fails.
 * @return  Other -ve value when an internal operation fails.
 */
static int eccsi_kpak_to_mont(EccsiKey* key)
{
    int err = 0;
    ecc_point* kpak = &key->ecc.pubkey;
    mp_int* mu = &key->tmp;
    mp_int* prime = &key->params.prime;

    if (!key->kpakMont) {
        err = mp_montgomery_calc_normalization(mu, prime);
        if (err == 0) {
            err = mp_mulmod(kpak->x, mu, prime, kpak->x);
        }
        if (err == 0) {
            err = mp_mulmod(kpak->y, mu, prime, kpak->y);
        }
        if (err == 0) {
            err = mp_mulmod(kpak->z, mu, prime, kpak->z);
        }
        if (err == 0) {
            key->kpakMont = 1;
        }
    }

    return err;
}
#endif

/*
 * Convert the KPAK from montgomery form.
 *
 * The KPAK is needed in Montgomery form for verification.
 *
 * @param  [in]  key      ECCSI key.
 * @return  0 on success.
 * @return  MP_MEM or MEMORY_E when dynamic memory allocation fails.
 * @return  Other -ve value when an internal operation fails.
 */
static int eccsi_kpak_from_mont(EccsiKey* key)
{
    int err = 0;
    ecc_point* kpak = &key->ecc.pubkey;
    mp_digit mp;
    mp_int* prime = &key->params.prime;

    if (key->kpakMont) {
        err = mp_montgomery_setup(prime, &mp);
        if (err == 0) {
            err = mp_montgomery_reduce(kpak->x, prime, mp);
        }
        if (err == 0) {
            err = mp_montgomery_reduce(kpak->y, prime, mp);
        }
        if (err == 0) {
            err = mp_montgomery_reduce(kpak->z, prime, mp);
        }
        if (err == 0) {
            key->kpakMont = 0;
        }
    }

    return err;
}

/*
 * Compute HS = hash( G | KPAK | ID | PVT )
 *
 * Use when making a (SSK,PVT) pair, signing and verifying.
 *
 * @param  [in]   key       ECCSI key.
 * @param  [in]   hashType  Type of hash algorithm. e.g. WC_SHA256
 * @param  [in]   id        Identity to create hash from.
 * @param  [in]   idSz      Length of identity in bytes.
 * @param  [in]   pvt       Public Validation Token (PVT) as an ECC point.
 * @param  [out]  hash      Buffer to hold hash data.
 * @param  [out]  hashSz    Length of hash data in bytes.
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 * @return  Other -ve value when an internal operation fails.
 */
static int eccsi_compute_hs(EccsiKey* key, enum wc_HashType hashType,
        const byte* id, word32 idSz, ecc_point* pvt, byte* hash, byte* hashSz)
{
    int err;
    word32 dataSz = 0;
    int idx = wc_ecc_get_curve_idx(key->ecc.dp->id);
    ecc_point* kpak = &key->ecc.pubkey;
    int hash_inited = 0;

    /* HS = hash( G | KPAK | ID | PVT ) */
    err = wc_HashInit_ex(&key->hash, hashType, key->heap, INVALID_DEVID);
    if (err == 0) {
        hash_inited = 1;
        /* Base Point - G */
        dataSz = sizeof(key->data);
        err = eccsi_encode_base(key, key->data, &dataSz);
    }
    if (err == 0) {
        err = wc_HashUpdate(&key->hash, hashType, key->data, dataSz);
    }
    if (err == 0) {
        err = eccsi_kpak_from_mont(key);
    }
    if (err == 0) {
        dataSz = sizeof(key->data);
        /* KPAK - public key */
        err = wc_ecc_export_point_der(idx, kpak, key->data, &dataSz);
    }
    if (err == 0) {
        err = wc_HashUpdate(&key->hash, hashType, key->data, dataSz);
    }
    if (err == 0) {
        /* Id - Signer's ID */
        err = wc_HashUpdate(&key->hash, hashType, id, idSz);
    }
    if (err == 0) {
        dataSz = sizeof(key->data);
        /* PVT - Public Validation Token */
        err = wc_ecc_export_point_der(idx, pvt, key->data, &dataSz);
    }
    if (err == 0) {
        /* PVT - Public Validation Token */
        err = wc_HashUpdate(&key->hash, hashType, key->data, dataSz);
    }
    if (err == 0) {
        err = wc_HashFinal(&key->hash, hashType, hash);
    }

    if (err == 0) {
        *hashSz = (byte)wc_HashGetDigestSize(hashType);
    }

    if (hash_inited) {
        (void)wc_HashFree(&key->hash, hashType);
    }

    return err;
}

#ifdef WOLFCRYPT_ECCSI_KMS
/**
 * Generate KMS Secret Auth Key (KSAK) and KMS Public Auth Key (KPAK).
 *
 * RFC 6507, Section 4.2
 *
 * Called when establishing a new KMS.\n
 * KSAK must be kept secret while KPAK is required by clients for signing
 * and verifying.\n
 * Export key using wc_ExportEccsiKey(), once generated, to reuse the key.\n
 * Export KPAK using wc_ExportEccsiPublicKey(), once generate to send to
 * clients.
 *
 * Creates a random private key and multiplies it by the base point to calculate
 * the public key.
 *
 * @param  [in]  key      ECCSI key.
 * @param  [in]  rng      Random number generator.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key or rng is NULL.
 * @return  MP_MEM or MEMORY_E when dynamic memory allocation fails.
 * @return  Other -ve value when an internal operation fails.
 */
int wc_MakeEccsiKey(EccsiKey* key, WC_RNG* rng)
{
    int err = 0;

    if ((key == NULL) || (rng == NULL)) {
        err = BAD_FUNC_ARG;
    }

    if (err == 0) {
        err = wc_ecc_make_key_ex(rng, key->ecc.dp->size, &key->ecc,
                key->ecc.dp->id);
    }

    return err;
}

/*
 * Encode a point into a buffer.
 *
 * X and y ordinate of point concatenated. Each number is zero padded tosize.
 * Descriptor byte (0x04) is prepended when not raw.
 *
 * @param  [in]      point    ECC point to encode.
 * @param  [in]      size     Size of prime in bytes - maximum ordinate length.
 * @param  [out]     data     Buffer to hold encoded data.
 *                            NULL when needing length of encoded data.
 * @param  [in,out]  sz       In, the size of the buffer in bytes.
 *                            Out, the size of the encoded data in bytes.
 * @param  [in]      raw      On 0, prepend descriptor byte.
 *                            On 1, only include ordinates.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key or sz is NULL.
 * @return  LENGTH_ONLY_E when data is NULL - sz will hold the size in bytes of
 *          the encoded data.
 * @return  BUFFER_E when size of buffer is too small.
 */
static int eccsi_encode_point(ecc_point* point, word32 size, byte* data,
        word32* sz, int raw)
{
    int err = 0;

    if (data == NULL) {
        *sz = size * 2 + !raw;
        err = WC_NO_ERR_TRACE(LENGTH_ONLY_E);
    }
    if ((err == 0) && (*sz < size * 2 + !raw)) {
        err = BUFFER_E;
    }

    if (err == 0) {
        if (!raw) {
            data[0] = 0x04;
            data++;
        }

        /* Write out the point's x ordinate into key size bytes. */
        err = mp_to_unsigned_bin_len(point->x, data, (int)size);
    }
    if (err == 0) {
        data += size;
        /* Write out the point's y ordinate into key size bytes. */
        err = mp_to_unsigned_bin_len(point->y, data, (int)size);
    }
    if (err == 0) {
        *sz = size * 2 + !raw;
    }

    return err;
}

/*
 * Decode the data into an ECC point.
 *
 * X and y ordinate of point concatenated. Each number is zero padded to
 * key size. Supports prepended descriptor byte (0x04).
 *
 * @param  [out]  point  ECC point to encode.
 * @param  [in]   size   Size of prime in bytes - maximum ordinate length.
 * @param  [in]   data   Encoded public key.
 * @param  [in]   sz     Size of the encoded public key in bytes.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key or z is NULL.
 * @return  BUFFER_E when size of data is not equal to the expected size.
 * @return  ASN_PARSE_E when format byte is invalid.
 * @return  MP_MEM or MEMORY_E when dynamic memory allocation fails.
 */
static int eccsi_decode_point(ecc_point* point, word32 size, const byte* data,
        word32 sz)
{
    int err = 0;

    if ((sz != size * 2) && (sz != size * 2 + 1)) {
        err = BUFFER_E;
    }

    if ((err == 0) && (sz & 1)) {
        if (data[0] != 0x04) {
            err = ASN_PARSE_E;
        }
        data++;
    }

    if (err == 0) {
        /* Read the public key point's x value from key size bytes. */
        err = mp_read_unsigned_bin(point->x, data, size);
    }
    if (err == 0) {
        data += size;
        /* Read the public key point's y value from key size bytes. */
        err = mp_read_unsigned_bin(point->y, data, size);
    }
    if (err == 0) {
        err = mp_set(point->z, 1);
    }

    return err;
}

/*
 * Encode the ECCSI key.
 *
 * Encodes the private key as big-endian bytes of fixed length.
 * Encodes the public key x and y ordinates as big-endian bytes of fixed length.
 *
 * @param  [in]      key   ECCSI key.
 * @param  [out]     data  Buffer to hold encoded ECCSI key.
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails (WOLFSSL_SMALL_STACK).
 */
static int eccsi_encode_key(EccsiKey* key, byte* data)
{
    int err;
    word32 sz = (word32)key->ecc.dp->size * 2;

    /* Write out the secret value into key size bytes. */
    err = mp_to_unsigned_bin_len(wc_ecc_key_get_priv(&key->ecc), data,
        key->ecc.dp->size);
    if (err == 0) {
        data += key->ecc.dp->size;
        /* Write the public key. */
        err = eccsi_encode_point(&key->ecc.pubkey, (word32)key->ecc.dp->size,
                data, &sz, 1);
    }

    return err;
}

/**
 * Export the ECCSI key as encoded public/private ECC key.
 *
 * Use when saving the KMS key pair.
 *
 * Private key, x ordinate of public key and y ordinate of public key
 * concatenated. Each number is zero padded to key size.
 *
 * @param  [in]      key   ECCSI key.
 * @param  [out]     data  Buffer to hold encoded ECCSI key.
 *                         NULL when requesting required length.
 * @param  [in,out]  sz    On in, size of buffer in bytes.
 *                         On out, size of encoded ECCSI key in bytes.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key or sz is NULL
 * @return  BAD_STATE_E when no key to export.
 * @return  LENGTH_ONLY_E when data is NULL - sz is set.
 * @return  BUFFER_E when the buffer passed in is too small.
 * @return  MEMORY_E when dynamic memory allocation fails (WOLFSSL_SMALL_STACK).
 */
int wc_ExportEccsiKey(EccsiKey* key, byte* data, word32* sz)
{
    int err = 0;

    if ((key == NULL) || (sz == NULL)) {
        err = BAD_FUNC_ARG;
    }

    if ((err == 0) && (key->ecc.type != ECC_PRIVATEKEY)) {
        err = BAD_STATE_E;
    }

    if (err == 0) {
        if (data == NULL) {
            *sz = (word32)(key->ecc.dp->size * 3);
            err = WC_NO_ERR_TRACE(LENGTH_ONLY_E);
        }
        else if (*sz < (word32)key->ecc.dp->size * 3) {
            err = BUFFER_E;
        }
        else {
            *sz = (word32)(key->ecc.dp->size * 3);
        }
    }
    if (err == 0) {
        err = eccsi_kpak_from_mont(key);
    }
    if (err == 0) {
        /* Encode key */
        err = eccsi_encode_key(key, data);
    }

    return err;
}

/*
 * Import the ECCSI key as encoded public/private ECC key.
 *
 * Decodes the private key as big-endian bytes of fixed length.
 * Decodes the public key x and y ordinates as big-endian bytes of fixed length.
 *
 * @param  [in]  key   ECCSI key.
 * @param  [in]  data  Buffer holding encoded ECCSI key.
 * @return  0 on success.
 * @return  MP_MEM or MEMORY_E when dynamic memory allocation fails.
 */
static int eccsi_decode_key(EccsiKey* key, const byte* data)
{
    int err;

    /* Read the secret value from key size bytes. */
    err = mp_read_unsigned_bin(wc_ecc_key_get_priv(&key->ecc), data,
        (word32)key->ecc.dp->size);
    if (err == 0) {
        data += key->ecc.dp->size;
        /* Read public key. */
        err = eccsi_decode_point(&key->ecc.pubkey, (word32)key->ecc.dp->size,
                data, (word32)(key->ecc.dp->size * 2));
    }

    return err;
}

/**
 * Import the ECCSI key as encoded public/private ECC key.
 *
 * Use when restoring the KMS key pair.
 *
 * Private key, x ordinate of public key and y ordinate of public key
 * concatenated. Each number is zero padded to key size.
 *
 * @param  [in]  key   ECCSI key.
 * @param  [in]  data  Buffer holding encoded ECCSI key.
 * @param  [in]  sz    Size of encoded ECCSI key in bytes.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key or data is NULL.
 * @return  BUFFER_E when size of data is not equal to the expected size.
 * @return  MP_MEM or MEMORY_E when dynamic memory allocation fails.
 */
int wc_ImportEccsiKey(EccsiKey* key, const byte* data, word32 sz)
{
    int err = 0;

    if ((key == NULL) || (data == NULL)) {
        err = BAD_FUNC_ARG;
    }
    if ((err == 0) && (sz != (word32)key->ecc.dp->size * 3)) {
        err = BUFFER_E;
    }

    if (err == 0) {
        key->kpakMont = 0;

        /* Decode key */
        err = eccsi_decode_key(key, data);
    }
    if (err == 0) {
        key->ecc.type = ECC_PRIVATEKEY;
    }

    return err;
}

/**
 * Export the ECCSI private key.
 *
 * Use when saving the KMS key.
 *
 * Private key is zero padded to key size.
 *
 * @param  [in]      key   ECCSI key.
 * @param  [out]     data  Buffer to hold encoded ECCSI private key.
 *                         NULL when requesting required length.
 * @param  [in,out]  sz    On in, size of buffer in bytes.
 *                         On out, size of encoded ECCSI private key in bytes.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key or sz is NULL
 * @return  BAD_STATE_E when no key to export.
 * @return  LENGTH_ONLY_E when data is NULL - sz is set.
 * @return  BUFFER_E when the buffer passed in is too small.
 * @return  MEMORY_E when dynamic memory allocation fails (WOLFSSL_SMALL_STACK).
 */
int wc_ExportEccsiPrivateKey(EccsiKey* key, byte* data, word32* sz)
{
    int err = 0;

    if ((key == NULL) || (sz == NULL)) {
        err = BAD_FUNC_ARG;
    }

    if ((err == 0) && (key->ecc.type != ECC_PRIVATEKEY)) {
        err = BAD_STATE_E;
    }

    if (err == 0) {
        if (data == NULL) {
            *sz = (word32)key->ecc.dp->size;
            err = WC_NO_ERR_TRACE(LENGTH_ONLY_E);
        }
        else if (*sz < (word32)key->ecc.dp->size) {
            err = BUFFER_E;
        }
        else {
            *sz = (word32)key->ecc.dp->size;
        }
    }
    if (err == 0) {
        err = mp_to_unsigned_bin_len(wc_ecc_key_get_priv(&key->ecc), data,
            key->ecc.dp->size);
    }

    return err;
}

/**
 * Import the ECCSI private key.
 *
 * Use when restoring the KMS key pair.
 *
 * Private key is zero padded to key size.
 *
 * @param  [in]  key   ECCSI key.
 * @param  [in]  data  Buffer holding encoded ECCSI private key.
 * @param  [in]  sz    Size of encoded ECCSI private key in bytes.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key or data is NULL.
 * @return  BUFFER_E when size of data is not equal to the expected size.
 * @return  MP_MEM or MEMORY_E when dynamic memory allocation fails.
 */
int wc_ImportEccsiPrivateKey(EccsiKey* key, const byte* data, word32 sz)
{
    int err = 0;

    if ((key == NULL) || (data == NULL)) {
        err = BAD_FUNC_ARG;
    }
    if ((err == 0) && (sz != (word32)key->ecc.dp->size)) {
        err = BUFFER_E;
    }

    if (err == 0) {
        err = mp_read_unsigned_bin(wc_ecc_key_get_priv(&key->ecc), data,
            (word32)key->ecc.dp->size);
    }

    return err;
}

/**
 * Export the KMS Public Auth Key (KPAK) from the ECCSI object.
 *
 * KPAK is required by all clients in order to perform cryptographic operations.
 *
 * X and y ordinate of public key concatenated. Each number is zero padded to
 * key size.
 * Descriptor byte (0x04) is prepended when not raw.
 *
 * @param  [in]      key      ECCSI key.
 * @param  [out]     data     Buffer to hold the encoded public key.
 * @param  [in,out]  sz       On in, size of buffer in bytes.
 *                            On out, length of encoded public key in bytes.
 * @param  [in]      raw   On 0, prepend descriptor byte.
 *                         On 1, only include ordinates.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key or sz is NULL.
 * @return  LENGTH_ONLY_E when data is NULL - sz is set.
 * @return  BUFFER_E when the buffer passed in is too small.
 */
int wc_ExportEccsiPublicKey(EccsiKey* key, byte* data, word32* sz, int raw)
{
    int err = 0;

    if ((key == NULL) || (sz == NULL)) {
        err = BAD_FUNC_ARG;
    }
    if ((err == 0) && (key->ecc.type != ECC_PRIVATEKEY) &&
            (key->ecc.type != ECC_PUBLICKEY)) {
        err = BAD_STATE_E;
    }

    if ((err == 0) && (data != NULL)) {
        err = eccsi_kpak_from_mont(key);
    }
    if (err == 0) {
        /* Write out public key. */
        err = eccsi_encode_point(&key->ecc.pubkey, (word32)key->ecc.dp->size,
            data, sz, raw);
    }

    return err;
}

/*
 * Generates an (SSK, PVT) Pair - signing key pair.
 *
 * RFC 6507, Section 5.1.1
 *
 * @param  [in]   key       ECCSI key.
 * @param  [in]   rng       Random number generator.
 * @param  [in]   hashType  Type of hash algorithm. e.g. WC_SHA256
 * @param  [in]   id        Identity to create hash from.
 * @param  [in]   idSz      Length of identity in bytes.
 * @param  [out]  ssk       Secret Signing Key as an MP integer.
 * @param  [out]  pvt       Public Validation Token (PVT) as an ECC point.
 * @return  0 on success.
 * @return  MP_MEM or MEMORY_E when dynamic memory allocation fails.
 * @return  Other -ve value when an internal operation fails.
 */
static int eccsi_make_pair(EccsiKey* key, WC_RNG* rng,
        enum wc_HashType hashType, const byte* id, word32 idSz, mp_int* ssk,
        ecc_point* pvt)
{
    int err = 0;
    byte hashSz = 0;
    int genTryCnt = 0;

    do {
        /* Don't infinitely make pairs when random number generator fails. */
        if ((++genTryCnt) > ECCSI_MAX_GEN_COUNT) {
            err = RNG_FAILURE_E;
        }

        if (err == 0) {
            wc_ecc_free(&key->pubkey);

            /* Step 1 and 2: Generate ephemeral key - v, PVT = [v]G */
            err = wc_ecc_make_key_ex(rng, key->ecc.dp->size, &key->pubkey,
                    key->ecc.dp->id);
        }
        if (err == 0) {
            err = wc_ecc_copy_point(&key->pubkey.pubkey, pvt);
        }

        /* Step 3: Compute HS */
        if (err == 0) {
            hashSz = (byte)sizeof(key->data);
            err = eccsi_compute_hs(key, hashType, id, idSz, pvt, key->data,
                    &hashSz);
        }

        /* Step 4: Compute SSK = ( KSAK + HS * v ) modulo q */
        if (err == 0) {
            err = mp_read_unsigned_bin(ssk, key->data, hashSz);
        }
        if (err == 0) {
            err = mp_mulmod(ssk, wc_ecc_key_get_priv(&key->pubkey),
                &key->params.order, ssk);
        }
        if (err == 0) {
            err = mp_addmod(ssk, wc_ecc_key_get_priv(&key->ecc),
                &key->params.order, ssk);
        }
    }
    while ((err == 0) && (mp_iszero(ssk) ||
            (mp_cmp(ssk, wc_ecc_key_get_priv(&key->ecc)) == MP_EQ)));
    /* Step 5: ensure SSK and HS are non-zero (code lines above) */

    /* Step 6: Copy out SSK (done during calc) and PVT. Erase v */
    mp_forcezero(wc_ecc_key_get_priv(&key->pubkey));

    return err;
}

/**
 * Generates an (SSK, PVT) Pair - signing key pair.
 *
 * RFC 6507, Section 5.1.1
 *
 * ID should include information to indicate a revocation date.\n
 * SSK must be zeroized after sending to client.\n
 * SSK is sent to signing client only.\n
 * PVT is sent to all client types.
 *
 * @param  [in]   key       ECCSI key.
 * @param  [in]   rng       Random number generator.
 * @param  [in]   hashType  Type of hash algorithm. e.g. WC_SHA256
 * @param  [in]   id        Identity to create hash from.
 * @param  [in]   idSz      Length of identity in bytes.
 * @param  [out]  ssk       Secret Signing Key as an MP integer.
 * @param  [out]  pvt       Public Validation Token (PVT) as an ECC point.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key, rng, id, ssk or pvt is NULL.
 * @return  BAD_STATE_E when curve not set (key not set).
 * @return  MP_MEM or MEMORY_E when dynamic memory allocation fails.
 * @return  Other -ve value when an internal operation fails.
 */
int wc_MakeEccsiPair(EccsiKey* key, WC_RNG* rng, enum wc_HashType hashType,
        const byte* id, word32 idSz, mp_int* ssk, ecc_point* pvt)
{
    int err = 0;

    if ((key == NULL) || (rng == NULL) || (id == NULL) || (ssk == NULL) ||
            (pvt == NULL)) {
        err = BAD_FUNC_ARG;
    }
    if ((err == 0) && (key->ecc.type != ECC_PRIVATEKEY)) {
        err = BAD_STATE_E;
    }

    if (err == 0) {
        err = eccsi_load_order(key);
    }
    if (err == 0) {
        err = eccsi_make_pair(key, rng, hashType, id, idSz, ssk, pvt);
    }

    return err;
}

/**
 * Encode the SSK and PVT into a buffer.
 *
 * SSK and PVT required by client signing messages.
 *
 * @param  [in]      key   ECCSI key.
 * @param  [in]      ssk   Secret Signing Key as an MP integer.
 * @param  [in]      pvt   Public Validation Token (PVT) as an ECC point.
 * @param  [out]     data  Buffer to encode key pair into.
 * @param  [in,out]  sz    In, size of buffer in bytes.
 *                         Out, size of encoded pair data in bytes.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key, ssk, pvt or sz is NULL.
 * @return  MP_MEM or MEMORY_E when dynamic memory allocation fails.
 * @return  LENGTH_ONLY_E when data is NULL - sz is set.
 */
int wc_EncodeEccsiPair(const EccsiKey* key, mp_int* ssk, ecc_point* pvt,
        byte* data, word32* sz)
{
    int err = 0;

    if ((key == NULL) || (ssk == NULL) || (pvt == NULL) || (sz == NULL)) {
        err = BAD_FUNC_ARG;
    }

    if ((err == 0) && (data == NULL)) {
        *sz = (word32)(key->ecc.dp->size * 3);
        err = WC_NO_ERR_TRACE(LENGTH_ONLY_E);
    }
    if ((err == 0) && (*sz < (word32)(key->ecc.dp->size * 3))) {
        err = BUFFER_E;
    }

    if (err == 0) {
        err = mp_to_unsigned_bin_len(ssk, data, key->ecc.dp->size);
    }
    if (err == 0) {
        data += key->ecc.dp->size;
        /* Write out the PVT's x ordinate into key size bytes. */
        err = mp_to_unsigned_bin_len(pvt->x, data, key->ecc.dp->size);
    }
    if (err == 0) {
        data += key->ecc.dp->size;
        /* Write out the PVT's y ordinate into key size bytes. */
        err = mp_to_unsigned_bin_len(pvt->y, data, key->ecc.dp->size);
    }
    if (err == 0) {
        *sz = (word32)(key->ecc.dp->size * 3);
    }

    return err;
}

/**
 * Encode the Secret Signing Key (SSK).
 *
 * Use when saving the key pair.
 *
 * SSK is zero padded to key size.
 *
 * @param  [in]      key   ECCSI key.
 * @param  [in]      ssk   Secret Signing Key as an MP integer.
 * @param  [out]     data  Buffer to hold encoded SSK.
 *                         NULL when requesting required length.
 * @param  [in,out]  sz    On in, size of buffer in bytes.
 *                         On out, size of encoded ECCSI key in bytes.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key, ssk or sz is NULL
 * @return  BAD_STATE_E when no key to export.
 * @return  LENGTH_ONLY_E when data is NULL - sz is set.
 * @return  BUFFER_E when the buffer passed in is too small.
 * @return  MEMORY_E when dynamic memory allocation fails (WOLFSSL_SMALL_STACK).
 */
int wc_EncodeEccsiSsk(const EccsiKey* key, mp_int* ssk, byte* data, word32* sz)
{
    int err = 0;

    if ((key == NULL) || (ssk == NULL) || (sz == NULL)) {
        err = BAD_FUNC_ARG;
    }

    if ((err == 0) && (key->ecc.type != ECC_PRIVATEKEY)) {
        err = BAD_STATE_E;
    }

    if (err == 0) {
        if (data == NULL) {
            *sz = (word32)key->ecc.dp->size;
            err = WC_NO_ERR_TRACE(LENGTH_ONLY_E);
        }
        else if (*sz < (word32)key->ecc.dp->size) {
            err = BUFFER_E;
        }
        else {
            *sz = (word32)key->ecc.dp->size;
        }
    }
    if (err == 0) {
        err = mp_to_unsigned_bin_len(ssk, data, key->ecc.dp->size);
    }

    return err;
}

/**
 * Decode the Secret Signing Key (SSK).
 *
 * Use when restoring the key pair.
 *
 * SSK is zero padded to key size.
 *
 * @param  [in]   key   ECCSI key.
 * @param  [in]   data  Buffer holding encoded ECCSI key.
 * @param  [in]   sz    Size of encoded ECCSI key in bytes.
 * @param  [out]  ssk   Secret Signing Key as an MP integer.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key, data or ssk is NULL.
 * @return  BUFFER_E when size of data is not equal to the expected size.
 * @return  MP_MEM or MEMORY_E when dynamic memory allocation fails.
 */
int wc_DecodeEccsiSsk(const EccsiKey* key, const byte* data, word32 sz,
        mp_int* ssk)
{
    int err = 0;

    if ((key == NULL) || (data == NULL) || (ssk == NULL)) {
        err = BAD_FUNC_ARG;
    }
    if ((err == 0) && (sz != (word32)key->ecc.dp->size)) {
        err = BUFFER_E;
    }

    if (err == 0) {
        err = mp_read_unsigned_bin(ssk, data, (word32)key->ecc.dp->size);
    }

    return err;
}

/**
 * Encode the PVT into a buffer.
 *
 * PVT required by client verifying messages.
 *
 * X and y ordinate of public key concatenated. Each number is zero padded to
 * key size.
 * Descriptor byte (0x04) is prepended when not raw.
 *
 * @param  [in]      key   ECCSI key.
 * @param  [in]      pvt   Public Validation Token (PVT) as an ECC point.
 * @param  [out]     data  Buffer to encode key pair into.
 * @param  [in,out]  sz    In, size of buffer in bytes.
 *                         Out, size of encoded pair data in bytes.
 * @param  [in]      raw   On 0, prepend descriptor byte.
 *                         On 1, only include ordinates.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key, pvt or sz is NULL.
 * @return  BAD_STATE_E when PVT has not been set.
 * @return  MP_MEM or MEMORY_E when dynamic memory allocation fails.
 * @return  LENGTH_ONLY_E when data is NULL - sz is set.
 */
int wc_EncodeEccsiPvt(const EccsiKey* key, ecc_point* pvt, byte* data,
        word32* sz, int raw)
{
    int err = 0;

    if ((key == NULL) || (pvt == NULL) || (sz == NULL)) {
        err = BAD_FUNC_ARG;
    }

    if (err == 0) {
        err = eccsi_encode_point(pvt, (word32)key->ecc.dp->size, data, sz, raw);
    }

    return err;
}

#endif /* WOLFCRYPT_ECCSI_KMS */

#ifdef WOLFCRYPT_ECCSI_CLIENT
/**
 * Decode the SSK and PVT data into separate variables.
 *
 * A signing client decodes the data so that it can validate the pair and sign.
 *
 * @param  [in]   key   ECCSI key.
 * @param  [in]   data  Buffer holding key pair data.
 * @param  [in]   sz    Size of data in bytes.
 * @param  [out]  ssk   Secret Signing Key as an MP integer.
 * @param  [out]  pvt   Public Validation Token (PVT) as an ECC point.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key, data, ssk or pvt is NULL.
 * @return  LENGTH_ONLY_E when data is NULL - sz is set.
 * @return  BUFFER_E when size of data is not equal to the expected size.
 * @return  MP_MEM or MEMORY_E when dynamic memory allocation fails.
 */
int wc_DecodeEccsiPair(const EccsiKey* key, const byte* data, word32 sz,
        mp_int* ssk, ecc_point* pvt)
{
    int err = 0;

    if ((key == NULL) || (data == NULL) || (ssk == NULL) || (pvt == NULL)) {
        err = BAD_FUNC_ARG;
    }
    if ((err == 0) && (sz != (word32)(key->ecc.dp->size * 3))) {
        err = BUFFER_E;
    }

    if (err == 0) {
        /* Read the SSK value from key size bytes. */
        err = mp_read_unsigned_bin(ssk, data, (word32)key->ecc.dp->size);
    }
    if (err == 0) {
        data += key->ecc.dp->size;
        /* Read the PVT's x value from key size bytes. */
        err = mp_read_unsigned_bin(pvt->x, data, (word32)key->ecc.dp->size);
    }
    if (err == 0) {
        data += key->ecc.dp->size;
        /* Read the PVT's y value from key size bytes. */
        err = mp_read_unsigned_bin(pvt->y, data, (word32)key->ecc.dp->size);
    }
    if (err == 0) {
        err = mp_set(pvt->z, 1);
    }

    return err;
}

/**
 * Decode the PVT data into an ECC point.
 *
 * A verifying client decodes the data so that it can verify a message.
 *
 * X and y ordinate of public key concatenated. Each number is zero padded to
 * key size.
 * Descriptor byte (0x04) is prepended when not raw.
 *
 * @param  [in]   key   ECCSI key.
 * @param  [in]   data  Buffer holding PVT data.
 * @param  [in]   sz    Size of data in bytes.
 * @param  [out]  pvt   Public Validation Token (PVT) as an ECC point.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key, data, ssk or pvt is NULL.
 * @return  BUFFER_E when size of data is not equal to the expected size.
 * @return  ASN_PARSE_E when format byte is invalid.
 * @return  MP_MEM or MEMORY_E when dynamic memory allocation fails.
 */
int wc_DecodeEccsiPvt(const EccsiKey* key, const byte* data, word32 sz,
        ecc_point* pvt)
{
    int err = 0;

    if ((key == NULL) || (data == NULL) || (pvt == NULL)) {
        err = BAD_FUNC_ARG;
    }

    if (err == 0) {
        err = eccsi_decode_point(pvt, (word32)key->ecc.dp->size, data, sz);
    }

    return err;
}

/**
 * Decode the PVT data, from a signature, into an ECC point.
 *
 * A verifying client decodes the data so that it can calculate the identity
 * hash.
 *
 * X and y ordinate of public key concatenated. Each number is zero padded to
 * key size.
 * Descriptor byte (0x04) is prepended when not raw.
 *
 * @param  [in]   key   ECCSI key.
 * @param  [in]   sig   Buffer holding signature data.
 * @param  [in]   sz    Size of data in bytes.
 * @param  [out]  pvt   Public Validation Token (PVT) as an ECC point.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key, data, ssk or pvt is NULL.
 * @return  BUFFER_E when size of data is not equal to the expected size.
 * @return  ASN_PARSE_E when format byte is invalid.
 * @return  MP_MEM or MEMORY_E when dynamic memory allocation fails.
 */
int wc_DecodeEccsiPvtFromSig(const EccsiKey* key, const byte* sig, word32 sz,
        ecc_point* pvt)
{
    int err = 0;

    if ((key == NULL) || (sig == NULL) || (pvt == NULL)) {
        err = BAD_FUNC_ARG;
    }

    if (err == 0) {
        word32 rSz = (word32)(key->ecc.dp->size * 2);
        err = eccsi_decode_point(pvt, (word32)key->ecc.dp->size, sig + rSz,
                sz - rSz);
    }

    return err;
}

/**
 * Import the KMS Public Auth Key (KPAK) into the ECCSI object.
 *
 * Clients import the KPAK to perform cryptographic operations.
 *
 * X and y ordinate of public key concatenated. Each number is zero padded to
 * key size.
 * Descriptor byte (0x04) is prepended when not raw.
 *
 * @param  [in]  key      ECCSI key.
 * @param  [in]  data     Encoded public key as an array of bytes.
 * @param  [in]  sz       Length of encoded KPAK in bytes.
 * @param  [in]  trusted  1 when public key is trusted.
 *                        0 when validation is required to be performed.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key or data is NULL.
 * @return  BUFFER_E when size of data is not equal to the expected size.
 * @return  ASN_PARSE_E when format byte is invalid.
 * @return  ECC_OUT_OF_RANGE_E when point is invalid.
 * @return  ECC_INF_E when point is at infinity and invalid.
 * @return  MP_MEM or MEMORY_E when dynamic memory allocation fails.
 */
int wc_ImportEccsiPublicKey(EccsiKey* key, const byte* data, word32 sz,
        int trusted)
{
    int err = 0;

    if ((key == NULL) || (data == NULL)) {
        err = BAD_FUNC_ARG;
    }

    if (err == 0) {
        key->kpakMont = 0;

        /* Read the public key. */
        err = eccsi_decode_point(&key->ecc.pubkey, (word32)key->ecc.dp->size,
                data, sz);
    }
    if (err == 0) {
        key->ecc.type = ECC_PUBLICKEY;
    }
    if ((err == 0) && (!trusted)) {
       err = wc_ecc_check_key(&key->ecc);
    }

    return err;
}

/*
 * Scalar multiply the base point of the curve and add a point.
 *
 * @param  [in]   key   ECCSI key.
 * @param  [in]   n     MP integer representing scalar to multiply by.
 * @param  [in]   a     ECC point to add.
 * @param  [out]  res   ECC point representation of the resulting point.
 * @param  [in]   mp    Montgomery reduction multiplier.
 * @param  [in]   map   0 indicates to leave in projective representation.
 *                      1 indicates map projective point to affine.
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 * @return  Other -ve value when an internal operation fails.
 */
static int eccsi_mulmod_base_add(EccsiKey* key, const mp_int* n,
        ecc_point* a, ecc_point* res, mp_digit mp, int map)
{
    int err = 0;

#if defined(WOLFSSL_HAVE_SP_ECC) && !defined(WOLFSSL_SP_NO_256)
    if ((key->ecc.idx != ECC_CUSTOM_IDX) &&
            (ecc_sets[key->ecc.idx].id == ECC_SECP256R1)) {
        err = sp_ecc_mulmod_base_add_256(n, a, 1, res, map, key->heap);
    }
    else
#endif
#ifndef WOLFSSL_SP_MATH
    {
        EccsiKeyParams* params = &key->params;
        err = wc_ecc_mulmod(n, params->base, params->base, &params->a,
                &params->prime, 0);
        key->params.haveBase = 0;
        if (err == 0) {
            err = ecc_projective_add_point(params->base, a, res, &params->a,
                    &params->prime, mp);
        }
        if ((err == 0) && map) {
            err = ecc_map(res, &params->prime, mp);
        }
    }
#else
    {
        err = NOT_COMPILED_IN;
    }
    (void)key;
    (void)n;
    (void)a;
    (void)res;
    (void)mp;
    (void)map;
#endif

    return err;
}

/*
 * Scalar multiply a point on the curve.
 *
 * @param  [in]   key    ECCSI key.
 * @param  [in]   n      MP integer representing scalar to multiply by.
 * @param  [in]   point  ECC point representation of a point on the curve.
 * @param  [out]  res    ECC point representation of the resulting point.
 * @param  [in]   map    0 indicates to leave in projective representation.
 *                       1 indicates map projective point to affine.
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 * @return  Other -ve value when an internal operation fails.
 */
static int eccsi_mulmod_point(EccsiKey* key, const mp_int* n, ecc_point* point,
        ecc_point* res, int map)
{
    int err;

#if defined(WOLFSSL_HAVE_SP_ECC) && !defined(WOLFSSL_SP_NO_256)
    if ((key->ecc.idx != ECC_CUSTOM_IDX) &&
            (ecc_sets[key->ecc.idx].id == ECC_SECP256R1)) {
        err = sp_ecc_mulmod_256(n, point, res, map, key->heap);
    }
    else
#endif
    {
        EccsiKeyParams* params = &key->params;

        err = wc_ecc_mulmod(n, point, res, &params->a, &params->prime, map);
    }

    return err;
}

/*
 * Scalar multiply a point on the curve and add a.
 *
 * @param  [in]   key    ECCSI key.
 * @param  [in]   n      MP integer representing scalar to multiply by.
 * @param  [in]   point  ECC point representation of a point on the curve.
 * @param  [in]   a      ECC point to add.
 * @param  [out]  res    ECC point representation of the resulting point.
 * @param  [in]   mp     Montgomery reduction multiplier.
 * @param  [in]   map    0 indicates to leave in projective representation.
 *                       1 indicates map projective point to affine.
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 * @return  Other -ve value when an internal operation fails.
 */
static int eccsi_mulmod_point_add(EccsiKey* key, const mp_int* n,
        ecc_point* point, ecc_point* a, ecc_point* res, mp_digit mp, int map)
{
#if defined(WOLFSSL_HAVE_SP_ECC) && !defined(WOLFSSL_SP_NO_256)
    int err = WC_NO_ERR_TRACE(NOT_COMPILED_IN);

    if ((key->ecc.idx != ECC_CUSTOM_IDX) &&
            (ecc_sets[key->ecc.idx].id == ECC_SECP256R1)) {
        err = sp_ecc_mulmod_add_256(n, point, a, 0, res, map, key->heap);
    }

    (void)mp;

    return err;
#else
    int err;
    EccsiKeyParams* params = &key->params;

    err = wc_ecc_mulmod(n, point, res, &params->a, &params->prime, 0);
    if (err == 0) {
        err = ecc_projective_add_point(res, a, res, &key->params.a,
                &params->prime, mp);
    }
    if ((err == 0) && map) {
        err = ecc_map(res, &params->prime, mp);
    }

    return err;
#endif
}

/**
 * Validate an (SSV, PVT) Pair.
 *
 * RFC 6507, Section 5.1.2
 *
 * A signing client should validate the key pair before first use.
 *
 * @param  [in]   key       ECCSI key.
 * @param  [in]   hashType  Type of hash algorithm. e.g. WC_SHA256
 * @param  [in]   id        Identity to create hash from.
 * @param  [in]   idSz      Length of identity in bytes.
 * @param  [in]   ssk       Secret Signing Key as an MP integer.
 * @param  [in]   pvt       Public Validation Token (PVT) as an ECC point.
 * @param  [out]  valid     1 when pair is valid and 0 otherwise.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key, id, ssk, pvt or valid is NULL.
 * @return  BAD_STATE_E when curve not set (key not set).
 * @return  MP_MEM or MEMORY_E when dynamic memory allocation fails.
 * @return  IS_POINT_E when point is not on the curve.
 * @return  Other -ve value when an internal operation fails.
 */
int wc_ValidateEccsiPair(EccsiKey* key, enum wc_HashType hashType,
        const byte* id, word32 idSz, const mp_int* ssk, ecc_point* pvt,
        int* valid)
{
    int err = 0;
    ecc_point* res = NULL;
    mp_int* hs = NULL;
    mp_digit mp = 0;
    byte hashSz = 0;
    EccsiKeyParams* params = NULL;

    if ((key == NULL) || (id == NULL) || (ssk == NULL) || (pvt == NULL) ||
            (valid == NULL)) {
        err = BAD_FUNC_ARG;
    }

    if ((err == 0) && (key->ecc.type != ECC_PRIVATEKEY) &&
            (key->ecc.type != ECC_PUBLICKEY)) {
        err = BAD_STATE_E;
    }

    if (err != 0)
        return err;

    SAVE_VECTOR_REGISTERS(return _svr_ret;);

    params = &key->params;
    hs = &key->tmp;
    res = &key->pubkey.pubkey;

    err = eccsi_load_base(key);

    if (err == 0) {
       err = eccsi_load_ecc_params(key);
    }
    if (err == 0) {
        err = mp_montgomery_setup(&params->prime, &mp);
    }

    /* Step 1: Validate PVT is on curve */
    if (err == 0) {
        err = wc_ecc_is_point(pvt, &params->a, &params->b, &params->prime);
        if (err == -1) {
            err = IS_POINT_E;
        }
    }

    /* Step 2: Compute HS = hash( G | KPAK | ID | PVT ) */
    if (err == 0) {
        hashSz = (byte)sizeof(key->data);
        /* Converts KPAK from mont. */
        err = eccsi_compute_hs(key, hashType, id, idSz, pvt, key->data,
                &hashSz);
    }

    /* Step 3: Validate that KPAK = [SSK]G - [HS]PVT */
    if (err == 0) {
        err = mp_read_unsigned_bin(hs, key->data, hashSz);
    }
    /* [HS]PVT */
    if (err == 0) {
        err = eccsi_mulmod_point(key, hs, pvt, res, 0);
    }
    /* -[HS]PVT */
    if (err == 0) {
        err = mp_sub(&params->prime, res->y, res->y);
    }
    /* [SSK]G + -[HS]PVT */
    if (err == 0) {
        err = eccsi_mulmod_base_add(key, ssk, res, res, mp, 1);
    }
    if (valid != NULL) {
        *valid = (err == 0);
        if (err == 0) {
            ecc_point* kpak = &key->ecc.pubkey;
            /* Compare KPAK and [SSK]G + -[HS]PVT */
            *valid = (wc_ecc_cmp_point(res, kpak) == MP_EQ);
        }
    }

    RESTORE_VECTOR_REGISTERS();

    return err;
}

/**
 * Validate Public Validation Token (PVT) is on the curve.
 *
 * RFC 6507, Section 5.1.2, Step 1
 *
 * A verifying client should validate the PVT before first use.
 *
 * @param  [in]   key       ECCSI key.
 * @param  [in]   pvt       Public Validation Token (PVT) as an ECC point.
 * @param  [out]  valid     1 when PVT is valid and 0 otherwise.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key, pvt or valid is NULL.
 * @return  BAD_STATE_E when curve not set (key not set).
 * @return  MP_MEM or MEMORY_E when dynamic memory allocation fails.
 * @return  Other -ve value when an internal operation fails.
 */
int wc_ValidateEccsiPvt(EccsiKey* key, const ecc_point* pvt, int* valid)
{
    int err = 0;

    if ((key == NULL)| (pvt == NULL) || (valid == NULL)) {
        err = BAD_FUNC_ARG;
    }

    if (err == 0) {
        err = wc_ecc_set_curve(&key->pubkey, key->ecc.dp->size,
                key->ecc.dp->id);
    }
    if (err == 0) {
        err = wc_ecc_copy_point(pvt, &key->pubkey.pubkey);
    }
    if (err == 0) {
        *valid = (wc_ecc_check_key(&key->pubkey) == 0);
    }

    return err;
}

/**
 * Creates the Hash of the ID and PVT with the ECCSI key.
 *
 * The hash ID is required as input to the sign and verify operations.\n
 * Signing clients may cache this value.
 *
 * RFC 6507, Section 5.2.1, Step 3
 *
 * Set the calculated hash internally for use.
 *
 * @param  [in]   key       ECCSI key.
 * @param  [in]   hashType  Type of hash algorithm. e.g. WC_SHA256
 * @param  [in]   id        Identity to create hash from.
 * @param  [in]   idSz      Length of identity in bytes.
 * @param  [in]   pvt       Public Validation Token (PVT) as an ECC point.
 * @param  [out]  hash      Buffer to hold hash result.
 * @param  [out]  hashSz    Length of hash data in bytes.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key, id, pvt, hash or hashSz is NULL.
 * @return  BAD_FUNC_ARG when hash size doesn't match curve size.
 * @return  BAD_STATE_E when public key not set.
 * @return  MEMORY_E when dynamic memory allocation fails.
 * @return  Other -ve value when an internal operation fails.
 */
int wc_HashEccsiId(EccsiKey* key, enum wc_HashType hashType, const byte* id,
        word32 idSz, ecc_point* pvt, byte* hash, byte* hashSz)
{
    int err = 0;
    int dgstSz = -1;
    int curveSz = -1;

    if ((key == NULL) || (id == NULL) || (pvt == NULL) || (hash == NULL) ||
            (hashSz == NULL)) {
        err = BAD_FUNC_ARG;
    }
    if ((err == 0) && (key->ecc.type != ECC_PRIVATEKEY) &&
            (key->ecc.type != ECC_PUBLICKEY)) {
        err = BAD_STATE_E;
    }
    /* Ensure digest output size matches curve size (RFC 6507 4.1). */
    if (err == 0) {
        dgstSz = wc_HashGetDigestSize(hashType);
        if (dgstSz < 0) {
            err = dgstSz;
        }
    }
    if (err == 0) {
        curveSz = wc_ecc_get_curve_size_from_id(key->ecc.dp->id);
        if (curveSz < 0) {
            err = curveSz;
        }
    }
    if ((err == 0) && (dgstSz != curveSz)) {
        err = BAD_FUNC_ARG;
    }
    /* Load the curve parameters for operations */
    if (err == 0) {
       err = eccsi_load_ecc_params(key);
    }
    if (err == 0) {
        err = eccsi_compute_hs(key, hashType, id, idSz, pvt, hash, hashSz);
    }
    if (err == 0) {
        XMEMCPY(key->idHash, hash, *hashSz);
        key->idHashSz = *hashSz;
    }

    return err;
}

/**
 * Set the identity hash for use with signing/verification.
 *
 * @param  [in]  key     ECCSI key.
 * @param  [in]  hash    Buffer with hash of identity.
 * @param  [in]  hashSz  Length of hash data in bytes.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key or hash is NULL, or hashSz is greater than
 *          WC_MAX_DIGEST_SIZE.
 */
int wc_SetEccsiHash(EccsiKey* key, const byte* hash, byte hashSz)
{
    int err = 0;

    if ((key == NULL) || (hash == NULL) || (hashSz > WC_MAX_DIGEST_SIZE)) {
        err = BAD_FUNC_ARG;
    }
    if (err == 0) {
        XMEMCPY(key->idHash, hash, hashSz);
        key->idHashSz = hashSz;
    }

    return err;
}

/**
 * Set an (SSV, PVT) Pair for signing.
 *
 * @param  [in]   key  ECCSI key.
 * @param  [in]   ssk  Secret Signing Key as an MP integer.
 * @param  [in]   pvt  Public Validation Token (PVT) as an ECC point.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key, ssk or pvt is NULL.
 * @return  MP math errors when copy fails
 */
int wc_SetEccsiPair(EccsiKey* key, const mp_int* ssk, const ecc_point* pvt)
{
    int err = 0;

    if ((key == NULL) || (ssk == NULL) || (pvt == NULL)) {
        err = BAD_FUNC_ARG;
    }

    if (err == 0) {
        err = mp_copy(ssk, &key->ssk);
    }

    if (err == 0) {
        err = wc_ecc_copy_point(pvt, key->pvt);
    }

    return err;
}

#ifdef ECCSI_ORDER_MORE_BITS_THAN_PRIME
/*
 * Fit the number to the maximum number of bytes.
 *
 * If the number is too big then subtract from order.
 * RFC 6507, Section 5.2.1, Note at end.
 * This should only happen when order is larger than prime in bits.
 *
 * @param  [in]   a      MP integer to fix.
 * @param  [in]   order  MP integer representing order of curve.
 * @param  [in]   m      Maximum number of bytes to encode into.
 * @param  [out]  r      MP integer that is the result after fixing.
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 */
static int eccsi_fit_to_octets(const mp_int* a, mp_int* order, int m,
        mp_int* r)
{
    int err;

    if (mp_count_bits(a) > m * 8) {
        err = mp_sub(order, (mp_int*)a, r);
    }
    else
    {
        err = mp_copy(a, r);
    }

    return err;
}
#else
/*
 * Fit the number to the maximum number of bytes.
 *
 * If the number is too big then subtract from order.
 * RFC 6507, Section 5.2.1, Note at end.
 * This should only happen when order is larger than prime in bits.
 *
 * @param  [in]   a      MP integer to fix.
 * @param  [in]   order  MP integer representing order of curve.
 * @param  [in]   m      Maximum number of bytes to encode into.
 * @param  [out]  r      MP integer that is the result after fixing.
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 */
static int eccsi_fit_to_octets(const mp_int* a, const mp_int* order, int m,
        mp_int* r)
{
    (void)order;
    (void)m;

    /* Duplicate line to stop static analyzer complaining. */
    return mp_copy(a, r);
}
#endif

/*
 * Compute the HE = hash( HS | r | M ), hash value of signature.
 *
 * Partial result required for signing and verification.
 *
 * @param  [in]   key       ECCSI key.
 * @param  [in]   hashType  Type of hash algorithm. e.g. WC_SHA256
 * @param  [in]   r         MP integer that is the first signature element.
 * @param  [in]   msg       Message of signature.
 * @param  [in]   msgSz     Length of message in bytes.
 * @param  [out]  he        Signature hash.
 * @param  [out]  heSz      Length of signature hash in bytes
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 * @return  Other -ve value when an internal operation fails.
 */
static int eccsi_compute_he(EccsiKey* key, enum wc_HashType hashType,
        mp_int* r, const byte* msg, word32 msgSz, byte* he, word32* heSz)
{
    int err = 0;
    word32 dataSz = (word32)key->ecc.dp->size;
    int hash_inited = 0;

    /* HE = hash( HS | r | M ) */
    err = wc_HashInit_ex(&key->hash, hashType, key->heap, INVALID_DEVID);
    if (err == 0) {
        hash_inited = 1;
        /* HS */
        err = wc_HashUpdate(&key->hash, hashType, key->idHash, key->idHashSz);
    }
    if (err == 0) {
        err = mp_to_unsigned_bin_len(r, key->data, (int)dataSz);
    }
    if (err == 0) {
        /* r */
        err = wc_HashUpdate(&key->hash, hashType, key->data, dataSz);
    }
    if (err == 0) {
        /* M */
        err = wc_HashUpdate(&key->hash, hashType, msg, msgSz);
    }
    if (err == 0) {
        err = wc_HashFinal(&key->hash, hashType, he);
    }
    if (err == 0) {
        *heSz = (word32)wc_HashGetDigestSize(hashType);
    }

    if (hash_inited) {
        (void)wc_HashFree(&key->hash, hashType);
    }

    return err;
}

/*
 * Encode the signature = ( r | s | PVT )
 *
 * @param  [in]   key    ECCSI key.
 * @param  [in]   r      MP integer that is the first signature element.
 * @param  [in]   s      MP integer that is the second signature element.
 * @param  [in]   pvt    ECC point representing Public Validation Token.
 * @param  [out]  sig    Signature of message.
 * @param  [out]  sigSz  Length of signature in bytes.
 */
static int eccsi_encode_sig(const EccsiKey* key, mp_int* r, mp_int* s,
        byte* sig, word32* sigSz)
{
    int err;
    word32 sz = (word32)key->ecc.dp->size;

    err = mp_to_unsigned_bin_len(r, sig, (int)sz);
    if (err == 0) {
        err = mp_to_unsigned_bin_len(s, sig + sz, (int)sz);
    }
    if (err == 0) {
        *sigSz = (word32)(key->ecc.dp->size * 2 + 1);
        err = wc_ecc_export_point_der(wc_ecc_get_curve_idx(key->ecc.dp->id),
                 key->pvt, sig + sz * 2, sigSz);
    }
    if (err == 0) {
        *sigSz = sz * 4 + 1;
    }

    return err;
}

/*
 * Sign the ECCSI hash (of ID with the key) to two mp_int objects: r and s.
 *
 * RFC 6507, Section 5.2.1, Steps 1 to 4
 *
 * @param  [in]   key       ECCSI key.
 * @param  [in]   rng       Random number generator.
 * @param  [in]   hashType  Type of hash algorithm. e.g. WC_SHA256
 * @param  [in]   msg       Message to sign.
 * @param  [in]   msgSz     Length of message in bytes.
 * @param  [out]  r         First big number integer part of signature.
 * @param  [out]  s         Second big number integer part of signature.
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 * @return  Other -ve value when an internal operation fails.
 */
static int eccsi_gen_sig(EccsiKey* key, WC_RNG* rng, enum wc_HashType hashType,
        const byte* msg, word32 msgSz, mp_int* r, mp_int* s)
{
    int err = 0;
    int sz = key->ecc.dp->size;
    word32 heSz = 0;
    const mp_int* jx = NULL;
    mp_int* he = &key->tmp;
    int genTryCnt = 0;

    do {
        /* Don't infinitely gen sigs when random number generator fails. */
        if ((++genTryCnt) > ECCSI_MAX_GEN_COUNT) {
            err = RNG_FAILURE_E;
        }

        if (err == 0) {
            wc_ecc_free(&key->pubkey);

            /* Step 1 and 2: Generate ephemeral key - j, J = [j]G, r = Jx */
            err = wc_ecc_make_key_ex(rng, sz, &key->pubkey, key->ecc.dp->id);
        }
        if (err == 0) {
            jx = key->pubkey.pubkey.x;
            err = eccsi_fit_to_octets(jx, &key->params.order, sz, r);
        }

        /* Step 3: Compute HE = hash( HS | r | M ) */
        if (err == 0) {
            err = eccsi_compute_he(key, hashType, r, msg, msgSz, key->data,
                    &heSz);
        }

        /* Step 4: Verify that HE + r * SSK is non-zero modulo q */
        if (err == 0) {
            err = mp_read_unsigned_bin(he, key->data, heSz);
        }
        /* s' = r * SSK */
        if (err == 0) {
            err = mp_mulmod(r, &key->ssk, &key->params.order, s);
        }
        /* s' = HE + r * SSK */
        if (err == 0) {
            err = mp_addmod(he, s, &key->params.order, s);
        }
    }
    while ((err == 0) && (mp_iszero(s) || (mp_cmp(s, he) == MP_EQ)));

    return err;
}


/**
 * Sign the ECCSI hash (of ID with the key).
 *
 * RFC 6507, Section 5.2.1
 *
 * Must have imported KPAK using wc_ImportEccsiPublicKey() before calling.\n
 * Use wc_HashEccsiId() to calculate the hash and wc_SetEccsiHash() to set
 * the identity hash to use.
 *
 * @param  [in]   key       ECCSI key.
 * @param  [in]   rng       Random number generator.
 * @param  [in]   hashType  Type of hash algorithm. e.g. WC_SHA256
 * @param  [in]   msg       Message to sign.
 * @param  [in]   msgSz     Length of message in bytes.
 * @param  [out]  sig       Signature of message.
 * @param  [out]  sigSz     Length of signature in bytes.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key, rng, msg or sigSz is NULL.
 * @return  BAD_STATE_E when the curve or id hash has not been set (no key set).
 * @return  LENGTH_ONLY_E when sig is NULL - sigSz is set.
 * @return  MEMORY_E when dynamic memory allocation fails.
 * @return  Other -ve value when an internal operation fails.
 */
int wc_SignEccsiHash(EccsiKey* key, WC_RNG* rng, enum wc_HashType hashType,
        const byte* msg, word32 msgSz, byte* sig, word32* sigSz)
{
    int err = 0;
    mp_int* r = NULL;
    mp_int* s = NULL;
    mp_int* j = NULL;
    word32 sz = 0;

    if ((key == NULL) || (rng == NULL) || (msg == NULL) || (sigSz == NULL)) {
        err = BAD_FUNC_ARG;
    }
    if ((err == 0) && (key->ecc.type != ECC_PUBLICKEY) &&
            (key->ecc.type != ECC_PRIVATEKEY)) {
        err = BAD_STATE_E;
    }
    if ((err == 0) && (sig != NULL) && (key->idHashSz == 0)) {
        err = BAD_STATE_E;
    }

    if (err == 0)  {
        sz = (word32)key->ecc.dp->size;
        if (sig == NULL) {
            *sigSz = sz * 4 + 1;
            err = WC_NO_ERR_TRACE(LENGTH_ONLY_E);
        }
    }
    if ((err == 0) && (*sigSz < sz * 4 + 1)) {
        err = BAD_FUNC_ARG;
    }

    if (err == 0) {
        r = key->pubkey.pubkey.y;
        s = key->pubkey.pubkey.z;

        err = eccsi_load_order(key);
    }

    if (err == 0) {
        /* Steps 1 to 4. */
        err = eccsi_gen_sig(key, rng, hashType, msg, msgSz, r, s);
    }

    /* Step 5: s' = ( (( HE + r * SSK )^-1) * j ) modulo q, erase j */
    if (err == 0) {
        err = mp_invmod(s, &key->params.order, s);
    }
    if (err == 0) {
        j = wc_ecc_key_get_priv(&key->pubkey);
        err = mp_mulmod(s, j, &key->params.order, s);
    }
    if (err == 0) {
        mp_forcezero(j);

        /* Step 6: s = s' fitted */
        err = eccsi_fit_to_octets(s, &key->params.order, (int)sz, s);
    }

    /* Step 7: Output Signature = ( r | s | PVT ) */
    if (err == 0) {
        err = eccsi_encode_sig(key, r, s, sig, sigSz);
    }

    return err;
}

/*
 * Decode the s part of the signature = ( r | s | PVT )
 *
 * @param  [in]   key    ECCSI key.
 * @param  [in]   sig    Signature of message.
 * @param  [in]   sigSz  Length of signature in bytes.
 * @param  [out]  s      MP integer that is the second signature element.
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 * @return  Other -ve value when an internal operation fails.
 */
static int eccsi_decode_sig_s(const EccsiKey* key, const byte* sig,
        word32 sigSz, mp_int* s)
{
    int err = 0;
    word32 sz = (word32)key->ecc.dp->size;

    if (sigSz != sz * 4 + 1) {
        err = BAD_FUNC_ARG;
    }

    if (err == 0) {
        err = mp_read_unsigned_bin(s, sig + sz, sz);
    }

    return err;
}

/*
 * Decode the r and pvt part of the signature = ( r | s | PVT )
 *
 * @param  [in]   key    ECCSI key.
 * @param  [in]   sig    Signature of message.
 * @param  [in]   sigSz  Length of signature in bytes.
 * @param  [out]  r      MP integer that is the first signature element.
 * @param  [out]  pvt    ECC point representing Public Validation Token.
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 * @return  Other -ve value when an internal operation fails.
 */
static int eccsi_decode_sig_r_pvt(const EccsiKey* key, const byte* sig,
        word32 sigSz, mp_int* r, ecc_point* pvt)
{
    int err = 0;
    word32 sz = (word32)key->ecc.dp->size;

    if (sigSz != sz * 4 + 1) {
        err = BAD_FUNC_ARG;
    }

    if (err == 0) {
        err = mp_read_unsigned_bin(r, sig, sz);
    }
    if (err == 0) {
        /* must free previous public point otherwise wc_ecc_import_point_der
         * could leak memory */
        mp_clear(pvt->x);
        mp_clear(pvt->y);
        mp_clear(pvt->z);

        err = wc_ecc_import_point_der(sig + sz * 2, sz * 2 + 1,
                wc_ecc_get_curve_idx(key->ecc.dp->id), pvt);
    }

    return err;
}

/*
 * Calculate Y point as part of verification process.
 *
 * Y = [HS]PVT + KPAK
 *
 * @param  [in]   key      ECCSI key.
 * @param  [in]   pvt      ECC point representing Public Validation Token.
 * @param  [in]   mp       Montgomery reduction multiplier.
 * @param  [out]  y        ECC point representing calculated value Y.
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 * @return  Other value when an an internal operation fails.
 */
static int eccsi_calc_y(EccsiKey* key, ecc_point* pvt, mp_digit mp,
        ecc_point* y)
{
    int err;
    mp_int* hs = &key->ssk;

    err = mp_read_unsigned_bin(hs, key->idHash, key->idHashSz);
#ifndef WOLFSSL_HAVE_SP_ECC
    /* Need KPAK in montgomery form. */
    if (err == 0) {
        err = eccsi_kpak_to_mont(key);
    }
#endif
    /* [HS]PVT + KPAK */
    if (err == 0) {
        ecc_point* kpak = &key->ecc.pubkey;
        err = eccsi_mulmod_point_add(key, hs, pvt, kpak, y, mp, 1);
    }

    return err;
}

/*
 * Calculate J point as part of verification process.
 *
 * J = [s]( [HE]G + [r]Y )
 *
 * @param  [in]   key    ECCSI key.
 * @param  [in]   hem    MP int representation of HE = Hash (hs, r and message).
 * @param  [in]   sig    Signature of message.
 * @param  [in]   sigSz  Length of signature in bytes.
 * @param  [in]   y      ECC point representing [r]Y.
 * @param  [in]   mp     Montgomery reduction multiplier.
 * @param  [out]  j      ECC point representing calculated value J.
 * @return  0 on success.
 * @return  MEMORY_E when dynamic memory allocation fails.
 * @return  Other value when an an internal operation fails.
 */
static int eccsi_calc_j(EccsiKey* key, const mp_int* hem, const byte* sig,
        word32 sigSz, ecc_point* y, mp_digit mp, ecc_point* j)
{
    int err;
    mp_int* s = &key->tmp;

    /* [HE]G + [r]Y */
    err = eccsi_mulmod_base_add(key, hem, y, j, mp, 1);
    if (err == 0) {
        err = eccsi_decode_sig_s(key, sig, sigSz, s);
    }
    /* Validate s is in [1, q-1]: reject zero or out-of-range second signature
     * component.  With s=0, [s](...) yields the point at infinity whose
     * affine x-coordinate is 0, making the final mp_cmp(0,0) accept any
     * forged signature. */
    if (err == 0) {
        if (mp_iszero(s)) {
            err = MP_ZERO_E;
        }
        else if (mp_cmp(s, &key->params.order) != MP_LT) {
            err = ECC_OUT_OF_RANGE_E;
        }
    }
    /* [s]( [HE]G + [r]Y ) */
    if (err == 0) {
        err = eccsi_mulmod_point(key, s, j, j, 1);
    }

    return err;
}

/**
 * Verify the ECCSI hash (of ID with the key).
 *
 * RFC 6507, Section 5.2.2
 *
 * Must have imported KPAK using wc_ImportEccsiPublicKey() before calling.\n
 * Use wc_HashEccsiId() to calculate the hash and wc_SetEccsiHash() to set
 * the identity hash to use.
 *
 * @param  [in]   key       ECCSI key.
 * @param  [in]   hashType  Type of hash algorithm. e.g. WC_SHA256
 * @param  [in]   msg       Message to verify.
 * @param  [in]   msgSz     Length of message in bytes.
 * @param  [in]   sig       Signature of message.
 * @param  [in]   sigSz     Length of signature in bytes.
 * @param  [out]  verified  1 when the signature was verified and 0 otherwise.
 * @return  0 on success.
 * @return  BAD_FUNC_ARG when key, hash, msg, sig or ret is NULL.
 * @return  BAD_STATE_E when the curve or id hash has not been set (no key set).
 * @return  MEMORY_E when dynamic memory allocation fails.
 * @return  Other value when an an internal operation fails.
 */
int wc_VerifyEccsiHash(EccsiKey* key, enum wc_HashType hashType,
        const byte* msg, word32 msgSz, const byte* sig, word32 sigSz,
        int* verified)
{
    int err = 0;
    byte* he = NULL;
    word32 heSz = 0;
    mp_int* r = NULL;
    mp_int* jx = NULL;
    mp_int* hem = NULL;
    ecc_point* pvt = NULL;
    ecc_point* y = NULL;
    ecc_point* j = NULL;
    mp_digit mp = 0;
    EccsiKeyParams* params = NULL;

    if ((key == NULL) || (msg == NULL) || (sig == NULL) || (verified == NULL)) {
        err = BAD_FUNC_ARG;
    }
    if ((err == 0) && (key->ecc.type != ECC_PRIVATEKEY) &&
            (key->ecc.type != ECC_PUBLICKEY)) {
        err = BAD_STATE_E;
    }
    if ((err == 0) && (key->idHashSz == 0)) {
        err = BAD_STATE_E;
    }

    if (err != 0)
        return err;

    SAVE_VECTOR_REGISTERS(return _svr_ret;);

    /* Decode the signature into components. */
    r = wc_ecc_key_get_priv(&key->pubkey);
    pvt = &key->pubkey.pubkey;
    err = eccsi_decode_sig_r_pvt(key, sig, sigSz, r, pvt);

    /* Load the curve parameters for operations */
    if (err == 0) {
        err = eccsi_load_base(key);
    }
    if (err == 0) {
        err = eccsi_load_ecc_params(key);
    }
    if (err == 0) {
        params = &key->params;
        err = mp_montgomery_setup(&params->prime, &mp);
    }

    /* Validate r is in [1, q-1]: reject zero or out-of-range first signature
     * component before any scalar multiplication takes place.
     * Without this check, r=0 causes J_x=0 and the final mp_cmp(0,0)==MP_EQ
     * comparison accepts the forged signature unconditionally. */
    if (err == 0) {
        if (mp_iszero(r)) {
            err = MP_ZERO_E;
        }
        else if (mp_cmp(r, &params->order) != MP_LT) {
            err = ECC_OUT_OF_RANGE_E;
        }
    }

    /* Step 1: Validate PVT is on curve */
    if (err == 0) {
        err = wc_ecc_is_point(pvt, &params->a, &params->b, &params->prime);
    }

    /* Step 2: Compute HS = hash( G | KPAK | ID | PVT )
     * HS is key->idHash, key->idHashSz */

    /* Step 3: Compute HE = hash( HS | r | M ) */
    if (err == 0) {
        he = key->data;
        err = eccsi_compute_he(key, hashType, r, msg, msgSz, he, &heSz);
    }

    /* Step 4: Y = [HS]PVT + KPAK */
    if (err == 0) {
        y = pvt;
        err = eccsi_calc_y(key, pvt, mp, y);
    }

    /* Step 5: Compute J = [s]( [HE]G + [r]Y ) */
    /* [r]Y */
    if (err == 0) {
        hem = &key->tmp;
        err = mp_read_unsigned_bin(hem, he, heSz);
    }
    if (err == 0) {
        err = eccsi_mulmod_point(key, r, y, y, 0);
    }
    if (err == 0) {
        j = params->base;
        err = eccsi_calc_j(key, hem, sig, sigSz, y, mp, j);
        key->params.haveBase = 0;
    }

    /* Defense-in-depth: reject J = point at infinity before the final
     * comparison. Catches any future path that might reach this point
     * with a neutral-element result (e.g. s = 0 mod q for a non-zero
     * encoded s). */
    if (err == 0) {
        if (wc_ecc_point_is_at_infinity(j)) {
            err = ECC_INF_E;
        }
    }

    /* Step 6: Jx fitting, compare with r */
    if (err == 0) {
        jx = &key->tmp;
        err = eccsi_fit_to_octets(j->x, &params->order, key->ecc.dp->size, jx);
    }

    if (verified != NULL) {
        *verified = ((err == 0) && (mp_cmp(jx, r) == MP_EQ));
    }

    RESTORE_VECTOR_REGISTERS();

    return err;
}
#endif /* WOLFCRYPT_ECCSI_CLIENT */

#endif /* WOLFCRYPT_HAVE_ECCSI */