summaryrefslogtreecommitdiffhomepage
path: root/libtomcrypt/doc/crypt.tex
blob: df0b8483b0c353ec6538630d9e755f68e899f557 (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
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
\documentclass[synpaper]{book}
\usepackage{geometry}
\usepackage{hyperref}
\usepackage{makeidx}
\usepackage{amssymb}
\usepackage{color}
\usepackage{alltt}
\usepackage{graphicx}
\usepackage{layout}
\usepackage{fancyhdr}
\usepackage{float}
\def\union{\cup}
\def\intersect{\cap}
\def\getsrandom{\stackrel{\rm R}{\gets}}
\def\cross{\times}
\def\cat{\hspace{0.5em} \| \hspace{0.5em}}
\def\catn{$\|$}
\def\divides{\hspace{0.3em} | \hspace{0.3em}}
\def\nequiv{\not\equiv}
\def\approx{\raisebox{0.2ex}{\mbox{\small $\sim$}}}
\def\lcm{{\rm lcm}}
\def\gcd{{\rm gcd}}
\def\log{{\rm log}}
\def\ord{{\rm ord}}
\def\abs{{\mathit abs}}
\def\rep{{\mathit rep}}
\def\mod{{\mathit\ mod\ }}
\renewcommand{\pmod}[1]{\ ({\rm mod\ }{#1})}
\newcommand{\floor}[1]{\left\lfloor{#1}\right\rfloor}
\newcommand{\ceil}[1]{\left\lceil{#1}\right\rceil}
\def\Or{{\rm\ or\ }}
\def\And{{\rm\ and\ }}
\def\iff{\hspace{1em}\Longleftrightarrow\hspace{1em}}
\def\implies{\Rightarrow}
\def\Proof{\vspace{1ex}\noindent {\bf Proof:}\hspace{1em}}
\let\oldphi\phi
\def\phi{\varphi}
\def\Pr{{\rm Pr}}
\newcommand{\str}[1]{{\mathbf{#1}}}
\def\F{{\mathbb F}}
\def\N{{\mathbb N}}
\def\Z{{\mathbb Z}}
\def\R{{\mathbb R}}
\def\C{{\mathbb C}}
\def\Q{{\mathbb Q}}
\definecolor{DGray}{gray}{0.5}
\newcommand{\emailaddr}[1]{\mbox{$<${#1}$>$}}
\def\twiddle{\raisebox{0.3ex}{\mbox{\tiny $\sim$}}}
\def\gap{\vspace{0.5ex}}
\makeindex
\newcommand{\mysection}[1]    % Re-define the chaptering command to use
	{                   % THESE headers.
	\section{#1}
   \markboth{\textsf{www.libtom.net}}{\thesection ~ {#1}}
	}

\newcommand{\mystarsection}[1]    % Re-define the chaptering command to use
	{                   % THESE headers.
	\section*{#1}
   \markboth{\textsf{www.libtom.net}}{{#1}}
	}
\pagestyle{empty}
\begin{document}
\frontmatter
\pagestyle{empty}

~

\vspace{2in}

~

\begin{center}
\begin{Huge}LibTomCrypt\end{Huge}

~

\begin{large}Developer Manual\end{large}

~

\vspace{15mm}


\begin{tabular}{c}
LibTom Projects
\end{tabular}
\end{center}
\vfil
\newpage
This document is part of the LibTomCrypt package and is hereby released into the public domain.

~

Open Source.  Open Academia.  Open Minds.

~

\begin{flushright}
LibTom Projects
~

\& originally
~

Tom St Denis
~

Ottawa, Ontario
~

Canada
~
\vfil
\end{flushright}
\newpage

\tableofcontents
\listoffigures
\pagestyle{myheadings}
\mainmatter
\chapter{Introduction}
\mysection{What is the LibTomCrypt?}
LibTomCrypt is a portable ISO C cryptographic library meant to be a tool set for cryptographers who are
designing cryptosystems.  It supports symmetric ciphers, one-way hashes, pseudo-random number generators,
public key cryptography (via PKCS \#1 RSA, DH or ECCDH), and a plethora of support routines.

The library was designed such that new ciphers/hashes/PRNGs can be added at run-time and the existing API
(and helper API functions) are able to use the new designs automatically.  There exists self-check functions for each
block cipher and hash function to ensure that they compile and execute to the published design specifications.  The library
also performs extensive parameter error checking to prevent any number of run-time exploits or errors.

\mysection{Why did I write it?}
You may be wondering, \textit{Tom, why did you write a crypto library.  I already have one.}  Well the reason falls into
two categories:
\begin{enumerate}
    \item I am too lazy to figure out someone else's API.  I'd rather invent my own simpler API and use that.
    \item It was (still is) good coding practice.
\end{enumerate}

The idea is that I am not striving to replace OpenSSL or Crypto++ or Cryptlib or etc.  I'm trying to write my
{\bf own} crypto library and hopefully along the way others will appreciate the work.

With this library all core functions (ciphers, hashes, prngs, and bignum) have the same prototype definition.  They all load
and store data in a format independent of the platform.  This means if you encrypt with Blowfish on a PPC it should decrypt
on an x86 with zero problems.  The consistent API also means that if you learn how to use Blowfish with the library you
know how to use Safer+, RC6, or Serpent as well.  With all of the core functions there are central descriptor tables
that can be used to make a program automatically pick between ciphers, hashes and PRNGs at run-time.  That means your
application can support all ciphers/hashes/prngs/bignum without changing the source code.

Not only did I strive to make a consistent and simple API to work with but I also attempted to make the library
configurable in terms of its build options.  Out of the box the library will build with any modern version of GCC
without having to use configure scripts.  This means that the library will work with platforms where development
tools may be limited (e.g. no autoconf).

On top of making the build simple and the API approachable I've also attempted for a reasonably high level of
robustness and efficiency.  LibTomCrypt traps and returns a series of errors ranging from invalid
arguments to buffer overflows/overruns.  It is mostly thread safe and has been clocked on various platforms
with \textit{cycles per byte} timings that are comparable (and often favourable) to other libraries such as OpenSSL and
Crypto++.

\subsection{Modular}
The LibTomCrypt package has also been written to be very modular.  The block ciphers, one--way hashes,
pseudo--random number generators (PRNG), and bignum math routines are all used within the API through \textit{descriptor} tables which
are essentially structures with pointers to functions.  While you can still call particular functions
directly (\textit{e.g. sha256\_process()}) this descriptor interface allows the developer to customize their
usage of the library.

For example, consider a hardware platform with a specialized RNG device.  Obviously one would like to tap
that for the PRNG needs within the library (\textit{e.g. making a RSA key}).  All the developer has to do
is write a descriptor and the few support routines required for the device.  After that the rest of the
API can make use of it without change.  Similarly imagine a few years down the road when AES2
(\textit{or whatever they call it}) has been invented.  It can be added to the library and used within applications
with zero modifications to the end applications provided they are written properly.

This flexibility within the library means it can be used with any combination of primitive algorithms and
unlike libraries like OpenSSL is not tied to direct routines.  For instance, in OpenSSL there are CBC block
mode routines for every single cipher.  That means every time you add or remove a cipher from the library
you have to update the associated support code as well.  In LibTomCrypt the associated code (\textit{chaining modes in this case})
are not directly tied to the ciphers.  That is a new cipher can be added to the library by simply providing
the key setup, ECB decrypt and encrypt and test vector routines.  After that all five chaining mode routines
can make use of the cipher right away.

\mysection{License}

The project is hereby released as public domain.

\mysection{Patent Disclosure}

The author (Tom St Denis) is not a patent lawyer so this section is not to be treated as legal advice.  To the best
of the author's knowledge the only patent related issues within the library are the RC5 and RC6 symmetric block ciphers.
They can be removed from a build by simply commenting out the two appropriate lines in \textit{tomcrypt\_custom.h}.  The rest
of the ciphers and hashes are patent free or under patents that have since expired.

The RC2 and RC4 symmetric ciphers are not under patents but are under trademark regulations.  This means you can use
the ciphers you just can't advertise that you are doing so.

\mysection{Thanks}
I would like to give thanks to the following people (in no particular order) for helping me develop this project from
early on:
\begin{enumerate}
   \item Richard van de Laarschot
   \item Richard Heathfield
   \item Ajay K. Agrawal
   \item Brian Gladman
   \item Svante Seleborg
   \item Clay Culver
   \item Jason Klapste
   \item Dobes Vandermeer
   \item Daniel Richards
   \item Wayne Scott
   \item Andrew Tyler
   \item Sky Schulz
   \item Christopher Imes
\end{enumerate}

There have been quite a few other people as well.  Please check the change log to see who else has contributed from
time to time.

\chapter{The Application Programming Interface (API)}
\mysection{Introduction}
\index{CRYPT\_ERROR} \index{CRYPT\_OK}

In general the API is very simple to memorize and use.  Most of the functions return either {\bf void} or {\bf int}.  Functions
that return {\bf int} will return {\bf CRYPT\_OK} if the function was successful, or one of the many error codes
if it failed.  Certain functions that return int will return $-1$ to indicate an error.  These functions will be explicitly
commented upon.  When a function does return a CRYPT error code it can be translated into a string with

\index{error\_to\_string()}
\begin{verbatim}
const char *error_to_string(int err);
\end{verbatim}

An example of handling an error is:
\begin{small}
\begin{verbatim}
void somefunc(void)
{
   int err;

   /* call a cryptographic function */
   if ((err = some_crypto_function(...)) != CRYPT_OK) {
      printf("A crypto error occurred, %s\n", error_to_string(err));
      /* perform error handling */
   }
   /* continue on if no error occurred */
}
\end{verbatim}
\end{small}

There is no initialization routine for the library and for the most part the code is thread safe.  The only thread
related issue is if you use the same symmetric cipher, hash or public key state data in multiple threads.  Normally
that is not an issue.

To include the prototypes for \textit{LibTomCrypt.a} into your own program simply include \textit{tomcrypt.h} like so:
\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void) {
    return 0;
}
\end{verbatim}
\end{small}

The header file \textit{tomcrypt.h} also includes \textit{stdio.h}, \textit{string.h}, \textit{stdlib.h}, \textit{time.h} and \textit{ctype.h}.

\mysection{Macros}

There are a few helper macros to make the coding process a bit easier.  The first set are related to loading and storing
32/64-bit words in little/big endian format.  The macros are:

\index{STORE32L} \index{STORE64L} \index{LOAD32L} \index{LOAD64L} \index{STORE32H} \index{STORE64H} \index{LOAD32H} \index{LOAD64H} \index{BSWAP}
\newpage
\begin{figure}[hpbt]
\begin{small}
\begin{center}
\begin{tabular}{|c|c|c|}
     \hline STORE32L(x, y) & {\bf ulong32} x, {\bf unsigned char} *y & $x \to y[0 \ldots 3]$ \\
     \hline STORE64L(x, y) & {\bf ulong64} x, {\bf unsigned char} *y & $x \to y[0 \ldots 7]$ \\
     \hline LOAD32L(x, y) & {\bf ulong32} x, {\bf unsigned char} *y & $y[0 \ldots 3] \to x$ \\
     \hline LOAD64L(x, y) & {\bf ulong64} x, {\bf unsigned char} *y & $y[0 \ldots 7] \to x$ \\
     \hline STORE32H(x, y) & {\bf ulong32} x, {\bf unsigned char} *y & $x \to y[3 \ldots 0]$ \\
     \hline STORE64H(x, y) & {\bf ulong64} x, {\bf unsigned char} *y & $x \to y[7 \ldots 0]$ \\
     \hline LOAD32H(x, y) & {\bf ulong32} x, {\bf unsigned char} *y & $y[3 \ldots 0] \to x$ \\
     \hline LOAD64H(x, y) & {\bf ulong64} x, {\bf unsigned char} *y & $y[7 \ldots 0] \to x$ \\
     \hline BSWAP(x) & {\bf ulong32} x & Swap bytes \\
     \hline
\end{tabular}
\caption{Load And Store Macros}
\end{center}
\end{small}
\end{figure}

There are 32 and 64-bit cyclic rotations as well:
\index{ROL} \index{ROR} \index{ROL64} \index{ROR64} \index{ROLc} \index{RORc} \index{ROL64c} \index{ROR64c}
\begin{figure}[hpbt]
\begin{small}
\begin{center}
\begin{tabular}{|c|c|c|}
     \hline ROL(x, y) & {\bf ulong32} x, {\bf ulong32} y & $x << y, 0 \le y \le 31$ \\
     \hline ROLc(x, y) & {\bf ulong32} x, {\bf const ulong32} y & $x << y, 0 \le y \le 31$ \\
     \hline ROR(x, y) & {\bf ulong32} x, {\bf ulong32} y & $x >> y, 0 \le y \le 31$ \\
     \hline RORc(x, y) & {\bf ulong32} x, {\bf const ulong32} y & $x >> y, 0 \le y \le 31$ \\
     \hline && \\
     \hline ROL64(x, y) & {\bf ulong64} x, {\bf ulong64} y & $x << y, 0 \le y \le 63$ \\
     \hline ROL64c(x, y) & {\bf ulong64} x, {\bf const ulong64} y & $x << y, 0 \le y \le 63$ \\
     \hline ROR64(x, y) & {\bf ulong64} x, {\bf ulong64} y & $x >> y, 0 \le y \le 63$ \\
     \hline ROR64c(x, y) & {\bf ulong64} x, {\bf const ulong64} y & $x >> y, 0 \le y \le 63$ \\
     \hline
\end{tabular}
\caption{Rotate Macros}
\end{center}
\end{small}
\end{figure}

\mysection{Functions with Variable Length Output}
Certain functions such as (for example) \textit{rsa\_export()} give an output that is variable length.  To prevent buffer overflows you
must pass it the length of the buffer where the output will be stored.  For example:
\index{rsa\_export()} \index{error\_to\_string()} \index{variable length output}
\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void) {
    rsa_key key;
    unsigned char buffer[1024];
    unsigned long x;
    int err;

    /* ... Make up the RSA key somehow ... */

    /* lets export the key, set x to the size of the
     * output buffer */
    x = sizeof(buffer);
    if ((err = rsa_export(buffer, &x, PK_PUBLIC, &key)) != CRYPT_OK) {
       printf("Export error: %s\n", error_to_string(err));
       return -1;
    }

    /* if rsa_export() was successful then x will have
     * the size of the output */
    printf("RSA exported key takes %d bytes\n", x);

    /* ... do something with the buffer */

    return 0;
}
\end{verbatim}
\end{small}
In the above example if the size of the RSA public key was more than 1024 bytes this function would return an error code
indicating a buffer overflow would have occurred.  If the function succeeds, it stores the length of the output back into
\textit{x} so that the calling application will know how many bytes were used.

As of v1.13, most functions will update your length on failure to indicate the size required by the function.  Not all functions
support this so please check the source before you rely on it doing that.

\mysection{Functions that need a PRNG}
\index{Pseudo Random Number Generator} \index{PRNG}
Certain functions such as \textit{rsa\_make\_key()} require a Pseudo Random Number Generator (PRNG).  These functions do not setup
the PRNG themselves so it is the responsibility of the calling function to initialize the PRNG before calling them.

Certain PRNG algorithms do not require a \textit{prng\_state} argument (sprng for example).  The \textit{prng\_state} argument
may be passed as \textbf{NULL} in such situations.

\index{register\_prng()} \index{rsa\_make\_key()}
\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void) {
    rsa_key key;
    int     err;

    /* register the system RNG */
    register_prng(&sprng_desc)

    /* make a 1024-bit RSA key with the system RNG */
    if ((err = rsa_make_key(NULL, find_prng("sprng"), 1024/8, 65537, &key))
        != CRYPT_OK) {
       printf("make_key error: %s\n", error_to_string(err));
       return -1;
    }

    /* use the key ... */

    return 0;
}
\end{verbatim}
\end{small}

\mysection{Functions that use Arrays of Octets}
Most functions require inputs that are arrays of the data type \textit{unsigned char}.  Whether it is a symmetric key, IV
for a chaining mode or public key packet it is assumed that regardless of the actual size of \textit{unsigned char} only the
lower eight bits contain data.  For example, if you want to pass a 256 bit key to a symmetric ciphers setup routine, you
must pass in (a pointer to) an array of 32 \textit{unsigned char} variables.  Certain routines (such as SAFER+) take
special care to work properly on platforms where an \textit{unsigned char} is not eight bits.

For the purposes of this library, the term \textit{byte} will refer to an octet or eight bit word.  Typically an array of
type \textit{byte} will be synonymous with an array of type \textit{unsigned char.}

\chapter{Symmetric Block Ciphers}
\mysection{Core Functions}
LibTomCrypt provides several block ciphers with an ECB block mode interface.  It is important to first note that you
should never use the ECB modes directly to encrypt data.  Instead you should use the ECB functions to make a chaining mode,
or use one of the provided chaining modes.  All of the ciphers are written as ECB interfaces since it allows the rest of
the API to grow in a modular fashion.

\subsection{Key Scheduling}
All ciphers store their scheduled keys in a single data type called \textit{symmetric\_key}.  This allows all ciphers to
have the same prototype and store their keys as naturally as possible.  This also removes the need for dynamic memory
allocation, and allows you to allocate a fixed sized buffer for storing scheduled keys.  All ciphers must provide six visible
functions which are (given that XXX is the name of the cipher) the following:
\index{Cipher Setup}
\begin{verbatim}
int XXX_setup(const unsigned char *key,
                              int  keylen,
                              int  rounds,
                    symmetric_key *skey);
\end{verbatim}

The XXX\_setup() routine will setup the cipher to be used with a given number of rounds and a given key length (in bytes).
The number of rounds can be set to zero to use the default, which is generally a good idea.

If the function returns successfully the variable \textit{skey} will have a scheduled key stored in it.  It's important to note
that you should only used this scheduled key with the intended cipher.  For example, if you call \textit{blowfish\_setup()} do not
pass the scheduled key onto \textit{rc5\_ecb\_encrypt()}.  All built--in setup functions do not allocate memory off the heap so
when you are done with a key you can simply discard it (e.g. they can be on the stack).  However, to maintain proper coding
practices you should always call the respective XXX\_done() function.  This allows for quicker porting to applications with
externally supplied plugins.

\subsection{ECB Encryption and Decryption}
To encrypt or decrypt a block in ECB mode there are these two functions per cipher:
\index{Cipher Encrypt} \index{Cipher Decrypt}
\begin{verbatim}
int XXX_ecb_encrypt(const unsigned char *pt,
                          unsigned char *ct,
                          symmetric_key *skey);

int XXX_ecb_decrypt(const unsigned char *ct,
                          unsigned char *pt,
                          symmetric_key *skey);
\end{verbatim}
These two functions will encrypt or decrypt (respectively) a single block of text\footnote{The size of which depends on
which cipher you are using.}, storing the result in the \textit{ct} buffer (\textit{pt} resp.).  It is possible that the input and output buffer are
the same buffer.  For the encrypt function \textit{pt}\footnote{pt stands for plaintext.} is the input and
\textit{ct}\footnote{ct stands for ciphertext.} is the output.  For the decryption function it's the opposite.  They both
return \textbf{CRYPT\_OK} on success.  To test a particular cipher against test vectors\footnote{As published in their design papers.}
call the following self-test function.

\subsection{Self--Testing}
\index{Cipher Testing}
\begin{verbatim}
int XXX_test(void);
\end{verbatim}
This function will return {\bf CRYPT\_OK} if the cipher matches the test vectors from the design publication it is
based upon.

\subsection{Key Sizing}
For each cipher there is a function which will help find a desired key size.  It is specified as follows:
\index{Key Sizing}
\begin{verbatim}
int XXX_keysize(int *keysize);
\end{verbatim}
Essentially, it will round the input keysize in \textit{keysize} down to the next appropriate key size.  This function
will return {\bf CRYPT\_OK} if the key size specified is acceptable.  For example:
\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
   int keysize, err;

   /* now given a 20 byte key what keysize does Twofish want to use? */
   keysize = 20;
   if ((err = twofish_keysize(&keysize)) != CRYPT_OK) {
      printf("Error getting key size: %s\n", error_to_string(err));
      return -1;
   }
   printf("Twofish suggested a key size of %d\n", keysize);
   return 0;
}
\end{verbatim}
\end{small}
This should indicate a keysize of sixteen bytes is suggested by storing 16 in \textit{keysize.}

\subsection{Cipher Termination}
When you are finished with a cipher you can de--initialize it with the done function.
\begin{verbatim}
void XXX_done(symmetric_key *skey);
\end{verbatim}
For the software based ciphers within LibTomCrypt, these functions will not do anything.  However, user supplied
cipher descriptors may require to be called for resource management purposes.  To be compliant, all functions which call a cipher
setup function must also call the respective cipher done function when finished.

\subsection{Simple Encryption Demonstration}
An example snippet that encodes a block with Blowfish in ECB mode.

\index{blowfish\_setup()} \index{blowfish\_ecb\_encrypt()} \index{blowfish\_ecb\_decrypt()} \index{blowfish\_done()}
\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
   unsigned char pt[8], ct[8], key[8];
   symmetric_key skey;
   int err;

   /* ... key is loaded appropriately in key ... */
   /* ... load a block of plaintext in pt ... */

   /* schedule the key */
   if ((err = blowfish_setup(key, /* the key we will use */
                               8, /* key is 8 bytes (64-bits) long */
                               0, /* 0 == use default # of rounds */
                           &skey) /* where to put the scheduled key */
       ) != CRYPT_OK) {
      printf("Setup error: %s\n", error_to_string(err));
      return -1;
   }

   /* encrypt the block */
   blowfish_ecb_encrypt(pt,       /* encrypt this 8-byte array */
                        ct,       /* store encrypted data here */
                        &skey);   /* our previously scheduled key */

   /* now ct holds the encrypted version of pt */

   /* decrypt the block */
   blowfish_ecb_decrypt(ct,       /* decrypt this 8-byte array */
                        pt,       /* store decrypted data here */
                        &skey);   /* our previously scheduled key */

   /* now we have decrypted ct to the original plaintext in pt */

   /* Terminate the cipher context */
   blowfish_done(&skey);

   return 0;
}
\end{verbatim}
\end{small}

\mysection{Key Sizes and Number of Rounds}
\index{Symmetric Keys}
As a general rule of thumb, do not use symmetric keys under 80 bits if you can help it.  Only a few of the ciphers support smaller
keys (mainly for test vectors anyways).  Ideally, your application should be making at least 256 bit keys.  This is not
because you are to be paranoid.  It is because if your PRNG has a bias of any sort the more bits the better.  For
example, if you have $\mbox{Pr}\left[X = 1\right] = {1 \over 2} \pm \gamma$ where $\vert \gamma \vert > 0$ then the
total amount of entropy in N bits is $N \cdot -log_2\left ({1 \over 2} + \vert \gamma \vert \right)$.  So if $\gamma$
were $0.25$ (a severe bias) a 256-bit string would have about 106 bits of entropy whereas a 128-bit string would have
only 53 bits of entropy.

The number of rounds of most ciphers is not an option you can change.  Only RC5 allows you to change the number of
rounds.  By passing zero as the number of rounds all ciphers will use their default number of rounds.  Generally the
ciphers are configured such that the default number of rounds provide adequate security for the given block and key
size.

\mysection{The Cipher Descriptors}
\index{Cipher Descriptor}
To facilitate automatic routines an array of cipher descriptors is provided in the array \textit{cipher\_descriptor}.  An element
of this array has the following (partial) format (See Section \ref{sec:cipherdesc}):

\begin{small}
\begin{verbatim}
struct _cipher_descriptor {
   /** name of cipher */
   char *name;

   /** internal ID */
   unsigned char ID;

   /** min keysize (octets) */
   int  min_key_length,

   /** max keysize (octets) */
        max_key_length,

   /** block size (octets) */
        block_length,

   /** default number of rounds */
        default_rounds;
...<snip>...
};
\end{verbatim}
\end{small}

Where \textit{name} is the lower case ASCII version of the name.  The fields \textit{min\_key\_length} and \textit{max\_key\_length}
are the minimum and maximum key sizes in bytes.  The \textit{block\_length} member is the block size of the cipher
in bytes.  As a good rule of thumb it is assumed that the cipher supports
the min and max key lengths but not always everything in between.  The \textit{default\_rounds} field is the default number
of rounds that will be used.

For a plugin to be compliant it must provide at least each function listed before the accelerators begin.  Accelerators are optional,
and if missing will be emulated in software.

The remaining fields are all pointers to the core functions for each cipher.  The end of the cipher\_descriptor array is
marked when \textit{name} equals {\bf NULL}.

As of this release the current cipher\_descriptors elements are the following:
\vfil
\index{Cipher descriptor table}
\index{blowfish\_desc} \index{xtea\_desc} \index{rc2\_desc} \index{rc5\_desc} \index{rc6\_desc} \index{saferp\_desc} \index{aes\_desc} \index{twofish\_desc}
\index{des\_desc} \index{des3\_desc} \index{noekeon\_desc} \index{skipjack\_desc} \index{anubis\_desc} \index{khazad\_desc} \index{kseed\_desc} \index{kasumi\_desc} \index{camellia\_desc} \index{aes\_enc\_desc}
\begin{figure}[hpbt]
\begin{small}
\begin{center}
\begin{tabular}{|c|c|c|c|c|c|}
     \hline \textbf{Name} & \textbf{Descriptor Name} & \textbf{Block Size} & \textbf{Key Range} & \textbf{Rounds} \\
     \hline Blowfish & blowfish\_desc & 8 & 8 $\ldots$ 56 & 16 \\
     \hline X-Tea & xtea\_desc & 8 & 16 & 32 \\
     \hline RC2 & rc2\_desc & 8 & 5 $\ldots$ 128 & 16 \\
     \hline RC5-32/12/b & rc5\_desc & 8 & 8 $\ldots$ 128 & 12 $\ldots$ 24 \\
     \hline RC6-32/20/b & rc6\_desc & 16 & 8 $\ldots$ 128 & 20 \\
     \hline SAFER+ & saferp\_desc &16 & 16, 24, 32 & 8, 12, 16 \\
     \hline AES & aes\_desc & 16 & 16, 24, 32 & 10, 12, 14 \\
                & aes\_enc\_desc & 16 & 16, 24, 32 & 10, 12, 14 \\
     \hline Twofish & twofish\_desc & 16 & 16, 24, 32 & 16 \\
     \hline DES & des\_desc & 8 & 8 & 16 \\
     \hline 3DES (EDE mode) & des3\_desc & 8 & 16, 24 & 16 \\
     \hline CAST5 (CAST-128) & cast5\_desc & 8 & 5 $\ldots$ 16 & 12, 16 \\
     \hline Noekeon & noekeon\_desc & 16 & 16 & 16 \\
     \hline Skipjack & skipjack\_desc & 8 & 10 & 32 \\
     \hline Anubis & anubis\_desc & 16 & 16 $\ldots$ 40 & 12 $\ldots$ 18 \\
     \hline Khazad & khazad\_desc & 8 & 16 & 8 \\
     \hline SEED   & kseed\_desc & 16 & 16 & 16 \\
     \hline KASUMI & kasumi\_desc & 8 & 16 & 8 \\
     \hline Camellia & camellia\_desc & 16 & 16, 24, 32 & 18, 24 \\
     \hline
\end{tabular}
\end{center}
\end{small}
\caption{Built--In Software Ciphers}
\end{figure}

\subsection{Notes}
\begin{small}
\begin{enumerate}
\item
For AES, (also known as Rijndael) there are four descriptors which complicate issues a little.  The descriptors
rijndael\_desc and rijndael\_enc\_desc provide the cipher named \textit{rijndael}.  The descriptors aes\_desc and
aes\_enc\_desc provide the cipher name \textit{aes}.  Functionally both \textit{rijndael} and \textit{aes} are the same cipher.  The
only difference is when you call find\_cipher() you have to pass the correct name.  The cipher descriptors with \textit{enc}
in the middle (e.g. rijndael\_enc\_desc) are related to an implementation of Rijndael with only the encryption routine
and tables.  The decryption and self--test function pointers of both \textit{encrypt only} descriptors are set to \textbf{NULL} and
should not be called.

The \textit{encrypt only} descriptors are useful for applications that only use the encryption function of the cipher.  Algorithms such
as EAX, PMAC and OMAC only require the encryption function.  So far this \textit{encrypt only} functionality has only been implemented for
Rijndael as it makes the most sense for this cipher.

\item
Note that for \textit{DES} and \textit{3DES} they use 8 and 24 byte keys but only 7 and 21 [respectively] bytes of the keys are in
fact used for the purposes of encryption.  My suggestion is just to use random 8/24 byte keys instead of trying to make a 8/24
byte string from the real 7/21 byte key.

For \textit{3DES} exists a two-key mode, that can be initialized by calling the setup function with a \textit{keylen} of 16. This results in the re-usage of key \textit{K1} as key \textit{K3}. This mode has been specified as \textit{Keying Option 2} in FIPS 46-3.

\item
Note that \textit{Twofish} has additional configuration options (Figure \ref{fig:twofishopts}) that take place at build time.  These options are found in
the file \textit{tomcrypt\_cfg.h}.  The first option is \textit{TWOFISH\_SMALL} which when defined will force the Twofish code
to not pre-compute the Twofish \textit{$g(X)$} function as a set of four $8 \times 32$ s-boxes.  This means that a scheduled
key will require less ram but the resulting cipher will be slower.  The second option is \textit{TWOFISH\_TABLES} which when
defined will force the Twofish code to use pre-computed tables for the two s-boxes $q_0, q_1$ as well as the multiplication
by the polynomials 5B and EF used in the MDS multiplication.  As a result the code is faster and slightly larger.  The
speed increase is useful when \textit{TWOFISH\_SMALL} is defined since the s-boxes and MDS multiply form the heart of the
Twofish round function.

\begin{figure}[hpbt]
\index{Twofish build options} \index{TWOFISH\_SMALL} \index{TWOFISH\_TABLES}
\begin{small}
\begin{center}
\begin{tabular}{|l|l|l|}
\hline \textbf{TWOFISH\_SMALL} & \textbf{TWOFISH\_TABLES} & \textbf{Speed and Memory (per key)} \\
\hline undefined & undefined & Very fast, 4.2KB of ram. \\
\hline undefined & defined & Faster key setup, larger code. \\
\hline defined & undefined & Very slow, 0.2KB of ram. \\
\hline defined & defined & Faster, 0.2KB of ram, larger code. \\
\hline
\end{tabular}
\end{center}
\end{small}
\caption{Twofish Build Options}
\label{fig:twofishopts}
\end{figure}

\item
As of v1.18.0 of the library RC2 got an extended setup function (which didn't fit in the regular API):

\index{rc2\_setup\_ex()}
\begin{verbatim}
int rc2_setup_ex(const unsigned char *key,
                                 int keylen,
                                 int bits,
                                 int num_rounds,
                       symmetric_key *skey);
\end{verbatim}

This setup function also allows to configure the effective key length in bits of the RC2 cipher as in its original specification.

\end{enumerate}
\end{small}


To work with the cipher\_descriptor array there is a function:
\index{find\_cipher()}
\begin{verbatim}
int find_cipher(char *name)
\end{verbatim}
Which will search for a given name in the array.  It returns $-1$ if the cipher is not found, otherwise it returns
the location in the array where the cipher was found.  For example, to indirectly setup Blowfish you can also use:
\begin{small}
\index{register\_cipher()} \index{find\_cipher()} \index{error\_to\_string()}
\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
   unsigned char key[8];
   symmetric_key skey;
   int err;

   /* you must register a cipher before you use it */
   if (register_cipher(&blowfish_desc)) == -1) {
      printf("Unable to register Blowfish cipher.");
      return -1;
   }

   /* generic call to function (assuming the key
    * in key[] was already setup) */
   if ((err =
        cipher_descriptor[find_cipher("blowfish")].
          setup(key, 8, 0, &skey)) != CRYPT_OK) {
      printf("Error setting up Blowfish: %s\n", error_to_string(err));
      return -1;
   }

   /* ... use cipher ... */
}
\end{verbatim}
\end{small}

A good safety would be to check the return value of \textit{find\_cipher()} before accessing the desired function.  In order
to use a cipher with the descriptor table you must register it first using:
\index{register\_cipher()}
\begin{verbatim}
int register_cipher(const struct _cipher_descriptor *cipher);
\end{verbatim}
Which accepts a pointer to a descriptor and returns the index into the global descriptor table.  If an error occurs such
as there is no more room (it can have 32 ciphers at most) it will return {\bf{-1}}.  If you try to add the same cipher more
than once it will just return the index of the first copy.  To remove a cipher call:
\index{unregister\_cipher()}
\begin{verbatim}
int unregister_cipher(const struct _cipher_descriptor *cipher);
\end{verbatim}
Which returns {\bf CRYPT\_OK} if it removes the cipher, otherwise it returns {\bf CRYPT\_ERROR}.
\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
   int err;

   /* register the cipher */
   if (register_cipher(&rijndael_desc) == -1) {
      printf("Error registering Rijndael\n");
      return -1;
   }

   /* use Rijndael */

   /* remove it */
   if ((err = unregister_cipher(&rijndael_desc)) != CRYPT_OK) {
      printf("Error removing Rijndael: %s\n", error_to_string(err));
      return -1;
   }

   return 0;
}
\end{verbatim}
\end{small}
This snippet is a small program that registers Rijndael.

\mysection{Symmetric Modes of Operations}
\subsection{Background}
A typical symmetric block cipher can be used in chaining modes to effectively encrypt messages larger than the block
size of the cipher.  Given a key $k$, a plaintext $P$ and a cipher $E$ we shall denote the encryption of the block
$P$ under the key $k$ as $E_k(P)$.  In some modes there exists an initialization vector denoted as $C_{-1}$.

\subsubsection{ECB Mode}
\index{ECB mode}
ECB or Electronic Codebook Mode is the simplest method to use.  It is given as:
\begin{equation}
C_i = E_k(P_i)
\end{equation}
This mode is very weak since it allows people to swap blocks and perform replay attacks if the same key is used more
than once.

\subsubsection{CBC Mode}
\index{CBC mode}
CBC or Cipher Block Chaining mode is a simple mode designed to prevent trivial forms of replay and swap attacks on ciphers.
It is given as:
\begin{equation}
C_i = E_k(P_i \oplus C_{i - 1})
\end{equation}
It is important that the initialization vector be unique and preferably random for each message encrypted under the same key.

\subsubsection{CTR Mode}
\index{CTR mode}
CTR or Counter Mode is a mode which only uses the encryption function of the cipher.  Given a initialization vector which is
treated as a large binary counter the CTR mode is given as:
\begin{eqnarray}
C_{-1} = C_{-1} + 1\mbox{ }(\mbox{mod }2^W) \nonumber \\
C_i = P_i \oplus E_k(C_{-1})
\end{eqnarray}
Where $W$ is the size of a block in bits (e.g. 64 for Blowfish).  As long as the initialization vector is random for each message
encrypted under the same key replay and swap attacks are infeasible.  CTR mode may look simple but it is as secure
as the block cipher is under a chosen plaintext attack (provided the initialization vector is unique).

\subsubsection{CFB Mode}
\index{CFB mode}
CFB or Ciphertext Feedback Mode is a mode akin to CBC.  It is given as:
\begin{eqnarray}
C_i = P_i \oplus C_{-1} \nonumber \\
C_{-1} = E_k(C_i)
\end{eqnarray}
Note that in this library the output feedback width is equal to the size of the block cipher.  That is this mode is used
to encrypt whole blocks at a time.  However, the library will buffer data allowing the user to encrypt or decrypt partial
blocks without a delay.  When this mode is first setup it will initially encrypt the initialization vector as required.

\subsubsection{OFB Mode}
\index{OFB mode}
OFB or Output Feedback Mode is a mode akin to CBC as well.  It is given as:
\begin{eqnarray}
C_{-1} = E_k(C_{-1}) \nonumber \\
C_i = P_i \oplus C_{-1}
\end{eqnarray}
Like the CFB mode the output width in CFB mode is the same as the width of the block cipher.  OFB mode will also
buffer the output which will allow you to encrypt or decrypt partial blocks without delay.

\subsection{Choice of Mode}
My personal preference is for the CTR mode since it has several key benefits:
\begin{enumerate}
   \item No short cycles which is possible in the OFB and CFB modes.
   \item Provably as secure as the block cipher being used under a chosen plaintext attack.
   \item Technically does not require the decryption routine of the cipher.
   \item Allows random access to the plaintext.
   \item Allows the encryption of block sizes that are not equal to the size of the block cipher.
\end{enumerate}
The CTR, CFB and OFB routines provided allow you to encrypt block sizes that differ from the ciphers block size.  They
accomplish this by buffering the data required to complete a block.  This allows you to encrypt or decrypt any size
block of memory with either of the three modes.

The ECB and CBC modes process blocks of the same size as the cipher at a time.  Therefore, they are less flexible than the
other modes.

\subsection{Ciphertext Stealing}
\index{Ciphertext stealing}
Ciphertext stealing is a method of dealing with messages in CBC mode which are not a multiple of the block length.  This is accomplished
by encrypting the last ciphertext block in ECB mode, and XOR'ing the output against the last partial block of plaintext.  LibTomCrypt does not
support this mode directly but it is fairly easy to emulate with a call to the cipher's ecb\_encrypt() callback function.

The more sane way to deal with partial blocks is to pad them with zeroes, and then use CBC normally.

\subsection{Initialization}
\index{CBC Mode} \index{CTR Mode}
\index{OFB Mode} \index{CFB Mode}
The library provides simple support routines for handling CBC, CTR, CFB, OFB and ECB encoded messages.  Assuming the mode
you want is XXX there is a structure called \textit{symmetric\_XXX} that will contain the information required to
use that mode.  They have identical setup routines (except CTR and ECB mode):
\index{ecb\_start()} \index{cfb\_start()} \index{cbc\_start()} \index{ofb\_start()} \index{ctr\_start()}
\begin{verbatim}
int XXX_start(                int  cipher,
              const unsigned char *IV,
              const unsigned char *key,
                              int  keylen,
                              int  num_rounds,
                    symmetric_XXX *XXX);

int ctr_start(                int  cipher,
              const unsigned char *IV,
              const unsigned char *key,
                              int  keylen,
                              int  num_rounds,
                              int  ctr_mode,
                    symmetric_CTR *ctr);

int ecb_start(                int  cipher,
              const unsigned char *key,
                              int  keylen,
                              int  num_rounds,
                    symmetric_ECB *ecb);
\end{verbatim}

In each case, \textit{cipher} is the index into the cipher\_descriptor array of the cipher you want to use.  The \textit{IV} value is
the initialization vector to be used with the cipher.  You must fill the IV yourself and it is assumed they are the same
length as the block size\footnote{In other words the size of a block of plaintext for the cipher, e.g. 8 for DES, 16 for AES, etc.}
of the cipher you choose.  It is important that the IV  be random for each unique message you want to encrypt.  The
parameters \textit{key}, \textit{keylen} and \textit{num\_rounds} are the same as in the XXX\_setup() function call.  The final parameter
is a pointer to the structure you want to hold the information for the mode of operation.

The routines return {\bf CRYPT\_OK} if the cipher initialized correctly, otherwise, they return an error code.

\subsubsection{CTR Mode}
In the case of CTR mode there is an additional parameter \textit{ctr\_mode} which specifies the mode that the counter is to be used in.
If \textbf{CTR\_COUNTER\_ LITTLE\_ENDIAN} was specified then the counter will be treated as a little endian value.  Otherwise, if
\textbf{CTR\_COUNTER\_BIG\_ENDIAN} was specified the counter will be treated as a big endian value.  As of v1.15 the RFC 3686 style of
increment then encrypt is also supported.  By OR'ing \textbf{LTC\_CTR\_RFC3686} with the CTR \textit{mode} value, ctr\_start() will increment
the counter before encrypting it for the first time.

As of V1.17, the library supports variable length counters for CTR mode.  The (optional) counter length is specified by OR'ing the octet
length of the counter against the \textit{ctr\_mode} parameter.  The default, zero, indicates that a full block length counter will be used.  This also
ensures backwards compatibility with software that uses older versions of the library.

\begin{small}
\begin{verbatim}
symmetric_CTR ctr;
int           err;
unsigned char IV[16], key[16];

/* use a 32-bit little endian counter */
if ((err = ctr_start(find_cipher("aes"),
                     IV, key, 16, 0,
                     CTR_COUNTER_LITTLE_ENDIAN | 4,
                     &ctr)) != CRYPT_OK) {
   handle_error(err);
}
\end{verbatim}
\end{small}

Changing the counter size has little (really no) effect on the performance of the CTR chaining mode.  It is provided for compatibility
with other software (and hardware) which have smaller fixed sized counters.

\subsection{Encryption and Decryption}
To actually encrypt or decrypt the following routines are provided:
\index{ecb\_encrypt()} \index{ecb\_decrypt()} \index{cfb\_encrypt()} \index{cfb\_decrypt()}
\index{cbc\_encrypt()} \index{cbc\_decrypt()} \index{ofb\_encrypt()} \index{ofb\_decrypt()} \index{ctr\_encrypt()} \index{ctr\_decrypt()}
\begin{verbatim}
int XXX_encrypt(const unsigned char *pt,
                      unsigned char *ct,
                      unsigned long  len,
                      symmetric_YYY *YYY);

int XXX_decrypt(const unsigned char *ct,
                      unsigned char *pt,
                      unsigned long  len,
                      symmetric_YYY *YYY);
\end{verbatim}
Where \textit{XXX} is one of $\lbrace ecb, cbc, ctr, cfb, ofb \rbrace$.

In all cases, \textit{len} is the size of the buffer (as number of octets) to encrypt or decrypt.  The CTR, OFB and CFB modes are order sensitive but not
chunk sensitive.  That is you can encrypt \textit{ABCDEF} in three calls like \textit{AB}, \textit{CD}, \textit{EF} or two like \textit{ABCDE} and \textit{F}
and end up with the same ciphertext.  However, encrypting \textit{ABC} and \textit{DABC} will result in different ciphertexts.  All
five of the modes will return {\bf CRYPT\_OK} on success from the encrypt or decrypt functions.

In the ECB and CBC cases, \textit{len} must be a multiple of the ciphers block size.  In the CBC case, you must manually pad the end of your message (either with
zeroes or with whatever your protocol requires).

To decrypt in either mode, perform the setup like before (recall you have to fetch the IV value you used), and use the decrypt routine on all of the blocks.

\subsection{IV Manipulation}
To change or read the IV of a previously initialized chaining mode use the following two functions.
\index{cbc\_setiv()} \index{cbc\_getiv()} \index{ofb\_setiv()} \index{ofb\_getiv()} \index{cfb\_setiv()} \index{cfb\_getiv()}
\index{ctr\_setiv()} \index{ctr\_getiv()}
\begin{verbatim}
int XXX_getiv(unsigned char *IV,
              unsigned long *len,
              symmetric_XXX *XXX);

int XXX_setiv(const unsigned char *IV,
                    unsigned long  len,
                    symmetric_XXX *XXX);
\end{verbatim}

The XXX\_getiv() functions will read the IV out of the chaining mode and store it into \textit{IV} along with the length of the IV
stored in \textit{len}.  The XXX\_setiv will initialize the chaining mode state as if the original IV were the new IV specified.  The length
of the IV passed in must be the size of the ciphers block size.

The XXX\_setiv() functions are handy if you wish to change the IV without re--keying the cipher.

What the \textit{setiv} function will do depends on the mode being changed.  In CBC mode, the new IV replaces the existing IV as if it
were the last ciphertext block.  In CFB mode, the IV is encrypted as if it were the prior encrypted pad.  In CTR mode, the IV is encrypted without
first incrementing it (regardless of the LTC\_RFC\_3686 flag presence).  In F8 mode, the IV is encrypted and becomes the new pad.  It does not change
the salted IV, and is only meant to allow seeking within a session.  In LRW, it changes the tweak, forcing a computation of the tweak pad, allowing for
seeking within the session.  In OFB mode, the IV is encrypted and becomes the new pad.

\subsection{Stream Termination}
To terminate an open stream call the done function.

\index{ecb\_done()} \index{cbc\_done()}\index{cfb\_done()}\index{ofb\_done()} \index{ctr\_done()}
\begin{verbatim}
int XXX_done(symmetric_XXX *XXX);
\end{verbatim}

This will terminate the stream (by terminating the cipher) and return \textbf{CRYPT\_OK} if successful.

\newpage
\subsection{Examples}
\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
   unsigned char key[16], IV[16], buffer[512];
   symmetric_CTR ctr;
   int x, err;

   /* register twofish first */
   if (register_cipher(&twofish_desc) == -1) {
      printf("Error registering cipher.\n");
      return -1;
   }

   /* somehow fill out key and IV */

   /* start up CTR mode */
   if ((err = ctr_start(
        find_cipher("twofish"), /* index of desired cipher */
                            IV, /* the initialization vector */
                           key, /* the secret key */
                            16, /* length of secret key (16 bytes) */
                             0, /* 0 == default # of rounds */
     CTR_COUNTER_LITTLE_ENDIAN, /* Little endian counter */
                         &ctr)  /* where to store the CTR state */
      ) != CRYPT_OK) {
      printf("ctr_start error: %s\n", error_to_string(err));
      return -1;
   }

   /* somehow fill buffer than encrypt it */
   if ((err = ctr_encrypt(        buffer, /* plaintext */
                                  buffer, /* ciphertext */
                          sizeof(buffer), /* length of plaintext pt */
                                   &ctr)  /* CTR state */
      ) != CRYPT_OK) {
      printf("ctr_encrypt error: %s\n", error_to_string(err));
      return -1;
   }

   /* make use of ciphertext... */

   /* now we want to decrypt so let's use ctr_setiv */
   if ((err = ctr_setiv(  IV, /* the initial IV we gave to ctr_start */
                          16, /* the IV is 16 bytes long */
                        &ctr) /* the ctr state we wish to modify */
       ) != CRYPT_OK) {
      printf("ctr_setiv error: %s\n", error_to_string(err));
      return -1;
   }

   if ((err = ctr_decrypt(        buffer, /* ciphertext */
                                  buffer, /* plaintext */
                          sizeof(buffer), /* length of plaintext */
                                   &ctr)  /* CTR state */
      ) != CRYPT_OK) {
      printf("ctr_decrypt error: %s\n", error_to_string(err));
      return -1;
   }

   /* terminate the stream */
   if ((err = ctr_done(&ctr)) != CRYPT_OK) {
      printf("ctr_done error: %s\n", error_to_string(err));
      return -1;
   }

   /* clear up and return */
   zeromem(key, sizeof(key));
   zeromem(&ctr, sizeof(ctr));

   return 0;
}
\end{verbatim}
\end{small}

\subsection{LRW Mode}
LRW mode is a cipher mode which is meant for indexed encryption like used to handle storage media.  It is meant to have efficient seeking and overcome the
security problems of ECB mode while not increasing the storage requirements.  It is used much like any other chaining mode except with two key differences.

The key is specified as two strings the first key $K_1$ is the (normally AES) key and can be any length (typically 16, 24 or 32 octets long).  The second key
$K_2$ is the \textit{tweak} key and is always 16 octets long.  The tweak value is \textbf{NOT} a nonce or IV value it must be random and secret.

To initialize LRW mode use:

\index{lrw\_start()}
\begin{verbatim}
int lrw_start(                int  cipher,
              const unsigned char *IV,
              const unsigned char *key,
                              int  keylen,
              const unsigned char *tweak,
                              int  num_rounds,
                    symmetric_LRW *lrw);
\end{verbatim}

This will initialize the LRW context with the given (16 octet) \textit{IV}, cipher $K_1$ \textit{key} of length \textit{keylen} octets and the (16 octet) $K_2$ \textit{tweak}.
While LRW was specified to be used only with AES, LibTomCrypt will allow any 128--bit block cipher to be specified as indexed by \textit{cipher}.  The
number of rounds for the block cipher \textit{num\_rounds} can be 0 to use the default number of rounds for the given cipher.

To process data use the following functions:

\index{lrw\_encrypt()} \index{lrw\_decrypt()}
\begin{verbatim}
int lrw_encrypt(const unsigned char *pt,
                      unsigned char *ct,
                      unsigned long  len,
                      symmetric_LRW *lrw);

int lrw_decrypt(const unsigned char *ct,
                      unsigned char *pt,
                      unsigned long  len,
                      symmetric_LRW *lrw);
\end{verbatim}

These will encrypt (or decrypt) the plaintext to the ciphertext buffer (or vice versa).  The length is specified by \textit{len} in octets but must be a multiple
of 16.  The LRW code uses a fast tweak update such that consecutive blocks are encrypted faster than if random seeking where used.

To manipulate the IV use the following functions:

\index{lrw\_getiv()} \index{lrw\_setiv()}
\begin{verbatim}
int lrw_getiv(unsigned char *IV,
              unsigned long *len,
              symmetric_LRW *lrw);

int lrw_setiv(const unsigned char *IV,
                    unsigned long  len,
                    symmetric_LRW *lrw);
\end{verbatim}
These will get or set the 16--octet IV.  Note that setting the IV is the same as \textit{seeking} and unlike other modes is not a free operation.  It requires
updating the entire tweak which is slower than sequential use.  Avoid seeking excessively in performance constrained code.

To terminate the LRW state use the following:

\index{lrw\_done()}
\begin{verbatim}
int lrw_done(symmetric_LRW *lrw);
\end{verbatim}

\subsection{XTS Mode}
As of v1.17, LibTomCrypt supports XTS mode with code donated by Elliptic Semiconductor Inc.\footnote{www.ellipticsemi.com}.
XTS is a chaining mode for 128--bit block ciphers, recommended by IEEE (P1619)
for disk encryption.  It is meant to be an encryption mode with random access to the message data without compromising privacy.  It requires two private keys (of equal
length) to perform the encryption process.  Each encryption invocation includes a sector number or unique identifier specified as a 128--bit string.

To initialize XTS mode use the following function call:

\index{xts\_start()}
\begin{verbatim}
int xts_start(                int  cipher,
              const unsigned char *key1,
              const unsigned char *key2,
                    unsigned long  keylen,
                              int  num_rounds,
                    symmetric_xts *xts)
\end{verbatim}
This will start the XTS mode with the two keys pointed to by \textit{key1} and \textit{key2} of length \textit{keylen} octets each.

To encrypt or decrypt a sector use the following calls:

\index{xts\_encrypt()} \index{xts\_decrypt()}
\begin{verbatim}
int xts_encrypt(
   const unsigned char *pt, unsigned long ptlen,
         unsigned char *ct,
   const unsigned char *tweak,
         symmetric_xts *xts);

int xts_decrypt(
   const unsigned char *ct, unsigned long ptlen,
         unsigned char *pt,
   const unsigned char *tweak,
         symmetric_xts *xts);
\end{verbatim}
The first will encrypt the plaintext pointed to by \textit{pt} of length \textit{ptlen} octets, and store the ciphertext in the array pointed to by
\textit{ct}.  It uses the 128--bit tweak pointed to by \textit{tweak} to encrypt the block.  The decrypt function performs the opposite operation.  Both
functions support ciphertext stealing (blocks that are not multiples of 16 bytes).

The P1619 specification states the tweak for sector number shall be represented as a 128--bit little endian string.

To terminate the XTS state call the following function:

\index{xts\_done()}
\begin{verbatim}
void xts_done(symmetric_xts *xts);
\end{verbatim}


\subsection{F8 Mode}
\index{F8 Mode}
The F8 Chaining mode (see RFC 3711 for instance) is yet another chaining mode for block ciphers.  It behaves much like CTR mode in that it XORs a keystream
against the plaintext to encrypt.  F8 mode comes with the additional twist that the counter value is secret, encrypted by a \textit{salt key}.  We
initialize F8 mode with the following function call:

\index{f8\_start()}
\begin{verbatim}
int f8_start(                int  cipher,
             const unsigned char *IV,
             const unsigned char *key,
                             int  keylen,
             const unsigned char *salt_key,
                             int  skeylen,
                             int  num_rounds,
                    symmetric_F8 *f8);
\end{verbatim}
This will start the F8 mode state using \textit{key} as the secret key, \textit{IV} as the counter.  It uses the \textit{salt\_key} as IV encryption key
(\textit{m} in the RFC 3711).  The salt\_key can be shorter than the secret key but it should not be longer.

To encrypt or decrypt data we use the following two functions:

\index{f8\_encrypt()} \index{f8\_decrypt()}
\begin{verbatim}
int f8_encrypt(const unsigned char *pt,
                     unsigned char *ct,
                     unsigned long  len,
                      symmetric_F8 *f8);

int f8_decrypt(const unsigned char *ct,
                     unsigned char *pt,
                     unsigned long  len,
                      symmetric_F8 *f8);
\end{verbatim}
These will encrypt or decrypt a variable length array of bytes using the F8 mode state specified.  The length is specified in bytes and does not have to be a multiple
of the ciphers block size.

To change or retrieve the current counter IV value use the following functions:
\index{f8\_getiv()} \index{f8\_setiv()}
\begin{verbatim}
int f8_getiv(unsigned char *IV,
             unsigned long *len,
              symmetric_F8 *f8);

int f8_setiv(const unsigned char *IV,
                   unsigned long  len,
                    symmetric_F8 *f8);
\end{verbatim}
These work with the current IV value only and not the encrypted IV value specified during the call to f8\_start().  The purpose of these two functions is to be
able to seek within a current session only.  If you want to change the session IV you will have to call f8\_done() and then start a new state with
f8\_start().

To terminate an F8 state call the following function:

\index{f8\_done()}
\begin{verbatim}
int f8_done(symmetric_F8 *f8);
\end{verbatim}

\chapter{Stream Ciphers}

Stream ciphers are symmetric key ciphers which operate on a stream of bytes (in theory on a stream of bits
however LibTomCrypt's implementation works with bytes).

The API for all stream ciphers operates in mode: \textit{setup} -- \textit{crypt} -- \textit{crypt} -- ... -- \textit{done}.
Please note that both encryption and decryption are implemented via \textit{crypt}.

Another useful feature of the stream ciphers API is generation of a random stream of bytes which works like:
\textit{setup} -- \textit{keystream} -- \textit{keystream} -- ... -- \textit{done}. The random stream generation is
implemented like encryption of a stream of \textit{0x00} bytes.

Note: You shouldn't use the keystream interface as a PRNG, as it doesn't allow to re-seed the internal state.

\mysection{ChaCha}

\textit{ChaCha} is currently the most modern stream cipher included in LibTomCrypt, so use this one unless you
have a reason for using some of the older algorithms.

For more information about ChaCha see \url{https://en.wikipedia.org/wiki/ChaCha_(cipher)}.

Supported key size: 16 or 32 bytes (128 or 256 bits).

You can initialize ChaCha with 96bit \textit{nonce} + 32bit \textit{counter}:
\begin{verbatim}
chacha_state st;
err = chacha_setup(&st, key, key_len, rounds);
err = chacha_ivctr32(&st, nonce, 12, initial_32bit_ctr);
\end{verbatim}

Or with 64bit \textit{nonce} + 64bit \textit{counter}:
\begin{verbatim}
chacha_state st;
err = chacha_setup(&st, key, key_len, rounds);
err = chacha_ivctr64(&st, nonce, 8, initial_64bit_ctr);
\end{verbatim}

The \textit{chacha\_setup} takes the number of rounds as a parameter -- choose 20 if you are not sure.
As always never ever use the same key + nonce pair more than once.

For the actual encryption or decryption you have to call:
\begin{verbatim}
err = chacha_crypt(&st, in_buffer, in_len, out_buffer);
\end{verbatim}

If you just want a random stream of bytes initialize the cipher with a truly random \textit{key} (32 bytes),
a truly random \textit{nonce} (8 bytes) and zero initial counter. After that you can get a stream of pseudo--random
bytes via:
\begin{verbatim}
err = chacha_keystream(&st, out_buffer, out_len);
\end{verbatim}

At the end you have to terminate the state:
\begin{verbatim}
err = chacha_done(&st);
\end{verbatim}

\mysection{RC4}

For more information about RC4 see \url{https://en.wikipedia.org/wiki/RC4}.

Supported key size: 5--256 bytes

You need to initialize RC4 only with a \textit{key}.
\begin{verbatim}
rc4_state st;
err = rc4_stream_setup(&st, key, key_len);
\end{verbatim}

For the actual encryption or decryption you have to call:
\begin{verbatim}
err = rc4_stream_crypt(&st, in_buffer, in_len, out_buffer);
\end{verbatim}


If you just want a random stream of bytes initialize the cipher with truly random \textit{key}.
After that you can get a stream of pseudo--random bytes via:
\begin{verbatim}
err = rc4_stream_keystream(&st, out_buffer, out_len);
\end{verbatim}

At the end you have to terminate the state:
\begin{verbatim}
err = rc4_stream_done(&st);
\end{verbatim}

\mysection{Sober128}

Supported key size: must be multiple of 4 bytes

You need to initialize Sober128 with a \textit{key} and a \textit{nonce} (must be multiple of 4 bytes).
\begin{verbatim}
sober128_state st;
err = sober128_stream_setup(&st, key, 16);
err = sober128_stream_setiv(&st, nonce, 12);
\end{verbatim}

For the actual encryption or decryption you to call:
\begin{verbatim}
err = sober128_stream_crypt(&st, in_buffer, in_len, out_buffer);
\end{verbatim}

If you just want a random stream of bytes initialize the cipher with a truly random \textit{key}
and a truly random \textit{nonce}. After that you can get a stream of pseudo--random bytes via:
\begin{verbatim}
err = sober128_stream_keystream(&st, out_buffer, out_len);
\end{verbatim}

At the end you have to terminate the state:
\begin{verbatim}
err = sober128_stream_done(&st);
\end{verbatim}

\chapter{Authenticated Encryption}

Authenticated Encryption - sometimes also called Authenticated Encryption with Associated Data (AEAD) - is a variant of encryption
that provides not only confidentiality (as other symmetric or stream ciphers) but also integrity.

The inputs of Authenticated Encryption are: \textit{key}, \textit{nonce} (sometimes called initialization vector), \textit{plaintext},
optional \textit{header} (sometimes called additional authenticated data - AAD). The outputs are: \textit{ciphertext} and \textit{tag}.

\mysection{EAX Mode}
LibTomCrypt provides support for a mode called EAX\footnote{See
M. Bellare, P. Rogaway, D. Wagner, A Conventional Authenticated-Encryption Mode.} in a manner similar to the way it was intended to be used
by the designers.  First, a short description of what EAX mode is before we explain how to use it.  EAX is a mode that requires a cipher,
CTR and OMAC support and provides encryption and
authentication\footnote{Note that since EAX only requires OMAC and CTR you may use \textit{encrypt only} cipher descriptors with this mode.}.
It is initialized with a random \textit{nonce} that can be shared publicly, a \textit{header} which can be fixed and public, and a random secret symmetric key.

The \textit{header} data is meant to be meta--data associated with a stream that isn't private (e.g., protocol messages).  It can
be added at anytime during an EAX stream, and is part of the authentication tag.  That is, changes in the meta-data can be detected by changes in the output tag.

The mode can then process plaintext producing ciphertext as well as compute a partial checksum.  The actual checksum
called a \textit{tag} is only emitted when the message is finished.  In the interim, the user can process any arbitrary
sized message block to send to the recipient as ciphertext.  This makes the EAX mode especially suited for streaming modes
of operation.

The mode is initialized with the following function.
\index{eax\_init()}
\begin{verbatim}
int eax_init(          eax_state *eax,
                             int  cipher,
             const unsigned char *key,
                   unsigned long  keylen,
             const unsigned char *nonce,
                   unsigned long  noncelen,
             const unsigned char *header,
                   unsigned long  headerlen);
\end{verbatim}

Where \textit{eax} is the EAX state.  The \textit{cipher} parameter is the index of the desired cipher in the descriptor table.
The \textit{key} parameter is the shared secret symmetric key of length \textit{keylen} octets.  The \textit{nonce} parameter is the
random public string of length \textit{noncelen} octets.  The \textit{header} parameter is the random (or fixed or \textbf{NULL}) header for the
message of length \textit{headerlen} octets.

When this function completes, the \textit{eax} state will be initialized such that you can now either have data decrypted or
encrypted in EAX mode.  Note: if \textit{headerlen} is zero you may pass \textit{header} as \textbf{NULL} to indicate there is no initial header data.

To encrypt or decrypt data in a streaming mode use the following.
\index{eax\_encrypt()} \index{eax\_decrypt()}
\begin{verbatim}
int eax_encrypt(          eax_state *eax,
                const unsigned char *pt,
                      unsigned char *ct,
                      unsigned long  length);

int eax_decrypt(          eax_state *eax,
                const unsigned char *ct,
                      unsigned char *pt,
                      unsigned long  length);
\end{verbatim}
The function \textit{eax\_encrypt} will encrypt the bytes in \textit{pt} of \textit{length} octets, and store the ciphertext in
\textit{ct}.  Note: \textit{ct} and \textit{pt} may be the same region in memory.   This function will also send the ciphertext
through the OMAC function.  The function \textit{eax\_decrypt} decrypts \textit{ct}, and stores it in \textit{pt}.  This also allows
\textit{pt} and \textit{ct} to be the same region in memory.

You cannot both encrypt or decrypt with the same \textit{eax} context.  For bi--directional communication you will need to initialize
two EAX contexts (preferably with different headers and nonces).

Note: both of these functions allow you to send the data in any granularity but the order is important.  While
the eax\_init() function allows you to add initial header data to the stream you can also add header data during the
EAX stream with the following.

\index{eax\_addheader()}
\begin{verbatim}
int eax_addheader(          eax_state *eax,
                  const unsigned char *header,
                        unsigned long  length);
\end{verbatim}
This will add the \textit{length} octet from \textit{header} to the given \textit{eax} header.  Once the message is finished, the
\textit{tag} (checksum) may be computed with the following function:

\index{eax\_done()}
\begin{verbatim}
int eax_done(    eax_state *eax,
             unsigned char *tag,
             unsigned long *taglen);
\end{verbatim}
This will terminate the EAX state \textit{eax}, and store up to \textit{taglen} bytes of the message tag in \textit{tag}.  The function
then stores how many bytes of the tag were written out back in to \textit{taglen}.

The EAX mode code can be tested to ensure it matches the test vectors by calling the following function:
\index{eax\_test()}
\begin{verbatim}
int eax_test(void);
\end{verbatim}
This requires that the AES (or Rijndael) block cipher be registered with the cipher\_descriptor table first.

\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
   int           err;
   eax_state     eax;
   unsigned char pt[64], ct[64], nonce[16], key[16], tag[16];
   unsigned long taglen;

   if (register_cipher(&rijndael_desc) == -1) {
      printf("Error registering Rijndael");
      return EXIT_FAILURE;
   }

   /* ... make up random nonce and key ... */

   /* initialize context */
   if ((err = eax_init(            &eax,  /* context */
                find_cipher("rijndael"),  /* cipher id */
                                  nonce,  /* the nonce */
                                     16,  /* nonce is 16 bytes */
                              "TestApp",  /* example header */
                                      7)  /* header length */
       ) != CRYPT_OK) {
      printf("Error eax_init: %s", error_to_string(err));
      return EXIT_FAILURE;
   }

   /* now encrypt data, say in a loop or whatever */
   if ((err = eax_encrypt(     &eax, /* eax context */
                                 pt, /* plaintext  (source) */
                                 ct, /* ciphertext (destination) */
                          sizeof(pt) /* size of plaintext */
      ) != CRYPT_OK) {
      printf("Error eax_encrypt: %s", error_to_string(err));
      return EXIT_FAILURE;
   }

   /* finish message and get authentication tag */
   taglen = sizeof(tag);
   if ((err = eax_done(   &eax,      /* eax context */
                           tag,      /* where to put tag */
                       &taglen       /* length of tag space */
      ) != CRYPT_OK) {
      printf("Error eax_done: %s", error_to_string(err));
      return EXIT_FAILURE;
   }

   /* now we have the authentication tag in "tag" and
    * it's taglen bytes long */
}
\end{verbatim}

You can also perform an entire EAX state on a block of memory in a single function call with the
following functions.


\index{eax\_encrypt\_authenticate\_memory} \index{eax\_decrypt\_verify\_memory}
\begin{verbatim}
int eax_encrypt_authenticate_memory(
                    int  cipher,
    const unsigned char *key,    unsigned long keylen,
    const unsigned char *nonce,  unsigned long noncelen,
    const unsigned char *header, unsigned long headerlen,
    const unsigned char *pt,     unsigned long ptlen,
          unsigned char *ct,
          unsigned char *tag,    unsigned long *taglen);

int eax_decrypt_verify_memory(
                    int  cipher,
    const unsigned char *key,    unsigned long keylen,
    const unsigned char *nonce,  unsigned long noncelen,
    const unsigned char *header, unsigned long headerlen,
    const unsigned char *ct,     unsigned long ctlen,
          unsigned char *pt,
          unsigned char *tag,    unsigned long taglen,
          int           *res);
\end{verbatim}

Both essentially just call eax\_init() followed by eax\_encrypt() (or eax\_decrypt() respectively) and eax\_done().  The parameters
have the same meaning as with those respective functions.

The only difference is eax\_decrypt\_verify\_memory() does not emit a tag.  Instead you pass it a tag as input and it compares it against
the tag it computed while decrypting the message.  If the tags match then it stores a $1$ in \textit{res}, otherwise it stores a $0$.

\mysection{OCB Modes}
\subsection{Preface}

LibTomCrypt provides support for a mode called OCB in version 1 ''OCB''\footnote{See
P. Rogaway, M. Bellare, J. Black, T. Krovetz, \textit{OCB: A Block Cipher Mode of Operation for Efficient Authenticated Encryption}.}
and version 3 ''OCB3''\footnote{See RFC7253, T. Krovetz, P. Rogaway, \textit{The OCB Authenticated-Encryption Algorithm}.}.
OCB is an encryption protocol that simultaneously provides authentication.  It is slightly faster to use than EAX mode
but is less flexible.

Please be aware that all versions of OCB are patented and there are several licensing models provided by P. Rogaway, the patent holder
-- see \url{http://web.cs.ucdavis.edu/~rogaway/ocb/license.htm}.

\subsection{OCB}
\subsubsection{Initialization and processing}

Let's review how to initialize an OCB context.

\index{ocb\_init()}
\begin{verbatim}
int ocb_init(          ocb_state *ocb,
                             int  cipher,
             const unsigned char *key,
                   unsigned long  keylen,
             const unsigned char *nonce);
\end{verbatim}

This will initialize the \textit{ocb} context using cipher descriptor \textit{cipher}.  It will use a \textit{key} of length \textit{keylen}
and the random \textit{nonce}.  Note that \textit{nonce} must be a random (public) string the same length as the block ciphers
block size (e.g. 16 bytes for AES).

This mode has no \textit{Associated Data} like EAX mode does which means you cannot authenticate metadata along with the stream.
To encrypt or decrypt data use the following.

\index{ocb\_encrypt()} \index{ocb\_decrypt()}
\begin{verbatim}
int ocb_encrypt(          ocb_state *ocb,
                const unsigned char *pt,
                      unsigned char *ct);

int ocb_decrypt(          ocb_state *ocb,
                const unsigned char *ct,
                      unsigned char *pt);
\end{verbatim}

This will encrypt (or decrypt for the latter) a fixed length of data from \textit{pt} to \textit{ct} (vice versa for the latter).
They assume that \textit{pt} and \textit{ct} are the same size as the block cipher's block size.  Note that you cannot call
both functions given a single \textit{ocb} state.  For bi-directional communication you will have to initialize two \textit{ocb}
states (with different nonces).  Also \textit{pt} and \textit{ct} may point to the same location in memory.

\subsubsection{State Termination}

When you are finished encrypting the message you call the following function to compute the tag.

\index{ocb\_done\_encrypt()}
\begin{verbatim}
int ocb_done_encrypt(          ocb_state *ocb,
                     const unsigned char *pt,
                           unsigned long  ptlen,
                           unsigned char *ct,
                           unsigned char *tag,
                           unsigned long *taglen);
\end{verbatim}

This will terminate an encrypt stream \textit{ocb}.  If you have trailing bytes of plaintext that will not complete a block
you can pass them here.  This will also encrypt the \textit{ptlen} bytes in \textit{pt} and store them in \textit{ct}.  It will also
store up to \textit{taglen} bytes of the tag into \textit{tag}.

Note that \textit{ptlen} must be less than or equal to the block size of block cipher chosen.  Also note that if you have
an input message equal to the length of the block size then you pass the data here (not to ocb\_encrypt()) only.

To terminate a decrypt stream and compared the tag you call the following.

\index{ocb\_done\_decrypt()}
\begin{verbatim}
int ocb_done_decrypt(          ocb_state *ocb,
                     const unsigned char *ct,
                           unsigned long  ctlen,
                           unsigned char *pt,
                     const unsigned char *tag,
                           unsigned long  taglen,
                                     int *res);
\end{verbatim}
Similarly to the previous function you can pass trailing message bytes into this function.  This will compute the
tag of the message (internally) and then compare it against the \textit{taglen} bytes of \textit{tag} provided.  By default
\textit{res} is set to zero.  If all \textit{taglen} bytes of \textit{tag} can be verified then \textit{res} is set to one (authenticated
message).

\subsubsection{Packet Functions}
To make life simpler the following two functions are provided for memory bound OCB.

%\index{ocb\_encrypt\_authenticate\_memory()}
\begin{verbatim}
int ocb_encrypt_authenticate_memory(
                    int  cipher,
    const unsigned char *key,    unsigned long keylen,
    const unsigned char *nonce,
    const unsigned char *pt,     unsigned long ptlen,
          unsigned char *ct,
          unsigned char *tag,    unsigned long *taglen);
\end{verbatim}

This will OCB encrypt the message \textit{pt} of length \textit{ptlen}, and store the ciphertext in \textit{ct}.  The length \textit{ptlen}
can be any arbitrary length.

\index{ocb\_decrypt\_verify\_memory()}
\begin{verbatim}
int ocb_decrypt_verify_memory(
                    int  cipher,
    const unsigned char *key,    unsigned long keylen,
    const unsigned char *nonce,
    const unsigned char *ct,     unsigned long ctlen,
          unsigned char *pt,
    const unsigned char *tag,    unsigned long taglen,
          int           *res);
\end{verbatim}

Similarly, this will OCB decrypt, and compare the internally computed tag against the tag provided. \textit{res} is set
appropriately to \textit{1} if the tag matches or to \textit{0} if it doesn't match.

\subsection{OCB3}
\subsubsection{Initialization and processing}

\index{ocb3\_init()}
\begin{verbatim}
int ocb3_init(ocb3_state *ocb, int cipher,
             const unsigned char *key, unsigned long keylen,
             const unsigned char *nonce, unsigned long noncelen,
             unsigned long taglen);
\end{verbatim}

This will initialize the \textit{ocb} context using cipher descriptor \textit{cipher}.  It will use a \textit{key} of length \textit{keylen}
and the random \textit{nonce} of length \textit{noncelen}.  The \textit{nonce} must be a random (public) string of an arbitrary length
between 1 and 15 octets.  The desired length of the TAG that should be created when terminating the state has to be passed in \textit{taglen}
and has to be between 0 and 16 octets.

Note that you can only use ciphers with a block length of 16.

\subsubsection{Additional Authenticated Data}

OCB3 has, in contrary to OCB, the possibility to add "Additional Authenticated Data" (AAD) when performing cryptographic operations.

\index{ocb3\_add\_aad()}
\begin{verbatim}
int ocb3_add_aad(ocb3_state *ocb, const unsigned char *aad, unsigned long aadlen);
\end{verbatim}

This will add the AAD at \textit{aad} of the arbitrary length \textit{aadlen} to be authenticated within the context \textit{ocb}.

\index{ocb3\_encrypt()} \index{ocb3\_decrypt()}
\begin{verbatim}
int ocb3_encrypt(         ocb3_state *ocb,
                 const unsigned char *pt,
                       unsigned long ptlen,
                       unsigned char *ct);

int ocb3_decrypt(         ocb3_state *ocb,
                 const unsigned char *ct,
                       unsigned long ctlen,
                       unsigned char *pt);
\end{verbatim}

This will encrypt (or decrypt for the latter) a fixed length of data from \textit{pt} to \textit{ct} (vice versa for the latter).
They assume that \textit{pt} and \textit{ct} are the same size as the block cipher's block size.  Note that you cannot call
both functions given a single \textit{ocb} state.  For bi-directional communication you will have to initialize two \textit{ocb}
states (with different nonces).  Also \textit{pt} and \textit{ct} may point to the same location in memory.

\subsubsection{State Termination}

\index{ocb3\_encrypt\_last()} \index{ocb3\_decrypt\_last()}
\begin{verbatim}
int ocb3_encrypt_last(         ocb3_state *ocb,
                      const unsigned char *pt,
                            unsigned long ptlen,
                            unsigned char *ct);

int ocb3_decrypt_last(         ocb3_state *ocb,
                      const unsigned char *ct,
                            unsigned long ctlen,
                            unsigned char *pt);
\end{verbatim}

This has to be called for the last encrypt (or decrypt) operation. Note that if you have to invoke only a single operation you can
directly use these functions instead of \textit{ocb3\_encrypt()} or \textit{ocb3\_decrypt()}.

When you are finished encrypting the message you call the following function to compute the tag.

\index{ocb3\_done()}
\begin{verbatim}
int ocb3_done(ocb3_state *ocb, unsigned char *tag, unsigned long *taglen);
\end{verbatim}

This stores the tag of the \textit{ocb} state in \textit{tag}.
The \textit{taglen} parameter defines on input the length of the tag to output and will be set to the actual length written, which
is at most 16 octets.

\subsubsection{Packet Functions}
To make life simpler the following two functions are provided for memory bound OCB3.

\index{ocb3\_encrypt\_authenticate\_memory()}
\begin{verbatim}
int ocb3_encrypt_authenticate_memory(int cipher,
    const unsigned char *key,    unsigned long keylen,
    const unsigned char *nonce,  unsigned long noncelen,
    const unsigned char *adata,  unsigned long adatalen,
    const unsigned char *pt,     unsigned long ptlen,
          unsigned char *ct,
          unsigned char *tag,    unsigned long *taglen);
\end{verbatim}

This will OCB3 encrypt the message \textit{pt} of length \textit{ptlen}, and store the ciphertext in \textit{ct}.  The length \textit{ptlen}
can be any arbitrary length.  The additional authenticated data \textit{adata} of length \textit{adatalen} is optional and can be left out
by passing \textit{NULL} as \textit{adata}. The length of the authentication TAG will be stored in \textit{tag}, which is also optional.
The length of the TAG passed in \textit{taglen} has to be between 0 and 16.

\index{ocb3\_decrypt\_verify\_memory()}
\begin{verbatim}
int ocb3_decrypt_verify_memory(int cipher,
    const unsigned char *key,    unsigned long keylen,
    const unsigned char *nonce,  unsigned long noncelen,
    const unsigned char *adata,  unsigned long adatalen,
    const unsigned char *ct,     unsigned long ctlen,
          unsigned char *pt,
    const unsigned char *tag,    unsigned long taglen,
          int           *stat);
\end{verbatim}

Similarly, this will OCB3 decrypt, and compare the internally computed tag against the tag provided. \textit{res} is set
appropriately to \textit{1} if the tag matches or to \textit{0} if it doesn't match.

\mysection{CCM Mode}
CCM is a NIST proposal for encrypt + authenticate that is centered around using AES (or any 16--byte cipher) as a primitive.

\subsection{Initialization}
To initialize the CCM context with a secret key call the following function.

\index{ccm\_init()}
\begin{verbatim}
int ccm_init(      ccm_state *ccm,
                   int cipher,
             const unsigned char *key,
                   int keylen,
                   int ptlen,
                   int taglen,
                   int aadlen);
\end{verbatim}
This initializes the CCM state \textit{ccm} for the given cipher indexed by \textit{cipher}, with a secret key \textit{key} of length \textit{keylen} octets. The cipher
chosen must have a 16--byte block size (e.g., AES).
Unlike EAX and OCB mode, CCM is only meant for \textit{packet} mode where the length of the input is known in advance. This is why the length of the stream
to authenticate is given as \textit{ptlen}.
With CCM, a header is meta--data you want to send with the message but not have encrypted. The header len is given in the init
as \textit{aadlen}.

\subsection{Nonce Vector}
After the state has been initialized (or reset) the next step is to add the session (or packet) initialization vector.  It should be unique per packet encrypted.

\index{ccm\_add\_nonce()}
\begin{verbatim}
int ccm_add_nonce(      ccm_state *ccm,
                  const unsigned char *nonce,
                        unsigned long noncelen);
\end{verbatim}

This adds the nonce (a.k.a. salt) \textit{nonce} of length \textit{noncelen} octets to the CCM state \textit{ccm}. Note that this function must be called
once and only once.

\subsection{Additional Authentication Data}
The header is meta--data you want to send with the message but not have encrypted, it must be stored in \textit{adata} of length \textit{adatalen} octets.

\index{ccm\_add\_aad()}
\begin{verbatim}
int ccm_add_aad(      ccm_state *ccm,
                const unsigned char *adata,
                      unsigned long adatalen);
\end{verbatim}
This adds the additional authentication data \textit{adata} of length \textit{adatalen} to the CCM state \textit{ccm}.

\subsection{Plaintext Processing}
After the AAD has been processed, the plaintext (or ciphertext depending on the direction) can be processed.

\index{ccm\_process()}
\begin{verbatim}
int ccm_process(ccm_state *ccm,
                unsigned char *pt,
                unsigned long  ptlen,
                unsigned char *ct,
                int  direction);
\end{verbatim}
This processes message data where \textit{pt} is the plaintext and \textit{ct} is the ciphertext.  The length of both are equal and stored in \textit{ptlen}.  Depending on
the mode \textit{pt} is the input and \textit{ct} is the output (or vice versa).  When \textit{direction} equals \textbf{CCM\_ENCRYPT} the plaintext is read,
encrypted and stored in the ciphertext buffer.  When \textit{direction} equals \textbf{CCM\_DECRYPT} the opposite occurs.

\subsection{State Termination}
To terminate a CCM state and retrieve the message authentication tag call the following function.

\index{ccm\_done()}
\begin{verbatim}
int ccm_done(    ccm_state *ccm,
             unsigned char *tag,
             unsigned long *taglen);
\end{verbatim}
This terminates the CCM state \textit{ccm} and stores the tag in \textit{tag} of length \textit{taglen} octets.

\subsection{State Reset}
The call to ccm\_init() will perform considerable pre--computation and if you're going to be dealing with a lot of packets
it is very costly to have to call it repeatedly.  To aid in this endeavour, the reset function is provided.

\index{ccm\_reset()}
\begin{verbatim}
int ccm_reset(ccm_state *ccm);
\end{verbatim}

This will reset the CCM state \textit{ccm} to the state that ccm\_init() left it.  The user would then call ccm\_add\_nonce(), ccm\_add\_aad(), etc.

\subsection{One--Shot Packet}
To process a single packet under any given key the following helper function can be used.

\index{ccm\_memory()}
\begin{verbatim}
int ccm_memory(
                    int  cipher,
    const unsigned char *key,    unsigned long keylen,
    symmetric_key       *uskey,
    const unsigned char *nonce,  unsigned long noncelen,
    const unsigned char *header, unsigned long headerlen,
          unsigned char *pt,     unsigned long ptlen,
          unsigned char *ct,
          unsigned char *tag,    unsigned long *taglen,
                    int  direction);
\end{verbatim}

This will initialize the CCM state with the given key, nonce and AAD value then proceed to encrypt or decrypt the message text and store the final
message tag.  The definition of the variables is the same as it is for all the manual functions.

If you are processing many packets under the same key you shouldn't use this function as it invokes the pre--computation with each call.

\subsection{Example Usage}
The following is an example usage of how to use CCM over multiple packets with a shared secret key.

\begin{small}
\begin{verbatim}
#include <tomcrypt.h>

int send_packet(const unsigned char *pt,     unsigned long ptlen,
                const unsigned char *nonce,  unsigned long noncelen,
                const unsigned char *aad,    unsigned long aadlen,
                      ccm_state     *ccm)
{
   int           err;
   unsigned long taglen;
   unsigned char tag[16];

   /* reset the state */
   if ((err = ccm_reset(ccm)) != CRYPT_OK) {
      return err;
   }

   /* Add the nonce */
   if ((err = ccm_add_nonce(ccm, nonce, noncelen)) != CRYPT_OK) {
      return err;
   }

   /* Add the AAD (note: aad can be NULL if aadlen == 0) */
   if ((err = ccm_add_aad(ccm, aad, aadlen)) != CRYPT_OK) {
      return err;
   }

   /* process the plaintext */
   if ((err =
        ccm_process(ccm, pt, ptlen, pt, CCM_ENCRYPT)) != CRYPT_OK) {
      return err;
   }

   /* Finish up and get the MAC tag */
   taglen = sizeof(tag);
   if ((err = ccm_done(ccm, tag, &taglen)) != CRYPT_OK) {
      return err;
   }

   /* ... send a header describing the lengths ... */

   /* depending on the protocol and how nonce is
    * generated you may have to send it too... */
   send(socket, nonce, noncelen, 0);

   /* send the aad */
   send(socket, aad, aadlen, 0);

   /* send the ciphertext */
   send(socket, pt, ptlen, 0);

   /* send the tag */
   send(socket, tag, taglen, 0);

   return CRYPT_OK;
}

int main(void)
{
   ccm_state     ccm;
   unsigned char key[16], NONCE[12], pt[PACKET_SIZE];
   int           err, x;
   unsigned long ptlen;

   /* somehow fill key/NONCE with random values */

   /* register AES */
   register_cipher(&aes_desc);

   /* init the CCM state */
   if ((err =
        ccm_init(&ccm, find_cipher("aes"), key, 16, PACKET_SIZE, 16, size(NONCE))) != CRYPT_OK) {
      whine_and_pout(err);
   }

   /* handle us some packets */
   for (;;) {
       ptlen = make_packet_we_want_to_send(pt);

       /* use NONCE as counter (12 byte counter) */
       for (x = 11; x >= 0; x--) {
           if (++NONCE[x]) {
              break;
           }
       }

       if ((err = send_packet(pt, ptlen, NONCE, 12, NULL, 0, &ccm))
           != CRYPT_OK) {
           whine_and_pout(err);
       }
   }
   return EXIT_SUCCESS;
}
\end{verbatim}
\end{small}

\mysection{GCM Mode}
Galois counter mode is an IEEE proposal for authenticated encryption (also it is a planned NIST standard).  Like EAX and OCB mode, it can be used in a streaming capacity
however, unlike EAX it cannot accept \textit{additional authentication data} (meta--data) after plaintext has been processed.  This mode also only works with
block ciphers with a 16--byte block.

A GCM stream is meant to be processed in three modes, one after another.  First, the initialization vector (per session) data is processed.  This should be
unique to every session.  Next, the the optional additional authentication data is processed, and finally the plaintext (or ciphertext depending on the direction).

\subsection{Initialization}
To initialize the GCM context with a secret key call the following function.

\index{gcm\_init()}
\begin{verbatim}
int gcm_init(          gcm_state *gcm,
                             int  cipher,
             const unsigned char *key,
                             int  keylen);
\end{verbatim}
This initializes the GCM state \textit{gcm} for the given cipher indexed by \textit{cipher}, with a secret key \textit{key} of length \textit{keylen} octets.  The cipher
chosen must have a 16--byte block size (e.g., AES).

\subsection{Initialization Vector}
After the state has been initialized (or reset) the next step is to add the session (or packet) initialization vector.  It should be unique per packet encrypted.

\index{gcm\_add\_iv()}
\begin{verbatim}
int gcm_add_iv(          gcm_state *gcm,
               const unsigned char *IV,
                     unsigned long  IVlen);
\end{verbatim}
This adds the initialization vector octets from \textit{IV} of length \textit{IVlen} to the GCM state \textit{gcm}.  You can call this function as many times as required
to process the entire IV.

Note: the GCM protocols provides a \textit{shortcut} for 12--byte IVs where no pre-processing is to be done.  If you want to minimize per packet latency it is ideal
to only use 12--byte IVs.  You can just increment it like a counter for each packet.

\subsection{Additional Authentication Data}
After the entire IV has been processed, the additional authentication data can be processed.  Unlike the IV, a packet/session does not require additional
authentication data (AAD) for security.  The AAD is meant to be used as side--channel data you want to be authenticated with the packet.  Note:  once
you begin adding AAD to the GCM state you cannot return to adding IV data until the state has been reset.

\index{gcm\_add\_aad()}
\begin{verbatim}
int gcm_add_aad(          gcm_state *gcm,
                const unsigned char *adata,
                      unsigned long  adatalen);
\end{verbatim}
This adds the additional authentication data \textit{adata} of length \textit{adatalen} to the GCM state \textit{gcm}.

\subsection{Plaintext Processing}
After the AAD has been processed, the plaintext (or ciphertext depending on the direction) can be processed.

\index{gcm\_process()}
\begin{verbatim}
int gcm_process(    gcm_state *gcm,
                unsigned char *pt,
                unsigned long  ptlen,
                unsigned char *ct,
                          int  direction);
\end{verbatim}
This processes message data where \textit{pt} is the plaintext and \textit{ct} is the ciphertext.  The length of both are equal and stored in \textit{ptlen}.  Depending on
the mode \textit{pt} is the input and \textit{ct} is the output (or vice versa).  When \textit{direction} equals \textbf{GCM\_ENCRYPT} the plaintext is read,
encrypted and stored in the ciphertext buffer.  When \textit{direction} equals \textbf{GCM\_DECRYPT} the opposite occurs.

\subsection{State Termination}
To terminate a GCM state and retrieve the message authentication tag call the following function.

\index{gcm\_done()}
\begin{verbatim}
int gcm_done(    gcm_state *gcm,
             unsigned char *tag,
             unsigned long *taglen);
\end{verbatim}
This terminates the GCM state \textit{gcm} and stores the tag in \textit{tag} of length \textit{taglen} octets.

\subsection{State Reset}
The call to gcm\_init() will perform considerable pre--computation (when \textbf{GCM\_TABLES} is defined) and if you're going to be dealing with a lot of packets
it is very costly to have to call it repeatedly.  To aid in this endeavour, the reset function has been provided.

\index{gcm\_reset()}
\begin{verbatim}
int gcm_reset(gcm_state *gcm);
\end{verbatim}

This will reset the GCM state \textit{gcm} to the state that gcm\_init() left it.  The user would then call gcm\_add\_iv(), gcm\_add\_aad(), etc.

\subsection{One--Shot Packet}
To process a single packet under any given key the following helper function can be used.

\index{gcm\_memory()}
\begin{verbatim}
int gcm_memory(
                    int  cipher,
    const unsigned char *key,
          unsigned long keylen,
    const unsigned char *IV,    unsigned long IVlen,
    const unsigned char *adata, unsigned long adatalen,
          unsigned char *pt,    unsigned long ptlen,
          unsigned char *ct,
          unsigned char *tag,   unsigned long *taglen,
                    int  direction);
\end{verbatim}

This will initialize the GCM state with the given key, IV and AAD value then proceed to encrypt or decrypt the message text and store the final
message tag.  The definition of the variables is the same as it is for all the manual functions.

If you are processing many packets under the same key you shouldn't use this function as it invokes the pre--computation with each call.

\subsection{Example Usage}
The following is an example usage of how to use GCM over multiple packets with a shared secret key.

\begin{small}
\begin{verbatim}
#include <tomcrypt.h>

int send_packet(const unsigned char *pt,  unsigned long ptlen,
                const unsigned char *iv,  unsigned long ivlen,
                const unsigned char *aad, unsigned long aadlen,
                      gcm_state     *gcm)
{
   int           err;
   unsigned long taglen;
   unsigned char tag[16];

   /* reset the state */
   if ((err = gcm_reset(gcm)) != CRYPT_OK) {
      return err;
   }

   /* Add the IV */
   if ((err = gcm_add_iv(gcm, iv, ivlen)) != CRYPT_OK) {
      return err;
   }

   /* Add the AAD (note: aad can be NULL if aadlen == 0) */
   if ((err = gcm_add_aad(gcm, aad, aadlen)) != CRYPT_OK) {
      return err;
   }

   /* process the plaintext */
   if ((err =
        gcm_process(gcm, pt, ptlen, pt, GCM_ENCRYPT)) != CRYPT_OK) {
      return err;
   }

   /* Finish up and get the MAC tag */
   taglen = sizeof(tag);
   if ((err = gcm_done(gcm, tag, &taglen)) != CRYPT_OK) {
      return err;
   }

   /* ... send a header describing the lengths ... */

   /* depending on the protocol and how IV is
    * generated you may have to send it too... */
   send(socket, iv, ivlen, 0);

   /* send the aad */
   send(socket, aad, aadlen, 0);

   /* send the ciphertext */
   send(socket, pt, ptlen, 0);

   /* send the tag */
   send(socket, tag, taglen, 0);

   return CRYPT_OK;
}

int main(void)
{
   gcm_state     gcm;
   unsigned char key[16], IV[12], pt[PACKET_SIZE];
   int           err, x;
   unsigned long ptlen;

   /* somehow fill key/IV with random values */

   /* register AES */
   register_cipher(&aes_desc);

   /* init the GCM state */
   if ((err =
        gcm_init(&gcm, find_cipher("aes"), key, 16)) != CRYPT_OK) {
      whine_and_pout(err);
   }

   /* handle us some packets */
   for (;;) {
       ptlen = make_packet_we_want_to_send(pt);

       /* use IV as counter (12 byte counter) */
       for (x = 11; x >= 0; x--) {
           if (++IV[x]) {
              break;
           }
       }

       if ((err = send_packet(pt, ptlen, iv, 12, NULL, 0, &gcm))
           != CRYPT_OK) {
           whine_and_pout(err);
       }
   }
   return EXIT_SUCCESS;
}
\end{verbatim}
\end{small}

\mysection{ChaCha20--Poly1305}

This authenticated encryption is based on ChaCha20 stream cipher and Poly1305 authenticator.
It is defined by \url{https://tools.ietf.org/html/rfc7539}.

\subsection{Initialization}
To initialize the ChaCha20--Poly1305 context with a secret key call the following function.

\index{chacha20poly1305\_init()}
\begin{verbatim}
int chacha20poly1305_init(chacha20poly1305_state *st,
                             const unsigned char *key,
                                   unsigned long  keylen);
\end{verbatim}
This initializes the ChaCha20--Poly1305 state \textit{st} with a secret key \textit{key} of length \textit{keylen}
octets (valid lengths: 32 or 16).

\subsection{Initialization Vector}
After the state has been initialized the next step is to add the initialization vector.

\index{chacha20poly1305\_setiv()}
\begin{verbatim}
int chacha20poly1305_setiv(chacha20poly1305_state *st,
                              const unsigned char *iv,
                                    unsigned long  ivlen);
\end{verbatim}
This adds the initialization vector from \textit{iv} of length \textit{ivlen} octects (valid lengths: 8 or 12) to
the ChaCha20--Poly1305 state \textit{st}.

\index{chacha20poly1305\_setiv\_rfc7905()}
\begin{verbatim}
int chacha20poly1305_setiv_rfc7905(chacha20poly1305_state *st,
                                      const unsigned char *iv,
                                            unsigned long  ivlen,
                                                  ulong64  sequence_number);
\end{verbatim}
This also adds the initialization vector from \textit{iv} of length \textit{ivlen} octects (valid lengths: 8 or 12) to
the state \textit{st} but it also incorporates 64bit \textit{sequence\_number} into IV as described in RFC7905.

You can call only one of \textit{chacha20poly1305\_setiv} or \textit{chacha20poly1305\_setiv\_rfc7905}.

\subsection{Additional Authentication Data}
After the IV has been set, the additional authentication data can be processed.

\index{chacha20poly1305\_add\_aad()}
\begin{verbatim}
int chacha20poly1305_add_aad(chacha20poly1305_state *st,
                                const unsigned char *adata,
                                      unsigned long  adatalen);

\end{verbatim}
This adds the additional authentication data \textit{adata} of length \textit{adatalen} to the ChaCha20--Poly1305 state \textit{st}.

\subsection{Encryption / Decryption}
After the AAD has been processed, the plaintext (or ciphertext depending on the direction) can be processed.

\index{chacha20poly1305\_encrypt()}
\begin{verbatim}
int chacha20poly1305_encrypt(chacha20poly1305_state *st,
                                const unsigned char *in,
                                      unsigned long  inlen,
                                      unsigned char *out);
\end{verbatim}
This encrypts the data where \textit{in} is the plaintext and \textit{out} is the ciphertext. The length of both are equal and stored in \textit{inlen}.

\index{chacha20poly1305\_decrypt()}
\begin{verbatim}
int chacha20poly1305_decrypt(chacha20poly1305_state *st,
                                const unsigned char *in,
                                      unsigned long  inlen,
                                      unsigned char *out);
\end{verbatim}
This decrypts the data where \textit{in} is the ciphertext and \textit{out} is the plaintext. The length of both are equal and stored in \textit{inlen}.

\subsection{State Termination}
To terminate a ChaCha20--Poly1305 state and retrieve the message authentication tag call the following function.

\index{chacha20poly1305\_done()}
\begin{verbatim}
int chacha20poly1305_done(chacha20poly1305_state *st,
                                   unsigned char *tag,
                                   unsigned long *taglen);
\end{verbatim}
This terminates the ChaCha20--Poly1305 state \textit{st} and stores the tag in \textit{tag} of length \textit{taglen} octets (always 16).

\subsection{One--Shot Packet}
To process a single packet under any given key the following helper function can be used.

\index{chacha20poly1305\_memory()}
\begin{verbatim}
int chacha20poly1305_memory(const unsigned char *key,
                                  unsigned long  keylen,
                            const unsigned char *iv,
                                  unsigned long  ivlen,
                            const unsigned char *aad,
                                  unsigned long  aadlen,
                            const unsigned char *in,
                                  unsigned long  inlen,
                                  unsigned char *out,
                                  unsigned char *tag,
                                  unsigned long *taglen,
                                            int  direction);
\end{verbatim}
This will initialize the ChaCha20--Poly1305 state with the given key, IV and AAD value then proceed to
encrypt (\textit{direction} equals \textbf{CHACHA20POLY1305\_ENCRYPT}) or decrypt (\textit{direction} equals
\textbf{CHACHA20POLY1305\_DECRYPT}) the message text and store the final message tag. The definition of the
variables is the same as it is for all the manual functions.

\chapter{One-Way Cryptographic Hash Functions}
\mysection{Core Functions}
Like the ciphers, there are hash core functions and a universal data type to hold the hash state called \textit{hash\_state}.  To initialize hash
XXX (where XXX is the name) call:
\index{Hash Functions}
\begin{verbatim}
void XXX_init(hash_state *md);
\end{verbatim}

This simply sets up the hash to the default state governed by the specifications of the hash.  To add data to the message being hashed call:
\begin{verbatim}
int XXX_process(         hash_state *md,
                const unsigned char *in,
                      unsigned long  inlen);
\end{verbatim}
Essentially all hash messages are virtually infinitely\footnote{Most hashes are limited to $2^{64}$ bits or 2,305,843,009,213,693,952 bytes.} long message which
are buffered.  In the case where this limit is reached the \textit{XXX\_process()} function returns \textit{CRYPT\_HASH\_OVERFLOW}.
\index{CRYPT\_HASH\_OVERFLOW}
The data can be passed in any sized chunks as long as the order of the bytes are the same, the message digest (hash output) will be the same.  For example, this means that:
\begin{verbatim}
md5_process(&md, "hello ", 6);
md5_process(&md, "world", 5);
\end{verbatim}
Will produce the same message digest as the single call:
\index{Message Digest}
\begin{verbatim}
md5_process(&md, "hello world", 11);
\end{verbatim}

To finally get the message digest (the hash) call:
\begin{verbatim}
int XXX_done(   hash_state *md,
             unsigned char *out);
\end{verbatim}

This function will finish up the hash and store the result in the \textit{out} array.  You must ensure that \textit{out} is long
enough for the hash in question.  Often hashes are used to get keys for symmetric ciphers so the \textit{XXX\_done()} functions
will wipe the \textit{md} variable before returning automatically.

To test a hash function call:
\begin{verbatim}
int XXX_test(void);
\end{verbatim}

This will return {\bf CRYPT\_OK} if the hash matches the test vectors, otherwise it returns an error code.  An
example snippet that hashes a message with md5 is given below.
\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
    hash_state md;
    unsigned char *in = "hello world", out[16];

    /* setup the hash */
    md5_init(&md);

    /* add the message */
    md5_process(&md, in, strlen(in));

    /* get the hash in out[0..15] */
    md5_done(&md, out);

    return 0;
}
\end{verbatim}
\end{small}

\mysection{Hash Descriptors}
Like the set of ciphers, the set of hashes have descriptors as well.  They are stored in an array called \textit{hash\_descriptor} and
are defined by:
\begin{verbatim}
struct _hash_descriptor {
    char *name;

    unsigned long hashsize;    /* digest output size in bytes  */
    unsigned long blocksize;   /* the block size the hash uses */

    void (*init)   (hash_state *hash);

    int  (*process)(         hash_state *hash,
                    const unsigned char *in,
                          unsigned long  inlen);

    int  (*done)   (hash_state *hash, unsigned char *out);

    int  (*test)   (void);
};
\end{verbatim}

\index{find\_hash()}
The \textit{name} member is the name of the hash function (all lowercase).  The \textit{hashsize} member is the size of the digest output
in bytes, while \textit{blocksize} is the size of blocks the hash expects to the compression function.  Technically, this detail is not important
for high level developers but is useful to know for performance reasons.

The \textit{init} member initializes the hash, \textit{process} passes data through the hash, \textit{done} terminates the hash and retrieves the
digest.  The \textit{test} member tests the hash against the specified test vectors.

There is a function to search the array as well called \textit{int find\_hash(char *name)}.  It returns -1 if the hash is not found, otherwise, the
position in the descriptor table of the hash.

In addition, there is also find\_hash\_oid() which finds a hash by the ASN.1 OBJECT IDENTIFIER string.
\index{find\_hash\_oid()}
\begin{verbatim}
int find_hash_oid(const unsigned long *ID, unsigned long IDlen);
\end{verbatim}

You can use the table to indirectly call a hash function that is chosen at run-time.  For example:
\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
   unsigned char buffer[100], hash[MAXBLOCKSIZE];
   int idx, x;
   hash_state md;

   /* register hashes .... */
   if (register_hash(&md5_desc) == -1) {
      printf("Error registering MD5.\n");
      return -1;
   }

   /* register other hashes ... */

   /* prompt for name and strip newline */
   printf("Enter hash name: \n");
   fgets(buffer, sizeof(buffer), stdin);
   buffer[strlen(buffer) - 1] = 0;

   /* get hash index */
   idx = find_hash(buffer);
   if (idx == -1) {
      printf("Invalid hash name!\n");
      return -1;
   }

   /* hash input until blank line */
   hash_descriptor[idx].init(&md);
   while (fgets(buffer, sizeof(buffer), stdin) != NULL)
         hash_descriptor[idx].process(&md, buffer, strlen(buffer));
   hash_descriptor[idx].done(&md, hash);

   /* dump to screen */
   for (x = 0; x < hash_descriptor[idx].hashsize; x++)
       printf("%02x ", hash[x]);
   printf("\n");
   return 0;
}
\end{verbatim}
\end{small}

Note the usage of \textbf{MAXBLOCKSIZE}.  In LibTomCrypt, no symmetric block, key or hash digest is larger than \textbf{MAXBLOCKSIZE} in
length.  This provides a simple size you can set your automatic arrays to that will not get overrun.

There are three helper functions to make working with hashes easier.  The first is a function to hash a buffer, and produce the digest in a single
function call.

\index{hash\_memory()}
\begin{verbatim}
int hash_memory(                int  hash,
                const unsigned char *in,
                      unsigned long  inlen,
                      unsigned char *out,
                      unsigned long *outlen);
\end{verbatim}

This will hash the data pointed to by \textit{in} of length \textit{inlen}.  The hash used is indexed by the \textit{hash} parameter.  The message
digest is stored in \textit{out}, and the \textit{outlen} parameter is updated to hold the message digest size.

The next helper function allows for the hashing of a file based on a file name.
\index{hash\_file()}
\begin{verbatim}
int hash_file(          int  hash,
                 const char *fname,
              unsigned char *out,
              unsigned long *outlen);
\end{verbatim}

This will hash the file named by \textit{fname} using the hash indexed by \textit{hash}.  The file named in this function call must be readable by the
user owning the process performing the request.  This function can be omitted by the \textbf{LTC\_NO\_FILE} define, which forces it to return \textbf{CRYPT\_NOP}
when it is called.  The message digest is stored in \textit{out}, and the \textit{outlen} parameter is updated to hold the message digest size.

\index{hash\_filehandle()}
\begin{verbatim}
int hash_filehandle(          int  hash,
                             FILE *in,
                    unsigned char *out,
                    unsigned long *outlen);
\end{verbatim}

This will hash the file identified by the handle \textit{in} using the hash indexed by \textit{hash}.  This will begin hashing from the current file pointer position, and
will not rewind the file pointer when finished.  This function can be omitted by the \textbf{LTC\_NO\_FILE} define, which forces it to return \textbf{CRYPT\_NOP}
when it is called.  The message digest is stored in \textit{out}, and the \textit{outlen} parameter is updated to hold the message digest size.

To perform the above hash with md5 the following code could be used:
\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
   int idx, err;
   unsigned long len;
   unsigned char out[MAXBLOCKSIZE];

   /* register the hash */
   if (register_hash(&md5_desc) == -1) {
      printf("Error registering MD5.\n");
      return -1;
   }

   /* get the index of the hash  */
   idx = find_hash("md5");

   /* call the hash */
   len = sizeof(out);
   if ((err =
       hash_memory(idx, "hello world", 11, out, &len)) != CRYPT_OK) {
      printf("Error hashing data: %s\n", error_to_string(err));
      return -1;
   }
   return 0;
}
\end{verbatim}
\end{small}

\subsection{Hash Registration}
Similar to the cipher descriptor table you must register your hash algorithms before you can use them.  These functions
work exactly like those of the cipher registration code.  The functions are:
\index{register\_hash()} \index{unregister\_hash()}
\begin{verbatim}
int register_hash(const struct _hash_descriptor *hash);

int unregister_hash(const struct _hash_descriptor *hash);
\end{verbatim}

The following hashes are provided as of this release within the LibTomCrypt library:
\index{Hash descriptor table}

\begin{figure}[H]
\begin{center}
\begin{tabular}{|c|c|c|}
      \hline \textbf{Name} & \textbf{Descriptor Name} & \textbf{Size of Message Digest (bytes)} \\
      \hline WHIRLPOOL & whirlpool\_desc & 64 \\
      \hline SHA3-512 & sha3\_512\_desc & 64 \\
      \hline SHA-512 & sha512\_desc & 64 \\
      \hline BLAKE2B-512 & blake2b\_512\_desc & 64 \\
      \hline SHA3-384 & sha3\_384\_desc & 48 \\
      \hline SHA-384 & sha384\_desc & 48 \\
      \hline RIPEMD-320 & rmd160\_desc & 40 \\
      \hline SHA-512/256 & sha512\_256\_desc & 32 \\
      \hline SHA3-256 & sha3\_256\_desc & 32 \\
      \hline SHA-256 & sha256\_desc & 32 \\
      \hline RIPEMD-256 & rmd160\_desc & 32 \\
      \hline BLAKE2S-256 & blake2s\_256\_desc & 32 \\
      \hline BLAKE2B-256 & blake2b\_256\_desc & 32 \\
      \hline SHA-512/224 & sha512\_224\_desc & 28 \\
      \hline SHA3-224 & sha3\_224\_desc & 28 \\
      \hline SHA-224 & sha224\_desc & 28 \\
      \hline BLAKE2S-224 & blake2s\_224\_desc & 28 \\
      \hline BLAKE2B-384 & blake2b\_384\_desc & 48 \\
      \hline TIGER-192 & tiger\_desc & 24 \\
      \hline SHA-1 & sha1\_desc & 20 \\
      \hline RIPEMD-160 & rmd160\_desc & 20 \\
      \hline BLAKE2S-160 & blake2s\_160\_desc & 20 \\
      \hline BLAKE2B-160 & blake2b\_160\_desc & 20 \\
      \hline RIPEMD-128 & rmd128\_desc & 16 \\
      \hline MD5 & md5\_desc & 16 \\
      \hline MD4 & md4\_desc & 16 \\
      \hline MD2 & md2\_desc & 16 \\
      \hline BLAKE2S-128 & blake2s\_128\_desc & 16 \\
      \hline
\end{tabular}
\end{center}
\caption{Built--In Software Hashes}
\end{figure}
\vfil

\mysection{Cipher Hash Construction}
\index{Cipher Hash Construction}
An addition to the suite of hash functions is the \textit{Cipher Hash Construction} or \textit{CHC} mode.  In this mode
applicable block ciphers (such as AES) can be turned into hash functions that other LTC functions can use.  In
particular this allows a cryptosystem to be designed using very few moving parts.

In order to use the CHC system the developer will have to take a few extra steps.  First the \textit{chc\_desc} hash
descriptor must be registered with register\_hash().  At this point the CHC hash cannot be used to hash
data.  While it is in the hash system you still have to tell the CHC code which cipher to use.  This is accomplished
via the chc\_register() function.

\index{chc\_register()}
\begin{verbatim}
int chc_register(int cipher);
\end{verbatim}

A cipher has to be registered with CHC (and also in the cipher descriptor tables with
register\_cipher()).  The chc\_register() function will bind a cipher to the CHC system.  Only one cipher can
be bound to the CHC hash at a time.  There are additional requirements for the system to work.

\begin{enumerate}
   \item The cipher must have a block size greater than 64--bits.
   \item The cipher must allow an input key the size of the block size.
\end{enumerate}

Example of using CHC with the AES block cipher.

\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
   int err;

   /* register cipher and hash */
   if (register_cipher(&aes_enc_desc) == -1) {
      printf("Could not register cipher\n");
      return EXIT_FAILURE;
   }
   if (register_hash(&chc_desc) == -1) {
      printf("Could not register hash\n");
      return EXIT_FAILURE;
   }

   /* start chc with AES */
   if ((err = chc_register(find_cipher("aes"))) != CRYPT_OK) {
      printf("Error binding AES to CHC: %s\n",
             error_to_string(err));
   }

   /* now you can use chc_hash in any LTC function
    * [aside from pkcs...] */
}
\end{verbatim}

\mysection{SHA3 SHAKE}
The SHA3 class of algorithms provides a special XOF (Extendable Output Functions) mode, called SHAKE.
SHAKE operates in 2 security configurations, 128bit or 256bit, and allows to generate message digests of an arbitrary length.

For further information see \url{https://en.wikipedia.org/wiki/SHA-3}

Example of using SHAKE256 with an arbitrary length output.

\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
   int err;
   hash_state state;
   const void* msg = "The quick brown fox jumps over the lazy dog";
   unsigned char output[345];

   if ((err = sha3_shake_init(&state, 256)) != CRYPT_OK) {
      printf("Could not init SHAKE256 (%s)\n", error_to_string(err));
      return EXIT_FAILURE;
   }
   if ((err = sha3_shake_process(&state, msg, strlen(msg))) != CRYPT_OK) {
      printf("Could not process SHAKE256 (%s)\n", error_to_string(err));
      return EXIT_FAILURE;
   }
   if ((err = sha3_shake_done(&state, output, sizeof(output))) != CRYPT_OK) {
      printf("Could not finish SHAKE256 (%s)\n", error_to_string(err));
      return EXIT_FAILURE;
   }
   return EXIT_SUCCESS;
}
\end{verbatim}

\mysection{Notice}
It is highly recommended that you \textbf{not} use the MD2, MD4, MD5, or SHA-1 hashes for the purposes of digital signatures or authentication codes.
These hashes are provided for completeness and they still can be used for the purposes of password hashing or one-way accumulators
(e.g. Yarrow).

The other hashes such as the SHA-2 (that includes SHA-512, SHA-512/384, SHA-384, SHA-512/256, SHA-256 and SHA-224) and TIGER-192 are still considered secure
for all purposes you would normally use a hash for.

\chapter{Checksum Functions}

\mysection{Preface}

The API for all checksum functions operate in mode: \textit{init} -- \textit{update} -- \textit{update} -- ... -- \textit{finish}.

The \textit{finish} functions allow to output a partial result if necessary.

\mysection{CRC-32 -- Cyclic redundancy check}

A Cyclic Redundancy Check is an error-detecting code, where LibTomCrypt implements CRC-32 with the polynomial \textit{0x04C11DB7}.

For further information see \url{https://en.wikipedia.org/wiki/Cyclic_redundancy_check}

\begin{verbatim}
void crc32_init(crc32_state *ctx);
void crc32_update(crc32_state *ctx, const unsigned char *input, unsigned long length);
void crc32_finish(crc32_state *ctx, void *hash, unsigned long size);
\end{verbatim}

\mysection{Adler-32}

Adler-32 is a checksum algorithm.

For further information see \url{https://en.wikipedia.org/wiki/Adler-32}.

\begin{verbatim}
void adler32_init(adler32_state *ctx);
void adler32_update(adler32_state *ctx, const unsigned char *input, unsigned long length);
void adler32_finish(adler32_state *ctx, void *hash, unsigned long size);
\end{verbatim}

\chapter{Message Authentication Codes}
\mysection{HMAC Protocol}
Thanks to Dobes Vandermeer, the library now includes support for hash based message authentication codes, or HMAC for short.  An HMAC
of a message is a keyed authentication code that only the owner of a private symmetric key will be able to verify.  The purpose is
to allow an owner of a private symmetric key to produce an HMAC on a message then later verify if it is correct.  Any impostor or
eavesdropper will not be able to verify the authenticity of a message.

The HMAC support works much like the normal hash functions except that the initialization routine requires you to pass a key
and its length.  The key is much like a key you would pass to a cipher.  That is, it is simply an array of octets stored in
unsigned characters.  The initialization routine is:
\index{hmac\_init()}
\begin{verbatim}
int hmac_init(         hmac_state *hmac,
                              int  hash,
              const unsigned char *key,
                    unsigned long  keylen);
\end{verbatim}
The \textit{hmac} parameter is the state for the HMAC code.  The \textit{hash} parameter is the index into the descriptor table of the hash you want
to use to authenticate the message.  The \textit{key} parameter is the pointer to the array of chars that make up the key.  The \textit{keylen} parameter is the
length (in octets) of the key you want to use to authenticate the message.  To send octets of a message through the HMAC system you must use the following function:
\index{hmac\_process()}
\begin{verbatim}
int hmac_process(         hmac_state *hmac,
                 const unsigned char *in,
                       unsigned long  inlen);
\end{verbatim}
\textit{hmac} is the HMAC state you are working with. \textit{in} is the array of octets to send into the HMAC process.  \textit{inlen} is the
number of octets to process.  Like the hash process routines, you can send the data in arbitrarily sized chunks. When you
are finished with the HMAC process you must call the following function to get the HMAC code:
\index{hmac\_done()}
\begin{verbatim}
int hmac_done(   hmac_state *hmac,
              unsigned char *out,
              unsigned long *outlen);
\end{verbatim}
The \textit{hmac} parameter is the HMAC state you are working with.  The \textit{out} parameter is the array of octets where the HMAC code should be stored.
You must set \textit{outlen} to the size of the destination buffer before calling this function.  It is updated with the length of the HMAC code
produced (depending on which hash was picked).  If \textit{outlen} is less than the size of the message digest (and ultimately
the HMAC code) then the HMAC code is truncated as per FIPS-198 specifications (e.g. take the first \textit{outlen} bytes).

There are two utility functions provided to make using HMACs easier to do.  They accept the key and information about the
message (file pointer, address in memory), and produce the HMAC result in one shot.  These are useful if you want to avoid
calling the three step process yourself.

\index{hmac\_memory()}
\begin{verbatim}
int hmac_memory(
                   int  hash,
   const unsigned char *key, unsigned long  keylen,
   const unsigned char *in,  unsigned long  inlen,
         unsigned char *out, unsigned long *outlen);
\end{verbatim}
This will produce an HMAC code for the array of octets in \textit{in} of length \textit{inlen}.  The index into the hash descriptor
table must be provided in \textit{hash}.  It uses the key from \textit{key} with a key length of \textit{keylen}.
The result is stored in the array of octets \textit{out} and the length in \textit{outlen}.  The value of \textit{outlen} must be set
to the size of the destination buffer before calling this function.  Similarly for files there is the  following function:
\index{hmac\_file()}
\begin{verbatim}
int hmac_file(
                   int  hash,
            const char *fname,
   const unsigned char *key, unsigned long  keylen,
         unsigned char *out, unsigned long *outlen);
\end{verbatim}
\textit{hash} is the index into the hash descriptor table of the hash you want to use.  \textit{fname} is the filename to process.
\textit{key} is the array of octets to use as the key of length \textit{keylen}.  \textit{out} is the array of octets where the
result should be stored.

To test if the HMAC code is working there is the following function:
\index{hmac\_test()}
\begin{verbatim}
int hmac_test(void);
\end{verbatim}
Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code.  Some example code for using the
HMAC system is given below.

\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
   int idx, err;
   hmac_state hmac;
   unsigned char key[16], dst[MAXBLOCKSIZE];
   unsigned long dstlen;

   /* register SHA-1 */
   if (register_hash(&sha1_desc) == -1) {
      printf("Error registering SHA1\n");
      return -1;
   }

   /* get index of SHA1 in hash descriptor table */
   idx = find_hash("sha1");

   /* we would make up our symmetric key in "key[]" here */

   /* start the HMAC */
   if ((err = hmac_init(&hmac, idx, key, 16)) != CRYPT_OK) {
      printf("Error setting up hmac: %s\n", error_to_string(err));
      return -1;
   }

   /* process a few octets */
   if((err = hmac_process(&hmac, "hello", 5) != CRYPT_OK) {
      printf("Error processing hmac: %s\n", error_to_string(err));
      return -1;
   }

   /* get result (presumably to use it somehow...) */
   dstlen = sizeof(dst);
   if ((err = hmac_done(&hmac, dst, &dstlen)) != CRYPT_OK) {
      printf("Error finishing hmac: %s\n", error_to_string(err));
      return -1;
   }
   printf("The hmac is %lu bytes long\n", dstlen);

   /* return */
   return 0;
}
\end{verbatim}
\end{small}

\mysection{OMAC Support}
\index{OMAC} \index{CMAC}
OMAC\footnote{\url{http://crypt.cis.ibaraki.ac.jp/omac/omac.html}}, which stands for \textit{One-Key CBC MAC} is an
algorithm which produces a Message Authentication Code (MAC) using only a block cipher such as AES.  Note:  OMAC has been standardized as
CMAC within NIST, for the purposes of this library OMAC and CMAC are synonymous.  From an API standpoint, the OMAC routines work much like the
HMAC routines.  Instead, in this case a cipher is used instead of a hash.

To start an OMAC state you call
\index{omac\_init()}
\begin{verbatim}
int omac_init(         omac_state *omac,
                              int  cipher,
              const unsigned char *key,
                    unsigned long  keylen);
\end{verbatim}
The \textit{omac} parameter is the state for the OMAC algorithm.  The \textit{cipher} parameter is the index into the cipher\_descriptor table
of the cipher\footnote{The cipher must have a 64 or 128 bit block size.  Such as CAST5, Blowfish, DES, AES, Twofish, etc.} you
wish to use.  The \textit{key} and \textit{keylen} parameters are the keys used to authenticate the data.

To send data through the algorithm call
\index{omac\_process()}
\begin{verbatim}
int omac_process(         omac_state *state,
                 const unsigned char *in,
                       unsigned long  inlen);
\end{verbatim}
This will send \textit{inlen} bytes from \textit{in} through the active OMAC state \textit{state}.  Returns \textbf{CRYPT\_OK} if the
function succeeds.  The function is not sensitive to the granularity of the data.  For example,

\begin{verbatim}
omac_process(&mystate, "hello",  5);
omac_process(&mystate, " world", 6);
\end{verbatim}

Would produce the same result as,

\begin{verbatim}
omac_process(&mystate, "hello world",  11);
\end{verbatim}

When you are done processing the message you can call the following to compute the message tag.

\index{omac\_done()}
\begin{verbatim}
int omac_done(   omac_state *state,
              unsigned char *out,
              unsigned long *outlen);
\end{verbatim}
Which will terminate the OMAC and output the \textit{tag} (MAC) to \textit{out}.  Note that unlike the HMAC and other code
\textit{outlen} can be smaller than the default MAC size (for instance AES would make a 16-byte tag).  Part of the OMAC
specification states that the output may be truncated.  So if you pass in $outlen = 5$ and use AES as your cipher than
the output MAC code will only be five bytes long.  If \textit{outlen} is larger than the default size it is set to the default
size to show how many bytes were actually used.

Similar to the HMAC code the file and memory functions are also provided.  To OMAC a buffer of memory in one shot use the
following function.

\index{omac\_memory()}
\begin{verbatim}
int omac_memory(
                    int  cipher,
    const unsigned char *key, unsigned long keylen,
    const unsigned char *in,  unsigned long inlen,
          unsigned char *out, unsigned long *outlen);
\end{verbatim}
This will compute the OMAC of \textit{inlen} bytes of \textit{in} using the key \textit{key} of length \textit{keylen} bytes and the cipher
specified by the \textit{cipher}'th entry in the cipher\_descriptor table.  It will store the MAC in \textit{out} with the same
rules as omac\_done.

To OMAC a file use
\index{omac\_file()}
\begin{verbatim}
int omac_file(
                    int  cipher,
    const unsigned char *key,      unsigned long keylen,
             const char *filename,
          unsigned char *out,      unsigned long *outlen);
\end{verbatim}

Which will OMAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes
and the cipher specified by the \textit{cipher}'th entry in the cipher\_descriptor table.  It will store the MAC in \textit{out} with
the same rules as omac\_done.

To test if the OMAC code is working there is the following function:
\index{omac\_test()}
\begin{verbatim}
int omac_test(void);
\end{verbatim}
Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code.  Some example code for using the
OMAC system is given below.

\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
   int idx, err;
   omac_state omac;
   unsigned char key[16], dst[MAXBLOCKSIZE];
   unsigned long dstlen;

   /* register Rijndael */
   if (register_cipher(&rijndael_desc) == -1) {
      printf("Error registering Rijndael\n");
      return -1;
   }

   /* get index of Rijndael in cipher descriptor table */
   idx = find_cipher("rijndael");

   /* we would make up our symmetric key in "key[]" here */

   /* start the OMAC */
   if ((err = omac_init(&omac, idx, key, 16)) != CRYPT_OK) {
      printf("Error setting up omac: %s\n", error_to_string(err));
      return -1;
   }

   /* process a few octets */
   if((err = omac_process(&omac, "hello", 5) != CRYPT_OK) {
      printf("Error processing omac: %s\n", error_to_string(err));
      return -1;
   }

   /* get result (presumably to use it somehow...) */
   dstlen = sizeof(dst);
   if ((err = omac_done(&omac, dst, &dstlen)) != CRYPT_OK) {
      printf("Error finishing omac: %s\n", error_to_string(err));
      return -1;
   }
   printf("The omac is %lu bytes long\n", dstlen);

   /* return */
   return 0;
}
\end{verbatim}
\end{small}

\mysection{PMAC Support}
The PMAC\footnote{J.Black, P.Rogaway, \textit{A Block--Cipher Mode of Operation for Parallelizable Message Authentication}}
protocol is another MAC algorithm that relies solely on a symmetric-key block cipher.  It uses essentially the same
API as the provided OMAC code.

A PMAC state is initialized with the following.

\index{pmac\_init()}
\begin{verbatim}
int pmac_init(         pmac_state *pmac,
                              int  cipher,
              const unsigned char *key,
                    unsigned long  keylen);
\end{verbatim}
Which initializes the \textit{pmac} state with the given \textit{cipher} and \textit{key} of length \textit{keylen} bytes.  The chosen cipher
must have a 64 or 128 bit block size (e.x. AES).

To MAC data simply send it through the process function.

\index{pmac\_process()}
\begin{verbatim}
int pmac_process(         pmac_state *state,
                 const unsigned char *in,
                       unsigned long  inlen);
\end{verbatim}
This will process \textit{inlen} bytes of \textit{in} in the given \textit{state}.  The function is not sensitive to the granularity of the
data.  For example,

\begin{verbatim}
pmac_process(&mystate, "hello",  5);
pmac_process(&mystate, " world", 6);
\end{verbatim}

Would produce the same result as,

\begin{verbatim}
pmac_process(&mystate, "hello world",  11);
\end{verbatim}

When a complete message has been processed the following function can be called to compute the message tag.

\index{pmac\_done()}
\begin{verbatim}
int pmac_done(   pmac_state *state,
              unsigned char *out,
              unsigned long *outlen);
\end{verbatim}
This will store up to \textit{outlen} bytes of the tag for the given \textit{state} into \textit{out}.  Note that if \textit{outlen} is larger
than the size of the tag it is set to the amount of bytes stored in \textit{out}.

Similar to the OMAC code the file and memory functions are also provided.  To PMAC a buffer of memory in one shot use the
following function.

\index{pmac\_memory()}
\begin{verbatim}
int pmac_memory(
                    int  cipher,
    const unsigned char *key, unsigned long  keylen,
    const unsigned char *in,  unsigned long  inlen,
          unsigned char *out, unsigned long *outlen);
\end{verbatim}
This will compute the PMAC of \textit{msglen} bytes of \textit{msg} using the key \textit{key} of length \textit{keylen} bytes, and the cipher
specified by the \textit{cipher}'th entry in the cipher\_descriptor table.  It will store the MAC in \textit{out} with the same
rules as pmac\_done().

To PMAC a file use
\index{pmac\_file()}
\begin{verbatim}
int pmac_file(
                    int  cipher,
    const unsigned char *key,      unsigned long keylen,
             const char *filename,
          unsigned char *out,      unsigned long *outlen);
\end{verbatim}

Which will PMAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes,
and the cipher specified by the \textit{cipher}'th entry in the cipher\_descriptor table.  It will store the MAC in \textit{out} with
the same rules as pmac\_done().

To test if the PMAC code is working there is the following function:
\index{pmac\_test()}
\begin{verbatim}
int pmac_test(void);
\end{verbatim}
Which returns {\bf CRYPT\_OK} if the code passes otherwise it returns an error code.

\mysection{Pelican MAC}
Pelican MAC is a new (experimental) MAC by the AES team that uses four rounds of AES as a \textit{mixing function}.  It achieves a very high
rate of processing and is potentially very secure.  It requires AES to be enabled to function.  You do not have to register\_cipher() AES first though
as it calls AES directly.

\index{pelican\_init()}
\begin{verbatim}
int pelican_init(      pelican_state *pelmac,
                 const unsigned char *key,
                       unsigned long  keylen);
\end{verbatim}
This will initialize the Pelican state with the given AES key.  Once this has been done you can begin processing data.

\index{pelican\_process()}
\begin{verbatim}
int pelican_process(      pelican_state *pelmac,
                    const unsigned char *in,
                          unsigned long  inlen);
\end{verbatim}
This will process \textit{inlen} bytes of \textit{in} through the Pelican MAC.  It's best that you pass in multiples of 16 bytes as it makes the
routine more efficient but you may pass in any length of text.  You can call this function as many times as required to process
an entire message.

\index{pelican\_done()}
\begin{verbatim}
int pelican_done(pelican_state *pelmac, unsigned char *out);
\end{verbatim}
This terminates a Pelican MAC and writes the 16--octet tag to \textit{out}.

\subsection{Example}

\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
   pelican_state pelstate;
   unsigned char key[32], tag[16];
   int           err;

   /* somehow initialize a key */

   /* initialize pelican mac */
   if ((err = pelican_init(&pelstate, /* the state */
                           key,       /* user key */
                           32         /* key length in octets */
                          )) != CRYPT_OK) {
      printf("Error initializing Pelican: %s",
              error_to_string(err));
      return EXIT_FAILURE;
   }

   /* MAC some data */
   if ((err = pelican_process(&pelstate,       /* the state */
                              "hello world",   /* data to mac */
                              11               /* length of data */
                              )) != CRYPT_OK) {
      printf("Error processing Pelican: %s",
             error_to_string(err));
      return EXIT_FAILURE;
   }

   /* Terminate the MAC */
   if ((err = pelican_done(&pelstate,/* the state */
                           tag       /* where to store the tag */
                           )) != CRYPT_OK) {
      printf("Error terminating Pelican: %s",
             error_to_string(err));
      return EXIT_FAILURE;
   }

   /* tag[0..15] has the MAC output now */

   return EXIT_SUCCESS;
}
\end{verbatim}

\mysection{XCBC-MAC}
As of LibTomCrypt v1.15, XCBC-MAC (RFC 3566) has been provided to support TLS encryption suites.  Like OMAC, it computes a message authentication code
by using a cipher in CBC mode.  It also uses a single key which it expands into the requisite three keys for the MAC function.  A XCBC--MAC state is
initialized with the following function:

\index{xcbc\_init()}
\begin{verbatim}
int xcbc_init(         xcbc_state *xcbc,
                              int  cipher,
              const unsigned char *key,
                    unsigned long  keylen);
\end{verbatim}

This will initialize the XCBC--MAC state \textit{xcbc}, with the key specified in \textit{key} of length \textit{keylen} octets.  The cipher indicated
by the \textit{cipher} index can be either a 64 or 128--bit block cipher.  This will return \textbf{CRYPT\_OK} on success.

\index{LTC\_XCBC\_PURE}
It is possible to use XCBC in a three key mode by OR'ing the value \textbf{LTC\_XCBC\_PURE} against the \textit{keylen} parameter.  In this mode, the key is
interpretted as three keys.  If the cipher has a block size of $n$ octets, the first key is then $keylen - 2n$ octets and is the encryption key.  The next
$2n$ octets are the $K_1$ and $K_2$ padding keys (used on the last block).  For example, to use AES--192 \textit{keylen} should be $24 + 2 \cdot 16 = 56$ octets.
The three keys are interpretted as if they were concatenated in the \textit{key} buffer.


To process data through XCBC--MAC use the following function:

\index{xcbc\_process()}
\begin{verbatim}
int xcbc_process(         xcbc_state *state,
                 const unsigned char *in,
                       unsigned long  inlen);
\end{verbatim}

This will add the message octets pointed to by \textit{in} of length \textit{inlen} to the XCBC--MAC state pointed to by \textit{state}.  Like the other MAC functions,
the granularity of the input is not important but the order is.  This will return \textbf{CRYPT\_OK} on success.

To compute the MAC tag value use the following function:

\index{xcbc\_done()}
\begin{verbatim}
int xcbc_done(   xcbc_state *state,
              unsigned char *out,
              unsigned long *outlen);
\end{verbatim}

This will retrieve the XCBC--MAC tag from the state pointed to by \textit{state}, and store it in the array pointed to by \textit{out}.  The \textit{outlen} parameter
specifies the maximum size of the destination buffer, and is updated to hold the final size of the tag when the function returns.  This will return \textbf{CRYPT\_OK} on success.

Helper functions are provided to make parsing memory buffers and files easier.  The following functions are provided:

\index{xcbc\_memory()}
\begin{verbatim}
int xcbc_memory(
                    int  cipher,
    const unsigned char *key, unsigned long  keylen,
    const unsigned char *in,  unsigned long  inlen,
          unsigned char *out, unsigned long *outlen);
\end{verbatim}
This will compute the XCBC--MAC of \textit{msglen} bytes of \textit{msg}, using the key \textit{key} of length \textit{keylen} bytes, and the cipher
specified by the \textit{cipher}'th entry in the cipher\_descriptor table.  It will store the MAC in \textit{out} with the same rules as xcbc\_done().

To xcbc a file use
\index{xcbc\_file()}
\begin{verbatim}
int xcbc_file(
                    int  cipher,
    const unsigned char *key,      unsigned long keylen,
             const char *filename,
          unsigned char *out,      unsigned long *outlen);
\end{verbatim}

Which will XCBC--MAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes, and the cipher
specified by the \textit{cipher}'th entry in the cipher\_descriptor table.  It will store the MAC in \textit{out} with the same rules as xcbc\_done().


To test XCBC--MAC for RFC 3566 compliance use the following function:

\index{xcbc\_test()}
\begin{verbatim}
int xcbc_test(void);
\end{verbatim}

This will return \textbf{CRYPT\_OK} on success.  This requires the AES or Rijndael descriptor be previously registered, otherwise, it will return
\textbf{CRYPT\_NOP}.

\mysection{F9--MAC}
The F9--MAC is yet another CBC--MAC variant proposed for the 3GPP standard.  Originally specified to be used with the KASUMI block cipher, it can also be used
with other ciphers.  For LibTomCrypt, the F9--MAC code can use any cipher.

\subsection{Usage Notice}
F9--MAC differs slightly from the other MAC functions in that it requires the caller to perform the final message padding.  The padding quite simply is a direction
bit followed by a 1 bit and enough zeros to make the message a multiple of the cipher block size.  If the message is byte aligned, the padding takes on the form of
a single 0x40 or 0xC0 byte followed by enough 0x00 bytes to make the message proper multiple.

If the user simply wants a MAC function (hint: use OMAC) padding with a single 0x40 byte should be sufficient for security purposes and still be reasonably compatible
with F9--MAC.

\subsection{F9--MAC Functions}
A F9--MAC state is initialized with the following function:
\index{f9\_init()}
\begin{verbatim}
int f9_init(           f9_state *f9,
                            int  cipher,
            const unsigned char *key,
                  unsigned long  keylen);
\end{verbatim}

This will initialize the F9--MAC state \textit{f9}, with the key specified in \textit{key} of length \textit{keylen} octets.  The cipher indicated
by the \textit{cipher} index can be either a 64 or 128--bit block cipher.  This will return \textbf{CRYPT\_OK} on success.

To process data through F9--MAC use the following function:
\index{f9\_process()}
\begin{verbatim}
int f9_process(           f9_state *state,
               const unsigned char *in,
                     unsigned long  inlen);
\end{verbatim}

This will add the message octets pointed to by \textit{in} of length \textit{inlen} to the F9--MAC state pointed to by \textit{state}.  Like the other MAC functions,
the granularity of the input is not important but the order is.  This will return \textbf{CRYPT\_OK} on success.

To compute the MAC tag value use the following function:

\index{f9\_done()}
\begin{verbatim}
int f9_done(     f9_state *state,
            unsigned char *out,
            unsigned long *outlen);
\end{verbatim}

This will retrieve the F9--MAC tag from the state pointed to by \textit{state}, and store it in the array pointed to by \textit{out}.  The \textit{outlen} parameter
specifies the maximum size of the destination buffer, and is updated to hold the final size of the tag when the function returns.  This will return
\textbf{CRYPT\_OK} on success.

Helper functions are provided to make parsing memory buffers and files easier.  The following functions are provided:

\index{f9\_memory()}
\begin{verbatim}
int f9_memory(
                    int  cipher,
    const unsigned char *key, unsigned long  keylen,
    const unsigned char *in,  unsigned long  inlen,
          unsigned char *out, unsigned long *outlen);
\end{verbatim}
This will compute the F9--MAC of \textit{msglen} bytes of \textit{msg}, using the key \textit{key} of length \textit{keylen} bytes, and the cipher
specified by the \textit{cipher}'th entry in the cipher\_descriptor table.  It will store the MAC in \textit{out} with the same rules as f9\_done().

To F9--MAC a file use
\index{f9\_file()}
\begin{verbatim}
int f9_file(
                    int  cipher,
    const unsigned char *key,      unsigned long keylen,
             const char *filename,
          unsigned char *out,      unsigned long *outlen);
\end{verbatim}

Which will F9--MAC the entire contents of the file specified by \textit{filename} using the key \textit{key} of length \textit{keylen} bytes, and the cipher
specified by the \textit{cipher}'th entry in the cipher\_descriptor table.  It will store the MAC in \textit{out} with the same rules as f9\_done().


To test f9--MAC for RFC 3566 compliance use the following function:

\index{f9\_test()}
\begin{verbatim}
int f9_test(void);
\end{verbatim}

This will return \textbf{CRYPT\_OK} on success.  This requires the AES or Rijndael descriptor be previously registered, otherwise, it will return
\textbf{CRYPT\_NOP}.

\mysection{Poly1305--MAC}

The Poly1305--MAC is a cryptographic message authentication code created by Daniel J. Bernstein.
More info at \url{https://en.wikipedia.org/wiki/Poly1305}.

A Poly1305--MAC state is initialized with the following function:
\index{poly1305\_init()}
\begin{verbatim}
int poly1305_init(     poly1305_state *st,
                  const unsigned char *key,
                        unsigned long  keylen);
\end{verbatim}
This will initialize the Poly1305--MAC state \textit{st}, with the key specified in \textit{key} of length \textit{keylen} octets (always 32).

To process data through Poly1305--MAC use the following function:
\index{poly1305\_process()}
\begin{verbatim}
int poly1305_process(     poly1305_state *st,
                     const unsigned char *in,
                           unsigned long  inlen);
\end{verbatim}

This will add the message octets pointed to by \textit{in} of length \textit{inlen} to the Poly1305--MAC state pointed to by \textit{st}.

To compute the MAC tag value use the following function:
\index{poly1305\_done()}
\begin{verbatim}
int poly1305_done(poly1305_state *st,
                   unsigned char *mac,
                   unsigned long *maclen);
\end{verbatim}

This will retrieve the Poly1305--MAC tag from the state pointed to by \textit{st}, and store it in the array pointed to by \textit{mac}.
The \textit{maclen} parameter specifies the maximum size of the destination buffer, and is updated to hold the final size of the tag when
the function returns.

Helper functions are provided to make parsing memory buffers and files easier. The following functions are provided:
\index{poly1305\_memory()}
\begin{verbatim}
int poly1305_memory(const unsigned char *key,
                          unsigned long  keylen,
                    const unsigned char *in,
                          unsigned long  inlen,
                          unsigned char *mac,
                          unsigned long *maclen);
\end{verbatim}
This will compute the Poly1305--MAC of \textit{inlen} bytes of \textit{in}, using the key \textit{key} of length \textit{keylen} bytes.
It will store the MAC in \textit{mac} with the same rules as poly1305\_done().

To Poly1305--MAC a file use
\index{poly1305\_file()}
\begin{verbatim}
int poly1305_file(         const char *fname,
                  const unsigned char *key,
                        unsigned long  keylen,
                        unsigned char *mac,
                        unsigned long *maclen);
\end{verbatim}

Which will Poly1305--MAC the entire contents of the file specified by \textit{fname} using the key \textit{key} of
length \textit{keylen} bytes. It will store the MAC in \textit{mac} with the same rules as poly1305\_done().

\mysection{BLAKE2s + BLAKE2b MAC}

The BLAKE2s and BLAKE2b are cryptographic message authentication code designed by Jean--Philippe Aumasson,
Samuel Neves, Zooko Wilcox-O'Hearn, and Christian Winnerlein. More info at \url{https://tools.ietf.org/html/rfc7693}.

A BLAKE2s/b--MAC state is initialized with the following function:
\index{blake2smac\_init()}
\begin{verbatim}
int blake2smac_init(blake2smac_state *st,
                       unsigned long  outlen,
                 const unsigned char *key,
                       unsigned long  keylen);
\end{verbatim}
\index{blake2bmac\_init()}
\begin{verbatim}
int blake2bmac_init(blake2smac_state *st,
                       unsigned long  outlen,
                 const unsigned char *key,
                       unsigned long  keylen);
\end{verbatim}
This will initialize the BLAKE2s/b--MAC state \textit{st}, with the key specified in \textit{key} of length \textit{keylen} octets (up to 64).
The \textit{outlen} specifies the size of the final tag (up to 64 octets).

To process data through BLAKE2s/b--MAC use the following function:
\index{blake2smac\_process()}
\begin{verbatim}
int blake2smac_process(   blake2smac_state *st,
                       const unsigned char *in,
                             unsigned long  inlen);
\end{verbatim}
\index{blake2bmac\_process()}
\begin{verbatim}
int blake2bmac_process(   blake2bmac_state *st,
                       const unsigned char *in,
                             unsigned long  inlen);
\end{verbatim}

This will add the message octets pointed to by \textit{in} of length \textit{inlen} to the BLAKE2s/b--MAC state pointed to by \textit{st}.

To compute the MAC tag value use the following function:
\index{blake2smac\_done()}
\begin{verbatim}
int blake2smac_done(blake2smac_state *st,
                       unsigned char *mac,
                       unsigned long *maclen);
\end{verbatim}
\index{blake2bmac\_done()}
\begin{verbatim}
int blake2bmac_done(blake2bmac_state *st,
                       unsigned char *mac,
                       unsigned long *maclen);
\end{verbatim}

This will retrieve the BLAKE2s/b--MAC tag from the state pointed to by \textit{st}, and store it in the array pointed to by \textit{mac}.
The \textit{maclen} parameter specifies the maximum size of the destination buffer, and is updated to hold the final size of the tag when
the function returns.

Helper functions are provided to make parsing memory buffers and files easier. The following functions are provided:
\index{blake2smac\_memory()}
\begin{verbatim}
int blake2smac_memory(const unsigned char *key,
                            unsigned long  keylen,
                      const unsigned char *in,
                            unsigned long  inlen,
                            unsigned char *mac,
                            unsigned long *maclen);
\end{verbatim}
\index{blake2bmac\_memory()}
\begin{verbatim}
int blake2bmac_memory(const unsigned char *key,
                            unsigned long  keylen,
                      const unsigned char *in,
                            unsigned long  inlen,
                            unsigned char *mac,
                            unsigned long *maclen);
\end{verbatim}
This will compute the BLAKE2s/b--MAC of \textit{inlen} bytes of \textit{in}, using the key \textit{key} of length \textit{keylen} bytes.
It will store the MAC in \textit{mac} with the same rules as blake2smac\_done().

To BLAKE2s/b--MAC a file use
\index{blake2smac\_file()}
\begin{verbatim}
int blake2smac_file(         const char *fname,
                    const unsigned char *key,
                          unsigned long  keylen,
                          unsigned char *mac,
                          unsigned long *maclen);
\end{verbatim}
\index{blake2bmac\_file()}
\begin{verbatim}
int blake2bmac_file(         const char *fname,
                    const unsigned char *key,
                          unsigned long  keylen,
                          unsigned char *mac,
                          unsigned long *maclen);
\end{verbatim}

Which will BLAKE2s/b--MAC the entire contents of the file specified by \textit{fname} using the key \textit{key} of
length \textit{keylen} bytes. It will store the MAC in \textit{mac} with the same rules as blake2smac\_done().

\chapter{Pseudo-Random Number Generators}
\mysection{Core Functions}
The library provides an array of core functions for Pseudo-Random Number Generators (PRNGs) as well.  A cryptographic PRNG is
used to expand a shorter bit string into a longer bit string.  PRNGs are used wherever random data is required such as Public Key (PK)
key generation.  There is a universal structure called \textit{prng\_state}.  To initialize a PRNG call:
\index{PRNG start}
\begin{verbatim}
int XXX_start(prng_state *prng);
\end{verbatim}

This will setup the PRNG for future use and not seed it.  In order for the PRNG to be cryptographically useful you must give it
entropy.  Ideally you'd have some OS level source to tap like in UNIX.  To add entropy to the PRNG call:
\index{PRNG add\_entropy}
\begin{verbatim}
int XXX_add_entropy(const unsigned char *in,
                          unsigned long  inlen,
                             prng_state *prng);
\end{verbatim}
Which returns {\bf CRYPT\_OK} if the entropy was accepted.  Once you think you have enough entropy you call another
function to put the entropy into action.
\index{PRNG ready}
\begin{verbatim}
int XXX_ready(prng_state *prng);
\end{verbatim}

Which returns {\bf CRYPT\_OK} if it is ready.  Finally to actually read bytes call:
\index{PRNG read}
\begin{verbatim}
unsigned long XXX_read(unsigned char *out,
                       unsigned long  outlen,
                          prng_state *prng);
\end{verbatim}

Which returns the number of bytes read from the PRNG.  When you are finished with a PRNG state you call
the following.

\index{PRNG done}
\begin{verbatim}
void XXX_done(prng_state *prng);
\end{verbatim}

This will terminate a PRNG state and free any memory (if any) allocated.  To export a PRNG state
so that you can later resume the PRNG call the following.

\index{PRNG export}
\begin{verbatim}
int XXX_export(unsigned char *out,
               unsigned long *outlen,
                  prng_state *prng);
\end{verbatim}

This will write a \textit{PRNG state} to the buffer \textit{out} of length \textit{outlen} bytes.  The idea of
the export is meant to be used as a \textit{seed file}.  That is, when the program starts up there will not likely
be that much entropy available.   To import a state to seed a PRNG call the following function.

\index{PRNG import}
\begin{verbatim}
int XXX_import(const unsigned char *in,
                     unsigned long  inlen,
                        prng_state *prng);
\end{verbatim}

This will call the start and add\_entropy functions of the given PRNG.  It will use the state in
\textit{in} of length \textit{inlen} as the initial seed.  You must pass the same seed length as was exported
by the corresponding export function.

Note that importing a state will not \textit{resume} the PRNG from where it left off.  That is, if you export
a state, emit (say) 8 bytes and then import the previously exported state the next 8 bytes will not
specifically equal the 8 bytes you generated previously.

When a program is first executed the normal course of operation is:

\begin{enumerate}
   \item Gather entropy from your sources for a given period of time or number of events.
   \item Start, use your entropy via add\_entropy and ready the PRNG yourself.
\end{enumerate}

When your program is finished you simply call the export function and save the state to a medium (disk,
flash memory, etc).  The next time your application starts up you can detect the state, feed it to the
import function and go on your way.  It is ideal that (as soon as possible) after start up you export a
fresh state.  This helps in the case that the program aborts or the machine is powered down without
being given a chance to exit properly.

Note that even if you have a state to import it is important to add new entropy to the state.  However,
there is less pressure to do so.

To test a PRNG for operational conformity call the following functions.

\index{PRNG test}
\begin{verbatim}
int XXX_test(void);
\end{verbatim}

This will return \textbf{CRYPT\_OK} if PRNG is operating properly.

\subsection{Remarks}

It is possible to be adding entropy and reading from a PRNG at the same time.  For example, if you first seed the PRNG
and call ready() you can now read from it.  You can also keep adding new entropy to it.  The new entropy will not be used
in the PRNG until ready() is called again.  This allows the PRNG to be used and re-seeded at the same time.  No real error
checking is guaranteed to see if the entropy is sufficient, or if the PRNG is even in a ready state before reading.

\subsection{Example}
Below is a simple snippet to read 10 bytes from Yarrow.  It is important to note that this snippet is {\bf NOT} secure since
the entropy added is not random.

\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
   prng_state prng;
   unsigned char buf[10];
   int err;

   /* start it */
   if ((err = yarrow_start(&prng)) != CRYPT_OK) {
      printf("Start error: %s\n", error_to_string(err));
   }
   /* add entropy */
   if ((err = yarrow_add_entropy("hello world", 11, &prng))
       != CRYPT_OK) {
      printf("Add_entropy error: %s\n", error_to_string(err));
   }
   /* ready and read */
   if ((err = yarrow_ready(&prng)) != CRYPT_OK) {
      printf("Ready error: %s\n", error_to_string(err));
   }
   printf("Read %lu bytes from yarrow\n",
          yarrow_read(buf, sizeof(buf), &prng));
   return 0;
}
\end{verbatim}

\mysection{PRNG Descriptors}
\index{PRNG Descriptor}
PRNGs have descriptors that allow plugin driven functions to be created using PRNGs. The plugin descriptors are stored in the structure \textit{prng\_descriptor}.  The
format of an element is:
\begin{verbatim}
struct _prng_descriptor {
    char *name;
    int  export_size;    /* size in bytes of exported state */

    int (*start)      (prng_state *);

    int (*add_entropy)(const unsigned char *, unsigned long,
                       prng_state *);

    int (*ready)      (prng_state *);

    unsigned long (*read)(unsigned char *, unsigned long len,
                          prng_state *);

    void (*done)(prng_state *);

    int (*pexport)(unsigned char *, unsigned long *, prng_state *);

    int (*pimport)(const unsigned char *, unsigned long, prng_state *);

    int (*test)(void);
};
\end{verbatim}

To find a PRNG in the descriptor table the following function can be used:
\index{find\_prng()}
\begin{verbatim}
int find_prng(const char *name);
\end{verbatim}
This will search the PRNG descriptor table for the PRNG named \textit{name}.  It will return -1 if the PRNG is not found, otherwise, it returns
the index into the descriptor table.

Just like the ciphers and hashes, you must register your prng before you can use it.  The two functions provided work exactly as those for the cipher registry functions.
They are the following:
\index{register\_prng()} \index{unregister\_prng()}
\begin{verbatim}
int register_prng(const struct _prng_descriptor *prng);
int unregister_prng(const struct _prng_descriptor *prng);
\end{verbatim}

The register function will register the PRNG, and return the index into the table where it was placed (or -1 for error).  It will avoid registering the same
descriptor twice, and will return the index of the current placement in the table if the caller attempts to register it more than once.  The unregister function
will return \textbf{CRYPT\_OK} if the PRNG was found and removed.  Otherwise, it returns \textbf{CRYPT\_ERROR}.

\subsection{PRNGs Provided}
\begin{figure}[H]
\begin{center}
\begin{small}
\begin{tabular}{|c|c|l|}
\hline \textbf{Name} & \textbf{Descriptor} & \textbf{Usage} \\
\hline ChaCha20 & chacha20\_prng\_desc & Stream Cipher PRNG (recommended, fast) \\
\hline Fortuna & fortuna\_desc & Fast long-term PRNG (recommended, secure) \\
\hline RC4 & rc4\_desc & Stream Cipher PRNG \\
\hline SOBER-128 & sober128\_desc & Stream Cipher PRNG \\
\hline sprng & sprng\_desc & Secure PRNG using the System RNG \\
\hline Yarrow & yarrow\_desc & Fast short-term PRNG \\
\hline
\end{tabular}
\end{small}
\end{center}
\caption{List of Provided PRNGs}
\end{figure}

\subsubsection{Yarrow}
Yarrow is fast PRNG meant to collect an unspecified amount of entropy from sources
(keyboard, mouse, interrupts, etc), and produce an unbounded string of random bytes.

\textit{Note:} This PRNG is still secure for most tasks but is no longer recommended.  Users
should use Fortuna or ChaCha20 instead.

\subsubsection{Fortuna}

Fortuna is a fast attack tolerant and more thoroughly designed PRNG suitable for long term
usage.  It is faster than the default implementation of Yarrow\footnote{Yarrow has been implemented
to work with most cipher and hash combos based on which you have chosen to build into the library.} while
providing more security.

Fortuna is slightly less flexible than Yarrow in the sense that it only works with the AES block cipher
and SHA--256 hash function.  Technically, Fortuna will work with any block cipher that accepts a 256--bit
key, and any hash that produces at least a 256--bit output.  However, to make the implementation simpler
it has been fixed to those choices.

Fortuna is more secure than Yarrow in the sense that attackers who learn parts of the entropy being
added to the PRNG learn far less about the state than that of Yarrow.  Without getting into too many
details Fortuna has the ability to recover from state determination attacks where the attacker starts
to learn information from the PRNGs output about the internal state.  Yarrow on the other hand, cannot
recover from that problem until new entropy is added to the pool and put to use through the ready() function.

For detailed information on how the algorithm works and what you have to do to maintain the secure state
get a copy of the book\footnote{Niels Ferguson and Bruce Schneier, Practical Cryptography. ISBN 0-471-22357-3.} or
read the paper online\footnote{\url{https://www.schneier.com/academic/paperfiles/fortuna.pdf} [Accessed on 7th Dec. 2017]}.

\subsubsection{RC4}

RC4 is an old stream cipher that can also double duty as a PRNG in a pinch.  You key RC4 by
calling add\_entropy(), and setup the key by calling ready().

You really should not use RC4 for cryptographical purposes, it's broken.

\subsubsection{SOBER-128}

SOBER--128 is a stream cipher designed by the QUALCOMM Australia team.  Like RC4, you key it by
calling add\_entropy().  There is no need to call ready() for this PRNG as it does not do anything.

Note: this cipher has several oddities about how it operates.  The first call to add\_entropy() sets the cipher's key.
Every other time call to the add\_entropy() function sets the cipher's IV variable.  The IV mechanism allows you to
encrypt several messages with the same key, and not re--use the same key material.

Unlike Yarrow and Fortuna, all of the entropy (and hence security) of this algorithm rests in the data
you pass it on the \textbf{first} call to add\_entropy().  All buffers sent to add\_entropy() must have a length
that is a multiple of four bytes.

Like RC4, the output of SOBER--128 is XOR'ed against the buffer you provide it.  In this manner, you can use
sober128\_read() as an encrypt (and decrypt) function.

Since SOBER--128 has a fixed keying scheme, and is very fast (faster than RC4) the ideal usage of SOBER-128 is to
key it from the output of Fortuna (or Yarrow), and use it to encrypt messages.  It is also ideal for
simulations which need a high quality (and fast) stream of bytes.

\subsubsection{ChaCha20}

ChaCha20 is a fast stream cipher built on a pseudorandom function designed by Daniel J. Bernstein.
It can also double duty as a PRNG.

It is recommended to use 40 bytes of truly random bytes for initialization.

The implementation supports adding entropy via the add\_entropy() function while already being operational.

\subsubsection{Example Usage}
\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
   prng_state prng;
   unsigned char buf[32];
   int err;

   if ((err = rc4_start(&prng)) != CRYPT_OK) {
      printf("RC4 init error: %s\n", error_to_string(err));
      exit(-1);
   }

   /* use "key" as the key */
   if ((err = rc4_add_entropy("key", 3, &prng)) != CRYPT_OK) {
      printf("RC4 add entropy error: %s\n", error_to_string(err));
      exit(-1);
   }

   /* setup RC4 for use */
   if ((err = rc4_ready(&prng)) != CRYPT_OK) {
      printf("RC4 ready error: %s\n", error_to_string(err));
      exit(-1);
   }

   /* encrypt buffer */
   strcpy(buf,"hello world");
   if (rc4_read(buf, 11, &prng) != 11) {
      printf("RC4 read error\n");
      exit(-1);
   }
   return 0;
}
\end{verbatim}
\end{small}
To decrypt you have to do the exact same steps.

\mysection{The Secure RNG}
\index{Secure RNG}
An RNG is related to a PRNG in many ways, except that it does not expand a smaller seed to get the data.  They generate their random bits
by performing some computation on fresh input bits.  Possibly the hardest thing to get correctly in a cryptosystem is the
PRNG.  Computers are deterministic that try hard not to stray from pre--determined paths.  This makes gathering entropy needed to seed a PRNG
a hard task.

There is one small function that may help on certain platforms:
\index{rng\_get\_bytes()}
\begin{verbatim}
unsigned long rng_get_bytes(
    unsigned char *buf,
    unsigned long  len,
    void         (*callback)(void));
\end{verbatim}

Which will try one of three methods of getting random data.  The first is to open the popular \textit{/dev/random} device which
on most *NIX platforms provides cryptographic random bits\footnote{This device is available in Windows through the Cygwin compiler suite.  It emulates \textit{/dev/random} via the Microsoft CSP.}.
The second method is to try the Microsoft Cryptographic Service Provider, and read the RNG.  The third method is an ANSI C
clock drift method that is also somewhat popular but gives bits of lower entropy.  The \textit{callback} parameter is a pointer to a function that returns void.  It is
used when the slower ANSI C RNG must be used so the calling application can still work.  This is useful since the ANSI C RNG has a throughput of roughly three
bytes a second.  The callback pointer may be set to {\bf NULL} to avoid using it if you do not want to.  The function returns the number of bytes actually read from
any RNG source.  There is a function to help setup a PRNG as well:
\index{rng\_make\_prng()}
\begin{verbatim}
int rng_make_prng(       int  bits,
                         int  wprng,
                  prng_state *prng,
                       void (*callback)(void));
\end{verbatim}
This will try to initialize the prng with a state of at least \textit{bits} of entropy.  The \textit{callback} parameter works much like
the callback in \textit{rng\_get\_bytes()}.  It is highly recommended that you use this function to setup your PRNGs unless you have a
platform where the RNG does not work well.  Example usage of this function is given below:

\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
   ecc_key mykey;
   prng_state prng;
   int err;

   /* register yarrow */
   if (register_prng(&yarrow_desc) == -1) {
      printf("Error registering Yarrow\n");
      return -1;
   }

   /* setup the PRNG */
   if ((err = rng_make_prng(128, find_prng("yarrow"), &prng, NULL))
       != CRYPT_OK) {
      printf("Error setting up PRNG, %s\n", error_to_string(err));
      return -1;
   }

   /* make a 192-bit ECC key */
   if ((err = ecc_make_key(&prng, find_prng("yarrow"), 24, &mykey))
       != CRYPT_OK) {
      printf("Error making key: %s\n", error_to_string(err));
      return -1;
   }
   return 0;
}
\end{verbatim}
\end{small}

\subsection{The Secure PRNG Interface}
\index{sprng\_desc}
It is possible to access the secure RNG through the PRNG interface, and in turn use it within dependent functions such
as the PK API.  This simplifies the cryptosystem on platforms where the secure RNG is fast.  The secure PRNG never
requires to be started, that is you need not call the start, add\_entropy, or ready functions.  For example, consider
the previous example using this PRNG.

\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
   ecc_key mykey;
   int err;

   /* register SPRNG */
   if (register_prng(&sprng_desc) == -1) {
      printf("Error registering SPRNG\n");
      return -1;
   }

   /* make a 192-bit ECC key */
   if ((err = ecc_make_key(NULL, find_prng("sprng"), 24, &mykey))
       != CRYPT_OK) {
      printf("Error making key: %s\n", error_to_string(err));
      return -1;
   }
   return 0;
}
\end{verbatim}
\end{small}

\chapter{RSA Public Key Cryptography}

\mysection{Introduction}
RSA wrote the PKCS \#1 specifications which detail RSA Public Key Cryptography.  In the specifications are
padding algorithms for encryption and signatures.  The standard includes the \textit{v1.5} and \textit{v2.1} algorithms.
To simplify matters a little the v2.1 encryption and signature padding algorithms are called OAEP and PSS respectively.

\mysection{PKCS \#1 Padding}
PKCS \#1 v1.5 padding is so simple that both signature and encryption padding are performed by the same function.  Note: the
signature padding does \textbf{not} include the ASN.1 padding required.  That is performed by the rsa\_sign\_hash\_ex() function
documented later on in this chapter.

\subsection{PKCS \#1 v1.5 Encoding}
The following function performs PKCS \#1 v1.5 padding:
\index{pkcs\_1\_v1\_5\_encode()}
\begin{verbatim}
int pkcs_1_v1_5_encode(
    const unsigned char *msg,
          unsigned long  msglen,
                    int  block_type,
          unsigned long  modulus_bitlen,
             prng_state *prng,
                    int  prng_idx,
          unsigned char *out,
          unsigned long *outlen);
\end{verbatim}

This will encode the message pointed to by \textit{msg} of length \textit{msglen} octets.  The \textit{block\_type} parameter must be set to
\textbf{LTC\_PKCS\_1\_EME} to perform encryption padding.  It must be set to \textbf{LTC\_PKCS\_1\_EMSA} to perform signature padding.  The \textit{modulus\_bitlen}
parameter indicates the length of the modulus in bits.  The padded data is stored in \textit{out} with a length of \textit{outlen} octets.  The output will not be
longer than the modulus which helps allocate the correct output buffer size.

Only encryption padding requires a PRNG.  When performing signature padding the \textit{prng\_idx} parameter may be left to zero as it is not checked for validity.

\subsection{PKCS \#1 v1.5 Decoding}
The following function performs PKCS \#1 v1.5 de--padding:
\index{pkcs\_1\_v1\_5\_decode()}
\begin{verbatim}
int pkcs_1_v1_5_decode(
    const unsigned char *msg,
          unsigned long  msglen,
                    int  block_type,
          unsigned long  modulus_bitlen,
          unsigned char *out,
          unsigned long *outlen,
                    int *is_valid);
\end{verbatim}
\index{LTC\_PKCS\_1\_EME} \index{LTC\_PKCS\_1\_EMSA}
This will remove the PKCS padding data pointed to by \textit{msg} of length \textit{msglen}.  The decoded data is stored in \textit{out} of length
\textit{outlen}.  If the padding is valid, a 1 is stored in \textit{is\_valid}, otherwise, a 0 is stored.  The \textit{block\_type} parameter must be set to either
\textbf{LTC\_PKCS\_1\_EME} or \textbf{LTC\_PKCS\_1\_EMSA} depending on whether encryption or signature padding is being removed.

\mysection{PKCS \#1 v2.1 Encryption}
PKCS \#1 RSA Encryption amounts to OAEP padding of the input message followed by the modular exponentiation.  As far as this portion of
the library is concerned we are only dealing with th OAEP padding of the message.

\subsection{OAEP Encoding}

The following function performs PKCS \#1 v2.1 encryption padding:

\index{pkcs\_1\_oaep\_encode()}
\begin{alltt}
int pkcs_1_oaep_encode(
    const unsigned char *msg,
          unsigned long  msglen,
    const unsigned char *lparam,
          unsigned long  lparamlen,
          unsigned long  modulus_bitlen,
             prng_state *prng,
                    int  prng_idx,
                    int  hash_idx,
          unsigned char *out,
          unsigned long *outlen);
\end{alltt}

This accepts \textit{msg} as input of length \textit{msglen} which will be OAEP padded.  The \textit{lparam} variable is an additional system specific
tag that can be applied to the encoding.  This is useful to identify which system encoded the message.  If no variance is desired then
\textit{lparam} can be set to \textbf{NULL}.

OAEP encoding requires the length of the modulus in bits in order to calculate the size of the output.  This is passed as the parameter
\textit{modulus\_bitlen}.  \textit{hash\_idx} is the index into the hash descriptor table of the hash desired.  PKCS \#1 allows any hash to be
used but both the encoder and decoder must use the same hash in order for this to succeed.  The size of hash output affects the maximum
 sized input message.  \textit{prng\_idx} and \textit{prng} are the random number generator arguments required to randomize the padding process.
The padded message is stored in \textit{out} along with the length in \textit{outlen}.

If $h$ is the length of the hash and $m$ the length of the modulus (both in octets) then the maximum payload for \textit{msg} is
$m - 2h - 2$.  For example, with a $1024$--bit RSA key and SHA--1 as the hash the maximum payload is $86$ bytes.

Note that when the message is padded it still has not been RSA encrypted.  You must pass the output of this function to
rsa\_exptmod() to encrypt it.

\subsection{OAEP Decoding}

\index{pkcs\_1\_oaep\_decode()}
\begin{alltt}
int pkcs_1_oaep_decode(
    const unsigned char *msg,
          unsigned long  msglen,
    const unsigned char *lparam,
          unsigned long  lparamlen,
          unsigned long  modulus_bitlen,
                    int  hash_idx,
          unsigned char *out,
          unsigned long *outlen,
                    int *res);
\end{alltt}

This function decodes an OAEP encoded message and outputs the original message that was passed to the OAEP encoder.  \textit{msg} is the
output of pkcs\_1\_oaep\_encode() of length \textit{msglen}.  \textit{lparam} is the same system variable passed to the OAEP encoder.  If it does not
match what was used during encoding this function will not decode the packet.  \textit{modulus\_bitlen} is the size of the RSA modulus in bits
and must match what was used during encoding.  Similarly the \textit{hash\_idx} index into the hash descriptor table must match what was used
during encoding.

If the function succeeds it decodes the OAEP encoded message into \textit{out} of length \textit{outlen} and stores a
$1$ in \textit{res}.  If the packet is invalid it stores $0$ in \textit{res} and if the function fails for another reason
it returns an error code.

\mysection{PKCS \#1 Digital Signatures}

\subsection{PSS Encoding}
PSS encoding is the second half of the PKCS \#1 standard which is padding to be applied to messages that are signed.

\index{pkcs\_1\_pss\_encode()}
\begin{alltt}
int pkcs_1_pss_encode(
    const unsigned char *msghash,
          unsigned long  msghashlen,
          unsigned long  saltlen,
             prng_state *prng,
                    int  prng_idx,
                    int  hash_idx,
          unsigned long  modulus_bitlen,
          unsigned char *out,
          unsigned long *outlen);
\end{alltt}

This function assumes the message to be PSS encoded has previously been hashed.  The input hash \textit{msghash} is of length
\textit{msghashlen}.  PSS allows a variable length random salt (it can be zero length) to be introduced in the signature process.
\textit{hash\_idx} is the index into the hash descriptor table of the hash to use.  \textit{prng\_idx} and \textit{prng} are the random
number generator information required for the salt.

Similar to OAEP encoding \textit{modulus\_bitlen} is the size of the RSA modulus (in bits).  It limits the size of the salt.  If $m$ is the length
of the modulus $h$ the length of the hash output (in octets) then there can be $m - h - 2$ bytes of salt.

This function does not actually sign the data it merely pads the hash of a message so that it can be processed by rsa\_exptmod().

\subsection{PSS Decoding}

To decode a PSS encoded signature block you have to use the following.

\index{pkcs\_1\_pss\_decode()}
\begin{alltt}
int pkcs_1_pss_decode(
    const unsigned char *msghash,
          unsigned long  msghashlen,
    const unsigned char *sig,
          unsigned long  siglen,
          unsigned long  saltlen,
                    int  hash_idx,
          unsigned long  modulus_bitlen,
                    int *res);
\end{alltt}
This will decode the PSS encoded message in \textit{sig} of length \textit{siglen} and compare it to values in \textit{msghash} of length
\textit{msghashlen}.  If the block is a valid PSS block and the decoded hash equals the hash supplied \textit{res} is set to non--zero.  Otherwise,
it is set to zero.  The rest of the parameters are as in the PSS encode call.

It's important to use the same \textit{saltlen} and hash for both encoding and decoding as otherwise the procedure will not work.

\mysection{RSA Key Operations}
\subsection{Background}

RSA is a public key algorithm that is based on the inability to find the \textit{e-th} root modulo a composite of unknown
factorization.  Normally the difficulty of breaking RSA is associated with the integer factoring problem but they are
not strictly equivalent.

The system begins with with two primes $p$ and $q$ and their product $N = pq$.  The order or \textit{Euler totient} of the
multiplicative sub-group formed modulo $N$ is given as $\phi(N) = (p - 1)(q - 1)$ which can be reduced to
$\mbox{lcm}(p - 1, q - 1)$.  The public key consists of the composite $N$ and some integer $e$ such that
$\mbox{gcd}(e, \phi(N)) = 1$.  The private key consists of the composite $N$ and the inverse of $e$ modulo $\phi(N)$
often simply denoted as $de \equiv 1\mbox{ }(\mbox{mod }\phi(N))$.

A person who wants to encrypt with your public key simply forms an integer (the plaintext) $M$ such that
$1 < M < N-2$ and computes the ciphertext $C = M^e\mbox{ }(\mbox{mod }N)$.  Since finding the inverse exponent $d$
given only $N$ and $e$ appears to be intractable only the owner of the private key can decrypt the ciphertext and compute
$C^d \equiv \left (M^e \right)^d \equiv M^1 \equiv M\mbox{ }(\mbox{mod }N)$.  Similarly the owner of the private key
can sign a message by \textit{decrypting} it.  Others can verify it by \textit{encrypting} it.

Currently RSA is a difficult system to cryptanalyze provided that both primes are large and not close to each other.
Ideally $e$ should be larger than $100$ to prevent direct analysis.  For example, if $e$ is three and you do not pad
the plaintext to be encrypted than it is possible that $M^3 < N$ in which case finding the cube-root would be trivial.
The most often suggested value for $e$ is $65537$ since it is large enough to make such attacks impossible and also well
designed for fast exponentiation (requires 16 squarings and one multiplication).

It is important to pad the input to RSA since it has particular mathematical structure.  For instance
$M_1^dM_2^d = (M_1M_2)^d$ which can be used to forge a signature.  Suppose $M_3 = M_1M_2$ is a message you want
to have a forged signature for.  Simply get the signatures for $M_1$ and $M_2$ on their own and multiply the result
together.  Similar tricks can be used to deduce plaintexts from ciphertexts.  It is important not only to sign
the hash of documents only but also to pad the inputs with data to remove such structure.

\subsection{RSA Key Generation}

For RSA routines a single \textit{rsa\_key} structure is used.  To make a new RSA key call:
\index{rsa\_make\_key()}
\begin{verbatim}
int rsa_make_key(prng_state *prng,
                        int  wprng,
                        int  size,
                       long  e,
                    rsa_key *key);
\end{verbatim}

Where \textit{wprng} is the index into the PRNG descriptor array.  The \textit{size} parameter is the size in bytes of the RSA modulus desired.
The \textit{e} parameter is the encryption exponent desired, typical values are 3, 17, 257 and 65537.  Stick with 65537 since it is big enough to prevent
trivial math attacks, and not super slow.  The \textit{key} parameter is where the constructed key is placed.  All keys must be at
least 128 bytes, and no more than 512 bytes in size (\textit{that is from 1024 to 4096 bits}).

\index{rsa\_free()}
Note: the \textit{rsa\_make\_key()} function allocates memory at run--time when you make the key.  Make sure to call
\textit{rsa\_free()} (see below) when you are finished with the key.  If \textit{rsa\_make\_key()} fails it will automatically
free the memory allocated.

\index{PK\_PRIVATE} \index{PK\_PUBLIC}
There are two types of RSA keys.  The types are {\bf PK\_PRIVATE} and {\bf PK\_PUBLIC}.  The first type is a private
RSA key which includes the CRT parameters\footnote{As of v0.99 the PK\_PRIVATE\_OPTIMIZED type has been deprecated, and has been replaced by the
PK\_PRIVATE type.} in the form of a RSAPrivateKey (PKCS \#1 compliant).  The second type, is a public RSA key which only includes the modulus and public exponent.
It takes the form of a RSAPublicKey (PKCS \#1 compliant).

\subsection{RSA Exponentiation}
To do raw work with the RSA function, that is without padding, use the following function:
\index{rsa\_exptmod()}
\begin{verbatim}
int rsa_exptmod(const unsigned char *in,
                      unsigned long  inlen,
                      unsigned char *out,
                      unsigned long *outlen,
                                int  which,
                            rsa_key *key);
\end{verbatim}
This will load the bignum from \textit{in} as a big endian integer in the format PKCS \#1 specifies, raises it to either \textit{e} or \textit{d} and stores the result
in \textit{out} and the size of the result in \textit{outlen}. \textit{which} is set to {\bf PK\_PUBLIC} to use \textit{e}
(i.e. for encryption/verifying) and set to {\bf PK\_PRIVATE} to use \textit{d} as the exponent (i.e. for decrypting/signing).

Note: the output of this function is zero--padded as per PKCS \#1 specification.  This allows this routine to work with PKCS \#1 padding functions properly.

\subsection{RSA Key Size}
To fetch the key size of an RSA key, use the following function:
\index{rsa\_get\_size()}
\begin{verbatim}
int rsa_get_size(rsa_key *key);
\end{verbatim}
This can be used to determine the modulus size of an RSA key.

\mysection{RSA Key Encryption}
Normally RSA is used to encrypt short symmetric keys which are then used in block ciphers to encrypt a message.
To facilitate encrypting short keys the following functions have been provided.

\index{rsa\_encrypt\_key()}
\begin{verbatim}
int rsa_encrypt_key(
    const unsigned char *in,
          unsigned long  inlen,
          unsigned char *out,
          unsigned long *outlen,
    const unsigned char *lparam,
          unsigned long  lparamlen,
             prng_state *prng,
                    int  prng_idx,
                    int  hash_idx,
                rsa_key *key);
\end{verbatim}
This function will OAEP pad \textit{in} of length \textit{inlen} bytes, RSA encrypt it, and store the ciphertext
in \textit{out} of length \textit{outlen} octets.  The \textit{lparam} and \textit{lparamlen} are the same parameters you would pass
to \index{pkcs\_1\_oaep\_encode()} pkcs\_1\_oaep\_encode().

\subsection{Extended Encryption}
As of v1.15, the library supports both v1.5 and v2.1 PKCS \#1 style paddings in these higher level functions.  The following is the extended
encryption function:

\index{rsa\_encrypt\_key\_ex()}
\begin{verbatim}
int rsa_encrypt_key_ex(
    const unsigned char *in,
          unsigned long  inlen,
          unsigned char *out,
          unsigned long *outlen,
    const unsigned char *lparam,
          unsigned long  lparamlen,
             prng_state *prng,
                    int  prng_idx,
                    int  hash_idx,
                    int  padding,
                rsa_key *key);
\end{verbatim}

\index{LTC\_PKCS\_1\_OAEP} \index{LTC\_PKCS\_1\_V1\_5}
The parameters are all the same as for rsa\_encrypt\_key() except for the addition of the \textit{padding} parameter.  It must be set to
\textbf{LTC\_PKCS\_1\_V1\_5} to perform v1.5 encryption, or set to \textbf{LTC\_PKCS\_1\_OAEP} to perform v2.1 encryption.

When performing v1.5 encryption, the hash and lparam parameters are totally ignored and can be set to \textbf{NULL} or zero (respectively).

\mysection{RSA Key Decryption}
\index{rsa\_decrypt\_key()}
\begin{verbatim}
int rsa_decrypt_key(
    const unsigned char *in,
          unsigned long  inlen,
          unsigned char *out,
          unsigned long *outlen,
    const unsigned char *lparam,
          unsigned long  lparamlen,
                    int  hash_idx,
                    int *stat,
                rsa_key *key);
\end{verbatim}
This function will RSA decrypt \textit{in} of length \textit{inlen} then OAEP de-pad the resulting data and store it in
\textit{out} of length \textit{outlen}.  The \textit{lparam} and \textit{lparamlen} are the same parameters you would pass
to pkcs\_1\_oaep\_decode().

If the RSA decrypted data is not a valid OAEP packet then \textit{stat} is set to $0$.  Otherwise, it is set to $1$.

\subsection{Extended Decryption}
As of v1.15, the library supports both v1.5 and v2.1 PKCS \#1 style paddings in these higher level functions.  The following is the extended
decryption function:

\index{rsa\_decrypt\_key\_ex()}
\begin{verbatim}
int rsa_decrypt_key_ex(
    const unsigned char *in,
          unsigned long  inlen,
          unsigned char *out,
          unsigned long *outlen,
    const unsigned char *lparam,
          unsigned long  lparamlen,
                    int  hash_idx,
                    int  padding,
                    int *stat,
                rsa_key *key);
\end{verbatim}

Similar to the extended encryption, the new parameter \textit{padding} indicates which version of the PKCS \#1 standard to use.
It must be set to \textbf{LTC\_PKCS\_1\_V1\_5} to perform v1.5 decryption, or set to \textbf{LTC\_PKCS\_1\_OAEP} to perform v2.1 decryption.

When performing v1.5 decryption, the hash and lparam parameters are totally ignored and can be set to \textbf{NULL} or zero (respectively).


\mysection{RSA Signature Generation}
Similar to RSA key encryption RSA is also used to \textit{digitally sign} message digests (hashes).  To facilitate this
process the following functions have been provided.

\index{rsa\_sign\_hash()}
\begin{verbatim}
int rsa_sign_hash(const unsigned char *in,
                        unsigned long  inlen,
                        unsigned char *out,
                        unsigned long *outlen,
                           prng_state *prng,
                                  int  prng_idx,
                                  int  hash_idx,
                        unsigned long  saltlen,
                              rsa_key *key);
\end{verbatim}

This will PSS encode the message digest pointed to by \textit{in} of length \textit{inlen} octets.  Next, the PSS encoded hash will be RSA
\textit{signed} and the output stored in the buffer pointed to by \textit{out} of length \textit{outlen} octets.

The \textit{hash\_idx} parameter indicates which hash will be used to create the PSS encoding.  It should be the same as the hash used to
hash the message being signed.  The \textit{saltlen} parameter indicates the length of the desired salt, and should typically be small.  A good
default value is between 8 and 16 octets.  Strictly, it must be small than $modulus\_len - hLen - 2$ where \textit{modulus\_len} is the size of
the RSA modulus (in octets), and \textit{hLen} is the length of the message digest produced by the chosen hash.

\subsection{Extended Signatures}

As of v1.15, the library supports both v1.5 and v2.1 signatures.  The extended signature generation function has the following prototype:

\index{rsa\_sign\_hash\_ex()}
\begin{verbatim}
int rsa_sign_hash_ex(
    const unsigned char *in,
          unsigned long  inlen,
          unsigned char *out,
          unsigned long *outlen,
                    int  padding,
          prng_state    *prng,
                    int  prng_idx,
                    int  hash_idx,
          unsigned long  saltlen,
                rsa_key *key);
\end{verbatim}

This will PKCS encode the message digest pointed to by \textit{in} of length \textit{inlen} octets.  Next, the PKCS encoded hash will be RSA
\textit{signed} and the output stored in the buffer pointed to by \textit{out} of length \textit{outlen} octets.  The \textit{padding} parameter
must be set to \textbf{LTC\_PKCS\_1\_V1\_5} to produce a v1.5 signature, otherwise, it must be set to \textbf{LTC\_PKCS\_1\_PSS} to produce a
v2.1 signature.

\index{LTC\_PKCS\_1\_V1\_5\_NA1}
As of v1.18.0, the library also supports v1.5 signature generation without ASN.1 encoding the signature which can be indicated by passing
\textbf{LTC\_PKCS\_1\_V1\_5\_NA1} as \textit{padding} parameter. This option has been introduced to provide compatibilty to SSL3.0 implementations
which implemented this.

When generating a standard v1.5 signature the \textit{prng}, and \textit{prng\_idx} parameters are ignored.
When generating a v1.5 signature without ASN.1 decoding additionally the textit{hash\_idx} parameter is ignored.

\mysection{RSA Signature Verification}
\index{rsa\_verify\_hash()}
\begin{verbatim}
int rsa_verify_hash(const unsigned char *sig,
                          unsigned long  siglen,
                    const unsigned char *msghash,
                          unsigned long  msghashlen,
                                    int  hash_idx,
                          unsigned long  saltlen,
                                    int *stat,
                                rsa_key *key);
\end{verbatim}

This will RSA \textit{verify} the signature pointed to by \textit{sig} of length \textit{siglen} octets.  Next, the RSA decoded data is PSS decoded
and the extracted hash is compared against the message digest pointed to by \textit{msghash} of length \textit{msghashlen} octets.

If the RSA decoded data is not a valid PSS message, or if the PSS decoded hash does not match the \textit{msghash}
value, \textit{res} is set to $0$.  Otherwise, if the function succeeds, and signature is valid \textit{res} is set to $1$.

\subsection{RSA Signature Salt Length}

The v2.1 signature algorithm requires a salt length to be able to properly
encode resp. decode. To fetch the maximum possible salt length this function
is provided:

\index{rsa\_sign\_saltlen\_get\_max()}
\begin{verbatim}
int rsa_sign_saltlen_get_max(int hash_idx, rsa_key *key);
\end{verbatim}

As stated in the PKCS\#1 RFC3447 "Typical salt lengths in octets are hLen
(the length of the output of the hash function Hash) and 0".
This function is provided to be able to use other lengths as well and to make
sure at runtime that the RSA key can handle the desired salt length.

\subsection{Extended Verification}

As of v1.15, the library supports both v1.5 and v2.1 signature verification.  The extended signature verification function has the following prototype:

\index{rsa\_verify\_hash\_ex()}
\begin{verbatim}
int rsa_verify_hash_ex(
    const unsigned char *sig,
          unsigned long  siglen,
    const unsigned char *hash,
          unsigned long  hashlen,
                    int  padding,
                    int  hash_idx,
          unsigned long  saltlen,
                    int *stat,
                rsa_key *key);
\end{verbatim}

This will RSA \textit{verify} the signature pointed to by \textit{sig} of length \textit{siglen} octets.  Next, the RSA decoded data is PKCS decoded
and the extracted hash is compared against the message digest pointed to by \textit{msghash} of length \textit{msghashlen} octets.

If the RSA decoded data is not a valid PSS message, or if the PKCS decoded hash does not match the \textit{msghash}
value, \textit{res} is set to $0$.  Otherwise, if the function succeeds, and signature is valid \textit{res} is set to $1$.

The \textit{padding} parameter must be set to \textbf{LTC\_PKCS\_1\_V1\_5} to perform a v1.5 verification.  Otherwise, it must be set to
\textbf{LTC\_PKCS\_1\_PSS} to perform a v2.1 verification.

As of v1.18.0, the library also supports v1.5 signature verification without ASN.1 decoding the signature which can be indicated by passing
\textbf{LTC\_PKCS\_1\_V1\_5\_NA1} as \textit{padding} parameter.

When performing a standard v1.5 verification the \textit{saltlen} parameter is ignored.
When performing a v1.5 verification without ASN.1 decoding additionally the \textit{hash\_idx} parameter is ignored.


\mysection{RSA Encryption Example}
\begin{small}
\begin{verbatim}
#include <tomcrypt.h>
int main(void)
{
   int           err, hash_idx, prng_idx, res;
   unsigned long l1, l2;
   unsigned char pt[16], pt2[16], out[1024];
   rsa_key       key;

   /* register prng/hash */
   if (register_prng(&sprng_desc) == -1) {
      printf("Error registering sprng");
      return EXIT_FAILURE;
   }

   /* register a math library (in this case TomsFastMath)
   ltc_mp = tfm_desc;

   if (register_hash(&sha1_desc) == -1) {
      printf("Error registering sha1");
      return EXIT_FAILURE;
   }
   hash_idx = find_hash("sha1");
   prng_idx = find_prng("sprng");

   /* make an RSA-1024 key */
   if ((err = rsa_make_key(NULL,     /* PRNG state */
                           prng_idx, /* PRNG idx */
                           1024/8,   /* 1024-bit key */
                           65537,    /* we like e=65537 */
                           &key)     /* where to store the key */
       ) != CRYPT_OK) {
       printf("rsa_make_key %s", error_to_string(err));
       return EXIT_FAILURE;
   }

   /* fill in pt[] with a key we want to send ... */
   l1 = sizeof(out);
   if ((err = rsa_encrypt_key(pt, /* data we wish to encrypt */
                              16, /* data is 16 bytes long */
                             out, /* where to store ciphertext */
                             &l1, /* length of ciphertext */
                       "TestApp", /* our lparam for this program */
                               7, /* lparam is 7 bytes long */
                            NULL, /* PRNG state */
                        prng_idx, /* prng idx */
                        hash_idx, /* hash idx */
                            &key) /* our RSA key */
       ) != CRYPT_OK) {
       printf("rsa_encrypt_key %s", error_to_string(err));
       return EXIT_FAILURE;
   }

   /* now let's decrypt the encrypted key */
   l2 = sizeof(pt2);
   if ((err = rsa_decrypt_key(out, /* encrypted data */
                               l1, /* length of ciphertext */
                              pt2, /* where to put plaintext */
                              &l2, /* plaintext length */
                        "TestApp", /* lparam for this program */
                                7, /* lparam is 7 bytes long */
                         hash_idx, /* hash idx */
                             &res, /* validity of data */
                             &key) /* our RSA key */
        ) != CRYPT_OK) {
       printf("rsa_decrypt_key %s", error_to_string(err));
       return EXIT_FAILURE;
   }
   /* if all went well pt == pt2, l2 == 16, res == 1 */
}
\end{verbatim}
\end{small}

\mysection{RSA Key Format}

The RSA key format adopted for exporting and importing keys is the PKCS \#1 format defined by the ASN.1 constructs known as
RSAPublicKey and RSAPrivateKey.  Additionally, the OpenSSL key format is supported as well.

\subsection{RSA Key Export}
To export a RSA key use the following function.

\index{rsa\_export()}
\begin{verbatim}
int rsa_export(unsigned char *out,
               unsigned long *outlen,
                         int  type,
                     rsa_key *key);
\end{verbatim}

This will export the RSA key depending on the value of \textit{type}.

The RSAPublicKey (PKCS \#1 type) format will be used for the public key,
indicated by \textbf{PK\_PUBLIC}.
The RSAPrivateKey (PKCS \#1 type) format will be used for the private key,
indicated by \textbf{PK\_PRIVATE}.

As of v1.18.0 this function can also export OpenSSL-compatible formatted public RSA keys.
By OR'ing \textbf{PK\_STD} and \textbf{PK\_PUBLIC} the public key will be exported
in the SubjectPublicKeyInfo (X.509 type) format.

\subsection{RSA Key Import}
To import a RSA key use one of the following function.

\subsubsection{Import from standard formats}

This will import the key stored in \textit{in} of length inlen and import it to \textit{key}.

These formats are normally distributed in the PEM format, consisting of a label defining the content and base64 encoded DER-serialized data.

All the import functions expect binary DER data.

\index{rsa\_import()}
\begin{verbatim}
int rsa_import(const unsigned char *in,
                     unsigned long  inlen,
                           rsa_key *key);
\end{verbatim}

This function can import both RSAPublicKey and RSAPrivateKey formats.

As of v1.06 this function can also import OpenSSL DER formatted public RSA keys.  They are essentially encapsulated RSAPublicKeys.  LibTomCrypt will
import the key, strip off the additional data and fill in the \textit{rsa\_key} structure.

\index{rsa\_import\_pkcs8()}
\begin{verbatim}
int rsa_import_pkcs8(const unsigned char *in,
                           unsigned long inlen,
                              const void *passwd,
                           unsigned long passwdlen,
                                rsa_key *key);
\end{verbatim}

This function can import RSA private keys serialized in PKCS\#8 format.

It provides a \textit{password} parameter for the encrypted PKCS\#8 format, but this functionality is currently NOT implemented.

\index{rsa\_import\_x509()}
\begin{verbatim}
int rsa_import_x509(const unsigned char *in,
                          unsigned long inlen,
                                rsa_key *key);
\end{verbatim}

This function can import the RSA public key from a X.509 certificate.

\subsubsection{Import from plain big numbers}

\index{rsa\_set\_key()}
\begin{verbatim}
int rsa_set_key(const unsigned char *N,
                      unsigned long Nlen,
                const unsigned char *e,
                      unsigned long elen,
                const unsigned char *d,
                      unsigned long dlen,
                rsa_key *key);
\end{verbatim}

This function can import the plain RSA key parameters \textit{N}, \textit{e} and \textit{d}.
The parameter \textit{d} is optional and only required when importing a private key.

\index{rsa\_set\_factors()}
\begin{verbatim}
int rsa_set_factors(const unsigned char *p,
                          unsigned long plen,
                    const unsigned char *q,
                          unsigned long qlen,
                    rsa_key *key);
\end{verbatim}

This function can import the plain RSA key factors \textit{p} and \textit{q}.

\index{rsa\_set\_crt\_params()}
\begin{verbatim}
int rsa_set_crt_params(const unsigned char *dP,
                             unsigned long dPlen,
                       const unsigned char *dQ,
                             unsigned long dQlen,
                       const unsigned char *qP,
                             unsigned long qPlen,
                       rsa_key *key);
\end{verbatim}

This function can import the plain RSA CRT (chinese remainder theorem) parameters \textit{dP}, \textit{dQ} and \textit{qP}.

After importing \textit{p}, \textit{q}, \textit{dP}, \textit{dQ} and \textit{qP}
the library can perfrom the optimized CRT calculations on private key operations.

\chapter{Diffie-Hellman Key Exchange}

\mysection{Background}

Diffie-Hellman was the original public key system proposed.  The system is based upon the group structure
of finite fields.  For Diffie-Hellman a prime $p$ is chosen and a ``base'' $b$ such that $b^x\mbox{ }(\mbox{mod }p)$
generates a large sub-group of prime order (for unique values of $x$).

A secret key is an exponent $x$ and a public key is the value of $y \equiv g^x\mbox{ }(\mbox{mod }p)$.  The term
``discrete logarithm'' denotes the action of finding $x$ given only $y$, $g$ and $p$.  The key exchange part of
Diffie-Hellman arises from the fact that two users A and B with keys $(A_x, A_y)$ and $(B_x, B_y)$ can exchange
a shared key $K \equiv B_y^{A_x} \equiv A_y^{B_x} \equiv g^{A_xB_x}\mbox{ }(\mbox{mod }p)$.

From this public encryption and signatures can be developed.  The trivial way to encrypt (for example) using a public key
$y$ is to perform the key exchange offline.  The sender invents a key $k$ and its public copy
$k' \equiv g^k\mbox{ }(\mbox{mod }p)$ and uses $K \equiv k'^{A_x}\mbox{ }(\mbox{mod }p)$ as a key to encrypt
the message with.  Typically $K$ would be sent to a one-way hash and the message digested used as a key in a
symmetric cipher.

It is important that the order of the sub-group that $g$ generates not only be large but also prime.  There are
discrete logarithm algorithms that take $\sqrt r$ time given the order $r$.  The discrete logarithm can be computed
modulo each prime factor of $r$ and the results combined using the Chinese Remainder Theorem.  In the cases where
$r$ is ``B-Smooth'' (e.g. all small factors or powers of small prime factors) the solution is trivial to find.

To thwart such attacks the primes and bases in the library have been designed and fixed.  Given a prime $p$ the order of
 the sub-group generated is a large prime namely ${p - 1} \over 2$.  Such primes are known as ``strong primes'' and the
smaller prime (e.g. the order of the base) are known as Sophie-Germaine primes.

\mysection{Core Functions}

This library also provides core Diffie-Hellman functions so you can negotiate keys over insecure mediums.  The routines
provided are relatively easy to use and only take two function calls to negotiate a shared key.  There is a structure
called ``dh\_key'' which stores the Diffie-Hellman key in a format these routines can use.  The first set of routines
are to make a Diffie-Hellman private key pair:
\index{dh\_make\_key()}
\begin{verbatim}
int dh_set_pg_groupsize(int groupsize, dh_key *key);
int dh_generate_key(prng_state *prng, int wprng, dh_key *key);
\end{verbatim}
The ``groupsize'' is the size of the modulus you want in bytes.  Currently support sizes are 96 to 1024 bytes which correspond
to key sizes of 768 to 8192 bits. The smaller the key the faster it is to use however it will be less secure.  When
specifying a size not explicitly supported by the library it will round {\em up} to the next key size.  If the size is
above 512 it will return an error.  So if you pass ``groupsize == 32'' it will use a 768 bit key but if you pass
``groupsize == 20000'' it will return an error.  The primes and generators used are built-into the library and were designed
to meet very specific goals.  The primes are strong primes which means that if $p$ is the prime then
$p-1$ is equal to $2r$ where $r$ is a large prime.  The bases are chosen to generate a group of order $r$ to prevent
leaking a bit of the key.  This means the bases generate a very large prime order group which is good to make cryptanalysis
hard.

The next two routines are for exporting/importing Diffie-Hellman keys in/from DER encoded ASN.1.  This is useful for transport
over communication mediums.

\index{dh\_export()} \index{dh\_import()}
\begin{verbatim}
int dh_export(unsigned char *out, unsigned long *outlen,
              int type, dh_key *key);

int dh_import(const unsigned char *in, unsigned long inlen, dh_key *key);
\end{verbatim}

The ASN.1 sequence used to represent a DH key is as following:

\begin{verbatim}
DiffieHellmanKey ::= SEQUENCE {
      version Version,
      flags   Flags,
      p       INTEGER, -- prime
      g       INTEGER, -- base/group
      n       INTEGER  -- either x when private key or y when public key }

Version  ::=  INTEGER  {  v1(0)  }

Flags    ::=  BIT STRING {
      privateKey      (0) -- this BIT is '1' if it's a private key
                          --          or '0' if it's a public key
}
\end{verbatim}

These two functions work just like the ``rsa\_export()'' and ``rsa\_import()'' functions except these work with
Diffie-Hellman keys. Its important to note you do not have to free the ram for a ``dh\_key'' if an import fails.

You can free a ``dh\_key'' using:
\begin{verbatim}
void dh_free(dh_key *key);
\end{verbatim}
After you have exported a copy of your public key (using {\bf PK\_PUBLIC} as ``type'') you can now create a shared secret
with the other user using:
\index{dh\_shared\_secret()}
\begin{verbatim}
int dh_shared_secret(dh_key *private_key,
                     dh_key *public_key,
                     unsigned char *out, unsigned long *outlen);
\end{verbatim}

Where ``private\_key'' is the key you made and ``public\_key'' is the copy of the public key the other user sent you.  The result goes
into ``out'' and the length into ``outlen''.  If all went correctly the data in ``out'' should be identical for both parties.  It is important to
note that the two keys have to be the same size in order for this to work.  There is a function to get the size of a
key:
\index{dh\_get\_groupsize()}
\begin{verbatim}
int dh_get_groupsize(dh_key *key);
\end{verbatim}
This returns the size in bytes of the modulus chosen for that key.

\mysection{Other Diffie-Hellman Functions}

To be able to import Diffie-Hellman keys LibTomCrypt provides several API functions.
\\

To import the prime and group from binary format:
\index{dh\_set\_pg()}
\begin{verbatim}
int dh_set_pg(const unsigned char *p, unsigned long plen,
              const unsigned char *g, unsigned long glen,
              dh_key *key);
\end{verbatim}
This sets the prime \textit{p} of length \textit{plen} and the generator/base \textit{g} of length \textit{glen} in the DH key \textit{key}.
\\

To import the prime and group from an ASN.1 encoded DHparam Sequence:
\index{dh\_set\_pg\_dhparam()}
\begin{verbatim}
int dh_set_pg_dhparam(const unsigned char *dhparam, unsigned long dhparamlen, dh_key *key);
\end{verbatim}
This sets the parameters in \textit{dhparam} of \textit{dhparamlen} in the DH key \textit{key}.
\\

To import a private or public key from binary data:
\index{dh\_set\_key()}
\begin{verbatim}
int dh_set_key(const unsigned char *in, unsigned long inlen, int type, dh_key *key);
\end{verbatim}
This will import, depending on \textit{type} which can be either \textit{PK\_PRIVATE} or \textit{PK\_PUBLIC},
the according part of the DH key \textit{key} from \textit{in} of length \textit{inlen}.
After import the key will be verified and in case of an error it will be free'd.

\mysection{Remarks on Usage}
Its important that you hash the shared key before trying to use it as a key for a symmetric cipher or something.  An
example program that communicates over sockets, using MD5 and 1024-bit DH keys is\footnote{This function is a small example.  It is suggested that proper packaging be used.  For example, if the public key sent is truncated these routines will not detect that.}:
\newpage
\begin{small}
\begin{verbatim}
int establish_secure_socket(int sock, int mode, unsigned char *key,
                            prng_state *prng, int wprng)
{
   unsigned char buf[4096], buf2[4096];
   unsigned long x, len;
   int res, err, inlen;
   dh_key mykey, theirkey;

   /* make up our private key */
   if ((err = dh_set_pg_groupsize(128, &mykey)) != CRYPT_OK)  {
      return err;
   }
   if ((err = dh_generate_key(prng, wprng, &mykey)) != CRYPT_OK)  {
      return err;
   }

   /* export our key as public */
   x = sizeof(buf);
   if ((err = dh_export(buf, &x, PK_PUBLIC, &mykey)) != CRYPT_OK) {
      res = err;
      goto done2;
   }

   if (mode == 0) {
      /* mode 0 so we send first */
      if (send(sock, buf, x, 0) != x) {
         res = CRYPT_ERROR;
         goto done2;
      }

      /* get their key */
      if ((inlen = recv(sock, buf2, sizeof(buf2), 0)) <= 0) {
         res = CRYPT_ERROR;
         goto done2;
      }
   } else {
      /* mode >0 so we send second */
      if ((inlen = recv(sock, buf2, sizeof(buf2), 0)) <= 0) {
         res = CRYPT_ERROR;
         goto done2;
      }

      if (send(sock, buf, x, 0) != x) {
         res = CRYPT_ERROR;
         goto done2;
      }
   }

   if ((err = dh_import(buf2, inlen, &theirkey)) != CRYPT_OK) {
      res = err;
      goto done2;
   }

   /* make shared secret */
   x = sizeof(buf);
   if ((err = dh_shared_secret(&mykey, &theirkey, buf, &x)) != CRYPT_OK) {
      res = err;
      goto done;
   }

   /* hash it */
   len = 16;        /* default is MD5 so "key" must be at least 16 bytes long */
   if ((err = hash_memory(find_hash("md5"), buf, x, key, &len)) != CRYPT_OK) {
      res = err;
      goto done;
   }

   /* clean up and return */
   res = CRYPT_OK;
done:
   dh_free(&theirkey);
done2:
   dh_free(&mykey);
   zeromem(buf,  sizeof(buf));
   zeromem(buf2, sizeof(buf2));
   return res;
}
\end{verbatim}
\end{small}
\subsection{Remarks on The Snippet}
When the above code snippet is done (assuming all went well) there will be a shared 128-bit key in the ``key'' array
passed to ``establish\_secure\_socket()''.

\chapter{Elliptic Curve Cryptography}

\mysection{Background}
The library provides a set of core ECC functions as well that are designed to be the Elliptic Curve analogy of all of the
Diffie-Hellman routines in the previous chapter.  Elliptic curves (of certain forms) have the benefit that they are harder
to attack (no sub-exponential attacks exist unlike normal DH crypto) in fact the fastest attack requires the square root
of the order of the base point in time.  That means if you use a base point of order $2^{192}$ (which would represent a
192-bit key) then the work factor is $2^{96}$ in order to find the secret key.

The curves in this library are taken from the following website:
\begin{verbatim}
http://csrc.nist.gov/cryptval/dss.htm
\end{verbatim}

As of v1.15 three new curves from the SECG standards are also included they are the secp112r1, secp128r1, and secp160r1 curves.  These curves were added to
support smaller devices which do not need as large keys for security.

They are all curves over the integers modulo a prime.  The curves have the basic equation that is:
\begin{equation}
y^2 = x^3 - 3x + b\mbox{ }(\mbox{mod }p)
\end{equation}

The variable $b$ is chosen such that the number of points is nearly maximal.  In fact the order of the base points $\beta$
provided are very close to $p$ that is $\vert \vert \phi(\beta) \vert \vert \approx \vert \vert p \vert \vert$.  The curves
range in order from $\approx 2^{112}$ points to $\approx 2^{521}$.  According to the source document any key size greater
than or equal to 256-bits is sufficient for long term security.

\mysection{Fixed Point Optimizations}
\index{Fixed Point ECC}
\index{MECC\_FP}
As of v1.12 of LibTomCrypt, support for Fixed Point ECC point multiplication has been added.  It is a generic optimization that is
supported by any conforming math plugin.  It is enabled by defining \textbf{MECC\_FP} during the build, such as

\begin{verbatim}
CFLAGS="-DTFM_DESC -DMECC_FP" make
\end{verbatim}

which will build LTC using the TFM math library and enabling this new feature.  The feature is not enabled by default as it is \textbf{NOT} thread
safe (by default).  It supports the LTC locking macros (such as by enabling LTC\_PTHREAD), but by default is not locked.

\index{FP\_ENTRIES}
The optimization works by using a Fixed Point multiplier on any base point you use twice or more in a short period of time.  It has a limited size
cache (of FP\_ENTRIES entries) which it uses to hold recent bases passed to ltc\_ecc\_mulmod().  Any base detected to be used twice is sent through the
pre--computation phase, and then the fixed point algorithm can be used.  For example, if you use a NIST base point twice in a row, the 2$^{nd}$ and
all subsequent point multiplications with that point will use the faster algorithm.

\index{FP\_LUT}
The optimization uses a window on the multiplicand of FP\_LUT bits (default: 8, min: 2, max: 12), and this controls the memory/time trade-off. The larger the
value the faster the algorithm will be but the more memory it will take.  The memory usage is $3 \cdot 2^{FP\_LUT}$ integers which by default
with TFM amounts to about 400kB of memory.  Tuning TFM (by changing FP\_SIZE) can decrease the usage by a fair amount.  Memory is only used by a cache entry
if it is active.  Both FP\_ENTRIES and FP\_LUT are definable on the command line if you wish to override them. For instance,

\begin{verbatim}
CFLAGS="-DTFM_DESC -DMECC_FP -DFP_ENTRIES=8 -DFP_LUT=6" make
\end{verbatim}

\begin{flushleft}
\index{FP\_SIZE} \index{TFM} \index{tfm.h}
would define a window of 6 bits and limit the cache to 8 entries.  Generally, it is better to first tune TFM by adjusting FP\_SIZE (from tfm.h).  It defaults
to 4096 bits (512 bytes) which is way more than what is required by ECC.  At most, you need 1152 bits to accommodate ECC--521.  If you're only using (say)
ECC--256 you will only need 576 bits, which would reduce the memory usage by 700\%.
\end{flushleft}

\mysection{Key Format}
LibTomCrypt uses a unique format for ECC public and private keys.  While ANSI X9.63 partially specifies key formats, it does it in a less than ideally simple manner.  \
In the case of LibTomCrypt, it is meant \textbf{solely} for NIST and SECG $GF(p)$ curves.  The format of the keys is as follows:

\index{ECC Key Format}
\begin{small}
\begin{verbatim}
ECCPublicKey ::= SEQUENCE {
    flags       BIT STRING(0), -- public/private flag (always zero),
    keySize     INTEGER,       -- Curve size (in bits) divided by eight
                               -- and rounded down, e.g. 521 => 65
    pubkey.x    INTEGER,       -- The X co-ordinate of the public key point
    pubkey.y    INTEGER,       -- The Y co-ordinate of the public key point
}

ECCPrivateKey ::= SEQUENCE {
    flags       BIT STRING(1), -- public/private flag (always one),
    keySize     INTEGER,       -- Curve size (in bits) divided by eight
                               -- and rounded down, e.g. 521 => 65
    pubkey.x    INTEGER,       -- The X co-ordinate of the public key point
    pubkey.y    INTEGER,       -- The Y co-ordinate of the public key point
    secret.k    INTEGER,       -- The secret key scalar
}
\end{verbatim}
\end{small}

The first flags bit denotes whether the key is public (zero) or private (one).

\vfil

\mysection{ECC Curve Parameters}
The library uses the following structure to describe an elliptic curve.  This is used internally, as well as by the new
extended ECC functions which allow the user to specify their own curves.

\index{ltc\_ecc\_set\_type}
\begin{verbatim}
/** Structure defines a NIST GF(p) curve */
typedef struct {
   /** The size of the curve in octets */
   int size;

   /** name of curve */
   char *name;

   /** The prime that defines the field (encoded in hex) */
   char *prime;

   /** The fields B param (hex) */
   char *B;

   /** The order of the curve (hex) */
   char *order;

   /** The x co-ordinate of the base point on the curve (hex) */
   char *Gx;

   /** The y co-ordinate of the base point on the curve (hex) */
   char *Gy;
} ltc_ecc_set_type;
\end{verbatim}

The curve must be of the form $y^2 = x^3 - 3x + b$, and all of the integer parameters are encoded in hexadecimal format.

\mysection{Core Functions}
\subsection{ECC Key Generation}
There is a key structure called \textit{ecc\_key} used by the ECC functions.  There is a function to make a key:
\index{ecc\_make\_key()}
\begin{verbatim}
int ecc_make_key(prng_state *prng,
                        int  wprng,
                        int  keysize,
                    ecc_key *key);
\end{verbatim}

The \textit{keysize} is the size of the modulus in bytes desired.  Currently directly supported values are 12, 16, 20, 24, 28, 32, 48, and 65 bytes which
correspond to key sizes of 112, 128, 160, 192, 224, 256, 384, and 521 bits respectively.  If you pass a key size that is between any key size it will round
the keysize up to the next available one.

The function will free any internally allocated resources if there is an error.

\subsection{Extended Key Generation}
As of v1.16, the library supports an extended key generation routine which allows the user to specify their own curve.  It is specified as follows:

\index{ecc\_make\_key\_ex()}
\begin{verbatim}
int  ecc_make_key_ex(
                 prng_state *prng,
                        int  wprng,
                    ecc_key *key,
     const ltc_ecc_set_type *dp);
\end{verbatim}

This function generates a random ECC key over the curve specified by the parameters by \textit{dp}.  The rest of the parameters are equivalent to
those from the original key generation function.

\subsection{ECC Key Free}
To free the memory allocated by a ecc\_make\_key(), ecc\_make\_key\_ex(), ecc\_import(), or ecc\_import\_ex() call use the following function:
\index{ecc\_free()}
\begin{verbatim}
void ecc_free(ecc_key *key);
\end{verbatim}

\subsection{ECC Key Export}
To export an ECC key using the LibTomCrypt format call the following function:
\index{ecc\_export()}
\begin{verbatim}
int ecc_export(unsigned char *out,
               unsigned long *outlen,
                         int  type,
                     ecc_key *key);
\end{verbatim}
This will export the key with the given \textit{type} (\textbf{PK\_PUBLIC} or \textbf{PK\_PRIVATE}), and store it to \textit{out}.

\subsection{ECC Key Import}
The following function imports a LibTomCrypt format ECC key:
\index{ecc\_import()}
\begin{verbatim}
int ecc_import(const unsigned char *in,
                     unsigned long  inlen,
                           ecc_key *key);
\end{verbatim}
This will import the ECC key from \textit{in}, and store it in the ecc\_key structure pointed to by \textit{key}.  If the operation fails it will free
any allocated memory automatically.

\subsection{Extended Key Import}

The following function imports a LibTomCrypt format ECC key using a specified set of curve parameters:
\index{ecc\_import\_ex()}
\begin{verbatim}
int  ecc_import_ex(const unsigned char *in,
                         unsigned long  inlen,
                               ecc_key *key,
                const ltc_ecc_set_type *dp);
\end{verbatim}
This will import the key from the array pointed to by \textit{in} of length \textit{inlen} octets.  The key is stored in
the ECC structure pointed to by \textit{key}.  The curve is specified by the parameters pointed to by \textit{dp}.  The function will free
all internally allocated memory upon error.

\subsection{ANSI X9.63 Export}
The following function exports an ECC public key in the ANSI X9.63 format:

\index{ecc\_ansi\_x963\_export()}
\begin{verbatim}
int ecc_ansi_x963_export(      ecc_key *key,
                         unsigned char *out,
                         unsigned long *outlen);
\end{verbatim}
The ECC key pointed to by \textit{key} is exported in public fashion to the array pointed to by \textit{out}.  The ANSI X9.63 format used is from
section 4.3.6 of the standard.  It does not allow for the export of private keys.

\subsection{ANSI X9.63 Import}
The following function imports an ANSI X9.63 section 4.3.6 format public ECC key:

\index{ecc\_ansi\_x963\_import()}
\begin{verbatim}
int ecc_ansi_x963_import(const unsigned char *in,
                               unsigned long  inlen,
                                     ecc_key *key);
\end{verbatim}
This will import the key stored in the array pointed to by \textit{in} of length \textit{inlen} octets.  The imported key is stored in the ECC key pointed to by
\textit{key}.  The function will free any allocated memory upon error.

\subsection{Extended ANSI X9.63 Import}
The following function allows the importing of an ANSI x9.63 section 4.3.6 format public ECC key using user specified domain parameters:

\index{ecc\_ansi\_x963\_import\_ex()}
\begin{verbatim}
int ecc_ansi_x963_import_ex(const unsigned char *in,
                                  unsigned long  inlen,
                                        ecc_key *key,
                               ltc_ecc_set_type *dp);
\end{verbatim}
This will import the key stored in the array pointed to by \textit{in} of length \textit{inlen} octets using the domain parameters pointed to by \textit{dp}.
The imported key is stored in the ECC key pointed to by \textit{key}.  The function will free any allocated memory upon error.

\subsection{ECC Shared Secret}
To construct a Diffie-Hellman shared secret with a private and public ECC key, use the following function:
\index{ecc\_shared\_secret()}
\begin{verbatim}
int ecc_shared_secret(      ecc_key *private_key,
                            ecc_key *public_key,
                      unsigned char *out,
                      unsigned long *outlen);
\end{verbatim}
The \textit{private\_key} is typically the local private key, and \textit{public\_key} is the key the remote party has shared.
Note: this function stores only the $x$ co-ordinate of the shared elliptic point as described in ANSI X9.63 ECC--DH.

\mysection{ECC Diffie-Hellman Encryption}
ECC--DH Encryption is performed by producing a random key, hashing it, and XOR'ing the digest against the plaintext.  It is not strictly ANSI X9.63 compliant
but it is very similar.  It has been extended by using an ASN.1 sequence and hash object identifiers to allow portable usage.  The following function
encrypts a short string (no longer than the message digest) using this technique:

\subsection{ECC-DH Encryption}
\index{ecc\_encrypt\_key()}
\begin{verbatim}
int ecc_encrypt_key(const unsigned char *in,
                          unsigned long  inlen,
                          unsigned char *out,
                          unsigned long *outlen,
                             prng_state *prng,
                                    int  wprng,
                                    int  hash,
                                ecc_key *key);
\end{verbatim}

As the name implies this function encrypts a (symmetric) key, and is not intended for encrypting long messages directly.  It will encrypt the
plaintext in the array pointed to by \textit{in} of length \textit{inlen} octets.  It uses the public ECC key pointed to by \textit{key}, and
hash algorithm indexed by \textit{hash} to construct a shared secret which may be XOR'ed against the plaintext.  The ciphertext is stored in
the output buffer pointed to by \textit{out} of length \textit{outlen} octets.

The data is encrypted to the public ECC \textit{key} such that only the holder of the private key can decrypt the payload.  To have multiple
recipients multiple call to this function for each public ECC key is required.

\subsection{ECC-DH Decryption}
\index{ecc\_decrypt\_key()}
\begin{verbatim}
int ecc_decrypt_key(const unsigned char *in,
                          unsigned long  inlen,
                          unsigned char *out,
                          unsigned long *outlen,
                                ecc_key *key);
\end{verbatim}

This function will decrypt an encrypted payload.  The \textit{key} provided must be the private key corresponding to the public key
used during encryption.  If the wrong key is provided the function will not specifically return an error code.  It is important
to use some form of challenge response in that case (e.g. compute a MAC of a known string).

\subsection{ECC Encryption Format}
The packet format for the encrypted keys is the following ASN.1 SEQUENCE:

\begin{verbatim}
ECCEncrypt ::= SEQUENCE {
   hashID        OBJECT IDENTIFIER, -- OID of hash used
   pubkey        OCTET STRING     , -- Encapsulated ECCPublicKey
   skey          OCTET STRING       -- xor of plaintext and
                                    --"hash of shared secret"
}
\end{verbatim}

\mysection{EC DSA Signatures}

There are also functions to sign and verify messages.  They use the ANSI X9.62 EC-DSA algorithm to generate and verify signatures in the
ANSI X9.62 format.

\subsection{EC-DSA Signature Generation}
To sign a message digest (hash) use the following function:

\index{ecc\_sign\_hash()}
\begin{verbatim}
int ecc_sign_hash(const unsigned char *in,
                        unsigned long  inlen,
                        unsigned char *out,
                        unsigned long *outlen,
                           prng_state *prng,
                                  int  wprng,
                              ecc_key *key);
\end{verbatim}

This function will EC--DSA sign the message digest stored in the array pointed to by \textit{in} of length \textit{inlen} octets.  The signature
will be stored in the array pointed to by \textit{out} of length \textit{outlen} octets.  The function requires a properly seeded PRNG, and
the ECC \textit{key} provided must be a private key.

\index{ecc\_sign\_hash\_rfc7518()}
\begin{verbatim}
int ecc_sign_hash_rfc7518(const unsigned char *in,
                                unsigned long  inlen,
                                unsigned char *out,
                                unsigned long *outlen,
                                   prng_state *prng,
                                          int  wprng,
                                      ecc_key *key);
\end{verbatim}

This function creates the same EC--DSA signature as \textit{ecc\_sign\_hash} only the output format is different.
The format follows \url{https://tools.ietf.org/html/rfc7518#section-3.4}, sometimes it is also called plain signature.

\subsection{EC-DSA Signature Verification}
\index{ecc\_verify\_hash()}
\begin{verbatim}
int ecc_verify_hash(const unsigned char *sig,
                          unsigned long  siglen,
                    const unsigned char *hash,
                          unsigned long  hashlen,
                                    int *stat,
                                ecc_key *key);
\end{verbatim}

This function will verify the EC-DSA signature in the array pointed to by \textit{sig} of length \textit{siglen} octets, against the message digest
pointed to by the array \textit{hash} of length \textit{hashlen}.  It will store a non--zero value in \textit{stat} if the signature is valid.  Note:
the function will not return an error if the signature is invalid.  It will return an error, if the actual signature payload is an invalid format.
The ECC \textit{key} must be the public (or private) ECC key corresponding to the key that performed the signature.
The function \textit{ecc\_verify\_hash} implements signature format according to X9.62 EC--DSA, and the output is compliant for GF(p) curves.

\index{ecc\_verify\_hash\_rfc7518()}
\begin{verbatim}
int ecc_verify_hash_rfc7518(const unsigned char *sig,
                                  unsigned long  siglen,
                            const unsigned char *hash,
                                  unsigned long  hashlen,
                                            int *stat,
                                        ecc_key *key);
\end{verbatim}

This function validate the EC--DSA signature as \textit{ecc\_verify\_hash} only the signature input format
follows \url{https://tools.ietf.org/html/rfc7518#section-3.4}.

\mysection{ECC Keysizes}
With ECC if you try to sign a hash that is bigger than your ECC key you can run into problems.  The math will still work, and in effect the signature will still
work.  With ECC keys the strength of the signature is limited by the size of the hash, or the size of they key, whichever is smaller.  For example, if you sign with
SHA256 and an ECC-192 key, you in effect have 96--bits of security.

The library will not warn you if you make this mistake, so it is important to check yourself before using the signatures.

\chapter{Digital Signature Algorithm}
\mysection{Introduction}
The Digital Signature Algorithm (or DSA) is a variant of the ElGamal Signature scheme which has been modified to
reduce the bandwidth of the signatures.  For example, to have \textit{80-bits of security} with ElGamal, you need a group with an order of at least 1024--bits.
With DSA, you need a group of order at least 160--bits.  By comparison, the ElGamal signature would require at least 256 bytes of storage, whereas the DSA signature
would require only at least 40 bytes.

\mysection{Key Format}
Since no useful public standard for DSA key storage was presented to me during the course of this development I made my own ASN.1 SEQUENCE which I document
now so that others can interoperate with this library.

\begin{verbatim}
DSAPublicKey ::= SEQUENCE {
    publicFlags    BIT STRING(0), -- must be 0
    g              INTEGER      , -- base generator
                                  -- check that g^q mod p == 1
                                  -- and that 1 < g < p - 1
    p              INTEGER      , -- prime modulus
    q              INTEGER      , -- order of sub-group
                                  -- (must be prime)
    y              INTEGER      , -- public key, specifically,
                                  -- g^x mod p,
                                  -- check that y^q mod p == 1
                                  -- and that 1 < y < p - 1
}

DSAPrivateKey ::= SEQUENCE {
    publicFlags    BIT STRING(1), -- must be 1
    g              INTEGER      , -- base generator
                                  -- check that g^q mod p == 1
                                  -- and that 1 < g < p - 1
    p              INTEGER      , -- prime modulus
    q              INTEGER      , -- order of sub-group
                                  -- (must be prime)
    y              INTEGER      , -- public key, specifically,
                                  -- g^x mod p,
                                  -- check that y^q mod p == 1
                                  -- and that 1 < y < p - 1
    x              INTEGER        -- private key
}
\end{verbatim}

The leading BIT STRING has a single bit in it which is zero for public keys and one for private keys.  This makes the structure uniquely decodable,
and easy to work with.

\mysection{Key Generation}
To make a DSA key you must call the following function
\begin{verbatim}
int dsa_make_key(prng_state *prng,
                        int  wprng,
                        int  group_size,
                        int  modulus_size,
                    dsa_key *key);
\end{verbatim}
The variable \textit{prng} is an active PRNG state and \textit{wprng} the index to the descriptor.  \textit{group\_size} and
\textit{modulus\_size} control the difficulty of forging a signature.  Both parameters are in bytes.  The larger the
\textit{group\_size} the more difficult a forgery becomes upto a limit.  The value of $group\_size$ is limited by
$15 < group\_size < 1024$ and $modulus\_size - group\_size < 512$.  Suggested values for the pairs are as follows.

\begin{figure}[H]
\begin{center}
\begin{tabular}{|c|c|c|}
\hline \textbf{Bits of Security} & \textbf{group\_size} & \textbf{modulus\_size} \\
\hline 80  & 20 & 128 \\
\hline 120 & 30 & 256 \\
\hline 140 & 35 & 384 \\
\hline 160 & 40 & 512 \\
\hline
\end{tabular}
\end{center}
\caption{DSA Key Sizes}
\end{figure}

When you are finished with a DSA key you can call the following function to free the memory used.
\index{dsa\_free()}
\begin{verbatim}
void dsa_free(dsa_key *key);
\end{verbatim}

\mysection{Key Verification}
Each DSA key is composed of the following variables.

\begin{enumerate}
  \item $q$ a small prime of magnitude $256^{group\_size}$.
  \item $p = qr + 1$ a large prime of magnitude $256^{modulus\_size}$ where $r$ is a random even integer.
  \item $g = h^r \mbox{ (mod }p\mbox{)}$ a generator of order $q$ modulo $p$.  $h$ can be any non-trivial random
        value.  For this library they start at $h = 2$ and step until $g$ is not $1$.
  \item $x$ a random secret (the secret key) in the range $1 < x < q$
  \item $y = g^x \mbox{ (mod }p\mbox{)}$ the public key.
\end{enumerate}

A DSA key is considered valid if it passes all of the following tests.

\begin{enumerate}
   \item $q$ must be prime.
   \item $p$ must be prime.
   \item $g$ cannot be one of $\lbrace -1, 0, 1 \rbrace$ (modulo $p$).
   \item $g$ must be less than $p$.
   \item $(p-1) \equiv 0 \mbox{ (mod }q\mbox{)}$.
   \item $g^q \equiv 1 \mbox{ (mod }p\mbox{)}$.
   \item $1 < y < p - 1$
   \item $y^q \equiv 1 \mbox{ (mod }p\mbox{)}$.
\end{enumerate}

Tests one and two ensure that the values will at least form a field which is required for the signatures to
function.  Tests three and four ensure that the generator $g$ is not set to a trivial value which would make signature
forgery easier.  Test five ensures that $q$ divides the order of multiplicative sub-group of $\Z/p\Z$. Test six
ensures that the generator actually generates a prime order group.  Tests seven and eight ensure that the public key
is within range and belongs to a group of prime order.  Note that test eight does not prove that $g$ generated $y$ only
that $y$ belongs to a multiplicative sub-group of order $q$.

The following function will perform these tests.

\index{dsa\_verify\_key()}
\begin{verbatim}
int dsa_verify_key(dsa_key *key, int *stat);
\end{verbatim}

This will test \textit{key} and store the result in \textit{stat}.  If the result is $stat = 0$ the DSA key failed one of the tests
and should not be used at all.  If the result is $stat = 1$ the DSA key is valid (as far as valid mathematics are concerned).

\mysection{Signatures}
\subsection{Signature Generation}
To generate a DSA signature call the following function:

\index{dsa\_sign\_hash()}
\begin{verbatim}
int dsa_sign_hash(const unsigned char *in,
                        unsigned long  inlen,
                        unsigned char *out,
                        unsigned long *outlen,
                           prng_state *prng,
                                  int  wprng,
                              dsa_key *key);
\end{verbatim}

Which will sign the data in \textit{in} of length \textit{inlen} bytes.  The signature is stored in \textit{out} and the size
of the signature in \textit{outlen}.  If the signature is longer than the size you initially specify in \textit{outlen} nothing
is stored and the function returns an error code.  The DSA \textit{key} must be of the \textbf{PK\_PRIVATE} persuasion.

\subsection{Signature Verification}
To verify a hash created with that function use the following function:

\index{dsa\_verify\_hash()}
\begin{verbatim}
int dsa_verify_hash(const unsigned char *sig,
                          unsigned long  siglen,
                    const unsigned char *hash,
                          unsigned long  inlen,
                                    int *stat,
                                dsa_key *key);
\end{verbatim}
Which will verify the data in \textit{hash} of length \textit{inlen} against the signature stored in \textit{sig} of length \textit{siglen}.
It will set \textit{stat} to $1$ if the signature is valid, otherwise it sets \textit{stat} to $0$.

\mysection{DSA Encrypt and Decrypt}
As of version 1.07, the DSA keys can be used to encrypt and decrypt small payloads.  It works similar to the ECC encryption where
a shared key is computed, and the hash of the shared key XOR'ed against the plaintext forms the ciphertext.  The format used is functional port of
the ECC encryption format to the DSA algorithm.

\subsection{DSA Encryption}
This function will encrypt a small payload with a recipients public DSA key.

\index{dsa\_encrypt\_key()}
\begin{verbatim}
int dsa_encrypt_key(const unsigned char *in,
                          unsigned long  inlen,
                          unsigned char *out,
                          unsigned long *outlen,
                             prng_state *prng,
                                    int  wprng,
                                    int  hash,
                                dsa_key *key);
\end{verbatim}

This will encrypt the payload in \textit{in} of length \textit{inlen} and store the ciphertext in the output buffer \textit{out}.  The
length of the ciphertext \textit{outlen} must be originally set to the length of the output buffer.  The DSA \textit{key} can be
a public key.

\subsection{DSA Decryption}

\index{dsa\_decrypt\_key()}
\begin{verbatim}
int dsa_decrypt_key(const unsigned char *in,
                          unsigned long  inlen,
                          unsigned char *out,
                          unsigned long *outlen,
                                dsa_key *key);
\end{verbatim}
This will decrypt the ciphertext \textit{in} of length \textit{inlen}, and store the original payload in \textit{out} of length \textit{outlen}.
The DSA \textit{key} must be a private key.

\mysection{DSA Key Import and Export}

\subsection{DSA Key Export}
To export a DSA key so that it can be transported use the following function:
\index{dsa\_export()}
\begin{verbatim}
int dsa_export(unsigned char *out,
               unsigned long *outlen,
                         int  type,
                     dsa_key *key);
\end{verbatim}
This will export the DSA \textit{key} to the buffer \textit{out} and set the length in \textit{outlen} (which must have been previously
initialized to the maximum buffer size).  The \textit{type} variable may be either \textbf{PK\_PRIVATE} or \textbf{PK\_PUBLIC}
depending on whether you want to export a private or public copy of the DSA key.

\subsection{DSA Key Import}
To import an exported DSA key use the following function
:
\index{dsa\_import()}
\begin{verbatim}
int dsa_import(const unsigned char *in,
                     unsigned long  inlen,
                           dsa_key *key);
\end{verbatim}

This will import the DSA key from the buffer \textit{in} of length \textit{inlen} to the \textit{key}.  If the process fails the function
will automatically free all of the heap allocated in the process (you don't have to call dsa\_free()).

\mysection{Other DSA Functions}

The following functions allow to create a DSA key in 2 steps:

\begin{enumerate}
    \item Load or generate \textit{p}, \textit{q}, \textit{g} part of the key via \textit{dsa\_set\_pqg()}, \textit{dsa\_set\_pqg\_dsaparam()} or \textit{dsa\_generate\_pqg()}.
    \item Load or generate the actual DSA key -- private (\textit{x} and \textit{y} values) or public (\textit{y} value).
\end{enumerate}

\index{dsa\_set\_pqg()}
\begin{verbatim}
int dsa_set_pqg(const unsigned char *p,  unsigned long plen,
                const unsigned char *q,  unsigned long qlen,
                const unsigned char *g,  unsigned long glen,
                dsa_key *key);
\end{verbatim}

This will initialise the \textit{p}, \textit{q} and \textit{g} part of \textit{key} structure by directly loading binary
representation of \textit{p} (with length of \textit{plen}), \textit{q} (with length of \textit{qlen}) and \textit{g} (with length of \textit{glen}).
A simple DSA key validity check (without primality testing) is performed at the end of this function.

\index{dsa\_set\_pqg\_dsaparam()}
\begin{verbatim}
int dsa_set_pqg_dsaparam(const unsigned char *dsaparam,
                               unsigned long  dsaparamlen,
                                     dsa_key *key);
\end{verbatim}

This will initialise the \textit{p}, \textit{q} and \textit{g} part of \textit{key} structure by directly loading binary representation
of DSA parameters stored as a binary data in a buffer \textit{dsaparam} (with length of \textit{dsaparamlen}). A simple DSA key validity
check (without primality testing) is performed at the end of this function. The \textit{dsaparam} can be generated via:
\begin{verbatim}
 openssl dsaparam 2048 -outform DER -out dsaparam.der
\end{verbatim}

\index{dsa\_generate\_pqg()}
\begin{verbatim}
int dsa_generate_pqg(prng_state *prng,
                            int  wprng,
                            int  group_size,
                            int  modulus_size,
                        dsa_key *key);
\end{verbatim}

This will initialise the \textit{p}, \textit{q} and \textit{g} part of \textit{key} structure with newly generated random values.
As for the parameters they are the same as by \textit{dsa\_make\_key}.

\index{dsa\_set\_key()}
\begin{verbatim}
int dsa_set_key(const unsigned char *in,
                      unsigned long  inlen,
                                int  type,
                            dsa_key *key);
\end{verbatim}

This function can be used for setting the actual DSA key. If \textit{type} is \textit{PK\_PRIVATE} then the buffer \textit{in}
(with length of \textit{inlen}) contains a binary representation of \textit{x} part of the key (the public part \textit{y} is computed).
If \textit{type} is \textit{PK\_PUBLIC} then the buffer \textit{in} contains a binary representation of \textit{y} part of the key.

\index{dsa\_generate\_key()}
\begin{verbatim}
int dsa_generate_key(prng_state *prng,
                            int  wprng,
                        dsa_key *key);
\end{verbatim}

This function generates a private DSA key containing both \textit{x} and \textit{y} parts.

\chapter{Standards Support}
\mysection{ASN.1 Formats}
LibTomCrypt supports a variety of ASN.1 data types encoded with the Distinguished Encoding Rules (DER) suitable for various cryptographic protocols.  The data types
are all provided with three basic functions with \textit{similar} prototypes.  One function has been dedicated to calculate the length in octets of a given
format, and two functions have been dedicated to encoding and decoding the format.

On top of the basic data types are the SEQUENCE and SET data types which are collections of other ASN.1 types.  They are provided
in the same manner as the other data types except they use list of objects known as the \textbf{ltc\_asn1\_list} structure.  It is defined as the following:

\index{ltc\_asn1\_list structure}
\begin{verbatim}
typedef struct {
   ltc_asn1_type          type;
   void                  *data;
   unsigned long          size;
   int                    used;
   struct ltc_asn1_list_ *prev,  *next,
                         *child, *parent;
} ltc_asn1_list;
\end{verbatim}

\index{LTC\_SET\_ASN1 macro}
The \textit{type} field is one of the following ASN.1 field definitions.  The \textit{data} pointer is a void pointer to the data to be encoded (or the destination) and the
\textit{size} field is specific to what you are encoding (e.g. number of bits in the BIT STRING data type).  The \textit{used} field is primarily for the CHOICE decoder
and reflects if the particular member of a list was the decoded data type.  To help build the lists in an orderly fashion the macro
\textit{LTC\_SET\_ASN1(list, index, Type, Data, Size)} has been provided.

It will assign to the \textit{index}th position in the \textit{list} the triplet (Type, Data, Size).  An example usage would be:

\begin{small}
\begin{verbatim}
...
ltc_asn1_list   sequence[3];
unsigned long   three=3;

LTC_SET_ASN1(sequence, 0, LTC_ASN1_IA5_STRING,    "hello", 5);
LTC_SET_ASN1(sequence, 1, LTC_ASN1_SHORT_INTEGER, &three,  1);
LTC_SET_ASN1(sequence, 2, LTC_ASN1_NULL,           NULL,   0);
\end{verbatim}
\end{small}

The macro is relatively safe with respect to modifying variables, for instance the following code is equivalent.

\begin{small}
\begin{verbatim}
...
ltc_asn1_list   sequence[3];
unsigned long   three=3;
int             x=0;
LTC_SET_ASN1(sequence, x++, LTC_ASN1_IA5_STRING,    "hello", 5);
LTC_SET_ASN1(sequence, x++, LTC_ASN1_SHORT_INTEGER, &three,  1);
LTC_SET_ASN1(sequence, x++, LTC_ASN1_NULL,           NULL,   0);
\end{verbatim}
\end{small}

\begin{figure}[h]
\begin{center}
\begin{small}
\begin{tabular}{|l|l|}
\hline \textbf{Definition}           & \textbf{ASN.1 Type} \\
\hline LTC\_ASN1\_EOL                & End of a ASN.1 list structure. \\
\hline LTC\_ASN1\_BOOLEAN            & BOOLEAN type \\
\hline LTC\_ASN1\_INTEGER            & INTEGER (uses mp\_int) \\
\hline LTC\_ASN1\_SHORT\_INTEGER     & INTEGER (32--bit using unsigned long) \\
\hline LTC\_ASN1\_BIT\_STRING        & BIT STRING (one bit per char) \\
\hline LTC\_ASN1\_OCTET\_STRING      & OCTET STRING (one octet per char) \\
\hline LTC\_ASN1\_NULL               & NULL \\
\hline LTC\_ASN1\_OBJECT\_IDENTIFIER & OBJECT IDENTIFIER  \\
\hline LTC\_ASN1\_IA5\_STRING        & IA5 STRING (one octet per char) \\
\hline LTC\_ASN1\_PRINTABLE\_STRING  & PRINTABLE STRING (one octet per char) \\
\hline LTC\_ASN1\_UTF8\_STRING       & UTF8 STRING (one wchar\_t per char) \\
\hline LTC\_ASN1\_UTCTIME            & UTCTIME (see ltc\_utctime structure) \\
\hline LTC\_ASN1\_CHOICE             & CHOICE \\
\hline LTC\_ASN1\_SEQUENCE           & SEQUENCE (and SEQUENCE OF) \\
\hline LTC\_ASN1\_SET                & SET \\
\hline LTC\_ASN1\_SETOF              & SET OF \\
\hline LTC\_ASN1\_RAW\_BIT\_STRING   & BIT STRING (one octet per char) \\
\hline LTC\_ASN1\_TELETEX\_STRING    & TELETEX STRING (one octet per char) \\
\hline LTC\_ASN1\_CONSTRUCTED        & A constructed type that is not SEQUENCE or SET \\
\hline LTC\_ASN1\_CONTEXT\_SPECIFIC  & A context-specific type \\
\hline LTC\_ASN1\_GENERALIZEDTIME    & GeneralizedTime (see ltc\_generalizedtime structure) \\
\hline
\end{tabular}
\caption{List of ASN.1 Supported Types}
\index{ltc\_asn1\_type}
\end{small}
\end{center}
\end{figure}

\subsection{SEQUENCE Type}
The SEQUENCE data type is a collection of other ASN.1 data types encapsulated with a small header which is a useful way of sending multiple data types in one packet.

\subsubsection{SEQUENCE Encoding}
To encode a sequence a \textbf{ltc\_asn1\_list} array must be initialized with the members of the sequence and their respective pointers.  The encoding is performed
with the following function.

\index{der\_encode\_sequence()}\index{LTC\_ASN1\_EOL}
\begin{verbatim}
int der_encode_sequence(ltc_asn1_list *list,
                        unsigned long  inlen,
                        unsigned char *out,
                        unsigned long *outlen);
\end{verbatim}
This encodes a sequence of items pointed to by \textit{list} where the list has \textit{inlen} items in it.  The SEQUENCE will be encoded to \textit{out} and of length \textit{outlen}.  The
function will terminate when it reads all the items out of the list (upto \textit{inlen}) or it encounters an item in the list with a type of \textbf{LTC\_ASN1\_EOL}.

The \textit{data} pointer in the list would be the same pointer you would pass to the respective ASN.1 encoder (e.g. der\_encode\_bit\_string()) and it is simply passed on
verbatim to the dependent encoder.  The list can contain other SEQUENCE or SET types which enables you to have nested SEQUENCE and SET definitions.  In these cases
the \textit{data} pointer is simply a pointer to another \textbf{ltc\_asn1\_list}.

\subsubsection{SEQUENCE Decoding}

\index{der\_decode\_sequence()}

Decoding a SEQUENCE is similar to encoding.  You set up an array of \textbf{ltc\_asn1\_list} where in this case the \textit{size} member is the maximum size
(in certain cases).  For types such as IA5 STRING, BIT STRING, OCTET STRING (etc) the \textit{size} field is updated after successful decoding to reflect how many
units of the respective type has been loaded.

\begin{verbatim}
int der_decode_sequence(const unsigned char *in,
                              unsigned long  inlen,
                              ltc_asn1_list *list,
                              unsigned long  outlen);
\end{verbatim}

This will decode upto \textit{outlen} items from the input buffer \textit{in} of length \textit{inlen} octets.  The function will stop (gracefully) when it runs out of items to decode.
It will fail (for among other reasons) when it runs out of input bytes to read, a data type is invalid or a heap failure occurred.

For the following types the \textit{size} field will be updated to reflect the number of units read of the given type.
\begin{enumerate}
   \item BIT STRING
   \item OCTET STRING
   \item OBJECT IDENTIFIER
   \item IA5 STRING
   \item PRINTABLE STRING
\end{enumerate}

\subsubsection{SEQUENCE Length}

The length of a SEQUENCE can be determined with the following function.

\index{der\_length\_sequence()}
\begin{verbatim}
int der_length_sequence(ltc_asn1_list *list,
                        unsigned long  inlen,
                        unsigned long *outlen);
\end{verbatim}

This will get the encoding size for the given \textit{list} of length \textit{inlen} and store it in \textit{outlen}.

\subsubsection{SEQUENCE Multiple Argument Lists}\index{LTC\_ASN1\_EOL}

For small or simple sequences an encoding or decoding can be performed with one of the following two functions.

\index{der\_encode\_sequence\_multi()}
\index{der\_decode\_sequence\_multi()}

\begin{verbatim}
int der_encode_sequence_multi(unsigned char *out,
                              unsigned long *outlen, ...);

int der_decode_sequence_multi(const unsigned char *in,
                                    unsigned long  inlen, ...);
\end{verbatim}

These either encode or decode (respectively) a SEQUENCE data type where the items in the sequence are specified after the length parameter.

The list of items are specified as a triple of the form \textit{(type, size, data)}  where \textit{type} is an \textbf{int}, \textit{size} is a \textbf{unsigned long}
and \textit{data} is \textbf{void} pointer.  The list of items must be terminated with an item with the type \textbf{LTC\_ASN1\_EOL}.

It is ideal that you cast the \textit{size} values to unsigned long to ensure that the proper data type is passed to the function.  Constants such as \textit{1} without
a cast or prototype are of type \textbf{int} by default.  Appending \textit{UL} or pre-pending \textit{(unsigned long)} is enough to cast it to the correct type.

\begin{small}
\begin{verbatim}
unsigned char buf[MAXBUFSIZE];
unsigned long buflen;
int           err;

   buflen = sizeof(buf);
   if ((err =
        der_encode_sequence_multi(buf, &buflen,
        LTC_ASN1_IA5_STRING, 5UL, "Hello",
        LTC_ASN1_IA5_STRING, 7UL, " World!",
        LTC_ASN1_EOL,        0UL, NULL)) != CRYPT_OK) {
      // error handling
   }
\end{verbatim}
\end{small}

This example encodes a SEQUENCE with two IA5 STRING types containing ``Hello'' and `` World!'' respectively.  Note the usage of the \textbf{UL} modifier
on the size parameters.  This forces the compiler to pass the numbers as the required \textbf{unsigned long} type that the function expects.

\subsection{SET and SET OF}

\index{SET} \index{SET OF}
SET and SET OF are related to the SEQUENCE type in that they can be pretty much be decoded with the same code.  However, they are different, and they should
be carefully noted.  The SET type is an unordered array of ASN.1 types sorted by the TAG (type identifier), whereas the SET OF type is an ordered array of
a \textbf{single} ASN.1 object sorted in ascending order by the DER their respective encodings.

\subsubsection{SET Encoding}

SETs use the same array structure of ltc\_asn1\_list that the SEQUENCE functions use.  They are encoded with the following function:

\index{der\_encode\_set()}
\begin{verbatim}
int der_encode_set(ltc_asn1_list *list,
                   unsigned long  inlen,
                   unsigned char *out,
                   unsigned long *outlen);
\end{verbatim}

This will encode the list of ASN.1 objects in \textit{list} of length \textit{inlen} objects, and store the output in \textit{out} of length \textit{outlen} bytes.
The function will make a copy of the list provided, and sort it by the TAG.  Objects with identical TAGs are additionally sorted on their original placement in the
array (to make the process deterministic).

This function will \textbf{NOT} recognize \textit{DEFAULT} objects, and it is the responsibility of the caller to remove them as required.

\subsubsection{SET Decoding}

The SET type can be decoded with the following function.

\index{der\_decode\_set()}
\begin{verbatim}
int der_decode_set(const unsigned char *in,
                         unsigned long  inlen,
                         ltc_asn1_list *list,
                         unsigned long  outlen);
\end{verbatim}

This will decode the SET specified by \textit{list} of length \textit{outlen} objects from the input buffer \textit{in} of length \textit{inlen} octets.

It handles the fact that SETs are not strictly ordered and will make multiple passes (as required) through the list to decode all the objects.

\subsubsection{SET Length}
The length of a SET can be determined by calling der\_length\_sequence() since they have the same encoding length.

\subsubsection{SET OF Encoding}
A \textit{SET OF} object is an array of identical objects (e.g. OCTET STRING) sorted in ascending order by the DER encoding of the object.  They are
used to store objects deterministically based solely on their encoding.  It uses the same array structure of ltc\_asn1\_list that the SEQUENCE functions
use.  They are encoded with the following function.

\index{der\_encode\_setof()}
\begin{verbatim}
int der_encode_setof(ltc_asn1_list *list,
                     unsigned long  inlen,
                     unsigned char *out,
                     unsigned long *outlen);
\end{verbatim}

This will encode a \textit{SET OF} containing the \textit{list} of \textit{inlen} ASN.1 objects and store the encoding in the output buffer \textit{out} of length \textit{outlen}.

The routine will first encode the SET OF in an unordered fashion (in a temporary buffer) then sort using the XQSORT macro and copy back to the output buffer.  This
means you need at least enough memory to keep an additional copy of the output on the heap.

\subsubsection{SET OF Decoding}
Since the decoding of a \textit{SET OF} object is unambiguous it can be decoded with der\_decode\_sequence().

\subsubsection{SET OF Length}
Like the SET type the der\_length\_sequence() function can be used to determine the length of a \textit{SET OF} object.

\subsection{ASN.1 INTEGER}

To encode or decode INTEGER data types use the following functions.

\index{der\_encode\_integer()}\index{der\_decode\_integer()}\index{der\_length\_integer()}
\begin{verbatim}
int der_encode_integer(         void *num,
                       unsigned char *out,
                       unsigned long *outlen);

int der_decode_integer(const unsigned char *in,
                             unsigned long  inlen,
                                      void *num);

int der_length_integer(         void *num,
                       unsigned long *len);
\end{verbatim}

These will encode or decode a signed INTEGER data type using the bignum data type to store the large INTEGER.  To encode smaller values without allocating
a bignum to store the value, the \textit{short} INTEGER functions were made available.

\index{der\_encode\_short\_integer()}\index{der\_decode\_short\_integer()}\index{der\_length\_short\_integer()}
\begin{verbatim}
int der_encode_short_integer(unsigned long  num,
                             unsigned char *out,
                             unsigned long *outlen);

int der_decode_short_integer(const unsigned char *in,
                                   unsigned long  inlen,
                                   unsigned long *num);

int der_length_short_integer(unsigned long  num,
                             unsigned long *outlen);
\end{verbatim}

These will encode or decode an unsigned \textbf{unsigned long} type (only reads upto 32--bits).  For values in the range $0 \dots 2^{32} - 1$ the integer
and short integer functions can encode and decode each others outputs.

\subsection{ASN.1 BIT STRING}

\index{der\_encode\_bit\_string()}\index{der\_decode\_bit\_string()}\index{der\_length\_bit\_string()}
\begin{verbatim}
int der_encode_bit_string(const unsigned char *in,
                                unsigned long  inlen,
                                unsigned char *out,
                                unsigned long *outlen);

int der_decode_bit_string(const unsigned char *in,
                                unsigned long  inlen,
                                unsigned char *out,
                                unsigned long *outlen);

int der_length_bit_string(unsigned long  nbits,
                          unsigned long *outlen);
\end{verbatim}

These will encode or decode a BIT STRING data type.  The bits are passed in (or read out) using one \textbf{char} per bit.  A non--zero value will be interpreted
as a one bit, and a zero value a zero bit.

\subsection{ASN.1 RAW BIT STRING}

\index{der\_encode\_raw\_bit\_string()}\index{der\_decode\_raw\_bit\_string()}
\begin{verbatim}
int der_encode_raw_bit_string(const unsigned char *in,
                                    unsigned long  inlen,
                                    unsigned char *out,
                                    unsigned long *outlen);

int der_decode_raw_bit_string(const unsigned char *in,
                                    unsigned long  inlen,
                                    unsigned char *out,
                                    unsigned long *outlen);
\end{verbatim}

These will encode or decode a BIT STRING data type.
The bits are passed in (or read out) using one \textbf{unsigned char} per 8 bit.

This function differs from the normal BIT STRING, as it can be used to directly
process raw binary data and store it to resp. read it from an ASN.1 BIT STRING
data type.

The length function is the same as for the normal BIT STRING \textit{der\_length\_bit\_string()}.

\subsection{ASN.1 OCTET STRING}

\index{der\_encode\_octet\_string()}\index{der\_decode\_octet\_string()}\index{der\_length\_octet\_string()}
\begin{verbatim}
int der_encode_octet_string(const unsigned char *in,
                                  unsigned long  inlen,
                                  unsigned char *out,
                                  unsigned long *outlen);

int der_decode_octet_string(const unsigned char *in,
                                  unsigned long  inlen,
                                  unsigned char *out,
                                  unsigned long *outlen);

int der_length_octet_string(unsigned long  noctets,
                            unsigned long *outlen);
\end{verbatim}

These will encode or decode an OCTET STRING data type.  The octets are stored using one \textbf{unsigned char} each.

\subsection{ASN.1 OBJECT IDENTIFIER}

\index{der\_encode\_object\_identifier()}\index{der\_decode\_object\_identifier()}\index{der\_length\_object\_identifier()}
\begin{verbatim}
int der_encode_object_identifier(unsigned long *words,
                                 unsigned long  nwords,
                                 unsigned char *out,
                                 unsigned long *outlen);

int der_decode_object_identifier(const unsigned char *in,
                                       unsigned long  inlen,
                                       unsigned long *words,
                                       unsigned long *outlen);

int der_length_object_identifier(unsigned long *words,
                                 unsigned long  nwords,
                                 unsigned long *outlen);
\end{verbatim}

These will encode or decode an OBJECT IDENTIFIER object.  The words of the OID are stored in individual \textbf{unsigned long} elements, and must be in the range
$0 \ldots 2^{32} - 1$.

\subsection{ASN.1 IA5 STRING}

\index{der\_encode\_ia5\_string()}\index{der\_decode\_ia5\_string()}\index{der\_length\_ia5\_string()}
\begin{verbatim}
int der_encode_ia5_string(const unsigned char *in,
                                unsigned long  inlen,
                                unsigned char *out,
                                unsigned long *outlen);

int der_decode_ia5_string(const unsigned char *in,
                                unsigned long  inlen,
                                unsigned char *out,
                                unsigned long *outlen);

int der_length_ia5_string(const unsigned char *octets,
                                unsigned long  noctets,
                                unsigned long *outlen);
\end{verbatim}

These will encode or decode an IA5 STRING.  The characters are read or stored in individual \textbf{char} elements.  These functions performs internal character
to numerical conversions based on the conventions of the compiler being used.  For instance, on an x86\_32 machine 'A' == 65 but the same may not be true on
say a SPARC machine.  Internally, these functions have a table of literal characters and their numerical ASCII values.  This provides a stable conversion provided
that the build platform honours the run--time platforms character conventions.

\subsection{ASN.1 TELETEX STRING}

\index{der\_decode\_teletex\_string()}\index{der\_length\_teletex\_string()}
\begin{verbatim}
int der_decode_teletex_string(const unsigned char *in,
                                    unsigned long  inlen,
                                    unsigned char *out,
                                    unsigned long *outlen);

int der_length_teletex_string(const unsigned char *octets,
                                    unsigned long  noctets,
                                    unsigned long *outlen);
\end{verbatim}

These will decode a TELETEX STRING.
The characters are read in individual \textbf{char} elements.
The internal structure is similar to that of the IA5 STRING implementation, to
be able to provide a stable conversion independent of the build-- and run--time
platform.

\subsection{ASN.1 PRINTABLE STRING}

\index{der\_encode\_printable\_string()}\index{der\_decode\_printable\_string()}\index{der\_length\_printable\_string()}
\begin{verbatim}
int der_encode_printable_string(const unsigned char *in,
                                      unsigned long  inlen,
                                      unsigned char *out,
                                      unsigned long *outlen);

int der_decode_printable_string(const unsigned char *in,
                                      unsigned long  inlen,
                                      unsigned char *out,
                                      unsigned long *outlen);

int der_length_printable_string(const unsigned char *octets,
                                      unsigned long  noctets,
                                      unsigned long *outlen);
\end{verbatim}

These will encode or decode an PRINTABLE STRING.  The characters are read or stored in individual \textbf{char} elements.  These functions performs internal character
to numerical conversions based on the conventions of the compiler being used.  For instance, on an x86\_32 machine 'A' == 65 but the same may not be true on
say a SPARC machine.  Internally, these functions have a table of literal characters and their numerical ASCII values.  This provides a stable conversion provided
that the build platform honours the run-time platforms character conventions.

\subsection{ASN.1 UTF8 STRING}

\index{der\_encode\_utf8\_string()}\index{der\_decode\_utf8\_string()}\index{der\_length\_utf8\_string()}
\begin{verbatim}
int der_encode_utf8_string(const wchar_t *in,
                           unsigned long  inlen,
                           unsigned char *out,
                           unsigned long *outlen);

int der_decode_utf8_string(const unsigned char *in,
                                 unsigned long  inlen,
                                       wchar_t *out,
                                 unsigned long *outlen);

int der_length_utf8_string(const wchar_t *octets,
                           unsigned long  noctets,
                           unsigned long *outlen);
\end{verbatim}

These will encode or decode an UTF8 STRING.  The characters are read or stored in individual \textbf{wchar\_t} elements.  These function performs no internal
mapping and treat the characters as literals.

These functions use the \textbf{wchar\_t} type which is not universally available.  In those cases, the library will typedef it to \textbf{unsigned long}.  If you
intend to use the ISO C functions for working with wide--char arrays, you should make sure that wchar\_t has been defined previously.

\subsection{ASN.1 UTCTIME}

The UTCTIME type is to store a date and time in ASN.1 format.  It uses the following structure to organize the time.

\index{ltc\_utctime structure}
\begin{verbatim}
typedef struct {
   unsigned YY, /* year    00--99 */
            MM, /* month   01--12 */
            DD, /* day     01--31 */
            hh, /* hour    00--23 */
            mm, /* minute  00--59 */
            ss, /* second  00--59 */
            off_dir, /* timezone offset direction 0 == +, 1 == - */
            off_hh, /* timezone offset hours */
            off_mm; /* timezone offset minutes */
} ltc_utctime;
\end{verbatim}

The time can be offset plus or minus a set amount of hours (off\_hh) and minutes (off\_mm).  When \textit{off\_dir} is zero, the time will be added otherwise it
will be subtracted.  For instance, the array $\lbrace 5, 6, 20, 22, 4, 00, 0, 5, 0 \rbrace$ represents the current time of
\textit{2005, June 20th, 22:04:00} with a time offset of +05h00.

\index{der\_encode\_utctime()}\index{der\_decode\_utctime()}\index{der\_length\_utctime()}
\begin{verbatim}
int der_encode_utctime(  ltc_utctime *utctime,
                       unsigned char *out,
                       unsigned long *outlen);

int der_decode_utctime(const unsigned char *in,
                             unsigned long *inlen,
                               ltc_utctime *out);

int der_length_utctime(  ltc_utctime *utctime,
                       unsigned long *outlen);
\end{verbatim}

The encoder will store time in one of the two ASN.1 formats, either \textit{YYMMDDhhmmssZ} or \textit{YYMMDDhhmmss$\pm$hhmm}, and perform minimal error checking on the
input.  The decoder will read all valid ASN.1 formats and perform range checking on the values (not complete but rational) useful for catching packet errors.

It is suggested that decoded data be further scrutinized (e.g. days of month in particular).

\subsection{ASN.1 GeneralizedTime}

The GeneralizedTime type is to store a date and time in ASN.1 format.  It uses the following structure to organize the time.

\index{ltc\_utctime structure}
\begin{verbatim}
typedef struct {
   unsigned YYYY, /* year              0--9999 */
            MM, /* month               1--12 */
            DD, /* day                 1--31 */
            hh, /* hour                0--23 */
            mm, /* minute              0--59 */
            ss, /* second              0--59 */
            fs, /* fractional seconds  1--UINT_MAX */
            off_dir, /* timezone offset direction 0 == +, 1 == - */
            off_hh, /* timezone offset hours */
            off_mm; /* timezone offset minutes */
} ltc_generalizedtime;
\end{verbatim}

The time can be offset plus or minus a set amount of hours (off\_hh) and minutes (off\_mm).  When \textit{off\_dir} is zero, the time will be added otherwise it
will be subtracted.  For instance, the array $\lbrace 2005, 6, 20, 22, 4, 0, 122, 0, 5, 0 \rbrace$ represents the current time of
\textit{2005, June 20th, 22:04:00.122} with a time offset of +05h00.

\index{der\_encode\_utctime()}\index{der\_decode\_utctime()}\index{der\_length\_utctime()}
\begin{verbatim}
int der_encode_generalizedtime(ltc_generalizedtime *gtime,
                               unsigned char       *out,
                               unsigned long       *outlen);

int der_decode_generalizedtime(const unsigned char *in,
                               unsigned long       *inlen,
                               ltc_generalizedtime *out);

int der_length_generalizedtime(ltc_generalizedtime *gtime,
                               unsigned long       *outlen);
\end{verbatim}

The encoder will store time in one of the following ASN.1 formats, either \textit{YYYYMMDDhhmmssZ} or
\textit{YYYYMMDDhhmmss$\pm$hhmm} or\textit{YYYYMMDDhhmmss.fsZ} or \textit{YYYYMMDDhhmmss.fs$\pm$hhmm},
and perform minimal error checking on the input.
The decoder will read all valid ASN.1 formats and perform range checking on the values (not complete but
rational) useful for catching packet errors.

The fractional seconds are always added in case they are not $0$.
The implementation of fractional seconds is currently unreliable and you can't detect decoded
resp. encode leading $0$'s (e.g. \textit{20170424232717.005Z} would be decoded as
\textit{22. April 2017, 23:27:17.5}).

It is suggested that decoded data be further scrutinized (e.g. days of month in particular).

\subsection{ASN.1 CHOICE}

The CHOICE ASN.1 type represents a union of ASN.1 types all of which are stored in a \textit{ltc\_asn1\_list}.  There is no encoder for the CHOICE type, only a
decoder.  The decoder will scan through the provided list attempting to use the appropriate decoder on the input packet.  The list can contain any ASN.1 data
type\footnote{Except it cannot have LTC\_ASN1\_INTEGER and LTC\_ASN1\_SHORT\_INTEGER simultaneously.} except for other CHOICE types.

There is no encoder for the CHOICE type as the actual DER encoding is the encoding of the chosen type.

\index{der\_decode\_choice()}
\begin{verbatim}
int der_decode_choice(const unsigned char *in,
                            unsigned long *inlen,
                            ltc_asn1_list *list,
                            unsigned long  outlen);
\end{verbatim}

This will decode the input in the \textit{in} field of length \textit{inlen}.  It uses the provided ASN.1 list specified in the \textit{list} field which has
\textit{outlen} elements.  The \textit{inlen} field will be updated with the length of the decoded data type, as well as the respective entry in the \textit{list} field
will have the \textit{used} flag set to non--zero to reflect it was the data type decoded.

\subsection{ASN.1 Flexi Decoder}
The ASN.1 \textit{flexi} decoder allows the developer to decode arbitrary ASN.1 DER packets (provided they use data types LibTomCrypt supports) without first knowing
the structure of the data.  Where der\_decode\_sequence() requires the developer to specify the data types to decode in advance the flexi decoder is entirely
free form.

The flexi decoder uses the same \textit{ltc\_asn1\_list} but instead of being stored in an array it uses the linked list pointers \textit{prev}, \textit{next}, \textit{parent}
and \textit{child}.  The list works as a \textit{doubly-linked list} structure where decoded items at the same level are siblings (using next and prev) and items
encoded in a SEQUENCE are stored as a child element.

When a SEQUENCE or SET has been encountered a SEQUENCE (or SET resp.) item will be added as a sibling (e.g. list.type == LTC\_ASN1\_SEQUENCE) and the child
pointer points to a new list of items contained within the object.

\index{der\_decode\_sequence\_flexi()}
\index{LTC\_ASN1\_CONSTRUCTED}
\index{LTC\_ASN1\_CONTEXT\_SPECIFIC}
\begin{verbatim}
int  der_decode_sequence_flexi(const unsigned char *in,
                                     unsigned long *inlen,
                                    ltc_asn1_list **out);
\end{verbatim}

This will decode items in the \textit{in} buffer of max input length \textit{inlen} and store the newly created pointer to the list in \textit{out}.  This function allocates
all required memory for the decoding.  It stores the number of octets read back into \textit{inlen}.

The function will terminate when either it hits an invalid ASN.1 tag, or it reads \textit{inlen} octets.  An early termination is a soft error, and returns
normally.  The decoded list \textit{out} will point to the very first element of the list (e.g. both parent and prev pointers will be \textbf{NULL}).

An invalid decoding will terminate the process, and free the allocated memory automatically.

The flexi decoder calls itself when decoding a constructed type. This leads to
a 'child process' that will terminate when it decodes an unkown/invalid
identifier and leaves an allocated but uninitialized child element.
However the parent processing will continue with a "soft-error".
This can be detected by checking for \textit{child} elements with
type \textbf{LTC\_ASN1\_EOL} after decoding.

As of v1.18.0 the flexi decoder will also decode arbitrary constructed types
other than SEQUENCE and SET. The \textit{type} field will be set to
\textbf{LTC\_ASN1\_CONSTRUCTED} and the plain identifier that was indicated in the ASN.1
encoding is stored in the \textit{used} field. Further decoding is done in the
same way as if it were a SEQUENCE or SET.

Also as of v1.18.0 the flexi decoder is capable to handle
\textit{context-specific} encodings. The \textit{type} field will be set to
\textbf{LTC\_ASN1\_CONTEXT\_SPECIFIC} and the plain identifier that was indicated
in the ASN.1 encoding is stored in the \textit{used} field. Encapsulated data
in the \textit{context-specific} encoding is copied to newly allocated memory
and is accessible through the \textit{data} field.

\textbf{Note:} the list decoded by this function is \textbf{NOT} in the correct form for der\_encode\_sequence() to use directly.  You will first
have to convert the list by first storing all of the siblings in an array then storing all the children as sub-lists of a sequence using the \textit{.data}
pointer.  Currently no function in LibTomCrypt provides this ability.

\subsubsection{Sample Decoding}
Suppose we decode the following structure:
\begin{small}
\begin{verbatim}
User ::= SEQUENCE {
   Name        IA5 STRING
   LoginToken  SEQUENCE {
      passwdHash   OCTET STRING
      pubkey       ECCPublicKey
   }
   LastOn      UTCTIME
}
\end{verbatim}
\end{small}
\begin{flushleft}and we decoded it with the following code:\end{flushleft}

\begin{small}
\begin{verbatim}
unsigned char inbuf[MAXSIZE];
unsigned long inbuflen;
ltc_asn1_list *list;
int           err;

/* somehow fill inbuf/inbuflen */
if ((err = der_decode_sequence_flexi(inbuf, inbuflen, &list)) != CRYPT_OK) {
   printf("Error decoding: %s\n", error_to_string(err));
   exit(EXIT_FAILURE);
}
\end{verbatim}
\end{small}

At this point \textit{list} would point to the SEQUENCE identified by \textit{User}.  It would have no sibblings (prev or next), and only a child node.  Walking to the child
node with the following code will bring us to the \textit{Name} portion of the SEQUENCE:
\begin{small}
\begin{verbatim}
list = list->child;
\end{verbatim}
\end{small}
Now \textit{list} points to the \textit{Name} member (with the tag IA5 STRING).  The \textit{data}, \textit{size}, and \textit{type} members of \textit{list} should reflect
that of an IA5 STRING.  The sibbling will now be the \textit{LoginToken} SEQUENCE.  The sibbling has a child node which points to the \textit{passwdHash} OCTET STRING.
We can walk to this node with the following code:
\begin{small}
\begin{verbatim}
/* list already pointing to 'Name' */
list = list->next->child;
\end{verbatim}
\end{small}
At this point, \textit{list} will point to the \textit{passwdHash} member of the innermost SEQUENCE.  This node has a sibbling, the \textit{pubkey} member of the SEQUENCE.
The \textit{LastOn} member of the SEQUENCE is a sibbling of the LoginToken node, if we wanted to walk there we would have to go up and over via:
\begin{small}
\begin{verbatim}
list = list->parent->next;
\end{verbatim}
\end{small}
At this point, we are pointing to the last node of the list.  Lists are terminated in all directions by a \textbf{NULL} pointer.  All nodes are doubly linked so that you
can walk up and down the nodes without keeping pointers lying around.


\subsubsection{Shrink'ing a Flexi List}
While decoding the flexi decoder will recursively decode an ASN.1 \textit{constructed} type it will store the decoded list
as well as the plain data that was decoded.
To free up this additional data a shrink function is provided.

\index{der\_sequence\_shrink()}
\begin{verbatim}
void der_sequence_shrink(ltc_asn1_list *in);
\end{verbatim}

This will free all the plain constructed data, but keep the decoded list intact.

\subsubsection{Free'ing a Flexi List}
To free the list use the following function.

\index{der\_sequence\_free()}
\begin{verbatim}
void der_sequence_free(ltc_asn1_list *in);
\end{verbatim}

This will free all of the memory allocated by der\_decode\_sequence\_flexi().

\mysection{Password Based Cryptography}
\subsection{PKCS \#5}
\index{PKCS \#5}
In order to securely handle user passwords for the purposes of creating session keys and chaining IVs the PKCS \#5 was drafted.   PKCS \#5
is made up of two algorithms, Algorithm One and Algorithm Two.  Algorithm One is the older fairly limited algorithm which has been implemented
for completeness.  Algorithm Two is a bit more modern and more flexible to work with.

The OpenSSL project implemented an extension to Algorithm One that allows for arbitrary keylengths; we have a compatible implementation described below.

\subsection{Algorithm One}
Algorithm One accepts as input a password, an 8--byte salt, and an iteration counter.  The iteration counter is meant to act as delay for
people trying to brute force guess the password.  The higher the iteration counter the longer the delay.  This algorithm also requires a hash
algorithm and produces an output no longer than the output of the hash.

\index{pkcs\_5\_alg1()}
\begin{alltt}
int pkcs_5_alg1(const unsigned char *password,
                      unsigned long  password_len,
                const unsigned char *salt,
                                int  iteration_count,
                                int  hash_idx,
                      unsigned char *out,
                      unsigned long *outlen)
\end{alltt}
Where \textit{password} is the user's password.  Since the algorithm allows binary passwords you must also specify the length in \textit{password\_len}.
The \textit{salt} is a fixed size 8--byte array which should be random for each user and session.  The \textit{iteration\_count} is the delay desired
on the password.  The \textit{hash\_idx} is the index of the hash you wish to use in the descriptor table.

The output of length up to \textit{outlen} is stored in \textit{out}.  If \textit{outlen} is initially larger than the size of the hash functions output
it is set to the number of bytes stored.  If it is smaller than not all of the hash output is stored in \textit{out}.

\index{pkcs\_5\_alg1\_openssl()}
\begin{alltt}
int pkcs_5_alg1_openssl(const unsigned char *password,
                      unsigned long  password_len,
                const unsigned char *salt,
                                int  iteration_count,
                                int  hash_idx,
                      unsigned char *out,
                      unsigned long *outlen)
\end{alltt}
As above, but we generate as many bytes as requested in outlen per the OpenSSL extension to Algorithm One.  If you are trying to be compatible with OpenSSL's EVP\_BytesToKey() or the "openssl enc" command line (or variants such as perl's Crypt::CBC), then use this function with MD5 as your hash (ick!) and iteration\_count=1 (double-ick!!).
\subsection{Algorithm Two}

Algorithm Two is the recommended algorithm for this task.  It allows variable length salts, and can produce outputs larger than the
hash functions output.  As such, it can easily be used to derive session keys for ciphers and MACs as well initialization vectors as required
from a single password and invocation of this algorithm.

\index{pkcs\_5\_alg2()}
\begin{alltt}
int pkcs_5_alg2(const unsigned char *password,
                      unsigned long  password_len,
                const unsigned char *salt,
                      unsigned long  salt_len,
                                int  iteration_count,
                                int  hash_idx,
                      unsigned char *out,
                      unsigned long *outlen)
\end{alltt}
Where \textit{password} is the users password.  Since the algorithm allows binary passwords you must also specify the length in \textit{password\_len}.
The \textit{salt} is an array of size \textit{salt\_len}.  It should be random for each user and session.  The \textit{iteration\_count} is the delay desired
on the password.  The \textit{hash\_idx} is the index of the hash you wish to use in the descriptor table.   The output of length up to
\textit{outlen} is stored in \textit{out}.

\begin{verbatim}
/* demo to show how to make session state material
 * from a password */
#include <tomcrypt.h>
int main(void)
{
    unsigned char password[100], salt[100],
                  cipher_key[16], cipher_iv[16],
                  mac_key[16], outbuf[48];
    int           err, hash_idx;
    unsigned long outlen, password_len, salt_len;

    /* register hash and get it's idx .... */

    /* get users password and make up a salt ... */

    /* create the material (100 iterations in algorithm) */
    outlen = sizeof(outbuf);
    if ((err = pkcs_5_alg2(password, password_len, salt,
                           salt_len, 100, hash_idx, outbuf,
                           &outlen))
       != CRYPT_OK) {
       /* error handle */
    }

    /* now extract it */
    memcpy(cipher_key, outbuf, 16);
    memcpy(cipher_iv,  outbuf+16, 16);
    memcpy(mac_key,    outbuf+32, 16);

    /* use material (recall to store the salt in the output) */
}
\end{verbatim}

\mysection{Key Derviation Functions}
\subsection{HKDF}
\index{HKDF}
A key derivation function (KDF) is a basic and essential component of cryptographic systems.  Its goal is to take some source of initial
keying material and derive from it one or more cryptographically strong secret keys.

HKDF follows the "extract-then-expand" paradigm, where the KDF logically consists of two modules.  The first stage takes the input
keying material and "extracts" from it a fixed-length pseudorandom key K.  The second stage "expands" the key K into several additional
pseudorandom keys (the output of the KDF).

In many applications, the input keying material is not necessarily distributed uniformly, and the attacker may have some partial
knowledge about it (for example, a Diffie-Hellman value computed by a key exchange protocol) or even partial control of it (as in some
entropy-gathering applications).  Thus, the goal of the "extract" stage is to "concentrate" the possibly dispersed entropy of the input
keying material into a short, but cryptographically strong, pseudorandom key.  In some applications, the input may already be a
good pseudorandom key; in these cases, the "extract" stage is not necessary, and the "expand" part can be used alone.

The second stage "expands" the pseudorandom key to the desired length; the number and lengths of the output keys depend on the
specific cryptographic algorithms for which the keys are needed.

\subsection{HKDF Extract}
To perform the extraction phase, use the following function:

\index{hkdf\_extract()}
\begin{alltt}
int hkdf_extract(   int  hash_idx,
    const unsigned char *salt,
          unsigned long  saltlen,
    const unsigned char *in,
          unsigned long  inlen,
          unsigned char *out,
          unsigned long *outlen);
\end{alltt}
The \textit{hash\_idx} parameter is the index into the descriptor table of the hash you want to use.
The \textit{salt} parameter is a pointer to the array of octets of length \textit{saltlen} containing the salt or a NULL pointer if a salt is not being used (in that case set saltlen to 0).
\textit{in} is a pointer to an array of octets of length \textit{inlen} containing the source entropy.  The extracted output is stored in the location pointed to by \textit{out}.
You must set \textit{outlen} to the size of the destination buffer before calling this function. It is updated to the length of the extracted output. If \textit{outlen} is too small the extracted output will be truncated.

While the salt is optional, using one improves HKDF's security. If used, the salt should be randomly chosen, but does not need to be secret and may be re-used. Please see RFC5869 section 3.1 for more details.

\subsection{HKDF Expand}
To perform the expansion phase, use the following function:

\index{hkdf\_expand()}
\begin{alltt}
int hkdf_expand(    int  hash_idx,
    const unsigned char *info,
          unsigned long  infolen,
    const unsigned char *in,
          unsigned long  inlen,
          unsigned char *out,
          unsigned long  outlen);
\end{alltt}

The \textit{hash\_idx} parameter is the index into the descriptor table of the hash you want to use.
The \textit{info} parameter, an array of octets of length \textit{infolen}, is an optional parameter (set \textit{info} to NULL and \textit{infolen} to 0 if not using it) which
may be used to bind the derived keys to some application and context specific information. This prevents the same keying material from being generated in different contexts. Please see RFC5869 section 3.2 for more information.
The extracted keying material is passed as octet array \textit{in} of length \textit{inlen}.  Expanded output of length \textit{outlen} is generated and stored in octet arrat \textit{out}.

\subsection{HKDF Extract-and-Expand}
To perform both phases together, use the following function:

\index{hkdf()}
\begin{alltt}
int hkdf(           int  hash_idx,
    const unsigned char *salt,
          unsigned long  saltlen,
    const unsigned char *info,
          unsigned long  infolen,
    const unsigned char *in,
          unsigned long  inlen,
          unsigned char *out,
          unsigned long  outlen);
\end{alltt}

Parameters are as in \textit{hkdf\_extract()} and \textit{hkdf\_expand()}.

\chapter{Miscellaneous}
\mysection{Base64 Encoding and Decoding}
The library provides functions to encode and decode a RFC 4648 Base64 coding scheme.

\subsection{Standard 'base64' encoding}
The characters used in the mappings are:
\begin{verbatim}
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
\end{verbatim}
Those characters are supported in the 7-bit ASCII map, which means they can be used for transport over
common e-mail, usenet and HTTP mediums.  The format of an encoded stream is just a literal sequence of ASCII characters
where a group of four represent 24-bits of input.  The first four chars of the encoders output is the length of the
original input.  After the first four characters is the rest of the message.

Often, it is desirable to line wrap the output to fit nicely in an e-mail or usenet posting.  The decoder allows you to
put any character (that is not in the above sequence) in between any character of the encoders output.  You may not however,
break up the first four characters.

To encode a binary string in base64 call:
\index{base64\_encode()}
\begin{verbatim}
int base64_encode(const unsigned char *in,
                        unsigned long  len,
                        unsigned char *out,
                        unsigned long *outlen);
\end{verbatim}
Where \textit{in} is the binary string and \textit{out} is where the ASCII output is placed.  You must set the value of \textit{outlen} prior
to calling this function and it sets the length of the base64 output in \textit{outlen} when it is done.  To decode a base64
string call:
\index{base64\_decode()}
\begin{verbatim}
int base64_decode(const unsigned char *in,
                        unsigned long  len,
                        unsigned char *out,
                        unsigned long *outlen);
\end{verbatim}

The function \textit{base64\_decode} works in a relaxed way which allows decoding some inputs that do not strictly follow the standard.
If you want to be strict during decoding you can use:
\index{base64\_strict\_decode()}
\begin{verbatim}
int base64_strict_decode(const unsigned char *in,
                               unsigned long  len,
                               unsigned char *out,
                               unsigned long *outlen);
\end{verbatim}

\subsection{URL--safe 'base64url' encoding}
The characters used in the mappings are:
\begin{verbatim}
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_
\end{verbatim}
Those characters are sometimes also called URL and filename safe alphabet.
The interface is analogous to \textit{base64\_xxxx} functions in previous chapter.

\begin{verbatim}
int base64url_encode(const unsigned char *in,  unsigned long len,
                           unsigned char *out, unsigned long *outlen);

int base64url_strict_encode(const unsigned char *in,  unsigned long inlen,
                                  unsigned char *out, unsigned long *outlen);

int base64url_decode(const unsigned char *in,  unsigned long len,
                           unsigned char *out, unsigned long *outlen);

int base64url_strict_decode(const unsigned char *in,  unsigned long len,
                                  unsigned char *out, unsigned long *outlen);
\end{verbatim}

\mysection{Primality Testing}
\index{Primality Testing}
The library includes primality testing and random prime functions as well.  The primality tester will perform the test in
two phases.  First it will perform trial division by the first few primes.  Second it will perform \textit{LTC\_MILLER\_RABIN\_REPS} (pre-defined to $35$) rounds of the
Rabin-Miller primality testing algorithm.  If the candidate passes both phases it is declared prime otherwise it is declared
composite.  No prime number will fail the two phases but composites can.  Each round of the Rabin-Miller algorithm reduces
the probability of a pseudo-prime by $1 \over 4$ therefore after sixteen rounds the probability is no more than
$\left ( { 1 \over 4 } \right )^{8} = 2^{-16}$.  In practice the probability of error is in fact much lower than that.

When making random primes the trial division step is in fact an optimized implementation of \textit{Implementation of Fast RSA Key Generation on Smart Cards}\footnote{Chenghuai Lu, Andre L. M. dos Santos and Francisco R. Pimentel}.
In essence a table of machine-word sized residues are kept of a candidate modulo a set of primes.  When the candidate
is rejected and ultimately incremented to test the next number the residues are updated without using multi-word precision
math operations.  As a result the routine can scan ahead to the next number required for testing with very little work
involved.

In the event that a composite did make it through it would most likely cause the the algorithm trying to use it to fail.  For
instance, in RSA two primes $p$ and $q$ are required.  The order of the multiplicative sub-group (modulo $pq$) is given
as $\phi(pq)$ or $(p - 1)(q - 1)$.  The decryption exponent $d$ is found as $de \equiv 1\mbox{ }(\mbox{mod } \phi(pq))$.  If either $p$ or $q$ is composite the value of $d$ will be incorrect and the user
will not be able to sign or decrypt messages at all.  Suppose $p$ was prime and $q$ was composite this is just a variation of
the multi-prime RSA.  Suppose $q = rs$ for two primes $r$ and $s$ then $\phi(pq) = (p - 1)(r - 1)(s - 1)$ which clearly is
not equal to $(p - 1)(rs - 1)$.

These are not technically part of the LibTomMath library but this is the best place to document them.
To test if a \textit{mp\_int} is prime call:
\begin{verbatim}
int is_prime(mp_int *N, int *result);
\end{verbatim}
This puts a one in \textit{result} if the number is probably prime, otherwise it places a zero in it.  It is assumed that if
it returns an error that the value in \textit{result} is undefined.  To make
a random prime call:
\begin{verbatim}
int rand_prime(       mp_int *N,
               unsigned long len,
                  prng_state *prng,
                         int  wprng);
\end{verbatim}
Where \textit{len} is the size of the prime in bytes ($2 \le len \le 256$).  You can set \textit{len} to the negative size you want
to get a prime of the form $p \equiv 3\mbox{ }(\mbox{mod } 4)$.  So if you want a 1024-bit prime of this sort pass
\textit{len = -128} to the function.  Upon success it will return {\bf CRYPT\_OK} and \textit{N} will contain an integer which
is very likely prime.

\mysection{Random MPI Generation}
\index{Random MPI Generation}

Several Public Key Cryptography algorithms require random MPI's for operations like signature generation.
The library provides two API functions to generate random MPI's which allow the utilisation of a user-defined PRNG to aquire the random data.

\index{rand\_bn\_bits()}
\begin{verbatim}
int rand_bn_bits(       void *N,
                         int bits,
                  prng_state *prng,
                         int wprng);
\end{verbatim}

This sets \textit{N} to a \textit{bits}-long random MPI.

\index{rand\_bn\_upto()}
\begin{verbatim}
int rand_bn_upto(       void *N,
                        void *limit,
                  prng_state *prng,
                         int wprng);
\end{verbatim}

This ensures that \textit{N} is set to a random MPI in the range $1 \le N < limit$.


\mysection{Helper functions}

\subsection{Zero'ing data}

As widely know optimizing-compilers are sometimes allowed to remove an invocation of \textit{memset(out, 0, outlen)}, which could result
in sensitive data beeing not zero'ed out. Therefore LibTomCrypt implements a variant of this routine which won't be optimized-away.

\index{zeromem()}
\begin{verbatim}
void zeromem(volatile void *out, size_t outlen);
\end{verbatim}

This zero's the buffer \textit{out} of size \textit{outlen}.

\subsection{Constant-time memory compare}

Some symmetric-key cryptographic operation-modes are vulnerable to timing attacks in case non-contant-time memory comparison functions
are used to compare results. Therefore LibTomCrypt implements a constant-time memory compare function.

\index{mem\_neq()}
\begin{verbatim}
int mem_neq(const void *a, const void *b, size_t len);
\end{verbatim}

This will compare the buffer \textit{a} against the buffer \textit{b} for \textit{len} bytes.
The return value is either \textit{0} when the content of \textit{a} and \textit{b} is equal or \textit{1} when it differs.

\subsection{Radix to binary conversion}

All public-key cryptographic algorithms provide a way to import and/or export their key parameters in binary format.
In order to be able to import keys stored in different formats, e.g. hexadecimal strings, the \textit{radix\_to\_bin()} function is provided.

\index{radix\_to\_bin()}
\begin{verbatim}
int radix_to_bin(const void *in, int radix, void *out, unsigned long *len);
\end{verbatim}

This will convert the MPI \textit{in} of radix \textit{radix} to the buffer pointed to by \textit{out}.
The field \textit{len} is a pointer to the length of the buffer on input and the length stored on output.

In case you don't know the length of the buffer you can use \textit{radix\_to\_bin()} to determine the length for you.

\begin{verbatim}
#include <tomcrypt.h>

int main(void)
{
   const char *mpi = "AABBCCDD";
   unsigned long l = 0;
   void* buf;
   int ret;
   ltc_mp = ltm_desc;

   if (radix_to_bin(mpi, 16, NULL, &l) != CRYPT_BUFFER_OVERFLOW)
      return EXIT_FAILURE;
   buf = malloc(l);

   ret = EXIT_SUCCESS;
   if (radix_to_bin(mpi, 16, buf, &l) != CRYPT_OK)
      ret = EXIT_FAILURE;

   free(buf);
   return ret;
}
\end{verbatim}


\mysection{Dynamic Language Support}
\index{Dynamic Language Support}
Various LibTomCrypt functions require that their callers define a struct
(or a union) and provide a pointer to it, or allocate sufficient memory and
provide its pointer.  Programs written in C or C++ can obtain the necessary
information by simply including the appropriate header files, but dynamic
languages like Python don't understand C header files, and without assistance,
have no way to know how much memory to allocate.  A similar story can be told
for certain LTC constant values.

LTC's Dynamic Language Support provides functions that return the size of
a named struct or union, the value of a named constant, a list of all sizes
supported, and a list of all named constants supported.  Two additional
functions can initialize LTM and TFM.

To get the size of a named struct or union:
\begin{verbatim}
int crypt_get_size(  const char *namein,
                   unsigned int *sizeout);
\end{verbatim}
$namein$ is spelled exactly as found in the C header files.  This function will
return -1 if $namein$ is not found.

To get the value of a named constant:
\begin{verbatim}
int crypt_get_constant(const char *namein,
                              int *valueout);
\end{verbatim}
$namein$ is spelled exactly as found in the C header files.  Again, -1 is
returned if $namein$ is not found.

To get the names of all the supported structs, unions and constants:
\begin{verbatim}
int crypt_list_all_sizes(        char *names_list,
                         unsigned int *names_list_size);

int crypt_list_all_constants(        char *names_list,
                             unsigned int *names_list_size);
\end{verbatim}
You may want to call these functions twice, first to get the amount
of memory to be allocated for the $names_list$, and a final time to
actually populate $names_list$.  If $names_list$ is NULL,
$names_list_size$ will be the minimum size needed to receive the
complete $names_list$.  If $names_list$ is NOT NULL, $names_list$ must
be a pointer to sufficient memory into which the $names_list$ will be
written.  Also, the value in $names_list_size$ sets the upper bound of
the number of characters to be written.  A -1 return value signifies
insufficient space.

The format of the $names_list$ string is a series of $name,value$ pairs
where each name and value is separated by a comma, the pairs are separated
by newlines, and the list is null terminated.

Calling either of these functions will initialize the respective
math library.
\begin{verbatim}
void init_LTM(void);
void init_TFM(void);
void init_GMP(void);
\end{verbatim}

Here is a Python program demonstrating how to call various LTC dynamic
language support functions.
\begin{verbatim}
from ctypes import *

# load the OSX shared/dynamic library
LIB = CDLL('libtomcrypt.dylib')

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# print info about this library

little = c_int()        # assume False is big
word32 = c_int()        # assume False is 64-bit

LIB.crypt_get_constant('ENDIAN_LITTLE', byref(little))
LIB.crypt_get_constant('ENDIAN_32BITWORD', byref(word32))

print('this lib was compiled for a %s endian %d-bit processor'
      % ('little' if little else 'big', 32 if word32 else 64))

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# print the size of the struct named "sha256_state"

struct_size = c_int()

# don't forget to add the '_struct' or '_union' suffix
LIB.crypt_get_size('sha256_state_struct', byref(struct_size))

print('allocate %d bytes for sha256_state' % struct_size.value)

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# print a list of all supported named constants

list_size = c_int()

# call with NULL to calc the min size needed for the list
LIB.crypt_list_all_constants(None, byref(list_size))

# allocate required space
names_list = c_buffer(list_size.value)

# call again providing a pointer to where to write the list
LIB.crypt_list_all_constants(names_list, byref(list_size))

print(names_list.value)

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# print a list of all supported named structs and unions

list_size = c_int()

# call with NULL to calc the min size needed for the list
LIB.crypt_list_all_sizes(None, byref(list_size))

# allocate required space
names_list = c_buffer(list_size.value)

# call again providing a pointer to where to write the list
LIB.crypt_list_all_sizes(names_list, byref(list_size))

print(names_list.value)
\end{verbatim}


\chapter{Programming Guidelines}

\mysection{Secure Pseudo Random Number Generators}
Probably the single most vulnerable point of any cryptosystem is the PRNG.  Without one, generating and protecting secrets
would be impossible.  The requirement that one be setup correctly is vitally important, and to address this point the library
does provide two RNG sources that will address the largest amount of end users as possible.  The \textit{sprng} PRNG provides an easy to
access source of entropy for any application on a UNIX (and the like) or Windows computer.

However, when the end user is not on one of these platforms, the application developer must address the issue of finding
entropy.  This manual is not designed to be a text on cryptography.  I would just like to highlight that when you design
a cryptosystem make sure the first problem you solve is getting a fresh source of entropy.

\mysection{Preventing Trivial Errors}
Two simple ways to prevent trivial errors is to prevent overflows, and to check the return values.  All of the functions
which output variable length strings will require you to pass the length of the destination.  If the size of your output
buffer is smaller than the output it will report an error.  Therefore, make sure the size you pass is correct!

Also, virtually all of the functions return an error code or {\bf CRYPT\_OK}.  You should detect all errors, as simple
typos can cause algorithms to fail to work as desired.

\mysection{Registering Your Algorithms}
To avoid linking and other run--time errors it is important to register the ciphers, hashes and PRNGs you intend to use
before you try to use them.  This includes any function which would use an algorithm indirectly through a descriptor table.

A neat bonus to the registry system is that you can add external algorithms that are not part of the library without
having to hack the library.  For example, suppose you have a hardware specific PRNG on your system.  You could easily
write the few functions required plus a descriptor.  After registering your PRNG, all of the library functions that
need a PRNG can instantly take advantage of it.  The same applies for ciphers, hashes, and bignum math routines.

\mysection{Key Sizes}

\subsection{Symmetric Ciphers}
For symmetric ciphers, use as large as of a key as possible.  For the most part \textit{bits are cheap} so using a 256--bit key
is not a hard thing to do.  As a good rule of thumb do not use a key smaller than 128 bits.

\subsection{Asymmetric Ciphers}
The following chart gives the work factor for solving a DH/RSA public key using the NFS.  The work factor for a key of order
$n$ is estimated to be
\begin{equation}
e^{1.923 \cdot ln(n)^{1 \over 3} \cdot ln(ln(n))^{2 \over 3}}
\end{equation}

Note that $n$ is not the bit-length but the magnitude.  For example, for a 1024-bit key $n = 2^{1024}$.  The work required
is:
\begin{figure}[H]
\begin{center}
\begin{tabular}{|c|c|}
    \hline RSA/DH Key Size (bits) & Work Factor ($log_2$) \\
    \hline 512 & 63.92 \\
    \hline 768 & 76.50 \\
    \hline 1024 & 86.76 \\
    \hline 1536 & 103.37 \\
    \hline 2048 & 116.88 \\
    \hline 2560 & 128.47 \\
    \hline 3072 & 138.73 \\
    \hline 4096 & 156.49 \\
    \hline
\end{tabular}
\end{center}
\caption{RSA/DH Key Strength}
\end{figure}

The work factor for ECC keys is much higher since the best attack is still fully exponential.  Given a key of magnitude
$n$ it requires $\sqrt n$ work.  The following table summarizes the work required:
\begin{figure}[H]
\begin{center}
\begin{tabular}{|c|c|}
    \hline ECC Key Size (bits) & Work Factor ($log_2$) \\
    \hline 112 & 56 \\
    \hline 128 & 64 \\
    \hline 160 & 80 \\
    \hline 192 & 96  \\
    \hline 224 & 112 \\
    \hline 256 & 128 \\
    \hline 384 & 192 \\
    \hline 521 & 260.5 \\
    \hline
\end{tabular}
\end{center}
\caption{ECC Key Strength}
\end{figure}

Using the above tables the following suggestions for key sizes seems appropriate:
\begin{center}
\begin{tabular}{|c|c|c|}
    \hline Security Goal & RSA/DH Key Size (bits) & ECC Key Size (bits) \\
    \hline Near term   & 1024 & 160 \\
    \hline Short term  & 1536 & 192 \\
    \hline Long Term   & 2560 & 384 \\
    \hline
\end{tabular}
\end{center}

\mysection{Thread Safety}
The library is not fully thread safe but several simple precautions can be taken to avoid any problems.  The registry functions
such as register\_cipher() are not thread safe no matter what you do.  It is best to call them from your programs initialization
code before threads are initiated.

The rest of the code uses state variables you must pass it such as hash\_state, hmac\_state, etc.  This means that if each
thread has its own state variables then they will not affect each other, and are fully thread safe.  This is fairly simple with symmetric ciphers
and hashes.

\index{LTC\_PTHREAD}
The only sticky issue is a shared PRNG which can be alleviated with the careful use of mutex devices.  Defining LTC\_PTHREAD for instance, enables
pthreads based mutex locking in various routines such as the Yarrow and Fortuna PRNGs, the fixed point ECC multiplier, and other routines.

\chapter{Configuring and Building the Library}
\mysection{Introduction}
The library is fairly flexible about how it can be built, used, and generally distributed.  Additions are being made with
each new release that will make the library even more flexible.  Each of the classes of functions can be disabled during
the build process to make a smaller library.  This is particularly useful for shared libraries.

As of v1.06 of the library, the build process has been moved to two steps for the typical LibTomCrypt application.  This is because
LibTomCrypt no longer provides a math API on its own and relies on third party libraries (such as LibTomMath, GnuMP, or TomsFastMath).

The build process now consists of installing a math library first, and then building and installing LibTomCrypt with a math library
configured.  Note that LibTomCrypt can be built with no internal math descriptors.  This means that one must be provided at either
build, or run time for the application.  LibTomCrypt comes with three math descriptors that provide a standard interface to math
libraries.

\mysection{Makefile variables}

All GNU driven makefiles (including the makefile for ICC) use a set of common variables to control the build and install process.  Most of the
settings can be overwritten from the command line which makes custom installation a breeze.

\subsection{MAKE, CC, AR and CROSS\_COMPILE}
\index{MAKE} \index{CC} \index{AR} \index{CROSS\_COMPILE}
The MAKE, CC and AR flags can all be overwritten.  They default to \textit{make}, \textit{\$CC} and \textit{\$AR} respectively.
Changing MAKE allows you to change what program will be invoked to handle sub--directories. For example, this

\begin{verbatim}
gmake install MAKE=gmake
\end{verbatim}

\begin{flushleft} will build and install the libraries with the \textit{gmake} tool.  Similarly, \end{flushleft}

\begin{verbatim}
make CC=arm-gcc AR=arm-ar
\end{verbatim}

\begin{flushleft} will build the library using \textit{arm--gcc} as the compiler and \textit{arm--ar} as the archiver. \end{flushleft}

\begin{verbatim}
make CROSS_COMPILE=arm-none-eabi-
\end{verbatim}

\begin{flushleft} will build the library using the \textit{arm--none--eabi--} prefix'ed toolchain. \end{flushleft}

\subsection{IGNORE\_SPEED and LTC\_DEBUG}
\index{IGNORE\_SPEED} \index{LTC\_DEBUG}
When \textbf{IGNORE\_SPEED} has been defined the default optimization flags for CFLAGS will be disabled which allows the developer to specify new
CFLAGS on the command line.  E.g. to add debugging

\begin{verbatim}
make IGNORE_SPEED=1 CFLAGS="-g3"
\end{verbatim}

This will turn off optimizations and add \textit{-g3} to the CFLAGS which enables debugging.

Alternatively one can define \textbf{LTC\_DEBUG} instead, which additionally defines \textit{LTC\_NO\_ASM} and enables debug output on test failures.

Defining \textit{LTC\_DEBUG=2} has the effect to enable verbose output in some of the tests.

\begin{verbatim}
make LTC_DEBUG=2
\end{verbatim}

\begin{flushleft} will build the library without compiler-optimisation or architecture specific code and will enable debugging
and verbose debug output. \end{flushleft}

\subsection{LIBNAME}
\index{LIBNAME}
\textbf{LIBNAME} is the name of the output library (archive) to create.  It defaults to \textit{libtomcrypt.a} for static builds and \textit{libtomcrypt.la} for
shared.
On installation of the shared library the appropriately versioned \textit{libtomcrypt.so}, \textit{libtomcrypt.so.0} etc. will be created by \textit{libtool}.

\subsection{Installation Directories}
\index{DESTDIR} \index{PREFIX} \index{LIBPATH} \index{INCPATH} \index{DATAPATH} \index{BINPATH}
\textbf{DESTDIR} is the location where the output will be stored.  It default to an empty string.
\textbf{PREFIX} is the prefix for the installation directories.  It defaults to \textit{/usr/local}.
\textbf{LIBPATH} is the location of the library directory which defaults to \textit{\$PREFIX/lib}.
\textbf{INCPATH} is the location of the header file directory which defaults to \textit{\$PREFIX/include}.
\textbf{DATAPATH} is the location of the data (documentation) directory which defaults to \textit{\$PREFIX/share/doc/libtomcrypt/pdf}.
\textbf{BINPATH} is the location of the binary file directory which defaults to \textit{\$PREFIX/bin}.

They allow to configure the installation locations of the libary.

\begin{verbatim}
make PREFIX=/home/tom/project DATAPATH=/home/tom/project/docs install
\end{verbatim}

This will build the library and install it to the directories under \textit{/home/tom/project/}.  e.g.

\begin{small}
\begin{verbatim}
/home/tom/project/:
total 1
drwxr-xr-x  2 tom users  80 Jul 30 16:02 docs
drwxr-xr-x  2 tom users 528 Jul 30 16:02 include
drwxr-xr-x  2 tom users  80 Jul 30 16:02 lib

/home/tom/project/docs:
total 452
-rwxr-xr-x  1 tom users 459009 Jul 30 16:02 crypt.pdf

/home/tom/project/include:
total 132
-rwxr-xr-x  1 tom users  2482 Jul 30 16:02 tomcrypt.h
-rwxr-xr-x  1 tom users   702 Jul 30 16:02 tomcrypt_argchk.h
-rwxr-xr-x  1 tom users  2945 Jul 30 16:02 tomcrypt_cfg.h
-rwxr-xr-x  1 tom users 22763 Jul 30 16:02 tomcrypt_cipher.h
-rwxr-xr-x  1 tom users  5174 Jul 30 16:02 tomcrypt_custom.h
-rwxr-xr-x  1 tom users 11314 Jul 30 16:02 tomcrypt_hash.h
-rwxr-xr-x  1 tom users 11571 Jul 30 16:02 tomcrypt_mac.h
-rwxr-xr-x  1 tom users 13614 Jul 30 16:02 tomcrypt_macros.h
-rwxr-xr-x  1 tom users 14714 Jul 30 16:02 tomcrypt_math.h
-rwxr-xr-x  1 tom users   632 Jul 30 16:02 tomcrypt_misc.h
-rwxr-xr-x  1 tom users 10934 Jul 30 16:02 tomcrypt_pk.h
-rwxr-xr-x  1 tom users  2634 Jul 30 16:02 tomcrypt_pkcs.h
-rwxr-xr-x  1 tom users  7067 Jul 30 16:02 tomcrypt_prng.h
-rwxr-xr-x  1 tom users  1467 Jul 30 16:02 tomcrypt_test.h

/home/tom/project/lib:
total 1073
-rwxr-xr-x  1 tom users 1096284 Jul 30 16:02 libtomcrypt.a
\end{verbatim}
\end{small}

For further information see: \url{https://www.gnu.org/prep/standards/html_node/DESTDIR.html}
and \url{https://www.freebsd.org/doc/en/books/porters-handbook/porting-prefix.html}.

\mysection{Extra libraries}
\index{EXTRALIBS}
\textbf{EXTRALIBS} specifies any extra libraries required to link the test programs and shared libraries.  They are specified in the notation
that GCC expects for global archives.

\begin{verbatim}
make install test timing CFLAGS="-DTFM_DESC -DUSE_TFM" EXTRALIBS=-ltfm
\end{verbatim}

This will install the library using the TomsFastMath library and link the \textit{libtfm.a} library out of the default library search path.  The two
defines are explained below.  You can specify multiple archives (say if you want to support two math libraries, or add on additional code) to
the \textbf{EXTRALIBS} variable by separating them by a space.

Note that \textbf{EXTRALIBS} is not required if you are only making and installing the static library but none of the test programs.

\mysection{Building a Static Library}

Building a static library is fairly trivial as it only requires one invocation of the GNU make command.

\begin{verbatim}
make install CFLAGS="-DTFM_DESC"
\end{verbatim}

That will build LibTomCrypt (including the TomsFastMath descriptor), and install it in the default locations indicated previously.  You can enable
the built--in LibTomMath descriptor as well (or in place of the TomsFastMath descriptor).  Similarly, you can build the library with no built--in
math descriptors.

\begin{verbatim}
make install
\end{verbatim}

In this case, no math descriptors are present in the library and they will have to be made available at build or run time before you can use any of the
public key functions.

Note that even if you include the built--in descriptors you must link against the source library as well.

\begin{verbatim}
gcc -DTFM_DESC myprogram.c -ltomcrypt -ltfm -o myprogram
\end{verbatim}

This will compile \textit{myprogram} and link it against the LibTomCrypt library as well as TomsFastMath (which must have been previously installed).  Note that
we define \textbf{TFM\_DESC} for compilation.  This is so that the TFM descriptor symbol will be defined for the client application to make use of without
giving warnings.

\mysection{Building a Shared Library}

LibTomCrypt can also be built as a shared library through the \textit{makefile.shared} make script.  It is similar to use as the static script except
that you \textbf{must} specify the \textbf{EXTRALIBS} variable at install time.

\begin{verbatim}
make -f makefile.shared install CFLAGS="-DTFM_DESC" EXTRALIBS=-ltfm
\end{verbatim}

This will build and install the library and link the shared object against the TomsFastMath library (which must be installed as a shared object as well).  The
shared build process requires libtool to be installed.

\mysection{Header Configuration}
The file \textit{tomcrypt\_cfg.h} is what lets you control various high level macros which control the behaviour of the library.  Build options are also
stored in \textit{tomcrypt\_custom.h} which allow the enabling and disabling of various algorithms.

\subsubsection{ARGTYPE}
This lets you control how the LTC\_ARGCHK macro will behave.  The macro is used to check pointers inside the functions against
NULL.  There are four settings for ARGTYPE.  When set to 0, it will have the default behaviour of printing a message to
stderr and raising a SIGABRT signal.  This is provided so all platforms that use LibTomCrypt can have an error that functions
similarly.  When set to 1, it will simply pass on to the assert() macro.  When set to 2, the macro will display the error to
stderr then return execution to the caller.  This could lead to a segmentation fault (e.g. when a pointer is \textbf{NULL}) but is useful
if you handle signals on your own.  When set to 3, it will resolve to a empty macro and no error checking will be performed.  Finally, when set
to 4, it will return CRYPT\_INVALID\_ARG to the caller.

\subsubsection{Endianness}
There are five macros related to endianness issues.  For little endian platforms define, \textbf{ENDIAN\_LITTLE}.  For big endian
platforms define \textbf{ENDIAN\_BIG}.  Similarly when the default word size of an \textit{unsigned long} is 32-bits define \textbf{ENDIAN\_32BITWORD}
or define \textbf{ENDIAN\_64BITWORD} when its 64-bits.  If you do not define any of them the library will automatically use \textbf{ENDIAN\_NEUTRAL}
which will work on all platforms.

Currently LibTomCrypt will detect x86-32, x86-64, MIPS R5900, SPARC and SPARC64 running GCC as well as x86-32 running MSVC.

\mysection{Customisation}
There are also options you can specify from the \textit{tomcrypt\_custom.h} header file.

\subsection{X memory routines}
\index{XMALLOC}\index{XREALLOC}\index{XCALLOC}\index{XFREE}\index{XMEMSET}\index{XMEMCPY}\index{XMEMMOVE}\index{XMEMCMP}\index{XSTRCMP}
At the top of tomcrypt\_custom.h are a series of macros denoted as XMALLOC, XCALLOC, XREALLOC, XFREE, and so on.  They resolve to
the name of the respective functions from the standard C library by default.  This lets you substitute in your own memory routines.
If you substitute in your own functions they must behave like the standard C library functions in terms of what they expect as input and
output.

These macros are handy for working with platforms which do not have a standard C library.
For instance, the OLPC\footnote{See \url{http://dev.laptop.org/git?p=bios-crypto;a=summary}}
bios code uses these macros to redirect to very compact heap and string operations.

\subsection{X clock routines}
The rng\_get\_bytes() function can call a function that requires the clock() function.  These macros let you override
the default clock() used with a replacement.  By default the standard C library clock() function is used.

\subsection{LTC\_NO\_FILE}
During the build if LTC\_NO\_FILE is defined then any function in the library that uses file I/O will not call the file I/O
functions and instead simply return CRYPT\_NOP.  This should help resolve any linker errors stemming from a lack of
file I/O on embedded platforms.

\subsection{LTC\_CLEAN\_STACK}
When this functions is defined the functions that store key material on the stack will clean up afterwards.
Assumes that you have no memory paging with the stack.

\subsection{LTC\_TEST}
When this has been defined the various self--test functions (for ciphers, hashes, prngs, etc) are included in the build.  This is the default configuration.
If LTC\_NO\_TEST has been defined, the testing routines will be compacted and only return CRYPT\_NOP.

\subsection{LTC\_NO\_FAST}
When this has been defined the library will not use faster word oriented operations.  By default, they are only enabled for platforms
which can be auto-detected.  This macro ensures that they are never enabled.

\subsection{LTC\_FAST}
This mode (auto-detected with x86\_32, x86\_64 platforms with GCC or CLANG) configures various routines such as ctr\_encrypt() or
cbc\_encrypt() that it can safely XOR multiple octets in one step by using a larger data type.  This has the benefit of
cutting down the overhead of the respective functions.

This mode does have one downside.  It can cause unaligned reads from memory if you are not careful with the functions.  This is why
it has been enabled by default only for the x86 class of processors where unaligned accesses are allowed.  Technically LTC\_FAST
is not \textit{portable} since unaligned accesses are not covered by the ISO C specifications.

In practice however, you can use it on pretty much any platform (even MIPS) with care.

By design the \textit{fast} mode functions won't get unaligned on their own.  For instance, if you call ctr\_encrypt() right after calling
ctr\_start() and all the inputs you gave are aligned than ctr\_encrypt() will perform aligned memory operations only.  However, if you
call ctr\_encrypt() with an odd amount of plaintext then call it again the CTR pad (the IV) will be partially used.  This will
cause the ctr routine to first use up the remaining pad bytes.  Then if there are enough plaintext bytes left it will use
whole word XOR operations.  These operations will be unaligned.

The simplest precaution is to make sure you process all data in power of two blocks and handle \textit{remainder} at the end.  e.g. If you are
CTR'ing a long stream process it in blocks of (say) four kilobytes and handle any remaining incomplete blocks at the end of the stream.

\index{LTC\_FAST\_TYPE}
If you do plan on using the \textit{LTC\_FAST} mode, a \textit{LTC\_FAST\_TYPE} type which resolves to an optimal sized
data type you can perform integer operations with is required.  For the auto-detected platforms this type will be defined automatically.  Ideally it should be four or eight bytes since it must properly divide the size
of your block cipher (e.g. 16 bytes for AES).  This means sadly if you're on a platform with 57--bit words (or something) you can't
use this mode.  So sad.

\subsection{LTC\_NO\_ASM}
When this has been defined the library will not use any inline assembler.  Only a few platforms support assembler inlines but various versions of ICC and GCC
cannot handle all of the assembler functions.

\subsection{Symmetric Ciphers, One-way Hashes, PRNGS and Public Key Functions}
There are a plethora of macros for the ciphers, hashes, PRNGs and public key functions which are fairly
self-explanatory.  When they are defined the functionality is included otherwise it is not.  There are some
dependency issues which are noted in the file.  For instance, Yarrow requires CTR chaining mode, a block
cipher and a hash function.

Also see technical note number five for more details.

\subsection{LTC\_EASY}
When defined the library is configured to build fewer algorithms and modes.  Mostly it sticks to NIST and ANSI approved algorithms.  See
the header file \textit{tomcrypt\_custom.h} for more details.  It is meant to provide literally an easy method of trimming the library
build to the most minimum of useful functionality.

\subsection{TWOFISH\_SMALL and TWOFISH\_TABLES}
Twofish is a 128-bit symmetric block cipher that is provided within the library.  The cipher itself is flexible enough
to allow some trade-offs in the implementation.  When TWOFISH\_SMALL is defined the scheduled symmetric key for Twofish
requires only 200 bytes of memory.  This is achieved by not pre-computing the substitution boxes.  Having this
defined will also greatly slow down the cipher.  When this macro is not defined Twofish will pre-compute the
tables at a cost of 4KB of memory.  The cipher will be much faster as a result.

When TWOFISH\_TABLES is defined the cipher will use pre-computed (and fixed in code) tables required to work.  This is
useful when TWOFISH\_SMALL is defined as the table values are computed on the fly.  When this is defined the code size
will increase by approximately 500 bytes.  If this is defined but TWOFISH\_SMALL is not the cipher will still work but
it will not speed up the encryption or decryption functions.

\subsection{GCM\_TABLES}
When defined GCM will use a 64KB table (per GCM state) which will greatly speed up the per--packet latency.
It also increases the initialization time and is not suitable when you are going to use a key a few times only.

\subsection{GCM\_TABLES\_SSE2}
\index{SSE2}
When defined GCM will use the SSE2 instructions to perform the $GF(2^x)$ multiply using 16 128--bit XOR operations.  It shaves a few cycles per byte
of GCM output on both the AMD64 and Intel Pentium 4 platforms.  Requires GCC and an SSE2 equipped platform.

\subsection{LTC\_SMALL\_CODE}
When this is defined some of the code such as the Rijndael and SAFER+ ciphers are replaced with smaller code variants.
These variants are slower but can save quite a bit of code space.

\subsection{LTC\_PTHREAD}
When this is activated all of the descriptor table functions will use pthread locking to ensure thread safe updates to the tables.  Note that
it doesn't prevent a thread that is passively using a table from being messed up by another thread that updates the table.

Generally the rule of thumb is to setup the tables once at startup and then leave them be.  This added build flag simply makes updating
the tables safer.

\subsection{LTC\_ECC\_TIMING\_RESISTANT}
When this has been defined the ECC point multiplier (built--in to the library) will use a timing resistant point multiplication
algorithm which prevents leaking key bits of the private key (scalar).  It is a slower algorithm but useful for situations
where timing side channels pose a significant threat.

This is enabled by default and can be disabled by defining \textbf{LTC\_NO\_ECC\_TIMING\_RESISTANT}.

\subsection{LTC\_RSA\_BLINDING}
When this has been defined the RSA modular exponentiation will use a blinding algorithm to improve timing resistance.

This is enabled by default and can be disabled by defining \textbf{LTC\_NO\_RSA\_BLINDING}.

\subsection{LTC\_RSA\_CRT\_HARDENING}
When this has been defined the RSA modular exponentiation will do some sanity checks regarding the CRT parameters and the operations' results.

This is enabled by default and can be disabled by defining \textbf{LTC\_NO\_RSA\_CRT\_HARDENING}.

\subsection{Math Descriptors}
The library comes with three math descriptors that allow you to interface the public key cryptography API to freely available math
libraries.  When \textbf{GMP\_DESC}, \textbf{LTM\_DESC}, or \textbf{TFM\_DESC} are defined
descriptors for the respective library are built and included in the library as \textit{gmp\_desc}, \textit{ltm\_desc}, or \textit{tfm\_desc} respectively.

In the test demos that use the libraries the additional flags \textbf{USE\_GMP}, \textbf{USE\_LTM}, and \textbf{USE\_TFM} can be defined
to tell the program which library to use.  Only one of the USE flags can be defined at once.

\index{GMP\_DESC} \index{USE\_GMP} \index{LTM\_DESC} \index{TFM\_DESC} \index{USE\_LTM} \index{USE\_TFM}
\begin{small}
\begin{verbatim}
make -f makefile.shared install timing CFLAGS="-DGMP_DESC -DLTM_DESC -DTFM_DESC -DUSE_TFM" \
EXTRALIBS="-lgmp -ltommath -ltfm"
\end{verbatim}
\end{small}

That will build and install the library with all descriptors (and link against all), but only use TomsFastMath in the timing demo.

\chapter{Optimizations}
\mysection{Introduction}
The entire API was designed with plug and play in mind at the low level.  That is you can swap out any cipher, hash, PRNG or bignum library and the dependent API will not
require updating.  This has the nice benefit that one can add ciphers (etc.) not have to re--write portions of the API.  For the most part, LibTomCrypt has also been written
to be highly portable and easy to build out of the box on pretty much any platform.  As such there are no assembler inlines throughout the code, I make no assumptions
about the platform, etc...

That works well for most cases but there are times where performance is of the essence.  This API allows optimized routines to be dropped in--place of the existing
portable routines.  For instance, hand optimized assembler versions of AES could be provided.  Any existing function that uses the cipher could automatically use
the optimized code without re--writing.  This also paves the way for hardware drivers that can access hardware accelerated cryptographic devices.

At the heart of this flexibility is the \textit{descriptor} system.  A descriptor is essentially just a C \textit{struct} which describes the algorithm and provides pointers
to functions that do the required work.  For a given class of operation (e.g. cipher, hash, prng, bignum) the functions of a descriptor have identical prototypes which makes
development simple.  In most dependent routines all an end developer has to do is register\_XXX() the descriptor and they are set.

\mysection{Ciphers}
The ciphers in LibTomCrypt are accessed through the ltc\_cipher\_descriptor structure.

\label{sec:cipherdesc}
\begin{small}
\begin{verbatim}
struct ltc_cipher_descriptor {
   /** name of cipher */
   char *name;

   /** internal ID */
   unsigned char ID;

   /** min keysize (octets) */
   int  min_key_length,

   /** max keysize (octets) */
        max_key_length,

   /** block size (octets) */
        block_length,

   /** default number of rounds */
        default_rounds;

   /** Setup the cipher
      @param key         The input symmetric key
      @param keylen      The length of the input key (octets)
      @param num_rounds  The requested number of rounds (0==default)
      @param skey        [out] The destination of the scheduled key
      @return CRYPT_OK if successful
   */
   int  (*setup)(const unsigned char *key,
                                 int  keylen,
                                 int  num_rounds,
                       symmetric_key *skey);

   /** Encrypt a block
      @param pt      The plaintext
      @param ct      [out] The ciphertext
      @param skey    The scheduled key
      @return CRYPT_OK if successful
   */
   int (*ecb_encrypt)(const unsigned char *pt,
                            unsigned char *ct,
                            symmetric_key *skey);

   /** Decrypt a block
      @param ct      The ciphertext
      @param pt      [out] The plaintext
      @param skey    The scheduled key
      @return CRYPT_OK if successful
   */
   int (*ecb_decrypt)(const unsigned char *ct,
                            unsigned char *pt,
                            symmetric_key *skey);

   /** Test the block cipher
       @return CRYPT_OK if successful,
               CRYPT_NOP if self-testing has been disabled
   */
   int (*test)(void);

   /** Terminate the context
      @param skey    The scheduled key
   */
   void (*done)(symmetric_key *skey);

   /** Determine a key size
       @param keysize    [in/out] The size of the key desired
                                  The suggested size
       @return CRYPT_OK if successful
   */
   int  (*keysize)(int *keysize);

/** Accelerators **/
   /** Accelerated ECB encryption
       @param pt      Plaintext
       @param ct      Ciphertext
       @param blocks  The number of complete blocks to process
       @param skey    The scheduled key context
       @return CRYPT_OK if successful
   */
   int (*accel_ecb_encrypt)(const unsigned char *pt,
                                  unsigned char *ct,
                                  unsigned long  blocks,
                                  symmetric_key *skey);

   /** Accelerated ECB decryption
       @param pt      Plaintext
       @param ct      Ciphertext
       @param blocks  The number of complete blocks to process
       @param skey    The scheduled key context
       @return CRYPT_OK if successful
   */
   int (*accel_ecb_decrypt)(const unsigned char *ct,
                                  unsigned char *pt,
                                  unsigned long  blocks,
                                  symmetric_key *skey);

   /** Accelerated CBC encryption
       @param pt      Plaintext
       @param ct      Ciphertext
       @param blocks  The number of complete blocks to process
       @param IV      The initial value (input/output)
       @param skey    The scheduled key context
       @return CRYPT_OK if successful
   */
   int (*accel_cbc_encrypt)(const unsigned char *pt,
                                  unsigned char *ct,
                                  unsigned long  blocks,
                                  unsigned char *IV,
                                  symmetric_key *skey);

   /** Accelerated CBC decryption
       @param pt      Plaintext
       @param ct      Ciphertext
       @param blocks  The number of complete blocks to process
       @param IV      The initial value (input/output)
       @param skey    The scheduled key context
       @return CRYPT_OK if successful
   */
   int (*accel_cbc_decrypt)(const unsigned char *ct,
                                  unsigned char *pt,
                                  unsigned long  blocks,
                                  unsigned char *IV,
                                  symmetric_key *skey);

   /** Accelerated CTR encryption
       @param pt      Plaintext
       @param ct      Ciphertext
       @param blocks  The number of complete blocks to process
       @param IV      The initial value (input/output)
       @param mode    little or big endian counter (mode=0 or mode=1)
       @param skey    The scheduled key context
       @return CRYPT_OK if successful
   */
   int (*accel_ctr_encrypt)(const unsigned char *pt,
                                  unsigned char *ct,
                                  unsigned long  blocks,
                                  unsigned char *IV,
                                            int  mode,
                                  symmetric_key *skey);

   /** Accelerated LRW
       @param pt      Plaintext
       @param ct      Ciphertext
       @param blocks  The number of complete blocks to process
       @param IV      The initial value (input/output)
       @param tweak   The LRW tweak
       @param skey    The scheduled key context
       @return CRYPT_OK if successful
   */
   int (*accel_lrw_encrypt)(const unsigned char *pt,
                                  unsigned char *ct,
                                  unsigned long  blocks,
                                  unsigned char *IV,
                            const unsigned char *tweak,
                                  symmetric_key *skey);

   /** Accelerated LRW
       @param ct      Ciphertext
       @param pt      Plaintext
       @param blocks  The number of complete blocks to process
       @param IV      The initial value (input/output)
       @param tweak   The LRW tweak
       @param skey    The scheduled key context
       @return CRYPT_OK if successful
   */
   int (*accel_lrw_decrypt)(const unsigned char *ct,
                                  unsigned char *pt,
                                  unsigned long  blocks,
                                  unsigned char *IV,
                            const unsigned char *tweak,
                                  symmetric_key *skey);

   /** Accelerated CCM packet (one-shot)
       @param key        The secret key to use
       @param keylen     The length of the secret key (octets)
       @param uskey      A previously scheduled key [can be NULL]
       @param nonce      The session nonce [use once]
       @param noncelen   The length of the nonce
       @param header     The header for the session
       @param headerlen  The length of the header (octets)
       @param pt         [out] The plaintext
       @param ptlen      The length of the plaintext (octets)
       @param ct         [out] The ciphertext
       @param tag        [out] The destination tag
       @param taglen     [in/out] The max size and resulting size
                                  of the authentication tag
       @param direction  Encrypt or Decrypt direction (0 or 1)
       @return CRYPT_OK if successful
   */
   int (*accel_ccm_memory)(
       const unsigned char *key,    unsigned long keylen,
       symmetric_key       *uskey,
       const unsigned char *nonce,  unsigned long noncelen,
       const unsigned char *header, unsigned long headerlen,
             unsigned char *pt,     unsigned long ptlen,
             unsigned char *ct,
             unsigned char *tag,    unsigned long *taglen,
                       int  direction);

   /** Accelerated GCM packet (one shot)
       @param key        The secret key
       @param keylen     The length of the secret key
       @param IV         The initialization vector
       @param IVlen      The length of the initialization vector
       @param adata      The additional authentication data (header)
       @param adatalen   The length of the adata
       @param pt         The plaintext
       @param ptlen      The length of the plaintext/ciphertext
       @param ct         The ciphertext
       @param tag        [out] The MAC tag
       @param taglen     [in/out] The MAC tag length
       @param direction  Encrypt or Decrypt mode (GCM_ENCRYPT or GCM_DECRYPT)
       @return CRYPT_OK on success
   */
   int (*accel_gcm_memory)(
       const unsigned char *key,    unsigned long keylen,
       const unsigned char *IV,     unsigned long IVlen,
       const unsigned char *adata,  unsigned long adatalen,
             unsigned char *pt,     unsigned long ptlen,
             unsigned char *ct,
             unsigned char *tag,    unsigned long *taglen,
                       int direction);

   /** Accelerated one shot OMAC
       @param key            The secret key
       @param keylen         The key length (octets)
       @param in             The message
       @param inlen          Length of message (octets)
       @param out            [out] Destination for tag
       @param outlen         [in/out] Initial and final size of out
       @return CRYPT_OK on success
   */
   int (*omac_memory)(
       const unsigned char *key, unsigned long keylen,
       const unsigned char *in,  unsigned long inlen,
             unsigned char *out, unsigned long *outlen);

   /** Accelerated one shot XCBC
       @param key            The secret key
       @param keylen         The key length (octets)
       @param in             The message
       @param inlen          Length of message (octets)
       @param out            [out] Destination for tag
       @param outlen         [in/out] Initial and final size of out
       @return CRYPT_OK on success
   */
   int (*xcbc_memory)(
       const unsigned char *key, unsigned long keylen,
       const unsigned char *in,  unsigned long inlen,
             unsigned char *out, unsigned long *outlen);

   /** Accelerated one shot F9
       @param key            The secret key
       @param keylen         The key length (octets)
       @param in             The message
       @param inlen          Length of message (octets)
       @param out            [out] Destination for tag
       @param outlen         [in/out] Initial and final size of out
       @return CRYPT_OK on success
       @remark Requires manual padding
   */
   int (*f9_memory)(
       const unsigned char *key, unsigned long keylen,
       const unsigned char *in,  unsigned long inlen,
             unsigned char *out, unsigned long *outlen);
};
\end{verbatim}
\end{small}

\subsection{Name}
\index{find\_cipher()}
The \textit{name} parameter specifies the name of the cipher.  This is what a developer would pass to find\_cipher() to find the cipher in the descriptor
tables.

\subsection{Internal ID}
This is a single byte Internal ID you can use to distinguish ciphers from each other.

\subsection{Key Lengths}
The minimum key length is \textit{min\_key\_length} and is measured in octets.  Similarly the maximum key length is \textit{max\_key\_length}.  They can be equal
and both must valid key sizes for the cipher.  Values in between are not assumed to be valid though they may be.

\subsection{Block Length}
The size of the ciphers plaintext or ciphertext is \textit{block\_length} and is measured in octets.

\subsection{Rounds}
Some ciphers allow different number of rounds to be used.  Usually you just use the default.  The default round count is \textit{default\_rounds}.

\subsection{Setup}
To initialize a cipher (for ECB mode) the function setup() was provided.  It accepts an array of key octets \textit{key} of length \textit{keylen} octets.  The user
can specify the number of rounds they want through \textit{num\_rounds} where $num\_rounds = 0$ means use the default.  The destination of a scheduled key is stored
in \textit{skey}.

Inside the \textit{symmetric\_key} union there is a \textit{void *data} which you can use to allocate data if you need a data structure that does not fit with the existing
ones provided.  Just make sure in your \textit{done()} function that you free the allocated memory.

\subsection{Single block ECB}
To process a single block in ECB mode the ecb\_encrypt() and ecb\_decrypt() functions were provided.  The plaintext and ciphertext buffers are allowed to overlap so you
must make sure you do not overwrite the output before you are finished with the input.

\subsection{Testing}
The test() function is used to self--test the \textit{device}.  It takes no arguments and returns \textbf{CRYPT\_OK} if all is working properly.  You may return
\textbf{CRYPT\_NOP} to indicate that no testing was performed.

\subsection{Key Sizing}
Occasionally, a function will want to find a suitable key size to use since the input is oddly sized.  The keysize() function is for this case.  It accepts a
pointer to an integer which represents the desired size.  The function then has to match it to the exact or a lower key size that is valid for the cipher.  For
example, if the input is $25$ and $24$ is valid then it stores $24$ back in the pointed to integer.  It must not round up and must return an error if the keysize
 cannot be mapped to a valid key size for the cipher.

\subsection{Acceleration}
The next set of functions cover the accelerated functionality of the cipher descriptor.  Any combination of these functions may be set to \textbf{NULL} to indicate
it is not supported.  In those cases the software defaults are used (using the single ECB block routines).

\subsubsection{Accelerated ECB}
These two functions are meant for cases where a user wants to encrypt (in ECB mode no less) an array of blocks.  These functions are accessed
through the accel\_ecb\_encrypt and accel\_ecb\_decrypt pointers.  The \textit{blocks} count is the number of complete blocks to process.

\subsubsection{Accelerated CBC}
These two functions are meant for accelerated CBC encryption.  These functions are accessed through the accel\_cbc\_encrypt and accel\_cbc\_decrypt pointers.
The \textit{blocks} value is the number of complete blocks to process.  The \textit{IV} is the CBC initialization vector.  It is an input upon calling this function and must be
updated by the function before returning.

\subsubsection{Accelerated CTR}
This function is meant for accelerated CTR encryption.  It is accessible through the accel\_ctr\_encrypt pointer.
The \textit{blocks} value is the number of complete blocks to process.  The \textit{IV} is the CTR counter vector.  It is an input upon calling this function and must be
updated by the function before returning.  The \textit{mode} value indicates whether the counter is big (mode = CTR\_COUNTER\_BIG\_ENDIAN) or
little (mode = CTR\_COUNTER\_LITTLE\_ENDIAN) endian.

This function (and the way it's called) differs from the other two since ctr\_encrypt() allows any size input plaintext.  The accelerator will only be
called if the following conditions are met.

\begin{enumerate}
   \item The accelerator is present
   \item The CTR pad is empty
   \item The remaining length of the input to process is greater than or equal to the block size.
\end{enumerate}

The \textit{CTR pad} is empty when a multiple (including zero) blocks of text have been processed.  That is, if you pass in seven bytes to AES--CTR mode you would have to
pass in a minimum of nine extra bytes before the accelerator could be called.  The CTR accelerator must increment the counter (and store it back into the
buffer provided) before encrypting it to create the pad.

The accelerator will only be used to encrypt whole blocks.  Partial blocks are always handled in software.

\subsubsection{Accelerated LRW}
These functions are meant for accelerated LRW.  They process blocks of input in lengths of multiples of 16 octets.  They must accept the \textit{IV} and \textit{tweak}
state variables and updated them prior to returning.  Note that you may want to disable \textbf{LRW\_TABLES} in \textit{tomcrypt\_custom.h} if you intend
to use accelerators for LRW.

While both encrypt and decrypt accelerators are not required it is suggested as it makes lrw\_setiv() more efficient.

Note that calling lrw\_done() will only invoke the cipher\_descriptor[].done() function on the \textit{symmetric\_key} parameter of the LRW state.  That means
if your device requires any (LRW specific) resources you should free them in your ciphers() done function.  The simplest way to think of it is to write
the plugin solely to do LRW with the cipher.  That way cipher\_descriptor[].setup() means to init LRW resources and cipher\_descriptor[].done() means to
free them.

\subsubsection{Accelerated CCM}
This function is meant for accelerated CCM encryption or decryption.  It processes the entire packet in one call.  You can optimize the work flow somewhat
by allowing the caller to call the setup() function first to schedule the key if your accelerator cannot do the key schedule on the fly (for instance).  This
function MUST support both key passing methods.

\begin{center}
\begin{small}
\begin{tabular}{|r|r|l|}
\hline \textbf{key} & \textbf{uskey} & \textbf{Source of key} \\
\hline NULL         & NULL           & Error, not supported \\
\hline non-NULL     & NULL           & Use key, do a key schedule \\
\hline NULL         & non-NULL       & Use uskey, key schedule not required \\
\hline non-NULL     & non-NULL       & Use uskey, key schedule not required \\
\hline
\end{tabular}
\end{small}
\end{center}

\index{ccm\_memory()} This function is called when the user calls ccm\_memory().

\subsubsection{Accelerated GCM}
\index{gcm\_memory()}
This function is meant for accelerated GCM encryption or decryption.  It processes the entire packet in one call.  Note that the setup() function will not
be called prior to this.  This function must handle scheduling the key provided on its own.  It is called when the user calls gcm\_memory().

\subsubsection{Accelerated OMAC}
\index{omac\_memory()}
This function is meant to perform an optimized OMAC1 (CMAC) message authentication code computation when the user calls omac\_memory().

\subsubsection{Accelerated XCBC-MAC}
\index{xcbc\_memory()}
This function is meant to perform an optimized XCBC-MAC message authentication code computation when the user calls xcbc\_memory().

\subsubsection{Accelerated F9}
\index{f9\_memory()}
This function is meant to perform an optimized F9 message authentication code computation when the user calls f9\_memory().  Like f9\_memory(), it requires
the caller to perform any 3GPP related padding before calling in order to ensure proper compliance with F9.


\mysection{One--Way Hashes}
The hash functions are accessed through the ltc\_hash\_descriptor structure.

\begin{small}
\begin{verbatim}
struct ltc_hash_descriptor {
    /** name of hash */
    char *name;

    /** internal ID */
    unsigned char ID;

    /** Size of digest in octets */
    unsigned long hashsize;

    /** Input block size in octets */
    unsigned long blocksize;

    /** ASN.1 OID */
    unsigned long OID[16];

    /** Length of DER encoding */
    unsigned long OIDlen;

    /** Init a hash state
      @param hash   The hash to initialize
      @return CRYPT_OK if successful
    */
    int (*init)(hash_state *hash);

    /** Process a block of data
      @param hash   The hash state
      @param in     The data to hash
      @param inlen  The length of the data (octets)
      @return CRYPT_OK if successful
    */
    int (*process)(         hash_state *hash,
                   const unsigned char *in,
                         unsigned long  inlen);

    /** Produce the digest and store it
      @param hash   The hash state
      @param out    [out] The destination of the digest
      @return CRYPT_OK if successful
    */
    int (*done)(   hash_state *hash,
                unsigned char *out);

    /** Self-test
      @return CRYPT_OK if successful,
              CRYPT_NOP if self-tests have been disabled
    */
    int (*test)(void);

    /* accelerated hmac callback: if you need to-do
       multiple packets just use the generic hmac_memory
       and provide a hash callback
    */
    int  (*hmac_block)(const unsigned char *key,
                             unsigned long  keylen,
                       const unsigned char *in,
                             unsigned long  inlen,
                             unsigned char *out,
                             unsigned long *outlen);
};
\end{verbatim}
\end{small}

\subsection{Name}
This is the name the hash is known by and what find\_hash() will look for.

\subsection{Internal ID}
This is the internal ID byte used to distinguish the hash from other hashes.

\subsection{Digest Size}
The \textit{hashsize} variable indicates the length of the output in octets.

\subsection{Block Size}
The \textit{blocksize} variable indicates the length of input (in octets) that the hash processes in a given
invocation.

\subsection{OID Identifier}
This is the universal ASN.1 Object Identifier for the hash.

\subsection{Initialization}
The init function initializes the hash and prepares it to process message bytes.

\subsection{Process}
This processes message bytes.  The algorithm must accept any length of input that the hash would allow.  The input is not
guaranteed to be a multiple of the block size in length.

\subsection{Done}
The done function terminates the hash and returns the message digest.

\subsection{Acceleration}
A compatible accelerator must allow processing data in any granularity which may require internal padding on the driver side.

\subsection{HMAC Acceleration}
The hmac\_block() callback is meant for single--shot optimized HMAC implementations.  It is called directly by hmac\_memory() if present.  If you need
to be able to process multiple blocks per MAC then you will have to simply provide a process() callback and use hmac\_memory() as provided in LibTomCrypt.

\mysection{Pseudo--Random Number Generators}
The pseudo--random number generators are accessible through the ltc\_prng\_descriptor structure.

\begin{small}
\begin{verbatim}
struct ltc_prng_descriptor {
    /** Name of the PRNG */
    char *name;

    /** size in bytes of exported state */
    int  export_size;

    /** Start a PRNG state
        @param prng   [out] The state to initialize
        @return CRYPT_OK if successful
    */
    int (*start)(prng_state *prng);

    /** Add entropy to the PRNG
        @param in         The entropy
        @param inlen      Length of the entropy (octets)
        @param prng       The PRNG state
        @return CRYPT_OK if successful
    */
    int (*add_entropy)(const unsigned char *in,
                             unsigned long  inlen,
                                prng_state *prng);

    /** Ready a PRNG state to read from
        @param prng       The PRNG state to ready
        @return CRYPT_OK if successful
    */
    int (*ready)(prng_state *prng);

    /** Read from the PRNG
        @param out     [out] Where to store the data
        @param outlen  Length of data desired (octets)
        @param prng    The PRNG state to read from
        @return Number of octets read
    */
    unsigned long (*read)(unsigned char *out,
                          unsigned long  outlen,
                             prng_state *prng);

    /** Terminate a PRNG state
        @param prng   The PRNG state to terminate
        @return CRYPT_OK if successful
    */
    int (*done)(prng_state *prng);

    /** Export a PRNG state
        @param out     [out] The destination for the state
        @param outlen  [in/out] The max size and resulting size
        @param prng    The PRNG to export
        @return CRYPT_OK if successful
    */
    int (*pexport)(unsigned char *out,
                   unsigned long *outlen,
                      prng_state *prng);

    /** Import a PRNG state
        @param in      The data to import
        @param inlen   The length of the data to import (octets)
        @param prng    The PRNG to initialize/import
        @return CRYPT_OK if successful
    */
    int (*pimport)(const unsigned char *in,
                         unsigned long  inlen,
                            prng_state *prng);

    /** Self-test the PRNG
        @return CRYPT_OK if successful,
                CRYPT_NOP if self-testing has been disabled
    */
    int (*test)(void);
};
\end{verbatim}
\end{small}

\subsection{Name}
The name by which find\_prng() will find the PRNG.

\subsection{Export Size}
When an PRNG state is to be exported for future use you specify the space required in this variable.

\subsection{Start}
Initialize the PRNG and make it ready to accept entropy.

\subsection{Entropy Addition}
Add entropy to the PRNG state.  The exact behaviour of this function depends on the particulars of the PRNG.

\subsection{Ready}
This function makes the PRNG ready to read from by processing the entropy added.  The behaviour of this function depends
on the specific PRNG used.

\subsection{Read}
Read from the PRNG and return the number of bytes read.  This function does not have to fill the buffer but it is best
if it does as many protocols do not retry reads and will fail on the first try.

\subsection{Done}
Terminate a PRNG state.  The behaviour of this function depends on the particular PRNG used.

\subsection{Exporting and Importing}
An exported PRNG state is data that the PRNG can later import to resume activity.  They're not meant to resume \textit{the same session}
but should at least maintain the same level of state entropy.

\mysection{BigNum Math Descriptors}
The library also makes use of the math descriptors to access math functions.  While bignum math libraries usually differ in implementation
it hasn't proven hard to write \textit{glue} to use math libraries so far.  The basic descriptor looks like.

\begin{small}
\begin{verbatim}
/** math descriptor */
typedef struct {
   /** Name of the math provider */
   char *name;

   /** Bits per digit, amount of bits must fit in an unsigned long */
   int  bits_per_digit;

/* ---- init/deinit functions ---- */

   /** initialize a bignum
     @param   a     The number to initialize
     @return  CRYPT_OK on success
   */
   int (*init)(void **a);

   /** init copy
     @param  dst    The number to initialize and write to
     @param  src    The number to copy from
     @return CRYPT_OK on success
   */
   int (*init_copy)(void **dst, void *src);

   /** deinit
      @param   a    The number to free
      @return CRYPT_OK on success
   */
   void (*deinit)(void *a);

/* ---- data movement ---- */

   /** negate
      @param   src   The number to negate
      @param   dst   The destination
      @return CRYPT_OK on success
   */
   int (*neg)(void *src, void *dst);

   /** copy
      @param   src   The number to copy from
      @param   dst   The number to write to
      @return CRYPT_OK on success
   */
   int (*copy)(void *src, void *dst);

/* ---- trivial low level functions ---- */

   /** set small constant
      @param a    Number to write to
      @param n    Source upto bits_per_digit (actually meant for very small constants)
      @return CRYPT_OK on success
   */
   int (*set_int)(void *a, unsigned long n);

   /** get small constant
      @param a  Small number to read,
                only fetches up to bits_per_digit from the number
      @return   The lower bits_per_digit of the integer (unsigned)
   */
   unsigned long (*get_int)(void *a);

   /** get digit n
     @param a  The number to read from
     @param n  The number of the digit to fetch
     @return  The bits_per_digit  sized n'th digit of a
   */
   ltc_mp_digit (*get_digit)(void *a, int n);

   /** Get the number of digits that represent the number
     @param a   The number to count
     @return The number of digits used to represent the number
   */
   int (*get_digit_count)(void *a);

   /** compare two integers
     @param a   The left side integer
     @param b   The right side integer
     @return LTC_MP_LT if a < b,
             LTC_MP_GT if a > b and
             LTC_MP_EQ otherwise.  (signed comparison)
   */
   int (*compare)(void *a, void *b);

   /** compare against int
     @param a   The left side integer
     @param b   The right side integer (upto bits_per_digit)
     @return LTC_MP_LT if a < b,
             LTC_MP_GT if a > b and
             LTC_MP_EQ otherwise.  (signed comparison)
   */
   int (*compare_d)(void *a, unsigned long n);

   /** Count the number of bits used to represent the integer
     @param a   The integer to count
     @return The number of bits required to represent the integer
   */
   int (*count_bits)(void * a);

   /** Count the number of LSB bits which are zero
     @param a   The integer to count
     @return The number of contiguous zero LSB bits
   */
   int (*count_lsb_bits)(void *a);

   /** Compute a power of two
     @param a  The integer to store the power in
     @param n  The power of two you want to store (a = 2^n)
     @return CRYPT_OK on success
   */
   int (*twoexpt)(void *a , int n);

/* ---- radix conversions ---- */

   /** read ascii string
     @param a     The integer to store into
     @param str   The string to read
     @param radix The radix the integer has been represented in (2-64)
     @return CRYPT_OK on success
   */
   int (*read_radix)(void *a, const char *str, int radix);

   /** write number to string
     @param a     The integer to store
     @param str   The destination for the string
     @param radix The radix the integer is to be represented in (2-64)
     @return CRYPT_OK on success
   */
   int (*write_radix)(void *a, char *str, int radix);

   /** get size as unsigned char string
     @param a  The integer to get the size (when stored in array of octets)
     @return   The length of the integer in octets
   */
   unsigned long (*unsigned_size)(void *a);

   /** store an integer as an array of octets
     @param src   The integer to store
     @param dst   The buffer to store the integer in
     @return CRYPT_OK on success
   */
   int (*unsigned_write)(void *src, unsigned char *dst);

   /** read an array of octets and store as integer
     @param dst   The integer to load
     @param src   The array of octets
     @param len   The number of octets
     @return CRYPT_OK on success
   */
   int (*unsigned_read)(         void *dst,
                        unsigned char *src,
                        unsigned long  len);

/* ---- basic math ---- */

   /** add two integers
     @param a   The first source integer
     @param b   The second source integer
     @param c   The destination of "a + b"
     @return CRYPT_OK on success
   */
   int (*add)(void *a, void *b, void *c);

   /** add two integers
     @param a   The first source integer
     @param b   The second source integer
                (single digit of upto bits_per_digit in length)
     @param c   The destination of "a + b"
     @return CRYPT_OK on success
   */
   int (*addi)(void *a, unsigned long b, void *c);

   /** subtract two integers
     @param a   The first source integer
     @param b   The second source integer
     @param c   The destination of "a - b"
     @return CRYPT_OK on success
   */
   int (*sub)(void *a, void *b, void *c);

   /** subtract two integers
     @param a   The first source integer
     @param b   The second source integer
                (single digit of upto bits_per_digit in length)
     @param c   The destination of "a - b"
     @return CRYPT_OK on success
   */
   int (*subi)(void *a, unsigned long b, void *c);

   /** multiply two integers
     @param a   The first source integer
     @param b   The second source integer
                (single digit of upto bits_per_digit in length)
     @param c   The destination of "a * b"
     @return CRYPT_OK on success
   */
   int (*mul)(void *a, void *b, void *c);

   /** multiply two integers
     @param a   The first source integer
     @param b   The second source integer
                (single digit of upto bits_per_digit in length)
     @param c   The destination of "a * b"
     @return CRYPT_OK on success
   */
   int (*muli)(void *a, unsigned long b, void *c);

   /** Square an integer
     @param a    The integer to square
     @param b    The destination
     @return CRYPT_OK on success
   */
   int (*sqr)(void *a, void *b);

   /** Divide an integer
     @param a    The dividend
     @param b    The divisor
     @param c    The quotient (can be NULL to signify don't care)
     @param d    The remainder (can be NULL to signify don't care)
     @return CRYPT_OK on success
   */
   int (*mpdiv)(void *a, void *b, void *c, void *d);

   /** divide by two
      @param  a   The integer to divide (shift right)
      @param  b   The destination
      @return CRYPT_OK on success
   */
   int (*div_2)(void *a, void *b);

   /** Get remainder (small value)
      @param  a    The integer to reduce
      @param  b    The modulus (upto bits_per_digit in length)
      @param  c    The destination for the residue
      @return CRYPT_OK on success
   */
   int (*modi)(void *a, unsigned long b, unsigned long *c);

   /** gcd
      @param  a     The first integer
      @param  b     The second integer
      @param  c     The destination for (a, b)
      @return CRYPT_OK on success
   */
   int (*gcd)(void *a, void *b, void *c);

   /** lcm
      @param  a     The first integer
      @param  b     The second integer
      @param  c     The destination for [a, b]
      @return CRYPT_OK on success
   */
   int (*lcm)(void *a, void *b, void *c);

   /** Modular multiplication
      @param  a     The first source
      @param  b     The second source
      @param  c     The modulus
      @param  d     The destination (a*b mod c)
      @return CRYPT_OK on success
   */
   int (*mulmod)(void *a, void *b, void *c, void *d);

   /** Modular squaring
      @param  a     The first source
      @param  b     The modulus
      @param  c     The destination (a*a mod b)
      @return CRYPT_OK on success
   */
   int (*sqrmod)(void *a, void *b, void *c);

   /** Modular inversion
      @param  a     The value to invert
      @param  b     The modulus
      @param  c     The destination (1/a mod b)
      @return CRYPT_OK on success
   */
   int (*invmod)(void *, void *, void *);

/* ---- reduction ---- */

   /** setup Montgomery
       @param a  The modulus
       @param b  The destination for the reduction digit
       @return CRYPT_OK on success
   */
   int (*montgomery_setup)(void *a, void **b);

   /** get normalization value
       @param a   The destination for the normalization value
       @param b   The modulus
       @return  CRYPT_OK on success
   */
   int (*montgomery_normalization)(void *a, void *b);

   /** reduce a number
       @param a   The number [and dest] to reduce
       @param b   The modulus
       @param c   The value "b" from montgomery_setup()
       @return CRYPT_OK on success
   */
   int (*montgomery_reduce)(void *a, void *b, void *c);

   /** clean up  (frees memory)
       @param a   The value "b" from montgomery_setup()
       @return CRYPT_OK on success
   */
   void (*montgomery_deinit)(void *a);

/* ---- exponentiation ---- */

   /** Modular exponentiation
       @param a    The base integer
       @param b    The power (can be negative) integer
       @param c    The modulus integer
       @param d    The destination
       @return CRYPT_OK on success
   */
   int (*exptmod)(void *a, void *b, void *c, void *d);

   /** Primality testing
       @param a     The integer to test
       @param b     The number of Miller-Rabin tests that shall be executed
       @param c     The destination of the result (FP_YES if prime)
       @return CRYPT_OK on success
   */
   int (*isprime)(void *a, int b, int *c);

/* ----  (optional) ecc point math ---- */

   /** ECC GF(p) point multiplication (from the NIST curves)
       @param k   The integer to multiply the point by
       @param G   The point to multiply
       @param R   The destination for kG
       @param modulus  The modulus for the field
       @param map Boolean indicated whether to map back to affine or not
                  (can be ignored if you work in affine only)
       @return CRYPT_OK on success
   */
   int (*ecc_ptmul)(     void *k,
                    ecc_point *G,
                    ecc_point *R,
                         void *modulus,
                          int  map);

   /** ECC GF(p) point addition
       @param P    The first point
       @param Q    The second point
       @param R    The destination of P + Q
       @param modulus  The modulus
       @param mp   The "b" value from montgomery_setup()
       @return CRYPT_OK on success
   */
   int (*ecc_ptadd)(ecc_point *P,
                    ecc_point *Q,
                    ecc_point *R,
                         void *modulus,
                         void *mp);

   /** ECC GF(p) point double
       @param P    The first point
       @param R    The destination of 2P
       @param modulus  The modulus
       @param mp   The "b" value from montgomery_setup()
       @return CRYPT_OK on success
   */
   int (*ecc_ptdbl)(ecc_point *P,
                    ecc_point *R,
                         void *modulus,
                         void *mp);

   /** ECC mapping from projective to affine,
       currently uses (x,y,z) => (x/z^2, y/z^3, 1)
       @param P     The point to map
       @param modulus The modulus
       @param mp    The "b" value from montgomery_setup()
       @return CRYPT_OK on success
       @remark The mapping can be different but keep in mind a
               ecc_point only has three integers (x,y,z) so if
               you use a different mapping you have to make it fit.
   */
   int (*ecc_map)(ecc_point *P, void *modulus, void *mp);

   /** Computes kA*A + kB*B = C using Shamir's Trick
       @param A        First point to multiply
       @param kA       What to multiple A by
       @param B        Second point to multiply
       @param kB       What to multiple B by
       @param C        [out] Destination point (can overlap with A or B)
       @param modulus  Modulus for curve
       @return CRYPT_OK on success
   */
   int (*ecc_mul2add)(ecc_point *A, void *kA,
                      ecc_point *B, void *kB,
                      ecc_point *C,
                           void *modulus);

/* ---- (optional) rsa optimized math (for internal CRT) ---- */

   /** RSA Key Generation
       @param prng     An active PRNG state
       @param wprng    The index of the PRNG desired
       @param size     The size of the key in octets
       @param e        The "e" value (public key).
                       e==65537 is a good choice
       @param key      [out] Destination of a newly created private key pair
       @return CRYPT_OK if successful, upon error all allocated ram is freed
    */
    int (*rsa_keygen)(prng_state *prng,
                             int  wprng,
                             int  size,
                            long  e,
                         rsa_key *key);

   /** RSA exponentiation
      @param in       The octet array representing the base
      @param inlen    The length of the input
      @param out      The destination (to be stored in an octet array format)
      @param outlen   The length of the output buffer and the resulting size
                      (zero padded to the size of the modulus)
      @param which    PK_PUBLIC for public RSA and PK_PRIVATE for private RSA
      @param key      The RSA key to use
      @return CRYPT_OK on success
   */
   int (*rsa_me)(const unsigned char *in,   unsigned long inlen,
                       unsigned char *out,  unsigned long *outlen, int which,
                       rsa_key *key);

/* ---- basic math continued ---- */

   /** Modular addition
      @param  a     The first source
      @param  b     The second source
      @param  c     The modulus
      @param  d     The destination (a + b mod c)
      @return CRYPT_OK on success
   */
   int (*addmod)(void *a, void *b, void *c, void *d);

   /** Modular substraction
      @param  a     The first source
      @param  b     The second source
      @param  c     The modulus
      @param  d     The destination (a - b mod c)
      @return CRYPT_OK on success
   */
   int (*submod)(void *a, void *b, void *c, void *d);

/* ---- misc stuff ---- */

   /** Make a pseudo-random mpi
      @param  a     The mpi to make random
      @param  size  The desired length
      @return CRYPT_OK on success
   */
   int (*rand)(void *a, int size);
} ltc_math_descriptor;
\end{verbatim}
\end{small}

Most of the functions are fairly straightforward and do not need documentation.  We'll cover the basic conventions of the API and then explain the accelerated functions.

\subsection{Conventions}

All \textit{bignums} are accessed through an opaque \textit{void *} data type.  You must internally cast the pointer if you need to access members of your bignum structure.  During
the init calls a \textit{void **} will be passed where you allocate your structure and set the pointer then initialize the number to zero.  During the deinit calls you must
free the bignum as well as the structure you allocated to place it in.

All functions except the Montgomery reductions work from left to right with the arguments.  For example, mul(a, b, c) computes $c \leftarrow ab$.

All functions (except where noted otherwise) return \textbf{CRYPT\_OK} to signify a successful operation.  All error codes must be valid LibTomCrypt error codes.

The digit routines (including functions with the \textit{i} suffix) use a \textit{ltc\_mp\_digit} to represent the digit.  If your internal digit is larger than this you must
then partition your digits.  Note that if your digit is smaller than an \textit{ltc\_mp\_digit} that is also acceptable as the \textit{bits\_per\_digit} parameter will specify this.

\subsubsection{ltc\_mp\_digit}
\index{ltc\_mp\_digit}

Depending on the archtitecture \textit{ltc\_mp\_digit} is either a $32$- or $64$-bit long \textit{unsigned} data type.

\subsection{ECC Functions}
The ECC system in LibTomCrypt is based off of the NIST recommended curves over $GF(p)$ and is used to implement EC-DSA and EC-DH.   The ECC functions work with
the \textbf{ecc\_point} structure and assume the points are stored in Jacobian projective format.

\begin{verbatim}
/** A point on a ECC curve, stored in Jacobian format such
    that (x,y,z) => (x/z^2, y/z^3, 1) when interpreted as affine */
typedef struct {
    /** The x co-ordinate */
    void *x;
    /** The y co-ordinate */
    void *y;
    /** The z co-ordinate */
    void *z;
} ecc_point;
\end{verbatim}

All ECC functions must use this mapping system.  The only exception is when you remap all ECC callbacks which will allow you to have more control
over how the ECC math will be implemented.  Out of the box you only have three parameters per point to use $(x, y, z)$ however, these are just void pointers.  They
could point to anything you want.  The only further exception is the export functions which expects the values to be in affine format.

\subsubsection{Point Multiply}
This will multiply the point $G$ by the scalar $k$ and store the result in the point $R$.  The value should be mapped to affine only if $map$ is set to one.

\subsubsection{Point Addition}
This will add the point $P$ to the point $Q$ and store it in the point $R$.  The $mp$ parameter is the \textit{b} value from the montgomery\_setup() call.  The input points
may be in either affine (with $z = 1$) or projective format and the output point is always projective.

\subsubsection{Point Mapping}
This will map the point $P$ back from projective to affine.  The output point $P$ must be of the form $(x, y, 1)$.

\subsubsection{Shamir's Trick}
\index{Shamir's Trick}
\index{ltc\_ecc\_mul2add()}
To accelerate EC--DSA verification the library provides a built--in function called ltc\_ecc\_mul2add().  This performs two point multiplications and an addition in
roughly the time of one point multiplication.  It is called from ecc\_verify\_hash() if an accelerator is not present.  The acclerator function must allow the points to
overlap (e.g., $A \leftarrow k_1A + k_2B$) and must return the final point in affine format.


\subsection{RSA Functions}
The RSA Modular Exponentiation (ME) function is used by the RSA API to perform exponentiations for private and public key operations.  In particular for
private key operations it uses the CRT approach to lower the time required.  It is passed an RSA key with the following format.

\begin{verbatim}
/** RSA PKCS style key */
typedef struct Rsa_key {
    /** Type of key, PK_PRIVATE or PK_PUBLIC */
    int type;
    /** The public exponent */
    void *e;
    /** The private exponent */
    void *d;
    /** The modulus */
    void *N;
    /** The p factor of N */
    void *p;
    /** The q factor of N */
    void *q;
    /** The 1/q mod p CRT param */
    void *qP;
    /** The d mod (p - 1) CRT param */
    void *dP;
    /** The d mod (q - 1) CRT param */
    void *dQ;
} rsa_key;
\end{verbatim}

The call reads the \textit{in} buffer as an unsigned char array in big endian format.  Then it performs the exponentiation and stores the output in big endian format
to the \textit{out} buffer.  The output must be zero padded (leading bytes) so that the length of the output matches the length of the modulus (in bytes).  For example,
for RSA--1024 the output is always 128 bytes regardless of how small the numerical value of the exponentiation is.

Since the function is given the entire RSA key (for private keys only) CRT is possible as prescribed in the PKCS \#1 v2.1 specification.

\newpage
\markboth{Index}{Index}
\input{crypt.ind}

\end{document}

% ref:         $Format:%D$
% git commit:  $Format:%H$
% commit time: $Format:%ai$