-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathcryptokit.mli
1580 lines (1342 loc) · 74.3 KB
/
cryptokit.mli
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
(***********************************************************************)
(* *)
(* 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. *)
(* *)
(***********************************************************************)
(** The Cryptokit library provides a variety of cryptographic primitives
that can be used to implement cryptographic protocols in
security-sensitive applications.
The primitives provided include:
- Symmetric-key ciphers: AES, Chacha20, DES, Triple-DES, Blowfish, ARCfour,
in ECB, CBC, CFB, OFB and counter modes.
- Authenticated encryption: AES-GCM, Chacha20-Poly1305
- Public-key cryptography: RSA encryption, Diffie-Hellman key agreement.
- Hash functions and MACs: SHA-3, SHA-2, BLAKE2, RIPEMD-160,
and MACs based on AES, DES, and SipHash.
- Random number generation.
- Encodings and compression: base 64, hexadecimal, Zlib compression.
*)
(** {1 General-purpose abstract interfaces} *)
(** A {i transform} is an arbitrary mapping from sequences of characters
to sequences of characters. Examples of transforms include
ciphering, deciphering, compression, decompression, and encoding
of binary data as text. Input data to a transform is provided
by successive calls to the methods [put_substring], [put_string],
[put_char] or [put_byte]. The result of transforming the input
data is buffered internally, and can be obtained via the
[get_string], [get_substring], [get_char] and [get_byte] methods. *)
class type transform =
object
method put_substring: bytes -> int -> int -> unit
(** [put_substring b pos len] processes [len] characters of
byte sequence [b], starting at character number [pos],
through the transform. *)
method put_string: string -> unit
(** [put_string str] processes all characters of string [str]
through the transform. *)
method put_char: char -> unit
(** [put_char c] processes character [c] through the transform. *)
method put_byte: int -> unit
(** [put_byte b] processes the character having code [b]
through the transform. [b] must be between [0] and [255]
inclusive. *)
method finish: unit
(** Call method [finish] to indicate that no further data will
be processed through the transform. This causes the transform
to flush its internal buffers and perform all appropriate
finalization actions, e.g. add final padding. Raise [Error
Wrong_data_length] if the total length of input data
provided via the [put_*] methods is not an integral number
of the input block size (see
{!Cryptokit.transform.input_block_size}). After calling
[finish], the transform can no longer accept additional
data. Hence, do not call any of the [put_*] methods nor
[flush] after calling [finish]. *)
method flush: unit
(** [flush] causes the transform to flush its internal buffers
and make all output processed up to this point available through
the [get_*] methods.
Raise [Error Wrong_data_length] if the total length
of input data provided via the [put_*] methods is not
an integral number of the input block size
(see {!Cryptokit.transform.input_block_size}).
(For padded block ciphers, the input block size used here
is that of the underlying block cipher, without the padding.)
Unlike method [finish], method [flush] does not add final
padding and leaves the transform in a state where it can
still accept more input. *)
method available_output: int
(** Return the number of characters of output currently available.
The output can be recovered with the [get_*] methods. *)
method get_string: string
(** Return a character string containing all output characters
available at this point. The internal output buffer is emptied;
in other terms, all currently available output is consumed
(and returned to the caller) by a call to [get_string]. *)
method get_substring: bytes * int * int
(** Return a triple [(buf,pos,len)], where [buf] is the internal
output buffer for the transform, [pos] the position of the
first character of available output, and [len] the number of
characters of available output. The byte array [buf] will be
modified later, so the caller must immediately copy
characters [pos] to [pos+len-1] of [buf] to some other
location. The internal output buffer is emptied;
in other terms, all currently available output is consumed
(and returned to the caller) by a call to [get_substring]. *)
method get_char: char
(** Return the first character of output, and remove it from the
internal output buffer. Raise [End_of_file] if no output
is currently available. *)
method get_byte: int
(** Return the code of the first character of output,
and remove it from the internal output buffer.
Raise [End_of_file] if no output is currently available. *)
method input_block_size: int
(** Some transforms (e.g. unpadded block ciphers) process
input data by blocks of several characters. This method
returns the size of input blocks for the current transform.
If [input_block_size > 1], the user of the transform
must ensure that the total length of input data provided
between calls to [flush] and [finish] is an integral
multiple of [input_block_size].
If [input_block_size = 1], the transform can accept
input data of arbitrary length. *)
method output_block_size: int
(** Some transforms (e.g. block ciphers) always produce output
data by blocks of several characters. This method
returns the size of output blocks for the current transform.
If [output_block_size > 1], the total length of output data
produced by the transform is always an integral multiple
of [output_block_size].
If [output_block_size = 1], the transform produces output data
of arbitrary length. *)
method wipe: unit
(** Erase all internal buffers and data structures of this transform,
overwriting them with zeroes. A transform may contain sensitive
data such as secret key-derived material, or parts of the
input or output data. Calling [wipe] ensures that this sensitive
data will not remain in memory longer than strictly necessary,
thus making invasive attacks more difficult.
It is thus prudent practice to call [wipe] on every
transform that the program no longer needs.
After calling [wipe], the transform is no longer in a working
state: do not call any other methods after calling [wipe]. *)
end
val transform_string: transform -> string -> string
(** [transform_string t s] runs the string [s] through the
transform [t] and returns the transformed string.
The transform [t] is wiped before returning, hence can
no longer be used for further transformations. *)
val transform_channel:
transform -> ?len:int -> in_channel -> out_channel -> unit
(** [transform_channel t ic oc] reads characters from input channel [ic],
runs them through the transform [t], and writes the transformed
data to the output channel [oc]. If the optional [len] argument
is provided, exactly [len] characters are read from [ic] and
transformed; [End_of_file] is raised if [ic] does not contain
at least [len] characters. If [len] is not provided, [ic] is
read all the way to end of file.
The transform [t] is wiped before returning, hence can
no longer be used for further transformations. *)
val compose: transform -> transform -> transform
(** Compose two transforms, feeding the output of the first transform
to the input of the second transform. *)
(** A {i hash} is a function that maps arbitrarily-long character
sequences to small, fixed-size strings. *)
class type hash =
object
method add_substring: bytes -> int -> int -> unit
(** [add_substring b pos len] adds [len] characters from byte array
[b], starting at character number [pos], to the running
hash computation. *)
method add_string: string -> unit
(** [add_string str] adds all characters of string [str]
to the running hash computation. *)
method add_char: char -> unit
(** [add_char c] adds character [c] to the running hash computation. *)
method add_byte: int -> unit
(** [add_byte b] adds the character having code [b]
to the running hash computation. [b] must be between [0] and [255]
inclusive. *)
method result: string
(** Terminate the hash computation and return the hash value for
the input data provided via the [add_*] methods. The hash
value is a string of length [hash_size] characters.
After calling [result], the hash can no longer accept
additional data. Hence, do not call any of the [add_*] methods
after [result]. *)
method hash_size: int
(** Return the size of hash values produced by this hash function,
in bytes. *)
method wipe: unit
(** Erase all internal buffers and data structures of this hash,
overwriting them with zeroes. See {!Cryptokit.transform.wipe}. *)
end
val hash_string: hash -> string -> string
(** [hash_string h s] runs the string [s] through the hash function [h]
and returns the hash value of [s].
The hash [h] is wiped before returning, hence can
no longer be used for further hash computations. *)
val hash_channel: hash -> ?len:int -> in_channel -> string
(** [hash_channel h ic] reads characters from the input channel [ic],
computes their hash value and returns it.
If the optional [len] argument is provided, exactly [len] characters
are read from [ic] and hashed; [End_of_file] is raised if [ic]
does not contain at least [len] characters.
If [len] is not provided, [ic] is read all the way to end of file.
The hash [h] is wiped before returning, hence can
no longer be used for further hash computations. *)
(** An {i authenticated transform} maps sequences of bytes
to sequences of bytes, just like a transform, but also builds
a message authentication tag for the transformed data.
The tag is returned by the [finish] method.
Authenticated transforms are used for authenticated encryption
and decryption. *)
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
(** See {!Cryptokit.transform.put_substring}. *)
method put_string: string -> unit
(** See {!Cryptokit.transform.put_string}. *)
method put_char: char -> unit
(** See {!Cryptokit.transform.put_char}. *)
method put_byte: int -> unit
(** See {!Cryptokit.transform.put_byte}. *)
method finish_and_get_tag: string
(** Call method [finish_and_get_tag] to indicate that no further data will
be processed through the transform. This causes the transform
to flush its internal buffers and perform all appropriate
finalization actions, e.g. add final padding.
The authentication tag for the transformed data is computed
and returned. It's a string of length
{!Cryptokit.authenticated_transform.tag_size}.
After calling [finish_and_get_tag], the transform can no
longer accept additional data. Hence, after calling
[finish_and_get_tag], do not call any of the [put_*] methods
nor [finish_and_get_tag] again. *)
method available_output: int
(** See {!Cryptokit.transform.available_output}. *)
method get_string: string
(** See {!Cryptokit.transform.get_string}. *)
method get_substring: bytes * int * int
(** See {!Cryptokit.transform.get_substring}. *)
method get_char: char
(** See {!Cryptokit.transform.get_char}. *)
method get_byte: int
(** See {!Cryptokit.transform.get_byte}. *)
method tag_size: int
(** The size in bytes of the authentication tags. *)
method wipe: unit
(** See {!Cryptokit.transform.wipe}. *)
end
val auth_transform_string: authenticated_transform -> string -> string
(** [auth_transform_string t s] runs the string [s] through the
authenticated transform [t] and returns the concatenation
of the transformed string and its authentication tag.
The transform [t] is wiped before returning, hence can
no longer be used for further transformations. *)
val auth_check_transform_string:
authenticated_transform -> string -> string option
(** [auth_check_transform_string t s] splits the string [s]
into an input string [s1] and an expected authentication tag [a].
It runs [s1] through the authenticated transform [t]
and checks that the authentication tag is the expected tag [a].
If so, the transformed string is returned.
If not, [None] is returned.
The input string [s] must have length greater than or equal to
[t#tag_size]. Otherwise, the [Wrong_data_length] exception is raised.
The transform [t] is wiped before returning, hence can
no longer be used for further transformations. *)
val auth_transform_string_detached:
authenticated_transform -> string -> string * string
(** [auth_transform_string_detached t s] runs the string [s] through the
authenticated transform [t] and returns a pair of
the transformed string and its authentication tag.
The transform [t] is wiped before returning, hence can
no longer be used for further transformations. *)
val transform_then_hash: transform -> hash -> authenticated_transform
(** Build an authenticated transform from a transform [t] and a hash [h].
Input data is run through [t], producing transformed data.
The transformed data is hashed using [h]. The authentication tag
is the final hash value. *)
val transform_and_hash: transform -> hash -> authenticated_transform
(** Build an authenticated transform from a transform [t] and a hash [h].
Input data is run through [t], producing transformed data.
In parallel, the input data is hashed using [h]. The
authentication tag is the final hash value. *)
(** {1 Utilities: random numbers and padding schemes} *)
(** The [Random] module provides random and pseudo-random number generators
suitable for generating cryptographic keys, nonces, or challenges. *)
module Random : sig
class type rng =
object
method random_bytes: bytes -> int -> int -> unit
(** [random_bytes buf pos len] stores [len] random bytes
in byte array [buf], starting at position [pos]. *)
method wipe: unit
(** Erases the internal state of the generator.
Do not call [random_bytes] after calling [wipe]. *)
end
(** Generic interface for a random number generator. *)
val string: rng -> int -> string
(** [string rng len] returns a string of [len] random bytes
read from the generator [rng]. *)
val secure_rng: rng
(** A high-quality random number generator, using hard-to-predict
system data to generate entropy. This generator either uses
the OS-provided RNG, if any, or reads from [/dev/random] if
available, or uses the hardware random number generator, if
available.
The method [secure_rng#random_bytes] fails if no suitable RNG
is available. [secure_rng#random_bytes] may block until
enough entropy has been gathered. Do not use for generating
large quantities of random data, otherwise you could exhaust
the entropy sources of the system. *)
val system_rng: unit -> rng
(** [system_rng ()] returns a random number generator derived
from the OS-provided RNG. It raises [Error No_entropy_source]
if the OS does not provide a secure RNG. Currently, this function
is supported under Win32, and under Unix if the [getentropy()]
function is provided. *)
val device_rng: string -> rng
(** [device_rng devicename] returns a random number generator
that reads from the special file [devicename], e.g.
[/dev/random] or [/dev/urandom]. *)
val hardware_rng: unit -> rng
(** A hardware random number generator based on the [RDRAND] instruction
of the x86 architecture. Available only on recent Intel and AMD
x86 processors in 64-bit mode. Raises [Error No_entropy_source]
if not available. *)
val pseudo_rng: string -> rng
(** [pseudo_rng seed] returns a pseudo-random number generator
seeded by the string [seed]. [seed] must contain at least
16 characters, and can be arbitrarily longer than this,
except that only the first 32 characters are used.
The seed is used as a key for the Chacha20 stream cipher.
The generated pseudo-random data is the result of encrypting
the all-zero input with Chacha20.
While this generator is believed to have very good statistical
properties, it still does not generate ``true'' randomness:
the entropy of the byte strings it produces cannot exceed the
entropy contained in the seed. As a typical use,
[Random.pseudo_rng (Random.string Random.secure_rng 20)] returns a
generator that can generate arbitrarily long strings of pseudo-random
data without delays, and with a total entropy of approximately
160 bits. *)
val pseudo_rng_aes_ctr: string -> rng
(** This is another pseudo-random number generator, based on the AES
block cipher in counter mode. It is slightly slower than [pseudo_rng]
while having similar randomness characteristics.
The only reason to use it instead of [pseudo_rng] is that AES
has been cryptanalyzed even more than Chacha20.
The [seed] argument must contain at least 16 characters. Only the
first 16 characters are used, as an AES key. The generated
pseudo-random data is the result of encrypting the 128-bit integers
[0, 1, 2, ...] with this key. *)
end
(** The [Padding] module defines a generic interface
for padding input data to an integral number of blocks,
as well as two popular padding schemes. *)
module Padding : sig
class type scheme =
object
method pad: bytes -> int -> unit
(** [pad buf used] is called with a byte array [buf]
containing valid input data at positions [0, ..., used-1].
The [pad] method must write padding characters in positions
[used] to [Bytes.length str - 1]. It is guaranteed that
[used < Bytes.length str], so that at least one character of
padding must be added. The padding scheme must be unambiguous
in the following sense: from [buf] after padding, it must be
possible to determine [used] unambiguously. (This is what
method {!Cryptokit.Padding.scheme.strip} does.) *)
method strip: bytes -> int
(** This is the converse of the [pad] operation: from a padded
byte array [buf] as built by method [pad], [strip buf] determines
and returns the starting position of the padding data,
or equivalently the length of valid, non-padded input data
in [buf]. This method must raise [Error Bad_padding] if
[buf] does not have the format of a padded block as produced
by [pad]. *)
end
(** Generic interface of a padding scheme. *)
val length: scheme
(** This padding scheme pads data with [n] copies of the character
having code [n]. The integer [n] lies between 1 and the block
size (included). This constraint ensures non-ambiguity.
This scheme is defined in RFC 2040 and in PKCS 5 and 7. *)
val _8000: scheme
(** This padding scheme pads data with one [0x80] byte, followed
by as many [0] bytes as needed to fill the block. *)
end
(** {1 Cryptographic primitives (simplified interface)} *)
(** The [Cipher] module implements the AES, DES, Triple-DES, ARCfour
and Blowfish symmetric ciphers. Symmetric ciphers are presented
as transforms parameterized by a secret key and a "direction"
indicating whether encryption or decryption is to be performed.
The same secret key is used for encryption and for decryption. *)
module Cipher : sig
type direction = Encrypt | Decrypt (** *)
(** Indicate whether the cipher should perform encryption
(transforming plaintext to ciphertext) or decryption
(transforming ciphertext to plaintext). *)
(** Block ciphers such as AES or DES map a fixed-sized block of
input data to a block of output data of the same size.
A chaining mode indicates how to extend them to multiple blocks
of data. The chaining modes supported in this library are: *)
type chaining_mode =
ECB [@alert crypto "ECB mode is weak"]
(** Electronic Code Book mode *)
| CBC (** Cipher Block Chaining mode *)
| CFB of int (** Cipher Feedback Block with [n] bytes *)
| OFB of int (** Output Feedback Block with [n] bytes *)
| CTR (** Counter mode, incrementing all the bytes of the IV *)
| CTR_N of int (** Counter mode, incrementing only the final [n] bytes
of the IV. *)
(** A detailed description of these modes is beyond the scope of
this documentation; refer to a good cryptography book.
[CTR] is a recommended default.
For [CFB n] and [OFB n], note that the blocksize is reduced to
[n], but encryption speed drops by a factor of
[blocksize / n], where [blocksize] is the block size of the
underlying cipher; moreover, [n] must be between [1] and
[blocksize] included.
For [CTR_N n], [n] must be between [1] and [blocksize] included.
[CTR] is equivalent to [CTR_N blocksize].
NIST Special Publication 800-38D uses [CTR_N 4], which
increments the final 32 bits of the IV. *)
(** {2 Recommended ciphers} *)
val aes: ?mode:chaining_mode -> ?pad:Padding.scheme -> ?iv:string ->
string -> direction -> transform
(** AES is the Advanced Encryption Standard.
This is a modern block cipher, standardized in 2001.
It processes data by blocks of 128 bits (16 bytes),
and supports keys of 128, 192 or 256 bits.
The string argument is the key; it must have length 16, 24 or 32.
The direction argument specifies whether encryption or decryption
is to be performed.
The optional [mode] argument specifies a
chaining mode, as described above; [CBC] is used by default.
The optional [pad] argument specifies a padding scheme to
pad cleartext to an integral number of blocks. If no [pad]
argument is given, no padding is performed and the length
of the cleartext must be an integral number of blocks.
The optional [iv] argument is the initialization vector used
by the chaining mode. It is ignored in ECB mode. If
provided, it must be a string of the same size as the block
size (16 bytes). If omitted, the null initialization vector
(16 zero bytes) is used.
The [aes] function returns a transform that performs encryption
or decryption, depending on the direction argument. *)
val chacha20: ?iv:string -> ?ctr:int64 -> string -> direction -> transform
(** Chacha20 is a stream cipher proposed by D. J. Bernstein in 2008.
The Chacha20 cipher is a stream cipher, not a block cipher.
Hence, its natural block size is 1, and no padding is
required. Chaining modes do not apply. A feature of stream
ciphers is that the xor of two ciphertexts obtained with the
same key, IV and counter is the xor of the corresponding
plaintexts, which allows various attacks. Hence, the same key
can be used several times, but only with different IVs or
different counters.
The string argument is the key; its length must be either 16
or (better) 32.
The optional [iv] argument is the initialization vector (also
called nonce) that can be used to diversify the key. If present,
it must be 8 or 12 characters long. If absent, it is taken to be
eight zero bytes.
The optional [ctr] argument is the initial value of the internal
counter. If absent, it defaults to 0.
The direction argument is present for consistency with the
other ciphers only, and is actually ignored: for all stream
ciphers, decryption is the same function as encryption. *)
(** {2 Weaker, older ciphers, not recommended for new applications} *)
val des: ?mode:chaining_mode -> ?pad:Padding.scheme -> ?iv:string ->
string -> direction -> transform
[@@alert crypto "DES is broken"]
(** DES is the Data Encryption Standard. Very popular in the past,
but now completely insecure owing to its small key size (56 bits)
which can easily be broken by brute-force enumeration.
It should therefore be considered as weak encryption.
Its block size is 64 bits (8 bytes).
The arguments to the [des] function have the same meaning as
for the {!Cryptokit.Cipher.aes} function. The key argument is
a string of length 8 (64 bits); the least significant bit of
each key byte is ignored. *)
val triple_des: ?mode:chaining_mode -> ?pad:Padding.scheme -> ?iv:string ->
string -> direction -> transform
[@@alert crypto "Triple-DES is weak (small block size)"]
(** Triple DES with two or three DES keys.
This is a popular variant of DES
where each block is encrypted with a 56-bit key [k1],
decrypted with another 56-bit key [k2], then re-encrypted with
either [k1] or a third 56-bit key [k3].
This results in a 112-bit or 168-bit key length that resists
brute-force attacks. However, the three encryptions required
on each block make this cipher quite slow (4 times slower than
AES). Moreover, the small block size (64 bits) opens the way
to collision-based attacks. Triple DES should therefore be
considered as relatively weak encryption.
The arguments to the [triple_des] function have the
same meaning as for the {!Cryptokit.Cipher.aes} function. The
key argument is a string of length 16 or 24, representing the
concatenation of the key parts [k1], [k2], and optionally
[k3]. The least significant bit of each key byte is
ignored. *)
val arcfour: string -> direction -> transform
[@@alert crypto "ARCfour is weak (statistical biases)"]
(** ARCfour (``alleged RC4'') is a fast stream cipher
that appears to produce equivalent results with the commercial
RC4 cipher from RSA Data Security Inc. This company holds the
RC4 trademark, and sells the real RC4 cipher. So, it is prudent
not to use ARCfour in a commercial product.
ARCfour is popular for its speed: approximately 2 times faster
than AES. It accepts any key length up to 2048 bits. However,
the security of ARCfour is being questioned owing to several
statistical biases in its output. It should not be used for
new applications.
The ARCfour cipher is a stream cipher, not a block cipher.
Hence, its natural block size is 1, and no padding is
required. Chaining modes do not apply. A feature of stream
ciphers is that the xor of two ciphertexts obtained with the
same key is the xor of the corresponding plaintexts, which
allows various attacks. Hence, the same key must never be
reused.
The string argument is the key; its length must be between
1 and 256 inclusive. The direction argument is present for
consistency with the other ciphers only, and is actually
ignored: for all stream ciphers, decryption is the same
function as encryption. *)
val blowfish: ?mode:chaining_mode -> ?pad:Padding.scheme -> ?iv:string ->
string -> direction -> transform
[@@alert crypto "Blowfish is weak (small block size)"]
(** Blowfish is a fast block cipher proposed by B.Schneier in 1994.
It processes data by blocks of 64 bits (8 bytes),
and supports keys of 32 to 448 bits.
The small block size (64 bits) of Blowfish opens the way to
some collision-based attacks. Depending on the application,
ciphers with larger block size should be preferred.
The string argument is the key; its length must be between
4 and 56.
The direction argument specifies whether encryption or decryption
is to be performed.
The optional [mode] argument specifies a
chaining mode, as described above; [CBC] is used by default.
The optional [pad] argument specifies a padding scheme to
pad cleartext to an integral number of blocks. If no [pad]
argument is given, no padding is performed and the length
of the cleartext must be an integral number of blocks.
The optional [iv] argument is the initialization vector used
by the chaining mode. It is ignored in ECB mode.
If provided, it must be a string of the same size as the block size
(8 bytes). If omitted, the null initialization vector
(8 zero bytes) is used.
The [blowfish] function returns a transform that performs encryption
or decryption, depending on the direction argument. *)
end
(** The [AEAD] module implements authenticated encryption
with associated data. This provides the same confidentiality
guarantees as plain encryption, but also provides integrity
guarantees. This module implements the AES-GCM and Chacha20-Poly1305
algorithms.
*)
module AEAD : sig
type direction = Encrypt | Decrypt (** *)
(** Indicate whether the cipher should perform encryption
(transforming plaintext to ciphertext) or decryption
(transforming ciphertext to plaintext). *)
val aes_gcm: ?header: string -> iv: string -> string -> direction -> authenticated_transform
(** AES-GCM is a standardized and widely-used authenticated encryption
algorithm. It's an encrypt-then-MAC schema based on the AES
cipher in counter mode and on the GHASH hash function.
It supports keys of size 128, 192, or 256 bits, and produces
authentication tags of size 128 bits (16 bytes).
[aes_gcm ?header ~iv key dir] returns an authenticated transform
(see {!Cryptokit.authenticated_transform}).
- [key] is the encryption key; it must have length 16, 24 or 32.
- [dir] specifies whether encryption or decryption is to be performed.
- [iv] (mandatory) is the initialization vector used for counter mode.
It must not be reused for several encryptions. It is recommended
to use a 96-bit (12 bytes) randomly-generated initialization vector.
Initialization vectors of size other than 12 bytes are supported
but trigger additional computations.
- [header] is the associated data. It is not encrypted but it is
authenticated, i.e. taken into account for computing the authentication
tag. If not provided, it defaults to the empty string.
*)
val chacha20_poly1305: ?header: string -> iv: string -> string -> direction -> authenticated_transform
(** Chacha20-Poly1305 is a fast authenticated encryption
algorithm. It's an encrypt-then-MAC schema combining the
Chacha20 cipher with the Poly1305 one-time authentication
function.
It supports keys of size 128 or 256 bits, and produces
authentication tags of size 128 bits (16 bytes).
[chacha20_poly1305 ?header ~iv key dir] returns an
authenticated transform (see {!Cryptokit.authenticated_transform}).
- [key] is the encryption key; it must have length 16 or 32.
- [dir] specifies whether encryption or decryption is to be performed.
- [iv] (mandatory) is the initialization vector used for counter mode.
It must not be reused for several encryptions. It must have length
8 bytes (for the original Chacha20-Poly1305 algorithm) or
12 bytes (for the IETF variant described in RFC 7539).
- [header] is the associated data. It is not encrypted but it is
authenticated, i.e. taken into account for computing the authentication
tag. If not provided, it defaults to the empty string.
*)
end
(** The [Hash] module implements unkeyed cryptographic hashes (SHA-1,
SHA-256, SHA-512, SHA-3, RIPEMD-160 and MD5), also known as
message digest functions.
Hash functions used in cryptography are characterized as being
{i one-way} (given a hash value, it is computationally
infeasible to find a text that hashes to this value) and
{i collision-resistant} (it is computationally infeasible to
find two different texts that hash to the same value). Thus, the
hash of a text can be used as a compact replacement for this text
for the purposes of ensuring integrity of the text. *)
module Hash : sig
(** {2 Recommended hashes} *)
val sha3: int -> hash
(** SHA-3, the latest NIST standard for cryptographic hashing,
produces hashes of 224, 256, 384 or 512 bits (24, 32, 48 or 64
bytes). The parameter is the desired size of the hash, in
bits. It must be one of 224, 256, 384 or 512. *)
val keccak: int -> hash
(** The Keccak submission for the SHA-3 is very similar to [sha3] but
uses a slightly different padding. The parameter is the same as
that of [sha3]. *)
val sha2: int -> hash
(** SHA-2, another NIST standard for cryptographic hashing, produces
hashes of 224, 256, 384, or 512 bits (24, 32, 48 or 64 bytes).
The parameter is the desired size of the hash, in
bits. It must be one of 224, 256, 384 or 512. *)
val sha224: unit -> hash
(** SHA-224 is SHA-2 specialized to 224 bit hashes (24 bytes). *)
val sha256: unit -> hash
(** SHA-256 is SHA-2 specialized to 256 bit hashes (32 bytes). *)
val sha384: unit -> hash
(** SHA-384 is SHA-2 specialized to 384 bit hashes (48 bytes). *)
val sha512: unit -> hash
(** SHA-512 is SHA-2 specialized to 512 bit hashes (64 bytes). *)
val sha512_256: unit -> hash
(** SHA-512/256 is a truncated version of SHA-512 (32 bytes) with a different IV. *)
val sha512_224: unit -> hash
(** SHA-512/224 is a truncated version of SHA-512 (24 bytes) with a different IV. *)
val blake2b: int -> hash
(** The BLAKE2b hash function produces hashes of length 1 to 64 bytes.
The parameter is the desired size of the hash, in bits.
It must be between 8 and 512, and a multiple of 8. *)
val blake2b512: unit -> hash
(** BLAKE2b512 is BLAKE2b specialized to 512 bit hashes (64 bytes). *)
val blake2s: int -> hash
(** The BLAKE2s hash function produces hashes of length 1 to 32 bytes.
The parameter is the desired size of the hash, in bits.
It must be between 8 and 256, and a multiple of 8. *)
val blake2s256: unit -> hash
(** BLAKE2s256 is BLAKE2s specialized to 256 bit hashes (32 bytes). *)
val blake3: int -> hash
(** The BLAKE3 hash function produces hashes of arbitrary length.
The recommended length is 32 bytes (256 bits).
Shorter hashes are less secure, but longer hashes are not more secure.
The parameter is the desired size of the hash, in bits.
It must be positive and a multiple of 8. *)
val blake3_256: unit -> hash
(** The BLAKE3 hash function, specialized to 256 bit hashes (32 bytes). *)
val ripemd160: unit -> hash
(** RIPEMD-160 produces 160-bit hashes (20 bytes). *)
(** {2 Weak hashes, not recommended for new applications} *)
val sha1: unit -> hash
[@@alert crypto "SHA1 is broken"]
(** SHA-1 is the Secure Hash Algorithm revision 1. It is a NIST
standard, is widely used, and produces 160-bit hashes (20 bytes).
While popular in many legacy applications, it is now known
to be insecure. In particular, it is not collision-resistant. *)
val md5: unit -> hash
[@@alert crypto "MD5 is broken"]
(** MD5 is an older hash function, producing 128-bit hashes (16 bytes).
While popular in many legacy applications, it is now known
to be insecure. In particular, it is not collision-resistant. *)
end
(** The [MAC] module implements message authentication codes, also
known as keyed hash functions. These are hash functions parameterized
by a secret key. In addition to being one-way and collision-resistant,
a MAC has the property that without knowing the secret key, it is
computationally infeasible to find the hash for a known text,
even if many pairs of (text, MAC) are known to the attacker.
Thus, MAC can be used to authenticate the sender of a text:
the receiver of a (text, MAC) pair can recompute the MAC from the text,
and if it matches the transmitted MAC, be reasonably certain that
the text was authentified by someone who possesses the secret key.
The module [MAC] provides six MAC functions based on the hashes
BLAKE2b, SHA-1, SHA256, SHA512, RIPEMD160 and MD5;
five MAC functions based on the block ciphers AES, DES, and Triple-DES;
and the SipHash algorithm.
*)
module MAC: sig
val hmac_sha1: string -> hash
(** [hmac_sha1 key] returns a MAC based on the HMAC construction (RFC2104)
applied to SHA-1. The returned hash values are 160 bits (20 bytes)
long. The [key] argument is the MAC key; it can have any length,
but a minimal length of 20 bytes is recommended. *)
val hmac_sha256: string -> hash
(** [hmac_sha256 key] returns a MAC based on the HMAC construction
(RFC2104) applied to SHA-256. The returned hash values are
256 bits (32 bytes) long. The [key] argument is the MAC key;
it can have any length, but a minimal length of 32 bytes is
recommended. *)
val hmac_sha384: string -> hash
(** [hmac_sha384 key] returns a MAC based on the HMAC construction
(RFC2104) applied to SHA-384. The returned hash values are
384 bits (48 bytes) long. The [key] argument is the MAC key;
it can have any length, but a minimal length of 64 bytes is
recommended. *)
val hmac_sha512: string -> hash
(** [hmac_sha512 key] returns a MAC based on the HMAC construction
(RFC2104) applied to SHA-512. The returned hash values are
512 bits (64 bytes) long. The [key] argument is the MAC key;
it can have any length, but a minimal length of 64 bytes is
recommended. *)
val hmac_ripemd160: string -> hash
(** [hmac_ripemd160 key] returns a MAC based on the HMAC
construction (RFC2104) applied to RIPEMD-160. The returned
hash values are 160 bits (20 bytes) long. The [key] argument
is the MAC key; it can have any length, but a minimal length
of 20 bytes is recommended. *)
val hmac_md5: string -> hash
(** [hmac_md5 key] returns a MAC based on the HMAC construction (RFC2104)
applied to MD5. The returned hash values are 128 bits (16 bytes)
long. The [key] argument is the MAC key; it can have any length,
but a minimal length of 16 bytes is recommended. *)
val blake2b: int -> string -> hash
(** [blake2b sz key] is the BLAKE2b keyed hash function.
The returned hash values have length 1 to 64 bytes.
The [sz] is the desired size of the hash, in bits.
It must be between 8 and 512, and a multiple of 8.
The [key] argument is the MAC key. It must have length 64 at most.
A length of 64 bytes is recommended. *)
val blake2b512: string -> hash
(** [blake2b512 key] is the BLAKE2b keyed hash function specialized
to 512 bit hashes (64 bytes).
The [key] argument is the MAC key. It must have length 64 at most.
A length of 64 bytes is recommended. *)
val blake2s: int -> string -> hash
(** [blake2s sz key] is the BLAKE2s keyed hash function.
The returned hash values have length 1 to 32 bytes.
The [sz] is the desired size of the hash, in bits.
It must be between 8 and 256, and a multiple of 8.
The [key] argument is the MAC key. It must have length 32 at most.
A length of 32 bytes is recommended. *)
val blake2s256: string -> hash
(** [blake2s256 key] is the BLAKE2s keyed hash function specialized
to 256 bit hashes (32 bytes).
The [key] argument is the MAC key. It must have length 32 at most.
A length of 32 bytes is recommended. *)
val blake3: int -> string -> hash
(** [blake3 sz key] is the BLAKE3 keyed hash function.
[key] is the MAC key. It must have length 32.
[sz] is the desired size of the hash, in bits.
The recommended length is 256 bits (32 bytes).
Shorter hashes are less secure, but longer hashes are not more secure. *)
val blake3_256: string -> hash
(** [blake3_256 key] is the BLAKE3 keyed hash function specialized
to 256 bit hashes (32 bytes).
[key] is the MAC key. It must have length 32. *)
val aes_cmac: ?iv:string -> string -> hash
(** [aes_cmac key] returns a MAC based on AES encryption in CMAC mode,
also known as OMAC1 mode. The input data is encrypted using
AES in CBC mode, with a special treatment of the final block
that makes this MAC suitable for input data of variable length.
The final value of the initialization vector is the MAC value.
Thus, the returned hash values are 128 bit (16 bytes) long.
The [key] argument is the MAC key; it must have length 16, 24,
or 32. The optional [iv] argument is the first value of the
initialization vector, and defaults to 0. *)
val aes: ?iv:string -> ?pad:Padding.scheme -> string -> hash
(** [aes key] returns a MAC based on AES encryption in CBC mode.
Unlike [aes_cmac], there is no special treatment for the final
block, except padding it as per the optional [pad] argument.
This makes this MAC weak when used with input data of variable
length. (It is fine for data of fixed length, though.)
The returned hash values are 128 bit (16 bytes) long. The
[key] argument is the MAC key; it must have length 16, 24, or
32. The optional [iv] argument is the first value of the
initialization vector, and defaults to 0. The optional [pad]
argument specifies a padding scheme to pad input to an
integral number of 16-byte blocks. *)
val des: ?iv:string -> ?pad:Padding.scheme -> string -> hash
[@@alert crypto "DES MAC is weak"]
(** [des key] returns a MAC based on DES encryption in CBC mode.
The construction is identical to that used for the [aes] MAC.
The key size is 64 bits (8 bytes), of which only 56 are used.
The returned hash value has length 8 bytes.
Due to the small hash size and key size, this MAC is weak. *)
val triple_des: ?iv:string -> ?pad:Padding.scheme -> string -> hash
[@@alert crypto "Triple-DES MAC is weak"]
(** [triple_des key] returns a MAC based on triple DES encryption in CBC mode.
The construction is identical to that used for the [aes] MAC.
The key size is 16 or 24 bytes. The returned hash value has
length 8 bytes. The key size is sufficient to protect against
brute-force attacks, but the small hash size means that this
MAC is not collision-resistant. *)
val des_final_triple_des: ?iv:string -> ?pad:Padding.scheme -> string -> hash
[@@alert crypto "Triple-DES MAC is weak"]
(** [des_final_triple_des key] returns a MAC that uses DES CBC
with the first 8 bytes of [key] as key. The final initialization
vector is then DES-decrypted with bytes 8 to 15 of [key],
and DES-encrypted again with either the last 8 bytes of [key]
(if a triple-length key is provided) or the first 8 bytes of [key]
(if a double-length key is provided).
Thus, the key is 16 or 24 bytes long, of which
112 or 168 bits are used. The overall construction has the same
key size as a triple DES MAC, but runs faster because triple
encryption is not performed on all data blocks, but only on
the final MAC. *)
val siphash: string -> hash
(** [siphash key] is the SipHash-2-4 function.
The returned hash values have length 8 bytes.
The [key] argument is the MAC key. It must be 16 bytes (128 bits) long.
This MAC is very fast, especially for short inputs. However,
it has not been cryptanalyzed as intensively as the other
MACs above. *)
val siphash128: string -> hash
(** [siphash128 key] is a variant of [siphash] that returns
hash values of length 16 bytes instead of 8 bytes. *)
end
(** The [RSA] module implements RSA public-key cryptography.
Public-key cryptography is asymmetric: two distinct keys are used
for encrypting a message, then decrypting it. Moreover, while one of
the keys must remain secret, the other can be made public, since
it is computationally very hard to reconstruct the private key
from the public key. This feature supports both public-key
encryption (anyone can encode with the public key, but only the
owner of the private key can decrypt) and digital signature
(only the owner of the private key can sign, but anyone can check
the signature with the public key). *)
module RSA: sig
type public_key =
{ size: int; (** Size of the modulus [n], in bits *)
n: string; (** Modulus [n] *)
e: string (** Public exponent [e] *)
}
(** The type of RSA public keys. *)
type private_key =
{ size: int; (** Size of the modulus [n], in bits *)
n: string; (** Modulus [n = p.q] *)
d: string; (** Private exponent [d] *)
p: string; (** Prime factor [p] of [n] *)
q: string; (** The other prime factor [q] of [n] *)
dp: string; (** [dp] is [d mod (p-1)] *)
dq: string; (** [dq] is [d mod (q-1)] *)
qinv: string (** [qinv] is a multiplicative inverse of [q] modulo [p] *)
}
(** The type of RSA private keys. The main components are
[size], [n] and [d]. To speed up private key operations
through the use of the Chinese remainder theorem (CRT), additional
components [p], [q], [dp], [dq] and [qinv] can be provided. *)