Initialize Tizen 2.3
[external/nettle.git] / nettle.info
1 This is nettle.info, produced by makeinfo version 4.6 from
2 nettle.texinfo.
3
4 This manual is for the Nettle library (version 2.1), a low-level
5 cryptographic library.
6
7    Originally written 2001 by Niels Möller, updated 2010.
8
9      This manual is placed in the public domain. You may freely copy
10      it, in whole or in part, with or without modification. Attribution
11      is appreciated, but not required.
12    
13 INFO-DIR-SECTION Encryption
14 START-INFO-DIR-ENTRY
15 * Nettle: (nettle).             A low-level cryptographic library.
16 END-INFO-DIR-ENTRY
17
18 \1f
19 File: nettle.info,  Node: Top,  Next: Introduction,  Prev: (dir),  Up: (dir)
20
21 Nettle
22 ******
23
24 This document describes the Nettle low-level cryptographic library. You
25 can use the library directly from your C programs, or write or use an
26 object-oriented wrapper for your favorite language or application.
27
28 This manual is for the Nettle library (version 2.1), a low-level
29 cryptographic library.
30
31    Originally written 2001 by Niels Möller, updated 2010.
32
33      This manual is placed in the public domain. You may freely copy
34      it, in whole or in part, with or without modification. Attribution
35      is appreciated, but not required.
36    
37 * Menu:
38
39 * Introduction::                What is Nettle?
40 * Copyright::                   Your rights.
41 * Conventions::                 General interface conventions.
42 * Example::                     An example program.
43 * Linking::                     Linking with the libnettle and libhogweed.
44 * Reference::                   All Nettle functions and features.
45 * Nettle soup::                 For the serious nettle hacker.
46 * Installation::                How to install Nettle.
47 * Index::                       Function and concept index.
48
49 \1f
50 File: nettle.info,  Node: Introduction,  Next: Copyright,  Prev: Top,  Up: Top
51
52 Introduction
53 ************
54
55 Nettle is a cryptographic library that is designed to fit easily in more
56 or less any context: In crypto toolkits for object-oriented languages
57 (C++, Python, Pike, ...), in applications like LSH or GNUPG, or even in
58 kernel space. In most contexts, you need more than the basic
59 cryptographic algorithms, you also need some way to keep track of
60 available algorithms, their properties and variants. You often have
61 some algorithm selection process, often dictated by a protocol you want
62 to implement.
63
64    And as the requirements of applications differ in subtle and not so
65 subtle ways, an API that fits one application well can be a pain to use
66 in a different context. And that is why there are so many different
67 cryptographic libraries around.
68
69    Nettle tries to avoid this problem by doing one thing, the low-level
70 crypto stuff, and providing a _simple_ but general interface to it.  In
71 particular, Nettle doesn't do algorithm selection. It doesn't do memory
72 allocation. It doesn't do any I/O.
73
74    The idea is that one can build several application and context
75 specific interfaces on top of Nettle, and share the code, test cases,
76 benchmarks, documentation, etc. Examples are the Nettle module for the
77 Pike language, and LSH, which both use an object-oriented abstraction
78 on top of the library.
79
80    This manual explains how to use the Nettle library. It also tries to
81 provide some background on the cryptography, and advice on how to best
82 put it to use.
83
84 \1f
85 File: nettle.info,  Node: Copyright,  Next: Conventions,  Prev: Introduction,  Up: Top
86
87 Copyright
88 *********
89
90 Nettle is distributed under the GNU General Public License (GPL) (see
91 the file COPYING for details). However, most of the individual files
92 are dual licensed under less restrictive licenses like the GNU Lesser
93 General Public License (LGPL), or are in the public domain. This means
94 that if you don't use the parts of nettle that are GPL-only, you have
95 the option to use the Nettle library just as if it were licensed under
96 the LGPL. To find the current status of particular files, you have to
97 read the copyright notices at the top of the files.
98
99    This manual is in the public domain. You may freely copy it in whole
100 or in part, e.g., into documentation of programs that build on Nettle.
101 Attribution, as well as contribution of improvements to the text, is of
102 course appreciated, but it is not required.
103
104    A list of the supported algorithms, their origins and licenses:
105
106 _AES_
107      The implementation of the AES cipher (also known as rijndael) is
108      written by Rafael Sevilla. Assembler for x86 by Rafael Sevilla and
109      Niels Möller, Sparc assembler by Niels Möller. Released under the
110      LGPL.
111
112 _ARCFOUR_
113      The implementation of the ARCFOUR (also known as RC4) cipher is
114      written by Niels Möller. Released under the LGPL.
115
116 _ARCTWO_
117      The implementation of the ARCTWO (also known as RC2) cipher is
118      written by Nikos Mavroyanopoulos and modified by Werner Koch and
119      Simon Josefsson. Released under the LGPL.
120
121 _BLOWFISH_
122      The implementation of the BLOWFISH cipher is written by Werner
123      Koch, copyright owned by the Free Software Foundation. Also hacked
124      by Ray Dassen and Niels Möller. Released under the GPL.
125
126 _CAMELLIA_
127      The C implementation is by Nippon Telegraph and Telephone
128      Corporation (NTT), heavily modified by Niels Möller. Assembler for
129      x86 by Niels Möller. Released under the LGPL.
130
131 _CAST128_
132      The implementation of the CAST128 cipher is written by Steve Reid.
133      Released into the public domain.
134
135 _DES_
136      The implementation of the DES cipher is written by Dana L. How, and
137      released under the LGPL.
138
139 _MD2_
140      The implementation of MD2 is written by Andrew Kuchling, and hacked
141      some by Andreas Sigfridsson and Niels Möller. Python Cryptography
142      Toolkit license (essentially public domain).
143
144 _MD4_
145      This is almost the same code as for MD5 below, with modifications
146      by Marcus Comstedt. Released into the public domain.
147
148 _MD5_
149      The implementation of the MD5 message digest is written by Colin
150      Plumb.  It has been hacked some more by Andrew Kuchling and Niels
151      Möller.  Released into the public domain.
152
153 _SERPENT_
154      The implementation of the SERPENT cipher is written by Ross
155      Anderson, Eli Biham, and Lars Knudsen, adapted to LSH by Rafael
156      Sevilla, and to Nettle by Niels Möller. Released under the GPL.
157
158 _SHA1_
159      The C implementation of the SHA1 message digest is written by Peter
160      Gutmann, and hacked some more by Andrew Kuchling and Niels Möller.
161      Released into the public domain. Assembler for x86 by Niels Möller,
162      released under the LGPL.
163
164 _SHA224, SHA256, SHA384, and SHA512_
165      Written by Niels Möller, using Peter Gutmann's SHA1 code as a
166      model.  Released under the LGPL.
167
168 _TWOFISH_
169      The implementation of the TWOFISH cipher is written by Ruud de
170      Rooij.  Released under the LGPL.
171
172 _RSA_
173      Written by Niels Möller, released under the LGPL. Uses the GMP
174      library for bignum operations.
175
176 _DSA_
177      Written by Niels Möller, released under the LGPL. Uses the GMP
178      library for bignum operations.
179
180 \1f
181 File: nettle.info,  Node: Conventions,  Next: Example,  Prev: Copyright,  Up: Top
182
183 Conventions
184 ***********
185
186 For each supported algorithm, there is an include file that defines a
187 _context struct_, a few constants, and declares functions for operating
188 on the context. The context struct encapsulates all information needed
189 by the algorithm, and it can be copied or moved in memory with no
190 unexpected effects.
191
192    For consistency, functions for different algorithms are very similar,
193 but there are some differences, for instance reflecting if the key setup
194 or encryption function differ for encryption and decryption, and whether
195 or not key setup can fail. There are also differences between algorithms
196 that don't show in function prototypes, but which the application must
197 nevertheless be aware of. There is no big difference between the
198 functions for stream ciphers and for block ciphers, although they should
199 be used quite differently by the application.
200
201    If your application uses more than one algorithm of the same type,
202 you should probably create an interface that is tailor-made for your
203 needs, and then write a few lines of glue code on top of Nettle.
204
205    By convention, for an algorithm named `foo', the struct tag for the
206 context struct is `foo_ctx', constants and functions uses prefixes like
207 `FOO_BLOCK_SIZE' (a constant) and `foo_set_key' (a function).
208
209    In all functions, strings are represented with an explicit length, of
210 type `unsigned', and a pointer of type `uint8_t *' or `const uint8_t
211 *'. For functions that transform one string to another, the argument
212 order is length, destination pointer and source pointer. Source and
213 destination areas are of the same length. Source and destination may be
214 the same, so that you can process strings in place, but they _must not_
215 overlap in any other way.
216
217    Many of the functions lack return value and can never fail. Those
218 functions which can fail, return one on success and zero on failure.
219
220 \1f
221 File: nettle.info,  Node: Example,  Next: Linking,  Prev: Conventions,  Up: Top
222
223 Example
224 *******
225
226 A simple example program that reads a file from standard input and
227 writes its SHA1 checksum on standard output should give the flavor of
228 Nettle.
229
230      #include <stdio.h>
231      #include <stdlib.h>
232      
233      #include <nettle/sha.h>
234      
235      #define BUF_SIZE 1000
236      
237      static void
238      display_hex(unsigned length, uint8_t *data)
239      {
240        unsigned i;
241      
242        for (i = 0; i<length; i++)
243          printf("%02x ", data[i]);
244      
245        printf("\n");
246      }
247      
248      int
249      main(int argc, char **argv)
250      {
251        struct sha1_ctx ctx;
252        uint8_t buffer[BUF_SIZE];
253        uint8_t digest[SHA1_DIGEST_SIZE];
254        
255        sha1_init(&ctx);
256        for (;;)
257        {
258          int done = fread(buffer, 1, sizeof(buffer), stdin);
259          sha1_update(&ctx, done, buffer);
260          if (done < sizeof(buffer))
261            break;
262        }
263        if (ferror(stdin))
264          return EXIT_FAILURE;
265      
266        sha1_digest(&ctx, SHA1_DIGEST_SIZE, digest);
267      
268        display_hex(SHA1_DIGEST_SIZE, digest);
269        return EXIT_SUCCESS;  
270      }
271
272    On a typical Unix system, this program can be compiled and linked
273 with the command line
274      cc sha-example.c -o sha-example -lnettle
275
276 \1f
277 File: nettle.info,  Node: Linking,  Next: Reference,  Prev: Example,  Up: Top
278
279 Linking
280 *******
281
282 Nettle actually consists of two libraries, `libnettle' and
283 `libhogweed'. The `libhogweed' library contains those functions of
284 Nettle that uses bignum operations, and depends on the GMP library.
285 With this division, linking works the same for both static and dynamic
286 libraries.
287
288    If an application uses only the symmetric crypto algorithms of Nettle
289 (i.e., block ciphers, hash functions, and the like), it's sufficient to
290 link with `-lnettle'. If an application also uses public-key
291 algorithms, the recommended linker flags are `-lhogweed -lnettle
292 -lgmp'. If the involved libraries are installed as dynamic libraries, it
293 may be sufficient to link with just `-lhogweed', and the loader will
294 resolve the dependencies automatically.
295
296 \1f
297 File: nettle.info,  Node: Reference,  Next: Nettle soup,  Prev: Linking,  Up: Top
298
299 Reference
300 *********
301
302 This chapter describes all the Nettle functions, grouped by family.
303
304 * Menu:
305
306 * Hash functions::
307 * Cipher functions::
308 * Cipher modes::
309 * Keyed hash functions::
310 * Public-key algorithms::
311 * Randomness::
312 * Miscellaneous functions::
313 * Compatibility functions::
314
315 \1f
316 File: nettle.info,  Node: Hash functions,  Next: Cipher functions,  Prev: Reference,  Up: Reference
317
318 Hash functions
319 ==============
320
321 A cryptographic "hash function" is a function that takes variable size
322 strings, and maps them to strings of fixed, short, length. There are
323 naturally lots of collisions, as there are more possible 1MB files than
324 20 byte strings. But the function is constructed such that is hard to
325 find the collisions. More precisely, a cryptographic hash function `H'
326 should have the following properties:
327
328 _One-way_
329      Given a hash value `H(x)' it is hard to find a string `x' that
330      hashes to that value.
331
332 _Collision-resistant_
333      It is hard to find two different strings, `x' and `y', such that
334      `H(x)' = `H(y)'.
335
336
337    Hash functions are useful as building blocks for digital signatures,
338 message authentication codes, pseudo random generators, association of
339 unique ids to documents, and many other things.
340
341    The most commonly used hash functions are MD5 and SHA1.
342 Unfortunately, both these fail the collision-resistance requirement;
343 cryptologists have found ways to construct colliding inputs. The
344 recommended hash function for new applications is SHA256, even though
345 it uses a structure similar to MD5 and SHA1. Constructing better hash
346 functions is an urgent research problem.
347
348 MD5
349 ---
350
351 MD5 is a message digest function constructed by Ronald Rivest, and
352 described in `RFC 1321'. It outputs message digests of 128 bits, or 16
353 octets. Nettle defines MD5 in `<nettle/md5.h>'.
354
355  - Context struct: struct md5_ctx
356
357  - Constant: MD5_DIGEST_SIZE
358      The size of an MD5 digest, i.e. 16.
359
360  - Constant: MD5_DATA_SIZE
361      The internal block size of MD5. Useful for some special
362      constructions, in particular HMAC-MD5.
363
364  - Function: void md5_init (struct md5_ctx *CTX)
365      Initialize the MD5 state.
366
367  - Function: void md5_update (struct md5_ctx *CTX, unsigned LENGTH,
368           const uint8_t *DATA)
369      Hash some more data.
370
371  - Function: void md5_digest (struct md5_ctx *CTX, unsigned LENGTH,
372           uint8_t *DIGEST)
373      Performs final processing and extracts the message digest, writing
374      it to DIGEST. LENGTH may be smaller than `MD5_DIGEST_SIZE', in
375      which case only the first LENGTH octets of the digest are written.
376
377      This function also resets the context in the same way as
378      `md5_init'.
379
380    The normal way to use MD5 is to call the functions in order: First
381 `md5_init', then `md5_update' zero or more times, and finally
382 `md5_digest'. After `md5_digest', the context is reset to its initial
383 state, so you can start over calling `md5_update' to hash new data.
384
385    To start over, you can call `md5_init' at any time.
386
387 MD2
388 ---
389
390 MD2 is another hash function of Ronald Rivest's, described in `RFC
391 1319'. It outputs message digests of 128 bits, or 16 octets.  Nettle
392 defines MD2 in `<nettle/md2.h>'.
393
394  - Context struct: struct md2_ctx
395
396  - Constant: MD2_DIGEST_SIZE
397      The size of an MD2 digest, i.e. 16.
398
399  - Constant: MD2_DATA_SIZE
400      The internal block size of MD2.
401
402  - Function: void md2_init (struct md2_ctx *CTX)
403      Initialize the MD2 state.
404
405  - Function: void md2_update (struct md2_ctx *CTX, unsigned LENGTH,
406           const uint8_t *DATA)
407      Hash some more data.
408
409  - Function: void md2_digest (struct md2_ctx *CTX, unsigned LENGTH,
410           uint8_t *DIGEST)
411      Performs final processing and extracts the message digest, writing
412      it to DIGEST. LENGTH may be smaller than `MD2_DIGEST_SIZE', in
413      which case only the first LENGTH octets of the digest are written.
414
415      This function also resets the context in the same way as
416      `md2_init'.
417
418 MD4
419 ---
420
421 MD4 is a predecessor of MD5, described in `RFC 1320'. Like MD5, it is
422 constructed by Ronald Rivest. It outputs message digests of 128 bits,
423 or 16 octets. Nettle defines MD4 in `<nettle/md4.h>'. Use of MD4 is not
424 recommended, but it is sometimes needed for compatibility with existing
425 applications and protocols.
426
427  - Context struct: struct md4_ctx
428
429  - Constant: MD4_DIGEST_SIZE
430      The size of an MD4 digest, i.e. 16.
431
432  - Constant: MD4_DATA_SIZE
433      The internal block size of MD4.
434
435  - Function: void md4_init (struct md4_ctx *CTX)
436      Initialize the MD4 state.
437
438  - Function: void md4_update (struct md4_ctx *CTX, unsigned LENGTH,
439           const uint8_t *DATA)
440      Hash some more data.
441
442  - Function: void md4_digest (struct md4_ctx *CTX, unsigned LENGTH,
443           uint8_t *DIGEST)
444      Performs final processing and extracts the message digest, writing
445      it to DIGEST. LENGTH may be smaller than `MD4_DIGEST_SIZE', in
446      which case only the first LENGTH octets of the digest are written.
447
448      This function also resets the context in the same way as
449      `md4_init'.
450
451 SHA1
452 ----
453
454 SHA1 is a hash function specified by "NIST" (The U.S. National Institute
455 for Standards and Technology). It outputs hash values of 160 bits, or 20
456 octets. Nettle defines SHA1 in `<nettle/sha.h>'.
457
458    The functions are analogous to the MD5 ones.
459
460  - Context struct: struct sha1_ctx
461
462  - Constant: SHA1_DIGEST_SIZE
463      The size of an SHA1 digest, i.e. 20.
464
465  - Constant: SHA1_DATA_SIZE
466      The internal block size of SHA1. Useful for some special
467      constructions, in particular HMAC-SHA1.
468
469  - Function: void sha1_init (struct sha1_ctx *CTX)
470      Initialize the SHA1 state.
471
472  - Function: void sha1_update (struct sha1_ctx *CTX, unsigned LENGTH,
473           const uint8_t *DATA)
474      Hash some more data.
475
476  - Function: void sha1_digest (struct sha1_ctx *CTX, unsigned LENGTH,
477           uint8_t *DIGEST)
478      Performs final processing and extracts the message digest, writing
479      it to DIGEST. LENGTH may be smaller than `SHA1_DIGEST_SIZE', in
480      which case only the first LENGTH octets of the digest are written.
481
482      This function also resets the context in the same way as
483      `sha1_init'.
484
485 SHA256
486 ------
487
488 SHA256 is another hash function specified by "NIST", intended as a
489 replacement for SHA1, generating larger digests. It outputs hash values
490 of 256 bits, or 32 octets. Nettle defines SHA256 in `<nettle/sha.h>'.
491
492    The functions are analogous to the MD5 ones.
493
494  - Context struct: struct sha256_ctx
495
496  - Constant: SHA256_DIGEST_SIZE
497      The size of an SHA256 digest, i.e. 32.
498
499  - Constant: SHA256_DATA_SIZE
500      The internal block size of SHA256. Useful for some special
501      constructions, in particular HMAC-SHA256.
502
503  - Function: void sha256_init (struct sha256_ctx *CTX)
504      Initialize the SHA256 state.
505
506  - Function: void sha256_update (struct sha256_ctx *CTX, unsigned
507           LENGTH, const uint8_t *DATA)
508      Hash some more data.
509
510  - Function: void sha256_digest (struct sha256_ctx *CTX, unsigned
511           LENGTH, uint8_t *DIGEST)
512      Performs final processing and extracts the message digest, writing
513      it to DIGEST. LENGTH may be smaller than `SHA256_DIGEST_SIZE', in
514      which case only the first LENGTH octets of the digest are written.
515
516      This function also resets the context in the same way as
517      `sha256_init'.
518
519 SHA224
520 ------
521
522 SHA224 is a variant of SHA256, with a different initial state, and with
523 the output truncated to 224 bits, or 28 octets. Nettle defines SHA224 in
524 `<nettle/sha.h>'.
525
526    The functions are analogous to the MD5 ones.
527
528  - Context struct: struct sha224_ctx
529
530  - Constant: SHA224_DIGEST_SIZE
531      The size of an SHA224 digest, i.e. 28.
532
533  - Constant: SHA224_DATA_SIZE
534      The internal block size of SHA224. Useful for some special
535      constructions, in particular HMAC-SHA224.
536
537  - Function: void sha224_init (struct sha224_ctx *CTX)
538      Initialize the SHA224 state.
539
540  - Function: void sha224_update (struct sha224_ctx *CTX, unsigned
541           LENGTH, const uint8_t *DATA)
542      Hash some more data.
543
544  - Function: void sha224_digest (struct sha224_ctx *CTX, unsigned
545           LENGTH, uint8_t *DIGEST)
546      Performs final processing and extracts the message digest, writing
547      it to DIGEST. LENGTH may be smaller than `SHA224_DIGEST_SIZE', in
548      which case only the first LENGTH octets of the digest are written.
549
550      This function also resets the context in the same way as
551      `sha224_init'.
552
553 SHA512
554 ------
555
556 SHA512 is a larger sibling to SHA256, with a very similar structure but
557 with both the output and the internal variables of twice the size. The
558 internal variables are 64 bits rather than 32, making it significantly
559 slower on 32-bit computers. It outputs hash values of 512 bits, or 64
560 octets. Nettle defines SHA512 in `<nettle/sha.h>'.
561
562    The functions are analogous to the MD5 ones.
563
564  - Context struct: struct sha512_ctx
565
566  - Constant: SHA512_DIGEST_SIZE
567      The size of an SHA512 digest, i.e. 64.
568
569  - Constant: SHA512_DATA_SIZE
570      The internal block size of SHA512. Useful for some special
571      constructions, in particular HMAC-SHA512.
572
573  - Function: void sha512_init (struct sha512_ctx *CTX)
574      Initialize the SHA512 state.
575
576  - Function: void sha512_update (struct sha512_ctx *CTX, unsigned
577           LENGTH, const uint8_t *DATA)
578      Hash some more data.
579
580  - Function: void sha512_digest (struct sha512_ctx *CTX, unsigned
581           LENGTH, uint8_t *DIGEST)
582      Performs final processing and extracts the message digest, writing
583      it to DIGEST. LENGTH may be smaller than `SHA512_DIGEST_SIZE', in
584      which case only the first LENGTH octets of the digest are written.
585
586      This function also resets the context in the same way as
587      `sha512_init'.
588
589 SHA384
590 ------
591
592 SHA384 is a variant of SHA512, with a different initial state, and with
593 the output truncated to 384 bits, or 48 octets. Nettle defines SHA384 in
594 `<nettle/sha.h>'.
595
596    The functions are analogous to the MD5 ones.
597
598  - Context struct: struct sha384_ctx
599
600  - Constant: SHA384_DIGEST_SIZE
601      The size of an SHA384 digest, i.e. 48.
602
603  - Constant: SHA384_DATA_SIZE
604      The internal block size of SHA384. Useful for some special
605      constructions, in particular HMAC-SHA384.
606
607  - Function: void sha384_init (struct sha384_ctx *CTX)
608      Initialize the SHA384 state.
609
610  - Function: void sha384_update (struct sha384_ctx *CTX, unsigned
611           LENGTH, const uint8_t *DATA)
612      Hash some more data.
613
614  - Function: void sha384_digest (struct sha384_ctx *CTX, unsigned
615           LENGTH, uint8_t *DIGEST)
616      Performs final processing and extracts the message digest, writing
617      it to DIGEST. LENGTH may be smaller than `SHA384_DIGEST_SIZE', in
618      which case only the first LENGTH octets of the digest are written.
619
620      This function also resets the context in the same way as
621      `sha384_init'.
622
623 `struct nettle_hash'
624 --------------------
625
626 Nettle includes a struct including information about the supported hash
627 functions. It is defined in `<nettle/nettle-meta.h>', and is used by
628 Nettle's implementation of HMAC *note Keyed hash functions::.
629
630  - Meta struct: `struct nettle_hash' name context_size digest_size
631           block_size init update digest
632      The last three attributes are function pointers, of types
633      `nettle_hash_init_func', `nettle_hash_update_func', and
634      `nettle_hash_digest_func'. The first argument to these functions is
635      `void *' pointer to a context struct, which is of size
636      `context_size'.
637
638  - Constant Struct: struct nettle_hash nettle_md2
639  - Constant Struct: struct nettle_hash nettle_md4
640  - Constant Struct: struct nettle_hash nettle_md5
641  - Constant Struct: struct nettle_hash nettle_sha1
642  - Constant Struct: struct nettle_hash nettle_sha224
643  - Constant Struct: struct nettle_hash nettle_sha256
644  - Constant Struct: struct nettle_hash nettle_sha384
645  - Constant Struct: struct nettle_hash nettle_sha512
646      These are all the hash functions that Nettle implements.
647
648 \1f
649 File: nettle.info,  Node: Cipher functions,  Next: Cipher modes,  Prev: Hash functions,  Up: Reference
650
651 Cipher functions
652 ================
653
654 A "cipher" is a function that takes a message or "plaintext" and a
655 secret "key" and transforms it to a "ciphertext". Given only the
656 ciphertext, but not the key, it should be hard to find the plaintext.
657 Given matching pairs of plaintext and ciphertext, it should be hard to
658 find the key.
659
660    There are two main classes of ciphers: Block ciphers and stream
661 ciphers.
662
663    A block cipher can process data only in fixed size chunks, called
664 "blocks". Typical block sizes are 8 or 16 octets. To encrypt arbitrary
665 messages, you usually have to pad it to an integral number of blocks,
666 split it into blocks, and then process each block. The simplest way is
667 to process one block at a time, independent of each other. That mode of
668 operation is called "ECB", Electronic Code Book mode.  However, using
669 ECB is usually a bad idea. For a start, plaintext blocks that are equal
670 are transformed to ciphertext blocks that are equal; that leaks
671 information about the plaintext. Usually you should apply the cipher is
672 some "feedback mode", "CBC" (Cipher Block Chaining) and "CTR" (Counter
673 mode) being two of of the most popular. See *Note Cipher modes::, for
674 information on how to apply CBC and CTR with Nettle.
675
676    A stream cipher can be used for messages of arbitrary length. A
677 typical stream cipher is a keyed pseudo-random generator. To encrypt a
678 plaintext message of N octets, you key the generator, generate N octets
679 of pseudo-random data, and XOR it with the plaintext. To decrypt,
680 regenerate the same stream using the key, XOR it to the ciphertext, and
681 the plaintext is recovered.
682
683    *Caution:* The first rule for this kind of cipher is the same as for
684 a One Time Pad: _never_ ever use the same key twice.
685
686    A common misconception is that encryption, by itself, implies
687 authentication. Say that you and a friend share a secret key, and you
688 receive an encrypted message. You apply the key, and get a plaintext
689 message that makes sense to you. Can you then be sure that it really was
690 your friend that wrote the message you're reading? The answer is no. For
691 example, if you were using a block cipher in ECB mode, an attacker may
692 pick up the message on its way, and reorder, delete or repeat some of
693 the blocks. Even if the attacker can't decrypt the message, he can
694 change it so that you are not reading the same message as your friend
695 wrote. If you are using a block cipher in CBC mode rather than ECB, or
696 are using a stream cipher, the possibilities for this sort of attack
697 are different, but the attacker can still make predictable changes to
698 the message.
699
700    It is recommended to _always_ use an authentication mechanism in
701 addition to encrypting the messages. Popular choices are Message
702 Authentication Codes like HMAC-SHA1 *note Keyed hash functions::, or
703 digital signatures like RSA.
704
705    Some ciphers have so called "weak keys", keys that results in
706 undesirable structure after the key setup processing, and should be
707 avoided. In Nettle, most key setup functions have no return value, but
708 for ciphers with weak keys, the return value indicates whether or not
709 the given key is weak. For good keys, key setup returns 1, and for weak
710 keys, it returns 0. When possible, avoid algorithms that have weak
711 keys. There are several good ciphers that don't have any weak keys.
712
713    To encrypt a message, you first initialize a cipher context for
714 encryption or decryption with a particular key. You then use the context
715 to process plaintext or ciphertext messages. The initialization is known
716 as "key setup". With Nettle, it is recommended to use each context
717 struct for only one direction, even if some of the ciphers use a single
718 key setup function that can be used for both encryption and decryption.
719
720 AES
721 ---
722
723 AES is a block cipher, specified by NIST as a replacement for the older
724 DES standard. The standard is the result of a competition between
725 cipher designers. The winning design, also known as RIJNDAEL, was
726 constructed by Joan Daemen and Vincent Rijnmen.
727
728    Like all the AES candidates, the winning design uses a block size of
729 128 bits, or 16 octets, and variable key-size, 128, 192 and 256 bits
730 (16, 24 and 32 octets) being the allowed key sizes. It does not have
731 any weak keys. Nettle defines AES in `<nettle/aes.h>'.
732
733  - Context struct: struct aes_ctx
734
735  - Constant: AES_BLOCK_SIZE
736      The AES block-size, 16
737
738  - Constant: AES_MIN_KEY_SIZE
739
740  - Constant: AES_MAX_KEY_SIZE
741
742  - Constant: AES_KEY_SIZE
743      Default AES key size, 32
744
745  - Function: void aes_set_encrypt_key (struct aes_ctx *CTX, unsigned
746           LENGTH, const uint8_t *KEY)
747  - Function: void aes_set_decrypt_key (struct aes_ctx *CTX, unsigned
748           LENGTH, const uint8_t *KEY)
749      Initialize the cipher, for encryption or decryption, respectively.
750
751  - Function: void aes_invert_key (struct aes_ctx *DST, const struct
752           aes_ctx *SRC)
753      Given a context SRC initialized for encryption, initializes the
754      context struct DST for decryption, using the same key. If the same
755      context struct is passed for both `src' and `dst', it is converted
756      in place. Calling `aes_set_encrypt_key' and `aes_invert_key' is
757      more efficient than calling `aes_set_encrypt_key' and
758      `aes_set_decrypt_key'. This function is mainly useful for
759      applications which needs to both encrypt and decrypt using the
760      _same_ key.
761
762  - Function: void aes_encrypt (struct aes_ctx *CTX, unsigned LENGTH,
763           const uint8_t *DST, uint8_t *SRC)
764      Encryption function. LENGTH must be an integral multiple of the
765      block size. If it is more than one block, the data is processed in
766      ECB mode. `src' and `dst' may be equal, but they must not overlap
767      in any other way.
768
769  - Function: void aes_decrypt (struct aes_ctx *CTX, unsigned LENGTH,
770           const uint8_t *DST, uint8_t *SRC)
771      Analogous to `aes_encrypt'
772
773 ARCFOUR
774 -------
775
776 ARCFOUR is a stream cipher, also known under the trade marked name RC4,
777 and it is one of the fastest ciphers around. A problem is that the key
778 setup of ARCFOUR is quite weak, you should never use keys with
779 structure, keys that are ordinary passwords, or sequences of keys like
780 "secret:1", "secret:2", ..... If you have keys that don't look like
781 random bit strings, and you want to use ARCFOUR, always hash the key
782 before feeding it to ARCFOUR. Furthermore, the initial bytes of the
783 generated key stream leak information about the key; for this reason, it
784 is recommended to discard the first 512 bytes of the key stream.
785
786      /* A more robust key setup function for ARCFOUR */
787      void
788      arcfour_set_key_hashed(struct arcfour_ctx *ctx,
789                             unsigned length, const uint8_t *key)
790      {
791        struct sha256_ctx hash;
792        uint8_t digest[SHA256_DIGEST_SIZE];
793        uint8_t buffer[0x200];
794      
795        sha256_init(&hash);
796        sha256_update(&hash, length, key);
797        sha256_digest(&hash, SHA256_DIGEST_SIZE, digest);
798      
799        arcfour_set_key(ctx, SHA256_DIGEST_SIZE, digest);
800        arcfour_crypt(ctx, sizeof(buffer), buffer, buffer);
801      }
802
803    Nettle defines ARCFOUR in `<nettle/arcfour.h>'.
804
805  - Context struct: struct arcfour_ctx
806
807  - Constant: ARCFOUR_MIN_KEY_SIZE
808      Minimum key size, 1
809
810  - Constant: ARCFOUR_MAX_KEY_SIZE
811      Maximum key size, 256
812
813  - Constant: ARCFOUR_KEY_SIZE
814      Default ARCFOUR key size, 16
815
816  - Function: void arcfour_set_key (struct arcfour_ctx *CTX, unsigned
817           LENGTH, const uint8_t *KEY)
818      Initialize the cipher. The same function is used for both
819      encryption and decryption.
820
821  - Function: void arcfour_crypt (struct arcfour_ctx *CTX, unsigned
822           LENGTH, const uint8_t *DST, uint8_t *SRC)
823      Encrypt some data. The same function is used for both encryption
824      and decryption. Unlike the block ciphers, this function modifies
825      the context, so you can split the data into arbitrary chunks and
826      encrypt them one after another. The result is the same as if you
827      had called `arcfour_crypt' only once with all the data.
828
829 ARCTWO
830 ------
831
832 ARCTWO (also known as the trade marked name RC2) is a block cipher
833 specified in RFC 2268. Nettle also include a variation of the ARCTWO
834 set key operation that lack one step, to be compatible with the reverse
835 engineered RC2 cipher description, as described in a Usenet post to
836 `sci.crypt' by Peter Gutmann.
837
838    ARCTWO uses a block size of 64 bits, and variable key-size ranging
839 from 1 to 128 octets. Besides the key, ARCTWO also has a second
840 parameter to key setup, the number of effective key bits, `ekb'.  This
841 parameter can be used to artificially reduce the key size. In practice,
842 `ekb' is usually set equal to the input key size.  Nettle defines
843 ARCTWO in `<nettle/arctwo.h>'.
844
845    We do not recommend the use of ARCTWO; the Nettle implementation is
846 provided primarily for interoperability with existing applications and
847 standards.
848
849  - Context struct: struct arctwo_ctx
850
851  - Constant: ARCTWO_BLOCK_SIZE
852      The AES block-size, 8
853
854  - Constant: ARCTWO_MIN_KEY_SIZE
855
856  - Constant: ARCTWO_MAX_KEY_SIZE
857
858  - Constant: ARCTWO_KEY_SIZE
859      Default ARCTWO key size, 8
860
861  - Function: void arctwo_set_key_ekb (struct arctwo_ctx *CTX, unsigned
862           LENGTH, const uint8_t *KEY, unsigned EKB)
863  - Function: void arctwo_set_key (struct arctwo_ctx *CTX, unsigned
864           LENGTH, const uint8_t *KEY)
865  - Function: void arctwo_set_key_gutmann (struct arctwo_ctx *CTX,
866           unsigned LENGTH, const uint8_t *KEY)
867      Initialize the cipher. The same function is used for both
868      encryption and decryption. The first function is the most general
869      one, which lets you provide both the variable size key, and the
870      desired effective key size (in bits). The maximum value for EKB is
871      1024, and for convenience, `ekb = 0' has the same effect as `ekb =
872      1024'.
873
874      `arctwo_set_key(ctx, length, key)' is equivalent to
875      `arctwo_set_key_ekb(ctx, length, key, 8*length)', and
876      `arctwo_set_key_gutmann(ctx, length, key)' is equivalent to
877      `arctwo_set_key_ekb(ctx, length, key, 1024)'
878
879  - Function: void arctwo_encrypt (struct arctwo_ctx *CTX, unsigned
880           LENGTH, const uint8_t *DST, uint8_t *SRC)
881      Encryption function. LENGTH must be an integral multiple of the
882      block size. If it is more than one block, the data is processed in
883      ECB mode. `src' and `dst' may be equal, but they must not overlap
884      in any other way.
885
886  - Function: void arctwo_decrypt (struct arctwo_ctx *CTX, unsigned
887           LENGTH, const uint8_t *DST, uint8_t *SRC)
888      Analogous to `arctwo_encrypt'
889
890 BLOWFISH
891 --------
892
893 BLOWFISH is a block cipher designed by Bruce Schneier. It uses a block
894 size of 64 bits (8 octets), and a variable key size, up to 448 bits. It
895 has some weak keys. Nettle defines BLOWFISH in `<nettle/blowfish.h>'.
896
897  - Context struct: struct blowfish_ctx
898
899  - Constant: BLOWFISH_BLOCK_SIZE
900      The BLOWFISH block-size, 8
901
902  - Constant: BLOWFISH_MIN_KEY_SIZE
903      Minimum BLOWFISH key size, 8
904
905  - Constant: BLOWFISH_MAX_KEY_SIZE
906      Maximum BLOWFISH key size, 56
907
908  - Constant: BLOWFISH_KEY_SIZE
909      Default BLOWFISH key size, 16
910
911  - Function: int blowfish_set_key (struct blowfish_ctx *CTX, unsigned
912           LENGTH, const uint8_t *KEY)
913      Initialize the cipher. The same function is used for both
914      encryption and decryption. Checks for weak keys, returning 1 for
915      good keys and 0 for weak keys. Applications that don't care about
916      weak keys can ignore the return value.
917
918      `blowfish_encrypt' or `blowfish_decrypt' with a weak key will
919      crash with an assert violation.
920
921  - Function: void blowfish_encrypt (struct blowfish_ctx *CTX, unsigned
922           LENGTH, const uint8_t *DST, uint8_t *SRC)
923      Encryption function. LENGTH must be an integral multiple of the
924      block size. If it is more than one block, the data is processed in
925      ECB mode. `src' and `dst' may be equal, but they must not overlap
926      in any other way.
927
928  - Function: void blowfish_decrypt (struct blowfish_ctx *CTX, unsigned
929           LENGTH, const uint8_t *DST, uint8_t *SRC)
930      Analogous to `blowfish_encrypt'
931
932 Camellia
933 --------
934
935 Camellia is a block cipher developed by Mitsubishi and Nippon Telegraph
936 and Telephone Corporation, described in `RFC3713', and recommended by
937 some Japanese and European authorities as an alternative to AES. The
938 algorithm is patented. The implementation in Nettle is derived from the
939 implementation released by NTT under the GNU LGPL (v2.1 or later), and
940 relies on the implicit patent license of the LGPL. There is also a
941 statement of royalty-free licensing for Camellia at
942 <http://www.ntt.co.jp/news/news01e/0104/010417.html>, but this
943 statement has some limitations which seem problematic for free software.
944
945    Camellia uses a the same block size and key sizes as AES: The block
946 size is 128 bits (16 octets), and the supported key sizes are 128, 192,
947 and 256 bits. Nettle defines Camellia in `<nettle/camellia.h>'.
948
949  - Context struct: struct camellia_ctx
950
951  - Constant: CAMELLIA_BLOCK_SIZE
952      The CAMELLIA block-size, 16
953
954  - Constant: CAMELLIA_MIN_KEY_SIZE
955
956  - Constant: CAMELLIA_MAX_KEY_SIZE
957
958  - Constant: CAMELLIA_KEY_SIZE
959      Default CAMELLIA key size, 32
960
961  - Function: void camellia_set_encrypt_key (struct camellia_ctx *CTX,
962           unsigned LENGTH, const uint8_t *KEY)
963  - Function: void camellia_set_decrypt_key (struct camellia_ctx *CTX,
964           unsigned LENGTH, const uint8_t *KEY)
965      Initialize the cipher, for encryption or decryption, respectively.
966
967  - Function: void camellia_invert_key (struct camellia_ctx *DST, const
968           struct camellia_ctx *SRC)
969      Given a context SRC initialized for encryption, initializes the
970      context struct DST for decryption, using the same key. If the same
971      context struct is passed for both `src' and `dst', it is converted
972      in place. Calling `camellia_set_encrypt_key' and
973      `camellia_invert_key' is more efficient than calling
974      `camellia_set_encrypt_key' and `camellia_set_decrypt_key'. This
975      function is mainly useful for applications which needs to both
976      encrypt and decrypt using the _same_ key.
977
978  - Function: void camellia_crypt (struct camellia_ctx *CTX, unsigned
979           LENGTH, const uint8_t *DST, uint8_t *SRC)
980      The same function is used for both encryption and decryption.
981      LENGTH must be an integral multiple of the block size. If it is
982      more than one block, the data is processed in ECB mode. `src' and
983      `dst' may be equal, but they must not overlap in any other way.
984
985 CAST128
986 -------
987
988 CAST-128 is a block cipher, specified in `RFC 2144'. It uses a 64 bit
989 (8 octets) block size, and a variable key size of up to 128 bits.
990 Nettle defines cast128 in `<nettle/cast128.h>'.
991
992  - Context struct: struct cast128_ctx
993
994  - Constant: CAST128_BLOCK_SIZE
995      The CAST128 block-size, 8
996
997  - Constant: CAST128_MIN_KEY_SIZE
998      Minimum CAST128 key size, 5
999
1000  - Constant: CAST128_MAX_KEY_SIZE
1001      Maximum CAST128 key size, 16
1002
1003  - Constant: CAST128_KEY_SIZE
1004      Default CAST128 key size, 16
1005
1006  - Function: void cast128_set_key (struct cast128_ctx *CTX, unsigned
1007           LENGTH, const uint8_t *KEY)
1008      Initialize the cipher. The same function is used for both
1009      encryption and decryption.
1010
1011  - Function: void cast128_encrypt (struct cast128_ctx *CTX, unsigned
1012           LENGTH, const uint8_t *DST, uint8_t *SRC)
1013      Encryption function. LENGTH must be an integral multiple of the
1014      block size. If it is more than one block, the data is processed in
1015      ECB mode. `src' and `dst' may be equal, but they must not overlap
1016      in any other way.
1017
1018  - Function: void cast128_decrypt (struct cast128_ctx *CTX, unsigned
1019           LENGTH, const uint8_t *DST, uint8_t *SRC)
1020      Analogous to `cast128_encrypt'
1021
1022 DES
1023 ---
1024
1025 DES is the old Data Encryption Standard, specified by NIST. It uses a
1026 block size of 64 bits (8 octets), and a key size of 56 bits. However,
1027 the key bits are distributed over 8 octets, where the least significant
1028 bit of each octet may be used for parity. A common way to use DES is to
1029 generate 8 random octets in some way, then set the least significant bit
1030 of each octet to get odd parity, and initialize DES with the resulting
1031 key.
1032
1033    The key size of DES is so small that keys can be found by brute
1034 force, using specialized hardware or lots of ordinary work stations in
1035 parallel. One shouldn't be using plain DES at all today, if one uses
1036 DES at all one should be using "triple DES", see DES3 below.
1037
1038    DES also has some weak keys. Nettle defines DES in `<nettle/des.h>'.
1039
1040  - Context struct: struct des_ctx
1041
1042  - Constant: DES_BLOCK_SIZE
1043      The DES block-size, 8
1044
1045  - Constant: DES_KEY_SIZE
1046      DES key size, 8
1047
1048  - Function: int des_set_key (struct des_ctx *CTX, const uint8_t *KEY)
1049      Initialize the cipher. The same function is used for both
1050      encryption and decryption. Parity bits are ignored. Checks for
1051      weak keys, returning 1 for good keys and 0 for weak keys.
1052      Applications that don't care about weak keys can ignore the return
1053      value.
1054
1055  - Function: void des_encrypt (struct des_ctx *CTX, unsigned LENGTH,
1056           const uint8_t *DST, uint8_t *SRC)
1057      Encryption function. LENGTH must be an integral multiple of the
1058      block size. If it is more than one block, the data is processed in
1059      ECB mode. `src' and `dst' may be equal, but they must not overlap
1060      in any other way.
1061
1062  - Function: void des_decrypt (struct des_ctx *CTX, unsigned LENGTH,
1063           const uint8_t *DST, uint8_t *SRC)
1064      Analogous to `des_encrypt'
1065
1066  - Function: int des_check_parity (unsigned LENGTH, const uint8_t *KEY);
1067      Checks that the given key has correct, odd, parity. Returns 1 for
1068      correct parity, and 0 for bad parity.
1069
1070  - Function: void des_fix_parity (unsigned LENGTH, uint8_t *DST, const
1071           uint8_t *SRC)
1072      Adjusts the parity bits to match DES's requirements. You need this
1073      function if you have created a random-looking string by a key
1074      agreement protocol, and want to use it as a DES key. DST and SRC
1075      may be equal.
1076
1077 DES3
1078 ----
1079
1080 The inadequate key size of DES has already been mentioned. One way to
1081 increase the key size is to pipe together several DES boxes with
1082 independent keys. It turns out that using two DES ciphers is not as
1083 secure as one might think, even if the key size of the combination is a
1084 respectable 112 bits.
1085
1086    The standard way to increase DES's key size is to use three DES
1087 boxes.  The mode of operation is a little peculiar: the middle DES box
1088 is wired in the reverse direction. To encrypt a block with DES3, you
1089 encrypt it using the first 56 bits of the key, then _decrypt_ it using
1090 the middle 56 bits of the key, and finally encrypt it again using the
1091 last 56 bits of the key. This is known as "ede" triple-DES, for
1092 "encrypt-decrypt-encrypt".
1093
1094    The "ede" construction provides some backward compatibility, as you
1095 get plain single DES simply by feeding the same key to all three boxes.
1096 That should help keeping down the gate count, and the price, of hardware
1097 circuits implementing both plain DES and DES3.
1098
1099    DES3 has a key size of 168 bits, but just like plain DES, useless
1100 parity bits are inserted, so that keys are represented as 24 octets
1101 (192 bits).  As a 112 bit key is large enough to make brute force
1102 attacks impractical, some applications uses a "two-key" variant of
1103 triple-DES.  In this mode, the same key bits are used for the first and
1104 the last DES box in the pipe, while the middle box is keyed
1105 independently. The two-key variant is believed to be secure, i.e. there
1106 are no known attacks significantly better than brute force.
1107
1108    Naturally, it's simple to implement triple-DES on top of Nettle's DES
1109 functions. Nettle includes an implementation of three-key "ede"
1110 triple-DES, it is defined in the same place as plain DES,
1111 `<nettle/des.h>'.
1112
1113  - Context struct: struct des3_ctx
1114
1115  - Constant: DES3_BLOCK_SIZE
1116      The DES3 block-size is the same as DES_BLOCK_SIZE, 8
1117
1118  - Constant: DES3_KEY_SIZE
1119      DES key size, 24
1120
1121  - Function: int des3_set_key (struct des3_ctx *CTX, const uint8_t *KEY)
1122      Initialize the cipher. The same function is used for both
1123      encryption and decryption. Parity bits are ignored. Checks for
1124      weak keys, returning 1 if all three keys are good keys, and 0 if
1125      one or more key is weak.  Applications that don't care about weak
1126      keys can ignore the return value.
1127
1128    For random-looking strings, you can use `des_fix_parity' to adjust
1129 the parity bits before calling `des3_set_key'.
1130
1131  - Function: void des3_encrypt (struct des3_ctx *CTX, unsigned LENGTH,
1132           const uint8_t *DST, uint8_t *SRC)
1133      Encryption function. LENGTH must be an integral multiple of the
1134      block size. If it is more than one block, the data is processed in
1135      ECB mode. `src' and `dst' may be equal, but they must not overlap
1136      in any other way.
1137
1138  - Function: void des3_decrypt (struct des3_ctx *CTX, unsigned LENGTH,
1139           const uint8_t *DST, uint8_t *SRC)
1140      Analogous to `des_encrypt'
1141
1142 SERPENT
1143 -------
1144
1145 SERPENT is one of the AES finalists, designed by Ross Anderson, Eli
1146 Biham and Lars Knudsen. Thus, the interface and properties are similar
1147 to AES'. One peculiarity is that it is quite pointless to use it with
1148 anything but the maximum key size, smaller keys are just padded to
1149 larger ones. Nettle defines SERPENT in `<nettle/serpent.h>'.
1150
1151  - Context struct: struct serpent_ctx
1152
1153  - Constant: SERPENT_BLOCK_SIZE
1154      The SERPENT block-size, 16
1155
1156  - Constant: SERPENT_MIN_KEY_SIZE
1157      Minimum SERPENT key size, 16
1158
1159  - Constant: SERPENT_MAX_KEY_SIZE
1160      Maximum SERPENT key size, 32
1161
1162  - Constant: SERPENT_KEY_SIZE
1163      Default SERPENT key size, 32
1164
1165  - Function: void serpent_set_key (struct serpent_ctx *CTX, unsigned
1166           LENGTH, const uint8_t *KEY)
1167      Initialize the cipher. The same function is used for both
1168      encryption and decryption.
1169
1170  - Function: void serpent_encrypt (struct serpent_ctx *CTX, unsigned
1171           LENGTH, const uint8_t *DST, uint8_t *SRC)
1172      Encryption function. LENGTH must be an integral multiple of the
1173      block size. If it is more than one block, the data is processed in
1174      ECB mode. `src' and `dst' may be equal, but they must not overlap
1175      in any other way.
1176
1177  - Function: void serpent_decrypt (struct serpent_ctx *CTX, unsigned
1178           LENGTH, const uint8_t *DST, uint8_t *SRC)
1179      Analogous to `serpent_encrypt'
1180
1181 TWOFISH
1182 -------
1183
1184 Another AES finalist, this one designed by Bruce Schneier and others.
1185 Nettle defines it in `<nettle/twofish.h>'.
1186
1187  - Context struct: struct twofish_ctx
1188
1189  - Constant: TWOFISH_BLOCK_SIZE
1190      The TWOFISH block-size, 16
1191
1192  - Constant: TWOFISH_MIN_KEY_SIZE
1193      Minimum TWOFISH key size, 16
1194
1195  - Constant: TWOFISH_MAX_KEY_SIZE
1196      Maximum TWOFISH key size, 32
1197
1198  - Constant: TWOFISH_KEY_SIZE
1199      Default TWOFISH key size, 32
1200
1201  - Function: void twofish_set_key (struct twofish_ctx *CTX, unsigned
1202           LENGTH, const uint8_t *KEY)
1203      Initialize the cipher. The same function is used for both
1204      encryption and decryption.
1205
1206  - Function: void twofish_encrypt (struct twofish_ctx *CTX, unsigned
1207           LENGTH, const uint8_t *DST, uint8_t *SRC)
1208      Encryption function. LENGTH must be an integral multiple of the
1209      block size. If it is more than one block, the data is processed in
1210      ECB mode. `src' and `dst' may be equal, but they must not overlap
1211      in any other way.
1212
1213  - Function: void twofish_decrypt (struct twofish_ctx *CTX, unsigned
1214           LENGTH, const uint8_t *DST, uint8_t *SRC)
1215      Analogous to `twofish_encrypt'
1216
1217 `struct nettle_cipher'
1218 ----------------------
1219
1220 Nettle includes a struct including information about some of the more
1221 regular cipher functions. It should be considered a little experimental,
1222 but can be useful for applications that need a simple way to handle
1223 various algorithms. Nettle defines these structs in
1224 `<nettle/nettle-meta.h>'.
1225
1226  - Meta struct: `struct nettle_cipher' name context_size block_size
1227           key_size set_encrypt_key set_decrypt_key encrypt decrypt
1228      The last four attributes are function pointers, of types
1229      `nettle_set_key_func' and `nettle_crypt_func'. The first argument
1230      to these functions is a `void *' pointer to a context struct,
1231      which is of size `context_size'.
1232
1233  - Constant Struct: struct nettle_cipher nettle_aes128
1234  - Constant Struct: struct nettle_cipher nettle_aes192
1235  - Constant Struct: struct nettle_cipher nettle_aes256
1236  - Constant Struct: struct nettle_cipher nettle_arctwo40;
1237  - Constant Struct: struct nettle_cipher nettle_arctwo64;
1238  - Constant Struct: struct nettle_cipher nettle_arctwo128;
1239  - Constant Struct: struct nettle_cipher nettle_arctwo_gutmann128;
1240  - Constant Struct: struct nettle_cipher nettle_arcfour128
1241  - Constant Struct: struct nettle_cipher nettle_camellia128
1242  - Constant Struct: struct nettle_cipher nettle_camellia192
1243  - Constant Struct: struct nettle_cipher nettle_camellia256
1244  - Constant Struct: struct nettle_cipher nettle_cast128
1245  - Constant Struct: struct nettle_cipher nettle_serpent128
1246  - Constant Struct: struct nettle_cipher nettle_serpent192
1247  - Constant Struct: struct nettle_cipher nettle_serpent256
1248  - Constant Struct: struct nettle_cipher nettle_twofish128
1249  - Constant Struct: struct nettle_cipher nettle_twofish192
1250  - Constant Struct: struct nettle_cipher nettle_twofish256
1251  - Constant Struct: struct nettle_cipher nettle_arctwo40;
1252  - Constant Struct: struct nettle_cipher nettle_arctwo64;
1253  - Constant Struct: struct nettle_cipher nettle_arctwo128;
1254  - Constant Struct: struct nettle_cipher nettle_arctwo_gutmann128;
1255      Nettle includes such structs for all the _regular_ ciphers, i.e.
1256      ones without weak keys or other oddities.
1257
1258 \1f
1259 File: nettle.info,  Node: Cipher modes,  Next: Keyed hash functions,  Prev: Cipher functions,  Up: Reference
1260
1261 Cipher modes
1262 ============
1263
1264 Cipher modes of operation specifies the procedure to use when
1265 encrypting a message that is larger than the cipher's block size. As
1266 explained in *Note Cipher functions::, splitting the message into blocks
1267 and processing them independently with the block cipher (Electronic Code
1268 Book mode, ECB) leaks information. Besides ECB, Nettle provides two
1269 other modes of operation: Cipher Block Chaining (CBC) and Counter mode
1270 (CTR). CBC is widely used, but there are a few subtle issues of
1271 information leakage.  CTR was standardized more recently, and is
1272 believed to be more secure.
1273
1274 Cipher Block Chaining
1275 ---------------------
1276
1277 When using CBC mode, plaintext blocks are not encrypted independently
1278 of each other, like in Electronic Cook Book mode. Instead, when
1279 encrypting a block in CBC mode, the previous ciphertext block is XORed
1280 with the plaintext before it is fed to the block cipher.  When
1281 encrypting the first block, a random block called an "IV", or
1282 Initialization Vector, is used as the "previous ciphertext block". The
1283 IV should be chosen randomly, but it need not be kept secret, and can
1284 even be transmitted in the clear together with the encrypted data.
1285
1286    In symbols, if `E_k' is the encryption function of a block cipher,
1287 and `IV' is the initialization vector, then `n' plaintext blocks
1288 `M_1',... `M_n' are transformed into `n' ciphertext blocks `C_1',...
1289 `C_n' as follows:
1290
1291      C_1 = E_k(IV  XOR M_1)
1292      C_2 = E_k(C_1 XOR M_2)
1293      
1294      ...
1295      
1296      C_n = E_k(C_(n-1) XOR M_n)
1297
1298    Nettle's includes two functions for applying a block cipher in Cipher
1299 Block Chaining (CBC) mode, one for encryption and one for decryption.
1300 These functions uses `void *' to pass cipher contexts around.
1301
1302  - Function: void cbc_encrypt (void *CTX, nettle_crypt_func F, unsigned
1303           BLOCK_SIZE, uint8_t *IV, unsigned LENGTH, uint8_t *DST, const
1304           uint8_t *SRC)
1305  - Function: void cbc_decrypt (void *CTX, void (*F)(), unsigned
1306           BLOCK_SIZE, uint8_t *IV, unsigned LENGTH, uint8_t *DST, const
1307           uint8_t *SRC)
1308      Applies the encryption or decryption function F in CBC mode. The
1309      final ciphertext block processed is copied into IV before
1310      returning, so that large message be processed be a sequence of
1311      calls to `cbc_encrypt'. The function F is of type
1312
1313      `void f (void *CTX, unsigned LENGTH, uint8_t DST, const uint8_t
1314      *SRC)',
1315
1316      and the `cbc_encrypt' and `cbc_decrypt' functions pass their
1317      argument CTX on to F.
1318
1319    There are also some macros to help use these functions correctly.
1320
1321  - Macro: CBC_CTX (CONTEXT_TYPE, BLOCK_SIZE)
1322      Expands into
1323           {
1324              context_type ctx;
1325              uint8_t iv[block_size];
1326           }
1327
1328    It can be used to define a CBC context struct, either directly,
1329
1330      struct CBC_CTX(struct aes_ctx, AES_BLOCK_SIZE) ctx;
1331
1332    or to give it a struct tag,
1333
1334      struct aes_cbc_ctx CBC_CTX (struct aes_ctx, AES_BLOCK_SIZE);
1335
1336  - Macro: CBC_SET_IV (CTX, IV)
1337      First argument is a pointer to a context struct as defined by
1338      `CBC_CTX', and the second is a pointer to an Initialization Vector
1339      (IV) that is copied into that context.
1340
1341  - Macro: CBC_ENCRYPT (CTX, F, LENGTH, DST, SRC)
1342  - Macro: CBC_DECRYPT (CTX, F, LENGTH, DST, SRC)
1343      A simpler way to invoke `cbc_encrypt' and `cbc_decrypt'. The first
1344      argument is a pointer to a context struct as defined by `CBC_CTX',
1345      and the second argument is an encryption or decryption function
1346      following Nettle's conventions. The last three arguments define
1347      the source and destination area for the operation.
1348
1349    These macros use some tricks to make the compiler display a warning
1350 if the types of F and CTX don't match, e.g. if you try to use an
1351 `struct aes_ctx' context with the `des_encrypt' function.
1352
1353 Counter mode
1354 ------------
1355
1356 Counter mode (CTR) uses the block cipher as a keyed pseudo-random
1357 generator. The output of the generator is XORed with the data to be
1358 encrypted. It can be understood as a way to transform a block cipher to
1359 a stream cipher.
1360
1361    The message is divided into `n' blocks `M_1',...  `M_n', where `M_n'
1362 is of size `m' which may be smaller than the block size. Except for the
1363 last block, all the message blocks must be of size equal to the
1364 cipher's block size.
1365
1366    If `E_k' is the encryption function of a block cipher, `IC' is the
1367 initial counter, then the `n' plaintext blocks are transformed into `n'
1368 ciphertext blocks `C_1',...  `C_n' as follows:
1369
1370      C_1 = E_k(IC) XOR M_1
1371      C_2 = E_k(IC + 1) XOR M_2
1372      
1373      ...
1374      
1375      C_(n-1) = E_k(IC + n - 2) XOR M_(n-1)
1376      C_n = E_k(IC + n - 1) [1..m] XOR M_n
1377
1378    The IC is the initial value for the counter, it plays a similar role
1379 as the IV for CBC. When adding, `IC + x', IC is interpreted as an
1380 integer, in network byte order. For the last block, `E_k(IC + n - 1)
1381 [1..m]' means that the cipher output is truncated to `m' bytes.
1382
1383  - Function: void ctr_crypt (void *CTX, nettle_crypt_func F, unsigned
1384           BLOCK_SIZE, uint8_t *CTR, unsigned LENGTH, uint8_t *DST,
1385           const uint8_t *SRC)
1386      Applies the encryption function F in CTR mode. Note that for CTR
1387      mode, encryption and decryption is the same operation, and hence F
1388      should always be the encryption function for the underlying block
1389      cipher.
1390
1391      When a message is encrypted using a sequence of calls to
1392      `ctr_crypt', all but the last call _must_ use a length that is a
1393      multiple of the block size.
1394
1395    Like for CBC, there are also a couple of helper macros.
1396
1397  - Macro: CTR_CTX (CONTEXT_TYPE, BLOCK_SIZE)
1398      Expands into
1399           {
1400              context_type ctx;
1401              uint8_t ctr[block_size];
1402           }
1403
1404  - Macro: CTR_SET_COUNTER (CTX, IV)
1405      First argument is a pointer to a context struct as defined by
1406      `CTR_CTX', and the second is a pointer to an initial counter that
1407      is copied into that context.
1408
1409  - Macro: CTR_CRYPT (CTX, F, LENGTH, DST, SRC)
1410      A simpler way to invoke `ctr_crypt'. The first argument is a
1411      pointer to a context struct as defined by `CTR_CTX', and the second
1412      argument is an encryption function following Nettle's conventions.
1413      The last three arguments define the source and destination area
1414      for the operation.
1415
1416 \1f
1417 File: nettle.info,  Node: Keyed hash functions,  Next: Public-key algorithms,  Prev: Cipher modes,  Up: Reference
1418
1419 Keyed Hash Functions
1420 ====================
1421
1422 A "keyed hash function", or "Message Authentication Code" (MAC) is a
1423 function that takes a key and a message, and produces fixed size MAC.
1424 It should be hard to compute a message and a matching MAC without
1425 knowledge of the key. It should also be hard to compute the key given
1426 only messages and corresponding MACs.
1427
1428    Keyed hash functions are useful primarily for message authentication,
1429 when Alice and Bob shares a secret: The sender, Alice, computes the MAC
1430 and attaches it to the message. The receiver, Bob, also computes the
1431 MAC of the message, using the same key, and compares that to Alice's
1432 value. If they match, Bob can be assured that the message has not been
1433 modified on its way from Alice.
1434
1435    However, unlike digital signatures, this assurance is not
1436 transferable.  Bob can't show the message and the MAC to a third party
1437 and prove that Alice sent that message. Not even if he gives away the
1438 key to the third party. The reason is that the _same_ key is used on
1439 both sides, and anyone knowing the key can create a correct MAC for any
1440 message. If Bob believes that only he and Alice knows the key, and he
1441 knows that he didn't attach a MAC to a particular message, he knows it
1442 must be Alice who did it. However, the third party can't distinguish
1443 between a MAC created by Alice and one created by Bob.
1444
1445    Keyed hash functions are typically a lot faster than digital
1446 signatures as well.
1447
1448 HMAC
1449 ----
1450
1451 One can build keyed hash functions from ordinary hash functions. Older
1452 constructions simply concatenate secret key and message and hashes
1453 that, but such constructions have weaknesses. A better construction is
1454 HMAC, described in `RFC 2104'.
1455
1456    For an underlying hash function `H', with digest size `l' and
1457 internal block size `b', HMAC-H is constructed as follows: From a given
1458 key `k', two distinct subkeys `k_i' and `k_o' are constructed, both of
1459 length `b'. The HMAC-H of a message `m' is then computed as `H(k_o |
1460 H(k_i | m))', where `|' denotes string concatenation.
1461
1462    HMAC keys can be of any length, but it is recommended to use keys of
1463 length `l', the digest size of the underlying hash function `H'. Keys
1464 that are longer than `b' are shortened to length `l' by hashing with
1465 `H', so arbitrarily long keys aren't very useful.
1466
1467    Nettle's HMAC functions are defined in `<nettle/hmac.h>'.  There are
1468 abstract functions that use a pointer to a `struct nettle_hash' to
1469 represent the underlying hash function and `void *' pointers that point
1470 to three different context structs for that hash function. There are
1471 also concrete functions for HMAC-MD5, HMAC-SHA1, HMAC-SHA256, and
1472 HMAC-SHA512.  First, the abstract functions:
1473
1474  - Function: void hmac_set_key (void *OUTER, void *INNER, void *STATE,
1475           const struct nettle_hash *H, unsigned LENGTH, const uint8_t
1476           *KEY)
1477      Initializes the three context structs from the key. The OUTER and
1478      INNER contexts corresponds to the subkeys `k_o' and `k_i'. STATE
1479      is used for hashing the message, and is initialized as a copy of
1480      the INNER context.
1481
1482  - Function: void hmac_update (void *STATE, const struct nettle_hash
1483           *H, unsigned LENGTH, const uint8_t *DATA)
1484      This function is called zero or more times to process the message.
1485      Actually, `hmac_update(state, H, length, data)' is equivalent to
1486      `H->update(state, length, data)', so if you wish you can use the
1487      ordinary update function of the underlying hash function instead.
1488
1489  - Function: void hmac_digest (const void *OUTER, const void *INNER,
1490           void *STATE, const struct nettle_hash *H, unsigned LENGTH,
1491           uint8_t *DIGEST)
1492      Extracts the MAC of the message, writing it to DIGEST.  OUTER and
1493      INNER are not modified. LENGTH is usually equal to
1494      `H->digest_size', but if you provide a smaller value, only the
1495      first LENGTH octets of the MAC are written.
1496
1497      This function also resets the STATE context so that you can start
1498      over processing a new message (with the same key).
1499
1500    Like for CBC, there are some macros to help use these functions
1501 correctly.
1502
1503  - Macro: HMAC_CTX (TYPE)
1504      Expands into
1505           {
1506              type outer;
1507              type inner;
1508              type state;
1509           }
1510
1511    It can be used to define a HMAC context struct, either directly,
1512
1513      struct HMAC_CTX(struct md5_ctx) ctx;
1514
1515    or to give it a struct tag,
1516
1517      struct hmac_md5_ctx HMAC_CTX (struct md5_ctx);
1518
1519  - Macro: HMAC_SET_KEY (CTX, H, LENGTH, KEY)
1520      CTX is a pointer to a context struct as defined by `HMAC_CTX', H
1521      is a pointer to a `const struct nettle_hash' describing the
1522      underlying hash function (so it must match the type of the
1523      components of CTX). The last two arguments specify the secret key.
1524
1525  - Macro: HMAC_DIGEST (CTX, H, LENGTH, DIGEST)
1526      CTX is a pointer to a context struct as defined by `HMAC_CTX', H
1527      is a pointer to a `const struct nettle_hash' describing the
1528      underlying hash function. The last two arguments specify where the
1529      digest is written.
1530
1531    Note that there is no `HMAC_UPDATE' macro; simply call `hmac_update'
1532 function directly, or the update function of the underlying hash
1533 function.
1534
1535 Concrete HMAC functions
1536 -----------------------
1537
1538 Now we come to the specialized HMAC functions, which are easier to use
1539 than the general HMAC functions.
1540
1541 HMAC-MD5
1542 ........
1543
1544  - Context struct: struct hmac_md5_ctx
1545
1546  - Function: void hmac_md5_set_key (struct hmac_md5_ctx *CTX, unsigned
1547           KEY_LENGTH, const uint8_t *KEY)
1548      Initializes the context with the key.
1549
1550  - Function: void hmac_md5_update (struct hmac_md5_ctx *CTX, unsigned
1551           LENGTH, const uint8_t *DATA)
1552      Process some more data.
1553
1554  - Function: void hmac_md5_digest (struct hmac_md5_ctx *CTX, unsigned
1555           LENGTH, uint8_t *DIGEST)
1556      Extracts the MAC, writing it to DIGEST. LENGTH may be smaller than
1557      `MD5_DIGEST_SIZE', in which case only the first LENGTH octets of
1558      the MAC are written.
1559
1560      This function also resets the context for processing new messages,
1561      with the same key.
1562
1563 HMAC-SHA1
1564 .........
1565
1566  - Context struct: struct hmac_sha1_ctx
1567
1568  - Function: void hmac_sha1_set_key (struct hmac_sha1_ctx *CTX,
1569           unsigned KEY_LENGTH, const uint8_t *KEY)
1570      Initializes the context with the key.
1571
1572  - Function: void hmac_sha1_update (struct hmac_sha1_ctx *CTX, unsigned
1573           LENGTH, const uint8_t *DATA)
1574      Process some more data.
1575
1576  - Function: void hmac_sha1_digest (struct hmac_sha1_ctx *CTX, unsigned
1577           LENGTH, uint8_t *DIGEST)
1578      Extracts the MAC, writing it to DIGEST. LENGTH may be smaller than
1579      `SHA1_DIGEST_SIZE', in which case only the first LENGTH octets of
1580      the MAC are written.
1581
1582      This function also resets the context for processing new messages,
1583      with the same key.
1584
1585 HMAC-SHA256
1586 ...........
1587
1588  - Context struct: struct hmac_sha256_ctx
1589
1590  - Function: void hmac_sha256_set_key (struct hmac_sha256_ctx *CTX,
1591           unsigned KEY_LENGTH, const uint8_t *KEY)
1592      Initializes the context with the key.
1593
1594  - Function: void hmac_sha256_update (struct hmac_sha256_ctx *CTX,
1595           unsigned LENGTH, const uint8_t *DATA)
1596      Process some more data.
1597
1598  - Function: void hmac_sha256_digest (struct hmac_sha256_ctx *CTX,
1599           unsigned LENGTH, uint8_t *DIGEST)
1600      Extracts the MAC, writing it to DIGEST. LENGTH may be smaller than
1601      `SHA256_DIGEST_SIZE', in which case only the first LENGTH octets
1602      of the MAC are written.
1603
1604      This function also resets the context for processing new messages,
1605      with the same key.
1606
1607 HMAC-SHA512
1608 ...........
1609
1610  - Context struct: struct hmac_sha512_ctx
1611
1612  - Function: void hmac_sha512_set_key (struct hmac_sha512_ctx *CTX,
1613           unsigned KEY_LENGTH, const uint8_t *KEY)
1614      Initializes the context with the key.
1615
1616  - Function: void hmac_sha512_update (struct hmac_sha512_ctx *CTX,
1617           unsigned LENGTH, const uint8_t *DATA)
1618      Process some more data.
1619
1620  - Function: void hmac_sha512_digest (struct hmac_sha512_ctx *CTX,
1621           unsigned LENGTH, uint8_t *DIGEST)
1622      Extracts the MAC, writing it to DIGEST. LENGTH may be smaller than
1623      `SHA512_DIGEST_SIZE', in which case only the first LENGTH octets
1624      of the MAC are written.
1625
1626      This function also resets the context for processing new messages,
1627      with the same key.
1628
1629 \1f
1630 File: nettle.info,  Node: Public-key algorithms,  Next: Randomness,  Prev: Keyed hash functions,  Up: Reference
1631
1632 Public-key algorithms
1633 =====================
1634
1635 Nettle uses GMP, the GNU bignum library, for all calculations with
1636 large numbers. In order to use the public-key features of Nettle, you
1637 must install GMP, at least version 3.0, before compiling Nettle, and
1638 you need to link your programs with `-lhogweed -lnettle -lgmp'.
1639
1640    The concept of "Public-key" encryption and digital signatures was
1641 discovered by Whitfield Diffie and Martin E. Hellman and described in a
1642 paper 1976. In traditional, "symmetric", cryptography, sender and
1643 receiver share the same keys, and these keys must be distributed in a
1644 secure way. And if there are many users or entities that need to
1645 communicate, each _pair_ needs a shared secret key known by nobody else.
1646
1647    Public-key cryptography uses trapdoor one-way functions. A "one-way
1648 function" is a function `F' such that it is easy to compute the value
1649 `F(x)' for any `x', but given a value `y', it is hard to compute a
1650 corresponding `x' such that `y = F(x)'. Two examples are cryptographic
1651 hash functions, and exponentiation in certain groups.
1652
1653    A "trapdoor one-way function" is a function `F' that is one-way,
1654 unless one knows some secret information about `F'. If one knows the
1655 secret, it is easy to compute both `F' and it's inverse.  If this
1656 sounds strange, look at the RSA example below.
1657
1658    Two important uses for one-way functions with trapdoors are
1659 public-key encryption, and digital signatures. The public-key
1660 encryption functions in Nettle are not yet documented; the rest of this
1661 chapter is about digital signatures.
1662
1663    To use a digital signature algorithm, one must first create a
1664 "key-pair": A public key and a corresponding private key. The private
1665 key is used to sign messages, while the public key is used for verifying
1666 that that signatures and messages match. Some care must be taken when
1667 distributing the public key; it need not be kept secret, but if a bad
1668 guy is able to replace it (in transit, or in some user's list of known
1669 public keys), bad things may happen.
1670
1671    There are two operations one can do with the keys. The signature
1672 operation takes a message and a private key, and creates a signature for
1673 the message. A signature is some string of bits, usually at most a few
1674 thousand bits or a few hundred octets. Unlike paper-and-ink signatures,
1675 the digital signature depends on the message, so one can't cut it out of
1676 context and glue it to a different message.
1677
1678    The verification operation takes a public key, a message, and a
1679 string that is claimed to be a signature on the message, and returns
1680 true or false. If it returns true, that means that the three input
1681 values matched, and the verifier can be sure that someone went through
1682 with the signature operation on that very message, and that the
1683 "someone" also knows the private key corresponding to the public key.
1684
1685    The desired properties of a digital signature algorithm are as
1686 follows: Given the public key and pairs of messages and valid
1687 signatures on them, it should be hard to compute the private key, and
1688 it should also be hard to create a new message and signature that is
1689 accepted by the verification operation.
1690
1691    Besides signing meaningful messages, digital signatures can be used
1692 for authorization. A server can be configured with a public key, such
1693 that any client that connects to the service is given a random nonce
1694 message.  If the server gets a reply with a correct signature matching
1695 the nonce message and the configured public key, the client is granted
1696 access. So the configuration of the server can be understood as "grant
1697 access to whoever knows the private key corresponding to this
1698 particular public key, and to no others".
1699
1700 * Menu:
1701
1702 * RSA::                         The RSA public key algorithm.
1703 * DSA::                         The DSA digital signature algorithm.
1704
1705 \1f
1706 File: nettle.info,  Node: RSA,  Next: DSA,  Prev: Public-key algorithms,  Up: Public-key algorithms
1707
1708 RSA
1709 ---
1710
1711 The RSA algorithm was the first practical digital signature algorithm
1712 that was constructed. It was described 1978 in a paper by Ronald
1713 Rivest, Adi Shamir and L.M. Adleman, and the technique was also
1714 patented in the USA in 1983. The patent expired on September 20, 2000,
1715 and since that day, RSA can be used freely, even in the USA.
1716
1717    It's remarkably simple to describe the trapdoor function behind RSA.
1718 The "one-way"-function used is
1719
1720      F(x) = x^e mod n
1721
1722    I.e. raise x to the `e':th power, while discarding all multiples of
1723 `n'. The pair of numbers `n' and `e' is the public key.  `e' can be
1724 quite small, even `e = 3' has been used, although slightly larger
1725 numbers are recommended. `n' should be about 1000 bits or larger.
1726
1727    If `n' is large enough, and properly chosen, the inverse of F, the
1728 computation of `e':th roots modulo `n', is very difficult.  But,
1729 where's the trapdoor?
1730
1731    Let's first look at how RSA key-pairs are generated. First `n' is
1732 chosen as the product of two large prime numbers `p' and `q' of roughly
1733 the same size (so if `n' is 1000 bits, `p' and `q' are about 500 bits
1734 each). One also computes the number `phi = (p-1)(q-1)', in mathematical
1735 speak, `phi' is the order of the multiplicative group of integers
1736 modulo n.
1737
1738    Next, `e' is chosen. It must have no factors in common with `phi' (in
1739 particular, it must be odd), but can otherwise be chosen more or less
1740 randomly. `e = 65537' is a popular choice, because it makes raising to
1741 the `e''th power particularly efficient, and being prime, it usually
1742 has no factors common with `phi'.
1743
1744    Finally, a number `d', `d < n' is computed such that `e d mod phi =
1745 1'. It can be shown that such a number exists (this is why `e' and
1746 `phi' must have no common factors), and that for all x,
1747
1748      (x^e)^d mod n = x^(ed) mod n = (x^d)^e mod n = x
1749
1750    Using Euclid's algorithm, `d' can be computed quite easily from
1751 `phi' and `e'. But it is still hard to get `d' without knowing `phi',
1752 which depends on the factorization of `n'.
1753
1754    So `d' is the trapdoor, if we know `d' and `y = F(x)', we can
1755 recover x as `y^d mod n'. `d' is also the private half of the RSA
1756 key-pair.
1757
1758    The most common signature operation for RSA is defined in `PKCS#1',
1759 a specification by RSA Laboratories. The message to be signed is first
1760 hashed using a cryptographic hash function, e.g.  MD5 or SHA1. Next,
1761 some padding, the ASN.1 "Algorithm Identifier" for the hash function,
1762 and the message digest itself, are concatenated and converted to a
1763 number `x'. The signature is computed from `x' and the private key as
1764 `s = x^d mod n'(1) (*note RSA-Footnote-1::). The signature, `s' is a
1765 number of about the same size of `n', and it usually encoded as a
1766 sequence of octets, most significant octet first.
1767
1768    The verification operation is straight-forward, `x' is computed from
1769 the message in the same way as above. Then `s^e mod n' is computed, the
1770 operation returns true if and only if the result equals `x'.
1771
1772 Nettle's RSA support
1773 --------------------
1774
1775 Nettle represents RSA keys using two structures that contain large
1776 numbers (of type `mpz_t').
1777
1778  - Context struct: rsa_public_key size n e
1779      `size' is the size, in octets, of the modulo, and is used
1780      internally.  `n' and `e' is the public key.
1781
1782  - Context struct: rsa_private_key size d p q a b c
1783      `size' is the size, in octets, of the modulo, and is used
1784      internally.  `d' is the secret exponent, but it is not actually
1785      used when signing. Instead, the factors `p' and `q', and the
1786      parameters `a', `b' and `c' are used. They are computed from `p',
1787      `q' and `e' such that `a e mod (p - 1) = 1, b e mod (q - 1) = 1, c
1788      q mod p = 1'.
1789
1790    Before use, these structs must be initialized by calling one of
1791
1792  - Function: void rsa_public_key_init (struct rsa_public_key *PUB)
1793  - Function: void rsa_private_key_init (struct rsa_private_key *KEY)
1794      Calls `mpz_init' on all numbers in the key struct.
1795
1796    and when finished with them, the space for the numbers must be
1797 deallocated by calling one of
1798
1799  - Function: void rsa_public_key_clear (struct rsa_public_key *PUB)
1800  - Function: void rsa_private_key_clear (struct rsa_private_key *KEY)
1801      Calls `mpz_clear' on all numbers in the key struct.
1802
1803    In general, Nettle's RSA functions deviates from Nettle's "no memory
1804 allocation"-policy. Space for all the numbers, both in the key structs
1805 above, and temporaries, are allocated dynamically. For information on
1806 how to customize allocation, see *Note GMP Allocation: (gmp)Custom
1807 Allocation.
1808
1809    When you have assigned values to the attributes of a key, you must
1810 call
1811
1812  - Function: int rsa_public_key_prepare (struct rsa_public_key *PUB)
1813  - Function: int rsa_private_key_prepare (struct rsa_private_key *KEY)
1814      Computes the octet size of the key (stored in the `size' attribute,
1815      and may also do other basic sanity checks. Returns one if
1816      successful, or zero if the key can't be used, for instance if the
1817      modulo is smaller than the minimum size needed for RSA operations
1818      specified by PKCS#1.
1819
1820    Before signing or verifying a message, you first hash it with the
1821 appropriate hash function. You pass the hash function's context struct
1822 to the RSA signature function, and it will extract the message digest
1823 and do the rest of the work. There are also alternative functions that
1824 take the hash digest as argument.
1825
1826    There is currently no support for using SHA224 or SHA384 with RSA
1827 signatures, since there's no gain in either computation time nor
1828 message size compared to using SHA256 and SHA512, respectively.
1829
1830    Creation and verification of signatures is done with the following
1831 functions:
1832
1833  - Function: int rsa_md5_sign (const struct rsa_private_key *KEY,
1834           struct md5_ctx *HASH, mpz_t SIGNATURE)
1835  - Function: int rsa_sha1_sign (const struct rsa_private_key *KEY,
1836           struct sha1_ctx *HASH, mpz_t SIGNATURE)
1837  - Function: int rsa_sha256_sign (const struct rsa_private_key *KEY,
1838           struct sha256_ctx *HASH, mpz_t SIGNATURE)
1839  - Function: int rsa_sha512_sign (const struct rsa_private_key *KEY,
1840           struct sha512_ctx *HASH, mpz_t SIGNATURE)
1841      The signature is stored in SIGNATURE (which must have been
1842      `mpz_init''ed earlier). The hash context is reset so that it can be
1843      used for new messages. Returns one on success, or zero on failure.
1844      Signing fails if the key is too small for the given hash size,
1845      e.g., it's not possible to create a signature using SHA512 and a
1846      512-bit RSA key.
1847
1848  - Function: int rsa_md5_sign_digest (const struct rsa_private_key
1849           *KEY, const uint8_t *DIGEST, mpz_t SIGNATURE)
1850  - Function: int rsa_sha1_sign_digest (const struct rsa_private_key
1851           *KEY, const uint8_t *DIGEST, mpz_t SIGNATURE);
1852  - Function: int rsa_sha256_sign_digest (const struct rsa_private_key
1853           *KEY, const uint8_t *DIGEST, mpz_t SIGNATURE);
1854  - Function: int rsa_sha512_sign_digest (const struct rsa_private_key
1855           *KEY, const uint8_t *DIGEST, mpz_t SIGNATURE);
1856      Creates a signature from the given hash digest. DIGEST should
1857      point to a digest of size `MD5_DIGEST_SIZE', `SHA1_DIGEST_SIZE',
1858      or `SHA256_DIGEST_SIZE', respectively. The signature is stored in
1859      SIGNATURE (which must have been `mpz_init':ed earlier). Returns
1860      one on success, or zero on failure.
1861
1862  - Function: int rsa_md5_verify (const struct rsa_public_key *KEY,
1863           struct md5_ctx *HASH, const mpz_t SIGNATURE)
1864  - Function: int rsa_sha1_verify (const struct rsa_public_key *KEY,
1865           struct sha1_ctx *HASH, const mpz_t SIGNATURE)
1866  - Function: int rsa_sha256_verify (const struct rsa_public_key *KEY,
1867           struct sha256_ctx *HASH, const mpz_t SIGNATURE)
1868  - Function: int rsa_sha512_verify (const struct rsa_public_key *KEY,
1869           struct sha512_ctx *HASH, const mpz_t SIGNATURE)
1870      Returns 1 if the signature is valid, or 0 if it isn't. In either
1871      case, the hash context is reset so that it can be used for new
1872      messages.
1873
1874  - Function: int rsa_md5_verify_digest (const struct rsa_public_key
1875           *KEY, const uint8_t *DIGEST, const mpz_t SIGNATURE)
1876  - Function: int rsa_sha1_verify_digest (const struct rsa_public_key
1877           *KEY, const uint8_t *DIGEST, const mpz_t SIGNATURE)
1878  - Function: int rsa_sha256_verify_digest (const struct rsa_public_key
1879           *KEY, const uint8_t *DIGEST, const mpz_t SIGNATURE)
1880  - Function: int rsa_sha512_verify_digest (const struct rsa_public_key
1881           *KEY, const uint8_t *DIGEST, const mpz_t SIGNATURE)
1882      Returns 1 if the signature is valid, or 0 if it isn't. DIGEST
1883      should point to a digest of size `MD5_DIGEST_SIZE',
1884      `SHA1_DIGEST_SIZE', or `SHA256_DIGEST_SIZE', respectively.
1885
1886    If you need to use the RSA trapdoor, the private key, in a way that
1887 isn't supported by the above functions Nettle also includes a function
1888 that computes `x^d mod n' and nothing more, using the CRT optimization.
1889
1890  - Function: void rsa_compute_root (struct rsa_private_key *KEY, mpz_t
1891           X, const mpz_t M)
1892      Computes `x = m^d', efficiently.
1893
1894    At last, how do you create new keys?
1895
1896  - Function: int rsa_generate_keypair (struct rsa_public_key *PUB,
1897           struct rsa_private_key *KEY, void *RANDOM_CTX,
1898           nettle_random_func RANDOM, void *PROGRESS_CTX,
1899           nettle_progress_func PROGRESS, unsigned N_SIZE, unsigned
1900           E_SIZE);
1901      There are lots of parameters. PUB and KEY is where the resulting
1902      key pair is stored. The structs should be initialized, but you
1903      don't need to call `rsa_public_key_prepare' or
1904      `rsa_private_key_prepare' after key generation.
1905
1906      RANDOM_CTX and RANDOM is a randomness generator.
1907      `random(random_ctx, length, dst)' should generate `length' random
1908      octets and store them at `dst'. For advice, see *Note Randomness::.
1909
1910      PROGRESS and PROGRESS_CTX can be used to get callbacks during the
1911      key generation process, in order to uphold an illusion of
1912      progress. PROGRESS can be NULL, in that case there are no
1913      callbacks.
1914
1915      SIZE_N is the desired size of the modulo, in bits. If SIZE_E is
1916      non-zero, it is the desired size of the public exponent and a
1917      random exponent of that size is selected. But if E_SIZE is zero,
1918      it is assumed that the caller has already chosen a value for `e',
1919      and stored it in PUB.  Returns one on success, and zero on
1920      failure. The function can fail for example if if N_SIZE is too
1921      small, or if E_SIZE is zero and `pub->e' is an even number.
1922
1923 \1f
1924 File: nettle.info,  Node: RSA-Footnotes,  Up: RSA
1925
1926    (1) Actually, the computation is not done like this, it is done more
1927 efficiently using `p', `q' and the Chinese remainder theorem (CRT). But
1928 the result is the same.
1929
1930 \1f
1931 File: nettle.info,  Node: DSA,  Prev: RSA,  Up: Public-key algorithms
1932
1933 Nettle's DSA support
1934 --------------------
1935
1936 The DSA digital signature algorithm is more complex than RSA. It was
1937 specified during the early 1990s, and in 1994 NIST published FIPS 186
1938 which is the authoritative specification.  Sometimes DSA is referred to
1939 using the acronym DSS, for Digital Signature Standard. The most recent
1940 revision of the specification, FIPS186-3, was issueed in 2009, and it
1941 adds support for larger hash functions than sha1.
1942
1943    For DSA, the underlying mathematical problem is the computation of
1944 discreet logarithms. The public key consists of a large prime `p', a
1945 small prime `q' which is a factor of `p-1', a number `g' which
1946 generates a subgroup of order `q' modulo `p', and an element `y' in
1947 that subgroup.
1948
1949    In the original DSA, the size of `q' is fixed to 160 bits, to match
1950 with the SHA1 hash algorithm. The size of `p' is in principle
1951 unlimited, but the standard specifies only nine specific sizes: `512 +
1952 l*64', where `l' is between 0 and 8. Thus, the maximum size of `p' is
1953 1024 bits, and sizes less than 1024 bits are considered obsolete and not
1954 secure.
1955
1956    The subgroup requirement means that if you compute
1957
1958      g^t mod p
1959
1960    for all possible integers `t', you will get precisely `q' distinct
1961 values.
1962
1963    The private key is a secret exponent `x', such that
1964
1965      g^x = y mod p
1966
1967    In mathematical speak, `x' is the "discrete logarithm" of `y' mod
1968 `p', with respect to the generator `g'. The size of `x' will also be
1969 about the same size as `q'. The security of the DSA algorithm relies on
1970 the difficulty of the discrete logarithm problem. Current algorithms to
1971 compute discrete logarithms in this setting, and hence crack DSA, are
1972 of two types. The first type works directly in the (multiplicative)
1973 group of integers mod `p'. The best known algorithm of this type is the
1974 Number Field Sieve, and it's complexity is similar to the complexity of
1975 factoring numbers of the same size as `p'. The other type works in the
1976 smaller `q'-sized subgroup generated by `g', which has a more difficult
1977 group structure. One good algorithm is Pollard-rho, which has
1978 complexity `sqrt(q)'.
1979
1980    The important point is that security depends on the size of _both_
1981 `p' and `q', and they should be choosen so that the difficulty of both
1982 discrete logarithm methods are comparable. Today, the security margin
1983 of the original DSA may be uncomfortably small. Using a `p' of 1024
1984 bits implies that cracking using the number field sieve is expected to
1985 take about the same time as factoring a 1024-bit RSA modulo, and using
1986 a `q' of size 160 bits implies that cracking using Pollard-rho will
1987 take roughly `2^80' group operations. With the size of `q' fixed, tied
1988 to the SHA1 digest size, it may be tempting to increase the size of `p'
1989 to, say, 4096 bits. This will provide excellent resistance against
1990 attacks like the number field sieve which works in the large group. But
1991 it will do very little to defend against Pollard-rho attacking the small
1992 subgroup; the attacker is slowed down at most by a single factor of 10
1993 due to the more expensive group operation. And the attacker will surely
1994 choose the latter attack.
1995
1996    The signature generation algorithm is randomized; in order to create
1997 a DSA signature, you need a good source for random numbers (*note
1998 Randomness::). Let us describe the common case of a 160-bit `q'.
1999
2000    To create a signature, one starts with the hash digest of the
2001 message, `h', which is a 160 bit number, and a random number `k,
2002 0<k<q', also 160 bits. Next, one computes
2003
2004      r = (g^k mod p) mod q
2005      s = k^-1 (h + x r) mod q
2006
2007    The signature is the pair `(r, s)', two 160 bit numbers. Note the
2008 two different mod operations when computing `r', and the use of the
2009 secret exponent `x'.
2010
2011    To verify a signature, one first checks that `0 < r,s < q', and then
2012 one computes backwards,
2013
2014      w = s^-1 mod q
2015      v = (g^(w h) y^(w r) mod p) mod q
2016
2017    The signature is valid if `v = r'. This works out because `w = s^-1
2018 mod q = k (h + x r)^-1 mod q', so that
2019
2020      g^(w h) y^(w r) = g^(w h) (g^x)^(w r) = g^(w (h + x r)) = g^k
2021
2022    When reducing mod `q' this yields `r'. Note that when verifying a
2023 signature, we don't know either `k' or `x': those numbers are secret.
2024
2025    If you can choose between RSA and DSA, which one is best? Both are
2026 believed to be secure. DSA gained popularity in the late 1990s, as a
2027 patent free alternative to RSA. Now that the RSA patents have expired,
2028 there's no compelling reason to want to use DSA. Today, the original
2029 DSA key size does not provide a large security margin, and it should
2030 probably be phased out together with RSA keys of 1024 bits. Using the
2031 revised DSA algorithm with a larger hash function, in particular,
2032 SHA256, a 256-bit `q', and `p' of size 2048 bits or more, should
2033 provide for a more comfortable security margin, but these variants are
2034 not yet in wide use.
2035
2036    DSA signatures are smaller than RSA signatures, which is important
2037 for some specialized applications.
2038
2039    From a practical point of view, DSA's need for a good randomness
2040 source is a serious disadvantage. If you ever use the same `k' (and
2041 `r') for two different message, you leak your private key.
2042
2043 Nettle's DSA support
2044 --------------------
2045
2046 Like for RSA, Nettle represents DSA keys using two structures,
2047 containing values of type `mpz_t'. For information on how to customize
2048 allocation, see *Note GMP Allocation: (gmp)Custom Allocation.
2049
2050    Most of the DSA functions are very similar to the corresponding RSA
2051 functions, but there are a few differences pointed out below. For a
2052 start, there are no functions corresponding to `rsa_public_key_prepare'
2053 and `rsa_private_key_prepare'.
2054
2055  - Context struct: dsa_public_key p q g y
2056      The public parameters described above.
2057
2058  - Context struct: dsa_private_key x
2059      The private key `x'.
2060
2061    Before use, these structs must be initialized by calling one of
2062
2063  - Function: void dsa_public_key_init (struct dsa_public_key *PUB)
2064  - Function: void dsa_private_key_init (struct dsa_private_key *KEY)
2065      Calls `mpz_init' on all numbers in the key struct.
2066
2067    When finished with them, the space for the numbers must be
2068 deallocated by calling one of
2069
2070  - Function: void dsa_public_key_clear (struct dsa_public_key *PUB)
2071  - Function: void dsa_private_key_clear (struct dsa_private_key *KEY)
2072      Calls `mpz_clear' on all numbers in the key struct.
2073
2074    Signatures are represented using the structure below, and need to be
2075 initialized and cleared in the same way as the key structs.
2076
2077  - Context struct: dsa_signature r s
2078
2079  - Function: void dsa_signature_init (struct dsa_signature *SIGNATURE)
2080  - Function: void dsa_signature_clear (struct dsa_signature *SIGNATURE)
2081      You must call `dsa_signature_init' before creating or using a
2082      signature, and call `dsa_signature_clear' when you are finished
2083      with it.
2084
2085    For signing, you need to provide both the public and the private key
2086 (unlike RSA, where the private key struct includes all information
2087 needed for signing), and a source for random numbers.  Signatures can
2088 use the SHA1 or the SHA256 hash function, although the implementation
2089 of DSA with SHA256 should be considered somewhat experimental due to
2090 lack of official test vectors and interoperability testing.
2091
2092  - Function: int dsa_sha1_sign (const struct dsa_public_key *PUB, const
2093           struct dsa_private_key *KEY, void *RANDOM_CTX,
2094           nettle_random_func RANDOM, struct sha1_ctx *HASH, struct
2095           dsa_signature *SIGNATURE)
2096  - Function: int dsa_sha1_sign_digest (const struct dsa_public_key
2097           *PUB, const struct dsa_private_key *KEY, void *RANDOM_CTX,
2098           nettle_random_func RANDOM, const uint8_t *DIGEST, struct
2099           dsa_signature *SIGNATURE)
2100  - Function: int dsa_sha256_sign (const struct dsa_public_key *PUB,
2101           const struct dsa_private_key *KEY, void *RANDOM_CTX,
2102           nettle_random_func RANDOM, struct sha256_ctx *HASH, struct
2103           dsa_signature *SIGNATURE)
2104  - Function: int dsa_sha256_sign_digest (const struct dsa_public_key
2105           *PUB, const struct dsa_private_key *KEY, void *RANDOM_CTX,
2106           nettle_random_func RANDOM, const uint8_t *DIGEST, struct
2107           dsa_signature *SIGNATURE)
2108      Creates a signature from the given hash context or digest.
2109      RANDOM_CTX and RANDOM is a randomness generator.
2110      `random(random_ctx, length, dst)' should generate `length' random
2111      octets and store them at `dst'. For advice, see *Note
2112      Randomness::. Returns one on success, or zero on failure.  Signing
2113      fails if the key size and the hash size don't match.
2114
2115    Verifying signatures is a little easier, since no randomness
2116 generator is needed. The functions are
2117
2118  - Function: int dsa_sha1_verify (const struct dsa_public_key *KEY,
2119           struct sha1_ctx *HASH, const struct dsa_signature *SIGNATURE)
2120  - Function: int dsa_sha1_verify_digest (const struct dsa_public_key
2121           *KEY, const uint8_t *DIGEST, const struct dsa_signature
2122           *SIGNATURE)
2123  - Function: int dsa_sha256_verify (const struct dsa_public_key *KEY,
2124           struct sha256_ctx *HASH, const struct dsa_signature
2125           *SIGNATURE)
2126  - Function: int dsa_sha256_verify_digest (const struct dsa_public_key
2127           *KEY, const uint8_t *DIGEST, const struct dsa_signature
2128           *SIGNATURE)
2129      Verifies a signature. Returns 1 if the signature is valid,
2130      otherwise 0.
2131
2132    Key generation uses mostly the same parameters as the corresponding
2133 RSA function.
2134
2135  - Function: int dsa_generate_keypair (struct dsa_public_key *PUB,
2136           struct dsa_private_key *KEY, void *RANDOM_CTX,
2137           nettle_random_func RANDOM, void *PROGRESS_CTX,
2138           nettle_progress_func PROGRESS, unsigned P_BITS, unsigned
2139           Q_BITS)
2140      PUB and KEY is where the resulting key pair is stored. The structs
2141      should be initialized before you call this function.
2142
2143      RANDOM_CTX and RANDOM is a randomness generator.
2144      `random(random_ctx, length, dst)' should generate `length' random
2145      octets and store them at `dst'. For advice, see *Note Randomness::.
2146
2147      PROGRESS and PROGRESS_CTX can be used to get callbacks during the
2148      key generation process, in order to uphold an illusion of
2149      progress. PROGRESS can be NULL, in that case there are no
2150      callbacks.
2151
2152      P_BITS and Q_BITS are the desired sizes of `p' and `q'. To
2153      generate keys that conform to the original DSA standard, you must
2154      use `q_bits = 160' and select P_BITS of the form `p_bits = 512 +
2155      l*64', for `0 <= l <= 8', where the smaller sizes are no longer
2156      recommended, so you should most likely stick to `p_bits = 1024'.
2157      Non-standard sizes are possible, in particular `p_bits' larger
2158      than 1024, although DSA implementations can not in general be
2159      expected to support such keys. Also note that using very large
2160      P_BITS, with Q_BITS fixed at 160, doesn't make much sense, because
2161      the security is also limited by the size of the smaller prime.
2162      Using a larger `q_bits' requires switchign to a larger hash
2163      function. To generate DSA keys for use with SHA256, use `q_bits =
2164      256' and, e.g., `p_bits = 2048'.
2165
2166      Returns one on success, and zero on failure. The function will
2167      fail if Q_BITS is neither 160 nor 256, or if P_BITS is unreasonably
2168      small.
2169
2170 \1f
2171 File: nettle.info,  Node: Randomness,  Next: Miscellaneous functions,  Prev: Public-key algorithms,  Up: Reference
2172
2173 Randomness
2174 ==========
2175
2176 A crucial ingredient in many cryptographic contexts is randomness: Let
2177 `p' be a random prime, choose a random initialization vector `iv', a
2178 random key `k' and a random exponent `e', etc. In the theories, it is
2179 assumed that you have plenty of randomness around.  If this assumption
2180 is not true in practice, systems that are otherwise perfectly secure,
2181 can be broken. Randomness has often turned out to be the weakest link
2182 in the chain.
2183
2184    In non-cryptographic applications, such as games as well as
2185 scientific simulation, a good randomness generator usually means a
2186 generator that has good statistical properties, and is seeded by some
2187 simple function of things like the current time, process id, and host
2188 name.
2189
2190    However, such a generator is inadequate for cryptography, for at
2191 least two reasons:
2192
2193    * It's too easy for an attacker to guess the initial seed. Even if
2194      it will take some 2^32 tries before he guesses right, that's far
2195      too easy. For example, if the process id is 16 bits, the
2196      resolution of "current time" is one second, and the attacker knows
2197      what day the generator was seeded, there are only about 2^32
2198      possibilities to try if all possible values for the process id and
2199      time-of-day are tried.
2200
2201    * The generator output reveals too much. By observing only a small
2202      segment of the generator's output, its internal state can be
2203      recovered, and from there, all previous output and all future
2204      output can be computed by the attacker.
2205
2206    A randomness generator that is used for cryptographic purposes must
2207 have better properties. Let's first look at the seeding, as the issues
2208 here are mostly independent of the rest of the generator. The initial
2209 state of the generator (its seed) must be unguessable by the attacker.
2210 So what's unguessable? It depends on what the attacker already knows.
2211 The concept used in information theory to reason about such things is
2212 called "entropy", or "conditional entropy" (not to be confused with the
2213 thermodynamic concept with the same name). A reasonable requirement is
2214 that the seed contains a conditional entropy of at least some 80-100
2215 bits. This property can be explained as follows: Allow the attacker to
2216 ask `n' yes-no-questions, of his own choice, about the seed. If the
2217 attacker, using this question-and-answer session, as well as any other
2218 information he knows about the seeding process, still can't guess the
2219 seed correctly, then the conditional entropy is more than `n' bits.
2220
2221    Let's look at an example. Say information about timing of received
2222 network packets is used in the seeding process. If there is some random
2223 network traffic going on, this will contribute some bits of entropy or
2224 "unguessability" to the seed. However, if the attacker can listen in to
2225 the local network, or if all but a small number of the packets were
2226 transmitted by machines that the attacker can monitor, this additional
2227 information makes the seed easier for the attacker to figure out. Even
2228 if the information is exactly the same, the conditional entropy, or
2229 unguessability, is smaller for an attacker that knows some of it already
2230 before the hypothetical question-and-answer session.
2231
2232    Seeding of good generators is usually based on several sources. The
2233 key point here is that the amount of unguessability that each source
2234 contributes, depends on who the attacker is. Some sources that have been
2235 used are:
2236
2237 High resolution timing of i/o activities
2238      Such as completed blocks from spinning hard disks, network
2239      packets, etc.  Getting access to such information is quite system
2240      dependent, and not all systems include suitable hardware. If
2241      available, it's one of the better randomness source one can find
2242      in a digital, mostly predictable, computer.
2243
2244 User activity
2245      Timing and contents of user interaction events is another popular
2246      source that is available for interactive programs (even if I
2247      suspect that it is sometimes used in order to make the user feel
2248      good, not because the quality of the input is needed or used
2249      properly). Obviously, not available when a machine is unattended.
2250      Also beware of networks: User interaction that happens across a
2251      long serial cable, TELNET session, or even SSH session may be
2252      visible to an attacker, in full or partially.
2253
2254 Audio input
2255      Any room, or even a microphone input that's left unconnected, is a
2256      source of some random background noise, which can be fed into the
2257      seeding process.
2258
2259 Specialized hardware
2260      Hardware devices with the sole purpose of generating random data
2261      have been designed. They range from radioactive samples with an
2262      attached Geiger counter, to amplification of the inherent noise in
2263      electronic components such as diodes and resistors, to
2264      low-frequency sampling of chaotic systems. Hashing successive
2265      images of a Lava lamp is a spectacular example of the latter type.
2266
2267 Secret information
2268      Secret information, such as user passwords or keys, or private
2269      files stored on disk, can provide some unguessability. A problem
2270      is that if the information is revealed at a later time, the
2271      unguessability vanishes. Another problem is that this kind of
2272      information tends to be fairly constant, so if you rely on it and
2273      seed your generator regularly, you risk constructing almost
2274      similar seeds or even constructing the same seed more than once.
2275
2276    For all practical sources, it's difficult but important to provide a
2277 reliable lower bound on the amount of unguessability that it provides.
2278 Two important points are to make sure that the attacker can't observe
2279 your sources (so if you like the Lava lamp idea, remember that you have
2280 to get your own lamp, and not put it by a window or anywhere else where
2281 strangers can see it), and that hardware failures are detected. What if
2282 the bulb in the Lava lamp, which you keep locked into a cupboard
2283 following the above advice, breaks after a few months?
2284
2285    So let's assume that we have been able to find an unguessable seed,
2286 which contains at least 80 bits of conditional entropy, relative to all
2287 attackers that we care about (typically, we must at the very least
2288 assume that no attacker has root privileges on our machine).
2289
2290    How do we generate output from this seed, and how much can we get?
2291 Some generators (notably the Linux `/dev/random' generator) tries to
2292 estimate available entropy and restrict the amount of output. The goal
2293 is that if you read 128 bits from `/dev/random', you should get 128
2294 "truly random" bits. This is a property that is useful in some
2295 specialized circumstances, for instance when generating key material for
2296 a one time pad, or when working with unconditional blinding, but in most
2297 cases, it doesn't matter much. For most application, there's no limit on
2298 the amount of useful "random" data that we can generate from a small
2299 seed; what matters is that the seed is unguessable and that the
2300 generator has good cryptographic properties.
2301
2302    At the heart of all generators lies its internal state. Future output
2303 is determined by the internal state alone. Let's call it the generator's
2304 key. The key is initialized from the unguessable seed. Important
2305 properties of a generator are:
2306
2307 "Key-hiding"
2308      An attacker observing the output should not be able to recover the
2309      generator's key.
2310
2311 "Independence of outputs"
2312      Observing some of the output should not help the attacker to guess
2313      previous or future output.
2314
2315 "Forward secrecy"
2316      Even if an attacker compromises the generator's key, he should not
2317      be able to guess the generator output _before_ the key compromise.
2318
2319 "Recovery from key compromise"
2320      If an attacker compromises the generator's key, he can compute
2321      _all_ future output. This is inevitable if the generator is seeded
2322      only once, at startup. However, the generator can provide a
2323      reseeding mechanism, to achieve recovery from key compromise. More
2324      precisely: If the attacker compromises the key at a particular
2325      time `t_1', there is another later time `t_2', such that if the
2326      attacker observes all output generated between `t_1' and `t_2', he
2327      still can't guess what output is generated after `t_2'.
2328
2329
2330    Nettle includes one randomness generator that is believed to have all
2331 the above properties, and two simpler ones.
2332
2333    ARCFOUR, like any stream cipher, can be used as a randomness
2334 generator. Its output should be of reasonable quality, if the seed is
2335 hashed properly before it is used with `arcfour_set_key'. There's no
2336 single natural way to reseed it, but if you need reseeding, you should
2337 be using Yarrow instead.
2338
2339    The "lagged Fibonacci" generator in `<nettle/knuth-lfib.h>' is a
2340 fast generator with good statistical properties, but is *not* for
2341 cryptographic use, and therefore not documented here. It is included
2342 mostly because the Nettle test suite needs to generate some test data
2343 from a small seed.
2344
2345    The recommended generator to use is Yarrow, described below.
2346
2347 Yarrow
2348 ------
2349
2350 Yarrow is a family of pseudo-randomness generators, designed for
2351 cryptographic use, by John Kelsey, Bruce Schneier and Niels Ferguson.
2352 Yarrow-160 is described in a paper at
2353 <http://www.counterpane.com/yarrow.html>, and it uses SHA1 and
2354 triple-DES, and has a 160-bit internal state. Nettle implements
2355 Yarrow-256, which is similar, but uses SHA256 and AES to get an
2356 internal state of 256 bits.
2357
2358    Yarrow was an almost finished project, the paper mentioned above is
2359 the closest thing to a specification for it, but some smaller details
2360 are left out. There is no official reference implementation or test
2361 cases.  This section includes an overview of Yarrow, but for the
2362 details of Yarrow-256, as implemented by Nettle, you have to consult
2363 the source code. Maybe a complete specification can be written later.
2364
2365    Yarrow can use many sources (at least two are needed for proper
2366 reseeding), and two randomness "pools", referred to as the "slow pool"
2367 and the "fast pool". Input from the sources is fed alternatingly into
2368 the two pools. When one of the sources has contributed 100 bits of
2369 entropy to the fast pool, a "fast reseed" happens and the fast pool is
2370 mixed into the internal state. When at least two of the sources have
2371 contributed at least 160 bits each to the slow pool, a "slow reseed"
2372 takes place. The contents of both pools are mixed into the internal
2373 state. These procedures should ensure that the generator will eventually
2374 recover after a key compromise.
2375
2376    The output is generated by using AES to encrypt a counter, using the
2377 generator's current key. After each request for output, another 256
2378 bits are generated which replace the key. This ensures forward secrecy.
2379
2380    Yarrow can also use a "seed file" to save state across restarts.
2381 Yarrow is seeded by either feeding it the contents of the previous seed
2382 file, or feeding it input from its sources until a slow reseed happens.
2383
2384    Nettle defines Yarrow-256 in `<nettle/yarrow.h>'.
2385
2386  - Context struct: struct yarrow256_ctx
2387
2388  - Context struct: struct yarrow_source
2389      Information about a single source.
2390
2391  - Constant: YARROW256_SEED_FILE_SIZE
2392      Recommanded size of the Yarrow-256 seed file.
2393
2394  - Function: void yarrow256_init (struct yarrow256_ctx *CTX, unsigned
2395           NSOURCES, struct yarrow_source *SOURCES)
2396      Initializes the yarrow context, and its NSOURCES sources. It's
2397      possible to call it with NSOURCES=0 and SOURCES=NULL, if you don't
2398      need the update features.
2399
2400  - Function: void yarrow256_seed (struct yarrow256_ctx *CTX, unsigned
2401           LENGTH, uint8_t *SEED_FILE)
2402      Seeds Yarrow-256 from a previous seed file. LENGTH should be at
2403      least `YARROW256_SEED_FILE_SIZE', but it can be larger.
2404
2405      The generator will trust you that the SEED_FILE data really is
2406      unguessable. After calling this function, you _must_ overwrite the
2407      old seed file with newly generated data from `yarrow256_random'.
2408      If it's possible for several processes to read the seed file at
2409      about the same time, access must be coordinated using some locking
2410      mechanism.
2411
2412  - Function: int yarrow256_update (struct yarrow256_ctx *CTX, unsigned
2413           SOURCE, unsigned ENTROPY, unsigned LENGTH, const uint8_t
2414           *DATA)
2415      Updates the generator with data from source SOURCE (an index that
2416      must be smaller than the number of sources). ENTROPY is your
2417      estimated lower bound for the entropy in the data, measured in
2418      bits.  Calling update with zero ENTROPY is always safe, no matter
2419      if the data is random or not.
2420
2421      Returns 1 if a reseed happened, in which case an application using
2422      a seed file may want to generate new seed data with
2423      `yarrow256_random' and overwrite the seed file. Otherwise, the
2424      function returns 0.
2425
2426  - Function: void yarrow256_random (struct yarrow256_ctx *CTX, unsigned
2427           LENGTH, uint8_t *DST)
2428      Generates LENGTH octets of output. The generator must be seeded
2429      before you call this function.
2430
2431      If you don't need forward secrecy, e.g. if you need non-secret
2432      randomness for initialization vectors or padding, you can gain some
2433      efficiency by buffering, calling this function for reasonably large
2434      blocks of data, say 100-1000 octets at a time.
2435
2436  - Function: int yarrow256_is_seeded (struct yarrow256_ctx *CTX)
2437      Returns 1 if the generator is seeded and ready to generate output,
2438      otherwise 0.
2439
2440  - Function: unsigned yarrow256_needed_sources (struct yarrow256_ctx
2441           *CTX)
2442      Returns the number of sources that must reach the threshold before
2443      a slow reseed will happen. Useful primarily when the generator is
2444      unseeded.
2445
2446  - Function: void yarrow256_fast_reseed (struct yarrow256_ctx *CTX)
2447  - Function: void yarrow256_slow_reseed (struct yarrow256_ctx *CTX)
2448      Causes a fast or slow reseed to take place immediately, regardless
2449      of the current entropy estimates of the two pools. Use with care.
2450
2451    Nettle includes an entropy estimator for one kind of input source:
2452 User keyboard input.
2453
2454  - Context struct: struct yarrow_key_event_ctx
2455      Information about recent key events.
2456
2457  - Function: void yarrow_key_event_init (struct yarrow_key_event_ctx
2458           *CTX)
2459      Initializes the context.
2460
2461  - Function: unsigned yarrow_key_event_estimate (struct
2462           yarrow_key_event_ctx *CTX, unsigned KEY, unsigned TIME)
2463      KEY is the id of the key (ASCII value, hardware key code, X
2464      keysym, ..., it doesn't matter), and TIME is the timestamp of the
2465      event. The time must be given in units matching the resolution by
2466      which you read the clock. If you read the clock with microsecond
2467      precision, TIME should be provided in units of microseconds. But
2468      if you use `gettimeofday' on a typical Unix system where the clock
2469      ticks 10 or so microseconds at a time, TIME should be given in
2470      units of 10 microseconds.
2471
2472      Returns an entropy estimate, in bits, suitable for calling
2473      `yarrow256_update'. Usually, 0, 1 or 2 bits.
2474
2475 \1f
2476 File: nettle.info,  Node: Miscellaneous functions,  Next: Compatibility functions,  Prev: Randomness,  Up: Reference
2477
2478 Miscellaneous functions
2479 =======================
2480
2481  - Function: uint8_t * memxor (uint8_t *DST, const uint8_t *SRC, size_t
2482           N)
2483      XORs the source area on top of the destination area. The interface
2484      doesn't follow the Nettle conventions, because it is intended to be
2485      similar to the ANSI-C `memcpy' function.
2486
2487    `memxor' is declared in `<nettle/memxor.h>'.
2488
2489 \1f
2490 File: nettle.info,  Node: Compatibility functions,  Prev: Miscellaneous functions,  Up: Reference
2491
2492 Compatibility functions
2493 =======================
2494
2495 For convenience, Nettle includes alternative interfaces to some
2496 algorithms, for compatibility with some other popular crypto toolkits.
2497 These are not fully documented here; refer to the source or to the
2498 documentation for the original implementation.
2499
2500    MD5 is defined in [RFC 1321], which includes a reference
2501 implementation.  Nettle defines a compatible interface to MD5 in
2502 `<nettle/md5-compat.h>'. This file defines the typedef `MD5_CTX', and
2503 declares the functions `MD5Init', `MD5Update' and `MD5Final'.
2504
2505    Eric Young's "libdes" (also part of OpenSSL) is a quite popular DES
2506 implementation. Nettle includes a subset if its interface in
2507 `<nettle/des-compat.h>'. This file defines the typedefs
2508 `des_key_schedule' and `des_cblock', two constants `DES_ENCRYPT' and
2509 `DES_DECRYPT', and declares one global variable `des_check_key', and
2510 the functions `des_cbc_cksum' `des_cbc_encrypt', `des_ecb2_encrypt',
2511 `des_ecb3_encrypt', `des_ecb_encrypt', `des_ede2_cbc_encrypt',
2512 `des_ede3_cbc_encrypt', `des_is_weak_key', `des_key_sched',
2513 `des_ncbc_encrypt' `des_set_key', and `des_set_odd_parity'.
2514
2515 \1f
2516 File: nettle.info,  Node: Nettle soup,  Next: Installation,  Prev: Reference,  Up: Top
2517
2518 Traditional Nettle Soup
2519 ***********************
2520
2521 For the serious nettle hacker, here is a recipe for nettle soup. 4
2522 servings.
2523
2524      1 liter fresh nettles (urtica dioica)
2525
2526      2 tablespoons butter
2527
2528      3 tablespoons flour
2529
2530      1 liter stock (meat or vegetable)
2531
2532      1/2 teaspoon salt
2533
2534      a tad white pepper
2535
2536      some cream or milk
2537
2538    Gather 1 liter fresh nettles. Use gloves! Small, tender shoots are
2539 preferable but the tops of larger nettles can also be used.
2540
2541    Rinse the nettles very well. Boil them for 10 minutes in lightly
2542 salted water. Strain the nettles and save the water. Hack the nettles.
2543 Melt the butter and mix in the flour. Dilute with stock and the
2544 nettle-water you saved earlier. Add the hacked nettles. If you wish you
2545 can add some milk or cream at this stage. Bring to a boil and let boil
2546 for a few minutes.  Season with salt and pepper.
2547
2548    Serve with boiled egg-halves.
2549
2550 \1f
2551 File: nettle.info,  Node: Installation,  Next: Index,  Prev: Nettle soup,  Up: Top
2552
2553 Installation
2554 ************
2555
2556 Nettle uses `autoconf'. To build it, unpack the source and run
2557
2558      ./configure
2559      make
2560      make check
2561      make install
2562
2563 to install in the default location, `/usr/local'. The library files are
2564 installed in `/use/local/lib/libnettle.a' `/use/local/lib/libhogweed.a'
2565 and the include files are installed in `/use/local/include/nettle/'.
2566
2567    To get a list of configure options, use `./configure --help'.
2568
2569    By default, only static libraries are built and installed. To also
2570 build and install shared libraries, use the ` --enable-shared' option
2571 to `./configure'.
2572
2573    Using GNU make is recommended. For other make programs, in particular
2574 BSD make, you may have to use the `--disable-dependency-tracking'
2575 option to `./configure'.
2576
2577 \1f
2578 File: nettle.info,  Node: Index,  Prev: Installation,  Up: Top
2579
2580 Function and Concept Index
2581 **************************
2582
2583 * Menu:
2584
2585 * aes_decrypt:                           Cipher functions.
2586 * aes_encrypt:                           Cipher functions.
2587 * aes_invert_key:                        Cipher functions.
2588 * aes_set_decrypt_key:                   Cipher functions.
2589 * aes_set_encrypt_key:                   Cipher functions.
2590 * arcfour_crypt:                         Cipher functions.
2591 * arcfour_set_key:                       Cipher functions.
2592 * arctwo_decrypt:                        Cipher functions.
2593 * arctwo_encrypt:                        Cipher functions.
2594 * arctwo_set_key:                        Cipher functions.
2595 * arctwo_set_key_ekb:                    Cipher functions.
2596 * arctwo_set_key_gutmann:                Cipher functions.
2597 * Block Cipher:                          Cipher functions.
2598 * blowfish_decrypt:                      Cipher functions.
2599 * blowfish_encrypt:                      Cipher functions.
2600 * blowfish_set_key:                      Cipher functions.
2601 * camellia_crypt:                        Cipher functions.
2602 * camellia_invert_key:                   Cipher functions.
2603 * camellia_set_decrypt_key:              Cipher functions.
2604 * camellia_set_encrypt_key:              Cipher functions.
2605 * cast128_decrypt:                       Cipher functions.
2606 * cast128_encrypt:                       Cipher functions.
2607 * cast128_set_key:                       Cipher functions.
2608 * CBC Mode:                              Cipher modes.
2609 * CBC_CTX:                               Cipher modes.
2610 * CBC_DECRYPT:                           Cipher modes.
2611 * cbc_decrypt:                           Cipher modes.
2612 * CBC_ENCRYPT:                           Cipher modes.
2613 * cbc_encrypt:                           Cipher modes.
2614 * CBC_SET_IV:                            Cipher modes.
2615 * Cipher:                                Cipher functions.
2616 * Cipher Block Chaining:                 Cipher modes.
2617 * Collision-resistant:                   Hash functions.
2618 * Conditional entropy:                   Randomness.
2619 * Counter Mode:                          Cipher modes.
2620 * CTR Mode:                              Cipher modes.
2621 * CTR_CRYPT:                             Cipher modes.
2622 * ctr_crypt:                             Cipher modes.
2623 * CTR_CTX:                               Cipher modes.
2624 * CTR_SET_COUNTER:                       Cipher modes.
2625 * des3_decrypt:                          Cipher functions.
2626 * des3_encrypt:                          Cipher functions.
2627 * des3_set_key:                          Cipher functions.
2628 * des_check_parity:                      Cipher functions.
2629 * des_decrypt:                           Cipher functions.
2630 * des_encrypt:                           Cipher functions.
2631 * des_fix_parity:                        Cipher functions.
2632 * des_set_key:                           Cipher functions.
2633 * dsa_generate_keypair:                  DSA.
2634 * dsa_private_key_clear:                 DSA.
2635 * dsa_private_key_init:                  DSA.
2636 * dsa_public_key_clear:                  DSA.
2637 * dsa_public_key_init:                   DSA.
2638 * dsa_sha1_sign:                         DSA.
2639 * dsa_sha1_sign_digest:                  DSA.
2640 * dsa_sha1_verify:                       DSA.
2641 * dsa_sha1_verify_digest:                DSA.
2642 * dsa_sha256_sign:                       DSA.
2643 * dsa_sha256_sign_digest:                DSA.
2644 * dsa_sha256_verify:                     DSA.
2645 * dsa_sha256_verify_digest:              DSA.
2646 * dsa_signature_clear:                   DSA.
2647 * dsa_signature_init:                    DSA.
2648 * Entropy:                               Randomness.
2649 * Hash function:                         Hash functions.
2650 * HMAC_CTX:                              Keyed hash functions.
2651 * HMAC_DIGEST:                           Keyed hash functions.
2652 * hmac_digest:                           Keyed hash functions.
2653 * hmac_md5_digest:                       Keyed hash functions.
2654 * hmac_md5_set_key:                      Keyed hash functions.
2655 * hmac_md5_update:                       Keyed hash functions.
2656 * HMAC_SET_KEY:                          Keyed hash functions.
2657 * hmac_set_key:                          Keyed hash functions.
2658 * hmac_sha1_digest:                      Keyed hash functions.
2659 * hmac_sha1_set_key:                     Keyed hash functions.
2660 * hmac_sha1_update:                      Keyed hash functions.
2661 * hmac_sha256_digest:                    Keyed hash functions.
2662 * hmac_sha256_set_key:                   Keyed hash functions.
2663 * hmac_sha256_update:                    Keyed hash functions.
2664 * hmac_sha512_digest:                    Keyed hash functions.
2665 * hmac_sha512_set_key:                   Keyed hash functions.
2666 * hmac_sha512_update:                    Keyed hash functions.
2667 * hmac_update:                           Keyed hash functions.
2668 * Keyed Hash Function:                   Keyed hash functions.
2669 * MAC:                                   Keyed hash functions.
2670 * md2_digest:                            Hash functions.
2671 * md2_init:                              Hash functions.
2672 * md2_update:                            Hash functions.
2673 * md4_digest:                            Hash functions.
2674 * md4_init:                              Hash functions.
2675 * md4_update:                            Hash functions.
2676 * md5_digest:                            Hash functions.
2677 * md5_init:                              Hash functions.
2678 * md5_update:                            Hash functions.
2679 * memxor:                                Miscellaneous functions.
2680 * Message Authentication Code:           Keyed hash functions.
2681 * One-way:                               Hash functions.
2682 * One-way function:                      Public-key algorithms.
2683 * Public Key Cryptography:               Public-key algorithms.
2684 * Randomness:                            Randomness.
2685 * rsa_compute_root:                      RSA.
2686 * rsa_generate_keypair:                  RSA.
2687 * rsa_md5_sign:                          RSA.
2688 * rsa_md5_sign_digest:                   RSA.
2689 * rsa_md5_verify:                        RSA.
2690 * rsa_md5_verify_digest:                 RSA.
2691 * rsa_private_key_clear:                 RSA.
2692 * rsa_private_key_init:                  RSA.
2693 * rsa_private_key_prepare:               RSA.
2694 * rsa_public_key_clear:                  RSA.
2695 * rsa_public_key_init:                   RSA.
2696 * rsa_public_key_prepare:                RSA.
2697 * rsa_sha1_sign:                         RSA.
2698 * rsa_sha1_sign_digest:                  RSA.
2699 * rsa_sha1_verify:                       RSA.
2700 * rsa_sha1_verify_digest:                RSA.
2701 * rsa_sha256_sign:                       RSA.
2702 * rsa_sha256_sign_digest:                RSA.
2703 * rsa_sha256_verify:                     RSA.
2704 * rsa_sha256_verify_digest:              RSA.
2705 * rsa_sha512_sign:                       RSA.
2706 * rsa_sha512_sign_digest:                RSA.
2707 * rsa_sha512_verify:                     RSA.
2708 * rsa_sha512_verify_digest:              RSA.
2709 * serpent_decrypt:                       Cipher functions.
2710 * serpent_encrypt:                       Cipher functions.
2711 * serpent_set_key:                       Cipher functions.
2712 * sha1_digest:                           Hash functions.
2713 * sha1_init:                             Hash functions.
2714 * sha1_update:                           Hash functions.
2715 * sha224_digest:                         Hash functions.
2716 * sha224_init:                           Hash functions.
2717 * sha224_update:                         Hash functions.
2718 * sha256_digest:                         Hash functions.
2719 * sha256_init:                           Hash functions.
2720 * sha256_update:                         Hash functions.
2721 * sha384_digest:                         Hash functions.
2722 * sha384_init:                           Hash functions.
2723 * sha384_update:                         Hash functions.
2724 * sha512_digest:                         Hash functions.
2725 * sha512_init:                           Hash functions.
2726 * sha512_update:                         Hash functions.
2727 * Stream Cipher:                         Cipher functions.
2728 * twofish_decrypt:                       Cipher functions.
2729 * twofish_encrypt:                       Cipher functions.
2730 * twofish_set_key:                       Cipher functions.
2731 * yarrow256_fast_reseed:                 Randomness.
2732 * yarrow256_init:                        Randomness.
2733 * yarrow256_is_seeded:                   Randomness.
2734 * yarrow256_needed_sources:              Randomness.
2735 * yarrow256_random:                      Randomness.
2736 * yarrow256_seed:                        Randomness.
2737 * yarrow256_slow_reseed:                 Randomness.
2738 * yarrow256_update:                      Randomness.
2739 * yarrow_key_event_estimate:             Randomness.
2740 * yarrow_key_event_init:                 Randomness.
2741
2742
2743 \1f
2744 Tag Table:
2745 Node: Top\7f544
2746 Node: Introduction\7f1719
2747 Node: Copyright\7f3281
2748 Node: Conventions\7f6951
2749 Node: Example\7f8909
2750 Node: Linking\7f10201
2751 Node: Reference\7f11030
2752 Node: Hash functions\7f11394
2753 Node: Cipher functions\7f22959
2754 Node: Cipher modes\7f48587
2755 Node: Keyed hash functions\7f54929
2756 Node: Public-key algorithms\7f63350
2757 Node: RSA\7f67262
2758 Node: RSA-Footnotes\7f77826
2759 Ref: RSA-Footnote-1\7f77879
2760 Node: DSA\7f78048
2761 Node: Randomness\7f89349
2762 Node: Miscellaneous functions\7f104428
2763 Node: Compatibility functions\7f104923
2764 Node: Nettle soup\7f106160
2765 Node: Installation\7f107149
2766 Node: Index\7f107992
2767 \1f
2768 End Tag Table