Fix build error and set version 2.7.1
[platform/upstream/nettle.git] / nettle.texinfo
1 \input texinfo          @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename nettle.info
4 @settitle Nettle: a low-level cryptographic library
5 @documentencoding UTF-8
6 @footnotestyle separate
7 @syncodeindex fn cp
8 @c %**end of header
9
10 @set UPDATED-FOR 2.7
11 @set AUTHOR Niels Möller
12
13 @copying
14 This manual is for the Nettle library (version @value{UPDATED-FOR}), a
15 low-level cryptographic library.
16
17 Originally written 2001 by @value{AUTHOR}, updated 2013.
18
19 @quotation
20 This manual is placed in the public domain. You may freely copy it, in
21 whole or in part, with or without modification. Attribution is
22 appreciated, but not required.
23 @end quotation
24 @end copying
25
26 @ifnottex
27 @macro pmod {m} 
28 (mod \m\)
29 @end macro
30 @end ifnottex
31
32 @titlepage
33 @title Nettle Manual
34 @subtitle For the Nettle Library version @value{UPDATED-FOR}
35 @author @value{AUTHOR}
36 @page
37 @vskip 0pt plus 1filll
38 @insertcopying
39 @end titlepage
40
41 @dircategory Encryption
42 @direntry
43 * Nettle: (nettle).             A low-level cryptographic library.
44 @end direntry
45
46 @contents
47
48 @ifnottex
49 @node     Top, Introduction, (dir), (dir)
50 @comment  node-name,  next,  previous,  up
51 @top Nettle
52
53 This document describes the Nettle low-level cryptographic library. You
54 can use the library directly from your C programs, or write or use an
55 object-oriented wrapper for your favorite language or application.
56
57 @insertcopying
58
59 @menu
60 * Introduction::                What is Nettle?
61 * Copyright::                   Your rights.
62 * Conventions::                 General interface conventions.
63 * Example::                     An example program.
64 * Linking::                     Linking with libnettle and libhogweed.
65 * Reference::                   All Nettle functions and features.
66 * Nettle soup::                 For the serious nettle hacker.
67 * Installation::                How to install Nettle.
68 * Index::                       Function and concept index.
69
70 @detailmenu
71  --- The Detailed Node Listing ---
72
73 Reference
74
75 * Hash functions::              
76 * Cipher functions::            
77 * Cipher modes::                
78 * Keyed hash functions::        
79 * Key derivation functions::    
80 * Public-key algorithms::       
81 * Randomness::                  
82 * ASCII encoding::              
83 * Miscellaneous functions::     
84 * Compatibility functions::     
85
86 Cipher modes
87
88 * CBC::                         
89 * CTR::                         
90 * GCM::                         
91
92 Public-key algorithms
93
94 * RSA::                         The RSA public key algorithm.
95 * DSA::                         The DSA digital signature algorithm.
96 * Elliptic curves::             Elliptic curves and ECDSA
97
98 @end detailmenu
99 @end menu
100
101 @end ifnottex
102
103 @node Introduction, Copyright, Top, Top
104 @comment  node-name,  next,  previous,  up
105 @chapter Introduction
106
107 Nettle is a cryptographic library that is designed to fit easily in more
108 or less any context: In crypto toolkits for object-oriented languages
109 (C++, Python, Pike, ...), in applications like LSH or GNUPG, or even in
110 kernel space. In most contexts, you need more than the basic
111 cryptographic algorithms, you also need some way to keep track of available
112 algorithms, their properties and variants. You often have some algorithm
113 selection process, often dictated by a protocol you want to implement.
114
115 And as the requirements of applications differ in subtle and not so
116 subtle ways, an API that fits one application well can be a pain to use
117 in a different context. And that is why there are so many different
118 cryptographic libraries around.
119
120 Nettle tries to avoid this problem by doing one thing, the low-level
121 crypto stuff, and providing a @emph{simple} but general interface to it.
122 In particular, Nettle doesn't do algorithm selection. It doesn't do
123 memory allocation. It doesn't do any I/O.
124
125 The idea is that one can build several application and context specific
126 interfaces on top of Nettle, and share the code, test cases, benchmarks,
127 documentation, etc. Examples are the Nettle module for the Pike
128 language, and LSH, which both use an object-oriented abstraction on top
129 of the library.
130
131 This manual explains how to use the Nettle library. It also tries to
132 provide some background on the cryptography, and advice on how to best
133 put it to use.
134
135 @node Copyright, Conventions, Introduction, Top
136 @comment  node-name,  next,  previous,  up
137 @chapter Copyright
138
139 Nettle is distributed under the GNU Lesser General Public License
140 (LGPL), see the file COPYING.LIB for details. A few of the individual
141 files are in the public domain. To find the current status of particular
142 files, you have to read the copyright notices at the top of the files.
143
144 This manual is in the public domain. You may freely copy it in whole or
145 in part, e.g., into documentation of programs that build on Nettle.
146 Attribution, as well as contribution of improvements to the text, is of
147 course appreciated, but it is not required.
148
149 A list of the supported algorithms, their origins and licenses:
150
151 @table @emph
152 @item AES
153 The implementation of the AES cipher (also known as rijndael) is written
154 by Rafael Sevilla. Assembler for x86 by Rafael Sevilla and
155 @value{AUTHOR}, Sparc assembler by @value{AUTHOR}. Released under the
156 LGPL.
157
158 @item ARCFOUR
159 The implementation of the ARCFOUR (also known as RC4) cipher is written
160 by @value{AUTHOR}. Released under the LGPL.
161
162 @item ARCTWO
163 The implementation of the ARCTWO (also known as RC2) cipher is written
164 by Nikos Mavroyanopoulos and modified by Werner Koch and Simon
165 Josefsson. Released under the LGPL.
166
167 @item BLOWFISH
168 The implementation of the BLOWFISH cipher is written by Werner Koch,
169 copyright owned by the Free Software Foundation. Also hacked by Simon
170 Josefsson and Niels Möller. Released under the LGPL.
171
172 @item CAMELLIA
173 The C implementation is by Nippon Telegraph and Telephone Corporation
174 (NTT), heavily modified by @value{AUTHOR}. Assembler for x86 and x86_64
175 by @value{AUTHOR}. Released under the LGPL.
176
177 @item CAST128
178 The implementation of the CAST128 cipher is written by Steve Reid.
179 Released into the public domain.
180
181 @item DES
182 The implementation of the DES cipher is written by Dana L. How, and
183 released under the LGPL.
184
185 @item GOSTHASH94
186 The C implementation of the GOST94 message digest is written by 
187 Aleksey Kravchenko and was ported from the rhash library by Nikos
188 Mavrogiannopoulos. It is released under the MIT license.
189
190 @item MD2
191 The implementation of MD2 is written by Andrew Kuchling, and hacked
192 some by Andreas Sigfridsson and @value{AUTHOR}. Python Cryptography
193 Toolkit license (essentially public domain).
194
195 @item MD4
196 This is almost the same code as for MD5 below, with modifications by
197 Marcus Comstedt. Released into the public domain.
198
199 @item MD5
200 The implementation of the MD5 message digest is written by Colin Plumb.
201 It has been hacked some more by Andrew Kuchling and @value{AUTHOR}.
202 Released into the public domain.
203
204 @item PBKDF2
205 The C implementation of PBKDF2 is based on earlier work for Shishi and
206 GnuTLS by Simon Josefsson.  Released under the LGPL.
207
208 @item RIPEMD160
209 The implementation of RIPEMD160 message digest is based on the code in
210 libgcrypt, copyright owned by the Free Software Foundation. Ported to
211 Nettle by Andres Mejia. Released under the LGPL.
212
213 @item SALSA20
214 The C implementation of SALSA20 is based on D. J. Bernstein's reference
215 implementation (in the public domain), adapted to Nettle by Simon
216 Josefsson, and heavily modified by Niels Möller. Assembly for x86_64 and
217 ARM by Niels Möller. Released under the LGPL.
218
219 @item SERPENT
220 The implementation of the SERPENT cipher is based on the code in libgcrypt,
221 copyright owned by the Free Software Foundation. Adapted to Nettle by
222 Simon Josefsson and heavily modified by Niels Möller. Assembly for
223 x86_64 by Niels Möller. Released under the LGPL.
224
225 @item SHA1
226 The C implementation of the SHA1 message digest is written by Peter
227 Gutmann, and hacked some more by Andrew Kuchling and @value{AUTHOR}.
228 Released into the public domain. Assembler for x86, x86_64 and ARM by
229 @value{AUTHOR}, released under the LGPL.
230
231 @item SHA2
232 Written by @value{AUTHOR}, using Peter Gutmann's SHA1 code as a model. 
233 Released under the LGPL.
234
235 @item SHA3
236 Written by @value{AUTHOR}. Released under the LGPL.
237
238 @item TWOFISH
239 The implementation of the TWOFISH cipher is written by Ruud de Rooij.
240 Released under the LGPL.
241
242 @item UMAC
243 Written by @value{AUTHOR}. Released under the LGPL.
244
245 @item RSA
246 Written by @value{AUTHOR}, released under the LGPL. Uses the GMP library
247 for bignum operations.
248
249 @item DSA
250 Written by @value{AUTHOR}, released under the LGPL. Uses the GMP library
251 for bignum operations.
252
253 @item ECDSA
254 Written by @value{AUTHOR}, released under the LGPL. Uses the GMP library
255 for bignum operations. Development of Nettle's ECC support was funded by
256 the .SE Internet Fund.
257 @end table
258
259 @node Conventions, Example, Copyright, Top
260 @comment  node-name,  next,  previous,  up
261 @chapter Conventions
262
263 For each supported algorithm, there is an include file that defines a
264 @emph{context struct}, a few constants, and declares functions for
265 operating on the context. The context struct encapsulates all information
266 needed by the algorithm, and it can be copied or moved in memory with no
267 unexpected effects.
268
269 For consistency, functions for different algorithms are very similar,
270 but there are some differences, for instance reflecting if the key setup
271 or encryption function differ for encryption and decryption, and whether
272 or not key setup can fail. There are also differences between algorithms
273 that don't show in function prototypes, but which the application must
274 nevertheless be aware of. There is no big difference between the
275 functions for stream ciphers and for block ciphers, although they should
276 be used quite differently by the application.
277
278 If your application uses more than one algorithm of the same type, you
279 should probably create an interface that is tailor-made for your needs,
280 and then write a few lines of glue code on top of Nettle.
281
282 By convention, for an algorithm named @code{foo}, the struct tag for the
283 context struct is @code{foo_ctx}, constants and functions uses prefixes
284 like @code{FOO_BLOCK_SIZE} (a constant) and @code{foo_set_key} (a
285 function).
286
287 In all functions, strings are represented with an explicit length, of
288 type @code{unsigned}, and a pointer of type @code{uint8_t *} or
289 @code{const uint8_t *}. For functions that transform one string to
290 another, the argument order is length, destination pointer and source
291 pointer. Source and destination areas are of the same length. Source and
292 destination may be the same, so that you can process strings in place,
293 but they @emph{must not} overlap in any other way.
294
295 Many of the functions lack return value and can never fail. Those
296 functions which can fail, return one on success and zero on failure.
297
298 @c FIXME: Say something about the name mangling.
299
300 @node Example, Linking, Conventions, Top
301 @comment  node-name,  next,  previous,  up
302 @chapter Example
303
304 A simple example program that reads a file from standard input and
305 writes its SHA1 check-sum on standard output should give the flavor of
306 Nettle.
307
308 @example
309 @verbatiminclude sha-example.c
310 @end example
311
312 On a typical Unix system, this program can be compiled and linked with
313 the command line 
314 @example
315 gcc sha-example.c -o sha-example -lnettle
316 @end example
317
318 @node Linking, Reference, Example, Top
319 @comment  node-name,  next,  previous,  up
320 @chapter Linking
321
322 Nettle actually consists of two libraries, @file{libnettle} and
323 @file{libhogweed}. The @file{libhogweed} library contains those
324 functions of Nettle that uses bignum operations, and depends on the GMP
325 library. With this division, linking works the same for both static and
326 dynamic libraries.
327
328 If an application uses only the symmetric crypto algorithms of Nettle
329 (i.e., block ciphers, hash functions, and the like), it's sufficient to
330 link with @code{-lnettle}. If an application also uses public-key
331 algorithms, the recommended linker flags are @code{-lhogweed -lnettle
332 -lgmp}. If the involved libraries are installed as dynamic libraries, it
333 may be sufficient to link with just @code{-lhogweed}, and the loader
334 will resolve the dependencies automatically.
335
336 @node Reference, Nettle soup, Linking, Top
337 @comment  node-name,  next,  previous,  up
338 @chapter Reference
339
340 This chapter describes all the Nettle functions, grouped by family.
341
342 @menu
343 * Hash functions::              
344 * Cipher functions::            
345 * Cipher modes::                
346 * Keyed hash functions::        
347 * Key derivation functions::    
348 * Public-key algorithms::       
349 * Randomness::                  
350 * ASCII encoding::              
351 * Miscellaneous functions::     
352 * Compatibility functions::     
353 @end menu
354
355 @node Hash functions, Cipher functions, Reference, Reference
356 @comment  node-name,  next,  previous,  up
357
358 @section Hash functions
359 @cindex Hash function
360 A cryptographic @dfn{hash function} is a function that takes variable
361 size strings, and maps them to strings of fixed, short, length. There
362 are naturally lots of collisions, as there are more possible 1MB files
363 than 20 byte strings. But the function is constructed such that is hard
364 to find the collisions. More precisely, a cryptographic hash function
365 @code{H} should have the following properties:
366
367 @table @emph
368
369 @item One-way
370 @cindex One-way
371 Given a hash value @code{H(x)} it is hard to find a string @code{x}
372 that hashes to that value.
373
374 @item Collision-resistant
375 @cindex Collision-resistant
376 It is hard to find two different strings, @code{x} and @code{y}, such
377 that @code{H(x)} = @code{H(y)}.
378
379 @end table
380
381 Hash functions are useful as building blocks for digital signatures,
382 message authentication codes, pseudo random generators, association of
383 unique ids to documents, and many other things.
384
385 The most commonly used hash functions are MD5 and SHA1. Unfortunately,
386 both these fail the collision-resistance requirement; cryptologists have
387 found ways to construct colliding inputs. The recommended hash functions
388 for new applications are SHA2 (with main variants SHA256 and SHA512). At
389 the time of this writing (December 2012), the winner of the NIST SHA3
390 competition has recently been announced, and the new SHA3 (earlier known
391 as Keccak) and other top SHA3 candidates may also be reasonable
392 alternatives.
393
394 @menu
395 * Recommended hash functions::
396 * Legacy hash functions::
397 * nettle_hash abstraction::
398 @end menu
399
400 @node Recommended hash functions, Legacy hash functions,, Hash functions
401 @comment  node-name,  next,  previous,  up
402 @subsection Recommended hash functions
403
404 The following hash functions have no known weaknesses, and are suitable
405 for new applications. The SHA2 family of hash functions were specified
406 by @dfn{NIST}, intended as a replacement for @acronym{SHA1}.
407
408 @subsubsection @acronym{SHA256}
409
410 SHA256 is a member of the SHA2 family. It outputs hash values of 256
411 bits, or 32 octets. Nettle defines SHA256 in @file{<nettle/sha2.h>}.
412
413 @deftp {Context struct} {struct sha256_ctx}
414 @end deftp
415
416 @defvr Constant SHA256_DIGEST_SIZE
417 The size of a SHA256 digest, i.e. 32.
418 @end defvr
419
420 @defvr Constant SHA256_DATA_SIZE
421 The internal block size of SHA256. Useful for some special constructions,
422 in particular HMAC-SHA256.
423 @end defvr
424
425 @deftypefun void sha256_init (struct sha256_ctx *@var{ctx})
426 Initialize the SHA256 state.
427 @end deftypefun
428
429 @deftypefun void sha256_update (struct sha256_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
430 Hash some more data.
431 @end deftypefun
432
433 @deftypefun void sha256_digest (struct sha256_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
434 Performs final processing and extracts the message digest, writing it
435 to @var{digest}. @var{length} may be smaller than
436 @code{SHA256_DIGEST_SIZE}, in which case only the first @var{length}
437 octets of the digest are written.
438
439 This function also resets the context in the same way as
440 @code{sha256_init}.
441 @end deftypefun
442
443 Earlier versions of nettle defined SHA256 in the header file
444 @file{<nettle/sha.h>}, which is now deprecated, but kept for
445 compatibility.
446
447 @subsubsection @acronym{SHA224}
448
449 SHA224 is a variant of SHA256, with a different initial state, and with
450 the output truncated to 224 bits, or 28 octets. Nettle defines SHA224 in
451 @file{<nettle/sha2.h>} (and in @file{<nettle/sha.h>}, for backwards
452 compatibility).
453
454 @deftp {Context struct} {struct sha224_ctx}
455 @end deftp
456
457 @defvr Constant SHA224_DIGEST_SIZE
458 The size of a SHA224 digest, i.e. 28.
459 @end defvr
460
461 @defvr Constant SHA224_DATA_SIZE
462 The internal block size of SHA224. Useful for some special constructions,
463 in particular HMAC-SHA224.
464 @end defvr
465
466 @deftypefun void sha224_init (struct sha224_ctx *@var{ctx})
467 Initialize the SHA224 state.
468 @end deftypefun
469
470 @deftypefun void sha224_update (struct sha224_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
471 Hash some more data.
472 @end deftypefun
473
474 @deftypefun void sha224_digest (struct sha224_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
475 Performs final processing and extracts the message digest, writing it
476 to @var{digest}. @var{length} may be smaller than
477 @code{SHA224_DIGEST_SIZE}, in which case only the first @var{length}
478 octets of the digest are written.
479
480 This function also resets the context in the same way as
481 @code{sha224_init}.
482 @end deftypefun
483
484 @subsubsection @acronym{SHA512}
485
486 SHA512 is a larger sibling to SHA256, with a very similar structure but
487 with both the output and the internal variables of twice the size. The
488 internal variables are 64 bits rather than 32, making it significantly
489 slower on 32-bit computers. It outputs hash values of 512 bits, or 64
490 octets. Nettle defines SHA512 in @file{<nettle/sha2.h>} (and in
491 @file{<nettle/sha.h>}, for backwards compatibility).
492
493 @deftp {Context struct} {struct sha512_ctx}
494 @end deftp
495
496 @defvr Constant SHA512_DIGEST_SIZE
497 The size of a SHA512 digest, i.e. 64.
498 @end defvr
499
500 @defvr Constant SHA512_DATA_SIZE
501 The internal block size of SHA512. Useful for some special constructions,
502 in particular HMAC-SHA512.
503 @end defvr
504
505 @deftypefun void sha512_init (struct sha512_ctx *@var{ctx})
506 Initialize the SHA512 state.
507 @end deftypefun
508
509 @deftypefun void sha512_update (struct sha512_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
510 Hash some more data.
511 @end deftypefun
512
513 @deftypefun void sha512_digest (struct sha512_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
514 Performs final processing and extracts the message digest, writing it
515 to @var{digest}. @var{length} may be smaller than
516 @code{SHA512_DIGEST_SIZE}, in which case only the first @var{length}
517 octets of the digest are written.
518
519 This function also resets the context in the same way as
520 @code{sha512_init}.
521 @end deftypefun
522
523 @subsubsection @acronym{SHA384}
524
525 SHA384 is a variant of SHA512, with a different initial state, and with
526 the output truncated to 384 bits, or 48 octets. Nettle defines SHA384 in
527 @file{<nettle/sha2.h>} (and in @file{<nettle/sha.h>}, for backwards
528 compatibility).
529
530 @deftp {Context struct} {struct sha384_ctx}
531 @end deftp
532
533 @defvr Constant SHA384_DIGEST_SIZE
534 The size of a SHA384 digest, i.e. 48.
535 @end defvr
536
537 @defvr Constant SHA384_DATA_SIZE
538 The internal block size of SHA384. Useful for some special constructions,
539 in particular HMAC-SHA384.
540 @end defvr
541
542 @deftypefun void sha384_init (struct sha384_ctx *@var{ctx})
543 Initialize the SHA384 state.
544 @end deftypefun
545
546 @deftypefun void sha384_update (struct sha384_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
547 Hash some more data.
548 @end deftypefun
549
550 @deftypefun void sha384_digest (struct sha384_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
551 Performs final processing and extracts the message digest, writing it
552 to @var{digest}. @var{length} may be smaller than
553 @code{SHA384_DIGEST_SIZE}, in which case only the first @var{length}
554 octets of the digest are written.
555
556 This function also resets the context in the same way as
557 @code{sha384_init}.
558 @end deftypefun
559
560 @subsubsection @acronym{SHA3-224}
561
562 The SHA3 hash functions were specified by NIST in response to weaknesses
563 in SHA1, and doubts about SHA2 hash functions which structurally are
564 very similar to SHA1. The standard is a result of a competition, where
565 the winner, also known as Keccak, was designed by Guido Bertoni, Joan
566 Daemen, Michaël Peeters and Gilles Van Assche. It is structurally very
567 different from all widely used earlier hash functions. Like SHA2, there
568 are several variants, with output sizes of 224, 256, 384 and 512 bits
569 (28, 32, 48 and 64 octets, respectively).
570
571 Nettle defines SHA3-224 in @file{<nettle/sha3.h>}.
572
573 @deftp {Context struct} {struct sha3_224_ctx}
574 @end deftp
575
576 @defvr Constant SHA3_224_DIGEST_SIZE
577 The size of a SHA3_224 digest, i.e., 28.
578 @end defvr
579
580 @defvr Constant SHA3_224_DATA_SIZE
581 The internal block size of SHA3_224.
582 @end defvr
583
584 @deftypefun void sha3_224_init (struct sha3_224_ctx *@var{ctx})
585 Initialize the SHA3-224 state.
586 @end deftypefun
587
588 @deftypefun void sha3_224_update (struct sha3_224_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
589 Hash some more data.
590 @end deftypefun
591
592 @deftypefun void sha3_224_digest (struct sha3_224_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
593 Performs final processing and extracts the message digest, writing it
594 to @var{digest}. @var{length} may be smaller than
595 @code{SHA3_224_DIGEST_SIZE}, in which case only the first @var{length}
596 octets of the digest are written.
597
598 This function also resets the context.
599 @end deftypefun
600
601 @subsubsection @acronym{SHA3-256}
602
603 This is SHA3 with 256-bit output size, and possibly the most useful
604 of the SHA3 hash functions.
605
606 Nettle defines SHA3-256 in @file{<nettle/sha3.h>}.
607
608 @deftp {Context struct} {struct sha3_256_ctx}
609 @end deftp
610
611 @defvr Constant SHA3_256_DIGEST_SIZE
612 The size of a SHA3_256 digest, i.e., 32.
613 @end defvr
614
615 @defvr Constant SHA3_256_DATA_SIZE
616 The internal block size of SHA3_256.
617 @end defvr
618
619 @deftypefun void sha3_256_init (struct sha3_256_ctx *@var{ctx})
620 Initialize the SHA3-256 state.
621 @end deftypefun
622
623 @deftypefun void sha3_256_update (struct sha3_256_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
624 Hash some more data.
625 @end deftypefun
626
627 @deftypefun void sha3_256_digest (struct sha3_256_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
628 Performs final processing and extracts the message digest, writing it
629 to @var{digest}. @var{length} may be smaller than
630 @code{SHA3_256_DIGEST_SIZE}, in which case only the first @var{length}
631 octets of the digest are written.
632
633 This function also resets the context.
634 @end deftypefun
635
636 @subsubsection @acronym{SHA3-384}
637
638 This is SHA3 with 384-bit output size.
639
640 Nettle defines SHA3-384 in @file{<nettle/sha3.h>}.
641
642 @deftp {Context struct} {struct sha3_384_ctx}
643 @end deftp
644
645 @defvr Constant SHA3_384_DIGEST_SIZE
646 The size of a SHA3_384 digest, i.e., 48.
647 @end defvr
648
649 @defvr Constant SHA3_384_DATA_SIZE
650 The internal block size of SHA3_384.
651 @end defvr
652
653 @deftypefun void sha3_384_init (struct sha3_384_ctx *@var{ctx})
654 Initialize the SHA3-384 state.
655 @end deftypefun
656
657 @deftypefun void sha3_384_update (struct sha3_384_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
658 Hash some more data.
659 @end deftypefun
660
661 @deftypefun void sha3_384_digest (struct sha3_384_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
662 Performs final processing and extracts the message digest, writing it
663 to @var{digest}. @var{length} may be smaller than
664 @code{SHA3_384_DIGEST_SIZE}, in which case only the first @var{length}
665 octets of the digest are written.
666
667 This function also resets the context.
668 @end deftypefun
669
670 @subsubsection @acronym{SHA3-512}
671
672 This is SHA3 with 512-bit output size.
673
674 Nettle defines SHA3-512 in @file{<nettle/sha3.h>}.
675
676 @deftp {Context struct} {struct sha3_512_ctx}
677 @end deftp
678
679 @defvr Constant SHA3_512_DIGEST_SIZE
680 The size of a SHA3_512 digest, i.e. 64.
681 @end defvr
682
683 @defvr Constant SHA3_512_DATA_SIZE
684 The internal block size of SHA3_512.
685 @end defvr
686
687 @deftypefun void sha3_512_init (struct sha3_512_ctx *@var{ctx})
688 Initialize the SHA3-512 state.
689 @end deftypefun
690
691 @deftypefun void sha3_512_update (struct sha3_512_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
692 Hash some more data.
693 @end deftypefun
694
695 @deftypefun void sha3_512_digest (struct sha3_512_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
696 Performs final processing and extracts the message digest, writing it
697 to @var{digest}. @var{length} may be smaller than
698 @code{SHA3_512_DIGEST_SIZE}, in which case only the first @var{length}
699 octets of the digest are written.
700
701 This function also resets the context.
702 @end deftypefun
703
704 @node Legacy hash functions, nettle_hash abstraction, Recommended hash functions, Hash functions
705 @comment  node-name,  next,  previous,  up
706 @subsection Legacy hash functions
707
708 The hash functions in this section all have some known weaknesses, and
709 should be avoided for new applications. These hash functions are mainly
710 useful for compatibility with old applications and protocols. Some are
711 still considered safe as building blocks for particular constructions,
712 e.g., there seems to be no known attacks against HMAC-SHA1 or even
713 HMAC-MD5. In some important cases, use of a ``legacy'' hash function
714 does not in itself make the application insecure; if a known weakness is
715 relevant depends on how the hash function is used, and on the threat
716 model.
717
718 @subsubsection @acronym{MD5}
719
720 MD5 is a message digest function constructed by Ronald Rivest, and
721 described in @cite{RFC 1321}. It outputs message digests of 128 bits, or
722 16 octets. Nettle defines MD5 in @file{<nettle/md5.h>}.
723
724 @deftp {Context struct} {struct md5_ctx}
725 @end deftp
726
727 @defvr Constant MD5_DIGEST_SIZE
728 The size of an MD5 digest, i.e. 16.
729 @end defvr
730
731 @defvr Constant MD5_DATA_SIZE
732 The internal block size of MD5. Useful for some special constructions,
733 in particular HMAC-MD5.
734 @end defvr
735
736 @deftypefun void md5_init (struct md5_ctx *@var{ctx})
737 Initialize the MD5 state.
738 @end deftypefun
739
740 @deftypefun void md5_update (struct md5_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
741 Hash some more data.
742 @end deftypefun
743
744 @deftypefun void md5_digest (struct md5_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
745 Performs final processing and extracts the message digest, writing it
746 to @var{digest}. @var{length} may be smaller than
747 @code{MD5_DIGEST_SIZE}, in which case only the first @var{length}
748 octets of the digest are written.
749
750 This function also resets the context in the same way as
751 @code{md5_init}.
752 @end deftypefun
753
754 The normal way to use MD5 is to call the functions in order: First
755 @code{md5_init}, then @code{md5_update} zero or more times, and finally
756 @code{md5_digest}. After @code{md5_digest}, the context is reset to
757 its initial state, so you can start over calling @code{md5_update} to
758 hash new data.
759
760 To start over, you can call @code{md5_init} at any time.
761
762 @subsubsection @acronym{MD2}
763
764 MD2 is another hash function of Ronald Rivest's, described in
765 @cite{RFC 1319}. It outputs message digests of 128 bits, or 16 octets.
766 Nettle defines MD2 in @file{<nettle/md2.h>}.
767
768 @deftp {Context struct} {struct md2_ctx}
769 @end deftp
770
771 @defvr Constant MD2_DIGEST_SIZE
772 The size of an MD2 digest, i.e. 16.
773 @end defvr
774
775 @defvr Constant MD2_DATA_SIZE
776 The internal block size of MD2.
777 @end defvr
778
779 @deftypefun void md2_init (struct md2_ctx *@var{ctx})
780 Initialize the MD2 state.
781 @end deftypefun
782
783 @deftypefun void md2_update (struct md2_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
784 Hash some more data.
785 @end deftypefun
786
787 @deftypefun void md2_digest (struct md2_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
788 Performs final processing and extracts the message digest, writing it
789 to @var{digest}. @var{length} may be smaller than
790 @code{MD2_DIGEST_SIZE}, in which case only the first @var{length}
791 octets of the digest are written.
792
793 This function also resets the context in the same way as
794 @code{md2_init}.
795 @end deftypefun
796
797 @subsubsection @acronym{MD4}
798
799 MD4 is a predecessor of MD5, described in @cite{RFC 1320}. Like MD5, it
800 is constructed by Ronald Rivest. It outputs message digests of 128 bits,
801 or 16 octets. Nettle defines MD4 in @file{<nettle/md4.h>}. Use of MD4 is
802 not recommended, but it is sometimes needed for compatibility with
803 existing applications and protocols.
804
805 @deftp {Context struct} {struct md4_ctx}
806 @end deftp
807
808 @defvr Constant MD4_DIGEST_SIZE
809 The size of an MD4 digest, i.e. 16.
810 @end defvr
811
812 @defvr Constant MD4_DATA_SIZE
813 The internal block size of MD4.
814 @end defvr
815
816 @deftypefun void md4_init (struct md4_ctx *@var{ctx})
817 Initialize the MD4 state.
818 @end deftypefun
819
820 @deftypefun void md4_update (struct md4_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
821 Hash some more data.
822 @end deftypefun
823
824 @deftypefun void md4_digest (struct md4_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
825 Performs final processing and extracts the message digest, writing it
826 to @var{digest}. @var{length} may be smaller than
827 @code{MD4_DIGEST_SIZE}, in which case only the first @var{length}
828 octets of the digest are written.
829
830 This function also resets the context in the same way as
831 @code{md4_init}.
832 @end deftypefun
833
834 @subsubsection @acronym{RIPEMD160}
835
836 RIPEMD160 is a hash function designed by Hans Dobbertin, Antoon
837 Bosselaers, and Bart Preneel, as a strengthened version of RIPEMD
838 (which, like MD4 and MD5, fails the collision-resistance requirement).
839 It produces message digests of 160 bits, or 20 octets. Nettle defined
840 RIPEMD160 in @file{nettle/ripemd160.h}.
841
842 @deftp {Context struct} {struct ripemd160_ctx}
843 @end deftp
844
845 @defvr Constant RIPEMD160_DIGEST_SIZE
846 The size of a RIPEMD160 digest, i.e. 20.
847 @end defvr
848
849 @defvr Constant RIPEMD160_DATA_SIZE
850 The internal block size of RIPEMD160.
851 @end defvr
852
853 @deftypefun void ripemd160_init (struct ripemd160_ctx *@var{ctx})
854 Initialize the RIPEMD160 state.
855 @end deftypefun
856
857 @deftypefun void ripemd160_update (struct ripemd160_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
858 Hash some more data.
859 @end deftypefun
860
861 @deftypefun void ripemd160_digest (struct ripemd160_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
862 Performs final processing and extracts the message digest, writing it
863 to @var{digest}. @var{length} may be smaller than
864 @code{RIPEMD160_DIGEST_SIZE}, in which case only the first @var{length}
865 octets of the digest are written.
866
867 This function also resets the context in the same way as
868 @code{ripemd160_init}.
869 @end deftypefun
870
871 @subsubsection @acronym{SHA1}
872
873 SHA1 is a hash function specified by @dfn{NIST} (The U.S. National
874 Institute for Standards and Technology). It outputs hash values of 160
875 bits, or 20 octets. Nettle defines SHA1 in @file{<nettle/sha1.h>} (and
876 in @file{<nettle/sha.h>}, for backwards compatibility).
877
878 @deftp {Context struct} {struct sha1_ctx}
879 @end deftp
880
881 @defvr Constant SHA1_DIGEST_SIZE
882 The size of a SHA1 digest, i.e. 20.
883 @end defvr
884
885 @defvr Constant SHA1_DATA_SIZE
886 The internal block size of SHA1. Useful for some special constructions,
887 in particular HMAC-SHA1.
888 @end defvr
889
890 @deftypefun void sha1_init (struct sha1_ctx *@var{ctx})
891 Initialize the SHA1 state.
892 @end deftypefun
893
894 @deftypefun void sha1_update (struct sha1_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
895 Hash some more data.
896 @end deftypefun
897
898 @deftypefun void sha1_digest (struct sha1_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
899 Performs final processing and extracts the message digest, writing it
900 to @var{digest}. @var{length} may be smaller than
901 @code{SHA1_DIGEST_SIZE}, in which case only the first @var{length}
902 octets of the digest are written.
903
904 This function also resets the context in the same way as
905 @code{sha1_init}.
906 @end deftypefun
907
908
909 @subsubsection @acronym{GOSTHASH94}
910
911 The GOST94 or GOST R 34.11-94 hash algorithm is a Soviet-era algorithm 
912 used in Russian government standards (see @cite{RFC 4357}).
913 It outputs message digests of 256 bits, or 32 octets.
914 Nettle defines GOSTHASH94 in @file{<nettle/gosthash94.h>}.
915
916 @deftp {Context struct} {struct gosthash94_ctx}
917 @end deftp
918
919 @defvr Constant GOSTHASH94_DIGEST_SIZE
920 The size of a GOSTHASH94 digest, i.e. 32.
921 @end defvr
922
923 @defvr Constant GOSTHASH94_DATA_SIZE
924 The internal block size of GOSTHASH94, i.e., 32.
925 @end defvr
926
927 @deftypefun void gosthash94_init (struct gosthash94_ctx *@var{ctx})
928 Initialize the GOSTHASH94 state.
929 @end deftypefun
930
931 @deftypefun void gosthash94_update (struct gosthash94_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
932 Hash some more data.
933 @end deftypefun
934
935 @deftypefun void gosthash94_digest (struct gosthash94_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
936 Performs final processing and extracts the message digest, writing it
937 to @var{digest}. @var{length} may be smaller than
938 @code{GOSTHASH94_DIGEST_SIZE}, in which case only the first @var{length}
939 octets of the digest are written.
940
941 This function also resets the context in the same way as
942 @code{gosthash94_init}.
943 @end deftypefun
944
945 @node nettle_hash abstraction,, Legacy hash functions, Hash functions
946 @comment  node-name,  next,  previous,  up
947 @subsection The nettle_hash abstraction
948
949 Nettle includes a struct including information about the supported hash
950 functions. It is defined in @file{<nettle/nettle-meta.h>}, and is used
951 by Nettle's implementation of @acronym{HMAC} (@pxref{Keyed hash
952 functions}).
953
954 @deftp {Meta struct} @code{struct nettle_hash} name context_size digest_size block_size init update digest
955 The last three attributes are function pointers, of types
956 @code{nettle_hash_init_func}, @code{nettle_hash_update_func}, and
957 @code{nettle_hash_digest_func}. The first argument to these functions is
958 @code{void *} pointer to a context struct, which is of size
959 @code{context_size}. 
960 @end deftp
961
962 @deftypevr {Constant Struct} {struct nettle_hash} nettle_md2
963 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_md4
964 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_md5
965 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_ripemd160
966 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_sha1
967 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_sha224
968 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_sha256
969 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_sha384
970 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_sha512
971 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_sha3_256
972 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_gosthash94
973 These are all the hash functions that Nettle implements.
974 @end deftypevr
975
976 Nettle also exports a list of all these hashes.
977
978 @deftypevr {Constant Array} {struct nettle_hash **} nettle_hashes
979 This list can be used to dynamically enumerate or search the supported
980 algorithms. NULL-terminated.
981 @end deftypevr
982
983 @node Cipher functions, Cipher modes, Hash functions, Reference
984 @comment  node-name,  next,  previous,  up
985 @section Cipher functions
986 @cindex Cipher
987
988 A @dfn{cipher} is a function that takes a message or @dfn{plaintext}
989 and a secret @dfn{key} and transforms it to a @dfn{ciphertext}. Given
990 only the ciphertext, but not the key, it should be hard to find the
991 plaintext. Given matching pairs of plaintext and ciphertext, it should
992 be hard to find the key.
993
994 @cindex Block Cipher
995 @cindex Stream Cipher
996
997 There are two main classes of ciphers: Block ciphers and stream ciphers.
998
999 A block cipher can process data only in fixed size chunks, called
1000 @dfn{blocks}. Typical block sizes are 8 or 16 octets. To encrypt
1001 arbitrary messages, you usually have to pad it to an integral number of
1002 blocks, split it into blocks, and then process each block. The simplest
1003 way is to process one block at a time, independent of each other. That
1004 mode of operation is called @dfn{ECB}, Electronic Code Book mode.
1005 However, using @acronym{ECB} is usually a bad idea. For a start, plaintext blocks
1006 that are equal are transformed to ciphertext blocks that are equal; that
1007 leaks information about the plaintext. Usually you should apply the
1008 cipher is some ``feedback mode'', @dfn{CBC} (Cipher Block Chaining) and
1009 @dfn{CTR} (Counter mode) being two of
1010 of the most popular. See @xref{Cipher modes}, for information on
1011 how to apply @acronym{CBC} and @acronym{CTR} with Nettle.
1012
1013 A stream cipher can be used for messages of arbitrary length. A typical
1014 stream cipher is a keyed pseudo-random generator. To encrypt a plaintext
1015 message of @var{n} octets, you key the generator, generate @var{n}
1016 octets of pseudo-random data, and XOR it with the plaintext. To decrypt,
1017 regenerate the same stream using the key, XOR it to the ciphertext, and
1018 the plaintext is recovered.
1019
1020 @strong{Caution:} The first rule for this kind of cipher is the
1021 same as for a One Time Pad: @emph{never} ever use the same key twice.
1022
1023 A common misconception is that encryption, by itself, implies
1024 authentication. Say that you and a friend share a secret key, and you
1025 receive an encrypted message. You apply the key, and get a plaintext
1026 message that makes sense to you. Can you then be sure that it really was
1027 your friend that wrote the message you're reading? The answer is no. For
1028 example, if you were using a block cipher in ECB mode, an attacker may
1029 pick up the message on its way, and reorder, delete or repeat some of
1030 the blocks. Even if the attacker can't decrypt the message, he can
1031 change it so that you are not reading the same message as your friend
1032 wrote. If you are using a block cipher in @acronym{CBC} mode rather than
1033 ECB, or are using a stream cipher, the possibilities for this sort of
1034 attack are different, but the attacker can still make predictable
1035 changes to the message.
1036
1037 It is recommended to @emph{always} use an authentication mechanism in
1038 addition to encrypting the messages. Popular choices are Message
1039 Authentication Codes like @acronym{HMAC-SHA1} (@pxref{Keyed hash
1040 functions}), or digital signatures like @acronym{RSA}.
1041
1042 Some ciphers have so called ``weak keys'', keys that results in
1043 undesirable structure after the key setup processing, and should be
1044 avoided. In Nettle, most key setup functions have no return value, but
1045 for ciphers with weak keys, the return value indicates whether or not
1046 the given key is weak. For good keys, key setup returns 1, and for weak
1047 keys, it returns 0. When possible, avoid algorithms that
1048 have weak keys. There are several good ciphers that don't have any weak
1049 keys.
1050
1051 To encrypt a message, you first initialize a cipher context for
1052 encryption or decryption with a particular key. You then use the context
1053 to process plaintext or ciphertext messages. The initialization is known
1054 as @dfn{key setup}. With Nettle, it is recommended to use each
1055 context struct for only one direction, even if some of the ciphers use a
1056 single key setup function that can be used for both encryption and
1057 decryption.
1058
1059 @subsection AES
1060 AES is a block cipher, specified by NIST as a replacement for
1061 the older DES standard. The standard is the result of a competition
1062 between cipher designers. The winning design, also known as RIJNDAEL,
1063 was constructed by Joan Daemen and Vincent Rijnmen.
1064
1065 Like all the AES candidates, the winning design uses a block size of 128
1066 bits, or 16 octets, and variable key-size, 128, 192 and 256 bits (16, 24
1067 and 32 octets) being the allowed key sizes. It does not have any weak
1068 keys. Nettle defines AES in @file{<nettle/aes.h>}.
1069  
1070 @deftp {Context struct} {struct aes_ctx}
1071 @end deftp
1072
1073 @defvr Constant AES_BLOCK_SIZE
1074 The AES block-size, 16.
1075 @end defvr
1076
1077 @defvr Constant AES_MIN_KEY_SIZE
1078 @end defvr
1079
1080 @defvr Constant AES_MAX_KEY_SIZE
1081 @end defvr
1082
1083 @defvr Constant AES_KEY_SIZE
1084 Default AES key size, 32.
1085 @end defvr
1086
1087 @deftypefun void aes_set_encrypt_key (struct aes_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
1088 @deftypefunx void aes_set_decrypt_key (struct aes_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
1089 Initialize the cipher, for encryption or decryption, respectively.
1090 @end deftypefun
1091
1092 @deftypefun void aes_invert_key (struct aes_ctx *@var{dst}, const struct aes_ctx *@var{src})
1093 Given a context @var{src} initialized for encryption, initializes the
1094 context struct @var{dst} for decryption, using the same key. If the same
1095 context struct is passed for both @code{src} and @code{dst}, it is
1096 converted in place. Calling @code{aes_set_encrypt_key} and
1097 @code{aes_invert_key} is more efficient than calling
1098 @code{aes_set_encrypt_key} and @code{aes_set_decrypt_key}. This function
1099 is mainly useful for applications which needs to both encrypt and
1100 decrypt using the @emph{same} key.
1101 @end deftypefun
1102
1103 @deftypefun void aes_encrypt (struct aes_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1104 Encryption function. @var{length} must be an integral multiple of the
1105 block size. If it is more than one block, the data is processed in ECB
1106 mode. @code{src} and @code{dst} may be equal, but they must not overlap
1107 in any other way.
1108 @end deftypefun
1109
1110 @deftypefun void aes_decrypt (struct aes_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1111 Analogous to @code{aes_encrypt}
1112 @end deftypefun
1113
1114 @subsection ARCFOUR
1115 ARCFOUR is a stream cipher, also known under the trade marked name RC4,
1116 and it is one of the fastest ciphers around. A problem is that the key
1117 setup of ARCFOUR is quite weak, you should never use keys with
1118 structure, keys that are ordinary passwords, or sequences of keys like
1119 ``secret:1'', ``secret:2'', @enddots{}. If you have keys that don't look
1120 like random bit strings, and you want to use ARCFOUR, always hash the
1121 key before feeding it to ARCFOUR. Furthermore, the initial bytes of the
1122 generated key stream leak information about the key; for this reason, it
1123 is recommended to discard the first 512 bytes of the key stream.
1124
1125 @example
1126 /* A more robust key setup function for ARCFOUR */
1127 void
1128 arcfour_set_key_hashed(struct arcfour_ctx *ctx,
1129                        unsigned length, const uint8_t *key)
1130 @{
1131   struct sha256_ctx hash;
1132   uint8_t digest[SHA256_DIGEST_SIZE];
1133   uint8_t buffer[0x200];
1134
1135   sha256_init(&hash);
1136   sha256_update(&hash, length, key);
1137   sha256_digest(&hash, SHA256_DIGEST_SIZE, digest);
1138
1139   arcfour_set_key(ctx, SHA256_DIGEST_SIZE, digest);
1140   arcfour_crypt(ctx, sizeof(buffer), buffer, buffer);
1141 @}
1142 @end example
1143
1144 Nettle defines ARCFOUR in @file{<nettle/arcfour.h>}.
1145
1146 @deftp {Context struct} {struct arcfour_ctx}
1147 @end deftp
1148
1149 @defvr Constant ARCFOUR_MIN_KEY_SIZE
1150 Minimum key size, 1.
1151 @end defvr
1152
1153 @defvr Constant ARCFOUR_MAX_KEY_SIZE
1154 Maximum key size, 256.
1155 @end defvr
1156
1157 @defvr Constant ARCFOUR_KEY_SIZE
1158 Default ARCFOUR key size, 16.
1159 @end defvr
1160
1161 @deftypefun void arcfour_set_key (struct arcfour_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
1162 Initialize the cipher. The same function is used for both encryption and
1163 decryption. 
1164 @end deftypefun
1165
1166 @deftypefun void arcfour_crypt (struct arcfour_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1167 Encrypt some data. The same function is used for both encryption and
1168 decryption. Unlike the block ciphers, this function modifies the
1169 context, so you can split the data into arbitrary chunks and encrypt
1170 them one after another. The result is the same as if you had called
1171 @code{arcfour_crypt} only once with all the data.
1172 @end deftypefun
1173
1174 @subsection ARCTWO
1175 ARCTWO (also known as the trade marked name RC2) is a block cipher
1176 specified in RFC 2268. Nettle also include a variation of the ARCTWO
1177 set key operation that lack one step, to be compatible with the
1178 reverse engineered RC2 cipher description, as described in a Usenet
1179 post to @code{sci.crypt} by Peter Gutmann.
1180
1181 ARCTWO uses a block size of 64 bits, and variable key-size ranging
1182 from 1 to 128 octets. Besides the key, ARCTWO also has a second
1183 parameter to key setup, the number of effective key bits, @code{ekb}.
1184 This parameter can be used to artificially reduce the key size. In
1185 practice, @code{ekb} is usually set equal to the input key size.
1186 Nettle defines ARCTWO in @file{<nettle/arctwo.h>}.
1187
1188 We do not recommend the use of ARCTWO; the Nettle implementation is
1189 provided primarily for interoperability with existing applications and
1190 standards.
1191
1192 @deftp {Context struct} {struct arctwo_ctx}
1193 @end deftp
1194
1195 @defvr Constant ARCTWO_BLOCK_SIZE
1196 The ARCTWO block-size, 8.
1197 @end defvr
1198
1199 @defvr Constant ARCTWO_MIN_KEY_SIZE
1200 @end defvr
1201
1202 @defvr Constant ARCTWO_MAX_KEY_SIZE
1203 @end defvr
1204
1205 @defvr Constant ARCTWO_KEY_SIZE
1206 Default ARCTWO key size, 8.
1207 @end defvr
1208
1209 @deftypefun void arctwo_set_key_ekb (struct arctwo_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key}, unsigned @var{ekb})
1210 @deftypefunx void arctwo_set_key (struct arctwo_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
1211 @deftypefunx void arctwo_set_key_gutmann (struct arctwo_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
1212 Initialize the cipher. The same function is used for both encryption
1213 and decryption. The first function is the most general one, which lets
1214 you provide both the variable size key, and the desired effective key
1215 size (in bits). The maximum value for @var{ekb} is 1024, and for
1216 convenience, @code{ekb = 0} has the same effect as @code{ekb = 1024}.
1217
1218 @code{arctwo_set_key(ctx, length, key)} is equivalent to
1219 @code{arctwo_set_key_ekb(ctx, length, key, 8*length)}, and
1220 @code{arctwo_set_key_gutmann(ctx, length, key)} is equivalent to
1221 @code{arctwo_set_key_ekb(ctx, length, key, 1024)}
1222 @end deftypefun
1223
1224 @deftypefun void arctwo_encrypt (struct arctwo_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1225 Encryption function. @var{length} must be an integral multiple of the
1226 block size. If it is more than one block, the data is processed in ECB
1227 mode. @code{src} and @code{dst} may be equal, but they must not
1228 overlap in any other way.
1229 @end deftypefun
1230
1231 @deftypefun void arctwo_decrypt (struct arctwo_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1232 Analogous to @code{arctwo_encrypt}
1233 @end deftypefun
1234
1235 @subsection BLOWFISH
1236
1237 BLOWFISH is a block cipher designed by Bruce Schneier. It uses a block
1238 size of 64 bits (8 octets), and a variable key size, up to 448 bits. It
1239 has some weak keys. Nettle defines BLOWFISH in @file{<nettle/blowfish.h>}.
1240
1241 @deftp {Context struct} {struct blowfish_ctx}
1242 @end deftp
1243
1244 @defvr Constant BLOWFISH_BLOCK_SIZE
1245 The BLOWFISH block-size, 8.
1246 @end defvr
1247
1248 @defvr Constant BLOWFISH_MIN_KEY_SIZE
1249 Minimum BLOWFISH key size, 8.
1250 @end defvr
1251
1252 @defvr Constant BLOWFISH_MAX_KEY_SIZE
1253 Maximum BLOWFISH key size, 56.
1254 @end defvr
1255
1256 @defvr Constant BLOWFISH_KEY_SIZE
1257 Default BLOWFISH key size, 16.
1258 @end defvr
1259
1260 @deftypefun int blowfish_set_key (struct blowfish_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
1261 Initialize the cipher. The same function is used for both encryption and
1262 decryption. Checks for weak keys, returning 1
1263 for good keys and 0 for weak keys. Applications that don't care about
1264 weak keys can ignore the return value.
1265
1266 @code{blowfish_encrypt} or @code{blowfish_decrypt} with a weak key will
1267 crash with an assert violation.
1268 @end deftypefun
1269
1270 @deftypefun void blowfish_encrypt (struct blowfish_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1271 Encryption function. @var{length} must be an integral multiple of the
1272 block size. If it is more than one block, the data is processed in ECB
1273 mode. @code{src} and @code{dst} may be equal, but they must not overlap
1274 in any other way.
1275 @end deftypefun
1276
1277 @deftypefun void blowfish_decrypt (struct blowfish_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1278 Analogous to @code{blowfish_encrypt}
1279 @end deftypefun
1280
1281 @subsection Camellia
1282
1283 Camellia is a block cipher developed by Mitsubishi and Nippon Telegraph
1284 and Telephone Corporation, described in @cite{RFC3713}, and recommended
1285 by some Japanese and European authorities as an alternative to AES. The
1286 algorithm is patented. The implementation in Nettle is derived from the
1287 implementation released by NTT under the GNU LGPL (v2.1 or later), and
1288 relies on the implicit patent license of the LGPL. There is also a
1289 statement of royalty-free licensing for Camellia at
1290 @url{http://www.ntt.co.jp/news/news01e/0104/010417.html}, but this
1291 statement has some limitations which seem problematic for free software.
1292
1293 Camellia uses a the same block size and key sizes as AES: The block size
1294 is 128 bits (16 octets), and the supported key sizes are 128, 192, and
1295 256 bits. Nettle defines Camellia in @file{<nettle/camellia.h>}.
1296
1297 @deftp {Context struct} {struct camellia_ctx}
1298 @end deftp
1299
1300 @defvr Constant CAMELLIA_BLOCK_SIZE
1301 The CAMELLIA block-size, 16.
1302 @end defvr
1303
1304 @defvr Constant CAMELLIA_MIN_KEY_SIZE
1305 @end defvr
1306
1307 @defvr Constant CAMELLIA_MAX_KEY_SIZE
1308 @end defvr
1309
1310 @defvr Constant CAMELLIA_KEY_SIZE
1311 Default CAMELLIA key size, 32.
1312 @end defvr
1313
1314 @deftypefun void camellia_set_encrypt_key (struct camellia_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
1315 @deftypefunx void camellia_set_decrypt_key (struct camellia_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
1316 Initialize the cipher, for encryption or decryption, respectively.
1317 @end deftypefun
1318
1319 @deftypefun void camellia_invert_key (struct camellia_ctx *@var{dst}, const struct camellia_ctx *@var{src})
1320 Given a context @var{src} initialized for encryption, initializes the
1321 context struct @var{dst} for decryption, using the same key. If the same
1322 context struct is passed for both @code{src} and @code{dst}, it is
1323 converted in place. Calling @code{camellia_set_encrypt_key} and
1324 @code{camellia_invert_key} is more efficient than calling
1325 @code{camellia_set_encrypt_key} and @code{camellia_set_decrypt_key}. This function
1326 is mainly useful for applications which needs to both encrypt and
1327 decrypt using the @emph{same} key.
1328 @end deftypefun
1329
1330 @deftypefun void camellia_crypt (struct camellia_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1331 The same function is used for both encryption and decryption.
1332 @var{length} must be an integral multiple of the block size. If it is
1333 more than one block, the data is processed in ECB mode. @code{src} and
1334 @code{dst} may be equal, but they must not overlap in any other way.
1335 @end deftypefun
1336
1337 @subsection CAST128
1338
1339 CAST-128 is a block cipher, specified in @cite{RFC 2144}. It uses a 64
1340 bit (8 octets) block size, and a variable key size of up to 128 bits.
1341 Nettle defines cast128 in @file{<nettle/cast128.h>}.
1342
1343 @deftp {Context struct} {struct cast128_ctx}
1344 @end deftp
1345
1346 @defvr Constant CAST128_BLOCK_SIZE
1347 The CAST128 block-size, 8.
1348 @end defvr
1349
1350 @defvr Constant CAST128_MIN_KEY_SIZE
1351 Minimum CAST128 key size, 5.
1352 @end defvr
1353
1354 @defvr Constant CAST128_MAX_KEY_SIZE
1355 Maximum CAST128 key size, 16.
1356 @end defvr
1357
1358 @defvr Constant CAST128_KEY_SIZE
1359 Default CAST128 key size, 16.
1360 @end defvr
1361
1362 @deftypefun void cast128_set_key (struct cast128_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
1363 Initialize the cipher. The same function is used for both encryption and
1364 decryption. 
1365 @end deftypefun
1366
1367 @deftypefun void cast128_encrypt (struct cast128_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1368 Encryption function. @var{length} must be an integral multiple of the
1369 block size. If it is more than one block, the data is processed in ECB
1370 mode. @code{src} and @code{dst} may be equal, but they must not overlap
1371 in any other way.
1372 @end deftypefun
1373
1374 @deftypefun void cast128_decrypt (struct cast128_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1375 Analogous to @code{cast128_encrypt}
1376 @end deftypefun
1377
1378 @subsection DES
1379 DES is the old Data Encryption Standard, specified by NIST. It uses a
1380 block size of 64 bits (8 octets), and a key size of 56 bits. However,
1381 the key bits are distributed over 8 octets, where the least significant
1382 bit of each octet may be used for parity. A common way to use DES is to
1383 generate 8 random octets in some way, then set the least significant bit
1384 of each octet to get odd parity, and initialize DES with the resulting
1385 key.
1386
1387 The key size of DES is so small that keys can be found by brute force,
1388 using specialized hardware or lots of ordinary work stations in
1389 parallel. One shouldn't be using plain DES at all today, if one uses
1390 DES at all one should be using ``triple DES'', see DES3 below.
1391
1392 DES also has some weak keys. Nettle defines DES in @file{<nettle/des.h>}.
1393
1394 @deftp {Context struct} {struct des_ctx}
1395 @end deftp
1396
1397 @defvr Constant DES_BLOCK_SIZE
1398 The DES block-size, 8.
1399 @end defvr
1400
1401 @defvr Constant DES_KEY_SIZE
1402 DES key size, 8.
1403 @end defvr
1404
1405 @deftypefun int des_set_key (struct des_ctx *@var{ctx}, const uint8_t *@var{key})
1406 Initialize the cipher. The same function is used for both encryption and
1407 decryption. Parity bits are ignored. Checks for weak keys, returning 1
1408 for good keys and 0 for weak keys. Applications that don't care about
1409 weak keys can ignore the return value.
1410 @end deftypefun
1411
1412 @deftypefun void des_encrypt (struct des_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1413 Encryption function. @var{length} must be an integral multiple of the
1414 block size. If it is more than one block, the data is processed in ECB
1415 mode. @code{src} and @code{dst} may be equal, but they must not overlap
1416 in any other way.
1417 @end deftypefun
1418
1419 @deftypefun void des_decrypt (struct des_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1420 Analogous to @code{des_encrypt}
1421 @end deftypefun
1422
1423 @deftypefun int des_check_parity (unsigned @var{length}, const uint8_t *@var{key});
1424 Checks that the given key has correct, odd, parity. Returns 1 for
1425 correct parity, and 0 for bad parity.
1426 @end deftypefun
1427
1428 @deftypefun void des_fix_parity (unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1429 Adjusts the parity bits to match DES's requirements. You need this
1430 function if you have created a random-looking string by a key agreement
1431 protocol, and want to use it as a DES key. @var{dst} and @var{src} may
1432 be equal.
1433 @end deftypefun
1434
1435 @subsection DES3
1436 The inadequate key size of DES has already been mentioned. One way to
1437 increase the key size is to pipe together several DES boxes with
1438 independent keys. It turns out that using two DES ciphers is not as
1439 secure as one might think, even if the key size of the combination is a
1440 respectable 112 bits.
1441
1442 The standard way to increase DES's key size is to use three DES boxes.
1443 The mode of operation is a little peculiar: the middle DES box is wired
1444 in the reverse direction. To encrypt a block with DES3, you encrypt it
1445 using the first 56 bits of the key, then @emph{decrypt} it using the
1446 middle 56 bits of the key, and finally encrypt it again using the last
1447 56 bits of the key. This is known as ``ede'' triple-DES, for
1448 ``encrypt-decrypt-encrypt''.
1449
1450 The ``ede'' construction provides some backward compatibility, as you get
1451 plain single DES simply by feeding the same key to all three boxes. That
1452 should help keeping down the gate count, and the price, of hardware
1453 circuits implementing both plain DES and DES3.
1454
1455 DES3 has a key size of 168 bits, but just like plain DES, useless parity
1456 bits are inserted, so that keys are represented as 24 octets (192 bits).
1457 As a 112 bit key is large enough to make brute force attacks
1458 impractical, some applications uses a ``two-key'' variant of triple-DES.
1459 In this mode, the same key bits are used for the first and the last DES
1460 box in the pipe, while the middle box is keyed independently. The
1461 two-key variant is believed to be secure, i.e. there are no known
1462 attacks significantly better than brute force.
1463
1464 Naturally, it's simple to implement triple-DES on top of Nettle's DES
1465 functions. Nettle includes an implementation of three-key ``ede''
1466 triple-DES, it is defined in the same place as plain DES,
1467 @file{<nettle/des.h>}.
1468
1469 @deftp {Context struct} {struct des3_ctx}
1470 @end deftp
1471
1472 @defvr Constant DES3_BLOCK_SIZE
1473 The DES3 block-size is the same as DES_BLOCK_SIZE, 8.
1474 @end defvr
1475
1476 @defvr Constant DES3_KEY_SIZE
1477 DES key size, 24.
1478 @end defvr
1479
1480 @deftypefun int des3_set_key (struct des3_ctx *@var{ctx}, const uint8_t *@var{key})
1481 Initialize the cipher. The same function is used for both encryption and
1482 decryption. Parity bits are ignored. Checks for weak keys, returning 1
1483 if all three keys are good keys, and 0 if one or more key is weak.
1484 Applications that don't care about weak keys can ignore the return
1485 value.
1486 @end deftypefun
1487
1488 For random-looking strings, you can use @code{des_fix_parity} to adjust
1489 the parity bits before calling @code{des3_set_key}.
1490
1491 @deftypefun void des3_encrypt (struct des3_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1492 Encryption function. @var{length} must be an integral multiple of the
1493 block size. If it is more than one block, the data is processed in ECB
1494 mode. @code{src} and @code{dst} may be equal, but they must not overlap
1495 in any other way.
1496 @end deftypefun
1497
1498 @deftypefun void des3_decrypt (struct des3_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1499 Analogous to @code{des_encrypt}
1500 @end deftypefun
1501
1502 @subsection Salsa20
1503 Salsa20 is a fairly recent stream cipher designed by D. J. Bernstein. It
1504 is built on the observation that a cryptographic hash function can be
1505 used for encryption: Form the hash input from the secret key and a
1506 counter, xor the hash output and the first block of the plaintext, then
1507 increment the counter to process the next block (similar to CTR mode, see
1508 @pxref{CTR}). Bernstein defined an encryption algorithm, Snuffle,
1509 in this way to ridicule United States export restrictions which treated hash
1510 functions as nice and harmless, but ciphers as dangerous munitions.
1511
1512 Salsa20 uses the same idea, but with a new specialized hash function to
1513 mix key, block counter, and a couple of constants. It's also designed
1514 for speed; on x86_64, it is currently the fastest cipher offered by
1515 nettle. It uses a block size of 512 bits (64 octets) and there are two
1516 specified key sizes, 128 and 256 bits (16 and 32 octets).
1517
1518 @strong{Caution:} The hash function used in Salsa20 is @emph{not}
1519 directly applicable for use as a general hash function. It's @emph{not}
1520 collision resistant if arbitrary inputs are allowed, and furthermore,
1521 the input and output is of fixed size.
1522
1523 When using Salsa20 to process a message, one specifies both a key and a
1524 @dfn{nonce}, the latter playing a similar rôle to the initialization
1525 vector (@acronym{IV}) used with @acronym{CBC} or @acronym{CTR} mode. For
1526 this reason, Nettle uses the term @acronym{IV} to refer to the Salsa20
1527 nonce. One can use the same key for several messages, provided one uses
1528 a unique random @acronym{iv} for each message. The @acronym{iv} is 64
1529 bits (8 octets). The block counter is initialized to zero for each
1530 message, and is also 64 bits (8 octets). Nettle defines Salsa20 in
1531 @file{<nettle/salsa20.h>}.
1532
1533 @deftp {Context struct} {struct salsa20_ctx}
1534 @end deftp
1535
1536 @defvr Constant SALSA20_MIN_KEY_SIZE
1537 @defvrx Constant SALSA20_MAX_KEY_SIZE
1538 The two supported key sizes, 16 and 32 octets.
1539 @end defvr
1540
1541 @defvr Constant SALSA20_KEY_SIZE
1542 Recommended key size, 32.
1543 @end defvr
1544
1545 @defvr Constant SALSA20_BLOCK_SIZE
1546 Salsa20 block size, 64.
1547 @end defvr
1548
1549 @defvr Constant SALSA20_IV_SIZE
1550 Size of the @acronym{IV}, 8.
1551 @end defvr
1552
1553 @deftypefun void salsa20_set_key (struct salsa20_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
1554 Initialize the cipher. The same function is used for both encryption and
1555 decryption. Before using the cipher, you @emph{must} also call
1556 @code{salsa20_set_iv}, see below.
1557 @end deftypefun
1558
1559 @deftypefun void salsa20_set_iv (struct salsa20_ctx *@var{ctx}, const uint8_t *@var{iv})
1560 Sets the @acronym{IV}. It is always of size @code{SALSA20_IV_SIZE}, 8
1561 octets. This function also initializes the block counter, setting it to
1562 zero.
1563 @end deftypefun
1564
1565 @deftypefun void salsa20_crypt (struct salsa20_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1566 Encrypts or decrypts the data of a message, using salsa20. When a
1567 message is encrypted using a sequence of calls to @code{salsa20_crypt},
1568 all but the last call @emph{must} use a length that is a multiple of
1569 @code{SALSA20_BLOCK_SIZE}.
1570 @end deftypefun
1571
1572 The full salsa20 cipher uses 20 rounds of mixing. Variants of Salsa20
1573 with fewer rounds are possible, and the 12-round variant is specified by
1574 eSTREAM, see @url{http://www.ecrypt.eu.org/stream/finallist.html}.
1575 Nettle calls this variant @code{salsa20r12}. It uses the same context
1576 struct and key setup as the full salsa20 cipher, but a separate function
1577 for encryption and decryption.
1578
1579 @deftypefun void salsa20r12_crypt (struct salsa20_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1580 Encrypts or decrypts the data of a message, using salsa20 reduced to 12
1581 rounds.
1582 @end deftypefun
1583
1584 @subsection SERPENT
1585 SERPENT is one of the AES finalists, designed by Ross Anderson, Eli
1586 Biham and Lars Knudsen. Thus, the interface and properties are similar
1587 to AES'. One peculiarity is that it is quite pointless to use it with
1588 anything but the maximum key size, smaller keys are just padded to
1589 larger ones. Nettle defines SERPENT in @file{<nettle/serpent.h>}.
1590
1591 @deftp {Context struct} {struct serpent_ctx}
1592 @end deftp
1593
1594 @defvr Constant SERPENT_BLOCK_SIZE
1595 The SERPENT block-size, 16.
1596 @end defvr
1597
1598 @defvr Constant SERPENT_MIN_KEY_SIZE
1599 Minimum SERPENT key size, 16.
1600 @end defvr
1601
1602 @defvr Constant SERPENT_MAX_KEY_SIZE
1603 Maximum SERPENT key size, 32.
1604 @end defvr
1605
1606 @defvr Constant SERPENT_KEY_SIZE
1607 Default SERPENT key size, 32.
1608 @end defvr
1609
1610 @deftypefun void serpent_set_key (struct serpent_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
1611 Initialize the cipher. The same function is used for both encryption and
1612 decryption. 
1613 @end deftypefun
1614
1615 @deftypefun void serpent_encrypt (struct serpent_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1616 Encryption function. @var{length} must be an integral multiple of the
1617 block size. If it is more than one block, the data is processed in ECB
1618 mode. @code{src} and @code{dst} may be equal, but they must not overlap
1619 in any other way.
1620 @end deftypefun
1621
1622 @deftypefun void serpent_decrypt (struct serpent_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1623 Analogous to @code{serpent_encrypt}
1624 @end deftypefun
1625
1626
1627 @subsection TWOFISH
1628 Another AES finalist, this one designed by Bruce Schneier and others.
1629 Nettle defines it in @file{<nettle/twofish.h>}.
1630
1631 @deftp {Context struct} {struct twofish_ctx}
1632 @end deftp
1633
1634 @defvr Constant TWOFISH_BLOCK_SIZE
1635 The TWOFISH block-size, 16.
1636 @end defvr
1637
1638 @defvr Constant TWOFISH_MIN_KEY_SIZE
1639 Minimum TWOFISH key size, 16.
1640 @end defvr
1641
1642 @defvr Constant TWOFISH_MAX_KEY_SIZE
1643 Maximum TWOFISH key size, 32.
1644 @end defvr
1645
1646 @defvr Constant TWOFISH_KEY_SIZE
1647 Default TWOFISH key size, 32.
1648 @end defvr
1649
1650 @deftypefun void twofish_set_key (struct twofish_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
1651 Initialize the cipher. The same function is used for both encryption and
1652 decryption. 
1653 @end deftypefun
1654
1655 @deftypefun void twofish_encrypt (struct twofish_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1656 Encryption function. @var{length} must be an integral multiple of the
1657 block size. If it is more than one block, the data is processed in ECB
1658 mode. @code{src} and @code{dst} may be equal, but they must not overlap
1659 in any other way.
1660 @end deftypefun
1661
1662 @deftypefun void twofish_decrypt (struct twofish_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1663 Analogous to @code{twofish_encrypt}
1664 @end deftypefun
1665
1666 @c @node nettle_cipher, Cipher Block Chaining, Cipher functions, Reference
1667 @c @comment  node-name,  next,  previous,  up
1668 @subsection @code{struct nettle_cipher}
1669
1670 Nettle includes a struct including information about some of the more
1671 regular cipher functions. It should be considered a little experimental,
1672 but can be useful for applications that need a simple way to handle
1673 various algorithms. Nettle defines these structs in
1674 @file{<nettle/nettle-meta.h>}. 
1675
1676 @deftp {Meta struct} @code{struct nettle_cipher} name context_size block_size key_size set_encrypt_key set_decrypt_key encrypt decrypt
1677 The last four attributes are function pointers, of types
1678 @code{nettle_set_key_func} and @code{nettle_crypt_func}. The first
1679 argument to these functions is a @code{void *} pointer to a context
1680 struct, which is of size @code{context_size}.
1681 @end deftp
1682
1683 @deftypevr {Constant Struct} {struct nettle_cipher} nettle_aes128
1684 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_aes192
1685 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_aes256
1686
1687 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arctwo40
1688 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arctwo64
1689 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arctwo128
1690 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arctwo_gutmann128
1691
1692 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arcfour128
1693
1694 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_camellia128
1695 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_camellia192
1696 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_camellia256
1697
1698 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_cast128
1699
1700 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_serpent128
1701 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_serpent192
1702 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_serpent256
1703
1704 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_twofish128
1705 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_twofish192
1706 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_twofish256
1707 Nettle includes such structs for all the @emph{regular} ciphers, i.e.
1708 ones without weak keys or other oddities.
1709 @end deftypevr
1710
1711 Nettle also exports a list of all these ciphers without weak keys or
1712 other oddities.
1713
1714 @deftypevr {Constant Array} {struct nettle_cipher **} nettle_ciphers
1715 This list can be used to dynamically enumerate or search the supported
1716 algorithms. NULL-terminated.
1717 @end deftypevr
1718
1719 @node Cipher modes, Keyed hash functions, Cipher functions, Reference
1720 @comment  node-name,  next,  previous,  up
1721 @section Cipher modes
1722
1723 Cipher modes of operation specifies the procedure to use when encrypting
1724 a message that is larger than the cipher's block size. As explained in
1725 @xref{Cipher functions}, splitting the message into blocks and
1726 processing them independently with the block cipher (Electronic Code
1727 Book mode, @acronym{ECB}) leaks information. Besides @acronym{ECB},
1728 Nettle provides three other modes of operation: Cipher Block Chaining
1729 (@acronym{CBC}), Counter mode (@acronym{CTR}), and Galois/Counter mode
1730 (@acronym{GCM}). @acronym{CBC} is widely used, but there are a few
1731 subtle issues of information leakage, see, e.g.,
1732 @uref{http://www.kb.cert.org/vuls/id/958563, @acronym{SSH} @acronym{CBC}
1733 vulnerability}. @acronym{CTR} and @acronym{GCM}
1734 were standardized more recently, and are believed to be more secure.
1735 @acronym{GCM} includes message authentication; for the other modes, one
1736 should always use a @acronym{MAC} (@pxref{Keyed hash functions}) or
1737 signature to authenticate the message.
1738
1739 @menu
1740 * CBC::                         
1741 * CTR::                         
1742 * GCM::                         
1743 @end menu
1744
1745
1746 @node CBC, CTR, Cipher modes, Cipher modes
1747 @comment  node-name,  next,  previous,  up
1748 @subsection Cipher Block Chaining
1749
1750 @cindex Cipher Block Chaining
1751 @cindex CBC Mode
1752
1753 When using @acronym{CBC} mode, plaintext blocks are not encrypted
1754 independently of each other, like in Electronic Cook Book mode. Instead,
1755 when encrypting a block in @acronym{CBC} mode, the previous ciphertext
1756 block is XORed with the plaintext before it is fed to the block cipher.
1757 When encrypting the first block, a random block called an @dfn{IV}, or
1758 Initialization Vector, is used as the ``previous ciphertext block''. The
1759 IV should be chosen randomly, but it need not be kept secret, and can
1760 even be transmitted in the clear together with the encrypted data.
1761
1762 In symbols, if @code{E_k} is the encryption function of a block cipher,
1763 and @code{IV} is the initialization vector, then @code{n} plaintext blocks
1764 @code{M_1},@dots{} @code{M_n} are transformed into @code{n} ciphertext blocks
1765 @code{C_1},@dots{} @code{C_n} as follows:
1766
1767 @example
1768 C_1 = E_k(IV  XOR M_1)
1769 C_2 = E_k(C_1 XOR M_2)
1770
1771 @dots{}
1772
1773 C_n = E_k(C_(n-1) XOR M_n)
1774 @end example
1775
1776 Nettle's includes two functions for applying a block cipher in Cipher
1777 Block Chaining (@acronym{CBC}) mode, one for encryption and one for
1778 decryption. These functions uses @code{void *} to pass cipher contexts
1779 around.
1780
1781 @deftypefun {void} cbc_encrypt (void *@var{ctx}, nettle_crypt_func @var{f}, unsigned @var{block_size}, uint8_t *@var{iv}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1782 @deftypefunx {void} cbc_decrypt (void *@var{ctx}, void (*@var{f})(), unsigned @var{block_size}, uint8_t *@var{iv}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1783
1784 Applies the encryption or decryption function @var{f} in @acronym{CBC}
1785 mode. The final ciphertext block processed is copied into @var{iv}
1786 before returning, so that large message be processed be a sequence of
1787 calls to @code{cbc_encrypt}. The function @var{f} is of type
1788
1789 @code{void f (void *@var{ctx}, unsigned @var{length}, uint8_t @var{dst},
1790 const uint8_t *@var{src})},
1791
1792 @noindent and the @code{cbc_encrypt} and @code{cbc_decrypt} functions pass their
1793 argument @var{ctx} on to @var{f}.
1794 @end deftypefun
1795
1796 There are also some macros to help use these functions correctly.
1797
1798 @deffn Macro CBC_CTX (@var{context_type}, @var{block_size})
1799 Expands to
1800 @example
1801 @{
1802    context_type ctx;
1803    uint8_t iv[block_size];
1804 @}
1805 @end example
1806 @end deffn
1807
1808 It can be used to define a @acronym{CBC} context struct, either directly,
1809
1810 @example
1811 struct CBC_CTX(struct aes_ctx, AES_BLOCK_SIZE) ctx;
1812 @end example
1813
1814 or to give it a struct tag,
1815
1816 @example
1817 struct aes_cbc_ctx CBC_CTX (struct aes_ctx, AES_BLOCK_SIZE);
1818 @end example
1819
1820 @deffn Macro CBC_SET_IV (@var{ctx}, @var{iv})
1821 First argument is a pointer to a context struct as defined by @code{CBC_CTX},
1822 and the second is a pointer to an Initialization Vector (IV) that is
1823 copied into that context.
1824 @end deffn
1825
1826 @deffn Macro CBC_ENCRYPT (@var{ctx}, @var{f}, @var{length}, @var{dst}, @var{src})
1827 @deffnx Macro CBC_DECRYPT (@var{ctx}, @var{f}, @var{length}, @var{dst}, @var{src})
1828 A simpler way to invoke @code{cbc_encrypt} and @code{cbc_decrypt}. The
1829 first argument is a pointer to a context struct as defined by
1830 @code{CBC_CTX}, and the second argument is an encryption or decryption
1831 function following Nettle's conventions. The last three arguments define
1832 the source and destination area for the operation.
1833 @end deffn
1834
1835 These macros use some tricks to make the compiler display a warning if
1836 the types of @var{f} and @var{ctx} don't match, e.g. if you try to use
1837 an @code{struct aes_ctx} context with the @code{des_encrypt} function.
1838
1839 @node CTR, GCM, CBC, Cipher modes
1840 @comment  node-name,  next,  previous,  up
1841 @subsection Counter mode
1842
1843 @cindex Counter Mode
1844 @cindex CTR Mode
1845
1846 Counter mode (@acronym{CTR}) uses the block cipher as a keyed
1847 pseudo-random generator. The output of the generator is XORed with the
1848 data to be encrypted. It can be understood as a way to transform a block
1849 cipher to a stream cipher.
1850
1851 The message is divided into @code{n} blocks @code{M_1},@dots{}
1852 @code{M_n}, where @code{M_n} is of size @code{m} which may be smaller
1853 than the block size. Except for the last block, all the message blocks
1854 must be of size equal to the cipher's block size.
1855
1856 If @code{E_k} is the encryption function of a block cipher, @code{IC} is
1857 the initial counter, then the @code{n} plaintext blocks are
1858 transformed into @code{n} ciphertext blocks @code{C_1},@dots{}
1859 @code{C_n} as follows:
1860
1861 @example
1862 C_1 = E_k(IC) XOR M_1
1863 C_2 = E_k(IC + 1) XOR M_2
1864
1865 @dots{}
1866
1867 C_(n-1) = E_k(IC + n - 2) XOR M_(n-1)
1868 C_n = E_k(IC + n - 1) [1..m] XOR M_n
1869 @end example
1870
1871 The @acronym{IC} is the initial value for the counter, it plays a
1872 similar rôle as the @acronym{IV} for @acronym{CBC}. When adding,
1873 @code{IC + x}, @acronym{IC} is interpreted as an integer, in network
1874 byte order. For the last block, @code{E_k(IC + n - 1) [1..m]} means that
1875 the cipher output is truncated to @code{m} bytes.
1876
1877 @deftypefun {void} ctr_crypt (void *@var{ctx}, nettle_crypt_func @var{f}, unsigned @var{block_size}, uint8_t *@var{ctr}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1878
1879 Applies the encryption function @var{f} in @acronym{CTR} mode. Note that
1880 for @acronym{CTR} mode, encryption and decryption is the same operation,
1881 and hence @var{f} should always be the encryption function for the
1882 underlying block cipher.
1883
1884 When a message is encrypted using a sequence of calls to
1885 @code{ctr_crypt}, all but the last call @emph{must} use a length that is
1886 a multiple of the block size.
1887 @end deftypefun
1888
1889 Like for @acronym{CBC}, there are also a couple of helper macros.
1890
1891 @deffn Macro CTR_CTX (@var{context_type}, @var{block_size})
1892 Expands to
1893 @example
1894 @{
1895    context_type ctx;
1896    uint8_t ctr[block_size];
1897 @}
1898 @end example
1899 @end deffn
1900
1901 @deffn Macro CTR_SET_COUNTER (@var{ctx}, @var{iv})
1902 First argument is a pointer to a context struct as defined by
1903 @code{CTR_CTX}, and the second is a pointer to an initial counter that
1904 is copied into that context.
1905 @end deffn
1906
1907 @deffn Macro CTR_CRYPT (@var{ctx}, @var{f}, @var{length}, @var{dst}, @var{src})
1908 A simpler way to invoke @code{ctr_crypt}. The first argument is a
1909 pointer to a context struct as defined by @code{CTR_CTX}, and the second
1910 argument is an encryption function following Nettle's conventions. The
1911 last three arguments define the source and destination area for the
1912 operation.
1913 @end deffn
1914
1915 @node GCM,  , CTR, Cipher modes
1916 @comment  node-name,  next,  previous,  up
1917 @subsection Galois counter mode
1918
1919 @cindex Galois Counter Mode
1920 @cindex GCM
1921
1922 Galois counter mode is the combination of counter mode with message
1923 authentication based on universal hashing. The main objective of the
1924 design is to provide high performance for hardware implementations,
1925 where other popular @acronym{MAC} algorithms (@pxref{Keyed hash
1926 functions} becomes a bottleneck for high-speed hardware implementations.
1927 It was proposed by David A. McGrew and John Viega in 2005, and
1928 recommended by NIST in 2007,
1929 @uref{http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf,
1930 NIST Special Publication 800-38D}. It is constructed on top of a block
1931 cipher which must have a block size of 128 bits.
1932
1933 @acronym{GCM} is applied to messages of arbitrary length. The inputs
1934 are:
1935
1936 @itemize
1937 @item 
1938 A key, which can be used for many messages.
1939 @item 
1940 An initialization vector (@acronym{IV}) which @emph{must} be unique for
1941 each message.
1942 @item
1943 Additional authenticated data, which is to be included in the message
1944 authentication, but not encrypted. May be empty.
1945 @item
1946 The plaintext. Maybe empty.
1947 @end itemize
1948
1949 The outputs are a ciphertext, of the same length as the plaintext, and a
1950 message digest of length 128 bits. Nettle's support for @acronym{GCM}
1951 consists of a low-level general interface, some convenience macros, and
1952 specific functions for @acronym{GCM} using @acronym{AES} as the
1953 underlying cipher. These interfaces are defined in @file{<nettle/gcm.h>}
1954
1955 @subsubsection General @acronym{GCM} interface
1956
1957 @deftp {Context struct} {struct gcm_key}
1958 Message independent hash sub-key, and related tables.
1959 @end deftp
1960
1961 @deftp {Context struct} {struct gcm_ctx}
1962 Holds state corresponding to a particular message.
1963 @end deftp
1964
1965 @defvr Constant GCM_BLOCK_SIZE
1966 @acronym{GCM}'s block size, 16.
1967 @end defvr
1968
1969 @defvr Constant GCM_IV_SIZE
1970 Recommended size of the @acronym{IV}, 12. Other sizes are allowed.
1971 @end defvr
1972
1973 @deftypefun void gcm_set_key (struct gcm_key *@var{key}, void *@var{cipher}, nettle_crypt_func *@var{f})
1974 Initializes @var{key}. @var{cipher} gives a context struct for the
1975 underlying cipher, which must have been previously initialized for
1976 encryption, and @var{f} is the encryption function.
1977 @end deftypefun
1978
1979 @deftypefun void gcm_set_iv (struct gcm_ctx *@var{ctx}, const struct gcm_key *@var{key}, unsigned @var{length}, const uint8_t *@var{iv})
1980 Initializes @var{ctx} using the given @acronym{IV}. The @var{key}
1981 argument is actually needed only if @var{length} differs from
1982 @code{GCM_IV_SIZE}.
1983 @end deftypefun
1984
1985 @deftypefun void gcm_update (struct gcm_ctx *@var{ctx}, const struct gcm_key *@var{key}, unsigned @var{length}, const uint8_t *@var{data})
1986 Provides associated data to be authenticated. If used, must be called
1987 before @code{gcm_encrypt} or @code{gcm_decrypt}. All but the last call
1988 for each message @emph{must} use a length that is a multiple of the
1989 block size.
1990 @end deftypefun
1991
1992 @deftypefun void gcm_encrypt (struct gcm_ctx *@var{ctx}, const struct gcm_key *@var{key} void *@var{cipher}, nettle_crypt_func *@var{f}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1993 @deftypefunx void gcm_decrypt (struct gcm_ctx *@var{ctx}, const struct gcm_key *@var{key}, void *@var{cipher}, nettle_crypt_func *@var{f}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1994 Encrypts or decrypts the data of a message. @var{cipher} is the context
1995 struct for the underlying cipher and @var{f} is the encryption function.
1996 All but the last call for each message @emph{must} use a length that is
1997 a multiple of the block size.
1998 @end deftypefun
1999
2000 @deftypefun void gcm_digest (struct gcm_ctx *@var{ctx}, const struct gcm_key *@var{key}, void *@var{cipher}, nettle_crypt_func *@var{f}, unsigned @var{length}, uint8_t *@var{digest})
2001 Extracts the message digest (also known ``authentication tag''). This is
2002 the final operation when processing a message. @var{length} is usually
2003 equal to @code{GCM_BLOCK_SIZE}, but if you provide a smaller value,
2004 only the first @var{length} octets of the digest are written.
2005 @end deftypefun
2006
2007 To encrypt a message using @acronym{GCM}, first initialize a context for
2008 the underlying block cipher with a key to use for encryption. Then call
2009 the above functions in the following order: @code{gcm_set_key},
2010 @code{gcm_set_iv}, @code{gcm_update}, @code{gcm_encrypt},
2011 @code{gcm_digest}. The decryption procedure is analogous, just calling
2012 @code{gcm_decrypt} instead of @code{gcm_encrypt} (note that
2013 @acronym{GCM} decryption still uses the encryption function of the
2014 underlying block cipher). To process a new message, using the same key,
2015 call @code{gcm_set_iv} with a new @acronym{iv}.
2016
2017 @subsubsection @acronym{GCM} helper macros
2018
2019 The following macros are defined.
2020
2021 @deffn Macro GCM_CTX (@var{context_type})
2022 This defines an all-in-one context struct, including the context of the
2023 underlying cipher, the hash sub-key, and the per-message state. It expands
2024 to
2025 @example
2026 @{
2027    context_type cipher;
2028    struct gcm_key key; 
2029    struct gcm_ctx gcm;
2030 @}
2031 @end example
2032 @end deffn
2033
2034 Example use:
2035 @example
2036 struct gcm_aes_ctx GCM_CTX(struct aes_ctx);
2037 @end example
2038
2039 The following macros operate on context structs of this form.
2040
2041 @deffn Macro GCM_SET_KEY (@var{ctx}, @var{set_key}, @var{encrypt}, @var{length}, @var{data})
2042 First argument, @var{ctx}, is a context struct as defined
2043 by @code{GCM_CTX}. @var{set_key} and @var{encrypt} are functions for
2044 setting the encryption key and for encrypting data using the underlying
2045 cipher. @var{length} and @var{data} give the key.
2046 @end deffn
2047
2048 @deffn Macro GCM_SET_IV (@var{ctx}, @var{length}, @var{data})
2049 First argument is a context struct as defined by
2050 @code{GCM_CTX}. @var{length} and @var{data} give the initialization
2051 vector (@acronym{IV}).
2052 @end deffn
2053
2054 @deffn Macro GCM_UPDATE (@var{ctx}, @var{length}, @var{data})
2055 Simpler way to call @code{gcm_update}. First argument is a context
2056 struct as defined by @code{GCM_CTX}
2057 @end deffn
2058
2059 @deffn Macro GCM_ENCRYPT (@var{ctx}, @var{encrypt}, @var{length}, @var{dst}, @var{src})
2060 @deffnx Macro GCM_DECRYPT (@var{ctx}, @var{encrypt}, @var{length}, @var{dst}, @var{src})
2061 @deffnx Macro GCM_DIGEST (@var{ctx}, @var{encrypt}, @var{length}, @var{digest})
2062 Simpler way to call @code{gcm_encrypt}, @code{gcm_decrypt} or
2063 @code{gcm_digest}. First argument is a context struct as defined by
2064 @code{GCM_CTX}. Second argument, @var{encrypt}, is a pointer to the
2065 encryption function of the underlying cipher.
2066 @end deffn
2067
2068 @subsubsection @acronym{GCM}-@acronym{AES} interface
2069
2070 The following functions implement the common case of @acronym{GCM} using
2071 @acronym{AES} as the underlying cipher.
2072
2073 @deftp {Context struct} {struct gcm_aes_ctx}
2074 The context struct, defined using @code{GCM_CTX}.
2075 @end deftp
2076
2077 @deftypefun void gcm_aes_set_key (struct gcm_aes_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
2078 Initializes @var{ctx} using the given key. All valid @acronym{AES} key
2079 sizes can be used.
2080 @end deftypefun
2081
2082 @deftypefun void gcm_aes_set_iv (struct gcm_aes_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{iv})
2083 Initializes the per-message state, using the given @acronym{IV}.
2084 @end deftypefun
2085
2086 @deftypefun void gcm_aes_update (struct gcm_aes_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
2087 Provides associated data to be authenticated. If used, must be called
2088 before @code{gcm_aes_encrypt} or @code{gcm_aes_decrypt}. All but the last call
2089 for each message @emph{must} use a length that is a multiple of the
2090 block size.
2091 @end deftypefun
2092
2093 @deftypefun void gcm_aes_encrypt (struct gcm_aes_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2094 @deftypefunx void gcm_aes_decrypt (struct gcm_aes_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2095 Encrypts or decrypts the data of a message. All but the last call for
2096 each message @emph{must} use a length that is a multiple of the block
2097 size.
2098
2099 @end deftypefun
2100
2101 @deftypefun void gcm_aes_digest (struct gcm_aes_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
2102 Extracts the message digest (also known ``authentication tag''). This is
2103 the final operation when processing a message. @var{length} is usually
2104 equal to @code{GCM_BLOCK_SIZE}, but if you provide a smaller value,
2105 only the first @var{length} octets of the digest are written.
2106 @end deftypefun
2107
2108
2109
2110 @node Keyed hash functions, Key derivation functions, Cipher modes, Reference
2111 @comment  node-name,  next,  previous,  up
2112 @section Keyed Hash Functions
2113
2114 @cindex Keyed Hash Function
2115 @cindex Message Authentication Code
2116 @cindex MAC
2117
2118 A @dfn{keyed hash function}, or @dfn{Message Authentication Code}
2119 (@acronym{MAC}) is a function that takes a key and a message, and
2120 produces fixed size @acronym{MAC}. It should be hard to compute a
2121 message and a matching @acronym{MAC} without knowledge of the key. It
2122 should also be hard to compute the key given only messages and
2123 corresponding @acronym{MAC}s.
2124
2125 Keyed hash functions are useful primarily for message authentication,
2126 when Alice and Bob shares a secret: The sender, Alice, computes the
2127 @acronym{MAC} and attaches it to the message. The receiver, Bob, also computes
2128 the @acronym{MAC} of the message, using the same key, and compares that
2129 to Alice's value. If they match, Bob can be assured that
2130 the message has not been modified on its way from Alice.
2131
2132 However, unlike digital signatures, this assurance is not transferable.
2133 Bob can't show the message and the @acronym{MAC} to a third party and
2134 prove that Alice sent that message. Not even if he gives away the key to
2135 the third party. The reason is that the @emph{same} key is used on both
2136 sides, and anyone knowing the key can create a correct @acronym{MAC} for
2137 any message. If Bob believes that only he and Alice knows the key, and
2138 he knows that he didn't attach a @acronym{MAC} to a particular message,
2139 he knows it must be Alice who did it. However, the third party can't
2140 distinguish between a @acronym{MAC} created by Alice and one created by
2141 Bob.
2142
2143 Keyed hash functions are typically a lot faster than digital signatures
2144 as well.
2145
2146 @subsection @acronym{HMAC}
2147 @cindex HMAC
2148
2149 One can build keyed hash functions from ordinary hash functions. Older
2150 constructions simply concatenate secret key and message and hashes that, but
2151 such constructions have weaknesses. A better construction is
2152 @acronym{HMAC}, described in @cite{RFC 2104}.
2153
2154 For an underlying hash function @code{H}, with digest size @code{l} and
2155 internal block size @code{b}, @acronym{HMAC-H} is constructed as
2156 follows: From a given key @code{k}, two distinct subkeys @code{k_i} and
2157 @code{k_o} are constructed, both of length @code{b}. The
2158 @acronym{HMAC-H} of a message @code{m} is then computed as @code{H(k_o |
2159 H(k_i | m))}, where @code{|} denotes string concatenation.
2160
2161 @acronym{HMAC} keys can be of any length, but it is recommended to use
2162 keys of length @code{l}, the digest size of the underlying hash function
2163 @code{H}. Keys that are longer than @code{b} are shortened to length
2164 @code{l} by hashing with @code{H}, so arbitrarily long keys aren't
2165 very useful. 
2166
2167 Nettle's @acronym{HMAC} functions are defined in @file{<nettle/hmac.h>}.
2168 There are abstract functions that use a pointer to a @code{struct
2169 nettle_hash} to represent the underlying hash function and @code{void *}
2170 pointers that point to three different context structs for that hash
2171 function. There are also concrete functions for @acronym{HMAC-MD5},
2172 @acronym{HMAC-RIPEMD160} @acronym{HMAC-SHA1}, @acronym{HMAC-SHA256}, and
2173 @acronym{HMAC-SHA512}. First, the abstract functions:
2174
2175 @deftypefun void hmac_set_key (void *@var{outer}, void *@var{inner}, void *@var{state}, const struct nettle_hash *@var{H}, unsigned @var{length}, const uint8_t *@var{key})
2176 Initializes the three context structs from the key. The @var{outer} and
2177 @var{inner} contexts corresponds to the subkeys @code{k_o} and
2178 @code{k_i}. @var{state} is used for hashing the message, and is
2179 initialized as a copy of the @var{inner} context.
2180 @end deftypefun
2181
2182 @deftypefun void hmac_update (void *@var{state}, const struct nettle_hash *@var{H}, unsigned @var{length}, const uint8_t *@var{data})
2183 This function is called zero or more times to process the message.
2184 Actually, @code{hmac_update(state, H, length, data)} is equivalent to
2185 @code{H->update(state, length, data)}, so if you wish you can use the
2186 ordinary update function of the underlying hash function instead.
2187 @end deftypefun
2188
2189 @deftypefun void hmac_digest (const void *@var{outer}, const void *@var{inner}, void *@var{state}, const struct nettle_hash *@var{H}, unsigned @var{length}, uint8_t *@var{digest})
2190 Extracts the @acronym{MAC} of the message, writing it to @var{digest}.
2191 @var{outer} and @var{inner} are not modified. @var{length} is usually
2192 equal to @code{H->digest_size}, but if you provide a smaller value,
2193 only the first @var{length} octets of the @acronym{MAC} are written.
2194
2195 This function also resets the @var{state} context so that you can start
2196 over processing a new message (with the same key).
2197 @end deftypefun
2198
2199 Like for @acronym{CBC}, there are some macros to help use these
2200 functions correctly.
2201
2202 @deffn Macro HMAC_CTX (@var{type})
2203 Expands to
2204 @example
2205 @{
2206    type outer;
2207    type inner;
2208    type state;
2209 @}
2210 @end example
2211 @end deffn
2212
2213 It can be used to define a @acronym{HMAC} context struct, either
2214 directly,
2215
2216 @example
2217 struct HMAC_CTX(struct md5_ctx) ctx;
2218 @end example
2219
2220 or to give it a struct tag,
2221
2222 @example
2223 struct hmac_md5_ctx HMAC_CTX (struct md5_ctx);
2224 @end example
2225
2226 @deffn Macro HMAC_SET_KEY (@var{ctx}, @var{H}, @var{length}, @var{key})
2227 @var{ctx} is a pointer to a context struct as defined by
2228 @code{HMAC_CTX}, @var{H} is a pointer to a @code{const struct
2229 nettle_hash} describing the underlying hash function (so it must match
2230 the type of the components of @var{ctx}). The last two arguments specify
2231 the secret key.
2232 @end deffn
2233
2234 @deffn Macro HMAC_DIGEST (@var{ctx}, @var{H}, @var{length}, @var{digest})
2235 @var{ctx} is a pointer to a context struct as defined by
2236 @code{HMAC_CTX}, @var{H} is a pointer to a @code{const struct
2237 nettle_hash} describing the underlying hash function. The last two
2238 arguments specify where the digest is written.
2239 @end deffn
2240
2241 Note that there is no @code{HMAC_UPDATE} macro; simply call
2242 @code{hmac_update} function directly, or the update function of the
2243 underlying hash function.
2244
2245 @subsection Concrete @acronym{HMAC} functions
2246 Now we come to the specialized @acronym{HMAC} functions, which are
2247 easier to use than the general @acronym{HMAC} functions.
2248
2249 @subsubsection @acronym{HMAC-MD5}
2250
2251 @deftp {Context struct} {struct hmac_md5_ctx}
2252 @end deftp
2253
2254 @deftypefun void hmac_md5_set_key (struct hmac_md5_ctx *@var{ctx}, unsigned @var{key_length}, const uint8_t *@var{key})
2255 Initializes the context with the key.
2256 @end deftypefun
2257
2258 @deftypefun void hmac_md5_update (struct hmac_md5_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
2259 Process some more data.
2260 @end deftypefun
2261
2262 @deftypefun void hmac_md5_digest (struct hmac_md5_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
2263 Extracts the @acronym{MAC}, writing it to @var{digest}. @var{length} may be smaller than
2264 @code{MD5_DIGEST_SIZE}, in which case only the first @var{length}
2265 octets of the @acronym{MAC} are written.
2266
2267 This function also resets the context for processing new messages, with
2268 the same key.
2269 @end deftypefun
2270
2271 @subsubsection @acronym{HMAC-RIPEMD160}
2272
2273 @deftp {Context struct} {struct hmac_ripemd160_ctx}
2274 @end deftp
2275
2276 @deftypefun void hmac_ripemd160_set_key (struct hmac_ripemd160_ctx *@var{ctx}, unsigned @var{key_length}, const uint8_t *@var{key})
2277 Initializes the context with the key.
2278 @end deftypefun
2279
2280 @deftypefun void hmac_ripemd160_update (struct hmac_ripemd160_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
2281 Process some more data.
2282 @end deftypefun
2283
2284 @deftypefun void hmac_ripemd160_digest (struct hmac_ripemd160_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
2285 Extracts the @acronym{MAC}, writing it to @var{digest}. @var{length} may be smaller than
2286 @code{RIPEMD160_DIGEST_SIZE}, in which case only the first @var{length}
2287 octets of the @acronym{MAC} are written.
2288
2289 This function also resets the context for processing new messages, with
2290 the same key.
2291 @end deftypefun
2292
2293 @subsubsection @acronym{HMAC-SHA1}
2294
2295 @deftp {Context struct} {struct hmac_sha1_ctx}
2296 @end deftp
2297
2298 @deftypefun void hmac_sha1_set_key (struct hmac_sha1_ctx *@var{ctx}, unsigned @var{key_length}, const uint8_t *@var{key})
2299 Initializes the context with the key.
2300 @end deftypefun
2301
2302 @deftypefun void hmac_sha1_update (struct hmac_sha1_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
2303 Process some more data.
2304 @end deftypefun
2305
2306 @deftypefun void hmac_sha1_digest (struct hmac_sha1_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
2307 Extracts the @acronym{MAC}, writing it to @var{digest}. @var{length} may be smaller than
2308 @code{SHA1_DIGEST_SIZE}, in which case only the first @var{length}
2309 octets of the @acronym{MAC} are written.
2310
2311 This function also resets the context for processing new messages, with
2312 the same key.
2313 @end deftypefun
2314
2315
2316 @subsubsection @acronym{HMAC-SHA256}
2317
2318 @deftp {Context struct} {struct hmac_sha256_ctx}
2319 @end deftp
2320
2321 @deftypefun void hmac_sha256_set_key (struct hmac_sha256_ctx *@var{ctx}, unsigned @var{key_length}, const uint8_t *@var{key})
2322 Initializes the context with the key.
2323 @end deftypefun
2324
2325 @deftypefun void hmac_sha256_update (struct hmac_sha256_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
2326 Process some more data.
2327 @end deftypefun
2328
2329 @deftypefun void hmac_sha256_digest (struct hmac_sha256_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
2330 Extracts the @acronym{MAC}, writing it to @var{digest}. @var{length} may be smaller than
2331 @code{SHA256_DIGEST_SIZE}, in which case only the first @var{length}
2332 octets of the @acronym{MAC} are written.
2333
2334 This function also resets the context for processing new messages, with
2335 the same key.
2336 @end deftypefun
2337
2338
2339 @subsubsection @acronym{HMAC-SHA512}
2340
2341 @deftp {Context struct} {struct hmac_sha512_ctx}
2342 @end deftp
2343
2344 @deftypefun void hmac_sha512_set_key (struct hmac_sha512_ctx *@var{ctx}, unsigned @var{key_length}, const uint8_t *@var{key})
2345 Initializes the context with the key.
2346 @end deftypefun
2347
2348 @deftypefun void hmac_sha512_update (struct hmac_sha512_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
2349 Process some more data.
2350 @end deftypefun
2351
2352 @deftypefun void hmac_sha512_digest (struct hmac_sha512_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
2353 Extracts the @acronym{MAC}, writing it to @var{digest}. @var{length} may be smaller than
2354 @code{SHA512_DIGEST_SIZE}, in which case only the first @var{length}
2355 octets of the @acronym{MAC} are written.
2356
2357 This function also resets the context for processing new messages, with
2358 the same key.
2359 @end deftypefun
2360
2361 @subsection @acronym{UMAC}
2362 @cindex UMAC
2363
2364 @acronym{UMAC} is a message authentication code based on universal
2365 hashing, and designed for high performance on modern processors (in
2366 contrast to GCM, @xref{GCM}, which is designed primarily for hardware
2367 performance). On processors with good integer multiplication
2368 performance, it can be 10 times faster than SHA256 and SHA512.
2369 @acronym{UMAC} is specified in @cite{RFC 4418}.
2370
2371 The secret key is always 128 bits (16 octets). The key is used as an
2372 encryption key for the @acronym{AES} block cipher. This cipher is used
2373 in counter mode to generate various internal subkeys needed in
2374 @acronym{UMAC}. Messages are of arbitrary size, and for each message,
2375 @acronym{UMAC} also needs a unique nonce. Nonce values must not be
2376 reused for two messages with the same key, but they need not be kept
2377 secret.
2378
2379 The nonce must be at least one octet, and at most 16; nonces shorter
2380 than 16 octets are zero-padded. Nettle's implementation of
2381 @acronym{UMAC} increments the nonce for automatically each message, so
2382 explicitly setting the nonce for each message is optional. This
2383 auto-increment uses network byte order and it takes the length of the
2384 nonce into acount. E.g., if the initial nonce is ``abc'' (3 octets),
2385 this value is zero-padded to 16 octets for the first message. For the
2386 next message, the nonce is incremented to ``abd'', and this incremented
2387 value is zero-padded to 16 octets.
2388
2389 @acronym{UMAC} is defined in four variants, for different output sizes:
2390 32 bits (4 octest), 64 bits (8 octets), 96 bits (12 octets) and 128 bits
2391 (16 octets), corresponding to different tradeoffs between speed and
2392 security. Using a shorter output size sometimes (but not always!) gives
2393 the same result as using a longer output size and truncating the result.
2394 So it is important to use the right variant. For consistency with other
2395 hash and @acronym{MAC} functions, Nettle's @code{_digest} functions for
2396 @acronym{UMAC} accept a length parameter so that the output can be
2397 truncated to any desired size, but it is recommended to stick to the
2398 specified output size and select the @acronym{umac} variant
2399 corresponding to the desired size.
2400
2401 The internal block size of @acronym{UMAC} is 1024 octets, and it also
2402 generates more than 1024 bytes of subkeys. This makes the size of the
2403 context struct a bit larger than other hash functions and @acronym{MAC}
2404 algorithms in Nettle.
2405
2406 Nettle defines @acronym{UMAC} in @file{<nettle/umac.h>}.
2407
2408 @deftp {Context struct} {struct umac32_ctx}
2409 @deftpx {Context struct} {struct umac64_ctx}
2410 @deftpx {Context struct} {struct umac96_ctx}
2411 @deftpx {Context struct} {struct umac128_ctx}
2412 Each @acronym{UMAC} variant uses its own context struct.
2413 @end deftp
2414
2415 @defvr Constant UMAC_KEY_SIZE
2416 The UMAC key size, 16.
2417 @end defvr
2418 @defvr Constant UMAC32_DIGEST_SIZE
2419 The size of an UMAC32 digest, 4.
2420 @end defvr
2421 @defvr Constant UMAC64_DIGEST_SIZE
2422 The size of an UMAC64 digest, 8.
2423 @end defvr
2424 @defvr Constant UMAC96_DIGEST_SIZE
2425 The size of an UMAC96 digest, 12.
2426 @end defvr
2427 @defvr Constant UMAC128_DIGEST_SIZE
2428 The size of an UMAC128 digest, 16.
2429 @end defvr
2430 @defvr Constant UMAC128_DATA_SIZE
2431 The internal block size of UMAC.
2432 @end defvr
2433
2434 @deftypefun void umac32_set_key (struct umac32_ctx *@var{ctx}, const uint8_t *@var{key})
2435 @deftypefunx void umac64_set_key (struct umac64_ctx *@var{ctx}, const uint8_t *@var{key})
2436 @deftypefunx void umac96_set_key (struct umac96_ctx *@var{ctx}, const uint8_t *@var{key})
2437 @deftypefunx void umac128_set_key (struct umac128_ctx *@var{ctx}, const uint8_t *@var{key})
2438 These functions initialize the @acronym{UMAC} context struct. They also
2439 initialize the nonce to zero (with length 16, for auto-increment).
2440 @end deftypefun
2441
2442 @deftypefun void umac32_set_nonce (struct umac32_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{nonce})
2443 @deftypefunx void umac64_set_nonce (struct umac64_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{nonce})
2444 @deftypefunx void umac96_set_nonce (struct umac96_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{nonce})
2445 @deftypefunx void umac128_set_nonce (struct umac128_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{nonce})
2446 Sets the nonce to be used for the next message. In general, nonces
2447 should be set before processing of the message. This is not strictly
2448 required for @acronym{UMAC} (the nonce only affects the final processing
2449 generating the digest), but it is nevertheless recommended that this
2450 function is called @emph{before} the first @code{_update} call for the
2451 message.
2452 @end deftypefun
2453
2454 @deftypefun void umac32_update (struct umac32_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
2455 @deftypefunx void umac64_update (struct umac64_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
2456 @deftypefunx void umac96_update (struct umac96_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
2457 @deftypefunx void umac128_update (struct umac128_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
2458 These functions are called zero or more times to process the message.
2459 @end deftypefun
2460
2461 @deftypefun void umac32_digest (struct umac32_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
2462 @deftypefunx void umac64_digest (struct umac64_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
2463 @deftypefunx void umac96_digest (struct umac96_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
2464 @deftypefunx void umac128_digest (struct umac128_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
2465 Extracts the @acronym{MAC} of the message, writing it to @var{digest}.
2466 @var{length} is usually equal to the specified output size, but if you
2467 provide a smaller value, only the first @var{length} octets of the
2468 @acronym{MAC} are written. These functions reset the context for
2469 processing of a new message with the same key. The nonce is incremented
2470 as described above, the new value is used unless you call the
2471 @code{_set_nonce} function explicitly for each message.
2472 @end deftypefun
2473
2474 @node Key derivation functions, Public-key algorithms, Keyed hash functions, Reference
2475 @comment  node-name,  next,  previous,  up
2476 @section Key derivation Functions
2477
2478 @cindex Key Derivation Function
2479 @cindex Password Based Key Derivation Function
2480 @cindex PKCS #5
2481 @cindex KDF
2482 @cindex PBKDF
2483
2484 A @dfn{key derivation function} (@acronym{KDF}) is a function that from
2485 a given symmetric key derives other symmetric keys.  A sub-class of KDFs
2486 is the @dfn{password-based key derivation functions} (@acronym{PBKDFs}),
2487 which take as input a password or passphrase, and its purpose is
2488 typically to strengthen it and protect against certain pre-computation
2489 attacks by using salting and expensive computation.
2490
2491 @subsection @acronym{PBKDF2}
2492 The most well known PBKDF is the @code{PKCS #5 PBKDF2} described in
2493 @cite{RFC 2898} which uses a pseudo-random function such as
2494 @acronym{HMAC-SHA1}.
2495
2496 Nettle's @acronym{PBKDF2} functions are defined in
2497 @file{<nettle/pbkdf2.h>}.  There is an abstract function that operate on
2498 any PRF implemented via the @code{nettle_hash_update_func},
2499 @code{nettle_hash_digest_func} interfaces.  There is also helper macros
2500 and concrete functions PBKDF2-HMAC-SHA1 and PBKDF2-HMAC-SHA256.  First,
2501 the abstract function:
2502
2503 @deftypefun void pbkdf2 (void *mac_ctx, nettle_hash_update_func *update, nettle_hash_digest_func *digest, unsigned digest_size, unsigned iterations, unsigned salt_length, const uint8_t *salt, unsigned length, uint8_t *dst)
2504 Derive symmetric key from a password according to PKCS #5 PBKDF2.  The
2505 PRF is assumed to have been initialized and this function will call the
2506 @var{update} and @var{digest} functions passing the @var{mac_ctx}
2507 context parameter as an argument in order to compute digest of size
2508 @var{digest_size}.  Inputs are the salt @var{salt} of length
2509 @var{salt_length}, the iteration counter @var{iterations} (> 0), and the
2510 desired derived output length @var{length}.  The output buffer is
2511 @var{dst} which must have room for at least @var{length} octets.
2512 @end deftypefun
2513
2514 Like for CBC and HMAC, there is a macro to help use the function
2515 correctly.
2516
2517 @deffn Macro PBKDF2 (@var{ctx}, @var{update}, @var{digest}, @var{digest_size}, @var{iterations}, @var{salt_length}, @var{salt}, @var{length}, @var{dst})
2518 @var{ctx} is a pointer to a context struct passed to the @var{update}
2519 and @var{digest} functions (of the types @code{nettle_hash_update_func}
2520 and @code{nettle_hash_digest_func} respectively) to implement the
2521 underlying PRF with digest size of @var{digest_size}.  Inputs are the
2522 salt @var{salt} of length @var{salt_length}, the iteration counter
2523 @var{iterations} (> 0), and the desired derived output length
2524 @var{length}.  The output buffer is @var{dst} which must have room for
2525 at least @var{length} octets.
2526 @end deffn
2527
2528 @subsection Concrete @acronym{PBKDF2} functions
2529 Now we come to the specialized @acronym{PBKDF2} functions, which are
2530 easier to use than the general @acronym{PBKDF2} function.
2531
2532 @subsubsection @acronym{PBKDF2-HMAC-SHA1}
2533
2534 @deftypefun void pbkdf2_hmac_sha1 (unsigned @var{key_length}, const uint8_t *@var{key}, unsigned @var{iterations}, unsigned @var{salt_length}, const uint8_t *@var{salt}, unsigned @var{length}, uint8_t *@var{dst})
2535 PBKDF2 with HMAC-SHA1.  Derive @var{length} bytes of key into buffer
2536 @var{dst} using the password @var{key} of length @var{key_length} and
2537 salt @var{salt} of length @var{salt_length}, with iteration counter
2538 @var{iterations} (> 0).  The output buffer is @var{dst} which must have
2539 room for at least @var{length} octets.
2540 @end deftypefun
2541
2542 @subsubsection @acronym{PBKDF2-HMAC-SHA256}
2543
2544 @deftypefun void pbkdf2_hmac_sha256 (unsigned @var{key_length}, const uint8_t *@var{key}, unsigned @var{iterations}, unsigned @var{salt_length}, const uint8_t *@var{salt}, unsigned @var{length}, uint8_t *@var{dst})
2545 PBKDF2 with HMAC-SHA256.  Derive @var{length} bytes of key into buffer
2546 @var{dst} using the password @var{key} of length @var{key_length} and
2547 salt @var{salt} of length @var{salt_length}, with iteration counter
2548 @var{iterations} (> 0).  The output buffer is @var{dst} which must have
2549 room for at least @var{length} octets.
2550 @end deftypefun
2551
2552 @node Public-key algorithms, Randomness, Key derivation functions, Reference
2553 @comment  node-name,  next,  previous,  up
2554 @section Public-key algorithms
2555
2556 Nettle uses @acronym{GMP}, the GNU bignum library, for all calculations
2557 with large numbers. In order to use the public-key features of Nettle,
2558 you must install @acronym{GMP}, at least version 3.0, before compiling
2559 Nettle, and you need to link your programs with @code{-lhogweed -lnettle
2560 -lgmp}.
2561
2562 The concept of @dfn{Public-key} encryption and digital signatures was
2563 discovered by Whitfield Diffie and Martin E. Hellman and described in a
2564 paper 1976. In traditional, ``symmetric'', cryptography, sender and
2565 receiver share the same keys, and these keys must be distributed in a
2566 secure way. And if there are many users or entities that need to
2567 communicate, each @emph{pair} needs a shared secret key known by nobody
2568 else.
2569
2570 @cindex Public Key Cryptography
2571 @cindex One-way function
2572
2573 Public-key cryptography uses trapdoor one-way functions. A
2574 @dfn{one-way function} is a function @code{F} such that it is easy to
2575 compute the value @code{F(x)} for any @code{x}, but given a value
2576 @code{y}, it is hard to compute a corresponding @code{x} such that
2577 @code{y = F(x)}. Two examples are cryptographic hash functions, and
2578 exponentiation in certain groups.
2579
2580 A @dfn{trapdoor one-way function} is a function @code{F} that is
2581 one-way, unless one knows some secret information about @code{F}. If one
2582 knows the secret, it is easy to compute both @code{F} and it's inverse.
2583 If this sounds strange, look at the @acronym{RSA} example below.
2584
2585 Two important uses for one-way functions with trapdoors are public-key
2586 encryption, and digital signatures. The public-key encryption functions
2587 in Nettle are not yet documented; the rest of this chapter is about
2588 digital signatures.
2589
2590 To use a digital signature algorithm, one must first create a
2591 @dfn{key-pair}: A public key and a corresponding private key. The private
2592 key is used to sign messages, while the public key is used for verifying
2593 that that signatures and messages match. Some care must be taken when
2594 distributing the public key; it need not be kept secret, but if a bad
2595 guy is able to replace it (in transit, or in some user's list of known
2596 public keys), bad things may happen.
2597
2598 There are two operations one can do with the keys. The signature
2599 operation takes a message and a private key, and creates a signature for
2600 the message. A signature is some string of bits, usually at most a few
2601 thousand bits or a few hundred octets. Unlike paper-and-ink signatures,
2602 the digital signature depends on the message, so one can't cut it out of
2603 context and glue it to a different message.
2604
2605 The verification operation takes a public key, a message, and a string
2606 that is claimed to be a signature on the message, and returns true or
2607 false. If it returns true, that means that the three input values
2608 matched, and the verifier can be sure that someone went through with the
2609 signature operation on that very message, and that the ``someone'' also
2610 knows the private key corresponding to the public key.
2611
2612 The desired properties of a digital signature algorithm are as follows:
2613 Given the public key and pairs of messages and valid signatures on them,
2614 it should be hard to compute the private key, and it should also be hard
2615 to create a new message and signature that is accepted by the
2616 verification operation.
2617
2618 Besides signing meaningful messages, digital signatures can be used for
2619 authorization. A server can be configured with a public key, such that
2620 any client that connects to the service is given a random nonce message.
2621 If the server gets a reply with a correct signature matching the nonce
2622 message and the configured public key, the client is granted access. So
2623 the configuration of the server can be understood as ``grant access to
2624 whoever knows the private key corresponding to this particular public
2625 key, and to no others''.
2626
2627
2628 @menu
2629 * RSA::                         The RSA public key algorithm.
2630 * DSA::                         The DSA digital signature algorithm.
2631 * Elliptic curves::             Elliptic curves and ECDSA
2632 @end menu
2633
2634 @node RSA, DSA, Public-key algorithms, Public-key algorithms
2635 @comment  node-name,  next,  previous,  up
2636 @subsection @acronym{RSA}
2637
2638 The @acronym{RSA} algorithm was the first practical digital signature
2639 algorithm that was constructed. It was described 1978 in a paper by
2640 Ronald Rivest, Adi Shamir and L.M. Adleman, and the technique was also
2641 patented in the @acronym{USA} in 1983. The patent expired on September 20, 2000, and since
2642 that day, @acronym{RSA} can be used freely, even in the @acronym{USA}.
2643
2644 It's remarkably simple to describe the trapdoor function behind
2645 @acronym{RSA}. The ``one-way''-function used is
2646
2647 @example
2648 F(x) = x^e mod n
2649 @end example
2650
2651 I.e. raise x to the @code{e}'th power, while discarding all multiples of
2652 @code{n}. The pair of numbers @code{n} and @code{e} is the public key.
2653 @code{e} can be quite small, even @code{e = 3} has been used, although
2654 slightly larger numbers are recommended. @code{n} should be about 1000
2655 bits or larger.
2656
2657 If @code{n} is large enough, and properly chosen, the inverse of F,
2658 the computation of @code{e}'th roots modulo @code{n}, is very difficult.
2659 But, where's the trapdoor?
2660
2661 Let's first look at how @acronym{RSA} key-pairs are generated. First
2662 @code{n} is chosen as the product of two large prime numbers @code{p}
2663 and @code{q} of roughly the same size (so if @code{n} is 1000 bits,
2664 @code{p} and @code{q} are about 500 bits each). One also computes the
2665 number @code{phi = (p-1)(q-1)}, in mathematical speak, @code{phi} is the
2666 order of the multiplicative group of integers modulo n.
2667
2668 Next, @code{e} is chosen. It must have no factors in common with @code{phi} (in
2669 particular, it must be odd), but can otherwise be chosen more or less
2670 randomly. @code{e = 65537} is a popular choice, because it makes raising
2671 to the @code{e}'th power particularly efficient, and being prime, it
2672 usually has no factors common with @code{phi}.
2673
2674 Finally, a number @code{d}, @code{d < n} is computed such that @code{e d
2675 mod phi = 1}. It can be shown that such a number exists (this is why
2676 @code{e} and @code{phi} must have no common factors), and that for all x,
2677
2678 @example
2679 (x^e)^d mod n = x^(ed) mod n = (x^d)^e mod n = x
2680 @end example
2681
2682 Using Euclid's algorithm, @code{d} can be computed quite easily from
2683 @code{phi} and @code{e}. But it is still hard to get @code{d} without
2684 knowing @code{phi}, which depends on the factorization of @code{n}.
2685
2686 So @code{d} is the trapdoor, if we know @code{d} and @code{y = F(x)}, we can
2687 recover x as @code{y^d mod n}. @code{d} is also the private half of
2688 the @acronym{RSA} key-pair.
2689
2690 The most common signature operation for @acronym{RSA} is defined in
2691 @cite{PKCS#1}, a specification by RSA Laboratories. The message to be
2692 signed is first hashed using a cryptographic hash function, e.g.
2693 @acronym{MD5} or @acronym{SHA1}. Next, some padding, the @acronym{ASN.1}
2694 ``Algorithm Identifier'' for the hash function, and the message digest
2695 itself, are concatenated and converted to a number @code{x}. The
2696 signature is computed from @code{x} and the private key as @code{s = x^d
2697 mod n}@footnote{Actually, the computation is not done like this, it is
2698 done more efficiently using @code{p}, @code{q} and the Chinese remainder
2699 theorem (@acronym{CRT}). But the result is the same.}. The signature, @code{s} is a
2700 number of about the same size of @code{n}, and it usually encoded as a
2701 sequence of octets, most significant octet first.
2702
2703 The verification operation is straight-forward, @code{x} is computed
2704 from the message in the same way as above. Then @code{s^e mod n} is
2705 computed, the operation returns true if and only if the result equals
2706 @code{x}.
2707
2708 @subsection Nettle's @acronym{RSA} support
2709
2710 Nettle represents @acronym{RSA} keys using two structures that contain
2711 large numbers (of type @code{mpz_t}).
2712
2713 @deftp {Context struct} {rsa_public_key} size n e
2714 @code{size} is the size, in octets, of the modulo, and is used internally.
2715 @code{n} and @code{e} is the public key.
2716 @end deftp
2717
2718 @deftp {Context struct} {rsa_private_key} size d p q a b c
2719 @code{size} is the size, in octets, of the modulo, and is used internally.
2720 @code{d} is the secret exponent, but it is not actually used when
2721 signing. Instead, the factors @code{p} and @code{q}, and the parameters
2722 @code{a}, @code{b} and @code{c} are used. They are computed from @code{p},
2723 @code{q} and @code{e} such that @code{a e mod (p - 1) = 1, b e mod (q -
2724 1) = 1, c q mod p = 1}.
2725 @end deftp
2726
2727 Before use, these structs must be initialized by calling one of
2728
2729 @deftypefun void rsa_public_key_init (struct rsa_public_key *@var{pub})
2730 @deftypefunx void rsa_private_key_init (struct rsa_private_key *@var{key})
2731 Calls @code{mpz_init} on all numbers in the key struct.
2732 @end deftypefun
2733
2734 and when finished with them, the space for the numbers must be
2735 deallocated by calling one of
2736
2737 @deftypefun void rsa_public_key_clear (struct rsa_public_key *@var{pub})
2738 @deftypefunx void rsa_private_key_clear (struct rsa_private_key *@var{key})
2739 Calls @code{mpz_clear} on all numbers in the key struct.
2740 @end deftypefun
2741
2742 In general, Nettle's @acronym{RSA} functions deviates from Nettle's ``no
2743 memory allocation''-policy. Space for all the numbers, both in the key structs
2744 above, and temporaries, are allocated dynamically. For information on how
2745 to customize allocation, see
2746 @xref{Custom Allocation,,GMP Allocation,gmp, GMP Manual}.
2747
2748 When you have assigned values to the attributes of a key, you must call
2749
2750 @deftypefun int rsa_public_key_prepare (struct rsa_public_key *@var{pub})
2751 @deftypefunx int rsa_private_key_prepare (struct rsa_private_key *@var{key})
2752 Computes the octet size of the key (stored in the @code{size} attribute,
2753 and may also do other basic sanity checks. Returns one if successful, or
2754 zero if the key can't be used, for instance if the modulo is smaller
2755 than the minimum size needed for @acronym{RSA} operations specified by PKCS#1.
2756 @end deftypefun
2757
2758 Before signing or verifying a message, you first hash it with the
2759 appropriate hash function. You pass the hash function's context struct
2760 to the @acronym{RSA} signature function, and it will extract the message
2761 digest and do the rest of the work. There are also alternative functions
2762 that take the hash digest as argument. 
2763
2764 There is currently no support for using SHA224 or SHA384 with
2765 @acronym{RSA} signatures, since there's no gain in either computation
2766 time nor message size compared to using SHA256 and SHA512, respectively.
2767
2768 Creation and verification of signatures is done with the following functions:
2769
2770 @deftypefun int rsa_md5_sign (const struct rsa_private_key *@var{key}, struct md5_ctx *@var{hash}, mpz_t @var{signature})
2771 @deftypefunx int rsa_sha1_sign (const struct rsa_private_key *@var{key}, struct sha1_ctx *@var{hash}, mpz_t @var{signature})
2772 @deftypefunx int rsa_sha256_sign (const struct rsa_private_key *@var{key}, struct sha256_ctx *@var{hash}, mpz_t @var{signature})
2773 @deftypefunx int rsa_sha512_sign (const struct rsa_private_key *@var{key}, struct sha512_ctx *@var{hash}, mpz_t @var{signature})
2774 The signature is stored in @var{signature} (which must have been
2775 @code{mpz_init}'ed earlier). The hash context is reset so that it can be
2776 used for new messages. Returns one on success, or zero on failure.
2777 Signing fails if the key is too small for the given hash size, e.g.,
2778 it's not possible to create a signature using SHA512 and a 512-bit
2779 @acronym{RSA} key.
2780 @end deftypefun
2781
2782 @deftypefun int rsa_md5_sign_digest (const struct rsa_private_key *@var{key}, const uint8_t *@var{digest}, mpz_t @var{signature})
2783 @deftypefunx int rsa_sha1_sign_digest (const struct rsa_private_key *@var{key}, const uint8_t *@var{digest}, mpz_t @var{signature});
2784 @deftypefunx int rsa_sha256_sign_digest (const struct rsa_private_key *@var{key}, const uint8_t *@var{digest}, mpz_t @var{signature});
2785 @deftypefunx int rsa_sha512_sign_digest (const struct rsa_private_key *@var{key}, const uint8_t *@var{digest}, mpz_t @var{signature});
2786 Creates a signature from the given hash digest. @var{digest} should
2787 point to a digest of size @code{MD5_DIGEST_SIZE},
2788 @code{SHA1_DIGEST_SIZE}, or @code{SHA256_DIGEST_SIZE}, respectively. The
2789 signature is stored in @var{signature} (which must have been
2790 @code{mpz_init}:ed earlier). Returns one on success, or zero on failure.
2791 @end deftypefun
2792
2793 @deftypefun int rsa_md5_verify (const struct rsa_public_key *@var{key}, struct md5_ctx *@var{hash}, const mpz_t @var{signature})
2794 @deftypefunx int rsa_sha1_verify (const struct rsa_public_key *@var{key}, struct sha1_ctx *@var{hash}, const mpz_t @var{signature})
2795 @deftypefunx int rsa_sha256_verify (const struct rsa_public_key *@var{key}, struct sha256_ctx *@var{hash}, const mpz_t @var{signature})
2796 @deftypefunx int rsa_sha512_verify (const struct rsa_public_key *@var{key}, struct sha512_ctx *@var{hash}, const mpz_t @var{signature})
2797 Returns 1 if the signature is valid, or 0 if it isn't. In either case,
2798 the hash context is reset so that it can be used for new messages.
2799 @end deftypefun
2800
2801 @deftypefun int rsa_md5_verify_digest (const struct rsa_public_key *@var{key}, const uint8_t *@var{digest}, const mpz_t @var{signature})
2802 @deftypefunx int rsa_sha1_verify_digest (const struct rsa_public_key *@var{key}, const uint8_t *@var{digest}, const mpz_t @var{signature})
2803 @deftypefunx int rsa_sha256_verify_digest (const struct rsa_public_key *@var{key}, const uint8_t *@var{digest}, const mpz_t @var{signature})
2804 @deftypefunx int rsa_sha512_verify_digest (const struct rsa_public_key *@var{key}, const uint8_t *@var{digest}, const mpz_t @var{signature})
2805 Returns 1 if the signature is valid, or 0 if it isn't. @var{digest} should
2806 point to a digest of size @code{MD5_DIGEST_SIZE},
2807 @code{SHA1_DIGEST_SIZE}, or @code{SHA256_DIGEST_SIZE}, respectively.
2808 @end deftypefun
2809
2810 If you need to use the @acronym{RSA} trapdoor, the private key, in a way
2811 that isn't supported by the above functions Nettle also includes a
2812 function that computes @code{x^d mod n} and nothing more, using the
2813 @acronym{CRT} optimization.
2814
2815 @deftypefun void rsa_compute_root (struct rsa_private_key *@var{key}, mpz_t @var{x}, const mpz_t @var{m})
2816 Computes @code{x = m^d}, efficiently.
2817 @end deftypefun
2818
2819 At last, how do you create new keys?
2820
2821 @deftypefun int rsa_generate_keypair (struct rsa_public_key *@var{pub}, struct rsa_private_key *@var{key}, void *@var{random_ctx}, nettle_random_func @var{random}, void *@var{progress_ctx}, nettle_progress_func @var{progress}, unsigned @var{n_size}, unsigned @var{e_size});
2822 There are lots of parameters. @var{pub} and @var{key} is where the
2823 resulting key pair is stored. The structs should be initialized, but you
2824 don't need to call @code{rsa_public_key_prepare} or
2825 @code{rsa_private_key_prepare} after key generation.
2826
2827 @var{random_ctx} and @var{random} is a randomness generator.
2828 @code{random(random_ctx, length, dst)} should generate @code{length}
2829 random octets and store them at @code{dst}. For advice, see
2830 @xref{Randomness}.
2831
2832 @var{progress} and @var{progress_ctx} can be used to get callbacks
2833 during the key generation process, in order to uphold an illusion of
2834 progress. @var{progress} can be NULL, in that case there are no
2835 callbacks.
2836
2837 @var{size_n} is the desired size of the modulo, in bits. If @var{size_e}
2838 is non-zero, it is the desired size of the public exponent and a random
2839 exponent of that size is selected. But if @var{e_size} is zero, it is
2840 assumed that the caller has already chosen a value for @code{e}, and
2841 stored it in @var{pub}.
2842 Returns one on success, and zero on failure. The function can fail for
2843 example if if @var{n_size} is too small, or if @var{e_size} is zero and
2844 @code{pub->e} is an even number.
2845 @end deftypefun
2846
2847 @node DSA, Elliptic curves, RSA, Public-key algorithms
2848 @comment  node-name,  next,  previous,  up
2849 @subsection @acronym{DSA}
2850
2851 The @acronym{DSA} digital signature algorithm is more complex than
2852 @acronym{RSA}. It was specified during the early 1990s, and in 1994 NIST
2853 published @acronym{FIPS} 186 which is the authoritative specification.
2854 Sometimes @acronym{DSA} is referred to using the acronym @acronym{DSS},
2855 for Digital Signature Standard. The most recent revision of the
2856 specification, FIPS186-3, was issued in 2009, and it adds support for
2857 larger hash functions than @acronym{sha1}.
2858
2859 For @acronym{DSA}, the underlying mathematical problem is the
2860 computation of discrete logarithms. The public key consists of a large
2861 prime @code{p}, a small prime @code{q} which is a factor of @code{p-1},
2862 a number @code{g} which generates a subgroup of order @code{q} modulo
2863 @code{p}, and an element @code{y} in that subgroup.
2864
2865 In the original @acronym{DSA}, the size of @code{q} is fixed to 160
2866 bits, to match with the @acronym{SHA1} hash algorithm. The size of
2867 @code{p} is in principle unlimited, but the
2868 standard specifies only nine specific sizes: @code{512 + l*64}, where
2869 @code{l} is between 0 and 8. Thus, the maximum size of @code{p} is 1024
2870 bits, and sizes less than 1024 bits are considered obsolete and not
2871 secure.
2872
2873 The subgroup requirement means that if you compute 
2874
2875 @example
2876 g^t mod p
2877 @end example
2878
2879 for all possible integers @code{t}, you will get precisely @code{q}
2880 distinct values.
2881
2882 The private key is a secret exponent @code{x}, such that
2883
2884 @example
2885 g^x = y mod p
2886 @end example
2887
2888 In mathematical speak, @code{x} is the @dfn{discrete logarithm} of
2889 @code{y} mod @code{p}, with respect to the generator @code{g}. The size
2890 of @code{x} will also be about the same size as @code{q}. The security of the
2891 @acronym{DSA} algorithm relies on the difficulty of the discrete
2892 logarithm problem. Current algorithms to compute discrete logarithms in
2893 this setting, and hence crack @acronym{DSA}, are of two types. The first
2894 type works directly in the (multiplicative) group of integers mod
2895 @code{p}. The best known algorithm of this type is the Number Field
2896 Sieve, and it's complexity is similar to the complexity of factoring
2897 numbers of the same size as @code{p}. The other type works in the
2898 smaller @code{q}-sized subgroup generated by @code{g}, which has a more
2899 difficult group structure. One good algorithm is Pollard-rho, which has
2900 complexity @code{sqrt(q)}.
2901
2902 The important point is that security depends on the size of @emph{both}
2903 @code{p} and @code{q}, and they should be chosen so that the difficulty
2904 of both discrete logarithm methods are comparable. Today, the security
2905 margin of the original @acronym{DSA} may be uncomfortably small. Using a
2906 @code{p} of 1024 bits implies that cracking using the number field sieve
2907 is expected to take about the same time as factoring a 1024-bit
2908 @acronym{RSA} modulo, and using a @code{q} of size 160 bits implies
2909 that cracking using Pollard-rho will take roughly @code{2^80} group
2910 operations. With the size of @code{q} fixed, tied to the @acronym{SHA1}
2911 digest size, it may be tempting to increase the size of @code{p} to,
2912 say, 4096 bits. This will provide excellent resistance against attacks
2913 like the number field sieve which works in the large group. But it will
2914 do very little to defend against Pollard-rho attacking the small
2915 subgroup; the attacker is slowed down at most by a single factor of 10
2916 due to the more expensive group operation. And the attacker will surely
2917 choose the latter attack.
2918
2919 The signature generation algorithm is randomized; in order to create a
2920 @acronym{DSA} signature, you need a good source for random numbers
2921 (@pxref{Randomness}). Let us describe the common case of a 160-bit
2922 @code{q}.
2923
2924 To create a signature, one starts with the hash digest of the message,
2925 @code{h}, which is a 160 bit number, and a random number @code{k,
2926 0<k<q}, also 160 bits. Next, one computes 
2927
2928 @example
2929 r = (g^k mod p) mod q
2930 s = k^-1 (h + x r) mod q
2931 @end example
2932
2933 The signature is the pair @code{(r, s)}, two 160 bit numbers. Note the
2934 two different mod operations when computing @code{r}, and the use of the
2935 secret exponent @code{x}.
2936
2937 To verify a signature, one first checks that @code{0 < r,s < q}, and
2938 then one computes backwards,
2939
2940 @example
2941 w = s^-1 mod q
2942 v = (g^(w h) y^(w r) mod p) mod q
2943 @end example
2944
2945 The signature is valid if @code{v = r}. This works out because @code{w =
2946 s^-1 mod q = k (h + x r)^-1 mod q}, so that
2947
2948 @example
2949 g^(w h) y^(w r) = g^(w h) (g^x)^(w r) = g^(w (h + x r)) = g^k 
2950 @end example
2951
2952 When reducing mod @code{q} this yields @code{r}. Note that when
2953 verifying a signature, we don't know either @code{k} or @code{x}: those
2954 numbers are secret.
2955
2956 If you can choose between @acronym{RSA} and @acronym{DSA}, which one is
2957 best? Both are believed to be secure. @acronym{DSA} gained popularity in
2958 the late 1990s, as a patent free alternative to @acronym{RSA}. Now that
2959 the @acronym{RSA} patents have expired, there's no compelling reason to
2960 want to use @acronym{DSA}. Today, the original @acronym{DSA} key size
2961 does not provide a large security margin, and it should probably be
2962 phased out together with @acronym{RSA} keys of 1024 bits. Using the
2963 revised @acronym{DSA} algorithm with a larger hash function, in
2964 particular, @acronym{SHA256}, a 256-bit @code{q}, and @code{p} of size
2965 2048 bits or more, should provide for a more comfortable security
2966 margin, but these variants are not yet in wide use.
2967
2968 @acronym{DSA} signatures are smaller than @acronym{RSA} signatures,
2969 which is important for some specialized applications.
2970
2971 From a practical point of view, @acronym{DSA}'s need for a good
2972 randomness source is a serious disadvantage. If you ever use the same
2973 @code{k} (and @code{r}) for two different message, you leak your private
2974 key.
2975
2976 @subsection Nettle's @acronym{DSA} support
2977
2978 Like for @acronym{RSA}, Nettle represents @acronym{DSA} keys using two
2979 structures, containing values of type @code{mpz_t}. For information on
2980 how to customize allocation, see @xref{Custom Allocation,,GMP
2981 Allocation,gmp, GMP Manual}.
2982
2983 Most of the @acronym{DSA} functions are very similar to the
2984 corresponding @acronym{RSA} functions, but there are a few differences
2985 pointed out below. For a start, there are no functions corresponding to
2986 @code{rsa_public_key_prepare} and @code{rsa_private_key_prepare}.
2987
2988 @deftp {Context struct} {dsa_public_key} p q g y
2989 The public parameters described above.
2990 @end deftp
2991
2992 @deftp {Context struct} {dsa_private_key} x
2993 The private key @code{x}.
2994 @end deftp
2995
2996 Before use, these structs must be initialized by calling one of
2997
2998 @deftypefun void dsa_public_key_init (struct dsa_public_key *@var{pub})
2999 @deftypefunx void dsa_private_key_init (struct dsa_private_key *@var{key})
3000 Calls @code{mpz_init} on all numbers in the key struct.
3001 @end deftypefun
3002
3003 When finished with them, the space for the numbers must be
3004 deallocated by calling one of
3005
3006 @deftypefun void dsa_public_key_clear (struct dsa_public_key *@var{pub})
3007 @deftypefunx void dsa_private_key_clear (struct dsa_private_key *@var{key})
3008 Calls @code{mpz_clear} on all numbers in the key struct.
3009 @end deftypefun
3010
3011 Signatures are represented using the structure below, and need to be
3012 initialized and cleared in the same way as the key structs.
3013
3014 @deftp {Context struct} {dsa_signature} r s
3015 @end deftp
3016
3017 @deftypefun void dsa_signature_init (struct dsa_signature *@var{signature})
3018 @deftypefunx void dsa_signature_clear (struct dsa_signature *@var{signature})
3019 You must call @code{dsa_signature_init} before creating or using a
3020 signature, and call @code{dsa_signature_clear} when you are finished
3021 with it.
3022 @end deftypefun
3023
3024 For signing, you need to provide both the public and the private key
3025 (unlike @acronym{RSA}, where the private key struct includes all
3026 information needed for signing), and a source for random numbers.
3027 Signatures can use the @acronym{SHA1} or the @acronym{SHA256} hash
3028 function, although the implementation of @acronym{DSA} with
3029 @acronym{SHA256} should be considered somewhat experimental due to lack
3030 of official test vectors and interoperability testing.
3031
3032 @deftypefun int dsa_sha1_sign (const struct dsa_public_key *@var{pub}, const struct dsa_private_key *@var{key}, void *@var{random_ctx}, nettle_random_func @var{random}, struct sha1_ctx *@var{hash}, struct dsa_signature *@var{signature})
3033 @deftypefunx int dsa_sha1_sign_digest (const struct dsa_public_key *@var{pub}, const struct dsa_private_key *@var{key}, void *@var{random_ctx}, nettle_random_func @var{random}, const uint8_t *@var{digest}, struct dsa_signature *@var{signature})
3034 @deftypefunx int dsa_sha256_sign (const struct dsa_public_key *@var{pub}, const struct dsa_private_key *@var{key}, void *@var{random_ctx}, nettle_random_func @var{random}, struct sha256_ctx *@var{hash}, struct dsa_signature *@var{signature})
3035 @deftypefunx int dsa_sha256_sign_digest (const struct dsa_public_key *@var{pub}, const struct dsa_private_key *@var{key}, void *@var{random_ctx}, nettle_random_func @var{random}, const uint8_t *@var{digest}, struct dsa_signature *@var{signature})
3036 Creates a signature from the given hash context or digest.
3037 @var{random_ctx} and @var{random} is a randomness generator.
3038 @code{random(random_ctx, length, dst)} should generate @code{length}
3039 random octets and store them at @code{dst}. For advice, see
3040 @xref{Randomness}. Returns one on success, or zero on failure.
3041 Signing fails if the key size and the hash size don't match.
3042 @end deftypefun
3043
3044 Verifying signatures is a little easier, since no randomness generator is
3045 needed. The functions are
3046
3047 @deftypefun int dsa_sha1_verify (const struct dsa_public_key *@var{key}, struct sha1_ctx *@var{hash}, const struct dsa_signature *@var{signature})
3048 @deftypefunx int dsa_sha1_verify_digest (const struct dsa_public_key *@var{key}, const uint8_t *@var{digest}, const struct dsa_signature *@var{signature})
3049 @deftypefunx int dsa_sha256_verify (const struct dsa_public_key *@var{key}, struct sha256_ctx *@var{hash}, const struct dsa_signature *@var{signature})
3050 @deftypefunx int dsa_sha256_verify_digest (const struct dsa_public_key *@var{key}, const uint8_t *@var{digest}, const struct dsa_signature *@var{signature})
3051 Verifies a signature. Returns 1 if the signature is valid, otherwise 0.
3052 @end deftypefun
3053
3054 Key generation uses mostly the same parameters as the corresponding
3055 @acronym{RSA} function.
3056
3057 @deftypefun int dsa_generate_keypair (struct dsa_public_key *@var{pub}, struct dsa_private_key *@var{key}, void *@var{random_ctx}, nettle_random_func @var{random}, void *@var{progress_ctx}, nettle_progress_func @var{progress}, unsigned @var{p_bits}, unsigned @var{q_bits})
3058 @var{pub} and @var{key} is where the resulting key pair is stored. The
3059 structs should be initialized before you call this function. 
3060
3061 @var{random_ctx} and @var{random} is a randomness generator.
3062 @code{random(random_ctx, length, dst)} should generate @code{length}
3063 random octets and store them at @code{dst}. For advice, see
3064 @xref{Randomness}.
3065
3066 @var{progress} and @var{progress_ctx} can be used to get callbacks
3067 during the key generation process, in order to uphold an illusion of
3068 progress. @var{progress} can be NULL, in that case there are no
3069 callbacks.
3070
3071 @var{p_bits} and @var{q_bits} are the desired sizes of @code{p} and
3072 @code{q}. To generate keys that conform to the original @acronym{DSA}
3073 standard, you must use @code{q_bits = 160} and select @var{p_bits} of
3074 the form @code{p_bits = 512 + l*64}, for @code{0 <= l <= 8}, where the
3075 smaller sizes are no longer recommended, so you should most likely stick
3076 to @code{p_bits = 1024}. Non-standard sizes are possible, in particular
3077 @code{p_bits} larger than 1024, although @acronym{DSA} implementations
3078 can not in general be expected to support such keys. Also note that
3079 using very large @var{p_bits}, with @var{q_bits} fixed at 160, doesn't
3080 make much sense, because the security is also limited by the size of the
3081 smaller prime. Using a larger @code{q_bits} requires switching to a
3082 larger hash function. To generate @acronym{DSA} keys for use with
3083 @acronym{SHA256}, use @code{q_bits = 256} and, e.g., @code{p_bits =
3084 2048}.
3085
3086 Returns one on success, and zero on failure. The function will fail if
3087 @var{q_bits} is neither 160 nor 256, or if @var{p_bits} is unreasonably
3088 small.
3089 @end deftypefun
3090
3091 @node Elliptic curves,, DSA, Public-key algorithms
3092 @comment  node-name,  next,  previous,  up
3093 @subsection @acronym{Elliptic curves}
3094
3095 For cryptographic purposes, an elliptic curve is a mathematical group of
3096 points, and computing logarithms in this group is computationally
3097 difficult problem. Nettle uses additive notation for elliptic curve
3098 groups. If @math{P} and @math{Q} are two points, and @math{k} is an
3099 integer, the point sum, @math{P + Q}, and the multiple @math{k P} can be
3100 computed efficiently, but given only two points @math{P} and @math{Q},
3101 finding an integer @math{k} such that @math{Q = k P} is the elliptic
3102 curve discrete logarithm problem.
3103
3104 Nettle supports standard curves which are all of the form @math{y^2 =
3105 x^3 - 3 x + b @pmod{p}}, i.e., the points have coordinates @math{(x,y)},
3106 both considered as integers modulo a specified prime @math{p}. Curves
3107 are represented as a @code{struct ecc_curve}. Supported curves are
3108 declared in @file{<nettle/ecc-curve.h>}, e.g., @code{nettle_secp_256r1}
3109 for a standardized curve using the 256-bit prime @math{p = 2^{256} -
3110 2^{224} + 2^{192} + 2^{96} - 1}. The contents of these structs is not
3111 visible to nettle users. The ``bitsize of the curve'' is used as a
3112 shorthand for the bitsize of the curve's prime @math{p}, e.g., 256 bits
3113 for @code{nettle_secp_256r1}.
3114
3115 @subsubsection Side-channel silence
3116 Nettle's implementation of the elliptic curve operations is intended to
3117 be side-channel silent. The side-channel attacks considered are:
3118
3119 @itemize
3120 @item Timing attacks
3121 If the timing of operations depends on secret values, an attacker
3122 interacting with your system can measure the response time, and infer
3123 information about your secrets, e.g., a private signature key.
3124
3125 @item Attacks using memory caches
3126 Assume you have some secret data on a multi-user system, and that this
3127 data is properly protected so that other users get no direct access to
3128 it. If you have a process operating on the secret data, and this process
3129 does memory accesses depending on the data, e.g, an internal lookup
3130 table in some cryptographic algorithm, an attacker running a separate
3131 process on the same system may use behavior of internal CPU caches to
3132 get information about your secrets.
3133 @end itemize
3134
3135 Nettle's ECC implementation is designed to be @dfn{side-channel silent},
3136 and not leak any information to these attacks. Timing and memory
3137 accesses depend only on the size of the input data and its location in
3138 memory, not on the actual data bits. This implies a performance penalty
3139 in several of the building blocks.
3140
3141 @subsection ECDSA
3142
3143 ECDSA is a variant of the DSA digital signature scheme (@pxref{DSA}),
3144 which works over an elliptic curve group rather than over a (subgroup
3145 of) integers modulo @math{p}. Like DSA, creating a signature requires a unique
3146 random nonce (repeating the nonce with two different messages reveals
3147 the private key, and any leak or bias in the generation of the nonce
3148 also leaks information about the key).
3149
3150 Unlike DSA, signatures are in general not tied to any particular hash
3151 function or even hash size. Any hash function can be used, and the hash
3152 value is truncated or padded as needed to get a size matching the curve
3153 being used. It is recommended to use a strong cryptographic hash
3154 function with digest size close to the bit size of the curve, e.g.,
3155 SHA256 is a reasonable choice when using ECDSA signature over the curve
3156 secp256r1. A protocol or application using ECDSA has to specify which
3157 curve and which hash function to use, or provide some mechanism for
3158 negotiating.
3159
3160 Nettle defines ECDSA in @file{<nettle/ecdsa.h>}. We first need
3161 to define the data types used to represent public and private keys.
3162
3163 @deftp {struct} {struct ecc_point}
3164 Represents a point on an elliptic curve. In particular, it is used to
3165 represent an ECDSA public key.
3166 @end deftp
3167
3168 @deftypefun void ecc_point_init (struct ecc_point *@var{p}, const structecc_curve *@var{ecc})
3169 Initializes @var{p} to represent points on the given curve @var{ecc}.
3170 Allocates storage for the coordinates, using the same allocation
3171 functions as GMP.
3172 @end deftypefun
3173
3174 @deftypefun void ecc_point_clear (struct ecc_point *@var{p})
3175 Deallocate storage.
3176 @end deftypefun
3177
3178 @deftypefun int ecc_point_set (struct ecc_point *@var{p}, const mpz_t @var{x}, const mpz_t @var{y})
3179 Check that the given coordinates represent a point on the curve. If so,
3180 the coordinates are copied and converted to internal representation, and
3181 the function returns 1. Otherwise, it returns 0. Currently, the
3182 infinity point (or zero point, with additive notation) i snot allowed.
3183 @end deftypefun
3184
3185 @deftypefun void ecc_point_get (const struct ecc_point *@var{p}, mpz_t @var{x}, mpz_t @var{y})
3186 Extracts the coordinate of the point @var{p}. The output parameters
3187 @var{x} or @var{y} may be NULL if the caller doesn't want that
3188 coordinate.
3189 @end deftypefun
3190
3191 @deftp {struct} {struct ecc_scalar}
3192 Represents an integer in the range @math{0 < x < group order}, where the
3193 ``group order'' refers to the order of an ECC group. In particular, it
3194 is used to represent an ECDSA private key.
3195 @end deftp
3196
3197 @deftypefun void ecc_scalar_init (struct ecc_scalar *@var{s}, const struct ecc_curve *@var{ecc})
3198 Initializes @var{s} to represent a scalar suitable for the given curve
3199 @var{ecc}. Allocates storage using the same allocation functions as GMP.
3200 @end deftypefun
3201
3202 @deftypefun void ecc_scalar_clear (struct ecc_scalar *@var{s})
3203 Deallocate storage.
3204 @end deftypefun
3205
3206 @deftypefun int ecc_scalar_set (struct ecc_scalar *@var{s}, const mpz_t @var{z})
3207 Check that @var{z} is in the correct range. If so, copies the value to
3208 @var{s} and returns 1, otherwise returns 0.
3209 @end deftypefun
3210
3211 @deftypefun void ecc_scalar_get (const struct ecc_scalar *@var{s}, mpz_t @var{z})
3212 Extracts the scalar, in GMP @code{mpz_t} representation.
3213 @end deftypefun
3214
3215 To create and verify ECDSA signatures, the following functions are used.
3216
3217 @deftypefun void ecdsa_sign (const struct ecc_scalar *@var{key}, void *@var{random_ctx}, nettle_random_func *@var{random}, unsigned @var{digest_length}, const uint8_t *@var{digest}, struct dsa_signature *@var{signature})
3218 Uses the private key @var{key} to create a signature on @var{digest}.
3219 @var{random_ctx} and @var{random} is a randomness generator.
3220 @code{random(random_ctx, length, dst)} should generate @code{length}
3221 random octets and store them at @code{dst}. The signature is stored in
3222 @var{signature}, in the same was as for plain DSA.
3223 @end deftypefun
3224
3225 @deftypefun int ecdsa_verify (const struct ecc_point *@var{pub}, unsigned @var{length}, const uint8_t *@var{digest}, const struct dsa_signature *@var{signature})
3226 Uses the public key @var{pub} to verify that @var{signature} is a valid
3227 signature for the message digest @var{digest} (of @var{length} octets).
3228 Returns 1 if the signature is valid, otherwise 0.
3229 @end deftypefun
3230
3231 Finally, to generation of new an ECDSA key pairs
3232
3233 @deftypefun void ecdsa_generate_keypair (struct ecc_point *@var{pub}, struct ecc_scalar *@var{key}, void *@var{random_ctx}, nettle_random_func *@var{random});
3234 @var{pub} and @var{key} is where the resulting key pair is stored. The
3235 structs should be initialized, for the desired ECC curve, before you call this function.
3236
3237 @var{random_ctx} and @var{random} is a randomness generator.
3238 @code{random(random_ctx, length, dst)} should generate @code{length}
3239 random octets and store them at @code{dst}. For advice, see
3240 @xref{Randomness}.
3241 @end deftypefun
3242
3243 @node Randomness, ASCII encoding, Public-key algorithms, Reference
3244 @comment  node-name,  next,  previous,  up
3245 @section Randomness
3246
3247 @cindex Randomness
3248
3249 A crucial ingredient in many cryptographic contexts is randomness: Let
3250 @code{p} be a random prime, choose a random initialization vector
3251 @code{iv}, a random key @code{k} and a random exponent @code{e}, etc. In
3252 the theories, it is assumed that you have plenty of randomness around.
3253 If this assumption is not true in practice, systems that are otherwise
3254 perfectly secure, can be broken. Randomness has often turned out to be
3255 the weakest link in the chain.
3256
3257 In non-cryptographic applications, such as games as well as scientific
3258 simulation, a good randomness generator usually means a generator that
3259 has good statistical properties, and is seeded by some simple function
3260 of things like the current time, process id, and host name.
3261
3262 However, such a generator is inadequate for cryptography, for at least
3263 two reasons:
3264
3265
3266 @itemize
3267
3268 @item
3269 It's too easy for an attacker to guess the initial seed. Even if it will
3270 take some 2^32 tries before he guesses right, that's far too easy. For
3271 example, if the process id is 16 bits, the resolution of ``current time''
3272 is one second, and the attacker knows what day the generator was seeded,
3273 there are only about 2^32 possibilities to try if all possible values
3274 for the process id and time-of-day are tried.
3275
3276 @item
3277 The generator output reveals too much. By observing only a small segment
3278 of the generator's output, its internal state can be recovered, and from
3279 there, all previous output and all future output can be computed by the
3280 attacker. 
3281 @end itemize
3282
3283 A randomness generator that is used for cryptographic purposes must have
3284 better properties. Let's first look at the seeding, as the issues here
3285 are mostly independent of the rest of the generator. The initial state
3286 of the generator (its seed) must be unguessable by the attacker. So
3287 what's unguessable? It depends on what the attacker already knows. The
3288 concept used in information theory to reason about such things is called
3289 ``entropy'', or ``conditional entropy'' (not to be confused with the
3290 thermodynamic concept with the same name). A reasonable requirement is
3291 that the seed contains a conditional entropy of at least some 80-100
3292 bits. This property can be explained as follows: Allow the attacker to
3293 ask @code{n} yes-no-questions, of his own choice, about the seed. If
3294 the attacker, using this question-and-answer session, as well as any
3295 other information he knows about the seeding process, still can't guess
3296 the seed correctly, then the conditional entropy is more than @code{n}
3297 bits.
3298
3299 @cindex Entropy
3300 @cindex Conditional entropy
3301
3302 Let's look at an example. Say information about timing of received
3303 network packets is used in the seeding process. If there is some random
3304 network traffic going on, this will contribute some bits of entropy or
3305 ``unguessability'' to the seed. However, if the attacker can listen in to
3306 the local network, or if all but a small number of the packets were
3307 transmitted by machines that the attacker can monitor, this additional
3308 information makes the seed easier for the attacker to figure out. Even
3309 if the information is exactly the same, the conditional entropy, or
3310 unguessability, is smaller for an attacker that knows some of it already
3311 before the hypothetical question-and-answer session.
3312
3313 Seeding of good generators is usually based on several sources. The key
3314 point here is that the amount of unguessability that each source
3315 contributes, depends on who the attacker is. Some sources that have been
3316 used are:
3317
3318 @table @asis
3319 @item High resolution timing of i/o activities
3320 Such as completed blocks from spinning hard disks, network packets, etc.
3321 Getting access to such information is quite system dependent, and not
3322 all systems include suitable hardware. If available, it's one of the
3323 better randomness source one can find in a digital, mostly predictable,
3324 computer.
3325
3326 @item User activity
3327 Timing and contents of user interaction events is another popular source
3328 that is available for interactive programs (even if I suspect that it is
3329 sometimes used in order to make the user feel good, not because the
3330 quality of the input is needed or used properly). Obviously, not
3331 available when a machine is unattended. Also beware of networks: User
3332 interaction that happens across a long serial cable, @acronym{TELNET}
3333 session, or even @acronym{SSH} session may be visible to an attacker, in
3334 full or partially.
3335
3336 @item Audio input
3337 Any room, or even a microphone input that's left unconnected, is a
3338 source of some random background noise, which can be fed into the
3339 seeding process.
3340
3341 @item Specialized hardware
3342 Hardware devices with the sole purpose of generating random data have
3343 been designed. They range from radioactive samples with an attached
3344 Geiger counter, to amplification of the inherent noise in electronic
3345 components such as diodes and resistors, to low-frequency sampling of
3346 chaotic systems. Hashing successive images of a Lava lamp is a
3347 spectacular example of the latter type.
3348
3349 @item Secret information
3350 Secret information, such as user passwords or keys, or private files
3351 stored on disk, can provide some unguessability. A problem is that if
3352 the information is revealed at a later time, the unguessability
3353 vanishes. Another problem is that this kind of information tends to be
3354 fairly constant, so if you rely on it and seed your generator regularly,
3355 you risk constructing almost similar seeds or even constructing the same
3356 seed more than once.
3357 @end table
3358
3359 For all practical sources, it's difficult but important to provide a
3360 reliable lower bound on the amount of unguessability that it provides.
3361 Two important points are to make sure that the attacker can't observe
3362 your sources (so if you like the Lava lamp idea, remember that you have
3363 to get your own lamp, and not put it by a window or anywhere else where
3364 strangers can see it), and that hardware failures are detected. What if
3365 the bulb in the Lava lamp, which you keep locked into a cupboard
3366 following the above advice, breaks after a few months?
3367
3368 So let's assume that we have been able to find an unguessable seed,
3369 which contains at least 80 bits of conditional entropy, relative to all
3370 attackers that we care about (typically, we must at the very least
3371 assume that no attacker has root privileges on our machine).
3372
3373 How do we generate output from this seed, and how much can we get? Some
3374 generators (notably the Linux @file{/dev/random} generator) tries to
3375 estimate available entropy and restrict the amount of output. The goal
3376 is that if you read 128 bits from @file{/dev/random}, you should get 128
3377 ``truly random'' bits. This is a property that is useful in some
3378 specialized circumstances, for instance when generating key material for
3379 a one time pad, or when working with unconditional blinding, but in most
3380 cases, it doesn't matter much. For most application, there's no limit on
3381 the amount of useful ``random'' data that we can generate from a small
3382 seed; what matters is that the seed is unguessable and that the
3383 generator has good cryptographic properties.
3384
3385 At the heart of all generators lies its internal state. Future output
3386 is determined by the internal state alone. Let's call it the generator's
3387 key. The key is initialized from the unguessable seed. Important
3388 properties of a generator are:
3389
3390 @table @dfn
3391
3392 @item Key-hiding
3393 An attacker observing the output should not be able to recover the
3394 generator's key.
3395
3396 @item Independence of outputs
3397 Observing some of the output should not help the attacker to guess
3398 previous or future output.
3399
3400 @item Forward secrecy
3401 Even if an attacker compromises the generator's key, he should not be
3402 able to guess the generator output @emph{before} the key compromise.
3403
3404 @item Recovery from key compromise
3405 If an attacker compromises the generator's key, he can compute
3406 @emph{all} future output. This is inevitable if the generator is seeded
3407 only once, at startup. However, the generator can provide a reseeding
3408 mechanism, to achieve recovery from key compromise. More precisely: If
3409 the attacker compromises the key at a particular time @code{t_1}, there
3410 is another later time @code{t_2}, such that if the attacker observes all
3411 output generated between @code{t_1} and @code{t_2}, he still can't guess
3412 what output is generated after @code{t_2}.
3413
3414 @end table
3415
3416 Nettle includes one randomness generator that is believed to have all
3417 the above properties, and two simpler ones.
3418
3419 @acronym{ARCFOUR}, like any stream cipher, can be used as a randomness
3420 generator. Its output should be of reasonable quality, if the seed is
3421 hashed properly before it is used with @code{arcfour_set_key}. There's
3422 no single natural way to reseed it, but if you need reseeding, you
3423 should be using Yarrow instead.
3424
3425 The ``lagged Fibonacci'' generator in @file{<nettle/knuth-lfib.h>} is a
3426 fast generator with good statistical properties, but is @strong{not} for
3427 cryptographic use, and therefore not documented here. It is included
3428 mostly because the Nettle test suite needs to generate some test data
3429 from a small seed.
3430
3431 The recommended generator to use is Yarrow, described below.
3432
3433 @subsection Yarrow
3434
3435 Yarrow is a family of pseudo-randomness generators, designed for
3436 cryptographic use, by John Kelsey, Bruce Schneier and Niels Ferguson.
3437 Yarrow-160 is described in a paper at
3438 @url{http://www.counterpane.com/yarrow.html}, and it uses @acronym{SHA1}
3439 and triple-DES, and has a 160-bit internal state. Nettle implements
3440 Yarrow-256, which is similar, but uses @acronym{SHA256} and
3441 @acronym{AES} to get an internal state of 256 bits.
3442
3443 Yarrow was an almost finished project, the paper mentioned above is the
3444 closest thing to a specification for it, but some smaller details are
3445 left out. There is no official reference implementation or test cases.
3446 This section includes an overview of Yarrow, but for the details of
3447 Yarrow-256, as implemented by Nettle, you have to consult the source
3448 code. Maybe a complete specification can be written later.
3449
3450 Yarrow can use many sources (at least two are needed for proper
3451 reseeding), and two randomness ``pools'', referred to as the ``slow pool'' and
3452 the ``fast pool''. Input from the sources is fed alternatingly into the
3453 two pools. When one of the sources has contributed 100 bits of entropy
3454 to the fast pool, a ``fast reseed'' happens and the fast pool is mixed
3455 into the internal state. When at least two of the sources have
3456 contributed at least 160 bits each to the slow pool, a ``slow reseed''
3457 takes place. The contents of both pools are mixed into the internal
3458 state. These procedures should ensure that the generator will eventually
3459 recover after a key compromise.
3460
3461 The output is generated by using @acronym{AES} to encrypt a counter,
3462 using the generator's current key. After each request for output,
3463 another 256 bits are generated which replace the key. This ensures
3464 forward secrecy.
3465
3466 Yarrow can also use a @dfn{seed file} to save state across restarts.
3467 Yarrow is seeded by either feeding it the contents of the previous seed
3468 file, or feeding it input from its sources until a slow reseed happens.
3469
3470 Nettle defines Yarrow-256 in @file{<nettle/yarrow.h>}. 
3471
3472 @deftp {Context struct} {struct yarrow256_ctx}
3473 @end deftp
3474
3475 @deftp {Context struct} {struct yarrow_source}
3476 Information about a single source.
3477 @end deftp
3478
3479 @defvr Constant YARROW256_SEED_FILE_SIZE
3480 Recommended size of the Yarrow-256 seed file.
3481 @end defvr
3482
3483 @deftypefun void yarrow256_init (struct yarrow256_ctx *@var{ctx}, unsigned @var{nsources}, struct yarrow_source *@var{sources})
3484 Initializes the yarrow context, and its @var{nsources} sources. It's
3485 possible to call it with @var{nsources}=0 and @var{sources}=NULL, if
3486 you don't need the update features.
3487 @end deftypefun
3488
3489 @deftypefun void yarrow256_seed (struct yarrow256_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{seed_file})
3490 Seeds Yarrow-256 from a previous seed file. @var{length} should be at least
3491 @code{YARROW256_SEED_FILE_SIZE}, but it can be larger.
3492
3493 The generator will trust you that the @var{seed_file} data really is
3494 unguessable. After calling this function, you @emph{must} overwrite the old
3495 seed file with newly generated data from @code{yarrow256_random}. If it's
3496 possible for several processes to read the seed file at about the same
3497 time, access must be coordinated using some locking mechanism.
3498 @end deftypefun
3499
3500 @deftypefun int yarrow256_update (struct yarrow256_ctx *@var{ctx}, unsigned @var{source}, unsigned @var{entropy}, unsigned @var{length}, const uint8_t *@var{data})
3501 Updates the generator with data from source @var{SOURCE} (an index that
3502 must be smaller than the number of sources). @var{entropy} is your
3503 estimated lower bound for the entropy in the data, measured in bits.
3504 Calling update with zero @var{entropy} is always safe, no matter if the
3505 data is random or not.
3506
3507 Returns 1 if a reseed happened, in which case an application using a
3508 seed file may want to generate new seed data with
3509 @code{yarrow256_random} and overwrite the seed file. Otherwise, the
3510 function returns 0.
3511 @end deftypefun
3512
3513 @deftypefun void yarrow256_random (struct yarrow256_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst})
3514 Generates @var{length} octets of output. The generator must be seeded
3515 before you call this function.
3516
3517 If you don't need forward secrecy, e.g. if you need non-secret
3518 randomness for initialization vectors or padding, you can gain some
3519 efficiency by buffering, calling this function for reasonably large
3520 blocks of data, say 100-1000 octets at a time.
3521 @end deftypefun
3522
3523 @deftypefun int yarrow256_is_seeded (struct yarrow256_ctx *@var{ctx})
3524 Returns 1 if the generator is seeded and ready to generate output,
3525 otherwise 0.
3526 @end deftypefun
3527
3528 @deftypefun unsigned yarrow256_needed_sources (struct yarrow256_ctx *@var{ctx})
3529 Returns the number of sources that must reach the threshold before a
3530 slow reseed will happen. Useful primarily when the generator is unseeded.
3531 @end deftypefun
3532
3533 @deftypefun void yarrow256_fast_reseed (struct yarrow256_ctx *@var{ctx})
3534 @deftypefunx void yarrow256_slow_reseed (struct yarrow256_ctx *@var{ctx})
3535 Causes a fast or slow reseed to take place immediately, regardless of the
3536 current entropy estimates of the two pools. Use with care.
3537 @end deftypefun
3538
3539 Nettle includes an entropy estimator for one kind of input source: User
3540 keyboard input.
3541
3542 @deftp {Context struct} {struct yarrow_key_event_ctx}
3543 Information about recent key events.
3544 @end deftp
3545
3546 @deftypefun void yarrow_key_event_init (struct yarrow_key_event_ctx *@var{ctx})
3547 Initializes the context.
3548 @end deftypefun
3549
3550 @deftypefun unsigned yarrow_key_event_estimate (struct yarrow_key_event_ctx *@var{ctx}, unsigned @var{key}, unsigned @var{time})
3551 @var{key} is the id of the key (ASCII value, hardware key code, X
3552 keysym, @dots{}, it doesn't matter), and @var{time} is the timestamp of
3553 the event. The time must be given in units matching the resolution by
3554 which you read the clock. If you read the clock with microsecond
3555 precision, @var{time} should be provided in units of microseconds. But
3556 if you use @code{gettimeofday} on a typical Unix system where the clock
3557 ticks 10 or so microseconds at a time, @var{time} should be given in
3558 units of 10 microseconds.
3559
3560 Returns an entropy estimate, in bits, suitable for calling
3561 @code{yarrow256_update}. Usually, 0, 1 or 2 bits.
3562 @end deftypefun
3563
3564 @node ASCII encoding, Miscellaneous functions, Randomness, Reference
3565 @comment  node-name,  next,  previous,  up
3566 @section ASCII encoding
3567
3568 Encryption will transform your data from text into binary format, and that
3569 may be a problem if you want, for example, to send the data as if it was
3570 plain text in an email (or store it along with descriptive text in a
3571 file). You may then use an encoding from binary to text: each binary byte
3572 is translated into a number of bytes of plain text.
3573
3574 A base-N encoding of data is one representation of data that only uses N
3575 different symbols (instead of the 256 possible values of a byte).
3576
3577 The base64 encoding will always use alphanumeric (upper and lower case)
3578 characters and the '+', '/' and '=' symbols to represent the data. Four
3579 output characters are generated for each three bytes of input. In case
3580 the length of the input is not a multiple of three, padding characters
3581 are added at the end.
3582
3583 The base16 encoding, also known as ``hexadecimal'', uses the decimal
3584 digits and the letters from A to F. Two hexadecimal digits are generated
3585 for each input byte. Base16 may be useful if you want to use the data
3586 for filenames or URLs, for example.
3587
3588 Nettle supports both base64 and base16 encoding and decoding.
3589
3590 Encoding and decoding uses a context struct to maintain its state (with
3591 the exception of base16 encoding, which doesn't need any). To encode or
3592 decode the your data, first initialize the context, then call the update
3593 function as many times as necessary, and complete the operation by
3594 calling the final function.
3595
3596 The following functions can be used to perform base64 encoding and decoding.
3597 They are defined in @file{<nettle/base64.h>}.
3598
3599 @deftp {Context struct} {struct base64_encode_ctx}
3600 @end deftp
3601
3602 @deftypefun {void} base64_encode_init (struct base64_encode_ctx *@var{ctx})
3603 Initializes a base64 context. This is necessary before starting an encoding
3604 session.
3605 @end deftypefun
3606
3607
3608 @deftypefun {unsigned} base64_encode_single (struct base64_encode_ctx *@var{ctx}, uint8_t *@var{dst}, uint8_t @var{src})
3609 Encodes a single byte. Returns amount of output (always 1 or 2).
3610 @end deftypefun
3611
3612 @deffn Macro BASE64_ENCODE_LENGTH (@var{length})
3613 The maximum number of output bytes when passing @var{length} input bytes
3614 to @code{base64_encode_update}.
3615 @end deffn
3616
3617 @deftypefun {unsigned} base64_encode_update (struct base64_encode_ctx *@var{ctx}, uint8_t *@var{dst}, unsigned @var{length}, const uint8_t *@var{src})
3618 After @var{ctx} is initialized, this function may be called to encode @var{length}
3619 bytes from @var{src}. The result will be placed in @var{dst}, and the return value
3620 will be the number of bytes generated. Note that @var{dst} must be at least of size
3621 BASE64_ENCODE_LENGTH(@var{length}).
3622 @end deftypefun
3623
3624 @defvr Constant BASE64_ENCODE_FINAL_LENGTH
3625 The maximum amount of output from @code{base64_encode_final}.
3626 @end defvr
3627
3628 @deftypefun {unsigned} base64_encode_final (struct base64_encode_ctx *@var{ctx}, uint8_t *@var{dst})
3629 After calling base64_encode_update one or more times, this function
3630 should be called to generate the final output bytes, including any
3631 needed paddding. The return value is the number of output bytes
3632 generated.
3633 @end deftypefun
3634
3635 @deftp {Context struct} {struct base64_decode_ctx}
3636 @end deftp
3637
3638 @deftypefun {void} base64_decode_init (struct base64_decode_ctx *@var{ctx})
3639 Initializes a base64 decoding context. This is necessary before starting a decoding
3640 session.
3641 @end deftypefun
3642
3643 @deftypefun {int} base64_decode_single (struct base64_decode_ctx *@var{ctx}, uint8_t *@var{dst}, uint8_t @var{src})
3644 Decodes a single byte (@var{src}) and stores the result in @var{dst}.
3645 Returns amount of output (0 or 1), or -1 on errors.
3646 @end deftypefun
3647
3648 @deffn Macro BASE64_DECODE_LENGTH (@var{length})
3649 The maximum number of output bytes when passing @var{length} input bytes
3650 to @code{base64_decode_update}.
3651 @end deffn
3652
3653 @deftypefun {void} base64_decode_update (struct base64_decode_ctx *@var{ctx}, unsigned *@var{dst_length}, uint8_t *@var{dst}, unsigned @var{src_length}, const uint8_t *@var{src})
3654 After @var{ctx} is initialized, this function may be called to decode @var{src_length}
3655 bytes from @var{src}. @var{dst} should point to an area of size at least
3656 BASE64_DECODE_LENGTH(@var{length}), and for sanity checking, @var{dst_length}
3657 should be initialized to the size of that area before the call.
3658 @var{dst_length} is updated to the amount of decoded output. The function will return
3659 1 on success and 0 on error.
3660 @end deftypefun
3661
3662 @deftypefun {int} base64_decode_final (struct base64_decode_ctx *@var{ctx})
3663 Check that final padding is correct. Returns 1 on success, and 0 on
3664 error.
3665 @end deftypefun
3666
3667 Similarly to the base64 functions, the following functions perform base16 encoding,
3668 and are defined in @file{<nettle/base16.h>}. Note that there is no encoding context
3669 necessary for doing base16 encoding.
3670
3671 @deftypefun {void} base16_encode_single (uint8_t *@var{dst}, uint8_t @var{src})
3672 Encodes a single byte. Always stores two digits in @var{dst}[0] and @var{dst}[1].
3673 @end deftypefun
3674
3675 @deffn Macro BASE16_ENCODE_LENGTH (@var{length})
3676 The number of output bytes when passing @var{length} input bytes to
3677 @code{base16_encode_update}.
3678 @end deffn
3679
3680 @deftypefun {void} base16_encode_update (uint8_t *@var{dst}, unsigned @var{length}, const uint8_t *@var{src})
3681 Always stores BASE16_ENCODE_LENGTH(@var{length}) digits in @var{dst}.
3682 @end deftypefun
3683
3684 @deftp {Context struct} {struct base16_decode_ctx}
3685 @end deftp
3686
3687 @deftypefun {void} base16_decode_init (struct base16_decode_ctx *@var{ctx})
3688 Initializes a base16 decoding context. This is necessary before starting a decoding
3689 session.
3690 @end deftypefun
3691
3692 @deftypefun {int} base16_decode_single (struct base16_decode_ctx *@var{ctx}, uint8_t *@var{dst}, uint8_t @var{src})
3693 Decodes a single byte from @var{src} into @var{dst}. Returns amount of output (0 or 1), or -1 on errors.
3694 @end deftypefun
3695
3696 @deffn Macro BASE16_DECODE_LENGTH (@var{length})
3697 The maximum number of output bytes when passing @var{length} input bytes
3698 to @code{base16_decode_update}.
3699 @end deffn
3700
3701 @deftypefun {int} base16_decode_update (struct base16_decode_ctx *@var{ctx}, unsigned *@var{dst_length}, uint8_t *@var{dst}, unsigned @var{src_length}, const uint8_t *@var{src})
3702 After @var{ctx} is initialized, this function may be called to decode @var{src_length}
3703 bytes from @var{src}. @var{dst} should point to an area of size at least
3704 BASE16_DECODE_LENGTH(@var{length}), and for sanity checking, @var{dst_length}
3705 should be initialized to the size of that area before the call.
3706 @var{dst_length} is updated to the amount of decoded output. The function will return
3707 1 on success and 0 on error.
3708 @end deftypefun
3709
3710 @deftypefun {int} base16_decode_final (struct base16_decode_ctx *@var{ctx})
3711 Checks that the end of data is correct (i.e., an even number of
3712 hexadecimal digits have been seen). Returns 1 on success, and 0 on
3713 error.
3714 @end deftypefun
3715
3716 @node Miscellaneous functions, Compatibility functions, ASCII encoding, Reference
3717 @comment  node-name,  next,  previous,  up
3718 @section Miscellaneous functions
3719
3720 @deftypefun {uint8_t *} memxor (uint8_t *@var{dst}, const uint8_t *@var{src}, size_t @var{n})
3721 XORs the source area on top of the destination area. The interface
3722 doesn't follow the Nettle conventions, because it is intended to be
3723 similar to the ANSI-C @code{memcpy} function.
3724 @end deftypefun
3725
3726 @code{memxor} is declared in @file{<nettle/memxor.h>}.
3727
3728 @node Compatibility functions,  , Miscellaneous functions, Reference
3729 @comment  node-name,  next,  previous,  up
3730 @section Compatibility functions
3731
3732 For convenience, Nettle includes alternative interfaces to some
3733 algorithms, for compatibility with some other popular crypto toolkits.
3734 These are not fully documented here; refer to the source or to the
3735 documentation for the original implementation.
3736
3737 MD5 is defined in [RFC 1321], which includes a reference implementation.
3738 Nettle defines a compatible interface to MD5 in
3739 @file{<nettle/md5-compat.h>}. This file defines the typedef
3740 @code{MD5_CTX}, and declares the functions @code{MD5Init}, @code{MD5Update} and
3741 @code{MD5Final}.
3742
3743 Eric Young's ``libdes'' (also part of OpenSSL) is a quite popular DES
3744 implementation. Nettle includes a subset if its interface in
3745 @file{<nettle/des-compat.h>}. This file defines the typedefs
3746 @code{des_key_schedule} and @code{des_cblock}, two constants
3747 @code{DES_ENCRYPT} and @code{DES_DECRYPT}, and declares one global
3748 variable @code{des_check_key}, and the functions @code{des_cbc_cksum}
3749 @code{des_cbc_encrypt}, @code{des_ecb2_encrypt},
3750 @code{des_ecb3_encrypt}, @code{des_ecb_encrypt},
3751 @code{des_ede2_cbc_encrypt}, @code{des_ede3_cbc_encrypt},
3752 @code{des_is_weak_key}, @code{des_key_sched}, @code{des_ncbc_encrypt}
3753 @code{des_set_key}, and @code{des_set_odd_parity}.
3754
3755 @node Nettle soup, Installation, Reference, Top
3756 @comment  node-name,  next,  previous,  up
3757 @chapter Traditional Nettle Soup
3758 For the serious nettle hacker, here is a recipe for nettle soup. 4 servings.
3759
3760 @itemize @w{}
3761 @item
3762 1 liter fresh nettles (urtica dioica)
3763 @item
3764 2 tablespoons butter
3765 @item
3766 3 tablespoons flour
3767 @item
3768 1 liter stock (meat or vegetable)
3769 @item
3770 1/2 teaspoon salt
3771 @item
3772 a tad white pepper
3773 @item
3774 some cream or milk
3775 @end itemize
3776
3777 Gather 1 liter fresh nettles. Use gloves! Small, tender shoots are
3778 preferable but the tops of larger nettles can also be used.
3779
3780 Rinse the nettles very well. Boil them for 10 minutes in lightly salted
3781 water. Strain the nettles and save the water. Hack the nettles. Melt the
3782 butter and mix in the flour. Dilute with stock and the nettle-water you
3783 saved earlier. Add the hacked nettles. If you wish you can add some milk
3784 or cream at this stage. Bring to a boil and let boil for a few minutes.
3785 Season with salt and pepper.
3786
3787 Serve with boiled egg-halves.
3788
3789 @c And the original Swedish version.
3790 @ignore
3791
3792 Recept på nässelsoppa
3793 4 portioner
3794
3795 1 l färska nässlor
3796 2 msk smör
3797 3 msk vetemjöl
3798 1 l kött- eller grönsaksbuljong
3799 1/2 tsk salt
3800 1-2 krm peppar
3801 (lite grädde eller mjölk)
3802
3803 Plocka 1 liter färska nässlor. Använd handskar! Helst små och späda
3804 skott, men topparna av större nässlor går också bra.
3805
3806 Skölj nässlorna väl. Förväll dem ca 10 minuter i lätt saltat vatten.
3807 Häll av och spara spadet. Hacka nässlorna. Smält smöret, rör i mjöl och
3808 späd med buljong och nässelspad. Lägg i de hackade nässlorna. Om så
3809 önskas, häll i en skvätt mjölk eller grädde. Koka några minuter, och
3810 smaksätt med salt och peppar.
3811
3812 Servera med kokta ägghalvor.
3813 @end ignore
3814
3815 @node Installation, Index, Nettle soup, Top
3816 @comment  node-name,  next,  previous,  up
3817 @chapter Installation
3818
3819 Nettle uses @command{autoconf}. To build it, unpack the source and run
3820
3821 @example
3822 ./configure
3823 make
3824 make check
3825 make install
3826 @end example
3827
3828 @noindent
3829 to install in under the default prefix, @file{/usr/local}.
3830
3831 To get a list of configure options, use @code{./configure --help}.
3832
3833 By default, both static and shared libraries are built and installed. To
3834 omit building the shared libraries, use the @option{ --disable-shared}
3835 option to @command{./configure}.
3836
3837 Using GNU make is recommended. For other make programs, in particular
3838 BSD make, you may have to use the @option{--disable-dependency-tracking}
3839 option to @command{./configure}.
3840
3841 @node Index,  , Installation, Top
3842 @comment  node-name,  next,  previous,  up
3843 @unnumbered Function and Concept Index
3844
3845 @printindex cp
3846
3847 @bye
3848 \f
3849 Local Variables:
3850 ispell-local-dictionary: "american"
3851 ispell-skip-region-alist: (
3852  (ispell-words-keyword forward-line)
3853  ("^@example" . "^@end.*example")
3854  ("^@ignore" . "^@end.*ignore")
3855  ("^@\\(end\\|syncodeindex\\|vskip\\|\\(un\\)?macro\\|node\\|deftp\\) .*$")
3856  ("^@\\(printindex\\|set\\) .*$")
3857  ("^@def.*$")
3858  ;; Allows one level of nested braces in the argument 
3859  ("@\\(uref\\|value\\|badspell\\|code\\|file\\|var\\|url\\){[^{}]*\\({[^{}]*}[^{}]*\\)*}")
3860  ("@[a-z]+[{ ]")
3861  ("@[a-z]+$")
3862  ("\input texinfo.*$")
3863  ("ispell-ignore" . "ispell-end-ignore")
3864  ("^Local Variables:$" . "^End:$"))
3865 End:
3866
3867 @c  LocalWords:  cryptographics crypto LSH GNUPG API GPL LGPL aes rijndael ller
3868 @c  LocalWords:  Sevilla arcfour RC Niels Dassen Colin Kuchling Biham sha Ruud
3869 @c  LocalWords:  Gutmann twofish de Rooij struct MB Rivest RFC Nettle's ECB CBC
3870 @c  LocalWords:  RSA Daemen Rijnmen Schneier DES's ede structs oddnesses HMAC
3871 @c  LocalWords:  NIST Alice's GMP bignum Diffie Adi Shamir Adleman Euclid's ASN
3872 @c  LocalWords:  PKCS callbacks Young's urtica dioica autoconf SSH tad
3873 @c  LocalWords:  unguessability reseeding reseed alternatingly keysym subkeys
3874 @c  LocalWords:  DSA gmp FIPS DSS libdes OpenSSL ARCTWO Josefsson Nikos Andreas
3875 @c  LocalWords:  Mavroyanopoulos Sigfridsson Comstedt interoperability Sparc IC
3876 @c  LocalWords:  DES FIXME Rivest's plaintext ciphertext CTR XORed timestamp
3877 @c  LocalWords:  XORs cryptologists libnettle libhogweed GCM ECDSA NTT
3878 @c  LocalWords:  toolkits BLOWFISH Möller RIPEMD libgcrypt PBKDF Shishi
3879 @c  LocalWords:  GnuTLS Gutmann's GOSTHASH GOST Aleksey Kravchenko ECC
3880 @c  LocalWords:  rhash Mavrogiannopoulos Keccak Bertoni
3881 @c  LocalWords:  Michaël Peeters Assche Dobbertin Antoon Bosselaers KDF
3882 @c  LocalWords:  Preneel rôle McGrew Viega KDFs PBKDFs passphrase PRF
3883 @c  LocalWords:  th deallocate pre bitsize multi lookup secp startup
3884 @c  LocalWords:  typedef typedef