Source file cryptokit.ml

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
(***********************************************************************)
(*                                                                     *)
(*                      The Cryptokit library                          *)
(*                                                                     *)
(*            Xavier Leroy, projet Cristal, INRIA Rocquencourt         *)
(*                                                                     *)
(*  Copyright 2002 Institut National de Recherche en Informatique et   *)
(*  en Automatique.  All rights reserved.  This file is distributed    *)
(*  under the terms of the GNU Library General Public License, with    *)
(*  the special exception on linking described in file LICENSE.        *)
(*                                                                     *)
(***********************************************************************)

(* Utilities *)

let seq_equal (len: 'a -> int) (get: 'a -> int -> char) (s1: 'a) (s2: 'a) =
  let l = len s1 in
  let rec equal i accu =
    if i >= l
    then accu = 0
    else equal (i + 1)
               (accu lor ((Char.code (get s1 i)) lxor (Char.code (get s2 i))))
  in
    l = len s2 && equal 0 0

let string_equal = seq_equal String.length String.get
let bytes_equal = seq_equal Bytes.length Bytes.get

let wipe_bytes s = Bytes.fill s 0 (Bytes.length s) '\000'
let wipe_string s = wipe_bytes (Bytes.unsafe_of_string s)

let shl1_bytes src soff dst doff len =
  let rec shl1 carry i =
    if i >= 0 then begin
      let n = Char.code (Bytes.get src (soff + i)) in
      Bytes.set dst (doff + i) (Char.unsafe_chr ((n lsl 1) lor carry));
      shl1 (n lsr 7) (i - 1)
    end
  in shl1 0 (len - 1)

(* Error reporting *)

type error =
  | Wrong_key_size
  | Wrong_IV_size
  | Wrong_data_length
  | Bad_padding
  | Output_buffer_overflow
  | Incompatible_block_size
  | Number_too_long
  | Seed_too_short
  | Message_too_long
  | Bad_encoding
  | Compression_error of string * string
  | No_entropy_source
  | Entropy_source_closed
  | Compression_not_supported

exception Error of error

let _ = Callback.register_exception "Cryptokit.Error" (Error Wrong_key_size)

(* Interface with C *)

type dir = Encrypt | Decrypt

external xor_bytes: bytes -> int -> bytes -> int -> int -> unit = "caml_xor_string"
external xor_string: string -> int -> bytes -> int -> int -> unit = "caml_xor_string"
external aes_cook_encrypt_key : string -> bytes = "caml_aes_cook_encrypt_key"
external aes_cook_decrypt_key : string -> bytes = "caml_aes_cook_decrypt_key"
external aes_encrypt : bytes -> bytes -> int -> bytes -> int -> unit = "caml_aes_encrypt"
external aes_decrypt : bytes -> bytes -> int -> bytes -> int -> unit = "caml_aes_decrypt"
external blowfish_cook_key : string -> bytes = "caml_blowfish_cook_key"
external blowfish_encrypt : bytes -> bytes -> int -> bytes -> int -> unit = "caml_blowfish_encrypt"
external blowfish_decrypt : bytes -> bytes -> int -> bytes -> int -> unit = "caml_blowfish_decrypt"
external des_cook_key : string -> int -> dir -> bytes = "caml_des_cook_key"
external des_transform : bytes -> bytes -> int -> bytes -> int -> unit = "caml_des_transform"
external arcfour_cook_key : string -> bytes = "caml_arcfour_cook_key"
external arcfour_transform : bytes -> bytes -> int -> bytes -> int -> int -> unit = "caml_arcfour_transform_bytecode" "caml_arcfour_transform"
external chacha20_cook_key : string -> bytes -> int64 -> bytes = "caml_chacha20_cook_key"
external chacha20_transform : bytes -> bytes -> int -> bytes -> int -> int -> unit = "caml_chacha20_transform_bytecode" "caml_chacha20_transform"
external chacha20_extract : bytes -> bytes -> int -> int -> unit = "caml_chacha20_extract"

external sha1_init: unit -> bytes = "caml_sha1_init"
external sha1_update: bytes -> bytes -> int -> int -> unit = "caml_sha1_update"
external sha1_final: bytes -> string = "caml_sha1_final"
external sha256_init: unit -> bytes = "caml_sha256_init"
external sha224_init: unit -> bytes = "caml_sha224_init"
external sha256_update: bytes -> bytes -> int -> int -> unit = "caml_sha256_update"
external sha256_final: bytes -> string = "caml_sha256_final"
external sha224_final: bytes -> string = "caml_sha224_final"
external sha512_init: unit -> bytes = "caml_sha512_init"
external sha384_init: unit -> bytes = "caml_sha384_init"
external sha512_update: bytes -> bytes -> int -> int -> unit = "caml_sha512_update"
external sha512_final: bytes -> string = "caml_sha512_final"
external sha384_final: bytes -> string = "caml_sha384_final"
type sha3_context
external sha3_init: int -> sha3_context = "caml_sha3_init"
external sha3_absorb: sha3_context -> bytes -> int -> int -> unit = "caml_sha3_absorb"
external sha3_extract: bool -> sha3_context -> string = "caml_sha3_extract"
external sha3_wipe: sha3_context -> unit = "caml_sha3_wipe"
external ripemd160_init: unit -> bytes = "caml_ripemd160_init"
external ripemd160_update: bytes -> bytes -> int -> int -> unit = "caml_ripemd160_update"
external ripemd160_final: bytes -> string = "caml_ripemd160_final"
external md5_init: unit -> bytes = "caml_md5_init"
external md5_update: bytes -> bytes -> int -> int -> unit = "caml_md5_update"
external md5_final: bytes -> string = "caml_md5_final"
external blake2b_init: int -> string -> bytes = "caml_blake2b_init"
external blake2b_update: bytes -> bytes -> int -> int -> unit = "caml_blake2b_update"
external blake2b_final: bytes -> int -> string = "caml_blake2b_final"
external blake2s_init: int -> string -> bytes = "caml_blake2s_init"
external blake2s_update: bytes -> bytes -> int -> int -> unit = "caml_blake2s_update"
external blake2s_final: bytes -> int -> string = "caml_blake2s_final"
type ghash_context
external ghash_init: bytes -> ghash_context = "caml_ghash_init"
external ghash_mult: ghash_context -> bytes -> unit = "caml_ghash_mult"
external poly1305_init: bytes -> bytes = "caml_poly1305_init"
external poly1305_update: bytes -> bytes -> int -> int -> unit = "caml_poly1305_update"
external poly1305_final: bytes -> string = "caml_poly1305_final"
external siphash_init: string -> int -> bytes = "caml_siphash_init"
external siphash_update: bytes -> bytes -> int -> int -> unit = "caml_siphash_update"
external siphash_final: bytes -> int -> string = "caml_siphash_final"
type blake3_context
external blake3_init: string -> blake3_context = "caml_blake3_init"
external blake3_update: blake3_context -> bytes -> int -> int -> unit = "caml_blake3_update"
external blake3_final: blake3_context -> int -> string = "caml_blake3_extract"
external blake3_wipe: blake3_context -> unit = "caml_blake3_wipe"

(* Abstract transform type *)

class type transform =
  object
    method input_block_size: int
    method output_block_size: int

    method put_substring: bytes -> int -> int -> unit
    method put_string: string -> unit
    method put_char: char -> unit
    method put_byte: int -> unit

    method finish: unit
    method flush: unit

    method available_output: int

    method get_string: string
    method get_substring: bytes * int * int
    method get_char: char
    method get_byte: int

    method wipe: unit
  end

let transform_string tr s =
  tr#put_string s;
  tr#finish;
  let r = tr#get_string in tr#wipe; r

let transform_channel tr ?len ic oc =
  let ibuf = Bytes.create 256 in
  let rec transf_to_eof () =
    let r = input ic ibuf 0 256 in
    if r > 0 then begin
      tr#put_substring ibuf 0 r;
      let (obuf, opos, olen) = tr#get_substring in
      output oc obuf opos olen;
      transf_to_eof()
    end
  and transf_bounded numleft =
    if numleft > 0 then begin
      let r = input ic ibuf 0 (min 256 numleft) in
      if r = 0 then raise End_of_file;
      tr#put_substring ibuf 0 r;
      let (obuf, opos, olen) = tr#get_substring in
      output oc obuf opos olen;
      transf_bounded (numleft - r)
    end in
  begin match len with
      None -> transf_to_eof ()
    | Some l -> transf_bounded l
  end;
  wipe_bytes ibuf;
  tr#finish;
  let (obuf, opos, olen) = tr#get_substring in
  output oc obuf opos olen;
  tr#wipe  

class compose (tr1 : transform) (tr2 : transform) =
  object(self)
    method input_block_size = tr1#input_block_size
    method output_block_size = tr2#output_block_size

    method put_substring buf ofs len =
      tr1#put_substring buf ofs len; self#transfer
    method put_string s =
      tr1#put_string s; self#transfer
    method put_char c =
      tr1#put_char c; self#transfer
    method put_byte b =
      tr1#put_byte b; self#transfer

    method private transfer =
      let (buf, ofs, len) = tr1#get_substring in
      tr2#put_substring buf ofs len

    method available_output = tr2#available_output
    method get_string = tr2#get_string
    method get_substring = tr2#get_substring
    method get_char = tr2#get_char
    method get_byte = tr2#get_byte

    method flush = tr1#flush; self#transfer; tr2#flush
    method finish = tr1#finish; self#transfer; tr2#finish

    method wipe = tr1#wipe; tr2#wipe
  end

let compose tr1 tr2 = new compose tr1 tr2

class type hash =
  object
    method hash_size: int
    method add_substring: bytes -> int -> int -> unit
    method add_string: string -> unit
    method add_char: char -> unit
    method add_byte: int -> unit
    method result: string
    method wipe: unit
  end

let hash_string hash s =
  hash#add_string s;
  let r = hash#result in
  hash#wipe;
  r

let hash_channel hash ?len ic =
  let ibuf = Bytes.create 256 in
  let rec hash_to_eof () =
    let r = input ic ibuf 0 256 in
    if r > 0 then begin
      hash#add_substring ibuf 0 r;
      hash_to_eof()
    end
  and hash_bounded numleft =
    if numleft > 0 then begin
      let r = input ic ibuf 0 (min 256 numleft) in
      if r = 0 then raise End_of_file;
      hash#add_substring ibuf 0 r;
      hash_bounded (numleft - r)
    end in
  begin match len with
      None -> hash_to_eof ()
    | Some l -> hash_bounded l
  end;
  wipe_bytes ibuf;
  let res = hash#result in
  hash#wipe;
  res

class type authenticated_transform =
  object
    method input_block_size: int
    method output_block_size: int
    method tag_size: int

    method put_substring: bytes -> int -> int -> unit
    method put_string: string -> unit
    method put_char: char -> unit
    method put_byte: int -> unit

    method finish_and_get_tag: string

    method available_output: int

    method get_string: string
    method get_substring: bytes * int * int
    method get_char: char
    method get_byte: int

    method wipe: unit
  end

let auth_transform_string_detached tr s =
  tr#put_string s;
  let tag = tr#finish_and_get_tag in
  let txt = tr#get_string in
  tr#wipe;
  (txt, tag)

let auth_transform_string tr s =
  let (txt, tag) = auth_transform_string_detached tr s in
  txt ^ tag

let auth_check_transform_string tr s =
  let ls = String.length s in
  let lt = tr#tag_size in
  if ls < lt then raise (Error Wrong_data_length);
  tr#put_string (String.sub s 0 (ls - lt));
  let tag = tr#finish_and_get_tag in
  let res =
    if string_equal tag (String.sub s (ls - lt) lt)
    then Some (tr#get_string)
    else None in
  tr#wipe; res

(* Generic handling of output buffering *)

class buffered_output initial_buffer_size =
  object(self)
    val mutable obuf = Bytes.create initial_buffer_size
    val mutable obeg = 0
    val mutable oend = 0

    method private ensure_capacity n =
      let len = Bytes.length obuf in
      if oend + n > len then begin
        if oend - obeg + n < len then begin
          Bytes.blit obuf obeg obuf 0 (oend - obeg);
          oend <- oend - obeg;
          obeg <- 0
        end else begin
          let newlen = ref (2 * len) in
          while oend - obeg + n > (!newlen) do
            newlen := (!newlen) * 2
          done;
          if (!newlen) > Sys.max_string_length then begin
            if (oend - obeg + n) <= Sys.max_string_length then
              newlen := Sys.max_string_length
            else
              raise (Error Output_buffer_overflow)
          end;
          let newbuf = Bytes.create (!newlen) in
          Bytes.blit obuf obeg newbuf 0 (oend - obeg);
          obuf <- newbuf;
          oend <- oend - obeg;
          obeg <- 0
        end
      end

    method available_output = oend - obeg

    method get_substring =
      let res = (obuf, obeg, oend - obeg) in obeg <- 0; oend <- 0; res

    method get_string =
      let res = Bytes.sub_string obuf obeg (oend - obeg) in obeg <- 0; oend <- 0; res

    method get_char =
      if obeg >= oend then raise End_of_file;
      let r = Bytes.get obuf obeg in
      obeg <- obeg + 1;
      r

    method get_byte =
      Char.code self#get_char          

    method wipe =
      wipe_bytes obuf
  end

(* Combining a transform and a hash to get an authenticated transform *)

class transform_then_hash (tr: transform) (h: hash) =
  object(self)
    inherit buffered_output 256 as output_buffer

    method private transfer =
      let (buf, ofs, len) = tr#get_substring in
      h#add_substring buf ofs len;
      self#ensure_capacity len;
      Bytes.blit buf ofs obuf oend len;
      oend <- oend + len

    method input_block_size = tr#input_block_size
    method output_block_size = tr#output_block_size
    method tag_size = h#hash_size

    method put_substring buf ofs len =
      tr#put_substring buf ofs len; self#transfer
    method put_string s =
      tr#put_string s; self#transfer
    method put_char c =
      tr#put_char c; self#transfer
    method put_byte b =
      tr#put_byte b; self#transfer

    method finish_and_get_tag =
      tr#finish; self#transfer; h#result

    method wipe =
      output_buffer#wipe; tr#wipe; h#wipe

end

let transform_then_hash tr h = new transform_then_hash tr h

class transform_and_hash (tr: transform) (h: hash) =
  object(self)
    method input_block_size = tr#input_block_size
    method output_block_size = tr#output_block_size
    method tag_size = h#hash_size

    method put_substring buf ofs len =
      tr#put_substring buf ofs len; h#add_substring buf ofs len
    method put_string s =
      tr#put_string s; h#add_string s
    method put_char c =
      tr#put_char c; h#add_char c
    method put_byte b =
      tr#put_byte b; h#add_byte b

    method finish_and_get_tag =
      tr#finish; h#result

    method wipe =
      tr#wipe; h#wipe

    method available_output = tr#available_output
    method get_substring = tr#get_substring
    method get_string = tr#get_string
    method get_char = tr#get_char
    method get_byte = tr#get_byte
end

let transform_and_hash tr h = new transform_and_hash tr h

(* Padding schemes *)

module Padding = struct

class type scheme =
  object
    method pad: bytes -> int -> unit
    method strip: bytes -> int
  end

class length =
  object
    method pad buffer used =
      let n = Bytes.length buffer - used in
      assert (n > 0 && n < 256);
      Bytes.fill buffer used n (Char.chr n)
    method strip buffer =
      let blocksize = Bytes.length buffer in
      let n = Char.code (Bytes.get buffer (blocksize - 1)) in
      if n = 0 || n > blocksize then raise (Error Bad_padding);
      (* Characters blocksize - n to blocksize - 1 must be equal to n *)
      for i = blocksize - n to blocksize - 2 do
        if Char.code (Bytes.get buffer i) <> n then raise (Error Bad_padding)
      done;
      blocksize - n
  end

let length = new length

class _8000 =
  object
    method pad buffer used =
      Bytes.set buffer used '\128';
      for i = used + 1 to Bytes.length buffer - 1 do
        Bytes.set buffer i '\000'
      done
    method strip buffer =
      let rec strip pos =
        if pos < 0 then raise (Error Bad_padding) else
          match Bytes.get buffer pos with
            '\128' -> pos
          | '\000' -> strip (pos - 1)
          |    _   -> raise (Error Bad_padding)
      in strip (Bytes.length buffer - 1)
  end

let _8000 = new _8000

end

(* Block ciphers *)

module Block = struct

class type block_cipher =
  object
    method blocksize: int
    method transform: bytes -> int -> bytes -> int -> unit
    method wipe: unit
  end

class aes_encrypt key =
  object
    val ckey =
      let kl = String.length key in
      if kl = 16 || kl = 24 || kl = 32
      then aes_cook_encrypt_key key
      else raise(Error Wrong_key_size)
    method blocksize = 16
    method transform src src_ofs dst dst_ofs =
      if src_ofs < 0 || src_ofs > Bytes.length src - 16
      || dst_ofs < 0 || dst_ofs > Bytes.length dst - 16
      then invalid_arg "aes#transform";
      aes_encrypt ckey src src_ofs dst dst_ofs
    method wipe =
      wipe_bytes ckey;
      Bytes.set ckey (Bytes.length ckey - 1) '\016'
  end

class aes_decrypt key =
  object
    val ckey =
      let kl = String.length key in
      if kl = 16 || kl = 24 || kl = 32
      then aes_cook_decrypt_key key
      else raise(Error Wrong_key_size)
    method blocksize = 16
    method transform src src_ofs dst dst_ofs =
      if src_ofs < 0 || src_ofs > Bytes.length src - 16
      || dst_ofs < 0 || dst_ofs > Bytes.length dst - 16
      then invalid_arg "aes#transform";
      aes_decrypt ckey src src_ofs dst dst_ofs
    method wipe =
      wipe_bytes ckey;
      Bytes.set ckey (Bytes.length ckey - 1) '\016'
  end

class blowfish_encrypt key =
  object
    val ckey =
      let kl = String.length key in
      if kl >= 4 && kl <= 56
      then blowfish_cook_key key
      else raise(Error Wrong_key_size)
    method blocksize = 8
    method transform src src_ofs dst dst_ofs =
      if src_ofs < 0 || src_ofs > Bytes.length src - 8
      || dst_ofs < 0 || dst_ofs > Bytes.length dst - 8
      then invalid_arg "blowfish#transform";
      blowfish_encrypt ckey src src_ofs dst dst_ofs
    method wipe =
      wipe_bytes ckey
  end

class blowfish_decrypt key =
  object
    val ckey =
      let kl = String.length key in
      if kl >= 4 && kl <= 56
      then blowfish_cook_key key
      else raise(Error Wrong_key_size)
    method blocksize = 8
    method transform src src_ofs dst dst_ofs =
      if src_ofs < 0 || src_ofs > Bytes.length src - 8
      || dst_ofs < 0 || dst_ofs > Bytes.length dst - 8
      then invalid_arg "blowfish#transform";
      blowfish_decrypt ckey src src_ofs dst dst_ofs
    method wipe =
      wipe_bytes ckey
  end

class des direction key =
  object
    val ckey =
      if String.length key = 8
      then des_cook_key key 0 direction
      else raise(Error Wrong_key_size)
    method blocksize = 8
    method transform src src_ofs dst dst_ofs =
      if src_ofs < 0 || src_ofs > Bytes.length src - 8
      || dst_ofs < 0 || dst_ofs > Bytes.length dst - 8
      then invalid_arg "des#transform";
      des_transform ckey src src_ofs dst dst_ofs
    method wipe =
      wipe_bytes ckey
  end

class des_encrypt = des Encrypt
class des_decrypt = des Decrypt

class triple_des_encrypt key =
  let _ =
    let kl = String.length key in
    if kl <> 16 && kl <> 24 then raise (Error Wrong_key_size) in
  let ckey1 =
    des_cook_key key 0 Encrypt in
  let ckey2 =
    des_cook_key key 8 Decrypt in
  let ckey3 =
    if String.length key = 24
    then des_cook_key key 16 Encrypt
    else ckey1 in
  object
    method blocksize = 8
    method transform src src_ofs dst dst_ofs =
      if src_ofs < 0 || src_ofs > Bytes.length src - 8
      || dst_ofs < 0 || dst_ofs > Bytes.length dst - 8
      then invalid_arg "triple_des#transform";
      des_transform ckey1 src src_ofs dst dst_ofs;
      des_transform ckey2 dst dst_ofs dst dst_ofs;
      des_transform ckey3 dst dst_ofs dst dst_ofs
    method wipe =
      wipe_bytes ckey1;
      wipe_bytes ckey2;
      wipe_bytes ckey3
  end

class triple_des_decrypt key =
  let _ =
    let kl = String.length key in
    if kl <> 16 && kl <> 24 then raise (Error Wrong_key_size) in
  let ckey3 =
    des_cook_key key 0 Decrypt in
  let ckey2 =
    des_cook_key key 8 Encrypt in
  let ckey1 =
    if String.length key = 24
    then des_cook_key key 16 Decrypt
    else ckey3 in
  object
    method blocksize = 8
    method transform src src_ofs dst dst_ofs =
      if src_ofs < 0 || src_ofs > Bytes.length src - 8
      || dst_ofs < 0 || dst_ofs > Bytes.length dst - 8
      then invalid_arg "triple_des#transform";
      des_transform ckey1 src src_ofs dst dst_ofs;
      des_transform ckey2 dst dst_ofs dst dst_ofs;
      des_transform ckey3 dst dst_ofs dst dst_ofs
    method wipe =
      wipe_bytes ckey1;
      wipe_bytes ckey2;
      wipe_bytes ckey3
  end

(* Chaining modes *)

let make_initial_iv blocksize = function
  | None ->
      Bytes.make blocksize '\000'
  | Some s ->
      if String.length s <> blocksize then raise (Error Wrong_IV_size);
      Bytes.of_string s

class cbc_encrypt ?iv:iv_init (cipher : block_cipher) =
  let blocksize = cipher#blocksize in
  object(self)
    val iv = make_initial_iv blocksize iv_init
    method blocksize = blocksize
    method transform src src_off dst dst_off =
      xor_bytes src src_off iv 0 blocksize;
      cipher#transform iv 0 dst dst_off;
      Bytes.blit dst dst_off iv 0 blocksize
    method wipe =
      cipher#wipe;
      wipe_bytes iv
  end

class cbc_decrypt ?iv:iv_init (cipher : block_cipher) =
  let blocksize = cipher#blocksize in
  object(self)
    val iv = make_initial_iv blocksize iv_init
    val next_iv = Bytes.create blocksize
    method blocksize = blocksize
    method transform src src_off dst dst_off =
      Bytes.blit src src_off next_iv 0 blocksize;
      cipher#transform src src_off dst dst_off;
      xor_bytes iv 0 dst dst_off blocksize;
      Bytes.blit next_iv 0 iv 0 blocksize
    method wipe =
      cipher#wipe;
      wipe_bytes iv;
      wipe_bytes next_iv
  end

class cfb_encrypt ?iv:iv_init chunksize (cipher : block_cipher) =
  let blocksize = cipher#blocksize in
  let _ = assert (chunksize > 0 && chunksize <= blocksize) in
  object(self)
    val iv = make_initial_iv blocksize iv_init
    val out = Bytes.create blocksize
    method blocksize = chunksize
    method transform src src_off dst dst_off =
      cipher#transform iv 0 out 0;
      Bytes.blit src src_off dst dst_off chunksize;
      xor_bytes out 0 dst dst_off chunksize;
      Bytes.blit iv chunksize iv 0 (blocksize - chunksize);
      Bytes.blit dst dst_off iv (blocksize - chunksize) chunksize
    method wipe =
      cipher#wipe;
      wipe_bytes iv;
      wipe_bytes out
  end

class cfb_decrypt ?iv:iv_init chunksize (cipher : block_cipher) =
  let blocksize = cipher#blocksize in
  let _ = assert (chunksize > 0 && chunksize <= blocksize) in
  object(self)
    val iv = make_initial_iv blocksize iv_init
    val out = Bytes.create blocksize
    method blocksize = chunksize
    method transform src src_off dst dst_off =
      cipher#transform iv 0 out 0;
      Bytes.blit iv chunksize iv 0 (blocksize - chunksize);
      Bytes.blit src src_off iv (blocksize - chunksize) chunksize;
      Bytes.blit src src_off dst dst_off chunksize;
      xor_bytes out 0 dst dst_off chunksize
    method wipe =
      cipher#wipe;
      wipe_bytes iv;
      wipe_bytes out
  end

class ofb ?iv:iv_init chunksize (cipher : block_cipher) =
  let blocksize = cipher#blocksize in
  let _ = assert (chunksize > 0 && chunksize <= blocksize) in
  object(self)
    val iv = make_initial_iv blocksize iv_init
    method blocksize = chunksize
    method transform src src_off dst dst_off =
      cipher#transform iv 0 iv 0;
      Bytes.blit src src_off dst dst_off chunksize;
      xor_bytes iv 0 dst dst_off chunksize
    method wipe =
      cipher#wipe;
      wipe_bytes iv
  end

let rec increment_counter c lim pos =
  if pos >= lim then begin
    let i = 1 + Char.code (Bytes.get c pos) in
    Bytes.set c pos (Char.unsafe_chr i);
    if i = 0x100 then increment_counter c lim (pos - 1)
  end

class ctr ?iv:iv_init ?inc (cipher : block_cipher) =
  let blocksize = cipher#blocksize in
  let nincr =
    match inc with
    | None -> blocksize
    | Some n -> assert (n > 0 && n <= blocksize); n in
  object(self)
    val iv = make_initial_iv blocksize iv_init
    val out = Bytes.create blocksize
    val mutable max_transf =
      if nincr < 8 then Int64.(shift_left 1L (nincr * 8)) else 0L
    method blocksize = blocksize
    method transform src src_off dst dst_off =
      cipher#transform iv 0 out 0;
      Bytes.blit src src_off dst dst_off blocksize;
      xor_bytes out 0 dst dst_off blocksize;
      increment_counter iv (blocksize - nincr) (blocksize - 1);
      let m = Int64.pred max_transf in
      if m = 0L then raise (Error Message_too_long);
      max_transf <- m
    method wipe =
      cipher#wipe;
      wipe_bytes iv;
      wipe_bytes out
  end

(* Wrapping of a block cipher as a transform *)

class cipher (cipher : block_cipher) =
  let blocksize = cipher#blocksize in
  object(self)
    val ibuf = Bytes.create blocksize
    val mutable used = 0

    inherit buffered_output (max 256 (2 * blocksize)) as output_buffer

    method input_block_size = blocksize
    method output_block_size = blocksize

    method put_substring src ofs len =
      if len <= 0 then () else
      if used + len <= blocksize then begin
        (* Just accumulate len characters in ibuf *)
        Bytes.blit src ofs ibuf used len;
        used <- used + len
      end else begin
        (* Fill buffer and run it through cipher *)
        let n = blocksize - used in
        Bytes.blit src ofs ibuf used n;
        self#ensure_capacity blocksize;
        cipher#transform ibuf 0 obuf oend;
        oend <- oend + blocksize;
        used <- 0;
        (* Recurse on remainder of string *)
        self#put_substring src (ofs + n) (len - n)
      end

    method put_string s =
      self#put_substring (Bytes.unsafe_of_string s) 0 (String.length s)

    method put_char c =
      if used < blocksize then begin
        Bytes.set ibuf used c;
        used <- used + 1
      end else begin
        self#ensure_capacity blocksize;
        cipher#transform ibuf 0 obuf oend;
        oend <- oend + blocksize;
        Bytes.set ibuf 0 c;
        used <- 1
      end

    method put_byte b =
      self#put_char (Char.unsafe_chr b)

    method wipe =
      cipher#wipe;
      output_buffer#wipe;
      wipe_bytes ibuf

    method flush =
      if used = 0 then ()
      else if used = blocksize then begin
        self#ensure_capacity blocksize;
        cipher#transform ibuf 0 obuf oend;
        used <- 0;
        oend <- oend + blocksize
      end
      else raise (Error Wrong_data_length)

    method finish =
      self#flush
  end

(* Block cipher with padding *)

class cipher_padded_encrypt (padding : Padding.scheme)
                            (cipher : block_cipher) =
  let blocksize = cipher#blocksize in
  object(self)
    inherit cipher cipher
    method input_block_size = 1

    method finish =
      if used >= blocksize then begin
        self#ensure_capacity blocksize;
        cipher#transform ibuf 0 obuf oend;
        oend <- oend + blocksize;
        used <- 0
      end;
      padding#pad ibuf used;
      self#ensure_capacity blocksize;
      cipher#transform ibuf 0 obuf oend;
      oend <- oend + blocksize
  end

class cipher_padded_decrypt (padding : Padding.scheme)
                            (cipher : block_cipher) =
  let blocksize = cipher#blocksize in
  object(self)
    inherit cipher cipher
    method output_block_size = 1

    method finish =
      if used <> blocksize then raise (Error Wrong_data_length);
      cipher#transform ibuf 0 ibuf 0;
      let valid = padding#strip ibuf in
      self#ensure_capacity valid;
      Bytes.blit ibuf 0 obuf oend valid;
      oend <- oend + valid
  end

(* Wrapping of a block cipher as a MAC, using CBC mode *)

class mac ?iv:iv_init ?(pad: Padding.scheme option) (cipher : block_cipher) =
  let blocksize = cipher#blocksize in
  object(self)
    val iv = make_initial_iv blocksize iv_init
    val buffer = Bytes.create blocksize
    val mutable used = 0

    method hash_size = blocksize

    method add_substring src src_ofs len =
      let rec add src_ofs len =
        if len <= 0 then () else
        if used + len <= blocksize then begin
          (* Just accumulate len characters in buffer *)
          Bytes.blit src src_ofs buffer used len;
          used <- used + len
        end else begin
          (* Fill buffer and run it through cipher *)
          let n = blocksize - used in
          Bytes.blit src src_ofs buffer used n;
          xor_bytes iv 0 buffer 0 blocksize;
          cipher#transform buffer 0 iv 0;
          used <- 0;
          (* Recurse on remainder of string *)
          add (src_ofs + n) (len - n)
        end
      in add src_ofs len

    method add_string s =
      self#add_substring (Bytes.unsafe_of_string s) 0 (String.length s)

    method add_char c =
      if used < blocksize then begin
        Bytes.set buffer used c;
        used <- used + 1
      end else begin
        xor_bytes iv 0 buffer 0 blocksize;
        cipher#transform buffer 0 iv 0;
        Bytes.set buffer 0 c;
        used <- 1
      end

    method add_byte b =
      self#add_char (Char.unsafe_chr b)

    method wipe =
      cipher#wipe;
      wipe_bytes buffer;
      wipe_bytes iv

    method result =
      if used = blocksize then begin
        xor_bytes iv 0 buffer 0 blocksize;
        cipher#transform buffer 0 iv 0;
        used <- 0
      end;
      begin match pad with
        None ->
          if used <> 0 then raise (Error Wrong_data_length)
      | Some p ->
          p#pad buffer used;
          xor_bytes iv 0 buffer 0 blocksize;
          cipher#transform buffer 0 iv 0;
          used <- 0
      end;
      Bytes.to_string iv
  end

class mac_final_triple ?iv ?pad (cipher1 : block_cipher)
                                (cipher2 : block_cipher)
                                (cipher3 : block_cipher) =
  let _ = if cipher1#blocksize <> cipher2#blocksize
          || cipher2#blocksize <> cipher3#blocksize
          then raise(Error Incompatible_block_size) in
  object
    inherit mac ?iv ?pad cipher1 as super
    method result =
      let r = Bytes.of_string super#result in
      cipher2#transform r 0 r 0;
      cipher3#transform r 0 r 0;
      Bytes.unsafe_to_string r
    method wipe =
      super#wipe; cipher2#wipe; cipher3#wipe
  end

(* Wrapping of a block ciper as a MAC, in CMAC mode (a.k.a. OMAC1) *)

class cmac ?iv:iv_init (cipher : block_cipher) k1 k2 =
  object (self)
    inherit mac ?iv:iv_init cipher as super

    method result =
      let blocksize = cipher#blocksize in
      let k' =
        if used = blocksize then k1 else (Padding._8000#pad buffer used; k2) in
      xor_bytes iv 0 buffer 0 blocksize;
      xor_bytes k' 0 buffer 0 blocksize;
      cipher#transform buffer 0 iv 0;
      used <- 0; (* really useful? *)
      Bytes.to_string iv

    method wipe =
      super#wipe;
      wipe_bytes k1;
      wipe_bytes k2
  end
end

(* Stream ciphers *)

module Stream = struct

class type stream_cipher =
  object
    method transform: bytes -> int -> bytes -> int -> int -> unit
    method wipe: unit
  end

class arcfour key =
  object
    val ckey =
      if String.length key > 0 && String.length key <= 256
      then arcfour_cook_key key
      else raise(Error Wrong_key_size)
    method transform src src_ofs dst dst_ofs len =
      if len < 0
      || src_ofs < 0 || src_ofs > Bytes.length src - len
      || dst_ofs < 0 || dst_ofs > Bytes.length dst - len
      then invalid_arg "arcfour#transform";
      arcfour_transform ckey src src_ofs dst dst_ofs len
    method wipe =
      wipe_bytes ckey
  end

class chacha20 ?iv ?(ctr = 0L) key =
  object
    val ckey =
      if not (String.length key = 16 || String.length key = 32)
      then raise (Error Wrong_key_size);
      let iv =
        match iv with
        | None -> Bytes.make 8 '\000'
        | Some s ->
            if String.length s = 8
            || String.length s = 12 && ctr < 0x1_000_000L
            then Bytes.of_string s
            else raise (Error Wrong_IV_size) in
      chacha20_cook_key key iv ctr
    method transform src src_ofs dst dst_ofs len =
      if len < 0
      || src_ofs < 0 || src_ofs > Bytes.length src - len
      || dst_ofs < 0 || dst_ofs > Bytes.length dst - len
      then invalid_arg "chacha20#transform";
      chacha20_transform ckey src src_ofs dst dst_ofs len
    method wipe =
      wipe_bytes ckey
  end

(* Wrapping of a stream cipher as a cipher *)

class cipher (cipher : stream_cipher) =
  object(self)
    val charbuf = Bytes.create 1

    inherit buffered_output 256 as output_buffer
    method input_block_size = 1
    method output_block_size = 1

    method put_substring src ofs len =
      self#ensure_capacity len;
      cipher#transform src ofs obuf oend len;
      oend <- oend + len

    method put_string s =
      self#put_substring (Bytes.unsafe_of_string s) 0 (String.length s)

    method put_char c =
      Bytes.set charbuf 0 c;
      self#ensure_capacity 1;
      cipher#transform charbuf 0 obuf oend 1;
      oend <- oend + 1

    method put_byte b =
      self#put_char (Char.unsafe_chr b)

    method flush = ()
    method finish = ()

    method wipe =
      cipher#wipe;
      output_buffer#wipe;
      wipe_bytes charbuf
  end

end

(* Hash functions *)

module Hash = struct

class sha1 =
  object(self)
    val context = sha1_init()
    method hash_size = 20
    method add_substring src ofs len =
      if ofs < 0 || len < 0 || ofs > Bytes.length src - len
      then invalid_arg "sha1#add_substring";
      sha1_update context src ofs len
    method add_string src =
      sha1_update context (Bytes.unsafe_of_string src) 0 (String.length src)
    method add_char c =
      self#add_string (String.make 1 c)
    method add_byte b =
      self#add_char (Char.unsafe_chr b)
    method result =
      sha1_final context
    method wipe =
      wipe_bytes context
  end

let sha1 () = new sha1

class sha224 =
  object(self)
    val context = sha224_init()
    method hash_size = 24
    method add_substring src ofs len =
      if ofs < 0 || len < 0 || ofs > Bytes.length src - len
      then invalid_arg "sha224#add_substring";
      sha256_update context src ofs len
    method add_string src =
      sha256_update context (Bytes.unsafe_of_string src) 0 (String.length src)
    method add_char c =
      self#add_string (String.make 1 c)
    method add_byte b =
      self#add_char (Char.unsafe_chr b)
    method result =
      sha224_final context
    method wipe =
      wipe_bytes context
  end

let sha224 () = new sha224

class sha256 =
  object(self)
    val context = sha256_init()
    method hash_size = 32
    method add_substring src ofs len =
      if ofs < 0 || len < 0 || ofs > Bytes.length src - len
      then invalid_arg "sha256#add_substring";
      sha256_update context src ofs len
    method add_string src =
      sha256_update context (Bytes.unsafe_of_string src) 0 (String.length src)
    method add_char c =
      self#add_string (String.make 1 c)
    method add_byte b =
      self#add_char (Char.unsafe_chr b)
    method result =
      sha256_final context
    method wipe =
      wipe_bytes context
  end

let sha256 () = new sha256

class sha384 =
  object(self)
    val context = sha384_init()
    method hash_size = 48
    method add_substring src ofs len =
      if ofs < 0 || len < 0 || ofs > Bytes.length src - len
      then invalid_arg "sha384#add_substring";
      sha512_update context src ofs len
    method add_string src =
      sha512_update context (Bytes.unsafe_of_string src) 0 (String.length src)
    method add_char c =
      self#add_string (String.make 1 c)
    method add_byte b =
      self#add_char (Char.unsafe_chr b)
    method result =
      sha384_final context
    method wipe =
      wipe_bytes context
  end

let sha384 () = new sha384

class sha512 =
  object(self)
    val context = sha512_init()
    method hash_size = 64
    method add_substring src ofs len =
      if ofs < 0 || len < 0 || ofs > Bytes.length src - len
      then invalid_arg "sha512#add_substring";
      sha512_update context src ofs len
    method add_string src =
      sha512_update context (Bytes.unsafe_of_string src) 0 (String.length src)
    method add_char c =
      self#add_string (String.make 1 c)
    method add_byte b =
      self#add_char (Char.unsafe_chr b)
    method result =
      sha512_final context
    method wipe =
      wipe_bytes context
  end

let sha512 () = new sha512

let sha2 sz =
  match sz with
  | 224 -> new sha224
  | 256 -> new sha256
  | 384 -> new sha384
  | 512 -> new sha512
  |  _  -> raise (Error Wrong_key_size)

class sha3 sz official =
  object(self)
    val context =
      if sz = 224 || sz = 256 || sz = 384 || sz = 512
      then sha3_init sz
      else raise (Error Wrong_key_size)
    method hash_size = sz / 8
    method add_substring src ofs len =
      if ofs < 0 || len < 0 || ofs > Bytes.length src - len
      then invalid_arg ((if official then "sha3" else "keccak")^"#add_substring");
      sha3_absorb context src ofs len
    method add_string src =
      sha3_absorb context (Bytes.unsafe_of_string src) 0 (String.length src)
    method add_char c =
      self#add_string (String.make 1 c)
    method add_byte b =
      self#add_char (Char.unsafe_chr b)
    method result = sha3_extract official context
    method wipe =
      sha3_wipe context
  end

let sha3 sz = new sha3 sz true

let keccak sz = new sha3 sz false

class ripemd160 =
  object(self)
    val context = ripemd160_init()
    method hash_size = 32
    method add_substring src ofs len =
      if ofs < 0 || len < 0 || ofs > Bytes.length src - len
      then invalid_arg "ripemd160#add_substring";
      ripemd160_update context src ofs len
    method add_string src =
      ripemd160_update context (Bytes.unsafe_of_string src) 0 (String.length src)
    method add_char c =
      self#add_string (String.make 1 c)
    method add_byte b =
      self#add_char (Char.unsafe_chr b)
    method result =
      ripemd160_final context
    method wipe =
      wipe_bytes context
  end

let ripemd160 () = new ripemd160

class md5 =
  object(self)
    val context = md5_init()
    method hash_size = 16
    method add_substring src ofs len =
      if ofs < 0 || len < 0 || ofs > Bytes.length src - len
      then invalid_arg "md5#add_substring";
      md5_update context src ofs len
    method add_string src =
      md5_update context (Bytes.unsafe_of_string src) 0 (String.length src)
    method add_char c =
      self#add_string (String.make 1 c)
    method add_byte b =
      self#add_char (Char.unsafe_chr b)
    method result =
      md5_final context
    method wipe =
      wipe_bytes context
  end

let md5 () = new md5

class blake2b sz key =
  object(self)
    val context =
      if sz >= 8 && sz <= 512 && sz mod 8 = 0 && String.length key <= 64
      then blake2b_init (sz / 8) key
      else raise (Error Wrong_key_size)
    method hash_size = sz / 8
    method add_substring src ofs len =
      if ofs < 0 || len < 0 || ofs > Bytes.length src - len
      then invalid_arg "blake2b#add_substring";
      blake2b_update context src ofs len
    method add_string src =
      blake2b_update context (Bytes.unsafe_of_string src) 0 (String.length src)
    method add_char c =
      self#add_string (String.make 1 c)
    method add_byte b =
      self#add_char (Char.unsafe_chr b)
    method result = blake2b_final context (sz / 8)
    method wipe =
      wipe_bytes context
  end

let blake2b sz = new blake2b sz ""
let blake2b512 () = new blake2b 512 ""

class blake2s sz key =
  object(self)
    val context =
      if sz >= 8 && sz <= 256 && sz mod 8 = 0 && String.length key <= 32
      then blake2s_init (sz / 8) key
      else raise (Error Wrong_key_size)
    method hash_size = sz / 8
    method add_substring src ofs len =
      if ofs < 0 || len < 0 || ofs > Bytes.length src - len
      then invalid_arg "blake2s#add_substring";
      blake2s_update context src ofs len
    method add_string src =
      blake2s_update context (Bytes.unsafe_of_string src) 0 (String.length src)
    method add_char c =
      self#add_string (String.make 1 c)
    method add_byte b =
      self#add_char (Char.unsafe_chr b)
    method result = blake2s_final context (sz / 8)
    method wipe =
      wipe_bytes context
  end

let blake2s sz = new blake2s sz ""
let blake2s256 () = new blake2s 256 ""

class blake3 key sz =
  object(self)
    val context =
      if sz > 0 && sz mod 8 = 0
      && (String.length key = 0 || String.length key = 32)
      then blake3_init key
      else raise (Error Wrong_key_size)
    method hash_size = sz / 8
    method add_substring src ofs len =
      if ofs < 0 || len < 0 || ofs > Bytes.length src - len
      then invalid_arg "blake3#add_substring";
      blake3_update context src ofs len
    method add_string src =
      blake3_update context (Bytes.unsafe_of_string src) 0 (String.length src)
    method add_char c =
      self#add_string (String.make 1 c)
    method add_byte b =
      self#add_char (Char.unsafe_chr b)
    method result = blake3_final context (sz / 8)
    method wipe = blake3_wipe context
  end

let blake3 sz = new blake3 "" sz
let blake3_256 () = new blake3 "" 256

end

(* High-level entry points for ciphers *)

module Cipher = struct

type direction = dir = Encrypt | Decrypt

type chaining_mode =
    ECB
  | CBC
  | CFB of int
  | OFB of int
  | CTR
  | CTR_N of int

let make_block_cipher ?(mode = CBC) ?pad ?iv dir block_cipher =
  let chained_cipher =
    match (mode, dir) with
      (ECB, _) -> block_cipher
    | (CBC, Encrypt) -> new Block.cbc_encrypt ?iv block_cipher
    | (CBC, Decrypt) -> new Block.cbc_decrypt ?iv block_cipher

    | (CFB n, Encrypt) -> new Block.cfb_encrypt ?iv n block_cipher
    | (CFB n, Decrypt) -> new Block.cfb_decrypt ?iv n block_cipher
    | (OFB n, _) -> new Block.ofb ?iv n block_cipher
    | (CTR, _) -> new Block.ctr ?iv block_cipher
    | (CTR_N n, _) -> new Block.ctr ?iv ~inc:n block_cipher in
  match pad with
    None -> new Block.cipher chained_cipher
  | Some p ->
      match dir with
        Encrypt -> new Block.cipher_padded_encrypt p chained_cipher
      | Decrypt -> new Block.cipher_padded_decrypt p chained_cipher

let normalize_dir mode dir =
  match mode with
  | Some(CFB _) | Some(OFB _) | Some(CTR) | Some(CTR_N _) -> Encrypt
  | _ -> dir

let aes ?mode ?pad ?iv key dir =
  make_block_cipher ?mode ?pad ?iv dir
   (match normalize_dir mode dir with
      Encrypt -> new Block.aes_encrypt key
    | Decrypt -> new Block.aes_decrypt key)

let blowfish ?mode ?pad ?iv key dir =
  make_block_cipher ?mode ?pad ?iv dir
   (match normalize_dir mode dir with
      Encrypt -> new Block.blowfish_encrypt key
    | Decrypt -> new Block.blowfish_decrypt key)

let des ?mode ?pad ?iv key dir =
  make_block_cipher ?mode ?pad ?iv dir
    (new Block.des (normalize_dir mode dir) key)

let triple_des ?mode ?pad ?iv key dir =
  make_block_cipher ?mode ?pad ?iv dir
   (match normalize_dir mode dir with
      Encrypt -> new Block.triple_des_encrypt key
    | Decrypt -> new Block.triple_des_decrypt key)

let arcfour key dir = new Stream.cipher (new Stream.arcfour key)

let chacha20 ?iv ?ctr key dir =
  new Stream.cipher (new Stream.chacha20 key ?iv ?ctr)

end

(* The hmac construction *)

module HMAC(H: sig class h: hash  val blocksize: int end) =
  struct
    let hmac_pad key byte =
      let key =
        if String.length key > H.blocksize
        then hash_string (new H.h) key
        else key in
      let r = Bytes.make H.blocksize (Char.chr byte) in
      xor_string key 0 r 0 (String.length key);
      r
    class hmac key =
      object(self)
        inherit H.h as super
        initializer
          (let b = hmac_pad key 0x36 in
           self#add_substring b 0 (Bytes.length b);
           wipe_bytes b)
        method result =
          let h' = new H.h in
          let b = hmac_pad key 0x5C in
          h'#add_substring b 0 (Bytes.length b);
          wipe_bytes b;
          h'#add_string (super#result);
          let r = h'#result in
          h'#wipe;
          r
      end
  end

(* High-level entry points for MACs *)

module MAC = struct

module HMAC_SHA1 =
  HMAC(struct class h = Hash.sha1  let blocksize = 64 end)
module HMAC_SHA256 =
  HMAC(struct class h = Hash.sha256  let blocksize = 64 end)
module HMAC_SHA384 =
  HMAC(struct class h = Hash.sha384  let blocksize = 128 end)
module HMAC_SHA512 =
  HMAC(struct class h = Hash.sha512  let blocksize = 128 end)
module HMAC_RIPEMD160 = 
  HMAC(struct class h = Hash.ripemd160  let blocksize = 64 end)
module HMAC_MD5 =
  HMAC(struct class h = Hash.md5  let blocksize = 64 end)

let hmac_sha1 key = new HMAC_SHA1.hmac key
let hmac_sha256 key = new HMAC_SHA256.hmac key
let hmac_sha384 key = new HMAC_SHA384.hmac key
let hmac_sha512 key = new HMAC_SHA512.hmac key
let hmac_ripemd160 key = new HMAC_RIPEMD160.hmac key
let hmac_md5 key = new HMAC_MD5.hmac key

let blake2b sz key = new Hash.blake2b sz key
let blake2b512 key = new Hash.blake2b 512 key

let blake2s sz key = new Hash.blake2s sz key
let blake2s256 key = new Hash.blake2s 256 key

let blake3 sz key = new Hash.blake3 key sz
let blake3_256 key = new Hash.blake3 key 256

let aes ?iv ?pad key =
  new Block.mac ?iv ?pad (new Block.aes_encrypt key)
let des ?iv ?pad key =
  new Block.mac ?iv ?pad (new Block.des_encrypt key)
let triple_des ?iv ?pad key =
  new Block.mac ?iv ?pad (new Block.triple_des_encrypt key)
let des_final_triple_des ?iv ?pad key =
  let kl = String.length key in
  if kl <> 16 && kl <> 24 then raise (Error Wrong_key_size);
  let k1 = String.sub key 0 8 in
  let k2 = String.sub key 8 8 in
  let k3 = if kl = 24 then String.sub key 16 8 else k1 in
  let c1 = new Block.des_encrypt k1
  and c2 = new Block.des_decrypt k2
  and c3 = new Block.des_encrypt k3 in
  wipe_string k1; wipe_string k2; wipe_string k3;
  new Block.mac_final_triple ?iv ?pad c1 c2 c3

let aes_cmac ?iv key =
  let cipher = new Block.aes_encrypt key in
  let b = Bytes.make 16 '\000' in
  let l = Bytes.create 16 in
  cipher#transform b 0 l 0;           (* l = AES-128(K, 000...000 *)
  Bytes.set b 15 '\x87';              (* b = the Rb constant *)
  let k1 = Bytes.create 16 in
  shl1_bytes l 0 k1 0 16;
  if Char.code (Bytes.get l 0) land 0x80 > 0 then xor_bytes b 0 k1 0 16;
  let k2 = Bytes.create 16 in
  shl1_bytes k1 0 k2 0 16;
  if Char.code (Bytes.get k1 0) land 0x80 > 0 then xor_bytes b 0 k2 0 16;
  wipe_bytes l;
  new Block.cmac ?iv cipher k1 k2

class siphash sz key =
  object(self)
    val context =
      if String.length key = 16 && (sz = 64 || sz = 128)
      then siphash_init key (sz / 8)
      else raise (Error Wrong_key_size)
    method hash_size = sz / 8
    method add_substring src ofs len =
      if ofs < 0 || len < 0 || ofs > Bytes.length src - len
      then invalid_arg "siphash#add_substring";
      siphash_update context src ofs len
    method add_string src =
      siphash_update context (Bytes.unsafe_of_string src) 0 (String.length src)
    method add_char c =
      self#add_string (String.make 1 c)
    method add_byte b =
      self#add_char (Char.unsafe_chr b)
    method result = siphash_final context (sz / 8)
    method wipe =
      wipe_bytes context
  end

let siphash key = new siphash 64 key
let siphash128 key = new siphash 128 key

end

(* Authenticated encryption with associated data *)

module AEAD = struct

type direction = dir = Encrypt | Decrypt

(* AES-GCM *)

(* The H multiplier for GHASH is derived from the AES key by
   encrypting the all-zero block. *)

let ghash_multiplier (aes: Block.block_cipher) =
  let b = Bytes.make 16 '\000' in
  aes#transform b 0 b 0;
  ghash_init b

(* Add a block to the rolling MAC.  len must be between 0 and 16.
   If less than 16, we logically pad with zeros at the end,
   i.e. we "xor with zero" (= keep unchanged) the MAC bytes
   between len and 16. *)

let ghash_block h mac buf ofs len =
  xor_bytes buf ofs mac 0 len;
  ghash_mult h mac

let ghash_block_s h mac buf ofs len =
  xor_string buf ofs mac 0 len;
  ghash_mult h mac

(* Hash the given string, with zero padding.  Used for the non-encrypted
   authenticated data and for counter generation. *)

let ghash_string h msg =
  let mac = Bytes.make 16 '\000' in
  let l = String.length msg in
  let i = ref 0 in
  while !i + 16 <= l do
    ghash_block_s h mac msg !i 16;
    i := !i + 16
  done;
  if !i < l then ghash_block_s h mac msg !i (l - !i);
  mac

(* Produce the final authentication tag *)

let ghash_final h mac headerlen cipherlen e0 =
  let buf = Bytes.create 16 in
  (* Hash the extra block containing the lengths *)
  Bytes.set_int64_be buf 0 (Int64.mul headerlen 8L); (* in bits *)
  Bytes.set_int64_be buf 8 (Int64.mul cipherlen 8L); (* in bits *)
  ghash_block h mac buf 0 16;
  (* Authentication tag = final MAC xor encryption of the IV *)
  Bytes.blit mac 0 buf 0 16;
  xor_bytes e0 0 buf 0 16;
  Bytes.to_string buf

(* Initial value of the counter *)

let counter0 h iv =
  if String.length iv = 12 then
    Bytes.of_string (iv ^ "\000\000\000\001")
  else begin
    let mac = ghash_string h iv in
    let buf = Bytes.make 16 '\000' in
    Bytes.set_int64_be buf 8 (Int64.mul (Int64.of_int (String.length iv)) 8L);
    ghash_block h mac buf 0 16;
    mac
  end

(* Encryption of the initial counter *)

let enc_initial_counter (aes: Block.block_cipher) counter0 =
  let b = Bytes.create 16 in
  aes#transform counter0 0 b 0;
  b

(* CTR encryption / decryption *)

let ctr_enc_dec (aes: Block.block_cipher) ctr buf src soff dst doff len =
  Block.increment_counter ctr 12 15;
  aes#transform ctr 0 buf 0;
  xor_bytes src soff buf 0 len;
  Bytes.blit buf 0 dst doff len

class aes_gcm_encrypt ?(header = "") ~iv key =
  (* The AES block cipher *)
  let aes = new Block.aes_encrypt key in
  (* The multiplier for the GHASH MAC *)
  let h = ghash_multiplier aes in
  (* The counter for use in CTR mode. *)
  let ctr = counter0 h iv in
  (* The encryption of the initial counter, to be used for the final MAC *)
  let e0 = enc_initial_counter aes ctr in
  (* The current MAC, initialized with the header
     (the non-encrypted authenticated data) *)
  let mac = ghash_string h header in
  (* Lengths of the authenticated data and the encrypted data *)
  let headerlen = Int64.of_int (String.length header)
  and cipherlen = ref 0L in
  (* A wrapper around the block cipher that 
     - performs encryption in CTR mode
     - updates the MAC
     - updates the length of encrypted data *)
  let enc_wrapped : Block.block_cipher = 
    let buf = Bytes.create 16 in
    object
      method blocksize = 16
      method wipe = aes#wipe
      method transform src soff dst doff =
        ctr_enc_dec aes ctr buf src soff dst doff 16;
        ghash_block h mac dst doff 16;
        cipherlen := Int64.(add !cipherlen 16L);
        if !cipherlen > 0xfffffffe0L then raise (Error Message_too_long)
    end in
  object(self)
    inherit (Block.cipher enc_wrapped)
    method input_block_size = 1
    method output_block_size = 1
    method tag_size = 16
    method finish_and_get_tag =
      if used > 0 then begin
        let buf = Bytes.create 16 in
        (* Encrypt final block *)
        self#ensure_capacity used;
        ctr_enc_dec aes ctr buf ibuf 0 obuf oend used;
        (* Hash final block padded with zeros *)
        ghash_block h mac obuf oend used;
        oend <- oend + used;
        cipherlen := Int64.(add !cipherlen (of_int used));
        if !cipherlen > 0xfffffffe0L then raise (Error Message_too_long)
      end;
      (* Produce authentication tag *)
      ghash_final h mac headerlen !cipherlen e0
  end

class aes_gcm_decrypt ?(header = "") ~iv key =
  (* The AES block cipher *)
  let aes = new Block.aes_encrypt key in
  (* The multiplier for the GHASH MAC *)
  let h = ghash_multiplier aes in
  (* The counter for use in CTR mode. *)
  let ctr = counter0 h iv in
  (* The encryption of the initial counter, to be used for the final MAC *)
  let e0 = enc_initial_counter aes ctr in
  (* The current MAC, initialized with the header
     (the non-encrypted authenticated data) *)
  let mac = ghash_string h header in
  (* Lengths of the authenticated data and the encrypted data *)
  let headerlen = Int64.of_int (String.length header)
  and cipherlen = ref 0L in
  (* A wrapper around the block cipher that 
     - updates the MAC
     - performs decryption in CTR mode
     - updates the length of encrypted data *)
  let dec_wrapped : Block.block_cipher = 
    let buf = Bytes.create 16 in
    object
      method blocksize = 16
      method wipe = aes#wipe
      method transform src soff dst doff =
        ghash_block h mac src soff 16;
        ctr_enc_dec aes ctr buf src soff dst doff 16;
        cipherlen := Int64.(add !cipherlen 16L)
    end in
  object(self)
    inherit (Block.cipher dec_wrapped)
    method input_block_size = 1
    method output_block_size = 1
    method tag_size = 16
    method finish_and_get_tag =
      if used > 0 then begin
        let buf = Bytes.create 16 in
        (* Hash final block padded with zeros *)
        ghash_block h mac ibuf 0 used;
        (* Decrypt final block *)
        self#ensure_capacity used;
        ctr_enc_dec aes ctr buf ibuf 0 obuf oend used;
        oend <- oend + used;
        cipherlen := Int64.(add !cipherlen (of_int used))
      end;
      (* Produce authentication tag *)
      ghash_final h mac headerlen !cipherlen e0
  end

let aes_gcm ?header ~iv key dir =
  match dir with
  | Encrypt -> (new aes_gcm_encrypt ?header ~iv key :> authenticated_transform)
  | Decrypt -> (new aes_gcm_decrypt ?header ~iv key :> authenticated_transform)

(* Chacha20-Poly1305 *)

let poly1305_update_pad h n =
  let n = (0x10 - n) land 0xF in
  if n > 0 then poly1305_update h (Bytes.make n '\000') 0 n

let poly1305_init_hash cha header =
  let buf = Bytes.make 64 '\000' in
  cha#transform buf 0 buf 0 64;
  let h = poly1305_init buf in  (* only the first 32 bytes are used *)
  wipe_bytes buf;
  poly1305_update h (Bytes.unsafe_of_string header) 0 (String.length header);
  (* Pad header to a multiple of 16 bytes *)
  poly1305_update_pad h (String.length header land 0xF);
  h

let poly1305_finish_and_get_tag h headerlen cipherlen =
  (* Pad ciphertext to a multiple of 16 bytes *)
  poly1305_update_pad h Int64.(to_int (logand cipherlen 0xFL));
  (* Add lengths as 64-bit little-endian numbers *)
  let buf = Bytes.create 16 in
  Bytes.set_int64_le buf 0 headerlen;
  Bytes.set_int64_le buf 8 cipherlen;
  poly1305_update h buf 0 16;
  (* The final hash is the authentication tag *)
  poly1305_final h

class chapoly_encrypt ?(header = "") ~iv key =
  (* The Chacha20 stream cipher *)
  let cha = new Stream.chacha20 ~iv key in
  (* The Poly1305 hash *)
  let h = poly1305_init_hash cha header in
  (* Lengths of the authenticated data and the encrypted data *)
  let headerlen = Int64.of_int (String.length header)
  and cipherlen = ref 0L in
  (* Maximum length for encrypted data *)
  let maxlen =
    if String.length iv = 12 then 0x4000000000L else Int64.max_int in
  (* The stream cipher that wraps Chacha20 with hash updates *)
  let enc = object
    method transform src soff dst doff len =
      cha#transform src soff dst doff len;
      poly1305_update h dst doff len;
      cipherlen := Int64.(add !cipherlen (of_int len));
      if !cipherlen > maxlen then raise (Error Message_too_long)
    method wipe =
      cha#wipe; wipe_bytes h
  end in
  object(self)
    inherit (Stream.cipher enc)
    method input_block_size = 1
    method output_block_size = 1
    method tag_size = 16
    method finish_and_get_tag =
      poly1305_finish_and_get_tag h headerlen !cipherlen
  end

class chapoly_decrypt ?(header = "") ~iv key =
  (* The Chacha20 stream cipher *)
  let cha = new Stream.chacha20 ~iv key in
  (* The Poly1305 hash *)
  let h = poly1305_init_hash cha header in
  (* Lengths of the authenticated data and the encrypted data *)
  let headerlen = Int64.of_int (String.length header)
  and cipherlen = ref 0L in
  (* The stream cipher that wraps Chacha20 with hash updates *)
  let enc = object
    method transform src soff dst doff len =
      poly1305_update h src soff len;
      cha#transform src soff dst doff len;
      cipherlen := Int64.(add !cipherlen (of_int len))
    method wipe =
      cha#wipe; wipe_bytes h
  end in
  object(self)
    inherit (Stream.cipher enc)
    method input_block_size = 1
    method output_block_size = 1
    method tag_size = 16
    method finish_and_get_tag =
      poly1305_finish_and_get_tag h headerlen !cipherlen
  end

let chacha20_poly1305 ?header ~iv key dir =
  match dir with
  | Encrypt -> (new chapoly_encrypt ?header ~iv key :> authenticated_transform)
  | Decrypt -> (new chapoly_decrypt ?header ~iv key :> authenticated_transform)

end

(* Random number generation *)

module Random = struct

class type rng =
  object
    method random_bytes: bytes -> int -> int -> unit
    method wipe: unit
  end

let string rng len =
  let res = Bytes.create len in
  rng#random_bytes res 0 len;
  Bytes.unsafe_to_string res

type system_rng_handle
external get_system_rng: unit -> system_rng_handle = "caml_get_system_rng"
external close_system_rng: system_rng_handle -> unit = "caml_close_system_rng"
external system_rng_random_bytes: 
  system_rng_handle -> bytes -> int -> int -> bool
  = "caml_system_rng_random_bytes"

class system_rng =
  object(self)
    val h = get_system_rng ()
    method random_bytes buf ofs len =
      if ofs < 0 || len < 0 || ofs > Bytes.length buf - len
      then invalid_arg "random_bytes";
      if system_rng_random_bytes h buf ofs len
      then ()
      else raise(Error Entropy_source_closed)
    method wipe =
      close_system_rng h
  end

let system_rng () =
  try new system_rng with Not_found -> raise(Error No_entropy_source)

class device_rng filename =
  object(self)
    val fd = Unix.openfile filename [Unix.O_RDONLY; Unix.O_CLOEXEC] 0
    method random_bytes buf ofs len =
      if len > 0 then begin    
        let n = Unix.read fd buf ofs len in
        if n = 0 then raise(Error Entropy_source_closed);
        if n < len then self#random_bytes buf (ofs + n) (len - n)
      end
    method wipe =
      Unix.close fd
  end

let device_rng filename = new device_rng filename

external hardware_rng_available: unit -> bool = "caml_hardware_rng_available"
external hardware_rng_random_bytes: bytes -> int -> int -> bool = "caml_hardware_rng_random_bytes"

class hardware_rng =
  object
    method random_bytes buf ofs len =
      if ofs < 0 || len < 0 || ofs > Bytes.length buf - len      
      then invalid_arg "hardware_rng#random_bytes";
      if not (hardware_rng_random_bytes buf ofs len)
      then raise (Error Entropy_source_closed)
    method wipe =
      ()
  end

let hardware_rng () =
  if hardware_rng_available ()
  then new hardware_rng
  else raise (Error No_entropy_source)

class no_rng =
  object
    method random_bytes (buf:bytes) (ofs:int) (len:int) : unit = 
      raise (Error No_entropy_source)
    method wipe = ()
  end

let secure_rng =
  try
    new system_rng
  with Not_found ->
  try
    new device_rng "/dev/random"
  with Unix.Unix_error(_,_,_) ->
    if hardware_rng_available ()
    then new hardware_rng
    else new no_rng

class pseudo_rng seed =
  let _ = if String.length seed < 16 then raise (Error Seed_too_short) in
  object (self)
    val ckey =
      let l = String.length seed in
      chacha20_cook_key 
        (if l >= 32 then String.sub seed 0 32
         else if l > 16 then seed ^ String.make (32 - l) '\000'
         else seed)
        (Bytes.make 8 '\000') 0L
    method random_bytes buf ofs len =
      if len < 0 || ofs < 0 || ofs > Bytes.length buf - len
      then invalid_arg "pseudo_rng#random_bytes"
      else chacha20_extract ckey buf ofs len
    method wipe =
      wipe_bytes ckey; wipe_string seed
end

let pseudo_rng seed = new pseudo_rng seed

class pseudo_rng_aes_ctr seed =
  let _ = if String.length seed < 16 then raise (Error Seed_too_short) in
  object (self)
    val cipher = new Block.aes_encrypt (String.sub seed 0 16)
    val ctr = Bytes.make 16 '\000'
    val obuf = Bytes.create 16
    val mutable opos = 16

    method random_bytes buf ofs len =
      if len > 0 then begin
        if opos >= 16 then begin
          (* Encrypt the counter *)
          cipher#transform ctr 0 obuf 0;
          (* Increment the counter *)
          Block.increment_counter ctr 0 15;
          (* We have 16 fresh bytes of pseudo-random data *)
          opos <- 0
        end;
        let r = min (16 - opos) len in
        Bytes.blit obuf opos buf ofs r;
        opos <- opos + r;
        if r < len then self#random_bytes buf (ofs + r) (len - r)
      end

    method wipe =
      wipe_bytes obuf; wipe_string seed
  end

let pseudo_rng_aes_ctr seed = new pseudo_rng_aes_ctr seed

end

(* RSA operations *)

module Bn = CryptokitBignum

module RSA = struct

type key =
  { size: int;
    n: string;
    e: string;
    d: string;
    p: string;
    q: string;
    dp: string;
    dq: string;
    qinv: string }

let wipe_key k =
  wipe_string k.n;
  wipe_string k.e;
  wipe_string k.d;
  wipe_string k.p;
  wipe_string k.q;
  wipe_string k.dp;
  wipe_string k.dq;
  wipe_string k.qinv

let encrypt key msg =
  let msg = Bn.of_bytes msg in
  let n = Bn.of_bytes key.n in
  let e = Bn.of_bytes key.e in
  if Bn.compare msg n >= 0 then raise (Error Message_too_long);
  let r = Bn.mod_power msg e n in
  let s = Bn.to_bytes ~numbits:key.size r in
  Bn.wipe msg; Bn.wipe n; Bn.wipe e; Bn.wipe r;
  s

let unwrap_signature = encrypt

let decrypt key msg =
  let msg = Bn.of_bytes msg in
  let n = Bn.of_bytes key.n in
  let d = Bn.of_bytes key.d in
  if Bn.compare msg n >= 0 then raise (Error Message_too_long);
  let r = Bn.mod_power msg d n in
  let s = Bn.to_bytes ~numbits:key.size r in
  Bn.wipe msg; Bn.wipe n; Bn.wipe d; Bn.wipe r;
  s

let sign = decrypt

let decrypt_CRT key msg =
  let msg = Bn.of_bytes msg in
  let n = Bn.of_bytes key.n in
  let p = Bn.of_bytes key.p in
  let q = Bn.of_bytes key.q in
  let dp = Bn.of_bytes key.dp in
  let dq = Bn.of_bytes key.dq in
  let qinv = Bn.of_bytes key.qinv in
  if Bn.compare msg n >= 0 then raise (Error Message_too_long);
  let r = Bn.mod_power_CRT msg p q dp dq qinv in
  let s = Bn.to_bytes ~numbits:key.size r in
  Bn.wipe msg; Bn.wipe n; Bn.wipe p; Bn.wipe q;
  Bn.wipe dp; Bn.wipe dq; Bn.wipe qinv; Bn.wipe r;
  s

let sign_CRT = decrypt_CRT

let new_key ?(rng = Random.secure_rng) ?e numbits =
  if numbits < 32 || numbits land 1 > 0 then raise(Error Wrong_key_size);
  let numbits2 = numbits / 2 in
  (* Generate primes p, q with numbits / 2 digits.
     If fixed exponent e, make sure gcd(p-1,e) = 1 and
     gcd(q-1,e) = 1. *)
  let rec gen_factor nbits =
    let n = Bn.random_prime ~rng:(rng#random_bytes) nbits in
    match e with
      None -> n
    | Some e ->
        if Bn.relative_prime (Bn.sub n Bn.one) (Bn.of_int e)
        then n
        else gen_factor nbits in
  (* Make sure p > q *)
  let rec gen_factors nbits =
    let p = gen_factor nbits
    and q = gen_factor nbits in
    let cmp = Bn.compare p q in
    if cmp = 0 then gen_factors nbits else
    if cmp < 0 then (q, p) else (p, q) in
  let (p, q) = gen_factors numbits2 in
  (* p1 = p - 1 and q1 = q - 1 *)
  let p1 = Bn.sub p Bn.one
  and q1 = Bn.sub q Bn.one in
  (* If no fixed exponent specified, generate random exponent e such that
     gcd(p-1,e) = 1 and gcd(q-1,e) = 1 *)
  let e =
    match e with
      Some e -> Bn.of_int e
    | None ->
        let rec gen_exponent () =
          let n = Bn.random ~rng:(rng#random_bytes) numbits in
          if Bn.relative_prime n p1 && Bn.relative_prime n q1
          then n
          else gen_exponent () in
        gen_exponent () in
  (* n = pq *)
  let n = Bn.mult p q in
  (* d = e^-1 mod (p-1)(q-1) *)
  let d = Bn.mod_inv e (Bn.mult p1 q1) in
  (* dp = d mod p-1 and dq = d mod q-1 *)
  let dp = Bn.mod_ d p1 and dq = Bn.mod_ d q1 in
  (* qinv = q^-1 mod p *)
  let qinv = Bn.mod_inv q p in
  (* Build key *)
  let res =
    { size = numbits;
      n = Bn.to_bytes ~numbits:numbits n;
      e = Bn.to_bytes ~numbits:numbits e;
      d = Bn.to_bytes ~numbits:numbits d;
      p = Bn.to_bytes ~numbits:numbits2 p;
      q = Bn.to_bytes ~numbits:numbits2 q;
      dp = Bn.to_bytes ~numbits:numbits2 dp;
      dq = Bn.to_bytes ~numbits:numbits2 dq;
      qinv = Bn.to_bytes ~numbits:numbits2 qinv } in
  Bn.wipe n; Bn.wipe e; Bn.wipe d;
  Bn.wipe p; Bn.wipe q;
  Bn.wipe p1; Bn.wipe q1;
  Bn.wipe dp; Bn.wipe dq; Bn.wipe qinv;
  res

end

(* Diffie-Hellman key agreement *)

module DH = struct

type parameters =
  { p: string;
    g: string;
    privlen: int }

let new_parameters ?(rng = Random.secure_rng) ?(privlen = 160) numbits =
  if numbits < 32 || numbits <= privlen then raise(Error Wrong_key_size);
  let np = Bn.random_prime ~rng:(rng#random_bytes) numbits in
  let rec find_generator () =
    let g = Bn.random ~rng:(rng#random_bytes) (numbits - 1) in
    if Bn.compare g Bn.one <= 0 then find_generator() else g in
  let ng = find_generator () in
  { p = Bn.to_bytes ~numbits np;
    g = Bn.to_bytes ~numbits ng;
    privlen = privlen }

type private_secret = Bn.t

let private_secret ?(rng = Random.secure_rng) params =
  Bn.random ~rng:(rng#random_bytes) params.privlen

let message params privsec =
  Bn.to_bytes ~numbits:(String.length params.p * 8)
    (Bn.mod_power (Bn.of_bytes params.g) privsec (Bn.of_bytes params.p))

let shared_secret params privsec othermsg =
  let res =
    Bn.to_bytes ~numbits:(String.length params.p * 8)
      (Bn.mod_power (Bn.of_bytes othermsg) privsec (Bn.of_bytes params.p))
  in Bn.wipe privsec; res

let derive_key ?(diversification = "") sharedsec numbytes =
  let result = Bytes.create numbytes in
  let rec derive pos counter =
    if pos < numbytes then begin
      let h =
        hash_string (Hash.sha256()) 
                    (diversification ^ sharedsec ^ string_of_int counter) in
      String.blit h 0 result pos (min (String.length h) (numbytes - pos));
      wipe_string h;
      derive (pos + String.length h) (counter + 1)
    end in
  derive 0 1;
  Bytes.unsafe_to_string result

end

(* Base64 encoding *)

module Base64 = struct

let base64_conv_table =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

class encode multiline padding =
  object (self)
    method input_block_size = 1
    method output_block_size = 1

    inherit buffered_output 256 as output_buffer

    val ibuf = Bytes.create 3
    val mutable ipos = 0
    val mutable ocolumn = 0

    method put_char c =
      Bytes.set ibuf ipos c;
      ipos <- ipos + 1;
      if ipos = 3 then begin
        let b0 = Char.code (Bytes.get ibuf 0)
        and b1 = Char.code (Bytes.get ibuf 1)
        and b2 = Char.code (Bytes.get ibuf 2) in
        self#ensure_capacity 4;
        Bytes.set obuf oend     base64_conv_table.[b0 lsr 2];
        Bytes.set obuf (oend+1) base64_conv_table.[(b0 land 3) lsl 4 + (b1 lsr 4)];
        Bytes.set obuf (oend+2) base64_conv_table.[(b1 land 15) lsl 2 + (b2 lsr 6)];
        Bytes.set obuf (oend+3) base64_conv_table.[b2 land 63];
        oend <- oend + 4;
        ipos <- 0;
        ocolumn <- ocolumn + 4;
        if multiline && ocolumn >= 72 then begin
          self#ensure_capacity 1;
          Bytes.set obuf oend '\n';
          oend <- oend + 1;
          ocolumn <- 0
        end 
      end

    method put_substring s ofs len =
      for i = ofs to ofs + len - 1 do self#put_char (Bytes.get s i) done

    method put_string s =
      String.iter self#put_char s

    method put_byte b = self#put_char (Char.chr b)

    method flush : unit = raise (Error Wrong_data_length)

    method finish =
      begin match ipos with
        1 ->
          self#ensure_capacity 2;
          let b0 = Char.code (Bytes.get ibuf 0) in
          Bytes.set obuf oend     base64_conv_table.[b0 lsr 2];
          Bytes.set obuf (oend+1) base64_conv_table.[(b0 land 3) lsl 4];
          oend <- oend + 2
      | 2 ->
          self#ensure_capacity 3;
          let b0 = Char.code (Bytes.get ibuf 0)
          and b1 = Char.code (Bytes.get ibuf 1) in
          Bytes.set obuf oend     base64_conv_table.[b0 lsr 2];
          Bytes.set obuf (oend+1) base64_conv_table.[(b0 land 3) lsl 4 + (b1 lsr 4)];
          Bytes.set obuf (oend+2) (base64_conv_table.[(b1 land 15) lsl 2]);
          oend <- oend + 3
      | _ -> ()
      end;
      if multiline || padding then begin
        let num_equals =
          match ipos with 1 -> 2 | 2 -> 1 | _ -> 0 in
        self#ensure_capacity num_equals;
        Bytes.fill obuf oend num_equals '=';
        oend <- oend + num_equals
      end;
      if multiline && ocolumn > 0 then begin
        self#ensure_capacity 1;
        Bytes.set obuf oend '\n';
        oend <- oend + 1
      end;
      ocolumn <- 0

    method wipe =
      wipe_bytes ibuf; output_buffer#wipe
  end

let encode_multiline () = new encode true true
let encode_compact () = new  encode false false
let encode_compact_pad () = new encode false true

let base64_decode_char c =
  match c with
    'A' .. 'Z' -> Char.code c - 65
  | 'a' .. 'z' -> Char.code c - 97 + 26
  | '0' .. '9' -> Char.code c - 48 + 52
  | '+' -> 62
  | '/' -> 63
  | ' '|'\t'|'\n'|'\r' -> -1
  | _   -> raise (Error Bad_encoding)

class decode =
  object (self)
    inherit buffered_output 256 as output_buffer

    method input_block_size = 1
    method output_block_size = 1

    val ibuf = Array.make 4 0
    val mutable ipos = 0
    val mutable finished = false

    method put_char c =
      if c = '=' then finished <- true else begin
        let n = base64_decode_char c in
        if n >= 0 then begin
          if finished then raise(Error Bad_encoding);
          ibuf.(ipos) <- n;
          ipos <- ipos + 1;
          if ipos = 4 then begin
            self#ensure_capacity 3;
            Bytes.set obuf oend     (Char.chr(ibuf.(0) lsl 2 + ibuf.(1) lsr 4));
            Bytes.set obuf (oend+1) (Char.chr((ibuf.(1) land 15) lsl 4 + ibuf.(2) lsr 2));
            Bytes.set obuf (oend+2) (Char.chr((ibuf.(2) land 3) lsl 6 + ibuf.(3)));
            oend <- oend + 3;
            ipos <- 0
          end
        end
      end

    method put_substring s ofs len =
      for i = ofs to ofs + len - 1 do self#put_char (Bytes.get s i) done

    method put_string s =
      String.iter self#put_char s

    method put_byte b = self#put_char (Char.chr b)

    method flush : unit = raise (Error Wrong_data_length)

    method finish =
      finished <- true;
      match ipos with
      | 1 -> raise(Error Bad_encoding)
      | 2 ->
          self#ensure_capacity 1;
          Bytes.set obuf oend     (Char.chr(ibuf.(0) lsl 2 + ibuf.(1) lsr 4));
          oend <- oend + 1
      | 3 ->
          self#ensure_capacity 2;
          Bytes.set obuf oend     (Char.chr(ibuf.(0) lsl 2 + ibuf.(1) lsr 4));
          Bytes.set obuf (oend+1) (Char.chr((ibuf.(1) land 15) lsl 4 + ibuf.(2) lsr 2));
          oend <- oend + 2
      | _ -> ()

    method wipe =
      Array.fill ibuf 0 4 0; output_buffer#wipe
  end

let decode () = new decode

end

(* Hexadecimal encoding *)

module Hexa = struct

let hex_conv_table = "0123456789abcdef"

class encode =
  object (self)
    method input_block_size = 1
    method output_block_size = 1

    inherit buffered_output 256 as output_buffer

    method put_byte b =
      self#ensure_capacity 2;
      Bytes.set obuf oend     (hex_conv_table.[b lsr 4]);
      Bytes.set obuf (oend+1) (hex_conv_table.[b land 0xF]);
      oend <- oend + 2

    method put_char c = self#put_byte (Char.code c)

    method put_substring s ofs len =
      for i = ofs to ofs + len - 1 do self#put_char (Bytes.get s i) done

    method put_string s =
      String.iter self#put_char s

    method flush = ()
    method finish = ()

    method wipe = output_buffer#wipe
  end

let encode () = new encode

let hex_decode_char c =
  match c with
  | '0' .. '9' -> Char.code c - 48
  | 'A' .. 'F' -> Char.code c - 65 + 10
  | 'a' .. 'f' -> Char.code c - 97 + 10
  | ' '|'\t'|'\n'|'\r' -> -1
  | _   -> raise (Error Bad_encoding)

class decode =
  object (self)
    inherit buffered_output 256 as output_buffer

    method input_block_size = 1
    method output_block_size = 1

    val ibuf = Array.make 2 0
    val mutable ipos = 0

    method put_char c =
      let n = hex_decode_char c in
      if n >= 0 then begin
        ibuf.(ipos) <- n;
        ipos <- ipos + 1;
        if ipos = 2 then begin
          self#ensure_capacity 1;
          Bytes.set obuf oend (Char.chr(ibuf.(0) lsl 4 lor ibuf.(1)));
          oend <- oend + 1;
          ipos <- 0
        end
      end

    method put_substring s ofs len =
      for i = ofs to ofs + len - 1 do self#put_char (Bytes.get s i) done

    method put_string s =
      String.iter self#put_char s

    method put_byte b = self#put_char (Char.chr b)

    method flush =
      if ipos <> 0 then raise(Error Wrong_data_length)

    method finish =
      if ipos <> 0 then raise(Error Bad_encoding)

    method wipe =
      Array.fill ibuf 0 2 0; output_buffer#wipe
  end

let decode () = new decode

end

(* Compression *)

module Zlib = struct

type stream

type flush_command =
    Z_NO_FLUSH
  | Z_SYNC_FLUSH
  | Z_FULL_FLUSH
  | Z_FINISH

external deflate_init: int -> bool -> stream = "caml_zlib_deflateInit"
external deflate:
  stream -> bytes -> int -> int -> bytes -> int -> int -> flush_command
         -> bool * int * int
  = "caml_zlib_deflate_bytecode" "caml_zlib_deflate"
external deflate_end: stream -> unit = "caml_zlib_deflateEnd"

external inflate_init: bool -> stream = "caml_zlib_inflateInit"
external inflate:
  stream -> bytes -> int -> int -> bytes -> int -> int -> flush_command
         -> bool * int * int
  = "caml_zlib_inflate_bytecode" "caml_zlib_inflate"
external inflate_end: stream -> unit = "caml_zlib_inflateEnd"

class compress level write_zlib_header =
  object(self)
    val zs = deflate_init level write_zlib_header
    
    inherit buffered_output 512 as output_buffer

    method input_block_size = 1
    method output_block_size = 1

    method put_substring src ofs len =
      if len > 0 then begin
        self#ensure_capacity 256;
        let (_, used_in, used_out) =
          deflate zs
                  src ofs len
                  obuf oend (Bytes.length obuf - oend)
                  Z_NO_FLUSH in
        oend <- oend + used_out;
        if used_in < len
        then self#put_substring src (ofs + used_in) (len - used_in)
      end

    method put_string s =
      self#put_substring (Bytes.unsafe_of_string s) 0 (String.length s)

    method put_char c = self#put_string (String.make 1 c)

    method put_byte b = self#put_char (Char.chr b)

    method flush =
      self#ensure_capacity 256;
      let (_, _, used_out) =
         deflate zs
                 (Bytes.unsafe_of_string "") 0 0
                 obuf oend (Bytes.length obuf - oend)
                 Z_SYNC_FLUSH in
      oend <- oend + used_out;
      if oend = Bytes.length obuf then self#flush

    method finish =
      self#ensure_capacity 256;
      let (finished, _, used_out) =
         deflate zs
                 (Bytes.unsafe_of_string "") 0 0
                 obuf oend (Bytes.length obuf - oend)
                 Z_FINISH in
      oend <- oend + used_out;
      if finished then deflate_end zs else self#finish

    method wipe =
      output_buffer#wipe
end

let compress ?(level = 6) ?(write_zlib_header = false) () = new compress level write_zlib_header 

class uncompress expect_zlib_header =
  object(self)
    val zs = inflate_init expect_zlib_header
    
    inherit buffered_output 512 as output_buffer

    method input_block_size = 1
    method output_block_size = 1

    method put_substring src ofs len =
      if len > 0 then begin
        self#ensure_capacity 256;
        let (finished, used_in, used_out) =
          inflate zs
                  src ofs len
                  obuf oend (Bytes.length obuf - oend)
                  Z_SYNC_FLUSH in
        oend <- oend + used_out;
        if used_in < len then begin
          if finished then
            raise(Error(Compression_error("Zlib.uncompress",
               "garbage at end of compressed data")));
          self#put_substring src (ofs + used_in) (len - used_in)
        end
      end

    method put_string s =
      self#put_substring (Bytes.unsafe_of_string s) 0 (String.length s)

    method put_char c = self#put_string (String.make 1 c)

    method put_byte b = self#put_char (Char.chr b)

    method flush = ()

    method finish =
      let rec do_finish first_finish =
        self#ensure_capacity 256;
        let (finished, _, used_out) =
           inflate zs
                   (Bytes.unsafe_of_string " ") 0 (if first_finish then 1 else 0)
                   obuf oend (Bytes.length obuf - oend)
                   Z_SYNC_FLUSH in
        oend <- oend + used_out;
        if not finished then do_finish false in
      do_finish true; inflate_end zs

    method wipe =
      output_buffer#wipe
end

let uncompress ?(expect_zlib_header = false) () = new uncompress expect_zlib_header

end

(* Utilities *)

let xor_bytes src src_ofs dst dst_ofs len =
  if len < 0
  || src_ofs < 0 || src_ofs > Bytes.length src - len
  || dst_ofs < 0 || dst_ofs > Bytes.length dst - len
  then invalid_arg "xor_bytes";
  xor_bytes src src_ofs dst dst_ofs len
  
let xor_string src src_ofs dst dst_ofs len =
  if len < 0
  || src_ofs < 0 || src_ofs > String.length src - len
  || dst_ofs < 0 || dst_ofs > Bytes.length dst - len
  then invalid_arg "xor_string";
  xor_string src src_ofs dst dst_ofs len
  
let mod_power a b c =
  Bn.to_bytes ~numbits:(String.length c * 8)
    (Bn.mod_power (Bn.of_bytes a) (Bn.of_bytes b) (Bn.of_bytes c))
let mod_mult a b c =
  Bn.to_bytes ~numbits:(String.length c * 8)
    (Bn.mod_ (Bn.mult (Bn.of_bytes a) (Bn.of_bytes b))
             (Bn.of_bytes c))