aboutsummaryrefslogtreecommitdiff
path: root/src/scalar-crypto.adoc
blob: b879474da08f52c7b701d74c45aba559b38041e9 (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
== Cryptography Extensions: Scalar & Entropy Source Instructions, Version 1.0.1

=== Changelog

[cols="1,5"]
|===
| Version | Changes

| `v1.0.1` 
| Fix typos to show that 
  `c.srli`, `c.srai`, and `c.slli` are Zkt instructions in RV64.

| `v1.0.0` 
| Initial Release
|===

[[crypto_scalar_introduction]]
=== Introduction

This document describes the _scalar_ cryptography
extension for RISC-V.
All instructions described herein use the general-purpose `X`
registers, and obey the 2-read-1-write register access constraint.
These instructions are designed to be lightweight and suitable
for `32` and `64` bit base architectures; from embedded IoT class
cores to large, application class cores which do not implement a
vector unit.

This document also describes the architectural interface to an
Entropy Source, which can be used to generate cryptographic secrets.
This is found in <<crypto_scalar_es>>.

It also contains a mechanism allowing core implementers to provide
_"Constant Time Execution"_ guarantees in <<crypto_scalar_zkt>>.

A companion document _Volume II: Vector Instructions_, describes
instruction proposals which build on the RISC-V Vector Extension.
The Vector Cryptography extension is currently a work in progress
waiting for the base Vector extension to stabilise.
We expect to pick up this work in earnest in Q4-2021 or Q1-2022.

[[crypto_scalar_audience]]
==== Intended Audience

Cryptography is a specialised subject, requiring people with many different
backgrounds to cooperate in its secure and efficient implementation.
Where possible, we have written this specification to be understandable by
all, though we recognise that the motivations and references to
algorithms or other specifications and standards may be unfamiliar to those
who are not domain experts.

This specification anticipates being read and acted on by various people
with different backgrounds.
We have tried to capture these backgrounds
here, with a brief explanation of what we expect them to know, and how
it relates to the specification.
We hope this aids people's understanding of which aspects of the specification
are particularly relevant to them, and which they may (safely!) ignore or
pass to a colleague.

Cryptographers and cryptographic software developers::
These are the people we expect to write code using the instructions
in this specification.
They should understand fairly obviously the motivations for the
instructions we include, and be familiar with most of the algorithms
and outside standards to which we refer.
We expect the sections on constant time execution
(<<crypto_scalar_zkt>>)
and the entropy source
(<<crypto_scalar_es>>)
to be chiefly understood with their help.

Computer architects::
We do not expect architects to have a cryptography background.
We nonetheless expect architects to be able to examine our instructions
for implementation issues, understand how the instructions will be used
in context, and advise on how best to fit the functionality the
cryptographers want to the ISA interface.

Digital design engineers & micro-architects::
These are the people who will implement the specification inside a
core. Again, no cryptography expertise is assumed, but we expect them to
interpret the specification and anticipate any hardware implementation
issues, e.g., where high-frequency design considerations apply, or where
latency/area tradeoffs exist etc.
In particular, they should be aware of the literature around efficiently
implementing AES and SM4 SBoxes in hardware.

Verification engineers::
Responsible for ensuring the correct implementation of the extension
in hardware.
No cryptography background is assumed.
We expect them to identify interesting test cases from the
specification. An understanding of their real-world usage will help with this.
We do not expect verification engineers in this sense to be experts
in entropy source design or certification, since this is a very
specialised area.
We do expect them however to identify all of the _architectural_
test cases around the entropy source interface.

These are by no means the only people concerned with the specification,
but they are the ones we considered most while writing it.

[[crypto_scalar_sail_specifications]]
==== Sail Specifications

RISC-V maintains a 
link:https://github.com/riscv/sail-riscv[formal model]
of the ISA specification,
implemented in the Sail ISA specification language
cite:[sail].
Note that _Sail_ refers to the specification language itself,
and that there is a _model of RISC-V_, written using Sail.
It is not correct to refer to "the Sail model".
This is ambiguous, given there are many models of different ISAs implemented
using Sail. We refer to the Sail implementation of RISC-V as
"the RISC-V Sail model".

The Cryptography extension uses inline Sail code snippets from the
actual model to give canonical descriptions of instruction
functionality.
Each instruction is accompanied by its expression in Sail, and includes
calls to supporting functions which are too verbose to include directly
in the specification.
This supporting code is listed in
<<crypto_scalar_appx_sail>>.
The 
link:https://github.com/rems-project/sail/blob/sail2/manual.pdf[Sail Manual]
is recommended reading in order to best understand the code snippets.

Note that this document contains only a subset of the formal model: refer to
the formal model Github
link:https://github.com/riscv/sail-riscv[repository]
for the complete model.

[[crypto_scalar_policies]]
==== Policies

In creating this proposal, we tried to adhere to the following
policies:

* Where there is a choice between:
  . supporting diverse implementation strategies for an algorithm
  or
  . supporting a single implementation style which is more performant /
     less expensive;
  the crypto extension will pick the more constrained but performant
  option.
  This fits a common pattern in other parts of the RISC-V specification,
  where recommended (but not required) instruction sequences for performing
  particular tasks are given as an example, such that both hardware and
  software implementers can optimise for only a single use-case.
  
* The extension will be designed to support _existing_ standardised
  cryptographic constructs well.
  It will not try to support proposed standards, or cryptographic
  constructs which exist only in academia.
  Cryptographic standards which are settled upon concurrently with or after
  the RISC-V cryptographic extension standardisation will be dealt with
  by future additions to, or versions of, the RISC-V cryptographic
  standard extension. It is anticipated that the NIST Lightweight
  Cryptography contest and the NIST Post-Quantum Cryptography contest
  may be dealt with this way, depending on timescales.
  
* Historically, there has been some discussion
  cite:[LSYRR:04]
  on how newly supported operations in general-purpose computing might
  enable new bases for cryptographic algorithms.
  The standard will not try to anticipate new useful low-level
  operations which _may_ be useful as building blocks for
  future cryptographic constructs.
  
* Regarding side-channel countermeasures:
  Where relevant, proposed instructions must aim to remove the
  possibility of any timing side-channels.
  For side-channels based on power or electro-magnetic (EM) measurements,
  the extension will not aim to support countermeasures which are
  implemented above the ISA abstraction layer.
  Recommendations will be given where relevant on how micro-architectures
  can implement instructions in a power/EM side-channel resistant way.

[[crypto_scalar_extensions]]
=== Extensions Overview

The group of extensions introduced by the Scalar Cryptography Instruction Set
Extension is listed here.

Detection of individual cryptography extensions uses the
unified software-based RISC-V discovery method.

[NOTE]
====
At the time of writing, these discovery mechanisms are still a work in
progress.
====

.A note on extension rationale
[NOTE, caption="SH"]
====
Specialist encryption and decryption instructions are separated into different
functional groups because some use cases (e.g., Galois/Counter
Mode in TLS 1.3) do not require decryption functionality.

The NIST and ShangMi algorithms suites are separated because their
usefulness is heavily dependent on the countries a device is expected to
operate in. NIST ciphers are a part of most standardised internet
protocols, while ShangMi ciphers are required for use in China.
====

[[zbkb-sc,Zbkb-sc]]
==== `Zbkb` - Bitmanip instructions for Cryptography

These are a subset of the Bitmanipulation Extension `Zbb` which are
particularly useful for Cryptography.

NOTE: Some of these instructions are defined in the first Bitmanip
ratification package, and some are not (
<<insns-pack-sc,pack>>,
<<insns-packh-sc,packh>>,
<<insns-packw-sc,packw>>,
<<insns-brev8,brev8>>,
<<insns-zip-sc,zip>>,
<<insns-unzip-sc,unzip>>).
All of the instructions in <<zbkb-sc>> have their complete specification included
in this document, including those _not_ present in the initial
Bitmanip ratification package.
This is to make the present specification complete as a standalone document.
Inevitably there might be small divergences between the Bitmanip and
Scalar Cryptography specification documents as they move at different
paces.
When this happens, assume that the Bitmanip specification has the
most up-to-date version of Bitmanip instructions.
This is an unfortunate but necessary stop-gap while Scalar Cryptography
and Bitmanip are being rapidly iterated on prior to public review.

[%header,cols="^1,^1,4,8"]
|===
|RV32
|RV64
|Mnemonic
|Instruction

| &#10003; | &#10003; |  ror         | <<insns-ror-sc>>
| &#10003; | &#10003; |  rol         | <<insns-rol-sc>>
| &#10003; | &#10003; |  rori        | <<insns-rori-sc>>
|          | &#10003; |  rorw        | <<insns-rorw-sc>>
|          | &#10003; |  rolw        | <<insns-rolw-sc>>
|          | &#10003; |  roriw       | <<insns-roriw-sc>>
| &#10003; | &#10003; |  andn        | <<insns-andn-sc>>
| &#10003; | &#10003; |  orn         | <<insns-orn-sc>>
| &#10003; | &#10003; |  xnor        | <<insns-xnor-sc>>
| &#10003; | &#10003; |  pack        | <<insns-pack-sc>>
| &#10003; | &#10003; |  packh       | <<insns-packh-sc>>
|          | &#10003; |  packw       | <<insns-packw-sc>>
| &#10003; | &#10003; |  brev8       | <<insns-brev8>>
| &#10003; | &#10003; |  rev8        | <<insns-rev8-sc>>
| &#10003; |          |  zip         | <<insns-zip-sc>>
| &#10003; |          |  unzip       | <<insns-unzip-sc>>
|===

[[zbkc-sc,Zbkc-sc]]
==== `Zbkc` - Carry-less multiply instructions

Constant time carry-less multiply for Galois/Counter Mode.
These are separated from the <<zbkb-sc>> because they
have a considerable implementation overhead which cannot be amortised
across other instructions.

NOTE: These instructions are defined in the first Bitmanip
ratification package for the `Zbc` extension.
All of the instructions in <<zbkc-sc>> have their complete specification included
in this document, including those _not_ present in the initial
Bitmanip ratification package.
This is to make the present specification complete as a standalone document.
Inevitably there might be small divergences between the Bitmanip and
Scalar Cryptography specification documents as they move at different
paces.
When this happens, assume that the Bitmanip specification has the
most up-to-date version of Bitmanip instructions.
This is an unfortunate but necessary stop-gap while Scalar Cryptography
and Bitmanip are being rapidly iterated on prior to public review.

[%header,cols="^1,^1,4,8"]
|===
|RV32
|RV64
|Mnemonic
|Instruction

| &#10003; | &#10003; |  clmul       | <<insns-clmul>>
| &#10003; | &#10003; |  clmulh      | <<insns-clmulh-sc>>
|===

[[zbkx-sc,Zbkx-sc]]
==== `Zbkx` - Crossbar permutation instructions

These instructions are useful for implementing SBoxes in constant time, and
potentially with DPA protections.
These are separated from the <<zbkb-sc>> because they
have an implementation overhead which cannot be amortised
across other instructions.

NOTE: All of these instructions are missing from the first Bitmanip
ratification package.
Hence,  all of the instructions in <<zbkx-sc>> have their complete specification
included in this document.
This is to make the present specification complete as a standalone document.
Inevitably there might be small divergences between the Bitmanip and
Scalar Cryptography specification documents as they move at different
paces.
When this happens, assume that the Bitmanip specification has the
most up-to-date version of Bitmanip instructions.
This is an unfortunate but necessary stop-gap while Scalar Cryptography
and Bitmanip are being rapidly iterated on prior to public review.

[%header,cols="^1,^1,4,8"]
|===
|RV32
|RV64
|Mnemonic
|Instruction

| &#10003; | &#10003; |  xperm8      | <<insns-xperm8>>
| &#10003; | &#10003; |  xperm4      | <<insns-xperm4>>
|===

[[zknd,Zknd]]
==== `Zknd` - NIST Suite: AES Decryption

Instructions for accelerating the decryption and key-schedule functions of
the AES block cipher.

[%header,cols="^1,^1,4,8"]
|===
|RV32
|RV64
|Mnemonic
|Instruction

| &#10003; |          | aes32dsi     | <<insns-aes32dsi>>
| &#10003; |          | aes32dsmi    | <<insns-aes32dsmi>>
|          | &#10003; | aes64ds      | <<insns-aes64ds>>
|          | &#10003; | aes64dsm     | <<insns-aes64dsm>>
|          | &#10003; | aes64im      | <<insns-aes64im>>
|          | &#10003; | aes64ks1i    | <<insns-aes64ks1i>>
|          | &#10003; | aes64ks2     | <<insns-aes64ks2>>
|===

NOTE: The <<insns-aes64ks1i>> and <<insns-aes64ks2>> instructions are
present in both the <<zknd>> and <<zkne>> extensions.

[[zkne,Zkne]]
==== `Zkne` - NIST Suite: AES Encryption

Instructions for accelerating the encryption and key-schedule functions of
the AES block cipher.

[%header,cols="^1,^1,4,8"]
|===
|RV32
|RV64
|Mnemonic
|Instruction

| &#10003; |          | aes32esi     | <<insns-aes32esi>>
| &#10003; |          | aes32esmi    | <<insns-aes32esmi>>
|          | &#10003; | aes64es      | <<insns-aes64es>>
|          | &#10003; | aes64esm     | <<insns-aes64esm>>
|          | &#10003; | aes64ks1i    | <<insns-aes64ks1i>>
|          | &#10003; | aes64ks2     | <<insns-aes64ks2>>
|===

NOTE: The
<<insns-aes64ks1i,`aes64ks1i`>>
and
<<insns-aes64ks2,`aes64ks2`>>
instructions are present in both the <<zknd>> and <<zkne>> extensions.

[[zknh,Zknh]]
==== `Zknh` - NIST Suite: Hash Function Instructions

Instructions for accelerating the SHA2 family of cryptographic hash functions,
as specified in cite:[nist:fips:180:4].

[%header,cols="^1,^1,4,8"]
|===
|RV32
|RV64
|Mnemonic
|Instruction

| &#10003; | &#10003; | sha256sig0   | <<insns-sha256sig0>>
| &#10003; | &#10003; | sha256sig1   | <<insns-sha256sig1>>
| &#10003; | &#10003; | sha256sum0   | <<insns-sha256sum0>>
| &#10003; | &#10003; | sha256sum1   | <<insns-sha256sum1>>
| &#10003; |          | sha512sig0h  | <<insns-sha512sig0h>>
| &#10003; |          | sha512sig0l  | <<insns-sha512sig0l>>
| &#10003; |          | sha512sig1h  | <<insns-sha512sig1h>>
| &#10003; |          | sha512sig1l  | <<insns-sha512sig1l>>
| &#10003; |          | sha512sum0r  | <<insns-sha512sum0r>>
| &#10003; |          | sha512sum1r  | <<insns-sha512sum1r>>
|          | &#10003; | sha512sig0   | <<insns-sha512sig0>>
|          | &#10003; | sha512sig1   | <<insns-sha512sig1>>
|          | &#10003; | sha512sum0   | <<insns-sha512sum0>>
|          | &#10003; | sha512sum1   | <<insns-sha512sum1>>
|===

[[zksed,Zksed]]
==== `Zksed` - ShangMi Suite: SM4 Block Cipher Instructions

Instructions for accelerating the SM4 Block Cipher.
Note that unlike AES, this cipher uses the same core operation for
encryption and decryption, hence there is only one
extension for it.

[%header,cols="^1,^1,4,8"]
|===
|RV32
|RV64
|Mnemonic
|Instruction

| &#10003; | &#10003; | sm4ed        | <<insns-sm4ed>>
| &#10003; | &#10003; | sm4ks        | <<insns-sm4ks>>
|===

[[zksh,Zksh]]
==== `Zksh` - ShangMi Suite: SM3 Hash Function Instructions

Instructions for accelerating the SM3 hash function.

[%header,cols="^1,^1,4,8"]
|===
|RV32
|RV64
|Mnemonic
|Instruction

| &#10003; | &#10003; | sm3p0        | <<insns-sm3p0>>
| &#10003; | &#10003; | sm3p1        | <<insns-sm3p1>>
|===

[[zkr,Zkr]]
==== `Zkr` - Entropy Source Extension

The entropy source extension defines the `seed` CSR at address `0x015`. 
This CSR provides up to 16 physical `entropy` bits that can be used to
seed cryptographic random bit generators. 

See <<crypto_scalar_es>> for the normative specification and access control
notes. <<crypto_scalar_appx_es>> contains design rationale and further
recommendations to implementers.

[[zkn,Zkn]]
==== `Zkn` - NIST Algorithm Suite

This extension is shorthand for the following set of other extensions:

[%header,cols="^1,4"]
|===
|Included Extension
|Description

| <<zbkb-sc>>  | Bitmanipulation instructions for cryptography.
| <<zbkc-sc>>  | Carry-less multiply instructions.
| <<zbkx-sc>>  | Cross-bar Permutation instructions.
| <<zkne>>  | AES encryption instructions.
| <<zknd>>  | AES decryption instructions.
| <<zknh>>  | SHA2 hash function instructions.
|===

A core which implements `Zkn` must implement all of the above extensions.

[[zks,Zks]]
==== `Zks` - ShangMi Algorithm Suite

This extension is shorthand for the following set of other extensions:

[%header,cols="^1,4"]
|===
|Included Extension
|Description

| <<zbkb-sc>>  | Bitmanipulation instructions for cryptography.
| <<zbkc-sc>>  | Carry-less multiply instructions.
| <<zbkx-sc>>  | Cross-bar Permutation instructions.
| <<zksed>> | SM4 block cipher instructions.
| <<zksh>>  | SM3 hash function instructions.
|===

A core which implements `Zks` must implement all of the above extensions.

[[zk,Zk]]
==== `Zk` - Standard scalar cryptography extension

This extension is shorthand for the following set of other extensions:

[%header,cols="^1,4"]
|===
|Included Extension
|Description

| <<zkn>>  | NIST Algorithm suite extension.
| <<zkr>>  | Entropy Source extension.
| <<crypto_scalar_zkt,Zkt>>  | Data independent execution latency extension.
|===

A core which implements `Zk` must implement all of the above extensions.

==== `Zkt` - Data Independent Execution Latency

This extension allows CPU implementers to indicate to
cryptographic software developers that a subset of RISC-V instructions
are guaranteed to be implemented such that their execution latency
is independent of the data values they operate on.
A complete description of this extension is found in
<<crypto_scalar_zkt>>.

// ------------------------------------------------------------

[[crypto_scalar_insns, reftext="Scalar Cryptography Instructions"]]
=== Instructions

[#insns-aes32dsi, reftext="AES final round decrypt (RV32)"]
==== aes32dsi

Synopsis::
AES final round decryption instruction for RV32.

Mnemonic::
aes32dsi rd, rs1, rs2, bs

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x33},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x0},
{bits: 5, name: 'rs1'},
{bits: 5, name: 'rs2'},
{bits: 5, name: 0x15},
{bits: 2, name: 'bs'},
]}
....

Description:: 
This instruction sources a single byte from `rs2` according to `bs`.
To this it applies the inverse AES SBox operation, and XOR's the result with
`rs1`.
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

Operation::
[source,sail]
--
function clause execute (AES32DSI (bs,rs2,rs1,rd)) = {
  let shamt   : bits( 5) = bs @ 0b000; /* shamt = bs*8 */
  let si      : bits( 8) = (X(rs2)[31..0] >> shamt)[7..0]; /* SBox Input */
  let so      : bits(32) = 0x000000 @ aes_sbox_inv(si);
  let result  : bits(32) = X(rs1)[31..0] ^ rol32(so, unsigned(shamt));
  X(rd) = EXTS(result); RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zknd>> (RV32)
| v1.0.0
| Ratified
| <<zkn>> (RV32)
| v1.0.0
| Ratified
| <<zk>> (RV32)
| v1.0.0
| Ratified
|===

<<<

[#insns-aes32dsmi, reftext="AES middle round decrypt (RV32)"]
==== aes32dsmi

Synopsis::
AES middle round decryption instruction for RV32.

Mnemonic::
aes32dsmi rd, rs1, rs2, bs

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x33},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x0},
{bits: 5, name: 'rs1'},
{bits: 5, name: 'rs2'},
{bits: 5, name: 0x17},
{bits: 2, name: 'bs'},
]}
....

Description:: 
This instruction sources a single byte from `rs2` according to `bs`.
To this it applies the inverse AES SBox operation, and a partial inverse
MixColumn, before XOR'ing the result with `rs1`.
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

Operation::
[source,sail]
--
function clause execute (AES32DSMI (bs,rs2,rs1,rd)) = {
  let shamt   : bits( 5) = bs @ 0b000; /* shamt = bs*8 */
  let si      : bits( 8) = (X(rs2)[31..0] >> shamt)[7..0]; /* SBox Input */
  let so      : bits( 8) = aes_sbox_inv(si);
  let mixed   : bits(32) = aes_mixcolumn_byte_inv(so);
  let result  : bits(32) = X(rs1)[31..0] ^ rol32(mixed, unsigned(shamt));
  X(rd) = EXTS(result); RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zknd>> (RV32)
| v1.0.0
| Ratified
| <<zkn>> (RV32)
| v1.0.0
| Ratified
| <<zk>> (RV32)
| v1.0.0
| Ratified
|===

<<<

[#insns-aes32esi, reftext="AES final round encrypt (RV32)"]
==== aes32esi

Synopsis::
AES final round encryption instruction for RV32.

Mnemonic::
aes32esi rd, rs1, rs2, bs

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x33},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x0},
{bits: 5, name: 'rs1'},
{bits: 5, name: 'rs2'},
{bits: 5, name: 0x11},
{bits: 2, name: 'bs'},
]}
....

Description:: 
This instruction sources a single byte from `rs2` according to `bs`.
To this it applies the forward AES SBox operation,
before XOR'ing the result with `rs1`.
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

Operation::
[source,sail]
--
function clause execute (AES32ESI (bs,rs2,rs1,rd)) = {
  let shamt   : bits( 5) = bs @ 0b000; /* shamt = bs*8 */
  let si      : bits( 8) = (X(rs2)[31..0] >> shamt)[7..0]; /* SBox Input */
  let so      : bits(32) = 0x000000 @ aes_sbox_fwd(si);
  let result  : bits(32) = X(rs1)[31..0] ^ rol32(so, unsigned(shamt));
  X(rd) = EXTS(result); RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zkne>> (RV32)
| v1.0.0
| Ratified
| <<zkn>> (RV32)
| v1.0.0
| Ratified
| <<zk>> (RV32)
| v1.0.0
| Ratified
|===

<<<

[#insns-aes32esmi, reftext="AES middle round encrypt (RV32)"]
==== aes32esmi

Synopsis::
AES middle round encryption instruction for RV32.

Mnemonic::
aes32esmi rd, rs1, rs2, bs

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x33},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x0},
{bits: 5, name: 'rs1'},
{bits: 5, name: 'rs2'},
{bits: 5, name: 0x13},
{bits: 2, name: 'bs'},
]}
....

Description:: 
This instruction sources a single byte from `rs2` according to `bs`.
To this it applies the forward AES SBox operation, and a partial forward
MixColumn, before XOR'ing the result with `rs1`.
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

Operation::
[source,sail]
--
function clause execute (AES32ESMI (bs,rs2,rs1,rd)) = {
  let shamt   : bits( 5) = bs @ 0b000; /* shamt = bs*8 */
  let si      : bits( 8) = (X(rs2)[31..0] >> shamt)[7..0]; /* SBox Input */
  let so      : bits( 8) = aes_sbox_fwd(si);
  let mixed   : bits(32) = aes_mixcolumn_byte_fwd(so);
  let result  : bits(32) = X(rs1)[31..0] ^ rol32(mixed, unsigned(shamt));
  X(rd) = EXTS(result); RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zkne>> (RV32)
| v1.0.0
| Ratified
| <<zkn>> (RV32)
| v1.0.0
| Ratified
| <<zk>> (RV32)
| v1.0.0
| Ratified
|===

<<<

[#insns-aes64ds, reftext="AES decrypt final round (RV64)"]
==== aes64ds

Synopsis::
AES final round decryption instruction for RV64.

Mnemonic::
aes64ds rd, rs1, rs2

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x33},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x0},
{bits: 5, name: 'rs1'},
{bits: 5, name: 'rs2'},
{bits: 5, name: 0x1d},
{bits: 2, name: 0x0},
]}
....

Description:: 
Uses the two 64-bit source registers to represent the entire AES state,
and produces _half_ of the next round output, applying the Inverse ShiftRows
and SubBytes steps.
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

.Note To Software Developers
[NOTE,caption="SH"]
====
The following code snippet shows the final round of the AES block decryption.
`t0` and `t1` hold the current round state.
`t2` and `t3` hold the next round state.

  aes64ds t2, t0, t1
  aes64ds t3, t1, t0

Note the reversed register order of the second instruction.
====

Operation::
[source,sail]
--
function clause execute (AES64DS(rs2, rs1, rd)) = {
  let sr : bits(64) = aes_rv64_shiftrows_inv(X(rs2)[63..0], X(rs1)[63..0]);
  let wd : bits(64) = sr[63..0];
  X(rd) = aes_apply_inv_sbox_to_each_byte(wd);
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zknd>> (RV64)
| v1.0.0
| Ratified
| <<zkn>> (RV64)
| v1.0.0
| Ratified
| <<zk>> (RV64)
| v1.0.0
| Ratified
|===

<<<

[#insns-aes64dsm, reftext="AES decrypt middle round (RV64)"]
==== aes64dsm

Synopsis::
AES middle round decryption instruction for RV64.

Mnemonic::
aes64dsm rd, rs1, rs2

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x33},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x0},
{bits: 5, name: 'rs1'},
{bits: 5, name: 'rs2'},
{bits: 5, name: 0x1f},
{bits: 2, name: 0x0},
]}
....

Description:: 
Uses the two 64-bit source registers to represent the entire AES state,
and produces _half_ of the next round output, applying the Inverse ShiftRows,
SubBytes and MixColumns steps.
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

.Note To Software Developers
[NOTE,caption="SH"]
====
The following code snippet shows one middle round of the AES block decryption.
`t0` and `t1` hold the current round state.
`t2` and `t3` hold the next round state.

  aes64dsm t2, t0, t1
  aes64dsm t3, t1, t0

Note the reversed register order of the second instruction.
====

Operation::
[source,sail]
--
function clause execute (AES64DSM(rs2, rs1, rd)) = {
  let sr : bits(64) = aes_rv64_shiftrows_inv(X(rs2)[63..0], X(rs1)[63..0]);
  let wd : bits(64) = sr[63..0];
  let sb : bits(64) = aes_apply_inv_sbox_to_each_byte(wd);
  X(rd)  = aes_mixcolumn_inv(sb[63..32]) @ aes_mixcolumn_inv(sb[31..0]);
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zknd>> (RV64)
| v1.0.0
| Ratified
| <<zkn>> (RV64)
| v1.0.0
| Ratified
| <<zk>> (RV64)
| v1.0.0
| Ratified
|===

<<<

[#insns-aes64es, reftext="AES encrypt final round instruction (RV64)"]
==== aes64es

Synopsis::
AES final round encryption instruction for RV64.

Mnemonic::
aes64es rd, rs1, rs2

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x33},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x0},
{bits: 5, name: 'rs1'},
{bits: 5, name: 'rs2'},
{bits: 5, name: 0x19},
{bits: 2, name: 0x0},
]}
....

Description:: 
Uses the two 64-bit source registers to represent the entire AES state,
and produces _half_ of the next round output, applying the ShiftRows and
SubBytes steps.
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

.Note To Software Developers
[NOTE,caption="SH"]
====
The following code snippet shows the final round of the AES block encryption.
`t0` and `t1` hold the current round state.
`t2` and `t3` hold the next round state.

  aes64es t2, t0, t1
  aes64es t3, t1, t0

Note the reversed register order of the second instruction.
====

Operation::
[source,sail]
--
function clause execute (AES64ES(rs2, rs1, rd)) = {
  let sr : bits(64) = aes_rv64_shiftrows_fwd(X(rs2)[63..0], X(rs1)[63..0]);
  let wd : bits(64) = sr[63..0];
  X(rd) = aes_apply_fwd_sbox_to_each_byte(wd);
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zkne>> (RV64)
| v1.0.0
| Ratified
| <<zkn>> (RV64)
| v1.0.0
| Ratified
| <<zk>> (RV64)
| v1.0.0
| Ratified
|===

<<<

[#insns-aes64esm, reftext="AES encrypt middle round instruction (RV64)"]
==== aes64esm

Synopsis::
AES middle round encryption instruction for RV64.

Mnemonic::
aes64esm rd, rs1, rs2

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x33},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x0},
{bits: 5, name: 'rs1'},
{bits: 5, name: 'rs2'},
{bits: 5, name: 0x1b},
{bits: 2, name: 0x0},
]}
....

Description:: 
Uses the two 64-bit source registers to represent the entire AES state,
and produces _half_ of the next round output, applying the ShiftRows,
SubBytes and MixColumns steps.
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

.Note To Software Developers
[NOTE,caption="SH"]
====
The following code snippet shows one middle round of the AES block encryption.
`t0` and `t1` hold the current round state.
`t2` and `t3` hold the next round state.

  aes64esm t2, t0, t1
  aes64esm t3, t1, t0

Note the reversed register order of the second instruction.
====

Operation::
[source,sail]
--
function clause execute (AES64ESM(rs2, rs1, rd)) = {
  let sr : bits(64) = aes_rv64_shiftrows_fwd(X(rs2)[63..0], X(rs1)[63..0]);
  let wd : bits(64) = sr[63..0];
  let sb : bits(64) = aes_apply_fwd_sbox_to_each_byte(wd);
  X(rd)  =  aes_mixcolumn_fwd(sb[63..32]) @ aes_mixcolumn_fwd(sb[31..0]);
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zkne>> (RV64)
| v1.0.0
| Ratified
| <<zkn>> (RV64)
| v1.0.0
| Ratified
| <<zk>> (RV64)
| v1.0.0
| Ratified
|===

<<<

[#insns-aes64im, reftext="AES Decrypt KeySchedule MixColumns (RV64)"]
==== aes64im

Synopsis::
This instruction accelerates the inverse MixColumns step of the AES
Block Cipher, and is used to aid creation of the decryption KeySchedule.

Mnemonic::
aes64im rd, rs1

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x13},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x1},
{bits: 5, name: 'rs1'},
{bits: 5, name: 0x0},
{bits: 5, name: 0x18},
{bits: 2, name: 0x0},
]}
....

Description:: 
The instruction applies the inverse MixColumns
transformation to two columns of the state array, packed into a single
64-bit register.
It is used to create the inverse cipher KeySchedule, according to
the equivalent inverse cipher construction in
cite:[nist:fips:197] (Page 23, Section 5.3.5).
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

Operation::
[source,sail]
--
function clause execute (AES64IM(rs1, rd)) = {
  let w0 : bits(32) = aes_mixcolumn_inv(X(rs1)[31.. 0]);
  let w1 : bits(32) = aes_mixcolumn_inv(X(rs1)[63..32]);
  X(rd)  = w1 @ w0;
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zknd>> (RV64)
| v1.0.0
| Ratified
| <<zkn>> (RV64)
| v1.0.0
| Ratified
| <<zk>> (RV64)
| v1.0.0
| Ratified
|===

<<<

[#insns-aes64ks1i, reftext="AES Key Schedule Instruction 1 (RV64)"]
==== aes64ks1i

Synopsis::
This instruction implements part of the KeySchedule operation for the
AES Block cipher involving the SBox operation.

Mnemonic::
aes64ks1i rd, rs1, rnum

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x13},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x1},
{bits: 5, name: 'rs1'},
{bits: 4, name: 'rnum'},
{bits: 1, name: 0x1},
{bits: 5, name: 0x18},
{bits: 2, name: 0},
]}
....

Description:: 
This instruction implements the rotation, SubBytes and Round Constant
addition steps of the AES block cipher Key Schedule.
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.
Note that `rnum` must be in the range `0x0..0xA`.
The values `0xB..0xF` are reserved.

Operation::
[source,sail]
--
function clause execute (AES64KS1I(rnum, rs1, rd)) = {
  if(unsigned(rnum) > 10) then {
    handle_illegal();  RETIRE_SUCCESS
  } else {
    let tmp1 : bits(32) = X(rs1)[63..32];
    let rc   : bits(32) = aes_decode_rcon(rnum); /* round number -> round constant */
    let tmp2 : bits(32) = if (rnum ==0xA) then tmp1 else ror32(tmp1, 8);
    let tmp3 : bits(32) = aes_subword_fwd(tmp2);
    let result : bits(64) = (tmp3 ^ rc) @ (tmp3 ^ rc);
    X(rd) = EXTZ(result);
    RETIRE_SUCCESS
  }
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zkne>> (RV64)
| v1.0.0
| Ratified
| <<zknd>> (RV64)
| v1.0.0
| Ratified
| <<zkn>> (RV64)
| v1.0.0
| Ratified
| <<zk>> (RV64)
| v1.0.0
| Ratified
|===

<<<

[#insns-aes64ks2, reftext="AES Key Schedule Instruction 2 (RV64)"]
==== aes64ks2

Synopsis::
This instruction implements part of the KeySchedule operation for the
AES Block cipher.

Mnemonic::
aes64ks2 rd, rs1, rs2

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x33},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x0},
{bits: 5, name: 'rs1'},
{bits: 5, name: 'rs2'},
{bits: 5, name: 0x1f},
{bits: 2, name: 0x1},
]}
....

Description:: 
This instruction implements the additional XOR'ing of key words as
part of the AES block cipher Key Schedule.
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

Operation::
[source,sail]
--
function clause execute (AES64KS2(rs2, rs1, rd)) = {
  let w0 : bits(32) = X(rs1)[63..32] ^ X(rs2)[31..0];
  let w1 : bits(32) = X(rs1)[63..32] ^ X(rs2)[31..0] ^ X(rs2)[63..32];
  X(rd)  = w1 @ w0;
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zkne>> (RV64)
| v1.0.0
| Ratified
| <<zknd>> (RV64)
| v1.0.0
| Ratified
| <<zkn>> (RV64)
| v1.0.0
| Ratified
| <<zk>> (RV64)
| v1.0.0
| Ratified
|===

<<<

[#insns-andn-sc,reftext="AND with inverted operand"]
==== andn

Synopsis::
AND with inverted operand

Mnemonic::
andn _rd_, _rs1_, _rs2_

Encoding::
[wavedrom, , svg]
....
{reg:[
    { bits:  7, name: 0x33, attr: ['OP'] },
    { bits:  5, name: 'rd' },
    { bits:  3, name: 0x7, attr: ['ANDN']},
    { bits:  5, name: 'rs1' },
    { bits:  5, name: 'rs2' },
    { bits:  7, name: 0x20, attr: ['ANDN'] },
]}
....

Description:: 
This instruction performs the bitwise logical AND operation between _rs1_ and the bitwise inversion of _rs2_.

Operation::
[source,sail]
--
X(rd) = X(rs1) & ~X(rs2);
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

|Zbb (<<#zbb>>)
|1.0.0
|Ratified

|Zbkb (<<#zbkb-sc>>)
|v1.0.0-rc4
|Ratified
|===

<<<

[#insns-brev8,reftext="Reverse bits in bytes"]
==== brev8

Synopsis::
Reverse the bits in each byte of a source register.

Mnemonic::
brev8, _rd_, _rs_

Encoding::
[wavedrom, , svg]
....
{reg:[
    { bits:  7, name: 0x13, attr: ['OP-IMM'] },
    { bits:  5, name: 'rd' },
    { bits:  3, name: 0x65 },
    { bits:  5, name: 'rs' },
    { bits:  12, name: 0x687 },
]}
....

Description:: 
This instruction reverses the order of the bits in every byte of a register.

[NOTE]
====
This instruction is a specific encoding of a more generic instruction which was originally
proposed as part of the RISC-V Bitmanip extension (grevi). Eventually, the more generic
instruction may be standardised. Until then, only the most common instances of it, such as
this, are being included in specifications.
====

Operation::
[source,sail]
--
result : xlenbits = EXTZ(0b0);
foreach (i from 0 to sizeof(xlen) by 8) {
result[i+7..i] = reverse_bits_in_byte(X(rs1)[i+7..i]);
};
X(rd) = result;
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

|Zbkb (<<#zbkb-sc>>)
|v1.0.0-rc4
|Ratified
|===

<<<

[#insns-clmul-sc,reftext="Carry-less multiply (low-part)"]
==== clmul

Synopsis::
Carry-less multiply (low-part)

Mnemonic::
clmul _rd_, _rs1_, _rs2_

Encoding::
[wavedrom, , svg]
....
{reg:[
    { bits:  7, name: 0x33, attr: ['OP'] },
    { bits:  5, name: 'rd' },
    { bits:  3, name: 0x1, attr: ['CLMUL'] },
    { bits:  5, name: 'rs1' },
    { bits:  5, name: 'rs2' },
    { bits:  7, name: 0x5, attr: ['MINMAX/CLMUL'] },
]}
....

Description::
clmul produces the lower half of the 2·XLEN carry-less product.

Operation::
[source,sail]
--
let rs1_val = X(rs1);
let rs2_val = X(rs2);
let output : xlenbits = 0;

foreach (i from 0 to (xlen - 1) by 1) {
   output = if   ((rs2_val >> i) & 1)
            then output ^ (rs1_val << i);
            else output;
}

X[rd] = output
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

|Zbc (<<#zbc>>)
|1.0.0
|Ratified

|Zbkc (<<#zbkc-sc>>)
|v1.0.0-rc4
|Ratified
|===

<<<

[#insns-clmulh-sc,reftext="Carry-less multiply (high-part)"]
==== clmulh

Synopsis::
Carry-less multiply (high-part)

Mnemonic::
clmulh _rd_, _rs1_, _rs2_

Encoding::
[wavedrom, , svg]
....
{reg:[
    { bits:  7, name: 0x33, attr: ['OP'] },
    { bits:  5, name: 'rd' },
    { bits:  3, name: 0x3, attr: ['CLMULH'] },
    { bits:  5, name: 'rs1' },
    { bits:  5, name: 'rs2' },
    { bits:  7, name: 0x5, attr: ['MINMAX/CLMUL'] },
]}
....

Description::
clmulh produces the upper half of the 2·XLEN carry-less product.

Operation::
[source,sail]
--
let rs1_val = X(rs1);
let rs2_val = X(rs2);
let output : xlenbits = 0;

foreach (i from 1 to xlen by 1) {
   output = if   ((rs2_val >> i) & 1)
            then output ^ (rs1_val >> (xlen - i));
            else output;
}

X[rd] = output
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

|Zbc (<<#zbc>>)
|1.0.0
|Ratified

|Zbkc (<<#zbkc-sc>>)
|v1.0.0-rc4
|Ratified
|===

<<<

[#insns-orn-sc,reftext="OR with inverted operand"]
==== orn

Synopsis::
OR with inverted operand

Mnemonic::
orn _rd_, _rs1_, _rs2_

Encoding::
[wavedrom, , svg]
....
{reg:[
    { bits:  7, name: 0x33, attr: ['OP'] },
    { bits:  5, name: 'rd' },
    { bits:  3, name: 0x6, attr: ['ORN']},
    { bits:  5, name: 'rs1' },
    { bits:  5, name: 'rs2' },
    { bits:  7, name: 0x20, attr: ['ORN'] },
]}
....

Description:: 
This instruction performs the bitwise logical OR operation between _rs1_ and the bitwise inversion of _rs2_.

Operation::
[source,sail]
--
X(rd) = X(rs1) | ~X(rs2);
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

|Zbb (<<#zbb>>)
|v1.0.0
|Ratified

|Zbkb (<<#zbkb-sc>>)
|v1.0.0-rc4
|Ratified
|===

<<<

[#insns-pack-sc,reftext="Pack low halves of registers"]
==== pack

Synopsis::
Pack the low halves of _rs1_ and _rs2_ into _rd_.

Mnemonic::
pack _rd_, _rs1_, _rs2_

Encoding::
[wavedrom, , svg]
....
{reg:[
    {bits:  7, name: 0x33, attr: ['OP'] },
    {bits: 5, name: 'rd'},
    {bits: 3, name: 0x4, attr:['PACK']},
    {bits: 5, name: 'rs1'},
    {bits: 5, name: 'rs2'},
    {bits: 7, name: 0x4, attr:['PACK']},
]}
....

Description:: 
The pack instruction packs the XLEN/2-bit lower halves of _rs1_ and _rs2_ into
_rd_, with _rs1_ in the lower half and _rs2_ in the upper half.

Operation::
[source,sail]
--
let lo_half : bits(xlen/2) = X(rs1)[xlen/2-1..0];
let hi_half : bits(xlen/2) = X(rs2)[xlen/2-1..0];
X(rd) = EXTZ(hi_half @ lo_half);
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

|Zbkb (<<#zbkb-sc>>)
|v1.0.0-rc4
|Ratified
|===

<<<

[#insns-packh-sc,reftext="Pack low bytes of registers"]
==== packh

Synopsis::
Pack the low bytes of _rs1_ and _rs2_ into _rd_.

Mnemonic::
packh _rd_, _rs1_, _rs2_

Encoding::
[wavedrom, , svg]
....
{reg:[
    {bits:  7, name: 0x33, attr: ['OP'] },
    {bits: 5, name: 'rd'},
    {bits: 3, name: 0x7, attr: ['PACKH']},
    {bits: 5, name: 'rs1'},
    {bits: 5, name: 'rs2'},
    {bits: 7, name: 0x4, attr: ['PACKH']},
]}
....

Description:: 
And the packh instruction packs the least-significant bytes of
_rs1_ and _rs2_ into the 16 least-significant bits of _rd_,
zero extending the rest of _rd_.

Operation::
[source,sail]
--
let lo_half : bits(8) = X(rs1)[7..0];
let hi_half : bits(8) = X(rs2)[7..0];
X(rd) = EXTZ(hi_half @ lo_half);
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

|Zbkb (<<#zbkb-sc>>)
|v1.0.0-rc4
|Ratified
|===

<<<

[#insns-packw-sc,reftext="Pack low 16-bits of registers (RV64)"]
==== packw

Synopsis::
Pack the low 16-bits of _rs1_ and _rs2_ into _rd_ on RV64.

Mnemonic::
packw _rd_, _rs1_, _rs2_

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 2, name: 0x3},
{bits: 5, name: 0xe},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x4},
{bits: 5, name: 'rs1'},
{bits: 5, name: 'rs2'},
{bits: 7, name: 0x4},
]}
....

Description:: 
This instruction packs the low 16 bits of
_rs1_ and _rs2_ into the 32 least-significant bits of _rd_,
sign extending the 32-bit result to the rest of _rd_.
This instruction only exists on RV64 based systems.

Operation::
[source,sail]
--
let lo_half : bits(16) = X(rs1)[15..0];
let hi_half : bits(16) = X(rs2)[15..0];
X(rd) = EXTS(hi_half @ lo_half);
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

|Zbkb (<<#zbkb-sc>>)
|v1.0.0-rc4
|Ratified
|===

<<<

[#insns-rev8-sc,reftext="Byte-reverse register"]
==== rev8

Synopsis::
Byte-reverse register

Mnemonic::
rev8 _rd_, _rs_

Encoding (RV32)::
[wavedrom, , svg]
....
{reg:[
    { bits:  7, name: 0x13, attr: ['OP-IMM'] },
    { bits:  5, name: 'rd' },
    { bits:  3, name: 0x5 },
    { bits:  5, name: 'rs' },
    { bits: 12, name: 0x698 }
]}
....

Encoding (RV64)::
[wavedrom, , svg]
....
{reg:[
    { bits:  7, name: 0x13, attr: ['OP-IMM'] },
    { bits:  5, name: 'rd' },
    { bits:  3, name: 0x5 },
    { bits:  5, name: 'rs' },
    { bits: 12, name: 0x6b8 }
]}
....

Description:: 
This instruction reverses the order of the bytes in _rs_.

Operation::
[source,sail]
--
let input = X(rs);
let output : xlenbits = 0;
let j = xlen - 1;

foreach (i from 0 to (xlen - 8) by 8) {
   output[i..(i + 7)] = input[(j - 7)..j];
   j = j - 8;
}

X[rd] = output
--

.Note
[NOTE, caption="A" ]
===============================================================
The *rev8* mnemonic corresponds to different instruction encodings in RV32 and RV64.
===============================================================

.Software Hint
[NOTE, caption="SH" ]
===============================================================
The byte-reverse operation is only available for the full register
width.  To emulate word-sized and halfword-sized byte-reversal,
perform a `rev8 rd,rs` followed by a `srai rd,rd,K`, where K is
XLEN-32 and XLEN-16, respectively.
===============================================================

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

|Zbb (<<#zbb>>)
|v1.0.0
|Ratified

|Zbkb (<<#zbkb-sc>>)
|v1.0.0-rc4
|Ratified
|===

<<<

[#insns-rol-sc,reftext="Rotate left (Register)"]
==== rol

Synopsis::
Rotate Left (Register)

Mnemonic::
rol _rd_, _rs1_, _rs2_

Encoding::
[wavedrom, , svg]
....
{reg:[
    { bits:  7, name: 0x33, attr: ['OP'] },
    { bits:  5, name: 'rd' },
    { bits:  3, name: 0x1, attr: ['ROL']},
    { bits:  5, name: 'rs1' },
    { bits:  5, name: 'rs2' },
    { bits:  7, name: 0x30, attr: ['ROL'] },
]}
....

Description::
This instruction performs a rotate left of _rs1_ by the amount in least-significant log2(XLEN) bits of _rs2_.

Operation::
[source,sail]
--
let shamt = if   xlen == 32
            then X(rs2)[4..0]
            else X(rs2)[5..0];
let result = (X(rs1) << shamt) | (X(rs1) >> (xlen - shamt));

X(rd) = result;
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

|Zbb (<<#zbb>>)
|v1.0.0
|Ratified

|Zbkb (<<#zbkb-sc>>)
|v1.0.0-rc4
|Ratified
|===

<<<

[#insns-rolw-sc,reftext="Rotate Left Word (Register)"]
==== rolw

Synopsis::
Rotate Left Word (Register)

Mnemonic::
rolw _rd_, _rs1_, _rs2_

Encoding::
[wavedrom, , svg]
....
{reg:[
    { bits:  7, name: 0x3b, attr: ['OP-32'] },
    { bits:  5, name: 'rd' },
    { bits:  3, name: 0x1, attr: ['ROLW']},
    { bits:  5, name: 'rs1' },
    { bits:  5, name: 'rs2' },
    { bits:  7, name: 0x30, attr: ['ROLW'] },
]}
....

Description::
This instruction performs a rotate left on the least-significant word of  _rs1_ by the amount in least-significant 5 bits of _rs2_.
The resulting word value is sign-extended by copying bit 31 to all of the more-significant bits. 

Operation::
[source,sail]
--
let rs1 = EXTZ(X(rs1)[31..0])
let shamt = X(rs2)[4..0];
let result = (rs1 << shamt) | (rs1 >> (32 - shamt));
X(rd) = EXTS(result[31..0]);
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

|Zbb (<<#zbb>>)
|v1.0.0
|Ratified

|Zbkb (<<#zbkb-sc>>)
|v1.0.0-rc4
|Ratified
|===

<<<

[#insns-ror-sc, reftext="Rotate right (Register)"]
==== ror

Synopsis::
Rotate Right

Mnemonic::
ror _rd_, _rs1_, _rs2_

Encoding::
[wavedrom, , svg]
....
{reg:[
    { bits:  7, name: 0x33, attr: ['OP'] },
    { bits:  5, name: 'rd' },
    { bits:  3, name: 0x5, attr: ['ROR']},
    { bits:  5, name: 'rs1' },
    { bits:  5, name: 'rs2' },
    { bits:  7, name: 0x30, attr: ['ROR'] },
]}
....

Description::
This instruction performs a rotate right of _rs1_ by the amount in least-significant log2(XLEN) bits of _rs2_.

Operation::
[source,sail]
--
let shamt = if   xlen == 32
            then X(rs2)[4..0]
            else X(rs2)[5..0];
let result = (X(rs1) >> shamt) | (X(rs1) << (xlen - shamt));

X(rd) = result;
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

|Zbb (<<#zbb>>)
|v1.0.0
|Ratified

|Zbkb (<<#zbkb-sc>>)
|v1.0.0-rc4
|Ratified
|===

<<<

[#insns-rori-sc,reftext="Rotate right (Immediate)"]
==== rori

Synopsis::
Rotate Right (Immediate)

Mnemonic::
rori _rd_, _rs1_, _shamt_

Encoding (RV32)::
[wavedrom, , svg]
....
{reg:[
    { bits:  7, name: 0x13, attr: ['OP-IMM'] },
    { bits:  5, name: 'rd' },
    { bits:  3, name: 0x5, attr: ['RORI']},
    { bits:  5, name: 'rs1' },
    { bits:  5, name: 'shamt' },
    { bits:  7, name: 0x30, attr: ['RORI'] },
]}
....

Encoding (RV64)::
[wavedrom, , svg]
....
{reg:[
    { bits:  7, name: 0x13, attr: ['OP-IMM'] },
    { bits:  5, name: 'rd' },
    { bits:  3, name: 0x5, attr: ['RORI']},
    { bits:  5, name: 'rs1' },
    { bits:  6, name: 'shamt' },
    { bits:  6, name: 0x18, attr: ['RORI'] },
]}
....

Description:: 
This instruction performs a rotate right of _rs1_ by the amount in the least-significant log2(XLEN) bits of _shamt_.
For RV32, the encodings corresponding to shamt[5]=1 are reserved.

Operation::
[source,sail]
--
let shamt = if   xlen == 32
            then shamt[4..0]
            else shamt[5..0];
let result = (X(rs1) >> shamt) | (X(rs1) << (xlen - shamt));

X(rd) = result;
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

|Zbb (<<#zbb>>)
|v1.0.0
|Ratified

|Zbkb (<<#zbkb-sc>>)
|v1.0.0-rc4
|Ratified
|===

<<<

[#insns-roriw-sc,reftext="Rotate right Word (Immediate)"]
==== roriw

Synopsis::
Rotate Right Word by Immediate

Mnemonic::
roriw _rd_, _rs1_, _shamt_

Encoding::
[wavedrom, , svg]
....
{reg:[
    { bits:  7, name: 0x1b, attr: ['OP-IMM-32'] },
    { bits:  5, name: 'rd' },
    { bits:  3, name: 0x5, attr: ['RORIW']},
    { bits:  5, name: 'rs1' },
    { bits:  5, name: 'shamt' },
    { bits:  7, name: 0x30, attr: ['RORIW'] },
]}
....

Description:: 
This instruction performs a rotate right on the least-significant word
of _rs1_ by the amount in the least-significant log2(XLEN) bits of
_shamt_.
The resulting word value is sign-extended by copying bit 31 to all of
the more-significant bits.


Operation::
[source,sail]
--
let rs1_data = EXTZ(X(rs1)[31..0];
let result = (rs1_data >> shamt) | (rs1_data << (32 - shamt));
X(rd) = EXTS(result[31..0]);
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

|Zbb (<<#zbb>>)
|v1.0.0
|Ratified

|Zbkb (<<#zbkb-sc>>)
|v1.0.0-rc4
|Ratified
|===

<<<

[#insns-rorw-sc,reftext="Rotate right Word (Register)"]
==== rorw

Synopsis::
Rotate Right Word (Register)

Mnemonic::
rorw _rd_, _rs1_, _rs2_

Encoding::
[wavedrom, , svg]
....
{reg:[
    { bits:  7, name: 0x3b, attr: ['OP-32'] },
    { bits:  5, name: 'rd' },
    { bits:  3, name: 0x5, attr: ['RORW']},
    { bits:  5, name: 'rs1' },
    { bits:  5, name: 'rs2' },
    { bits:  7, name: 0x30, attr: ['RORW'] },
]}
....

Description:: 
This instruction performs a rotate right on the least-significant word of  _rs1_ by the amount in least-significant 5 bits of _rs2_.
The resultant word is sign-extended by copying bit 31 to all of the more-significant bits.

Operation::
[source,sail]
--
let rs1 = EXTZ(X(rs1)[31..0])
let shamt = X(rs2)[4..0];
let result = (rs1 >> shamt) | (rs1 << (32 - shamt));
X(rd) = EXTS(result);
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

|Zbb (<<#zbb>>)
|v1.0.0
|Ratified

|Zbkb (<<#zbkb-sc>>)
|v1.0.0-rc4
|Ratified
|===

<<<

[#insns-sha256sig0, reftext="SHA2-256 Sigma0 instruction"]
==== sha256sig0

Synopsis::
Implements the Sigma0 transformation function as used in
the SHA2-256 hash function cite:[nist:fips:180:4] (Section 4.1.2).

Mnemonic::
sha256sig0 rd, rs1

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x13},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x1},
{bits: 5, name: 'rs1'},
{bits: 5, name: 0x2},
{bits: 5, name: 0x8},
{bits: 2, name: 0x0},
]}
....

Description:: 
This instruction is supported for both RV32 and RV64 base architectures.
For RV32, the entire `XLEN` source register is operated on.
For RV64, the low `32` bits of the source register are operated on, and the
result sign extended to `XLEN` bits.
Though named for SHA2-256, the instruction works for both the
SHA2-224 and SHA2-256 parameterisations as described in
cite:[nist:fips:180:4].
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

Operation::
[source,sail]
--
function clause execute (SHA256SIG0(rs1,rd)) = {
  let inb    : bits(32) = X(rs1)[31..0];
  let result : bits(32) = ror32(inb,  7) ^ ror32(inb, 18) ^ (inb >>  3);
  X(rd)      = EXTS(result);
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zknh>>
| v1.0.0
| Ratified
| <<zkn>>
| v1.0.0
| Ratified
| <<zk>>
| v1.0.0
| Ratified
|===

<<<

[#insns-sha256sig1, reftext="SHA2-256 Sigma1 instruction"]
==== sha256sig1

Synopsis::
Implements the Sigma1 transformation function as used in
the SHA2-256 hash function cite:[nist:fips:180:4] (Section 4.1.2).

Mnemonic::
sha256sig1 rd, rs1

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x13},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x1},
{bits: 5, name: 'rs1'},
{bits: 5, name: 0x3},
{bits: 5, name: 0x8},
{bits: 2, name: 0x0},
]}
....

Description:: 
This instruction is supported for both RV32 and RV64 base architectures.
For RV32, the entire `XLEN` source register is operated on.
For RV64, the low `32` bits of the source register are operated on, and the
result sign extended to `XLEN` bits.
Though named for SHA2-256, the instruction works for both the
SHA2-224 and SHA2-256 parameterisations as described in
cite:[nist:fips:180:4].
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

Operation::
[source,sail]
--
function clause execute (SHA256SIG1(rs1,rd)) = {
  let inb    : bits(32) = X(rs1)[31..0];
  let result : bits(32) = ror32(inb, 17) ^ ror32(inb, 19) ^ (inb >> 10);
  X(rd)      = EXTS(result);
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zknh>>
| v1.0.0
| Ratified
| <<zkn>>
| v1.0.0
| Ratified
| <<zk>>
| v1.0.0
| Ratified
|===

<<<

[#insns-sha256sum0, reftext="SHA2-256 Sum0 instruction"]
==== sha256sum0

Synopsis::
Implements the Sum0 transformation function as used in
the SHA2-256 hash function cite:[nist:fips:180:4] (Section 4.1.2).

Mnemonic::
sha256sum0 rd, rs1

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x13},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x1},
{bits: 5, name: 'rs1'},
{bits: 5, name: 0x0},
{bits: 5, name: 0x8},
{bits: 2, name: 0x0},
]}
....

Description:: 
This instruction is supported for both RV32 and RV64 base architectures.
For RV32, the entire `XLEN` source register is operated on.
For RV64, the low `32` bits of the source register are operated on, and the
result sign extended to `XLEN` bits.
Though named for SHA2-256, the instruction works for both the
SHA2-224 and SHA2-256 parameterisations as described in
cite:[nist:fips:180:4].
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

Operation::
[source,sail]
--
function clause execute (SHA256SUM0(rs1,rd)) = {
  let inb    : bits(32) = X(rs1)[31..0];
  let result : bits(32) = ror32(inb,  2) ^ ror32(inb, 13) ^ ror32(inb, 22);
  X(rd)      = EXTS(result);
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zknh>>
| v1.0.0
| Ratified
| <<zkn>>
| v1.0.0
| Ratified
| <<zk>>
| v1.0.0
| Ratified
|===

<<<

[#insns-sha256sum1, reftext="SHA2-256 Sum1 instruction"]
==== sha256sum1

Synopsis::
Implements the Sum1 transformation function as used in
the SHA2-256 hash function cite:[nist:fips:180:4] (Section 4.1.2).

Mnemonic::
sha256sum1 rd, rs1

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x13},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x1},
{bits: 5, name: 'rs1'},
{bits: 5, name: 0x1},
{bits: 5, name: 0x8},
{bits: 2, name: 0x0},
]}
....

Description:: 
This instruction is supported for both RV32 and RV64 base architectures.
For RV32, the entire `XLEN` source register is operated on.
For RV64, the low `32` bits of the source register are operated on, and the
result sign extended to `XLEN` bits.
Though named for SHA2-256, the instruction works for both the
SHA2-224 and SHA2-256 parameterisations as described in
cite:[nist:fips:180:4].
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

Operation::
[source,sail]
--
function clause execute (SHA256SUM1(rs1,rd)) = {
  let inb    : bits(32) = X(rs1)[31..0];
  let result : bits(32) = ror32(inb,  6) ^ ror32(inb, 11) ^ ror32(inb, 25);
  X(rd)      = EXTS(result);
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zknh>>
| v1.0.0
| Ratified
| <<zkn>>
| v1.0.0
| Ratified
| <<zk>>
| v1.0.0
| Ratified
|===

<<<

[#insns-sha512sig0h, reftext="SHA2-512 Sigma0 high (RV32)"]
==== sha512sig0h

Synopsis::
Implements the _high half_ of the Sigma0 transformation, as
used in the SHA2-512 hash function cite:[nist:fips:180:4] (Section 4.1.3).

Mnemonic::
sha512sig0h rd, rs1, rs2

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x33},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x0},
{bits: 5, name: 'rs1'},
{bits: 5, name: 'rs2'},
{bits: 5, name: 0xe},
{bits: 2, name: 0x1},
]}
....

Description:: 
This instruction is implemented on RV32 only.
Used to compute the Sigma0 transform of the SHA2-512 hash function
in conjunction with the <<insns-sha512sig0l,`sha512sig0l`>> instruction.
The transform is a 64-bit to 64-bit function, so the input and output
are each represented by two 32-bit registers.
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

[TIP]
.Note to software developers
====
The entire Sigma0 transform for SHA2-512 may be computed on RV32
using the following instruction sequence:

 sha512sig0l    t0, a0, a1 
 sha512sig0h    t1, a1, a0 

====

Operation::
[source,sail]
--
function clause execute (SHA512SIG0H(rs2, rs1, rd)) = {
  X(rd) = EXTS((X(rs1) >>  1) ^ (X(rs1) >>  7) ^ (X(rs1) >>  8) ^
               (X(rs2) << 31)                  ^ (X(rs2) << 24) );
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zknh>> (RV32)
| v1.0.0
| Ratified
| <<zkn>> (RV32)
| v1.0.0
| Ratified
| <<zk>> (RV32)
| v1.0.0
| Ratified
|===

<<<

[#insns-sha512sig0l, reftext="SHA2-512 Sigma0 low (RV32)"]
==== sha512sig0l

Synopsis::
Implements the _low half_ of the Sigma0 transformation, as
used in the SHA2-512 hash function cite:[nist:fips:180:4] (Section 4.1.3).

Mnemonic::
sha512sig0l rd, rs1, rs2

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x33},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x0},
{bits: 5, name: 'rs1'},
{bits: 5, name: 'rs2'},
{bits: 5, name: 0xa},
{bits: 2, name: 0x1},
]}
....

Description:: 
This instruction is implemented on RV32 only.
Used to compute the Sigma0 transform of the SHA2-512 hash function
in conjunction with the <<insns-sha512sig0h,`sha512sig0h`>> instruction.
The transform is a 64-bit to 64-bit function, so the input and output
are each represented by two 32-bit registers.
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

[TIP]
.Note to software developers
====
The entire Sigma0 transform for SHA2-512 may be computed on RV32
using the following instruction sequence:

 sha512sig0l    t0, a0, a1 
 sha512sig0h    t1, a1, a0 

====

Operation::
[source,sail]
--
function clause execute (SHA512SIG0L(rs2, rs1, rd)) = {
  X(rd) = EXTS((X(rs1) >>  1) ^ (X(rs1) >>  7) ^ (X(rs1) >>  8) ^
               (X(rs2) << 31) ^ (X(rs2) << 25) ^ (X(rs2) << 24) );
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zknh>> (RV32)
| v1.0.0
| Ratified
| <<zkn>> (RV32)
| v1.0.0
| Ratified
| <<zk>> (RV32)
| v1.0.0
| Ratified
|===

<<<

[#insns-sha512sig1h, reftext="SHA2-512 Sigma1 high (RV32)"]
==== sha512sig1h

Synopsis::
Implements the _high half_ of the Sigma1 transformation, as
used in the SHA2-512 hash function cite:[nist:fips:180:4] (Section 4.1.3).

Mnemonic::
sha512sig1h rd, rs1, rs2

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x33},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x0},
{bits: 5, name: 'rs1'},
{bits: 5, name: 'rs2'},
{bits: 5, name: 0xf},
{bits: 2, name: 0x1},
]}
....

Description:: 
This instruction is implemented on RV32 only.
Used to compute the Sigma1 transform of the SHA2-512 hash function
in conjunction with the <<insns-sha512sig1l,`sha512sig1l`>> instruction.
The transform is a 64-bit to 64-bit function, so the input and output
are each represented by two 32-bit registers.
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

[TIP]
.Note to software developers
====
The entire Sigma1 transform for SHA2-512 may be computed on RV32
using the following instruction sequence:

 sha512sig1l    t0, a0, a1 
 sha512sig1h    t1, a1, a0

====

Operation::
[source,sail]
--
function clause execute (SHA512SIG1H(rs2, rs1, rd)) = {
  X(rd) = EXTS((X(rs1) <<  3) ^ (X(rs1) >>  6) ^ (X(rs1) >> 19) ^
               (X(rs2) >> 29)                  ^ (X(rs2) << 13) );
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zknh>> (RV32)
| v1.0.0
| Ratified
| <<zkn>> (RV32)
| v1.0.0
| Ratified
| <<zk>> (RV32)
| v1.0.0
| Ratified
|===

<<<

[#insns-sha512sig1l, reftext="SHA2-512 Sigma1 low (RV32)"]
==== sha512sig1l

Synopsis::
Implements the _low half_ of the Sigma1 transformation, as
used in the SHA2-512 hash function cite:[nist:fips:180:4] (Section 4.1.3).

Mnemonic::
sha512sig1l rd, rs1, rs2

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x33},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x0},
{bits: 5, name: 'rs1'},
{bits: 5, name: 'rs2'},
{bits: 5, name: 0xb},
{bits: 2, name: 0x1},
]}
....

Description:: 
This instruction is implemented on RV32 only.
Used to compute the Sigma1 transform of the SHA2-512 hash function
in conjunction with the <<insns-sha512sig1h,`sha512sig1h`>> instruction.
The transform is a 64-bit to 64-bit function, so the input and output
are each represented by two 32-bit registers.
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

[TIP]
.Note to software developers
====
The entire Sigma1 transform for SHA2-512 may be computed on RV32
using the following instruction sequence:

 sha512sig1l    t0, a0, a1 
 sha512sig1h    t1, a1, a0

====

Operation::
[source,sail]
--
function clause execute (SHA512SIG1L(rs2, rs1, rd)) = {
  X(rd) = EXTS((X(rs1) <<  3) ^ (X(rs1) >>  6) ^ (X(rs1) >> 19) ^
               (X(rs2) >> 29) ^ (X(rs2) << 26) ^ (X(rs2) << 13) );
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zknh>> (RV32)
| v1.0.0
| Ratified
| <<zkn>> (RV32)
| v1.0.0
| Ratified
| <<zk>> (RV32)
| v1.0.0
| Ratified
|===

<<<

[#insns-sha512sum0r, reftext="SHA2-512 Sum0 (RV32)"]
==== sha512sum0r

Synopsis::
Implements the Sum0 transformation, as
used in the SHA2-512 hash function cite:[nist:fips:180:4] (Section 4.1.3).

Mnemonic::
sha512sum0r rd, rs1, rs2

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x33},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x0},
{bits: 5, name: 'rs1'},
{bits: 5, name: 'rs2'},
{bits: 5, name: 0x8},
{bits: 2, name: 0x1},
]}
....

Description:: 
This instruction is implemented on RV32 only.
Used to compute the Sum0 transform of the SHA2-512 hash function.
The transform is a 64-bit to 64-bit function, so the input and output
is represented by two 32-bit registers.
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

[TIP]
.Note to software developers
====
The entire Sum0 transform for SHA2-512 may be computed on RV32
using the following instruction sequence:

 sha512sum0r    t0, a0, a1 
 sha512sum0r    t1, a1, a0 

Note the reversed source register ordering.
====

Operation::
[source,sail]
--
function clause execute (SHA512SUM0R(rs2, rs1, rd)) = {
  X(rd) = EXTS((X(rs1) << 25) ^ (X(rs1) << 30) ^ (X(rs1) >> 28) ^
               (X(rs2) >>  7) ^ (X(rs2) >>  2) ^ (X(rs2) <<  4) );
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zknh>> (RV32)
| v1.0.0
| Ratified
| <<zkn>> (RV32)
| v1.0.0
| Ratified
| <<zk>> (RV32)
| v1.0.0
| Ratified
|===

<<<

[#insns-sha512sum1r, reftext="SHA2-512 Sum1 (RV32)"]
==== sha512sum1r

Synopsis::
Implements the Sum1 transformation, as
used in the SHA2-512 hash function cite:[nist:fips:180:4] (Section 4.1.3).

Mnemonic::
sha512sum1r rd, rs1, rs2

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x33},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x0},
{bits: 5, name: 'rs1'},
{bits: 5, name: 'rs2'},
{bits: 5, name: 0x9},
{bits: 2, name: 0x1},
]}
....

Description:: 
This instruction is implemented on RV32 only.
Used to compute the Sum1 transform of the SHA2-512 hash function.
The transform is a 64-bit to 64-bit function, so the input and output
is represented by two 32-bit registers.
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

[TIP]
.Note to software developers
====
The entire Sum1 transform for SHA2-512 may be computed on RV32
using the following instruction sequence:

 sha512sum1r    t0, a0, a1 
 sha512sum1r    t1, a1, a0 

Note the reversed source register ordering.
====

Operation::
[source,sail]
--
function clause execute (SHA512SUM1R(rs2, rs1, rd)) = {
  X(rd) = EXTS((X(rs1) << 23) ^ (X(rs1) >> 14) ^ (X(rs1) >> 18) ^
               (X(rs2) >>  9) ^ (X(rs2) << 18) ^ (X(rs2) << 14) );
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zknh>> (RV32)
| v1.0.0
| Ratified
| <<zkn>> (RV32)
| v1.0.0
| Ratified
| <<zk>> (RV32)
| v1.0.0
| Ratified
|===

<<<

[#insns-sha512sig0, reftext="SHA2-512 Sigma0 instruction (RV64)"]
==== sha512sig0

Synopsis::
Implements the Sigma0 transformation function as used in
the SHA2-512 hash function cite:[nist:fips:180:4] (Section 4.1.3).

Mnemonic::
sha512sig0 rd, rs1

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x13},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x1},
{bits: 5, name: 'rs1'},
{bits: 5, name: 0x6},
{bits: 5, name: 0x8},
{bits: 2, name: 0x0},
]}
....

Description:: 
This instruction is supported for the RV64 base architecture.
It implements the Sigma0 transform of the SHA2-512 hash function.
cite:[nist:fips:180:4].
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

Operation::
[source,sail]
--
function clause execute (SHA512SIG0(rs1, rd)) = {
  X(rd) = ror64(X(rs1),  1) ^ ror64(X(rs1),  8) ^ (X(rs1) >> 7);
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zknh>> (RV64)
| v1.0.0
| Ratified
| <<zkn>> (RV64)
| v1.0.0
| Ratified
| <<zk>> (RV64)
| v1.0.0
| Ratified
|===

<<<

[#insns-sha512sig1, reftext="SHA2-512 Sigma1 instruction (RV64)"]
==== sha512sig1

Synopsis::
Implements the Sigma1 transformation function as used in
the SHA2-512 hash function cite:[nist:fips:180:4] (Section 4.1.3).

Mnemonic::
sha512sig1 rd, rs1

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x13},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x1},
{bits: 5, name: 'rs1'},
{bits: 5, name: 0x7},
{bits: 5, name: 0x8},
{bits: 2, name: 0x0},
]}
....

Description:: 
This instruction is supported for the RV64 base architecture.
It implements the Sigma1 transform of the SHA2-512 hash function.
cite:[nist:fips:180:4].
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

Operation::
[source,sail]
--
function clause execute (SHA512SIG1(rs1, rd)) = {
  X(rd) = ror64(X(rs1), 19) ^ ror64(X(rs1), 61) ^ (X(rs1) >> 6);
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zknh>> (RV64)
| v1.0.0
| Ratified
| <<zkn>> (RV64)
| v1.0.0
| Ratified
| <<zk>> (RV64)
| v1.0.0
| Ratified
|===

<<<

[#insns-sha512sum0, reftext="SHA2-512 Sum0 instruction (RV64)"]
==== sha512sum0

Synopsis::
Implements the Sum0 transformation function as used in
the SHA2-512 hash function cite:[nist:fips:180:4] (Section 4.1.3).

Mnemonic::
sha512sum0 rd, rs1

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x13},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x1},
{bits: 5, name: 'rs1'},
{bits: 5, name: 0x4},
{bits: 5, name: 0x8},
{bits: 2, name: 0x0},
]}
....

Description:: 
This instruction is supported for the RV64 base architecture.
It implements the Sum0 transform of the SHA2-512 hash function.
cite:[nist:fips:180:4].
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

Operation::
[source,sail]
--
function clause execute (SHA512SUM0(rs1, rd)) = {
  X(rd) = ror64(X(rs1), 28) ^ ror64(X(rs1), 34) ^ ror64(X(rs1) ,39);
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zknh>> (RV64)
| v1.0.0
| Ratified
| <<zkn>> (RV64)
| v1.0.0
| Ratified
| <<zk>> (RV64)
| v1.0.0
| Ratified
|===

<<<

[#insns-sha512sum1, reftext="SHA2-512 Sum1 instruction (RV64)"]
==== sha512sum1

Synopsis::
Implements the Sum1 transformation function as used in
the SHA2-512 hash function cite:[nist:fips:180:4] (Section 4.1.3).

Mnemonic::
sha512sum1 rd, rs1

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x13},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x1},
{bits: 5, name: 'rs1'},
{bits: 5, name: 0x5},
{bits: 5, name: 0x8},
{bits: 2, name: 0x0},
]}
....

Description:: 
This instruction is supported for the RV64 base architecture.
It implements the Sum1 transform of the SHA2-512 hash function.
cite:[nist:fips:180:4].
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

Operation::
[source,sail]
--
function clause execute (SHA512SUM1(rs1, rd)) = {
  X(rd) = ror64(X(rs1), 14) ^ ror64(X(rs1), 18) ^ ror64(X(rs1) ,41);
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zknh>> (RV64)
| v1.0.0
| Ratified
| <<zkn>> (RV64)
| v1.0.0
| Ratified
| <<zk>> (RV64)
| v1.0.0
| Ratified
|===

<<<

[#insns-sm3p0, reftext="SM3 P0 transform"]
==== sm3p0

Synopsis::
Implements the _P0_ transformation function as used in
the SM3 hash function cite:[gbt:sm3,iso:sm3].

Mnemonic::
sm3p0 rd, rs1

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x13},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x1},
{bits: 5, name: 'rs1'},
{bits: 5, name: 0x8},
{bits: 5, name: 0x8},
{bits: 2, name: 0x0},
]}
....

Description:: 
This instruction is supported for the RV32 and RV64 base architectures.
It implements the _P0_ transform of the SM3 hash function cite:[gbt:sm3,iso:sm3].
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

.Supporting Material
[NOTE]
====
This instruction is based on work done in cite:[MJS:LWSHA:20].
====

Operation::
[source,sail]
--
function clause execute (SM3P0(rs1, rd)) = {
  let r1     : bits(32) = X(rs1)[31..0];
  let result : bits(32) =  r1 ^ rol32(r1,  9) ^ rol32(r1, 17);
  X(rd) = EXTS(result);
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zksh>>
| v1.0.0
| Ratified
| <<zks>>
| v1.0.0
| Ratified
|===

<<<

[#insns-sm3p1, reftext="SM3 P1 transform"]
==== sm3p1

Synopsis::
Implements the _P1_ transformation function as used in
the SM3 hash function cite:[gbt:sm3,iso:sm3].

Mnemonic::
sm3p1 rd, rs1

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x13},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x1},
{bits: 5, name: 'rs1'},
{bits: 5, name: 0x9},
{bits: 5, name: 0x8},
{bits: 2, name: 0x0},
]}
....

Description:: 
This instruction is supported for the RV32 and RV64 base architectures.
It implements the _P1_ transform of the SM3 hash function cite:[gbt:sm3,iso:sm3].
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

.Supporting Material
[NOTE]
====
This instruction is based on work done in cite:[MJS:LWSHA:20].
====

Operation::
[source,sail]
--
function clause execute (SM3P1(rs1, rd)) = {
  let r1     : bits(32) = X(rs1)[31..0];
  let result : bits(32) =  r1 ^ rol32(r1, 15) ^ rol32(r1, 23);
  X(rd) = EXTS(result);
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zksh>>
| v1.0.0
| Ratified
| <<zks>>
| v1.0.0
| Ratified
|===

<<<

[#insns-sm4ed, reftext="SM4 Encrypt/Decrypt Instruction"]
==== sm4ed

Synopsis::
Accelerates the block encrypt/decrypt operation of the SM4 block cipher
cite:[gbt:sm4, iso:sm4].

Mnemonic::
sm4ed rd, rs1, rs2, bs

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x33},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x0},
{bits: 5, name: 'rs1'},
{bits: 5, name: 'rs2'},
{bits: 5, name: 0x18},
{bits: 2, name: 'bs'},
]}
....

Description:: 
Implements a T-tables in hardware style approach to accelerating the
SM4 round function.
A byte is extracted from `rs2` based on `bs`, to which the SBox and
linear layer transforms are applied, before the result is XOR'd with
`rs1` and written back to `rd`.
This instruction exists on RV32 and RV64 base architectures.
On RV64, the 32-bit result is sign extended to XLEN bits.
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

Operation::
[source,sail]
--
function clause execute (SM4ED (bs,rs2,rs1,rd)) = {
  let shamt : bits(5)  = bs @ 0b000; /* shamt = bs*8 */
  let sb_in : bits(8)  = (X(rs2)[31..0] >> shamt)[7..0];
  let x     : bits(32) = 0x000000 @ sm4_sbox(sb_in);
  let y     : bits(32) = x ^ (x               <<  8) ^ ( x               <<  2) ^
                             (x               << 18) ^ ((x & 0x0000003F) << 26) ^
                             ((x & 0x000000C0) << 10);
  let z     : bits(32) = rol32(y, unsigned(shamt));
  let result: bits(32) = z ^ X(rs1)[31..0];
  X(rd)                = EXTS(result);
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zksed>>
| v1.0.0
| Ratified
| <<zks>>
| v1.0.0
| Ratified
|===

<<<

[#insns-sm4ks, reftext="SM4 Key Schedule Instruction"]
==== sm4ks

Synopsis::
Accelerates the Key Schedule operation of the SM4 block cipher
cite:[gbt:sm4, iso:sm4].

Mnemonic::
sm4ks rd, rs1, rs2, bs

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x33},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x0},
{bits: 5, name: 'rs1'},
{bits: 5, name: 'rs2'},
{bits: 5, name: 0x1a},
{bits: 2, name: 'bs'},
]}
....

Description:: 
Implements a T-tables in hardware style approach to accelerating the
SM4 Key Schedule.
A byte is extracted from `rs2` based on `bs`, to which the SBox and
linear layer transforms are applied, before the result is XOR'd with
`rs1` and written back to `rd`.
This instruction exists on RV32 and RV64 base architectures.
On RV64, the 32-bit result is sign extended to XLEN bits.
This instruction must _always_ be implemented such that its execution
latency does not depend on the data being operated on.

Operation::
[source,sail]
--
function clause execute (SM4KS (bs,rs2,rs1,rd)) = {
  let shamt : bits(5)  = (bs @ 0b000); /* shamt = bs*8 */
  let sb_in : bits(8)  = (X(rs2)[31..0] >> shamt)[7..0];
  let x     : bits(32) = 0x000000 @ sm4_sbox(sb_in);
  let y     : bits(32) = x ^ ((x & 0x00000007) << 29) ^ ((x & 0x000000FE) <<  7) ^
                             ((x & 0x00000001) << 23) ^ ((x & 0x000000F8) << 13) ;
  let z     : bits(32) = rol32(y, unsigned(shamt));
  let result: bits(32) = z ^ X(rs1)[31..0];
  X(rd) = EXTS(result);
  RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

| <<zksed>>
| v1.0.0
| Ratified
| <<zks>>
| v1.0.0
| Ratified
|===

<<<

[#insns-unzip-sc,reftext="Bit deinterleave"]
==== unzip

Synopsis::
Implements the inverse of the zip instruction.

Mnemonic::
unzip _rd_, _rs_

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 2, name: 0x3},
{bits: 5, name: 0x4},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x5},
{bits: 5, name: 'rs1'},
{bits: 5, name: 0x1f},
{bits: 7, name: 0x4},
]}
....

Description:: 
This instruction gathers bits from the high and low halves of the source
word into odd/even bit positions in the destination word.
It is the inverse of the <<insns-zip-sc,zip>> instruction.
This instruction is available only on RV32.

Operation::
[source,sail]
--
foreach (i from 0 to xlen/2-1) {
  X(rd)[i] = X(rs1)[2*i]
  X(rd)[i+xlen/2] = X(rs1)[2*i+1]
}
--

.Software Hint
[NOTE, caption="SH" ]
===============================================================
This instruction is useful for implementing the SHA3 cryptographic
hash function on a 32-bit architecture, as it implements the
bit-interleaving operation used to speed up the 64-bit rotations
directly.
===============================================================

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

|Zbkb (<<#zbkb-sc>>) (RV32)
|v1.0.0-rc4
|Ratified
|===

<<<

[#insns-xnor-sc,reftext="Exclusive NOR"]
==== xnor

Synopsis::
Exclusive NOR

Mnemonic::
xnor _rd_, _rs1_, _rs2_

Encoding::
[wavedrom, , svg]
....
{reg:[
    { bits:  7, name: 0x33, attr: ['OP'] },
    { bits:  5, name: 'rd' },
    { bits:  3, name: 0x4, attr: ['XNOR']},
    { bits:  5, name: 'rs1' },
    { bits:  5, name: 'rs2' },
    { bits:  7, name: 0x20, attr: ['XNOR'] },
]}
....

Description:: 
This instruction performs the bit-wise exclusive-NOR operation on _rs1_ and _rs2_.

Operation::
[source,sail]
--
X(rd) = ~(X(rs1) ^ X(rs2));
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

|Zbb (<<#zbb>>)
|v1.0.0
|Ratified

|Zbkb (<<#zbkb-sc>>)
|v1.0.0-rc4
|Ratified
|===

<<<
[#insns-xperm8,reftext="Crossbar permutation (bytes)"]
==== xperm8

Synopsis::
Byte-wise lookup of indicies into a vector.

Mnemonic::
xprem8 _rd_, _rs1_, _rs2_

Encoding::
[wavedrom, , svg]
....
{reg:[
    { bits:  2, name: 0x3 },
    { bits:  5, name: 0xC },
    { bits:  5, name: 'rd'},
    { bits:  3, name: 0x4 },
    { bits:  5, name: 'rs1' },
    { bits:  5, name: 'rs2' },
    { bits:  7, name: 0x14 },
]}
....

Description:: 
The xperm8 instruction operates on bytes. The rs1 register contains a vector of XLEN/8 8-bit elements. The
rs2 register contains a vector of XLEN/8 8-bit indexes. The result is each element in rs2 replaced by the
indexed element in rs1, or zero if the index into rs2 is out of bounds.

Operation::
[source,sail]
--
val xperm8_lookup : (bits(8), xlenbits) -> bits(8)
function xperm8_lookup (idx, lut) = {
(lut >> (idx @ 0b000))[7..0]
}
function clause execute ( XPERM_8 (rs2,rs1,rd)) = {
result : xlenbits = EXTZ(0b0);
foreach(i from 0 to xlen by 8) {
result[i+7..i] = xperm8_lookup(X(rs2)[i+7..i], X(rs1));
};
X(rd) = result;
RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

|Zbkx (<<#zbkx-sc>>)
|v1.0.0-rc4
|Ratified
|===

<<<

[#insns-xperm4,reftext="Crossbar permutation (nibbles)"]
==== xperm4

Synopsis::
Nibble-wise lookup of indicies into a vector.

Mnemonic::
xperm4 _rd_, _rs1_, _rs2_

Encoding::
[wavedrom, , svg]
....
{reg:[
    { bits:  2, name: 0x3 },
    { bits:  5, name: 0xC },
    { bits:  5, name: 'rd'},
    { bits:  3, name: 0x2 },
    { bits:  5, name: 'rs1' },
    { bits:  5, name: 'rs2' },
    { bits:  7, name: 0x14 },
]}
....

Description:: 
The xperm4 instruction operates on nibbles. The rs1 register contains a vector of XLEN/4 4-bit elements.
The rs2 register contains a vector of XLEN/4 4-bit indexes. The result is each element in rs2 replaced by the
indexed element in rs1, or zero if the index into rs2 is out of bounds.

Operation::
[source,sail]
--
val xperm4_lookup : (bits(4), xlenbits) -> bits(4)
function xperm4_lookup (idx, lut) = {
(lut >> (idx @ 0b00))[3..0]
}
function clause execute ( XPERM_4 (rs2,rs1,rd)) = {
result : xlenbits = EXTZ(0b0);
foreach(i from 0 to xlen by 4) {
result[i+3..i] = xperm4_lookup(X(rs2)[i+3..i], X(rs1));
};
X(rd) = result;
RETIRE_SUCCESS
}
--

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

|Zbkx (<<#zbkx-sc>>)
|v1.0.0-rc4
|Ratified
|===

<<<

[#insns-zip-sc,reftext="Bit interleave"]
==== zip

Synopsis::
Gather odd and even bits of the source word into upper/lower halves of the
destination.

Mnemonic::
zip _rd_, _rs_

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 2, name: 0x3},
{bits: 5, name: 0x4},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x1},
{bits: 5, name: 'rs1'},
{bits: 5, name: 0x1e},
{bits: 7, name: 0x4},
]}
....

Description:: 
This instruction scatters all of the odd and even bits of a source word into
the high and low halves of a destination word.
It is the inverse of the <<insns-unzip-sc,unzip>> instruction.
This instruction is available only on RV32.

Operation::
[source,sail]
--
foreach (i from 0 to xlen/2-1) {
  X(rd)[2*i] = X(rs1)[i]
  X(rd)[2*i+1] = X(rs1)[i+xlen/2]
}
--

.Software Hint
[NOTE, caption="SH" ]
===============================================================
This instruction is useful for implementing the SHA3 cryptographic
hash function on a 32-bit architecture, as it implements the
bit-interleaving operation used to speed up the 64-bit rotations
directly.
===============================================================

Included in::
[%header,cols="4,2,2"]
|===
|Extension
|Minimum version
|Lifecycle state

|Zbkb (<<#zbkb-sc>>) (RV32)
|v1.0.0-rc4
|Ratified
|===

<<<

[[crypto_scalar_es]]
=== Entropy Source

The `seed` CSR provides an interface to a NIST SP 800-90B cite:[TuBaKe:18] 
or BSI AIS-31 cite:[KiSc11] compliant physical Entropy Source (ES).

An entropy source, by itself, is not a cryptographically secure Random
Bit Generator (RBG), but can be used to build standard (and nonstandard)
RBGs of many types with the help of symmetric cryptography. Expected usage
is to condition (typically with SHA-2/3) the output from an entropy source and
use it to seed a cryptographically secure Deterministic Random Bit Generator
(DRBG) such as AES-based `CTR_DRBG` cite:[BaKe15].
The combination of an Entropy Source, Conditioning, and a DRBG can be used
to create random bits securely cite:[BaKeRo:21].
See <<crypto_scalar_appx_es>> for a non-normative description of a
certification and self-certification procedures, design rationale, and more
detailed suggestions on how the entropy source output can be used.

[[crypto_scalar_seed_csr]]
==== The `seed` CSR

`seed` is an unprivileged CSR located at address `0x015`. 
The 32-bit contents of `seed` are as follows:

[%autowidth.stretch,cols="^,^,<",options="header",]
|=======================================================================
|Bits |Name |Description

|`31:30` |`OPST` |Status: `BIST` (00), `WAIT` (01), `ES16` (10), `DEAD`
(11).

|`29:24` |_reserved_ |For future use by the RISC-V specification.

|`23:16` |_custom_ |Designated for custom and experimental use.

|`15: 0` |`entropy` |16 bits of randomness, only when `OPST=ES16`.
|=======================================================================

The `seed` CSR must be accessed with a read-write instruction. A read-only
instruction such as `CSRRS/CSRRC` with `rs1=x0` or `CSRRSI/CSRRCI` with
`uimm=0` will raise an illegal instruction exception.
The write value (in `rs1` or `uimm`) must be ignored by implementations.
The purpose of the write is to signal polling and flushing.

The instruction `csrrw rd, seed, x0` can be used for fetching seed status
and entropy values. It is available on both RV32 and RV64 base architectures
and will zero-extend the 32-bit word to XLEN bits.

Encoding::
[wavedrom, , svg]
....
{reg:[
{bits: 7, name: 0x73, attr: "SYSTEM"},
{bits: 5, name: 'rd'},
{bits: 3, name: 0x1, attr: "CSRRW"},
{bits: 5, name: 0x0, attr: "x0"},
{bits: 12, name: 0x15, attr: "seed = 0x015"},
]}
....

The `seed` CSR is also access controlled by execution mode, and attempted
read or write access will raise an illegal instruction exception outside M mode
unless access is explicitly granted. See <<crypto_scalar_es_access>> for
more details.

The status bits `seed[31:30]` = `OPST` may be `ES16` (10),
indicating successful polling, or one of three entropy polling failure
statuses `BIST` (00), `WAIT` (01), or `DEAD` (11), discussed below.

Each returned `seed[15:0]` = `entropy` value represents unique randomness
when `OPST`=`ES16` (`seed[31:30]` = `10`), even if its numerical value is
the same as that of a previously polled `entropy` value. The implementation
requirements of `entropy` bits are defined in <<crypto_scalar_es_req>>.
When `OPST` is not `ES16`, `entropy` must be set to 0.
An implementation may safely set reserved and custom bits to zeros.

For security reasons, the interface guarantees that secret `entropy`
words are not made available multiple times. Hence polling (reading) must
also have the side effect of clearing (wipe-on-read) the `entropy` contents and
changing the state to `WAIT` (unless there is `entropy`
immediately available for `ES16`). Other states (`BIST`, `WAIT`, and `DEAD`)
may be unaffected by polling.

The Status Bits returned in `seed[31:30]`=`OPST`:

* `00` - `BIST`
indicates that Built-In Self-Test "on-demand" (BIST) testing is being
performed. If `OPST` returns temporarily to `BIST` from any other
state, this signals a non-fatal self-test alarm,
which is non-actionable, apart from being logged.
Such a `BIST` alarm must be latched until polled at least once to enable
software to record its occurrence.

* `01` - `WAIT`
means that a sufficient amount of entropy is not yet available. This
is not an error condition and may (in fact) be more frequent than ES16
since physical entropy sources often have low bandwidth.

* `10` - `ES16`
indicates success; the low bits `seed[15:0]` will have 16 bits of
randomness (`entropy`), which is guaranteed to meet certain minimum entropy
requirements, regardless of implementation.

* `11` - `DEAD`
is an unrecoverable self-test error. This may indicate a hardware
fault, a security issue, or (extremely rarely) a type-1 statistical
false positive in the continuous testing procedures. In case of a fatal
failure, an immediate lockdown may also be an appropriate response in
dedicated security devices.

**Example.** `0x8000ABCD` is a valid `ES16` status output, with `0xABCD`
being the `entropy` value. `0xFFFFFFFF` is an invalid output (`DEAD`) with
no `entropy` value.

[[crypto_scalar_es_state,reftext="Entropy Source State Transition Diagram"]]
====
image::es_state.svg[title="Entropy Source state transition diagram.", align="center",scaledwidth=40%]
Normally the operational state alternates between WAIT
(no data) and ES16, which means that 16 bits of randomness (`entropy`)
have been polled. BIST (Built-in Self-Test) only occurs after reset
or to signal a non-fatal self-test alarm (if reached after WAIT or
ES16). DEAD is an unrecoverable error state.
====

[[crypto_scalar_es_req]]
==== Entropy Source Requirements

The output `entropy` (`seed[15:0]` in ES16 state) is not necessarily
fully conditioned randomness due to hardware and energy limitations
of smaller, low-powered implementations. However, minimum requirements are
defined. The main requirement is that 2-to-1 cryptographic post-processing
in 256-bit input blocks will yield 128-bit "full entropy" output blocks.
Entropy source users may make this conservative assumption but are not
prohibited from using more than twice the number of seed bits relative
to the desired resulting entropy.

An implementation of the entropy source should meet at least one of the
following requirements sets in order to be considered a secure and
safe design:

*	<<crypto_scalar_es_req_90b>>: A physical entropy source meeting
	NIST SP 800-90B cite:[TuBaKe:18] criteria with evaluated min-entropy
	of 192 bits for each 256 output bits (min-entropy rate 0.75).

*	<<crypto_scalar_es_req_ptg2>>: A physical entropy source meeting the
	AIS-31 PTG.2 cite:[KiSc11] criteria, implying average Shannon entropy
	rate 0.997. The source must also meet the NIST 800-90B 
	min-entropy rate 192/256 = 0.75.
	
*	<<crypto_scalar_es_req_virt>>: A virtual entropy source is a DRBG
	seeded from a physical entropy source. It must have at least a
	256-bit (Post-Quantum Category 5) internal security level.

All implementations must signal initialization, test mode, and health
alarms as required by respective standards. This may require the implementer
to add non-standard (custom) test interfaces in a secure and safe manner,
an example of which is described in <<crypto_scalar_es_getnoise>>


[[crypto_scalar_es_req_90b]]
===== NIST SP 800-90B / FIPS 140-3 Requirements

All NIST SP 800-90B cite:[TuBaKe:18] required components and health test 
mechanisms must be implemented. 

The entropy requirement is satisfied if 128 bits of _full entropy_ can be
obtained from each 256-bit (16*16 -bit) successful, but possibly
non-consecutive `entropy` (ES16) output sequence using a vetted conditioning
algorithm such as a cryptographic hash (See Section 3.1.5.1.1, SP 800-90B
cite:[TuBaKe:18]). In practice, a min-entropy rate of 0.75 or larger is
required for this. 

Note that 128 bits of estimated input min-entropy does not yield 128 bits of 
conditioned, full entropy in SP 800-90B/C evaluation. Instead, the
implication is that every 256-bit sequence should have min-entropy of at
least 128+64 = 192 bits, as discussed in SP 800-90C cite:[BaKeRo:21];
the likelihood of successfully "guessing" an individual 256-bit output
sequence should not be higher than 2^-192^ even with (almost)
unconstrained amount of entropy source data and computational power.

Rather than attempting to define all the mathematical and architectural
properties that the entropy source must satisfy, we define that the physical
entropy source be strong and robust enough to pass the equivalent of
NIST SP 800-90 evaluation and certification for full entropy when
conditioned cryptographically in ratio 2:1 with 128-bit output blocks.

Even though the requirement is defined in terms of 128-bit full entropy
blocks, we recommend 256-bit security. This can be accomplished by using
at least 512 `entropy` bits to initialize a DRBG that has 256-bit security.

[[crypto_scalar_es_req_ptg2]]
===== BSI AIS-31 PTG.2 / Common Criteria Requirements

For alternative Common Criteria certification (or self-certification), 
AIS 31 PTG.2 class cite:[KiSc11] (Sect. 4.3.) required hardware components
and mechanisms must be implemented.
In addition to AIS-31 PTG.2 randomness requirements (Shannon entropy rate of
0.997 as evaluated in that standard), the overall min-entropy requirement of
remains, as discussed in <<crypto_scalar_es_req_90b>>. Note that 800-90B
min-entropy can be significantly lower than AIS-31 Shannon entropy. These
two metrics should not be equated or confused with each other.


[[crypto_scalar_es_req_virt]]
===== Virtual Sources: Security Requirement

NOTE: A virtual source is not an ISA compliance requirement. It is defined
for the benefit of the RISC-V security ecosystem so that virtual systems
may have a consistent level of security.

A virtual source is not a physical entropy source but provides
additional protection against covert channels, depletion attacks, and host
identification in operating environments that can not be entirely trusted
with direct access to a hardware resource. Despite limited trust,
implementors should try to guarantee that even such environments have
sufficient entropy available for secure cryptographic operations.

A virtual source traps access to the `seed` CSR, emulates it, or
otherwise implements it, possibly without direct access to a physical entropy
source. The output can be cryptographically secure pseudorandomness
instead of real entropy, but must have at least 256-bit security, as defined
below. A virtual source is intended especially for guest operating
systems, sandboxes, emulators, and similar use cases.

As a technical definition, a random-distinguishing attack against
the output should require computational resources comparable or greater
than those required for exhaustive key search on a secure block cipher
with a 256-bit key (e.g., AES 256). This applies to both classical
and quantum computing models, but only classical information flows.
The virtual source security requirement maps to Post-Quantum Security
Category 5 cite:[NI16].

Any implementation of the `seed` CSR that limits the security
strength shall not reduce it to less than 256 bits. If the security
level is under 256 bits, then the interface must not be available.

A virtual entropy source does not need to implement `WAIT` or `BIST` states.
It should fail (`DEAD`) if the host DRBG or entropy source fails and
there is insufficient seeding material for the host DRBG.


[[crypto_scalar_es_access]]
==== Access Control to `seed`

The `seed` CSR is by default only available in M mode, but can be made
available to other modes via the `mseccfg.sseed` and `mseccfg.useed`
access control bits. `sseed` is bit `9` of and `useed` is
bit `8` of the `mseccfg` CSR.
Without the corresponding access control bit set to 1, any attempted
access to `seed` from U, S, or HS modes will raise an illegal instruction
exception. 

VS and VU modes are present in systems with Hypervisor (H) extension
implemented. If desired, a hypervisor can emulate accesses to the seed CSR
from a virtual machine. Attempted access to `seed` from virtual modes
VS and VU always raises an exception; a read-only instruction causes an
illegal instruction exception, while a read-write instruction (that can
potentially be emulated) causes a virtual instruction exception only if
`mseccfg.sseed=1`. Note that `mseccfg.useed` has no effect on the exception
type for either VS or VU modes. 

.Entropy Source Access Control.

[cols="1,1,1,7",options="header",]
|=======================================================================
|Mode | `sseed` | `useed` | Description

| M
| `*`
| `*`
| The `seed` CSR is always available in machine mode as normal (with a
CSR read-write instruction.) Attempted read without a write raises an
illegal instruction exception regardless of mode and access control bits.

| U
| `*`
| `0`
| Any `seed` CSR access raises an illegal instruction exception.

| U
| `*`
| `1`
| The `seed` CSR is accessible as normal. No exception is raised for read-write.

| S/HS
| `0`
| `*`
| Any `seed` CSR access raises an illegal instruction exception.


| S/HS
| `1`
| `*`
| The `seed` CSR is accessible as normal. No exception is raised for read-write.

| VS/VU
| `0`
| `*`
| Any `seed` CSR access raises an illegal instruction exception.

| VS/VU
| `1`
| `*`
| A read-write `seed` access raises a virtual instruction exception,
while other access conditions raise an illegal instruction exception.

|=======================================================================


Systems should implement carefully considered access control policies from
lower privilege modes to physical entropy sources. The system can trap
attempted access to `seed` and feed a less privileged client
_virtual entropy source_ data (<<crypto_scalar_es_req_virt>>) instead of
invoking an SP 800-90B  (<<crypto_scalar_es_req_90b>>) or PTG.2 
(<<crypto_scalar_es_req_ptg2>>) _physical entropy source_. Emulated `seed`
data generation is made with an appropriately seeded, secure software DRBG.
See  <<crypto_scalar_appx_es_access>> for security considerations related 
to direct access to entropy sources.

Implementations may implement `mseccfg` such that `[s,u]seed` is a read-only
constant value `0`. Software may discover if access to the `seed` CSR can be
enabled in U and S mode by writing a `1` to `[s,u]seed` and reading back
the result.

If S or U mode is not implemented, then the corresponding `[s,u]seed`
bits of `mseccfg` must be hardwired to zero.
The `[s,u]seed` bits must have a defined reset value. The system
must not allow them to be in an undefined state after a reset.
`mseccfg` exists if `Zkr` is implemented, or if it is required by other
processor features. If `Zkr` is _not_ implemented, the `[s,u]seed` bits must
be hardwired to zero.

[[crypto_scalar_zkt]]

=== Data Independent Execution Latency Subset: Zkt

The Zkt extension attests that the machine has data-independent execution
time for a safe subset of instructions. This property is commonly called
_"constant-time"_ although should not be taken with that literal meaning.

All currently proposed cryptographic instructions (scalar K extension) are on
this list, together with a set of relevant supporting instructions from
I, M, C, and B extensions.


.Note to software developers
[NOTE,caption="SH"]
====
Failure to prevent leakage of sensitive parameters via the direct
timing channel is considered a serious security vulnerability and will
typically result in a CERT CVE security advisory.
====

==== Scope and Goal

An "ISA contract" is made between a programmer and the RISC-V implementation
that Zkt instructions do not leak information about processed secret data
(plaintext, keying information, or other "sensitive security parameters" --
FIPS 140-3 term) through differences in execution latency. Zkt does _not_
define a set of instructions available in the core; it just restricts the
behaviour of certain instructions if those are implemented.

Currently, the scope of this document is within scalar RV32/RV64 processors.
Vector cryptography instructions (and appropriate vector support instructions)
will be added later, as will other security-related functions that wish
to assert leakage-free execution latency properties.

Loads, stores, conditional branches are excluded, along with a set of
instructions that are rarely necessary to process secret data. Also excluded
are instructions for which workarounds exist in standard cryptographic
middleware due to the limitations of other ISA processors.

The stated goal is that OpenSSL, BoringSSL (Android), the Linux Kernel,
and similar trusted software will not have directly observable
timing side channels when compiled and running on a Zkt-enabled RISC-V target.
The Zkt extension explicitly states many of the common latency assumptions
made by cryptography developers.

Vendors do not have to implement all of the list's instructions to be Zkt
compliant; however, if they claim to have Zkt and implement any of the listed instructions, it must have data-independent latency. 

For example, many simple RV32I and RV64I cores (without Multiply, Compressed, 
Bitmanip, or Cryptographic extensions) are technically compliant with Zkt. 
A constant-time AES can be implemented on them using "bit-slice" techniques,
but it will be excruciatingly slow when compared to implementation with AES
instructions. There are no guarantees that even a bit-sliced cipher
implementation (largely based on boolean logic instructions) is secure on a
core without Zkt attestation.

Out-of-order implementations adhering to Zkt are still free to fuse, crack,
change or even ignore sequences of instructions, so long as the optimisations
are applied deterministically, and not based on operand data.
The guiding principle should be that no information about the data being
operated on should be leaked based on the execution latency.

[NOTE]
====
It is left to future extensions or other techniques to tackle the problem
of data-independent execution in implementations which advanced out-of-order
capabilities which use value prediction, or which are otherwise data-dependent.
====

.Note to software developers
[WARNING,caption="SH"]
====
Programming techniques can only mitigate leakage directly caused by
arithmetic, caches, and branches. Other ISAs have had micro-architectural
issues such as Spectre, Meltdown, Speculative Store Bypass, Rogue System
Register Read, Lazy FP State Restore, Bounds Check Bypass Store, TLBleed,
and L1TF/Foreshadow, etc. See e.g.
link:https://github.com/nsacyber/Hardware-and-Firmware-Security-Guidance[NSA Hardware and Firmware Security Guidance]

It is not within the remit of this proposal to mitigate these
_micro-architectural_ leakages.
====

==== Background

* Timing attacks are much more powerful than was realised before the 2010s,
which has led to a significant mitigation effort in current cryptographic
code-bases.
* Cryptography developers use static and dynamic security testing tools
to trace the handling of secret information and detect occasions where it
influences a branch or is used for a table lookup.
* Architectural testing for Zkt can be pragmatic and semi-formal;
_security by design_ against basic timing attacks can usually be achieved via
conscious implementation (of relevant iterative multi-cycle instructions or
instructions composed of micro-ops) in way that avoids data-dependent latency.
* Laboratory testing may utilize statistical timing attack leakage analysis
techniques such as those described in ISO/IEC 17825 cite:[IS16].
* Binary executables should not contain secrets in the instruction encodings
(Kerckhoffs's principle), so instruction timing may leak information about
immediates, ordering of input registers, etc. There may be an exception to this
in systems where a binary loader modifies the executable for purposes of
relocation -- and it is desirable to keep the execution location (PC) secret.
This is why instructions such as LUI, AUIPC, and ADDI are on the list.
* The rules used by audit tools are relatively simple to understand.
Very briefly; we call the plaintext, secret keys, expanded keys, nonces,
and other such variables "secrets". A secret variable (arithmetically)
modifying any other variable/register turns that into a secret too.
If a secret ends up in address calculation affecting a load or store, that
is a violation. If a secret affects a branch's condition, that is also a
violation. A secret variable location or register becomes a non-secret via
specific zeroization/sanitisation or by being declared ciphertext 
(or otherwise no-longer-secret information). In essence, secrets can only
"touch" instructions on the Zkt list while they are secrets.

==== Specific Instruction Rationale

* HINT instruction forms (typically encodings with `rd=x0`) are excluded from
the data-independent time requirement. 
* Floating point (F, D, Q, L extensions) are currently excluded from the
constant-time requirement as they have very few applications in standardised
cryptography. We may consider adding floating point add, sub, multiply as a
constant time requirement for some floating point extension in case a specific
algorithm (such as the PQC Signature algorithm Falcon) becomes critical.
*  Cryptographers typically assume division to be variable-time (while
multiplication is constant time) and implement their Montgomery reduction
routines with that assumption.
* Zicsr, Zifencei are excluded.
* Some instructions are on the list simply because we see no harm in
including them in testing scope.


==== Programming Information

For background information on secure programming "models", see:

* Thomas Pornin: _"Why Constant-Time Crypto?"_ (A great introduction to timing assumptions.) https://www.bearssl.org/constanttime.html
* Jean-Philippe Aumasson: _"Guidelines for low-level cryptography software."_
(A list of recommendations.) https://github.com/veorq/cryptocoding
* Peter Schwabe: _"Timing Attacks and Countermeasures."_
(Lecture slides -- nice references.)
https://summerschool-croatia.cs.ru.nl/2016/slides/PeterSchwabe.pdf
* Adam Langley: _"ctgrind."_ (This is from 2010 but is still relevant.)
https://www.imperialviolet.org/2010/04/01/ctgrind.html
* Kris Kwiatkowski: _"Constant-time code verification with Memory Sanitizer."_
https://www.amongbytes.com/post/20210709-testing-constant-time/
* For early examples of timing attack vulnerabilities, see
https://www.kb.cert.org/vuls/id/997481 and related academic papers.


==== Zkt listings

The following instructions are included in the `Zkt` subset
They are listed here grouped by their original parent extension.

.Note to implementers
[NOTE, caption="SH"]
====
You do not need to implement all of these instructions to implement `Zkt`.
Rather, every one of these instructions that the core does implement must
adhere to the requirements of `Zkt`.
====

=====	RVI (Base Instruction Set)

Only basic arithmetic and `slt*` (for carry computations) are included.
The data-independent timing requirement does not apply to HINT instruction
encoding forms of these instructions.

[%header,cols="^1,^1,4,8"]
|===
|RV32
|RV64
|Mnemonic
|Instruction

| &#10003; | &#10003; | lui   _rd_, _imm_        |  <<insns-lui>>
| &#10003; | &#10003; | auipc _rd_, _imm_        |  <<insns-auipc>>
| &#10003; | &#10003; | addi  _rd_, _rs1_, _imm_ |  <<insns-addi>>
| &#10003; | &#10003; | slti  _rd_, _rs1_, _imm_ |  <<insns-slti>>
| &#10003; | &#10003; | sltiu _rd_, _rs1_, _imm_ |  <<insns-sltiu>>
| &#10003; | &#10003; | xori  _rd_, _rs1_, _imm_ |  <<insns-xori>>
| &#10003; | &#10003; | ori   _rd_, _rs1_, _imm_ |  <<insns-ori>>
| &#10003; | &#10003; | andi  _rd_, _rs1_, _imm_ |  <<insns-andi>>
| &#10003; | &#10003; | slli  _rd_, _rs1_, _imm_ |  <<insns-slli>>
| &#10003; | &#10003; | srli  _rd_, _rs1_, _imm_ |  <<insns-srli>>
| &#10003; | &#10003; | srai  _rd_, _rs1_, _imm_ |  <<insns-srai>>
| &#10003; | &#10003; | add   _rd_, _rs1_, _rs2_ |  <<insns-add>>
| &#10003; | &#10003; | sub   _rd_, _rs1_, _rs2_ |  <<insns-sub>>
| &#10003; | &#10003; | sll   _rd_, _rs1_, _rs2_ |  <<insns-sll>>
| &#10003; | &#10003; | slt   _rd_, _rs1_, _rs2_ |  <<insns-slt>>
| &#10003; | &#10003; | sltu  _rd_, _rs1_, _rs2_ |  <<insns-sltu>>
| &#10003; | &#10003; | xor   _rd_, _rs1_, _rs2_ |  <<insns-xor>>
| &#10003; | &#10003; | srl   _rd_, _rs1_, _rs2_ |  <<insns-srl>>
| &#10003; | &#10003; | sra   _rd_, _rs1_, _rs2_ |  <<insns-sra>>
| &#10003; | &#10003; | or    _rd_, _rs1_, _rs2_ |  <<insns-or>>
| &#10003; | &#10003; | and   _rd_, _rs1_, _rs2_ |  <<insns-and>>
|          | &#10003; | addiw _rd_, _rs1_, _imm_ |  <<insns-addiw>>
|          | &#10003; | slliw _rd_, _rs1_, _imm_ |  <<insns-slliw>>
|          | &#10003; | srliw _rd_, _rs1_, _imm_ |  <<insns-srliw>>
|          | &#10003; | sraiw _rd_, _rs1_, _imm_ |  <<insns-sraiw>>
|          | &#10003; | addw  _rd_, _rs1_, _rs2_ |  <<insns-addw>>
|          | &#10003; | subw  _rd_, _rs1_, _rs2_ |  <<insns-subw>>
|          | &#10003; | sllw  _rd_, _rs1_, _rs2_ |  <<insns-sllw>>
|          | &#10003; | srlw  _rd_, _rs1_, _rs2_ |  <<insns-srlw>>
|          | &#10003; | sraw  _rd_, _rs1_, _rs2_ |  <<insns-sraw>>
|===

=====	RVM (Multiply)

Multiplication is included; division and remaindering excluded.

[%header,cols="^1,^1,4,8"]
|===
|RV32
|RV64
|Mnemonic
|Instruction

| &#10003; | &#10003; | mul    _rd_, _rs1_, _rs2_ | <<insns-mul>>
| &#10003; | &#10003; | mulh   _rd_, _rs1_, _rs2_ | <<insns-mulh>>
| &#10003; | &#10003; | mulhsu _rd_, _rs1_, _rs2_ | <<insns-mulhsu>>
| &#10003; | &#10003; | mulhu  _rd_, _rs1_, _rs2_ | <<insns-mulhu>>
|          | &#10003; | mulw   _rd_, _rs1_, _rs2_ | <<insns-mulw>>
|===

=====	RVC (Compressed)

Same criteria as in RVI. Organised by quadrants.

[%header,cols="^1,^1,4,8"]
|===
|RV32
|RV64
|Mnemonic
|Instruction

| &#10003; | &#10003; | c.nop      | <<insns-c_nop>>
| &#10003; | &#10003; | c.addi     | <<insns-c_addi>>
|          | &#10003; | c.addiw    | <<insns-c_addiw>>
| &#10003; | &#10003; | c.lui      | <<insns-c_lui>>
| &#10003; | &#10003; | c.srli     | <<insns-c_srli>>
| &#10003; | &#10003; | c.srai     | <<insns-c_srai>>
| &#10003; | &#10003; | c.andi     | <<insns-c_andi>>
| &#10003; | &#10003; | c.sub      | <<insns-c_sub>>
| &#10003; | &#10003; | c.xor      | <<insns-c_xor>>
| &#10003; | &#10003; | c.or       | <<insns-c_or>>
| &#10003; | &#10003; | c.and      | <<insns-c_and>>
|          | &#10003; | c.subw     | <<insns-c_subw>>
|          | &#10003; | c.addw     | <<insns-c_addw>>
| &#10003; | &#10003; | c.slli     | <<insns-c_slli>>
| &#10003; | &#10003; | c.mv       | <<insns-c_mv>>
| &#10003; | &#10003; | c.add      | <<insns-c_add>>
|===

=====	RVK (Scalar Cryptography)

All K-specific instructions are included.
Additionally, `seed` CSR latency should be independent of `ES16` state output
`entropy` bits, as that is a sensitive security parameter.
See <<crypto_scalar_appx_es_access>>.

[%header,cols="^1,^1,4,8"]
|===
|RV32
|RV64
|Mnemonic
|Instruction

| &#10003; |          | aes32dsi     | <<insns-aes32dsi>>
| &#10003; |          | aes32dsmi    | <<insns-aes32dsmi>>
| &#10003; |          | aes32esi     | <<insns-aes32esi>>
| &#10003; |          | aes32esmi    | <<insns-aes32esmi>>
|          | &#10003; | aes64ds      | <<insns-aes64ds>>
|          | &#10003; | aes64dsm     | <<insns-aes64dsm>>
|          | &#10003; | aes64es      | <<insns-aes64es>>
|          | &#10003; | aes64esm     | <<insns-aes64esm>>
|          | &#10003; | aes64im      | <<insns-aes64im>>
|          | &#10003; | aes64ks1i    | <<insns-aes64ks1i>>
|          | &#10003; | aes64ks2     | <<insns-aes64ks2>>
| &#10003; | &#10003; | sha256sig0   | <<insns-sha256sig0>>
| &#10003; | &#10003; | sha256sig1   | <<insns-sha256sig1>>
| &#10003; | &#10003; | sha256sum0   | <<insns-sha256sum0>>
| &#10003; | &#10003; | sha256sum1   | <<insns-sha256sum1>>
| &#10003; |          | sha512sig0h  | <<insns-sha512sig0h>>
| &#10003; |          | sha512sig0l  | <<insns-sha512sig0l>>
| &#10003; |          | sha512sig1h  | <<insns-sha512sig1h>>
| &#10003; |          | sha512sig1l  | <<insns-sha512sig1l>>
| &#10003; |          | sha512sum0r  | <<insns-sha512sum0r>>
| &#10003; |          | sha512sum1r  | <<insns-sha512sum1r>>
|          | &#10003; | sha512sig0   | <<insns-sha512sig0>>
|          | &#10003; | sha512sig1   | <<insns-sha512sig1>>
|          | &#10003; | sha512sum0   | <<insns-sha512sum0>>
|          | &#10003; | sha512sum1   | <<insns-sha512sum1>>
| &#10003; | &#10003; | sm3p0        | <<insns-sm3p0>>
| &#10003; | &#10003; | sm3p1        | <<insns-sm3p1>>
| &#10003; | &#10003; | sm4ed        | <<insns-sm4ed>>
| &#10003; | &#10003; | sm4ks        | <<insns-sm4ks>>
|===


=====	RVB (Bitmanip)

The <<zbkb-sc>>, <<zbkc-sc>> and <<zbkx-sc>> extensions are included in their entirety.

.Note to implementers
[NOTE,caption="SH"]
====
Recall that `rev`, `zip` and `unzip` are pseudo-instructions representing
specific instances of `grevi`, `shfli` and `unshfli` respectively.
====

[%header,cols="^1,^1,4,8"]
|===
|RV32
|RV64
|Mnemonic
|Instruction

| &#10003; | &#10003; |  clmul       | <<insns-clmul-sc>>
| &#10003; | &#10003; |  clmulh      | <<insns-clmulh-sc>>
| &#10003; | &#10003; |  xperm4      | <<insns-xperm4>>
| &#10003; | &#10003; |  xperm8      | <<insns-xperm8>>
| &#10003; | &#10003; |  ror         | <<insns-ror-sc>>
| &#10003; | &#10003; |  rol         | <<insns-rol-sc>>
| &#10003; | &#10003; |  rori        | <<insns-rori-sc>>
|          | &#10003; |  rorw        | <<insns-rorw-sc>>
|          | &#10003; |  rolw        | <<insns-rolw-sc>>
|          | &#10003; |  roriw       | <<insns-roriw-sc>>
| &#10003; | &#10003; |  andn        | <<insns-andn-sc>>
| &#10003; | &#10003; |  orn         | <<insns-orn-sc>>
| &#10003; | &#10003; |  xnor        | <<insns-xnor-sc>>
| &#10003; | &#10003; |  pack        | <<insns-pack-sc>>
| &#10003; | &#10003; |  packh       | <<insns-packh-sc>>
|          | &#10003; |  packw       | <<insns-packw-sc>>
| &#10003; | &#10003; |  brev8       | <<insns-brev8>>
| &#10003; | &#10003; |  rev8        | <<insns-rev8-sc>>
| &#10003; |          |  zip         | <<insns-zip-sc>>
| &#10003; |          |  unzip       | <<insns-unzip-sc>>
|===

[[crypto_scalar_appx_rationale]]
=== Instruction Rationale

This section contains various rationale, design notes and usage
recommendations for the instructions in the scalar cryptography
extension. It also tries to record how the designs of instructions were
derived, or where they were contributed from.

==== AES Instructions

The 32-bit instructions were derived from work in cite:[MJS:LWAES:20] and
contributed to the RISC-V cryptography extension.
The 64-bit instructions were developed collaboratively by task group
members on our mailing list.

Supporting material, including rationale and a design space exploration
for all of the AES instructions in the specification can be found in the paper
_"link:https://doi.org/10.46586/tches.v2021.i1.109-136[The design of scalar AES Instruction Set Extensions for RISC-V]"_ cite:[MNPSW:20].


==== SHA2 Instructions

These instructions were developed based on academic
work at the University of Bristol as part of the XCrypto project
cite:[MPP:19], and contributed to the RISC-V cryptography extension.

The RV32 SHA2-512 instructions were based on this work, and developed
in cite:[MJS:LWSHA:20], before being contributed in the same way.

==== SM3 and SM4 Instructions

The SM4 instructions were derived from work in cite:[MJS:LWAES:20], and
are hence very similar to the RV32 AES instructions.

The SM3 instructions were inspired by the SHA2 instructions, and
based on development work done in cite:[MJS:LWSHA:20], before being
contributed to the RISC-V cryptography extension.

[[crypto_scalar_zkb]]
==== Bitmanip Instructions for Cryptography

Many of the primitive operations used in symmetric key cryptography
and cryptographic hash functions are well supported by the
RISC-V Bitmanip cite:[riscv:bitmanip:repo] extensions.

NOTE: This section repeats much of the information in
<<zbkb-sc>>,
<<zbkc-sc>>
and
<<zbkx-sc>>,
but includes more rationale.

We proposed that the scalar cryptographic extension _reuse_ a
subset of the instructions from the Bitmanip extensions `Zb[abc]` directly.
Specifically, this would mean that
a core implementing
_either_
the scalar cryptographic extensions,
_or_
the `Zb[abc]`,
_or_
both,
would be required to implement these instructions.

===== Rotations

----
RV32, RV64:                         RV64 only:
    ror    rd, rs1, rs2                 rorw   rd, rs1, rs2
    rol    rd, rs1, rs2                 rolw   rd, rs1, rs2
    rori   rd, rs1, imm                 roriw  rd, rs1, imm
----

See cite:[riscv:bitmanip:draft] (Section 3.1.1) for details of
these instructions.

.Notes to software developers
[NOTE,caption="SH"]
====
Standard bitwise rotation is a primitive operation in many block ciphers
and hash functions; it features particularly in the ARX (Add, Rotate, Xor)
class of block ciphers and stream ciphers.

* Algorithms making use of 32-bit rotations:
  SHA256, AES (Shift Rows), ChaCha20, SM3.
* Algorithms making use of 64-bit rotations:
  SHA512, SHA3.
====

===== Bit & Byte Permutations

----
RV32:
    brev8   rd, rs1 // grevi rd, rs1,  7 - Reverse bits in bytes
    rev8    rd, rs1 // grevi rd, rs1, 24 - Reverse bytes in 32-bit word

RV64:
    brev8   rd, rs1 // grevi rd, rs1,  7 - Reverse bits in bytes
    rev8    rd, rs1 // grevi rd, rs1, 56 - Reverse bytes in 64-bit word
----

The scalar cryptography extension provides the following instructions for
manipulating the bit and byte endianness of data.
They are all parameterisations of the Generalised Reverse with Immediate
(`grevi` instruction.
The scalar cryptography extension requires _only_ the above instances
of `grevi` be implemented, which can be invoked via their pseudo-ops.

The full specification of the `grevi` instruction is available in
cite:[riscv:bitmanip:draft] (Section 2.2.2).

.Notes to software developers
[NOTE,caption="SH"]
====
Reversing bytes in words is very common in cryptography when setting a
standard endianness for input and output data.
Bit reversal within bytes is used for implementing the GHASH component
of Galois/Counter Mode (GCM) cite:[nist:gcm].
====

----
RV32:
    zip     rd, rs1 // shfli   rd, rs1, 15 - Bit interleave
    unzip   rd, rs1 // unshfli rd, rs1, 15 - Bit de-interleave
----

The `zip` and `unzip` pseudo-ops are specific instances of
the more general `shfli` and `unshfli` instructions.
The scalar cryptography extension requires _only_ the above instances
of `[un]shfli` be implemented, which can be invoked via their
pseudo-ops.
Only RV32 implementations require these instructions.

The full specification of the `shfli` instruction is available in
cite:[riscv:bitmanip:draft] (Section 2.2.3).

.Notes to software developers
[NOTE,caption="SH"]
====
These instructions perform a bit-interleave (or de-interleave) operation, and
are useful for implementing the 64-bit rotations in the
SHA3 cite:[nist:fips:202] algorithm on
a 32-bit architecture.
On RV64, the relevant operations in SHA3 can be done natively using
rotation instructions, so `zip` and `unzip` are not required.
====

===== Carry-less Multiply

----
RV32, RV64:
    clmul  rd, rs1, rs2
    clmulh rd, rs1, rs2
----

See cite:[riscv:bitmanip:draft] (Section 2.6) for details of
this instruction.
See <<crypto_scalar_zkt>> for additional implementation
requirements for these instructions, related to data independent
execution latency.

.Notes to software developers
[NOTE,caption="SH"]
====
As is mentioned there, obvious cryptographic use-cases for carry-less
multiply are for Galois Counter Mode (GCM) block cipher operations.
GCM is recommended by NIST as a block cipher mode of operation
cite:[nist:gcm], and is the only _required_ mode for the TLS 1.3
protocol.
====

===== Logic With Negate

----
RV32, RV64:
    andn rd, rs1, rs2
     orn rd, rs1, rs2
    xnor rd, rs1, rs2
----

See cite:[riscv:bitmanip:draft] (Section 2.1.3) for details of
these instructions.
These instructions are useful inside hash functions, block ciphers and
for implementing software based side-channel countermeasures like masking.
The `andn` instruction is also useful for constant time word-select
in systems without the ternary Bitmanip `cmov` instruction.

.Notes to software developers
[NOTE,caption="SH"]
====
In the context of Cryptography, these instructions are useful for:
SHA3/Keccak Chi step,
Bit-sliced function implementations,
Software based power/EM side-channel countermeasures based on masking.
====

===== Packing

----
RV32, RV64:                         RV64: 
    pack   rd, rs1, rs2                 packw  rd, rs1, rs2
    packh  rd, rs1, rs2
----

See cite:[riscv:bitmanip:draft] (Section 2.1.4) for details of
these instructions.

.Notes to software developers
[NOTE,caption="SH"]
====
The `pack*` instructions are
useful for re-arranging halfwords within words, and
generally getting data into the right shape prior to applying transforms.
This is particularly useful for cryptographic algorithms which pass inputs
around as (potentially un-aligned) byte strings, but can operate on words
made out of those byte strings.
This occurs (for example) in AES when loading blocks and keys (which may not
be word aligned) into registers to perform the round functions.
====

===== Crossbar Permutation Instructions

----
RV32, RV64:
    xperm4 rd, rs1, rs2
    xperm8 rd, rs1, rs2
----

See cite:[riscv:bitmanip:draft] (Section 2.2.4) for a complete
description of this instruction.

The `xperm4` instruction operates on nibbles.
`GPR[rs1]` contains a vector of `XLEN/4` 4-bit elements.
`GPR[rs2]` contains a vector of `XLEN/4` 4-bit indexes.
The result is each element in `GPR[rs2]` replaced by the indexed element
in `GPR[rs1]`, or zero if the index into `GPR[rs2]` is out of bounds.

The `xperm8` instruction operates on bytes.
`GPR[rs1]` contains a vector of `XLEN/8` 8-bit elements.
`GPR[rs2]` contains a vector of `XLEN/8` 8-bit indexes.
The result is each element in `GPR[rs2]` replaced by the indexed element
in `GPR[rs1]`, or zero if the index into `GPR[rs2]` is out of bounds.

.Notes to software developers
[NOTE,caption="SH"]
====
The instruction can be used to implement arbitrary bit
permutations.
For cryptography, they can accelerate bit-sliced implementations,
permutation layers of block ciphers, masking based countermeasures
and SBox operations.

Lightweight block ciphers using 4-bit SBoxes include:
PRESENT cite:[block:present],
Rectangle cite:[block:rectangle],
GIFT cite:[block:gift],
Twine cite:[block:twine],
Skinny, MANTIS cite:[block:skinny],
Midori cite:[block:midori].

National ciphers using 8-bit SBoxes include:
Camellia cite:[block:camellia] (Japan), 
Aria cite:[block:aria] (Korea),
AES cite:[nist:fips:197] (USA, Belgium),
SM4 cite:[gbt:sm4] (China)
Kuznyechik (Russia).

All of these SBoxes can be implemented efficiently, in constant
time, using the `xperm8` instruction
footnote:l[link:http://svn.clairexen.net/handicraft/2020/lut4perm/demo02.cc[]].
Note that this technique is also suitable for masking based
side-channel countermeasures.
====

[[crypto_scalar_appx_es]]

=== Entropy Source Rationale and Recommendations

This *non-normative* appendix focuses on the rationale, security,
self-certification, and implementation aspects of entropy sources. Hence we
also discuss non-ISA system features that may be needed for cryptographic
standards compliance and security testing.

====	Checklists for Design and Self-Certification 

The security of cryptographic systems is based on secret bits and keys.
These bits need to be random and originate from cryptographically secure
Random Bit Generators (RBGs). An Entropy Source (ES) is required to
construct secure RBGs.

While entropy source implementations do not have to be certified
designs, RISC-V expects that they behave in a compatible manner and do not
create unnecessary security risks to users. Self-evaluation and testing
following appropriate security standards is usually needed to achieve this.

*	*ISA Architectural Tests.* Verify, to the extent possible, that RISC-V ISA
	requirements in this specification are correctly implemented. This includes
	the state transitions (<<crypto_scalar_es>> and 
	<<crypto_scalar_es_getnoise>>), access control 
	(<<crypto_scalar_es_access>>), and that `seed` ES16 `entropy` words
	can only be read destructively.
	The scope of RISC-V ISA architectural tests are those behaviors that 
	are independent of the physical entropy source details. A smoke test ES
	module may be helpful in design phase.
*	*Technical justification for entropy.* This may take the form of a
	stochastic model or a heuristic argument that explains why the noise
	source output is from a random, rather than pseudorandom (deterministic)
	process, and is not easily predictable or externally observable.
	A complete physical model is not necessary; research literature can be
	cited. For example, one can show that a good ring oscillator noise derives
	an amount of physical entropy from local, spontaneously occurring
	Johnson-Nyquist thermal noise cite:[Sa21], and is therefore not merely
	"random-looking".
*	*Entropy Source Design Review.* An entropy source is more than a noise
	source, and must have features such as health tests
	(<<crypto_scalar_es_security_controls>>),
	a conditioner (<<crypto_scalar_appx_es_intro-cond>>), and a security
	boundary with clearly defined interfaces. One may tabulate the SHALL
	statements of SP 800-90B cite:[TuBaKe:18], FIPS 140-3 Implementation
	Guidance cite:[NICC21], AIS-31 cite:[KiSc11] or other standards being
	used. Official and non-official checklist tables are available:
	https://github.com/usnistgov/90B-Shall-Statements
*	*Experimental Tests.* The raw noise source is subjected to entropy
	estimation as defined in NIST 800-90B, Section 3 cite:[TuBaKe:18].
    The interface described in <<crypto_scalar_es_getnoise>> can used be to
    record datasets for this purpose. One also needs to show experimentally
    that the conditioner and health test components work appropriately to
    meet the ES16 output entropy requirements of <<crypto_scalar_es_req>>.
	For SP 800-90B, NIST has made a min-entropy estimation
	package freely available:
	https://github.com/usnistgov/SP800-90B_EntropyAssessment
*	**Resilience.** Above physical engineering steps should consider the
	operational environment of the device, which may be unexpected or
	hostile (actively attempting to exploit vulnerabilities in the design).

See <<crypto_scalar_appx_es_implementation>> for a discussion of various 
implementation options.

NOTE: It is one of the goals of the RISC-V Entropy Source specification
that a standard 90B Entropy Source Module or AIS-31 RNG IP may be licensed
from a third party and integrated with a RISC-V processor design. Compared
to older (FIPS 140-2) RNG and DRBG modules, an entropy source module may
have a relatively small area (just a few thousand NAND2 gate equivalent).
CMVP is introducing an "Entropy Source Validation Scope" which potentially
allows 90B validations to be re-used for different (FIPS 140-3) modules.

==== Standards and Terminology

As a fundamental security function, the generation of random numbers is
governed by numerous standards and technical evaluation methods, the main
ones being FIPS 140-3 cite:[NI19,NICC21] required for U.S. Federal use,
and Common Criteria Methodology cite:[Cr17] used in high-security evaluations
internationally.

Note that FIPS 140-3 is a significantly updated standard compared
to its predecessor FIPS 140-2 and is only coming into use in the 2020s.

These standards set many of the technical requirements for the RISC-V
entropy source design, and we use their terminology if possible.


[[crypto_scalar_es_fig_rng,reftext="TRNG Components"]]
====
image::es_dataflow.svg[align="center",scaledwidth=50%]
The `seed` CSR provides an Entropy Source (ES) interface, not a stateful
random number generator. As a result, it can support arbitrary
security levels. Cryptographic (AES, SHA-2/3) ISA Extensions
can be used to construct high-speed DRBGs that are seeded from the
entropy source.
====

[[crypto_scalar_appx_es_intro-es]]
===== Entropy Source (ES)

Entropy sources are built by sampling and processing data from a noise
source (<<crypto_scalar_appx_es_noise_sources>>). 
We will only consider physical sources of true randomness in this work.
Since these are directly based on natural phenomena and are subject to
environmental conditions (which may be adversarial), they require features 
that monitor the "health" and quality of those sources. 

The requirements for physical entropy sources are specified in
NIST SP 800-90B cite:[TuBaKe:18] (<<crypto_scalar_es_req_90b>>)
for U.S. Federal FIPS 140-3 cite:[NI19] evaluations and
in BSI AIS-31 cite:[KiSc01,KiSc11] (<<crypto_scalar_es_req_ptg2>>)
for high-security Common Criteria evaluations.
There is some divergence in the types of health tests and entropy metrics 
mandated in these standards, and RISC-V enables support for both alternatives.

[[crypto_scalar_appx_es_intro-cond]]
===== Conditioning: Cryptographic and Non-Cryptographic

Raw physical randomness (noise) sources are rarely statistically
perfect, and some generate very large amounts of bits, which need to be
"debiased" and reduced to a smaller number of bits. This process is
called conditioning. A secure hash function is an example of a
cryptographic conditioner. It is important to note that even though
hashing may make any data look random, it does not increase its
entropy content.

Non-cryptographic conditioners and extractors such as von Neumann's
"debiased coin tossing" cite:[Ne51] are easier to implement
efficiently but may reduce entropy content (in individual bits removed)
more than cryptographic hashes, which mix the input entropy very
efficiently. However, they do not require cryptanalytic or computational
hardness assumptions and are therefore inherently more future-proof.
See <<crypto_scalar_appx_es_noncrypto>> for a more detailed
discussion.

[[crypto_scalar_appx_es_intro-prng]]
===== Pseudorandom Number Generator (PRNG)

Pseudorandom Number Generators (PRNGs) use deterministic mathematical
formulas to create abundant random numbers from a smaller amount of
"seed" randomness. PRNGs are also divided into cryptographic and
non-cryptographic ones.

Non-cryptographic PRNGs, such as LFSRs and the linear-congruential
generators found in many programming libraries, may generate statistically
satisfactory random numbers but must never be used for cryptographic
keying. This is because they are not designed to resist
_cryptanalysis_; it is usually possible to take some output and
mathematically derive the "seed" or the internal state of the PRNG
from it. This is a security problem since knowledge of the state
allows the attacker to compute future or past outputs.

[[crypto_scalar_appx_es_intro-drbg]]
===== Deterministic Random Bit Generator (DRBG)

Cryptographic PRNGs are also known as Deterministic Random Bit
Generators (DRBGs), a term used by SP 800-90A cite:[BaKe15]. A strong
cryptographic algorithm such as AES cite:[nist:fips:197] or SHA-2/3
cite:[nist:fips:202,nist:fips:180:4]
is used to produce random bits from a seed. The secret
seed material is like a cryptographic key; determining the seed
from the DRBG output is as hard as breaking AES or a strong hash function.
This also illustrates that the seed/key needs to be long enough and
come from a trusted Entropy Source. The DRBG should still be frequently
refreshed (reseeded) for forward and backward security.

==== Specific Rationale and Considerations

===== (<<crypto_scalar_seed_csr>>) The `seed` CSR 

The interface was designed to be simple so that a vendor- and
device-independent driver component (e.g., in Linux kernel,
embedded firmware, or a cryptographic  library) may use `seed` to
generate truly random bits.

An entropy source does not require a high-bandwidth interface;
a single DRBG source initialization only requires 512 bits
(256 bits of entropy), and DRBG output can be shared by any number of
callers. Once initiated, a DRBG requires new entropy only to mitigate
the risk of state compromise.

From a security perspective, it is essential that the side effect of
flushing the secret entropy bits occurs upon reading. Hence we mandate
a write operation on this particular CSR.

A blocking instruction may have been easier to use, but most users should
be querying a (D)RBG instead of an entropy source.
Without a polling-style mechanism, the entropy source could hang for
thousands of cycles under some circumstances. A `wfi` ot `pause`
mechanism (at least potentially) allows energy-saving sleep on MCUs
and context switching on higher-end CPUs.

The reason for the particular `OPST = seed[31:0]` two-bit mechanism is to
provide redundancy. The "fault" bit combinations `11` (`DEAD`) and `00` 
(`BIST`) are more likely for electrical reasons if feature discovery fails
and the entropy source is actually not available.

The 16-bit bandwidth was a compromise motivated by the desire to
provide redundancy in the return value, some protection against
potential Power/EM leakage (further alleviated by the 2:1 cryptographic
conditioning discussed in <<crypto_scalar_appx_es_crypto-cond>>),
and the desire to have all of the bits "in the same place" on
both RV32 and RV64 architectures for programming convenience.

===== (<<crypto_scalar_es_req_90b>>) NIST SP 800-90B

SP 800-90C cite:[BaKeRo:21] states that each conditioned block of n bits
is required to have n+64 bits of input entropy to attain full entropy.
Hence NIST SP 800-90B cite:[TuBaKe:18] min-entropy assessment must
guarantee at least 128 + 64 = 192 bits input entropy per 256-bit block
( cite:[BaKeRo:21], Sections 4.1. and 4.3.2 ).
Only then a hashing of 16 * 16 = 256 bits from the entropy source
will produce the desired 128 bits of full entropy. This follows from
the specific requirements, threat model, and distinguishability proof
contained in SP 800-90C  cite:[BaKeRo:21], Appendix A.
The implied min-entropy rate is 192/256=12/16=0.75. The expected
Shannon entropy is much larger.

In FIPS 140-3 / SP 800-90 classification, an RBG2(P) construction is a
cryptographically secure RBG with continuous access to a physical entropy
source (`seed`) and output generated by a fully seeded, secure DRBG.
The entropy source can also be used to build RBG3
full entropy sources cite:[BaKeRo:21]. The concatenation of output words
corresponds to the `Get_ES_Bitstring` function.

The 128-bit output block size was selected because that is the output
size of the CBC-MAC conditioner specified in Appendix F of cite:[TuBaKe:18]
and also the smallest key size we expect to see in applications.

If NIST SP 800-90B certification is chosen, the entropy source
should implement at least the health tests defined in
Section 4.4 of cite:[TuBaKe:18]: the repetition count test and adaptive
proportion test, or show that the same flaws will be detected
by vendor-defined tests.

===== (<<crypto_scalar_es_req_ptg2>>) BSI AIS-31

PTG.2 is one of the security and functionality classes defined in
BSI AIS 20/31 cite:[KiSc11]. The PTG.2 source requirements work as a
building block for other types of BSI generators (e.g., DRBGs, or
PTG.3 TRNG with appropriate software post-processing).

For validation purposes, the PTG.2 requirements may be mapped to
security controls T1-3 (<<crypto_scalar_es_security_controls>>) and the
interface as follows:

* P1 *[PTG.2.1]* Start-up tests map to T1 and reset-triggered (on-demand)
`BIST` tests.
* P2 *[PTG.2.2]* Continuous testing total failure maps to T2 and the
`DEAD` state.
* P3 *[PTG.2.3]* Online tests are continuous tests of T2 – entropy output
is prevented in the `BIST` state.
* P4 *[PTG.2.4]* Is related to the design of effective entropy source
health tests, which we encourage.
* P5 *[PTG.2.5]* Raw random sequence may be checked via the GetNoise
interface (<<crypto_scalar_es_getnoise>>).
* P6 *[PTG.2.6]* Test Procedure A cite:[KiSc11] (Sect 2.4.4.1) is a
part of the evaluation process, and we suggest self-evaluation using these
tests even if AIS-31 certification is not sought.
* P7 *[PTG.2.7]* Average Shannon entropy of "internal random bits"
exceeds 0.997.

Note how P7 concerns Shannon entropy, not min-entropy as with NIST
sources. Hence the min-entropy requirement needs to be also stated.
PTG.2 modules built and certified to the AIS-31 standard can also meet the
"full entropy" condition after 2:1 cryptographic conditioning, but not
necessarily so. The technical validation process is somewhat different.

===== (<<crypto_scalar_es_req_virt>>) Virtual Sources

All sources that are not direct physical sources (meeting the SP 800-90B
or the AIS-31 PTG.2 requirements) need to meet the security requirements
of virtual entropy sources. It is assumed that a virtual entropy source
is not a limiting, shared bandwidth resource (but a software DRBG).

DRBGs can be used to feed other (virtual) DRBGs, but that does not
increase the absolute amount of entropy in the system.
The entropy source must be able to support current and future security
standards and applications. The 256-bit requirement maps to
"Category 5" of NIST Post-Quantum Cryptography (4.A.5
"Security Strength Categories" in cite:[NI16]) and TOP SECRET schemes
in Suite B and the newer U.S. Government CNSA Suite cite:[NS15].

[[crypto_scalar_appx_es_access]]
===== (<<crypto_scalar_es_access>>) Security Considerations for Direct Hardware Access

The ISA implementation and system design must try to ensure that the
hardware-software interface minimizes avenues for adversarial
information flow even if not explicitly forbidden in the specification.

For security, virtualization requires both conditioning and DRBG processing
of physical entropy output. It is recommended if a single physical entropy
source is shared between multiple different virtual machnies or if the 
guest OS is untrusted. A virtual entropy source is significantly more
resistant to depletion attacks and also lessens the risk from covert channels.

The direct `mseccfg.[s,u]seed` option allows one to draw a security boundary
around a component in relation to Sensitive Security Parameter (SSP) flows,
even if that component is not in M mode. This is
helpful when implementing trusted enclaves. Such modules can enforce the
entire key lifecycle from birth (in the entropy source) to death
(zeroization) to occur without the key being passed across the boundary
to external code.

*Depletion.*
Active polling may deny the entropy source to another simultaneously
running consumer. This can (for example) delay the instantiation of that
virtual machine if it requires entropy to initialize fully.

*Covert Channels.*
Direct access to a component such as the entropy source can be used to
establish communication channels across security boundaries. Active
polling from one consumer makes the resource unavailable WAIT instead of
ES16 to another (which is polling infrequently). Such interactions can
be used to establish low-bandwidth channels.

*Hardware Fingerprinting.*
An entropy source (and its noise source circuits) may have a uniquely
identifiable hardware "signature." This can be harmless or even useful
in some applications (as random sources may exhibit Physically Un-clonable
Function (PUF) -like features)
but highly undesirable in others (anonymized virtualized environments
and enclaves). A DRBG masks such statistical features.

*Side Channels.*
Some of the most devastating practical attacks against real-life
cryptosystems have used inconsequential-looking additional
information, such as padding error messages cite:[BaFoKa:12]
or timing information cite:[MoSuEi:20].

We urge implementers against creating unnecessary information flows
via status or custom bits or to allow any other mechanism to disable or
affect the entropy source output. All information flows and interaction
mechanisms must be considered from an adversarial viewpoint:
the fewer the better.

As an example of side-channel analysis, we note that the entropy
polling interface is typically not "constant time." One needs to
analyze what kind of information is revealed via the timing oracle;
one way of doing it is to model `seed` as a rejection
sampler. Such a timing oracle can reveal information about the noise
source type and entropy source usage, but not about the random output
`entropy` bits themselves. If it does, additional countermeasures are
necessary.

[[crypto_scalar_es_security_controls]]
==== Security Controls and Health Tests

The primary purpose of a cryptographic entropy source is to produce
secret keying material. In almost all cases, a hardware entropy source
must implement appropriate _security controls_ to guarantee
unpredictability, prevent leakage, detect attacks, and deny adversarial
control over the entropy output or ts generation mechanism. Explicit
security controls are required for security testing and certification.

Many of the security controls built into the device are called "health
checks." Health checks can take the form of integrity checks, start-up
tests, and on-demand tests. These tests can be implemented in hardware
or firmware, typically both. Several are mandated by standards such as
NIST SP 800-90B cite:[NI19].
The choice of appropriate health tests depends on the
certification target, system architecture, threat model, entropy
source type, and other factors.

Health checks are not intended for hardware diagnostics but for detecting
security issues. Hence the default action in case of a failure should be
aimed at damage control: Limiting further output and preventing weak
crypto keys from being generated.

We discuss three specific testing requirements T1-T3. The testing requirement
follows from the definition of an Entropy Source; without it, the module is
simply a noise source and can't be trusted to safely generate keying material.

===== T1: On-demand testing

A sequence of simple tests is invoked via resetting, rebooting, or
powering up the hardware (not an ISA signal). The implementation will
simply return `BIST` during the initial start-up self-test period;
in any case, the driver must wait for them to finish before starting
cryptographic operations. Upon failure, the entropy source will enter
a no-output `DEAD` state.

*Rationale.*
Interaction with hardware self-test mechanisms
from the software side should be minimal; the term "on-demand" does not
mean that the end-user or application program should be able to invoke
them in the field (the term is a throwback to an age of discrete,
non-autonomous crypto devices with human operators).

===== T2: Continuous checks

If an error is detected in continuous tests or
environmental sensors, the entropy source will enter a no-output state.
We define that a non-critical alarm is signaled if the entropy source
returns to `BIST` state from live (`WAIT` or `ES16`) states. Critical
failures will result in `DEAD` state immediately. A hardware-based
continuous testing mechanism must not make statistical information
externally available, and it must be zeroized periodically or upon
demand via reset, power-up, or similar signal.

*Rationale.*
Physical attacks can occur while the device is running. The design
should avoid guiding such active attacks by revealing detailed
status information. Upon detection of an attack, the default action
should be aimed at damage control -- to prevent weak crypto keys from
being generated.

The statistical nature of some tests makes "type-1" false
positives a possibility. There may also be requirements for signaling
of non-fatal alarms; AIS 31 specifies "noise alarms" that can go off
with non-negligible probability even if the device is functioning
correctly; these can be signaled with `BIST`.
There rarely is anything that can or should be done about a non-fatal
alarm condition in an operator-free, autonomous system.

The state of statistical runtime health checks (such as counters)
is potentially correlated with some secret keying material, hence
the zeroization requirement.

===== T3: Fatal error states

Since the security of most cryptographic operations depends on the
entropy source, a system-wide "default deny" security policy approach
is appropriate for most entropy source failures. A hardware test failure
should at least result in the `DEAD` state and possibly reset/halt.
It’s a show stopper: The entropy source (or its cryptographic client
application) _must not_ be allowed to run if its secure operation
can’t be guaranteed.

*Rationale.*
These tests can complement other integrity and tamper resistance
mechanisms (See Chapter 18 of cite:[An20] for examples).

Some hardware random generators are, by their physical construction,
exposed to relatively non-adversarial environmental and manufacturing
issues. However, even such  "innocent" failure modes may indicate
a  _fault attack_ cite:[KaScVe13] and therefore should be addressed
as a system integrity failure rather than as a diagnostic issue.

Security architects will understand to use
permanent or hard-to-recover "security-fuse" lockdowns only if the
threshold of a test is such that the probability of false-positive is
negligible over the entire device lifetime.

===== Information Flows

Some of the most devastating practical attacks
against real-life cryptosystems have used inconsequential-looking
additional information, such as padding error messages cite:[BaFoKa:12]
or timing information cite:[MoSuEi:20]. In cryptography, such
out-of-band information sources  are called "oracles."

To guarantee that no sensitive data is read twice and that different
callers don’t get correlated output, it is required that hardware
implements _wipe-on-read_ on the randomness pathway during each read
(successful poll). For the same reasons, only complete and fully
processed random words shall be made available via `entropy` (ES16 status 
of `seed`).

This also applies to the raw noise source. The raw source interface has
been delegated to an optional vendor-specific test interface.
Importantly the test interface and the main interface should not be
operational at the same time.

[quote, NIST SP 800-90B, Noise Source Requirements]
The noise source state shall be protected from adversarial
knowledge or influence to the greatest extent possible. The methods
used for this shall be documented, including a description of the
(conceptual) security boundarys role in protecting the noise source
from adversarial observation or influence.

An entropy source is a singular resource, subject to depletion
and also covert channels cite:[EvPo16]. Observation of the entropy
can be the same as the observation of the noise source output, as
cryptographic conditioning is mandatory only as a post-processing step.
SP 800-90B and other security standards mandate protection of
noise bits from observation and also influence.

[[crypto_scalar_appx_es_implementation]]
==== Implementation Strategies

As a general rule, RISC-V specifies the ISA only. We provide some
additional suggestions so that portable, vendor-independent middleware
and kernel components can be created. The actual hardware implementation
and certification are left to vendors and circuit designers;
the discussion in this Section is purely informational.
	
When considering implementation options and trade-offs, one must look
at the entire information flow.

. *A Noise Source* generates private, unpredictable signals
  from stable and well-understood physical random events.
. *Sampling* digitizes the noise signal into a raw stream of
  bits. This raw data also needs to be protected by the design.
. *Continuous health tests* ensure that the noise source
  and its environment meet their operational parameters.
. *Non-cryptographic conditioners* remove much of the bias
  and correlation in input noise.
. *Cryptographic conditioners* produce full entropy
  output, completely indistinguishable from ideal random.
. *DRBG* takes in `>=256` bits of seed entropy as keying
  material and uses a "one way" cryptographic process to rapidly
  generate bits on demand (without revealing the seed/state).

Steps 1-4 (possibly 5) are considered to be part of the Entropy
Source (ES) and provided by the `seed` CSR.
Adding the software-side cryptographic steps 5-6 and control logic
complements it into a True Random Number Generator (TRNG).

[[crypto_scalar_appx_es_noise_sources]]
===== Ring Oscillators

We will give some examples of common noise sources that can be
implemented in the processor itself (using standard cells).

The most common entropy source type in production use today is
based on "free running" ring oscillators and their timing jitter.
Here, an odd number of inverters is connected into a loop from which
noise source bits are sampled in relation to a reference clock
cite:[BaLuMi:11]. The sampled bit sequence may be expected to be
relatively uncorrelated (close to IID) if the sample rate is suitably low
cite:[KiSc11]. However, further processing is usually required.

AMD cite:[AM17], ARM cite:[AR17], and IBM cite:[LiBaBo:13] are
examples of ring oscillator TRNGs intended for high-security
applications.

There are related metastability-based generator designs such as
Transition Effect Ring Oscillator (TERO) cite:[VaDr10].
The differential/feedback Intel construction cite:[HaKoMa12] is slightly
different but also falls into the same general metastable
oscillator-based category.

The main benefits of ring oscillators are: (1) They can be implemented
with standard cell libraries without external components --
and even on FPGAs cite:[VaFiAu:10], (2) there is an established theory
for their behavior cite:[HaLe98,HaLiLe99,BaLuMi:11], and (3) ample
precedent exists for testing and certifying them at the highest security
levels.

Ring oscillators also have well-known implementation pitfalls.
Their output is sometimes highly dependent on temperature,
which must be taken into account in testing and modeling.
If the ring oscillator construction is parallelized, it is important
that the number of stages and/or inverters in each chain is suitable to
avoid entropy reduction due to harmonic "Huyghens synchronization"
cite:[Ba86].
Such harmonics can also be inserted maliciously in a frequency
injection attack, which can have devastating results cite:[MaMo09].
Countermeasures are related to circuit design; environmental sensors,
electrical filters, and usage of a differential oscillator may help.

===== Shot Noise

A category of random sources consisting of discrete events
and modeled as a Poisson process is called "shot noise."
There's a long-established precedent of certifying them; the
AIS 31 document cite:[KiSc11] itself offers reference designs based on
noisy diodes. Shot noise sources are often more resistant to
temperature changes than ring oscillators.
Some of these generators can also be fully implemented with standard
cells (The Rambus / Inside Secure generic TRNG IP cite:[Ra20] is
described as a Shot Noise generator).

===== Other types of noise

It may be possible to certify more exotic noise sources and designs,
although their stochastic model needs to be equally well understood,
and their CPU interfaces must be secure.
See <<crypto_scalar_appx_es_quantum>> for a discussion of Quantum
entropy sources.

[[crypto_scalar_appx_es_cont-tests]]
===== Continuous Health Tests

Health monitoring requires some state information related
to the noise source to be maintained. The tests should be designed
in a way that a specific number of samples guarantees a state
flush (no hung states). We suggest flush size `W =< 1024` to
match with the NIST SP 800-90B required tests (See Section 4.4 in
cite:[TuBaKe:18]). The state is also fully zeroized in a system reset.

The two mandatory tests can be built with minimal circuitry.
Full histograms are not required, only simple counter registers:
repetition count, window count, and sample count.
Repetition count is reset every time the output sample value
changes; if the count reaches a certain cutoff limit, a noise alarm
(`BIST`) or failure (`DEAD`) is signaled. The window counter is
used to save every W'th output (typically `W` in { 512, 1024 }).
The frequency of this reference sample in the following window is
counted; cutoff values are defined in the standard. We see that the
structure of the mandatory tests is such that, if well implemented,
no information is carried beyond a limit of `W` samples.

Section 4.5 of cite:[TuBaKe:18] explicitly permits additional
developer-defined tests, and several more were defined in early
versions of FIPS 140-1 before being "crossed out." The choice
of additional tests depends on the nature and implementation of the
physical source.

Especially if a non-cryptographic conditioner is used in hardware,
it is possible that the AIS 31 cite:[KiSc11] online tests are
implemented by driver software. They can also be implemented in hardware.
For some security profiles, AIS 31 mandates that their tolerances are
set in a way that the probability of an alarm is at least 10^-6^
yearly under "normal usage." Such requirements are problematic
in modern applications since their probability is too high for
critical systems.

There rarely is anything that can or should be done about a non-fatal
alarm condition in an operator-free, autonomous system. However,
AIS 31 allows the DRBG component to keep running despite a failure in
its Entropy Source, so we suggest re-entering a temporary `BIST`
state (<<crypto_scalar_es_security_controls>>) to signal a non-fatal
statistical error if such (non-actionable) signaling is necessary.
Drivers and applications can react to this appropriately (or simply
log it), but it will not directly affect the availability of the TRNG.
A permanent error condition should result in `DEAD` state.

[[crypto_scalar_appx_es_noncrypto]]
===== Non-cryptographic Conditioners

As noted in <<crypto_scalar_appx_es_intro-cond>>, physical randomness
sources generally require a post-processing step called _conditioning_ to
meet the desired quality requirements, which  are outlined in
<<crypto_scalar_es_req>>.

The approach taken in this interface is to allow a combination of
non-cryptographic and cryptographic filtering to take place. The
first stage (hardware) merely needs to be able to distill the entropy
comfortably above the necessary level.

* One may take a set of bits from a noise source and XOR them
  together to produce a less biased (and more independent) bit.
  However, such an XOR may introduce "pseudorandomness" and
  make the output difficult to analyze.
* The von Neumann extractor cite:[Ne51] looks at consecutive
  pairs of bits, rejects 00 and 11, and outputs 0 or 1 for
  01 and 10, respectively. It will reduce the number of bits to
  less than 25% of the original, but the output is provably unbiased
  (assuming independence).
* Blum's extractor cite:[Bl86] can be used on sources
  whose behavior resembles N-state Markov chains. If its
  assumptions hold, it also removes dependencies, creating an
  independent and identically distributed (IID) source.
* Other linear and non-linear correctors such as those
  discussed by Dichtl and Lacharme cite:[La08].

Note that the hardware may also implement a full cryptographic conditioner
in the entropy source, even though the software driver still needs
a cryptographic conditioner, too (<<crypto_scalar_es_req>>).

*Rationale:*
The main advantage of non-cryptographic extractors is in their
energy efficiency, relative simplicity, and amenability to mathematical
analysis. If well designed, they can be evaluated in
conjunction with a stochastic model of the noise source itself.
They do not require computational hardness assumptions.

[[crypto_scalar_appx_es_crypto-cond]]
===== Cryptographic Conditioners

For secure use, cryptographic conditioners are always required on the
software side of the ISA boundary. They may also be implemented on the
hardware side if necessary. In any case, the `entropy` ES16 output must
always be compressed 2:1 (or more) before being used as keying material
or considered "full entropy."

Examples of cryptographic conditioners include the random pool of the
Linux operating system, secure hash functions (SHA-2/3, SHAKE
cite:[nist:fips:202,nist:fips:180:4]), and the AES / CBC-MAC
construction in Appendix F, SP 800-90B cite:[TuBaKe:18].

In some constructions, such as the Linux RNG and SHA-3/SHAKE
cite:[nist:fips:202] based generators, the cryptographic conditioning
and output (DRBG) generation are provided by the same component.

*Rationale:*
For many low-power targets constructions the type of hardware AES CBC-MAC
conditioner used by Intel cite:[Me18] and AMD cite:[AM17] would be too
complex and energy-hungry to implement solely to serve the `seed` CSR.
On the other hand, simpler non-cryptographic conditioners may be too
wasteful on input entropy if high-quality random output is required --
(ARM TrustZone TRBG cite:[AR17] outputs only 10Kbit/sec at 200 MHz.)
Hence a resource-saving compromise is made between hardware and software
generation.

[[crypto_scalar_appx_es_drbgs]]
===== The Final Random: DRBGs

All random bits reaching end users and applications must come from a
cryptographic DRBG. These are generally implemented by the driver
component in software. The RISC-V AES and SHA instruction set extensions
should be used if available since they offer additional
security features such as timing attack resistance.

Currently recommended DRBGs are defined in NIST SP 800-90A (Rev 1)
cite:[BaKe15]: `CTR_DRBG`, `Hash_DRBG`, and `HMAC_DRBG`.
Certification often requires known answer tests (KATs) for the symmetric
components and the DRBG as a whole. These are significantly easier to
implement in software than in hardware. In addition to the directly
certifiable SP 800-90A DRBGs, a Linux-style random pool construction
based on ChaCha20 cite:[Mu20] can be used, or an appropriate construction
based on SHAKE256 cite:[nist:fips:202].

These are just recommendations; programmers can adjust the usage of the
CPU Entropy Source to meet future requirements.

[[crypto_scalar_appx_es_quantum]]
===== Quantum vs. Classical Random

[quote,U.K. NCSC QRNG Guidance, March 2020]
The NCSC believes that classical RNGs will continue to
meet our needs for government and military applications for the
foreseeable future.

A Quantum Random Number Generator (QRNG) is a TRNG whose source of
randomness can be unambiguously identified to be a specific
quantum phenomenon such as quantum state superposition, quantum state
entanglement, Heisenberg uncertainty, quantum tunneling, spontaneous
emission, or radioactive decay cite:[IT19].

Direct quantum entropy is theoretically the best possible kind of
entropy. A typical TRNG based on electronic noise is also largely
based on quantum phenomena and is equally unpredictable - the difference
is that the relative amount of quantum and classical physics involved is
difficult to quantify for a classical TRNG.

QRNGs are designed in a way that allows the amount of quantum-origin
entropy to be modeled and estimated. This distinction is important in
the security model used by QKD (Quantum Key Distribution) security
mechanisms which can be used to protect the physical layer (such as
fiber optic cables) against interception by using quantum mechanical
effects directly.

This security model means that many of the available QRNG devices do
not use cryptographic conditioning and may fail cryptographic statistical
requirements cite:[HuHe20]. Many implementers may consider them to be
entropy sources instead.

Relatively little research has gone into QRNG implementation security,
but many QRNG designs are arguably more susceptible to leakage than
classical generators (such as ring oscillators) as they tend to employ
external components and mixed materials. As an example, amplification of
a photon detector signal may be observable in power analysis,
which classical noise-based sources are designed to resist.

===== Post-Quantum Cryptography

PQC public-key cryptography standards cite:[NI16] do not require
quantum-origin randomness, just sufficiently secure keying material.
Recall that cryptography aims to protect the confidentiality and
integrity of data itself and does not place any requirements on
the physical communication channel (like QKD).

Classical good-quality TRNGs are perfectly suitable
for generating the secret keys for PQC protocols that are hard for
quantum computers to break but implementable on classical computers.
What matters in cryptography is that the secret keys have enough true
randomness (entropy) and that they are generated and stored securely.

Of course, one must avoid DRBGs that are based on problems that are
easily solvable with quantum computers, such as factoring cite:[Sh94]
in the case of the Blum-Blum-Shub generator cite:[BlBlSh86].
Most symmetric algorithms are not affected as the best quantum
attacks are still exponential to key size cite:[Gr96].

As an example, the original Intel RNG cite:[Me18], whose output generation
is based on AES-128, can be attacked using Grover's algorithm
with approximately square-root effort cite:[JaNaRo:20].
While even "64-bit" quantum security is extremely difficult to
break, many applications specify a higher security requirement.
NIST cite:[NI16] defines AES-128 to be "Category 1" equivalent
post-quantum security, while AES-256 is "Category 5" (highest).
We avoid this possible future issue by exposing direct access
to the entropy source which can derive its security from
information-theoretic assumptions only.

[[crypto_scalar_es_getnoise]]
==== Suggested GetNoise Test Interface

Compliance testing, characterization, and configuration of entropy sources
require access to raw, unconditioned noise samples. This conceptual test
interface is named GetNoise in Section 2.3.2 of NIST SP 800-90B 
cite:[TuBaKe:18].

Since this type of interface is both necessary for security testing 
and also constitutes a potential backdoor to the cryptographic key generation
process, we define a safety behavior that compliant implementations can
have for temporarily disabling the entropy source `seed` CSR interface during
test.

In order for shared RISC-V self-certification scripts (and drivers) to
accommodate the test interface in a secure fashion, we suggest that it is
implemented as a custom, M-mode only CSR, denoted here as `mnoise`. 

This non-normative interface is not intended to be used as a source of
randomness or for other production use. 
We define the semantics for single bit for this interface, `mnoise[31]`,
which is named `NOISE_TEST`, which will affect the behavior of `seed`
if implemented.

When `NOISE_TEST = 1` in `mnoise`, the `seed` CSR must not return
anything via `ES16`; it should be in `BIST` state unless the source
is `DEAD`. When `NOISE_TEST` is again disabled, the entropy source
shall return from `BIST` via an appropriate zeroization and self-test
mechanism.

The behavior of other input and output bits is largely left to the vendor
(as they depend on the technical details of the physical entropy source),
as is the address of the custom `mnoise` CSR. Other contents and behavior of the
CSR only can be interpreted in the context of `mvendorid`, `marchid`, and
`mimpid` CSR identifiers.

When not implemented (e.g., in virtual machines), `mnoise` can permanently
read zero (`0x00000000`) and ignore writes.
When available, but `NOISE_TEST = 0`, `mnoise` can return a
nonzero constant (e.g. `0x00000001`) but no noise samples.

[[crypto_scalar_es_noistest,reftext="Custom Entropy Test Mode Diagram"]]
====
image::es_noisetest.svg[title="Entropy source can't be read in test mode.", align="center",scaledwidth=66%]
In `NOISE_TEST` mode, the WAIT and ES16 states are unreachable,
and no entropy is output. Implementation of test interfaces that directly
affect ES16 entropy output from the `seed` CSR interface is discouraged.
Such vendor test interfaces have been exploited in attacks. For example,
an ECDSA cite:[nist:fips:186:4] signature process without sufficient
entropy will not only create an insecure signature but can also reveal
the secret signing key, that can be used for authentication forgeries by
attackers. Hence even a temporary lapse in `entropy` security may have serious
security implications.
====

[[crypto_scalar_appx_materials]]
=== Supplementary Materials 

While this document contains the specifications for the RISC-V cryptography
extensions, numerous supplementary materials and example codes have
also been developed.
All of the materials related to the RISC-V Cryptography
extension live in a Github Repository, located at
https://github.com/riscv/riscv-crypto

* `doc/`
  Contains the source code for this document.

* `doc/supp/`
  Contains supplementary information and recommendations for implementers of
  software and hardware.

* `benchmarks/`
  Example software implementations.

* `rtl/`
  Example Verilog implementations of each instruction.

* `sail/`
  Formal model implementations in Sail.

[[crypto_scalar_appx_sail]]
=== Supporting Sail Code

This section contains the supporting Sail code referenced by the
instruction descriptions throughout the specification.
The
link:https://github.com/rems-project/sail/blob/sail2/manual.pdf[Sail Manual]
is recommended reading in order to best understand the supporting code.

[source,sail]
----
/* Auxiliary function for performing GF multiplicaiton */
val xt2 : bits(8) -> bits(8)
function xt2(x) = {
  (x << 1) ^ (if bit_to_bool(x[7]) then 0x1b else 0x00)
}

val xt3 : bits(8) -> bits(8)
function xt3(x) = x ^ xt2(x)

/* Multiply 8-bit field element by 4-bit value for AES MixCols step */
val gfmul : (bits(8), bits(4)) -> bits(8)
function gfmul( x, y) = {
  (if bit_to_bool(y[0]) then             x    else 0x00) ^
  (if bit_to_bool(y[1]) then xt2(        x)   else 0x00) ^
  (if bit_to_bool(y[2]) then xt2(xt2(    x))  else 0x00) ^
  (if bit_to_bool(y[3]) then xt2(xt2(xt2(x))) else 0x00)
}

/* 8-bit to 32-bit partial AES Mix Colum - forwards */
val aes_mixcolumn_byte_fwd : bits(8) -> bits(32)
function aes_mixcolumn_byte_fwd(so) = {
  gfmul(so, 0x3) @ so @ so @ gfmul(so, 0x2)
}

/* 8-bit to 32-bit partial AES Mix Colum - inverse*/
val aes_mixcolumn_byte_inv : bits(8) -> bits(32)
function aes_mixcolumn_byte_inv(so) = {
  gfmul(so, 0xb) @ gfmul(so, 0xd) @ gfmul(so, 0x9) @ gfmul(so, 0xe)
}

/* 32-bit to 32-bit AES forward MixColumn */
val aes_mixcolumn_fwd : bits(32) -> bits(32)
function aes_mixcolumn_fwd(x) = {
  let s0 : bits (8) = x[ 7.. 0];
  let s1 : bits (8) = x[15.. 8];
  let s2 : bits (8) = x[23..16];
  let s3 : bits (8) = x[31..24];
  let b0 : bits (8) = xt2(s0) ^ xt3(s1) ^    (s2) ^    (s3);
  let b1 : bits (8) =    (s0) ^ xt2(s1) ^ xt3(s2) ^    (s3);
  let b2 : bits (8) =    (s0) ^    (s1) ^ xt2(s2) ^ xt3(s3);
  let b3 : bits (8) = xt3(s0) ^    (s1) ^    (s2) ^ xt2(s3);
  b3 @ b2 @ b1 @ b0 /* Return value */
}

/* 32-bit to 32-bit AES inverse MixColumn */
val aes_mixcolumn_inv : bits(32) -> bits(32)
function aes_mixcolumn_inv(x) = {
  let s0 : bits (8) = x[ 7.. 0];
  let s1 : bits (8) = x[15.. 8];
  let s2 : bits (8) = x[23..16];
  let s3 : bits (8) = x[31..24];
  let b0 : bits (8) = gfmul(s0, 0xE) ^ gfmul(s1, 0xB) ^ gfmul(s2, 0xD) ^ gfmul(s3, 0x9);
  let b1 : bits (8) = gfmul(s0, 0x9) ^ gfmul(s1, 0xE) ^ gfmul(s2, 0xB) ^ gfmul(s3, 0xD);
  let b2 : bits (8) = gfmul(s0, 0xD) ^ gfmul(s1, 0x9) ^ gfmul(s2, 0xE) ^ gfmul(s3, 0xB);
  let b3 : bits (8) = gfmul(s0, 0xB) ^ gfmul(s1, 0xD) ^ gfmul(s2, 0x9) ^ gfmul(s3, 0xE);
  b3 @ b2 @ b1 @ b0 /* Return value */
}

/* Turn a round number into a round constant for AES. Note that the
   AES64KS1I instruction is defined such that the r argument is always
   in the range 0x0..0xA. Values of rnum outside the range 0x0..0xA
   do not decode to the AES64KS1I instruction. The 0xA case is used
   specifically for the AES-256 KeySchedule, and this function is never
   called in that case. */
val aes_decode_rcon : bits(4) -> bits(32)
function aes_decode_rcon(r) = {
  assert(r <_u 0xA);
  match r {
    0x0 => 0x00000001,
    0x1 => 0x00000002,
    0x2 => 0x00000004,
    0x3 => 0x00000008,
    0x4 => 0x00000010,
    0x5 => 0x00000020,
    0x6 => 0x00000040,
    0x7 => 0x00000080,
    0x8 => 0x0000001b,
    0x9 => 0x00000036,
    _   => internal_error(__FILE__, __LINE__, "Unexpected AES r") /* unreachable -- required to silence Sail warning */
  }
}

/* SM4 SBox - only one sbox for forwards and inverse */
let sm4_sbox_table : vector(256, bits(8)) = [
0xD6, 0x90, 0xE9, 0xFE, 0xCC, 0xE1, 0x3D, 0xB7, 0x16, 0xB6, 0x14, 0xC2, 0x28,
0xFB, 0x2C, 0x05, 0x2B, 0x67, 0x9A, 0x76, 0x2A, 0xBE, 0x04, 0xC3, 0xAA, 0x44,
0x13, 0x26, 0x49, 0x86, 0x06, 0x99, 0x9C, 0x42, 0x50, 0xF4, 0x91, 0xEF, 0x98,
0x7A, 0x33, 0x54, 0x0B, 0x43, 0xED, 0xCF, 0xAC, 0x62, 0xE4, 0xB3, 0x1C, 0xA9,
0xC9, 0x08, 0xE8, 0x95, 0x80, 0xDF, 0x94, 0xFA, 0x75, 0x8F, 0x3F, 0xA6, 0x47,
0x07, 0xA7, 0xFC, 0xF3, 0x73, 0x17, 0xBA, 0x83, 0x59, 0x3C, 0x19, 0xE6, 0x85,
0x4F, 0xA8, 0x68, 0x6B, 0x81, 0xB2, 0x71, 0x64, 0xDA, 0x8B, 0xF8, 0xEB, 0x0F,
0x4B, 0x70, 0x56, 0x9D, 0x35, 0x1E, 0x24, 0x0E, 0x5E, 0x63, 0x58, 0xD1, 0xA2,
0x25, 0x22, 0x7C, 0x3B, 0x01, 0x21, 0x78, 0x87, 0xD4, 0x00, 0x46, 0x57, 0x9F,
0xD3, 0x27, 0x52, 0x4C, 0x36, 0x02, 0xE7, 0xA0, 0xC4, 0xC8, 0x9E, 0xEA, 0xBF,
0x8A, 0xD2, 0x40, 0xC7, 0x38, 0xB5, 0xA3, 0xF7, 0xF2, 0xCE, 0xF9, 0x61, 0x15,
0xA1, 0xE0, 0xAE, 0x5D, 0xA4, 0x9B, 0x34, 0x1A, 0x55, 0xAD, 0x93, 0x32, 0x30,
0xF5, 0x8C, 0xB1, 0xE3, 0x1D, 0xF6, 0xE2, 0x2E, 0x82, 0x66, 0xCA, 0x60, 0xC0,
0x29, 0x23, 0xAB, 0x0D, 0x53, 0x4E, 0x6F, 0xD5, 0xDB, 0x37, 0x45, 0xDE, 0xFD,
0x8E, 0x2F, 0x03, 0xFF, 0x6A, 0x72, 0x6D, 0x6C, 0x5B, 0x51, 0x8D, 0x1B, 0xAF,
0x92, 0xBB, 0xDD, 0xBC, 0x7F, 0x11, 0xD9, 0x5C, 0x41, 0x1F, 0x10, 0x5A, 0xD8,
0x0A, 0xC1, 0x31, 0x88, 0xA5, 0xCD, 0x7B, 0xBD, 0x2D, 0x74, 0xD0, 0x12, 0xB8,
0xE5, 0xB4, 0xB0, 0x89, 0x69, 0x97, 0x4A, 0x0C, 0x96, 0x77, 0x7E, 0x65, 0xB9,
0xF1, 0x09, 0xC5, 0x6E, 0xC6, 0x84, 0x18, 0xF0, 0x7D, 0xEC, 0x3A, 0xDC, 0x4D,
0x20, 0x79, 0xEE, 0x5F, 0x3E, 0xD7, 0xCB, 0x39, 0x48
]

let aes_sbox_fwd_table : vector(256, bits(8)) = [
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe,
0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4,
0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7,
0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3,
0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09,
0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3,
0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe,
0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85,
0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92,
0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c,
0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19,
0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14,
0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2,
0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5,
0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25,
0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86,
0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e,
0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42,
0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16
]

let aes_sbox_inv_table : vector(256, bits(8)) = [
0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81,
0xf3, 0xd7, 0xfb, 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e,
0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23,
0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, 0x08, 0x2e, 0xa1, 0x66,
0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, 0x72,
0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65,
0xb6, 0x92, 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46,
0x57, 0xa7, 0x8d, 0x9d, 0x84, 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a,
0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, 0xd0, 0x2c, 0x1e, 0x8f, 0xca,
0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, 0x3a, 0x91,
0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6,
0x73, 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8,
0x1c, 0x75, 0xdf, 0x6e, 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f,
0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2,
0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, 0x1f, 0xdd, 0xa8,
0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93,
0xc9, 0x9c, 0xef, 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb,
0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6,
0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d
]

/* Lookup function - takes an index and a table, and retrieves the
 * x'th element of that table. Note that the Sail vector literals
 * start at index 255, and go down to 0.
 */
val sbox_lookup : (bits(8), vector(256, bits(8))) -> bits(8)
function sbox_lookup(x, table) = {
  table[255 - unsigned(x)]
}

/* Easy function to perform a forward AES SBox operation on 1 byte. */
val aes_sbox_fwd : bits(8) -> bits(8)
function aes_sbox_fwd(x) = sbox_lookup(x, aes_sbox_fwd_table)

/* Easy function to perform an inverse AES SBox operation on 1 byte. */
val aes_sbox_inv : bits(8) -> bits(8)
function aes_sbox_inv(x) = sbox_lookup(x, aes_sbox_inv_table)

/* AES SubWord function used in the key expansion
 * - Applies the forward sbox to each byte in the input word.
 */
val aes_subword_fwd : bits(32) -> bits(32)
function aes_subword_fwd(x) = {
  aes_sbox_fwd(x[31..24]) @
  aes_sbox_fwd(x[23..16]) @
  aes_sbox_fwd(x[15.. 8]) @
  aes_sbox_fwd(x[ 7.. 0])
}

/* AES Inverse SubWord function.
 * - Applies the inverse sbox to each byte in the input word.
 */
val aes_subword_inv : bits(32) -> bits(32)
function aes_subword_inv(x) = {
  aes_sbox_inv(x[31..24]) @
  aes_sbox_inv(x[23..16]) @
  aes_sbox_inv(x[15.. 8]) @
  aes_sbox_inv(x[ 7.. 0])
}

/* Easy function to perform an SM4 SBox operation on 1 byte. */
val sm4_sbox : bits(8) -> bits(8)
function sm4_sbox(x) = sbox_lookup(x, sm4_sbox_table)

val aes_get_column : (bits(128), nat) -> bits(32)
function aes_get_column(state,c) = (state >> (to_bits(7, 32 * c)))[31..0]

/* 64-bit to 64-bit function which applies the AES forward sbox to each byte
 * in a 64-bit word.
 */
val aes_apply_fwd_sbox_to_each_byte : bits(64) -> bits(64)
function aes_apply_fwd_sbox_to_each_byte(x) = {
  aes_sbox_fwd(x[63..56]) @
  aes_sbox_fwd(x[55..48]) @
  aes_sbox_fwd(x[47..40]) @
  aes_sbox_fwd(x[39..32]) @
  aes_sbox_fwd(x[31..24]) @
  aes_sbox_fwd(x[23..16]) @
  aes_sbox_fwd(x[15.. 8]) @
  aes_sbox_fwd(x[ 7.. 0])
}

/* 64-bit to 64-bit function which applies the AES inverse sbox to each byte
 * in a 64-bit word.
 */
val aes_apply_inv_sbox_to_each_byte : bits(64) -> bits(64)
function aes_apply_inv_sbox_to_each_byte(x) = {
  aes_sbox_inv(x[63..56]) @
  aes_sbox_inv(x[55..48]) @
  aes_sbox_inv(x[47..40]) @
  aes_sbox_inv(x[39..32]) @
  aes_sbox_inv(x[31..24]) @
  aes_sbox_inv(x[23..16]) @
  aes_sbox_inv(x[15.. 8]) @
  aes_sbox_inv(x[ 7.. 0])
}

/*
 * AES full-round transformation functions.
 */

val getbyte : (bits(64), int) -> bits(8)
function getbyte(x, i) = (x >> to_bits(6, i * 8))[7..0]

val aes_rv64_shiftrows_fwd : (bits(64), bits(64)) -> bits(64)
function aes_rv64_shiftrows_fwd(rs2, rs1) = {
  getbyte(rs1, 3) @
  getbyte(rs2, 6) @
  getbyte(rs2, 1) @
  getbyte(rs1, 4) @
  getbyte(rs2, 7) @
  getbyte(rs2, 2) @
  getbyte(rs1, 5) @
  getbyte(rs1, 0)
}

val aes_rv64_shiftrows_inv : (bits(64), bits(64)) -> bits(64)
function aes_rv64_shiftrows_inv(rs2, rs1) = {
  getbyte(rs2, 3) @
  getbyte(rs2, 6) @
  getbyte(rs1, 1) @
  getbyte(rs1, 4) @
  getbyte(rs1, 7) @
  getbyte(rs2, 2) @
  getbyte(rs2, 5) @
  getbyte(rs1, 0)
}

/* 128-bit to 128-bit implementation of the forward AES ShiftRows transform.
 * Byte 0 of state is input column 0, bits  7..0.
 * Byte 5 of state is input column 1, bits 15..8.
 */
val aes_shift_rows_fwd : bits(128) -> bits(128)
function aes_shift_rows_fwd(x) = {
  let ic3 : bits(32) = aes_get_column(x, 3);
  let ic2 : bits(32) = aes_get_column(x, 2);
  let ic1 : bits(32) = aes_get_column(x, 1);
  let ic0 : bits(32) = aes_get_column(x, 0);
  let oc0 : bits(32) = ic0[31..24] @ ic1[23..16] @ ic2[15.. 8] @ ic3[ 7.. 0];
  let oc1 : bits(32) = ic1[31..24] @ ic2[23..16] @ ic3[15.. 8] @ ic0[ 7.. 0];
  let oc2 : bits(32) = ic2[31..24] @ ic3[23..16] @ ic0[15.. 8] @ ic1[ 7.. 0];
  let oc3 : bits(32) = ic3[31..24] @ ic0[23..16] @ ic1[15.. 8] @ ic2[ 7.. 0];
  (oc3 @ oc2 @ oc1 @ oc0) /* Return value */
}

/* 128-bit to 128-bit implementation of the inverse AES ShiftRows transform.
 * Byte 0 of state is input column 0, bits  7..0.
 * Byte 5 of state is input column 1, bits 15..8.
 */
val aes_shift_rows_inv : bits(128) -> bits(128)
function aes_shift_rows_inv(x) = {
  let ic3 : bits(32) = aes_get_column(x, 3); /* In column 3 */
  let ic2 : bits(32) = aes_get_column(x, 2);
  let ic1 : bits(32) = aes_get_column(x, 1);
  let ic0 : bits(32) = aes_get_column(x, 0);
  let oc0 : bits(32) = ic0[31..24] @ ic3[23..16] @ ic2[15.. 8] @ ic1[ 7.. 0];
  let oc1 : bits(32) = ic1[31..24] @ ic0[23..16] @ ic3[15.. 8] @ ic2[ 7.. 0];
  let oc2 : bits(32) = ic2[31..24] @ ic1[23..16] @ ic0[15.. 8] @ ic3[ 7.. 0];
  let oc3 : bits(32) = ic3[31..24] @ ic2[23..16] @ ic1[15.. 8] @ ic0[ 7.. 0];
  (oc3 @ oc2 @ oc1 @ oc0) /* Return value */
}

/* Applies the forward sub-bytes step of AES to a 128-bit vector
 * representation of its state.
 */
val aes_subbytes_fwd : bits(128) -> bits(128)
function aes_subbytes_fwd(x) = {
  let oc0 : bits(32) = aes_subword_fwd(aes_get_column(x, 0));
  let oc1 : bits(32) = aes_subword_fwd(aes_get_column(x, 1));
  let oc2 : bits(32) = aes_subword_fwd(aes_get_column(x, 2));
  let oc3 : bits(32) = aes_subword_fwd(aes_get_column(x, 3));
  (oc3 @ oc2 @ oc1 @ oc0) /* Return value */
}

/* Applies the inverse sub-bytes step of AES to a 128-bit vector
 * representation of its state.
 */
val aes_subbytes_inv : bits(128) -> bits(128)
function aes_subbytes_inv(x) = {
  let oc0 : bits(32) = aes_subword_inv(aes_get_column(x, 0));
  let oc1 : bits(32) = aes_subword_inv(aes_get_column(x, 1));
  let oc2 : bits(32) = aes_subword_inv(aes_get_column(x, 2));
  let oc3 : bits(32) = aes_subword_inv(aes_get_column(x, 3));
  (oc3 @ oc2 @ oc1 @ oc0) /* Return value */
}

/* Applies the forward MixColumns step of AES to a 128-bit vector
 * representation of its state.
 */
val aes_mixcolumns_fwd : bits(128) -> bits(128)
function aes_mixcolumns_fwd(x) = {
  let oc0 : bits(32) = aes_mixcolumn_fwd(aes_get_column(x, 0));
  let oc1 : bits(32) = aes_mixcolumn_fwd(aes_get_column(x, 1));
  let oc2 : bits(32) = aes_mixcolumn_fwd(aes_get_column(x, 2));
  let oc3 : bits(32) = aes_mixcolumn_fwd(aes_get_column(x, 3));
  (oc3 @ oc2 @ oc1 @ oc0) /* Return value */
}

/* Applies the inverse MixColumns step of AES to a 128-bit vector
 * representation of its state.
 */
val aes_mixcolumns_inv : bits(128) -> bits(128)
function aes_mixcolumns_inv(x) = {
  let oc0 : bits(32) = aes_mixcolumn_inv(aes_get_column(x, 0));
  let oc1 : bits(32) = aes_mixcolumn_inv(aes_get_column(x, 1));
  let oc2 : bits(32) = aes_mixcolumn_inv(aes_get_column(x, 2));
  let oc3 : bits(32) = aes_mixcolumn_inv(aes_get_column(x, 3));
  (oc3 @ oc2 @ oc1 @ oc0) /* Return value */
}
----