91bddbd13a29e4ad957f2bd4d31ec93871f623ec
[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 3.2
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 2015.
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 Hash functions
87
88 * Recommended hash functions::
89 * Legacy hash functions::
90 * nettle_hash abstraction::
91
92 Cipher modes
93
94 * CBC::                         
95 * CTR::                         
96 * GCM::                         
97 * CCM::                         
98
99 Keyed Hash Functions
100
101 * HMAC::
102 * UMAC::
103
104 Public-key algorithms
105
106 * RSA::                         The RSA public key algorithm.
107 * DSA::                         The DSA digital signature algorithm.
108 * Elliptic curves::             Elliptic curves and ECDSA
109
110 @end detailmenu
111 @end menu
112
113 @end ifnottex
114
115 @node Introduction, Copyright, Top, Top
116 @comment  node-name,  next,  previous,  up
117 @chapter Introduction
118
119 Nettle is a cryptographic library that is designed to fit easily in more
120 or less any context: In crypto toolkits for object-oriented languages
121 (C++, Python, Pike, ...), in applications like LSH or GNUPG, or even in
122 kernel space. In most contexts, you need more than the basic
123 cryptographic algorithms, you also need some way to keep track of available
124 algorithms, their properties and variants. You often have some algorithm
125 selection process, often dictated by a protocol you want to implement.
126
127 And as the requirements of applications differ in subtle and not so
128 subtle ways, an API that fits one application well can be a pain to use
129 in a different context. And that is why there are so many different
130 cryptographic libraries around.
131
132 Nettle tries to avoid this problem by doing one thing, the low-level
133 crypto stuff, and providing a @emph{simple} but general interface to it.
134 In particular, Nettle doesn't do algorithm selection. It doesn't do
135 memory allocation. It doesn't do any I/O.
136
137 The idea is that one can build several application and context specific
138 interfaces on top of Nettle, and share the code, test cases, benchmarks,
139 documentation, etc. Examples are the Nettle module for the Pike
140 language, and LSH, which both use an object-oriented abstraction on top
141 of the library.
142
143 This manual explains how to use the Nettle library. It also tries to
144 provide some background on the cryptography, and advice on how to best
145 put it to use.
146
147 @node Copyright, Conventions, Introduction, Top
148 @comment  node-name,  next,  previous,  up
149 @chapter Copyright
150
151 Nettle is dual licenced under the GNU General Public License version 2
152 or later, and the GNU Lesser General Public License version 3 or later.
153 When using Nettle, you must comply fully with all conditions of at least
154 one of these licenses. A few of the individual files are licensed under
155 more permissive terms, or in the public domain. To find the current
156 status of particular files, you have to read the copyright notices at
157 the top of the files.
158
159 This manual is in the public domain. You may freely copy it in whole or
160 in part, e.g., into documentation of programs that build on Nettle.
161 Attribution, as well as contribution of improvements to the text, is of
162 course appreciated, but it is not required.
163
164 A list of the supported algorithms, their origins, and exceptions to the
165 above licensing:
166
167 @table @emph
168 @item AES
169 The implementation of the AES cipher (also known as rijndael) is written
170 by Rafael Sevilla. Assembler for x86 by Rafael Sevilla and
171 @value{AUTHOR}, Sparc assembler by @value{AUTHOR}.
172
173 @item ARCFOUR
174 The implementation of the ARCFOUR (also known as RC4) cipher is written
175 by @value{AUTHOR}.
176
177 @item ARCTWO
178 The implementation of the ARCTWO (also known as RC2) cipher is written
179 by Nikos Mavroyanopoulos and modified by Werner Koch and Simon
180 Josefsson.
181
182 @item BLOWFISH
183 The implementation of the BLOWFISH cipher is written by Werner Koch,
184 copyright owned by the Free Software Foundation. Also hacked by Simon
185 Josefsson and Niels Möller.
186
187 @item CAMELLIA
188 The C implementation is by Nippon Telegraph and Telephone Corporation
189 (NTT), heavily modified by @value{AUTHOR}. Assembler for x86 and x86_64
190 by @value{AUTHOR}.
191
192 @item CAST128
193 The implementation of the CAST128 cipher is written by Steve Reid.
194 Released into the public domain.
195
196 @item CHACHA
197 Implemented by Joachim Strömbergson, based on the implementation of
198 SALSA20 (see below). Assembly for x86_64 by Niels Möller.
199
200 @item DES
201 The implementation of the DES cipher is written by Dana L. How, and
202 released under the LGPL, version 2 or later.
203
204 @item GOSTHASH94
205 The C implementation of the GOST94 message digest is written by 
206 Aleksey Kravchenko and was ported from the rhash library by Nikos
207 Mavrogiannopoulos. It is released under the MIT license.
208
209 @item MD2
210 The implementation of MD2 is written by Andrew Kuchling, and hacked
211 some by Andreas Sigfridsson and @value{AUTHOR}. Python Cryptography
212 Toolkit license (essentially public domain).
213
214 @item MD4
215 This is almost the same code as for MD5 below, with modifications by
216 Marcus Comstedt. Released into the public domain.
217
218 @item MD5
219 The implementation of the MD5 message digest is written by Colin Plumb.
220 It has been hacked some more by Andrew Kuchling and @value{AUTHOR}.
221 Released into the public domain.
222
223 @item PBKDF2
224 The C implementation of PBKDF2 is based on earlier work for Shishi and
225 GnuTLS by Simon Josefsson.
226
227 @item RIPEMD160
228 The implementation of RIPEMD160 message digest is based on the code in
229 libgcrypt, copyright owned by the Free Software Foundation. Ported to
230 Nettle by Andres Mejia.
231
232 @item SALSA20
233 The C implementation of SALSA20 is based on D. J. Bernstein's reference
234 implementation (in the public domain), adapted to Nettle by Simon
235 Josefsson, and heavily modified by Niels Möller. Assembly for x86_64 and
236 ARM by Niels Möller.
237
238 @item SERPENT
239 The implementation of the SERPENT cipher is based on the code in libgcrypt,
240 copyright owned by the Free Software Foundation. Adapted to Nettle by
241 Simon Josefsson and heavily modified by Niels Möller. Assembly for
242 x86_64 by Niels Möller.
243
244 @item POLY1305
245 Based on the implementation by Andrew M. (floodyberry), modified by
246 Nikos Mavrogiannopoulos and Niels Möller. Assembly for x86_64 by Niels
247 Möller.
248
249 @item SHA1
250 The C implementation of the SHA1 message digest is written by Peter
251 Gutmann, and hacked some more by Andrew Kuchling and @value{AUTHOR}.
252 Released into the public domain. Assembler for x86, x86_64 and ARM by
253 @value{AUTHOR}, released under the LGPL.
254
255 @item SHA2
256 Written by @value{AUTHOR}, using Peter Gutmann's SHA1 code as a model. 
257
258 @item SHA3
259 Written by @value{AUTHOR}.
260
261 @item TWOFISH
262 The implementation of the TWOFISH cipher is written by Ruud de Rooij.
263
264 @item UMAC
265 Written by @value{AUTHOR}.
266
267 @item RSA
268 Written by @value{AUTHOR}. Uses the GMP library for bignum operations.
269
270 @item DSA
271 Written by @value{AUTHOR}. Uses the GMP library for bignum operations.
272
273 @item ECDSA
274 Written by @value{AUTHOR}. Uses the GMP library for bignum operations.
275 Development of Nettle's ECC support was funded by the .SE Internet Fund.
276 @end table
277
278 @node Conventions, Example, Copyright, Top
279 @comment  node-name,  next,  previous,  up
280 @chapter Conventions
281
282 For each supported algorithm, there is an include file that defines a
283 @emph{context struct}, a few constants, and declares functions for
284 operating on the context. The context struct encapsulates all information
285 needed by the algorithm, and it can be copied or moved in memory with no
286 unexpected effects.
287
288 For consistency, functions for different algorithms are very similar,
289 but there are some differences, for instance reflecting if the key setup
290 or encryption function differ for encryption and decryption, and whether
291 or not key setup can fail. There are also differences between algorithms
292 that don't show in function prototypes, but which the application must
293 nevertheless be aware of. There is no big difference between the
294 functions for stream ciphers and for block ciphers, although they should
295 be used quite differently by the application.
296
297 If your application uses more than one algorithm of the same type, you
298 should probably create an interface that is tailor-made for your needs,
299 and then write a few lines of glue code on top of Nettle.
300
301 By convention, for an algorithm named @code{foo}, the struct tag for the
302 context struct is @code{foo_ctx}, constants and functions uses prefixes
303 like @code{FOO_BLOCK_SIZE} (a constant) and @code{foo_set_key} (a
304 function).
305
306 In all functions, strings are represented with an explicit length, of
307 type @code{size_t}, and a pointer of type @code{uint8_t *} or
308 @code{const uint8_t *}. For functions that transform one string to
309 another, the argument order is length, destination pointer and source
310 pointer. Source and destination areas are usually of the same length.
311 When they differ, e.g., for @code{ccm_encrypt_message}, the length
312 argument specifies the size of the destination area. Source and
313 destination pointers may be equal, so that you can process strings in
314 place, but source and destination areas @emph{must not} overlap in any
315 other way.
316
317 Many of the functions lack return value and can never fail. Those
318 functions which can fail, return one on success and zero on failure.
319
320 @c FIXME: Say something about the name mangling.
321
322 @node Example, Linking, Conventions, Top
323 @comment  node-name,  next,  previous,  up
324 @chapter Example
325
326 A simple example program that reads a file from standard input and
327 writes its SHA1 check-sum on standard output should give the flavor of
328 Nettle.
329
330 @example
331 @verbatiminclude sha-example.c
332 @end example
333
334 On a typical Unix system, this program can be compiled and linked with
335 the command line 
336 @example
337 gcc sha-example.c -o sha-example -lnettle
338 @end example
339
340 @node Linking, Reference, Example, Top
341 @comment  node-name,  next,  previous,  up
342 @chapter Linking
343
344 Nettle actually consists of two libraries, @file{libnettle} and
345 @file{libhogweed}. The @file{libhogweed} library contains those
346 functions of Nettle that uses bignum operations, and depends on the GMP
347 library. With this division, linking works the same for both static and
348 dynamic libraries.
349
350 If an application uses only the symmetric crypto algorithms of Nettle
351 (i.e., block ciphers, hash functions, and the like), it's sufficient to
352 link with @code{-lnettle}. If an application also uses public-key
353 algorithms, the recommended linker flags are @code{-lhogweed -lnettle
354 -lgmp}. If the involved libraries are installed as dynamic libraries, it
355 may be sufficient to link with just @code{-lhogweed}, and the loader
356 will resolve the dependencies automatically.
357
358 @node Reference, Nettle soup, Linking, Top
359 @comment  node-name,  next,  previous,  up
360 @chapter Reference
361
362 This chapter describes all the Nettle functions, grouped by family.
363
364 @menu
365 * Hash functions::              
366 * Cipher functions::            
367 * Cipher modes::                
368 * Authenticated encryption::
369 * Keyed hash functions::        
370 * Key derivation functions::    
371 * Public-key algorithms::       
372 * Randomness::                  
373 * ASCII encoding::              
374 * Miscellaneous functions::     
375 * Compatibility functions::     
376 @end menu
377
378 @node Hash functions, Cipher functions, Reference, Reference
379 @comment  node-name,  next,  previous,  up
380
381 @section Hash functions
382 @cindex Hash function
383 A cryptographic @dfn{hash function} is a function that takes variable
384 size strings, and maps them to strings of fixed, short, length. There
385 are naturally lots of collisions, as there are more possible 1MB files
386 than 20 byte strings. But the function is constructed such that is hard
387 to find the collisions. More precisely, a cryptographic hash function
388 @code{H} should have the following properties:
389
390 @table @emph
391
392 @item One-way
393 @cindex One-way
394 Given a hash value @code{H(x)} it is hard to find a string @code{x}
395 that hashes to that value.
396
397 @item Collision-resistant
398 @cindex Collision-resistant
399 It is hard to find two different strings, @code{x} and @code{y}, such
400 that @code{H(x)} = @code{H(y)}.
401
402 @end table
403
404 Hash functions are useful as building blocks for digital signatures,
405 message authentication codes, pseudo random generators, association of
406 unique ids to documents, and many other things.
407
408 The most commonly used hash functions are MD5 and SHA1. Unfortunately,
409 both these fail the collision-resistance requirement; cryptologists have
410 found ways to construct colliding inputs. The recommended hash functions
411 for new applications are SHA2 (with main variants SHA256 and SHA512). At
412 the time of this writing (Autumn 2015), SHA3 has recently been
413 standardized, and the new SHA3 and other top SHA3 candidates may also be
414 reasonable alternatives.
415
416 @menu
417 * Recommended hash functions::
418 * Legacy hash functions::
419 * nettle_hash abstraction::
420 @end menu
421
422 @node Recommended hash functions, Legacy hash functions,, Hash functions
423 @comment  node-name,  next,  previous,  up
424 @subsection Recommended hash functions
425
426 The following hash functions have no known weaknesses, and are suitable
427 for new applications. The SHA2 family of hash functions were specified
428 by @dfn{NIST}, intended as a replacement for @acronym{SHA1}.
429
430 @subsubsection @acronym{SHA256}
431
432 SHA256 is a member of the SHA2 family. It outputs hash values of 256
433 bits, or 32 octets. Nettle defines SHA256 in @file{<nettle/sha2.h>}.
434
435 @deftp {Context struct} {struct sha256_ctx}
436 @end deftp
437
438 @defvr Constant SHA256_DIGEST_SIZE
439 The size of a SHA256 digest, i.e. 32.
440 @end defvr
441
442 @defvr Constant SHA256_BLOCK_SIZE
443 The internal block size of SHA256. Useful for some special constructions,
444 in particular HMAC-SHA256.
445 @end defvr
446
447 @deftypefun void sha256_init (struct sha256_ctx *@var{ctx})
448 Initialize the SHA256 state.
449 @end deftypefun
450
451 @deftypefun void sha256_update (struct sha256_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
452 Hash some more data.
453 @end deftypefun
454
455 @deftypefun void sha256_digest (struct sha256_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
456 Performs final processing and extracts the message digest, writing it
457 to @var{digest}. @var{length} may be smaller than
458 @code{SHA256_DIGEST_SIZE}, in which case only the first @var{length}
459 octets of the digest are written.
460
461 This function also resets the context in the same way as
462 @code{sha256_init}.
463 @end deftypefun
464
465 Earlier versions of nettle defined SHA256 in the header file
466 @file{<nettle/sha.h>}, which is now deprecated, but kept for
467 compatibility.
468
469 @subsubsection @acronym{SHA224}
470
471 SHA224 is a variant of SHA256, with a different initial state, and with
472 the output truncated to 224 bits, or 28 octets. Nettle defines SHA224 in
473 @file{<nettle/sha2.h>} (and in @file{<nettle/sha.h>}, for backwards
474 compatibility).
475
476 @deftp {Context struct} {struct sha224_ctx}
477 @end deftp
478
479 @defvr Constant SHA224_DIGEST_SIZE
480 The size of a SHA224 digest, i.e. 28.
481 @end defvr
482
483 @defvr Constant SHA224_BLOCK_SIZE
484 The internal block size of SHA224. Useful for some special constructions,
485 in particular HMAC-SHA224.
486 @end defvr
487
488 @deftypefun void sha224_init (struct sha224_ctx *@var{ctx})
489 Initialize the SHA224 state.
490 @end deftypefun
491
492 @deftypefun void sha224_update (struct sha224_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
493 Hash some more data.
494 @end deftypefun
495
496 @deftypefun void sha224_digest (struct sha224_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
497 Performs final processing and extracts the message digest, writing it
498 to @var{digest}. @var{length} may be smaller than
499 @code{SHA224_DIGEST_SIZE}, in which case only the first @var{length}
500 octets of the digest are written.
501
502 This function also resets the context in the same way as
503 @code{sha224_init}.
504 @end deftypefun
505
506 @subsubsection @acronym{SHA512}
507
508 SHA512 is a larger sibling to SHA256, with a very similar structure but
509 with both the output and the internal variables of twice the size. The
510 internal variables are 64 bits rather than 32, making it significantly
511 slower on 32-bit computers. It outputs hash values of 512 bits, or 64
512 octets. Nettle defines SHA512 in @file{<nettle/sha2.h>} (and in
513 @file{<nettle/sha.h>}, for backwards compatibility).
514
515 @deftp {Context struct} {struct sha512_ctx}
516 @end deftp
517
518 @defvr Constant SHA512_DIGEST_SIZE
519 The size of a SHA512 digest, i.e. 64.
520 @end defvr
521
522 @defvr Constant SHA512_BLOCK_SIZE
523 The internal block size of SHA512, 128. Useful for some special
524 constructions, in particular HMAC-SHA512.
525 @end defvr
526
527 @deftypefun void sha512_init (struct sha512_ctx *@var{ctx})
528 Initialize the SHA512 state.
529 @end deftypefun
530
531 @deftypefun void sha512_update (struct sha512_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
532 Hash some more data.
533 @end deftypefun
534
535 @deftypefun void sha512_digest (struct sha512_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
536 Performs final processing and extracts the message digest, writing it
537 to @var{digest}. @var{length} may be smaller than
538 @code{SHA512_DIGEST_SIZE}, in which case only the first @var{length}
539 octets of the digest are written.
540
541 This function also resets the context in the same way as
542 @code{sha512_init}.
543 @end deftypefun
544
545 @subsubsection @acronym{SHA384 and other variants of SHA512}
546
547 Several variants of SHA512 have been defined, with a different initial
548 state, and with the output truncated to shorter length than 512 bits.
549 Naming is a bit confused, these algorithms are called SHA512-224,
550 SHA512-256 and SHA384, for output sizes of 224, 256 and 384 bits,
551 respectively. Nettle defines these in @file{<nettle/sha2.h>} (and in
552 @file{<nettle/sha.h>}, for backwards compatibility).
553
554 @deftp {Context struct} {struct sha512_224_ctx}
555 @deftpx {Context struct} {struct sha512_256_ctx}
556 @deftpx {Context struct} {struct sha384_ctx}
557 These context structs are all the same as sha512_ctx. They are defined as
558 simple preprocessor aliases, which may cause some problems if used as
559 identifiers for other purposes. So avoid doing that.
560 @end deftp
561
562 @defvr Constant SHA512_224_DIGEST_SIZE
563 @defvrx Constant SHA512_256_DIGEST_SIZE
564 @defvrx Constant SHA384_DIGEST_SIZE
565 The digest size for each variant, i.e., 28, 32, and 48, respectively.
566 @end defvr
567
568 @defvr Constant SHA512_224_BLOCK_SIZE
569 @defvrx Constant SHA512_256_BLOCK_SIZE
570 @defvrx Constant SHA384_BLOCK_SIZE
571 The internal block size, same as SHA512_BLOCK_SIZE, i.e., 128. Useful for
572 some special constructions, in particular HMAC-SHA384.
573 @end defvr
574
575 @deftypefun void sha512_224_init (struct sha512_224_ctx *@var{ctx})
576 @deftypefunx void sha512_256_init (struct sha512_256_ctx *@var{ctx})
577 @deftypefunx void sha384_init (struct sha384_ctx *@var{ctx})
578 Initialize the context struct.
579 @end deftypefun
580
581 @deftypefun void sha512_224_update (struct sha512_224_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
582 @deftypefunx void sha512_256_update (struct sha512_256_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
583 @deftypefunx void sha384_update (struct sha384_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
584 Hash some more data. These are all aliases for sha512_update, which does
585 the same thing.
586 @end deftypefun
587
588 @deftypefun void sha512_224_digest (struct sha512_224_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
589 @deftypefunx void sha512_256_digest (struct sha512_256_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
590 @deftypefunx void sha384_digest (struct sha384_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
591 Performs final processing and extracts the message digest, writing it to
592 @var{digest}. @var{length} may be smaller than the specified digest
593 size, in which case only the first @var{length} octets of the digest are
594 written.
595
596 These function also reset the context in the same way as the
597 corresponding init function.
598 @end deftypefun
599
600 @subsubsection @acronym{SHA3-224}
601 @cindex SHA3
602
603 The SHA3 hash functions were specified by NIST in response to weaknesses
604 in SHA1, and doubts about SHA2 hash functions which structurally are
605 very similar to SHA1. SHA3 is a result of a competition, where the
606 winner, also known as Keccak, was designed by Guido Bertoni, Joan
607 Daemen, Michaël Peeters and Gilles Van Assche. It is structurally very
608 different from all widely used earlier hash functions. Like SHA2, there
609 are several variants, with output sizes of 224, 256, 384 and 512 bits
610 (28, 32, 48 and 64 octets, respectively). In August 2015, it was
611 formally standardized by NIST, as FIPS 202,
612 @uref{http://dx.doi.org/10.6028/NIST.FIPS.202}.
613
614 Note that the SHA3 implementation in earlier versions of Nettle was
615 based on the specification at the time Keccak was announced as the
616 winner of the competition, which is incompatible with the final standard
617 and hence with current versions of Nettle. The @file{nette/sha3.h}
618 defines a preprocessor symbol @code{NETTLE_SHA3_FIPS202} to indicate
619 conformance with the standard.
620
621 @defvr Constant NETTLE_SHA3_FIPS202
622 Defined to 1 in Nettle versions supporting FIPS 202. Undefined in
623 earlier versions.
624 @end defvr
625
626 Nettle defines SHA3-224 in @file{<nettle/sha3.h>}.
627
628 @deftp {Context struct} {struct sha3_224_ctx}
629 @end deftp
630
631 @defvr Constant SHA3_224_DIGEST_SIZE
632 The size of a SHA3_224 digest, i.e., 28.
633 @end defvr
634
635 @defvr Constant SHA3_224_BLOCK_SIZE
636 The internal block size of SHA3_224.
637 @end defvr
638
639 @deftypefun void sha3_224_init (struct sha3_224_ctx *@var{ctx})
640 Initialize the SHA3-224 state.
641 @end deftypefun
642
643 @deftypefun void sha3_224_update (struct sha3_224_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
644 Hash some more data.
645 @end deftypefun
646
647 @deftypefun void sha3_224_digest (struct sha3_224_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
648 Performs final processing and extracts the message digest, writing it
649 to @var{digest}. @var{length} may be smaller than
650 @code{SHA3_224_DIGEST_SIZE}, in which case only the first @var{length}
651 octets of the digest are written.
652
653 This function also resets the context.
654 @end deftypefun
655
656 @subsubsection @acronym{SHA3-256}
657
658 This is SHA3 with 256-bit output size, and possibly the most useful
659 of the SHA3 hash functions.
660
661 Nettle defines SHA3-256 in @file{<nettle/sha3.h>}.
662
663 @deftp {Context struct} {struct sha3_256_ctx}
664 @end deftp
665
666 @defvr Constant SHA3_256_DIGEST_SIZE
667 The size of a SHA3_256 digest, i.e., 32.
668 @end defvr
669
670 @defvr Constant SHA3_256_BLOCK_SIZE
671 The internal block size of SHA3_256.
672 @end defvr
673
674 @deftypefun void sha3_256_init (struct sha3_256_ctx *@var{ctx})
675 Initialize the SHA3-256 state.
676 @end deftypefun
677
678 @deftypefun void sha3_256_update (struct sha3_256_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
679 Hash some more data.
680 @end deftypefun
681
682 @deftypefun void sha3_256_digest (struct sha3_256_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
683 Performs final processing and extracts the message digest, writing it
684 to @var{digest}. @var{length} may be smaller than
685 @code{SHA3_256_DIGEST_SIZE}, in which case only the first @var{length}
686 octets of the digest are written.
687
688 This function also resets the context.
689 @end deftypefun
690
691 @subsubsection @acronym{SHA3-384}
692
693 This is SHA3 with 384-bit output size.
694
695 Nettle defines SHA3-384 in @file{<nettle/sha3.h>}.
696
697 @deftp {Context struct} {struct sha3_384_ctx}
698 @end deftp
699
700 @defvr Constant SHA3_384_DIGEST_SIZE
701 The size of a SHA3_384 digest, i.e., 48.
702 @end defvr
703
704 @defvr Constant SHA3_384_BLOCK_SIZE
705 The internal block size of SHA3_384.
706 @end defvr
707
708 @deftypefun void sha3_384_init (struct sha3_384_ctx *@var{ctx})
709 Initialize the SHA3-384 state.
710 @end deftypefun
711
712 @deftypefun void sha3_384_update (struct sha3_384_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
713 Hash some more data.
714 @end deftypefun
715
716 @deftypefun void sha3_384_digest (struct sha3_384_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
717 Performs final processing and extracts the message digest, writing it
718 to @var{digest}. @var{length} may be smaller than
719 @code{SHA3_384_DIGEST_SIZE}, in which case only the first @var{length}
720 octets of the digest are written.
721
722 This function also resets the context.
723 @end deftypefun
724
725 @subsubsection @acronym{SHA3-512}
726
727 This is SHA3 with 512-bit output size.
728
729 Nettle defines SHA3-512 in @file{<nettle/sha3.h>}.
730
731 @deftp {Context struct} {struct sha3_512_ctx}
732 @end deftp
733
734 @defvr Constant SHA3_512_DIGEST_SIZE
735 The size of a SHA3_512 digest, i.e. 64.
736 @end defvr
737
738 @defvr Constant SHA3_512_BLOCK_SIZE
739 The internal block size of SHA3_512.
740 @end defvr
741
742 @deftypefun void sha3_512_init (struct sha3_512_ctx *@var{ctx})
743 Initialize the SHA3-512 state.
744 @end deftypefun
745
746 @deftypefun void sha3_512_update (struct sha3_512_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
747 Hash some more data.
748 @end deftypefun
749
750 @deftypefun void sha3_512_digest (struct sha3_512_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
751 Performs final processing and extracts the message digest, writing it
752 to @var{digest}. @var{length} may be smaller than
753 @code{SHA3_512_DIGEST_SIZE}, in which case only the first @var{length}
754 octets of the digest are written.
755
756 This function also resets the context.
757 @end deftypefun
758
759 @node Legacy hash functions, nettle_hash abstraction, Recommended hash functions, Hash functions
760 @comment  node-name,  next,  previous,  up
761 @subsection Legacy hash functions
762
763 The hash functions in this section all have some known weaknesses, and
764 should be avoided for new applications. These hash functions are mainly
765 useful for compatibility with old applications and protocols. Some are
766 still considered safe as building blocks for particular constructions,
767 e.g., there seems to be no known attacks against HMAC-SHA1 or even
768 HMAC-MD5. In some important cases, use of a ``legacy'' hash function
769 does not in itself make the application insecure; if a known weakness is
770 relevant depends on how the hash function is used, and on the threat
771 model.
772
773 @subsubsection @acronym{MD5}
774
775 MD5 is a message digest function constructed by Ronald Rivest, and
776 described in @cite{RFC 1321}. It outputs message digests of 128 bits, or
777 16 octets. Nettle defines MD5 in @file{<nettle/md5.h>}.
778
779 @deftp {Context struct} {struct md5_ctx}
780 @end deftp
781
782 @defvr Constant MD5_DIGEST_SIZE
783 The size of an MD5 digest, i.e. 16.
784 @end defvr
785
786 @defvr Constant MD5_BLOCK_SIZE
787 The internal block size of MD5. Useful for some special constructions,
788 in particular HMAC-MD5.
789 @end defvr
790
791 @deftypefun void md5_init (struct md5_ctx *@var{ctx})
792 Initialize the MD5 state.
793 @end deftypefun
794
795 @deftypefun void md5_update (struct md5_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
796 Hash some more data.
797 @end deftypefun
798
799 @deftypefun void md5_digest (struct md5_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
800 Performs final processing and extracts the message digest, writing it
801 to @var{digest}. @var{length} may be smaller than
802 @code{MD5_DIGEST_SIZE}, in which case only the first @var{length}
803 octets of the digest are written.
804
805 This function also resets the context in the same way as
806 @code{md5_init}.
807 @end deftypefun
808
809 The normal way to use MD5 is to call the functions in order: First
810 @code{md5_init}, then @code{md5_update} zero or more times, and finally
811 @code{md5_digest}. After @code{md5_digest}, the context is reset to
812 its initial state, so you can start over calling @code{md5_update} to
813 hash new data.
814
815 To start over, you can call @code{md5_init} at any time.
816
817 @subsubsection @acronym{MD2}
818
819 MD2 is another hash function of Ronald Rivest's, described in
820 @cite{RFC 1319}. It outputs message digests of 128 bits, or 16 octets.
821 Nettle defines MD2 in @file{<nettle/md2.h>}.
822
823 @deftp {Context struct} {struct md2_ctx}
824 @end deftp
825
826 @defvr Constant MD2_DIGEST_SIZE
827 The size of an MD2 digest, i.e. 16.
828 @end defvr
829
830 @defvr Constant MD2_BLOCK_SIZE
831 The internal block size of MD2.
832 @end defvr
833
834 @deftypefun void md2_init (struct md2_ctx *@var{ctx})
835 Initialize the MD2 state.
836 @end deftypefun
837
838 @deftypefun void md2_update (struct md2_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
839 Hash some more data.
840 @end deftypefun
841
842 @deftypefun void md2_digest (struct md2_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
843 Performs final processing and extracts the message digest, writing it
844 to @var{digest}. @var{length} may be smaller than
845 @code{MD2_DIGEST_SIZE}, in which case only the first @var{length}
846 octets of the digest are written.
847
848 This function also resets the context in the same way as
849 @code{md2_init}.
850 @end deftypefun
851
852 @subsubsection @acronym{MD4}
853
854 MD4 is a predecessor of MD5, described in @cite{RFC 1320}. Like MD5, it
855 is constructed by Ronald Rivest. It outputs message digests of 128 bits,
856 or 16 octets. Nettle defines MD4 in @file{<nettle/md4.h>}. Use of MD4 is
857 not recommended, but it is sometimes needed for compatibility with
858 existing applications and protocols.
859
860 @deftp {Context struct} {struct md4_ctx}
861 @end deftp
862
863 @defvr Constant MD4_DIGEST_SIZE
864 The size of an MD4 digest, i.e. 16.
865 @end defvr
866
867 @defvr Constant MD4_BLOCK_SIZE
868 The internal block size of MD4.
869 @end defvr
870
871 @deftypefun void md4_init (struct md4_ctx *@var{ctx})
872 Initialize the MD4 state.
873 @end deftypefun
874
875 @deftypefun void md4_update (struct md4_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
876 Hash some more data.
877 @end deftypefun
878
879 @deftypefun void md4_digest (struct md4_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
880 Performs final processing and extracts the message digest, writing it
881 to @var{digest}. @var{length} may be smaller than
882 @code{MD4_DIGEST_SIZE}, in which case only the first @var{length}
883 octets of the digest are written.
884
885 This function also resets the context in the same way as
886 @code{md4_init}.
887 @end deftypefun
888
889 @subsubsection @acronym{RIPEMD160}
890
891 RIPEMD160 is a hash function designed by Hans Dobbertin, Antoon
892 Bosselaers, and Bart Preneel, as a strengthened version of RIPEMD
893 (which, like MD4 and MD5, fails the collision-resistance requirement).
894 It produces message digests of 160 bits, or 20 octets. Nettle defined
895 RIPEMD160 in @file{nettle/ripemd160.h}.
896
897 @deftp {Context struct} {struct ripemd160_ctx}
898 @end deftp
899
900 @defvr Constant RIPEMD160_DIGEST_SIZE
901 The size of a RIPEMD160 digest, i.e. 20.
902 @end defvr
903
904 @defvr Constant RIPEMD160_BLOCK_SIZE
905 The internal block size of RIPEMD160.
906 @end defvr
907
908 @deftypefun void ripemd160_init (struct ripemd160_ctx *@var{ctx})
909 Initialize the RIPEMD160 state.
910 @end deftypefun
911
912 @deftypefun void ripemd160_update (struct ripemd160_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
913 Hash some more data.
914 @end deftypefun
915
916 @deftypefun void ripemd160_digest (struct ripemd160_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
917 Performs final processing and extracts the message digest, writing it
918 to @var{digest}. @var{length} may be smaller than
919 @code{RIPEMD160_DIGEST_SIZE}, in which case only the first @var{length}
920 octets of the digest are written.
921
922 This function also resets the context in the same way as
923 @code{ripemd160_init}.
924 @end deftypefun
925
926 @subsubsection @acronym{SHA1}
927
928 SHA1 is a hash function specified by @dfn{NIST} (The U.S. National
929 Institute for Standards and Technology). It outputs hash values of 160
930 bits, or 20 octets. Nettle defines SHA1 in @file{<nettle/sha1.h>} (and
931 in @file{<nettle/sha.h>}, for backwards compatibility).
932
933 @deftp {Context struct} {struct sha1_ctx}
934 @end deftp
935
936 @defvr Constant SHA1_DIGEST_SIZE
937 The size of a SHA1 digest, i.e. 20.
938 @end defvr
939
940 @defvr Constant SHA1_BLOCK_SIZE
941 The internal block size of SHA1. Useful for some special constructions,
942 in particular HMAC-SHA1.
943 @end defvr
944
945 @deftypefun void sha1_init (struct sha1_ctx *@var{ctx})
946 Initialize the SHA1 state.
947 @end deftypefun
948
949 @deftypefun void sha1_update (struct sha1_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
950 Hash some more data.
951 @end deftypefun
952
953 @deftypefun void sha1_digest (struct sha1_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
954 Performs final processing and extracts the message digest, writing it
955 to @var{digest}. @var{length} may be smaller than
956 @code{SHA1_DIGEST_SIZE}, in which case only the first @var{length}
957 octets of the digest are written.
958
959 This function also resets the context in the same way as
960 @code{sha1_init}.
961 @end deftypefun
962
963
964 @subsubsection @acronym{GOSTHASH94}
965
966 The GOST94 or GOST R 34.11-94 hash algorithm is a Soviet-era algorithm 
967 used in Russian government standards (see @cite{RFC 4357}).
968 It outputs message digests of 256 bits, or 32 octets.
969 Nettle defines GOSTHASH94 in @file{<nettle/gosthash94.h>}.
970
971 @deftp {Context struct} {struct gosthash94_ctx}
972 @end deftp
973
974 @defvr Constant GOSTHASH94_DIGEST_SIZE
975 The size of a GOSTHASH94 digest, i.e. 32.
976 @end defvr
977
978 @defvr Constant GOSTHASH94_BLOCK_SIZE
979 The internal block size of GOSTHASH94, i.e., 32.
980 @end defvr
981
982 @deftypefun void gosthash94_init (struct gosthash94_ctx *@var{ctx})
983 Initialize the GOSTHASH94 state.
984 @end deftypefun
985
986 @deftypefun void gosthash94_update (struct gosthash94_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
987 Hash some more data.
988 @end deftypefun
989
990 @deftypefun void gosthash94_digest (struct gosthash94_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
991 Performs final processing and extracts the message digest, writing it
992 to @var{digest}. @var{length} may be smaller than
993 @code{GOSTHASH94_DIGEST_SIZE}, in which case only the first @var{length}
994 octets of the digest are written.
995
996 This function also resets the context in the same way as
997 @code{gosthash94_init}.
998 @end deftypefun
999
1000 @node nettle_hash abstraction,, Legacy hash functions, Hash functions
1001 @comment  node-name,  next,  previous,  up
1002 @subsection The @code{struct nettle_hash} abstraction
1003 @cindex nettle_hash
1004 @cindex nettle_hashes
1005
1006 Nettle includes a struct including information about the supported hash
1007 functions. It is defined in @file{<nettle/nettle-meta.h>}, and is used
1008 by Nettle's implementation of @acronym{HMAC} (@pxref{Keyed hash
1009 functions}).
1010
1011 @deftp {Meta struct} @code{struct nettle_hash} name context_size digest_size block_size init update digest
1012 The last three attributes are function pointers, of types
1013 @code{nettle_hash_init_func *}, @code{nettle_hash_update_func *}, and
1014 @code{nettle_hash_digest_func *}. The first argument to these functions is
1015 @code{void *} pointer to a context struct, which is of size
1016 @code{context_size}.
1017 @end deftp
1018
1019 @deftypevr {Constant Struct} {struct nettle_hash} nettle_md2
1020 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_md4
1021 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_md5
1022 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_ripemd160
1023 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_sha1
1024 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_sha224
1025 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_sha256
1026 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_sha384
1027 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_sha512
1028 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_sha3_256
1029 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_gosthash94
1030 These are all the hash functions that Nettle implements.
1031 @end deftypevr
1032
1033 Nettle also exports a list of all these hashes.
1034
1035 @deftypevr {Constant Array} {struct nettle_hash **} nettle_hashes
1036 This list can be used to dynamically enumerate or search the supported
1037 algorithms. NULL-terminated.
1038 @end deftypevr
1039
1040 @node Cipher functions, Cipher modes, Hash functions, Reference
1041 @comment  node-name,  next,  previous,  up
1042 @section Cipher functions
1043 @cindex Cipher
1044
1045 A @dfn{cipher} is a function that takes a message or @dfn{plaintext}
1046 and a secret @dfn{key} and transforms it to a @dfn{ciphertext}. Given
1047 only the ciphertext, but not the key, it should be hard to find the
1048 plaintext. Given matching pairs of plaintext and ciphertext, it should
1049 be hard to find the key.
1050
1051 @cindex Block Cipher
1052 @cindex Stream Cipher
1053
1054 There are two main classes of ciphers: Block ciphers and stream ciphers.
1055
1056 A block cipher can process data only in fixed size chunks, called
1057 @dfn{blocks}. Typical block sizes are 8 or 16 octets. To encrypt
1058 arbitrary messages, you usually have to pad it to an integral number of
1059 blocks, split it into blocks, and then process each block. The simplest
1060 way is to process one block at a time, independent of each other. That
1061 mode of operation is called @dfn{ECB}, Electronic Code Book mode.
1062 However, using @acronym{ECB} is usually a bad idea. For a start, plaintext blocks
1063 that are equal are transformed to ciphertext blocks that are equal; that
1064 leaks information about the plaintext. Usually you should apply the
1065 cipher is some ``feedback mode'', @dfn{CBC} (Cipher Block Chaining) and
1066 @dfn{CTR} (Counter mode) being two of
1067 of the most popular. See @xref{Cipher modes}, for information on
1068 how to apply @acronym{CBC} and @acronym{CTR} with Nettle.
1069
1070 A stream cipher can be used for messages of arbitrary length. A typical
1071 stream cipher is a keyed pseudo-random generator. To encrypt a plaintext
1072 message of @var{n} octets, you key the generator, generate @var{n}
1073 octets of pseudo-random data, and XOR it with the plaintext. To decrypt,
1074 regenerate the same stream using the key, XOR it to the ciphertext, and
1075 the plaintext is recovered.
1076
1077 @strong{Caution:} The first rule for this kind of cipher is the
1078 same as for a One Time Pad: @emph{never} ever use the same key twice.
1079
1080 A common misconception is that encryption, by itself, implies
1081 authentication. Say that you and a friend share a secret key, and you
1082 receive an encrypted message. You apply the key, and get a plaintext
1083 message that makes sense to you. Can you then be sure that it really was
1084 your friend that wrote the message you're reading? The answer is no. For
1085 example, if you were using a block cipher in ECB mode, an attacker may
1086 pick up the message on its way, and reorder, delete or repeat some of
1087 the blocks. Even if the attacker can't decrypt the message, he can
1088 change it so that you are not reading the same message as your friend
1089 wrote. If you are using a block cipher in @acronym{CBC} mode rather than
1090 ECB, or are using a stream cipher, the possibilities for this sort of
1091 attack are different, but the attacker can still make predictable
1092 changes to the message.
1093
1094 It is recommended to @emph{always} use an authentication mechanism in
1095 addition to encrypting the messages. Popular choices are Message
1096 Authentication Codes like @acronym{HMAC-SHA1} (@pxref{Keyed hash
1097 functions}), or digital signatures like @acronym{RSA}.
1098
1099 Some ciphers have so called ``weak keys'', keys that results in
1100 undesirable structure after the key setup processing, and should be
1101 avoided. In Nettle, most key setup functions have no return value, but
1102 for ciphers with weak keys, the return value indicates whether or not
1103 the given key is weak. For good keys, key setup returns 1, and for weak
1104 keys, it returns 0. When possible, avoid algorithms that
1105 have weak keys. There are several good ciphers that don't have any weak
1106 keys.
1107
1108 To encrypt a message, you first initialize a cipher context for
1109 encryption or decryption with a particular key. You then use the context
1110 to process plaintext or ciphertext messages. The initialization is known
1111 as @dfn{key setup}. With Nettle, it is recommended to use each
1112 context struct for only one direction, even if some of the ciphers use a
1113 single key setup function that can be used for both encryption and
1114 decryption.
1115
1116 @subsection AES
1117 AES is a block cipher, specified by NIST as a replacement for
1118 the older DES standard. The standard is the result of a competition
1119 between cipher designers. The winning design, also known as RIJNDAEL,
1120 was constructed by Joan Daemen and Vincent Rijnmen.
1121
1122 Like all the AES candidates, the winning design uses a block size of 128
1123 bits, or 16 octets, and three possible key-size, 128, 192 and 256 bits
1124 (16, 24 and 32 octets) being the allowed key sizes. It does not have any
1125 weak keys. Nettle defines AES in @file{<nettle/aes.h>}, and there is one
1126 context struct for each key size. (Earlier versions of Nettle used a
1127 single context struct, @code{struct aes_ctx}, for all key sizes. This
1128 interface kept for backwards compatibility).
1129  
1130 @deftp {Context struct} {struct aes128_ctx}
1131 @deftpx {Context struct} {struct aes192_ctx}
1132 @deftpx {Context struct} {struct aes256_ctx}
1133 @end deftp
1134
1135 @deftp {Context struct} {struct aes_ctx}
1136 Alternative struct, for the old AES interface.
1137 @end deftp
1138
1139 @defvr Constant AES_BLOCK_SIZE
1140 The AES block-size, 16.
1141 @end defvr
1142
1143 @defvr Constant AES128_KEY_SIZE
1144 @defvrx Constant AES192_KEY_SIZE
1145 @defvrx Constant AES256_KEY_SIZE
1146 @defvrx Constant AES_MIN_KEY_SIZE
1147 @defvrx Constant AES_MAX_KEY_SIZE
1148 @end defvr
1149
1150 @defvr Constant AES_KEY_SIZE
1151 Default AES key size, 32.
1152 @end defvr
1153
1154 @deftypefun void aes128_set_encrypt_key (struct aes128_ctx *@var{ctx}, const uint8_t *@var{key})
1155 @deftypefunx void aes128_set_decrypt_key (struct aes128_ctx *@var{ctx}, const uint8_t *@var{key})
1156 @deftypefunx void aes192_set_encrypt_key (struct aes192_ctx *@var{ctx}, const uint8_t *@var{key})
1157 @deftypefunx void aes192_set_decrypt_key (struct aes192_ctx *@var{ctx}, const uint8_t *@var{key})
1158 @deftypefunx void aes256_set_encrypt_key (struct aes256_ctx *@var{ctx}, const uint8_t *@var{key})
1159 @deftypefunx void aes256_set_decrypt_key (struct aes256_ctx *@var{ctx}, const uint8_t *@var{key})
1160 @deftypefunx void aes_set_encrypt_key (struct aes_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{key})
1161 @deftypefunx void aes_set_decrypt_key (struct aes_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{key})
1162 Initialize the cipher, for encryption or decryption, respectively.
1163 @end deftypefun
1164
1165 @deftypefun void aes128_invert_key (struct aes128_ctx *@var{dst}, const struct aes128_ctx *@var{src})
1166 @deftypefunx void aes192_invert_key (struct aes192_ctx *@var{dst}, const struct aes192_ctx *@var{src})
1167 @deftypefunx void aes256_invert_key (struct aes256_ctx *@var{dst}, const struct aes256_ctx *@var{src})
1168 @deftypefunx void aes_invert_key (struct aes_ctx *@var{dst}, const struct aes_ctx *@var{src})
1169 Given a context @var{src} initialized for encryption, initializes the
1170 context struct @var{dst} for decryption, using the same key. If the same
1171 context struct is passed for both @code{src} and @code{dst}, it is
1172 converted in place. These functions are mainly useful for applications
1173 which needs to both encrypt and decrypt using the @emph{same} key,
1174 because calling, e.g., @code{aes128_set_encrypt_key} and
1175 @code{aes128_invert_key}, is more efficient than calling
1176 @code{aes128_set_encrypt_key} and @code{aes128_set_decrypt_key}.
1177 @end deftypefun
1178
1179 @deftypefun void aes128_encrypt (struct aes128_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1180 @deftypefunx void aes192_encrypt (struct aes192_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1181 @deftypefunx void aes256_encrypt (struct aes256_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1182 @deftypefunx void aes_encrypt (struct aes_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1183 Encryption function. @var{length} must be an integral multiple of the
1184 block size. If it is more than one block, the data is processed in ECB
1185 mode. @code{src} and @code{dst} may be equal, but they must not overlap
1186 in any other way.
1187 @end deftypefun
1188
1189 @deftypefun void aes128_decrypt (struct aes128_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1190 @deftypefunx void aes192_decrypt (struct aes192_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1191 @deftypefunx void aes256_decrypt (struct aes256_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1192 @deftypefunx void aes_decrypt (struct aes_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1193 Analogous to the encryption functions above.
1194 @end deftypefun
1195
1196 @subsection ARCFOUR
1197 ARCFOUR is a stream cipher, also known under the trade marked name RC4,
1198 and it is one of the fastest ciphers around. A problem is that the key
1199 setup of ARCFOUR is quite weak, you should never use keys with
1200 structure, keys that are ordinary passwords, or sequences of keys like
1201 ``secret:1'', ``secret:2'', @enddots{}. If you have keys that don't look
1202 like random bit strings, and you want to use ARCFOUR, always hash the
1203 key before feeding it to ARCFOUR. Furthermore, the initial bytes of the
1204 generated key stream leak information about the key; for this reason, it
1205 is recommended to discard the first 512 bytes of the key stream.
1206
1207 @example
1208 /* A more robust key setup function for ARCFOUR */
1209 void
1210 arcfour_set_key_hashed(struct arcfour_ctx *ctx,
1211                        size_t length, const uint8_t *key)
1212 @{
1213   struct sha256_ctx hash;
1214   uint8_t digest[SHA256_DIGEST_SIZE];
1215   uint8_t buffer[0x200];
1216
1217   sha256_init(&hash);
1218   sha256_update(&hash, length, key);
1219   sha256_digest(&hash, SHA256_DIGEST_SIZE, digest);
1220
1221   arcfour_set_key(ctx, SHA256_DIGEST_SIZE, digest);
1222   arcfour_crypt(ctx, sizeof(buffer), buffer, buffer);
1223 @}
1224 @end example
1225
1226 Nettle defines ARCFOUR in @file{<nettle/arcfour.h>}.
1227
1228 @deftp {Context struct} {struct arcfour_ctx}
1229 @end deftp
1230
1231 @defvr Constant ARCFOUR_MIN_KEY_SIZE
1232 Minimum key size, 1.
1233 @end defvr
1234
1235 @defvr Constant ARCFOUR_MAX_KEY_SIZE
1236 Maximum key size, 256.
1237 @end defvr
1238
1239 @defvr Constant ARCFOUR_KEY_SIZE
1240 Default ARCFOUR key size, 16.
1241 @end defvr
1242
1243 @deftypefun void arcfour_set_key (struct arcfour_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{key})
1244 Initialize the cipher. The same function is used for both encryption and
1245 decryption. 
1246 @end deftypefun
1247
1248 @deftypefun void arcfour_crypt (struct arcfour_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1249 Encrypt some data. The same function is used for both encryption and
1250 decryption. Unlike the block ciphers, this function modifies the
1251 context, so you can split the data into arbitrary chunks and encrypt
1252 them one after another. The result is the same as if you had called
1253 @code{arcfour_crypt} only once with all the data.
1254 @end deftypefun
1255
1256 @subsection ARCTWO
1257 ARCTWO (also known as the trade marked name RC2) is a block cipher
1258 specified in RFC 2268. Nettle also include a variation of the ARCTWO
1259 set key operation that lack one step, to be compatible with the
1260 reverse engineered RC2 cipher description, as described in a Usenet
1261 post to @code{sci.crypt} by Peter Gutmann.
1262
1263 ARCTWO uses a block size of 64 bits, and variable key-size ranging
1264 from 1 to 128 octets. Besides the key, ARCTWO also has a second
1265 parameter to key setup, the number of effective key bits, @code{ekb}.
1266 This parameter can be used to artificially reduce the key size. In
1267 practice, @code{ekb} is usually set equal to the input key size.
1268 Nettle defines ARCTWO in @file{<nettle/arctwo.h>}.
1269
1270 We do not recommend the use of ARCTWO; the Nettle implementation is
1271 provided primarily for interoperability with existing applications and
1272 standards.
1273
1274 @deftp {Context struct} {struct arctwo_ctx}
1275 @end deftp
1276
1277 @defvr Constant ARCTWO_BLOCK_SIZE
1278 The ARCTWO block-size, 8.
1279 @end defvr
1280
1281 @defvr Constant ARCTWO_MIN_KEY_SIZE
1282 @end defvr
1283
1284 @defvr Constant ARCTWO_MAX_KEY_SIZE
1285 @end defvr
1286
1287 @defvr Constant ARCTWO_KEY_SIZE
1288 Default ARCTWO key size, 8.
1289 @end defvr
1290
1291 @deftypefun void arctwo_set_key_ekb (struct arctwo_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{key}, unsigned @var{ekb})
1292 @deftypefunx void arctwo_set_key (struct arctwo_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{key})
1293 @deftypefunx void arctwo_set_key_gutmann (struct arctwo_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{key})
1294 Initialize the cipher. The same function is used for both encryption
1295 and decryption. The first function is the most general one, which lets
1296 you provide both the variable size key, and the desired effective key
1297 size (in bits). The maximum value for @var{ekb} is 1024, and for
1298 convenience, @code{ekb = 0} has the same effect as @code{ekb = 1024}.
1299
1300 @code{arctwo_set_key(ctx, length, key)} is equivalent to
1301 @code{arctwo_set_key_ekb(ctx, length, key, 8*length)}, and
1302 @code{arctwo_set_key_gutmann(ctx, length, key)} is equivalent to
1303 @code{arctwo_set_key_ekb(ctx, length, key, 1024)}
1304 @end deftypefun
1305
1306 @deftypefun void arctwo_encrypt (struct arctwo_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1307 Encryption function. @var{length} must be an integral multiple of the
1308 block size. If it is more than one block, the data is processed in ECB
1309 mode. @code{src} and @code{dst} may be equal, but they must not
1310 overlap in any other way.
1311 @end deftypefun
1312
1313 @deftypefun void arctwo_decrypt (struct arctwo_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1314 Analogous to @code{arctwo_encrypt}
1315 @end deftypefun
1316
1317 @subsection BLOWFISH
1318
1319 BLOWFISH is a block cipher designed by Bruce Schneier. It uses a block
1320 size of 64 bits (8 octets), and a variable key size, up to 448 bits. It
1321 has some weak keys. Nettle defines BLOWFISH in @file{<nettle/blowfish.h>}.
1322
1323 @deftp {Context struct} {struct blowfish_ctx}
1324 @end deftp
1325
1326 @defvr Constant BLOWFISH_BLOCK_SIZE
1327 The BLOWFISH block-size, 8.
1328 @end defvr
1329
1330 @defvr Constant BLOWFISH_MIN_KEY_SIZE
1331 Minimum BLOWFISH key size, 8.
1332 @end defvr
1333
1334 @defvr Constant BLOWFISH_MAX_KEY_SIZE
1335 Maximum BLOWFISH key size, 56.
1336 @end defvr
1337
1338 @defvr Constant BLOWFISH_KEY_SIZE
1339 Default BLOWFISH key size, 16.
1340 @end defvr
1341
1342 @deftypefun int blowfish_set_key (struct blowfish_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{key})
1343 Initialize the cipher. The same function is used for both encryption and
1344 decryption. Checks for weak keys, returning 1
1345 for good keys and 0 for weak keys. Applications that don't care about
1346 weak keys can ignore the return value.
1347
1348 @code{blowfish_encrypt} or @code{blowfish_decrypt} with a weak key will
1349 crash with an assert violation.
1350 @end deftypefun
1351
1352 @deftypefun void blowfish_encrypt (struct blowfish_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1353 Encryption function. @var{length} must be an integral multiple of the
1354 block size. If it is more than one block, the data is processed in ECB
1355 mode. @code{src} and @code{dst} may be equal, but they must not overlap
1356 in any other way.
1357 @end deftypefun
1358
1359 @deftypefun void blowfish_decrypt (struct blowfish_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1360 Analogous to @code{blowfish_encrypt}
1361 @end deftypefun
1362
1363 @subsection Camellia
1364
1365 Camellia is a block cipher developed by Mitsubishi and Nippon Telegraph
1366 and Telephone Corporation, described in @cite{RFC3713}. It is
1367 recommended by some Japanese and European authorities as an alternative
1368 to AES, and it is one of the selected algorithms in the New European
1369 Schemes for Signatures, Integrity and Encryption (NESSIE) project. The
1370 algorithm is patented. The implementation in Nettle is derived from the
1371 implementation released by NTT under the GNU LGPL (v2.1 or later), and
1372 relies on the implicit patent license of the LGPL. There is also a
1373 statement of royalty-free licensing for Camellia at
1374 @url{http://www.ntt.co.jp/news/news01e/0104/010417.html}, but this
1375 statement has some limitations which seem problematic for free software.
1376
1377 Camellia uses a the same block size and key sizes as AES: The block size
1378 is 128 bits (16 octets), and the supported key sizes are 128, 192, and
1379 256 bits. The variants with 192 and 256 bit keys are identical, except
1380 for the key setup. Nettle defines Camellia in
1381 @file{<nettle/camellia.h>}, and there is one context struct for each key
1382 size. (Earlier versions of Nettle used a single context struct,
1383 @code{struct camellia_ctx}, for all key sizes. This interface kept for
1384 backwards compatibility).
1385
1386 @deftp {Context struct} {struct camellia128_ctx}
1387 @deftpx {Context struct} {struct camellia192_ctx}
1388 @deftpx {Context struct} {struct camellia256_ctx}
1389 Contexts structs. Actually, @code{camellia192_ctx} is an alias for
1390 @code{camellia256_ctx}.
1391 @end deftp
1392
1393 @deftp {Context struct} {struct camellia_ctx}
1394 Alternative struct, for the old Camellia interface.
1395 @end deftp
1396
1397 @defvr Constant CAMELLIA_BLOCK_SIZE
1398 The CAMELLIA block-size, 16.
1399 @end defvr
1400
1401 @defvr Constant CAMELLIA128_KEY_SIZE
1402 @defvrx Constant CAMELLIA192_KEY_SIZE
1403 @defvrx Constant CAMELLIA256_KEY_SIZE
1404 @defvrx Constant CAMELLIA_MIN_KEY_SIZE
1405 @defvrx Constant CAMELLIA_MAX_KEY_SIZE
1406 @end defvr
1407
1408 @defvr Constant CAMELLIA_KEY_SIZE
1409 Default CAMELLIA key size, 32.
1410 @end defvr
1411
1412 @deftypefun void camellia128_set_encrypt_key (struct camellia128_ctx *@var{ctx}, const uint8_t *@var{key})
1413 @deftypefunx void camellia128_set_decrypt_key (struct camellia128_ctx *@var{ctx}, const uint8_t *@var{key})
1414 @deftypefunx void camellia192_set_encrypt_key (struct camellia192_ctx *@var{ctx}, const uint8_t *@var{key})
1415 @deftypefunx void camellia192_set_decrypt_key (struct camellia192_ctx *@var{ctx}, const uint8_t *@var{key})
1416 @deftypefunx void camellia256_set_encrypt_key (struct camellia256_ctx *@var{ctx}, const uint8_t *@var{key})
1417 @deftypefunx void camellia256_set_decrypt_key (struct camellia256_ctx *@var{ctx}, const uint8_t *@var{key})
1418 @deftypefunx void camellia_set_encrypt_key (struct camellia_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{key})
1419 @deftypefunx void camellia_set_decrypt_key (struct camellia_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{key})
1420 Initialize the cipher, for encryption or decryption, respectively.
1421 @end deftypefun
1422
1423 @deftypefun void camellia128_invert_key (struct camellia128_ctx *@var{dst}, const struct camellia128_ctx *@var{src})
1424 @deftypefunx void camellia192_invert_key (struct camellia192_ctx *@var{dst}, const struct camellia192_ctx *@var{src})
1425 @deftypefunx void camellia256_invert_key (struct camellia256_ctx *@var{dst}, const struct camellia256_ctx *@var{src})
1426 @deftypefunx void camellia_invert_key (struct camellia_ctx *@var{dst}, const struct camellia_ctx *@var{src})
1427 Given a context @var{src} initialized for encryption, initializes the
1428 context struct @var{dst} for decryption, using the same key. If the same
1429 context struct is passed for both @code{src} and @code{dst}, it is
1430 converted in place. These functions are mainly useful for applications
1431 which needs to both encrypt and decrypt using the @emph{same} key.
1432 @end deftypefun
1433
1434 @deftypefun void camellia128_crypt (struct camellia128_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1435 @deftypefunx void camellia192_crypt (struct camellia192_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1436 @deftypefunx void camellia256_crypt (struct camellia256_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1437 @deftypefunx void camellia_crypt (struct camellia_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1438 The same function is used for both encryption and decryption.
1439 @var{length} must be an integral multiple of the block size. If it is
1440 more than one block, the data is processed in ECB mode. @code{src} and
1441 @code{dst} may be equal, but they must not overlap in any other way.
1442 @end deftypefun
1443
1444 @subsection CAST128
1445
1446 CAST-128 is a block cipher, specified in @cite{RFC 2144}. It uses a 64
1447 bit (8 octets) block size, and a variable key size of up to 128 bits.
1448 Nettle defines cast128 in @file{<nettle/cast128.h>}.
1449
1450 @deftp {Context struct} {struct cast128_ctx}
1451 @end deftp
1452
1453 @defvr Constant CAST128_BLOCK_SIZE
1454 The CAST128 block-size, 8.
1455 @end defvr
1456
1457 @defvr Constant CAST128_MIN_KEY_SIZE
1458 Minimum CAST128 key size, 5.
1459 @end defvr
1460
1461 @defvr Constant CAST128_MAX_KEY_SIZE
1462 Maximum CAST128 key size, 16.
1463 @end defvr
1464
1465 @defvr Constant CAST128_KEY_SIZE
1466 Default CAST128 key size, 16.
1467 @end defvr
1468
1469 @deftypefun void cast128_set_key (struct cast128_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{key})
1470 Initialize the cipher. The same function is used for both encryption and
1471 decryption. 
1472 @end deftypefun
1473
1474 @deftypefun void cast128_encrypt (struct cast128_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1475 Encryption function. @var{length} must be an integral multiple of the
1476 block size. If it is more than one block, the data is processed in ECB
1477 mode. @code{src} and @code{dst} may be equal, but they must not overlap
1478 in any other way.
1479 @end deftypefun
1480
1481 @deftypefun void cast128_decrypt (struct cast128_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1482 Analogous to @code{cast128_encrypt}
1483 @end deftypefun
1484
1485 @subsection ChaCha
1486
1487 ChaCha is a variant of the stream cipher Salsa20, also designed by D. J.
1488 Bernstein. For more information on Salsa20, see below. Nettle defines
1489 ChaCha in @file{<nettle/chacha.h>}.
1490
1491 @deftp {Context struct} {struct chacha_ctx}
1492 @end deftp
1493
1494 @defvr Constant CHACHA_KEY_SIZE
1495 ChaCha key size, 32.
1496 @end defvr
1497
1498 @defvr Constant CHACHA_BLOCK_SIZE
1499 ChaCha block size, 64.
1500 @end defvr
1501
1502 @defvr Constant CHACHA_NONCE_SIZE
1503 Size of the nonce, 8.
1504 @end defvr
1505
1506 @deftypefun void chacha_set_key (struct chacha_ctx *@var{ctx}, const uint8_t *@var{key})
1507 Initialize the cipher. The same function is used for both encryption and
1508 decryption. Before using the cipher,
1509 you @emph{must} also call @code{chacha_set_nonce}, see below.
1510 @end deftypefun
1511
1512 @deftypefun void chacha_set_nonce (struct chacha_ctx *@var{ctx}, const uint8_t *@var{nonce})
1513 Sets the nonce. It is always of size @code{CHACHA_NONCE_SIZE}, 8
1514 octets. This function also initializes the block counter, setting it to
1515 zero.
1516 @end deftypefun
1517
1518 @deftypefun void chacha_crypt (struct chacha_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1519 Encrypts or decrypts the data of a message, using ChaCha. When a
1520 message is encrypted using a sequence of calls to @code{chacha_crypt},
1521 all but the last call @emph{must} use a length that is a multiple of
1522 @code{CHACHA_BLOCK_SIZE}.
1523 @end deftypefun
1524
1525 @subsection DES
1526 DES is the old Data Encryption Standard, specified by NIST. It uses a
1527 block size of 64 bits (8 octets), and a key size of 56 bits. However,
1528 the key bits are distributed over 8 octets, where the least significant
1529 bit of each octet may be used for parity. A common way to use DES is to
1530 generate 8 random octets in some way, then set the least significant bit
1531 of each octet to get odd parity, and initialize DES with the resulting
1532 key.
1533
1534 The key size of DES is so small that keys can be found by brute force,
1535 using specialized hardware or lots of ordinary work stations in
1536 parallel. One shouldn't be using plain DES at all today, if one uses
1537 DES at all one should be using ``triple DES'', see DES3 below.
1538
1539 DES also has some weak keys. Nettle defines DES in @file{<nettle/des.h>}.
1540
1541 @deftp {Context struct} {struct des_ctx}
1542 @end deftp
1543
1544 @defvr Constant DES_BLOCK_SIZE
1545 The DES block-size, 8.
1546 @end defvr
1547
1548 @defvr Constant DES_KEY_SIZE
1549 DES key size, 8.
1550 @end defvr
1551
1552 @deftypefun int des_set_key (struct des_ctx *@var{ctx}, const uint8_t *@var{key})
1553 Initialize the cipher. The same function is used for both encryption and
1554 decryption. Parity bits are ignored. Checks for weak keys, returning 1
1555 for good keys and 0 for weak keys. Applications that don't care about
1556 weak keys can ignore the return value.
1557 @end deftypefun
1558
1559 @deftypefun void des_encrypt (struct des_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1560 Encryption function. @var{length} must be an integral multiple of the
1561 block size. If it is more than one block, the data is processed in ECB
1562 mode. @code{src} and @code{dst} may be equal, but they must not overlap
1563 in any other way.
1564 @end deftypefun
1565
1566 @deftypefun void des_decrypt (struct des_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1567 Analogous to @code{des_encrypt}
1568 @end deftypefun
1569
1570 @deftypefun int des_check_parity (size_t @var{length}, const uint8_t *@var{key});
1571 Checks that the given key has correct, odd, parity. Returns 1 for
1572 correct parity, and 0 for bad parity.
1573 @end deftypefun
1574
1575 @deftypefun void des_fix_parity (size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1576 Adjusts the parity bits to match DES's requirements. You need this
1577 function if you have created a random-looking string by a key agreement
1578 protocol, and want to use it as a DES key. @var{dst} and @var{src} may
1579 be equal.
1580 @end deftypefun
1581
1582 @subsection DES3
1583 The inadequate key size of DES has already been mentioned. One way to
1584 increase the key size is to pipe together several DES boxes with
1585 independent keys. It turns out that using two DES ciphers is not as
1586 secure as one might think, even if the key size of the combination is a
1587 respectable 112 bits.
1588
1589 The standard way to increase DES's key size is to use three DES boxes.
1590 The mode of operation is a little peculiar: the middle DES box is wired
1591 in the reverse direction. To encrypt a block with DES3, you encrypt it
1592 using the first 56 bits of the key, then @emph{decrypt} it using the
1593 middle 56 bits of the key, and finally encrypt it again using the last
1594 56 bits of the key. This is known as ``ede'' triple-DES, for
1595 ``encrypt-decrypt-encrypt''.
1596
1597 The ``ede'' construction provides some backward compatibility, as you get
1598 plain single DES simply by feeding the same key to all three boxes. That
1599 should help keeping down the gate count, and the price, of hardware
1600 circuits implementing both plain DES and DES3.
1601
1602 DES3 has a key size of 168 bits, but just like plain DES, useless parity
1603 bits are inserted, so that keys are represented as 24 octets (192 bits).
1604 As a 112 bit key is large enough to make brute force attacks
1605 impractical, some applications uses a ``two-key'' variant of triple-DES.
1606 In this mode, the same key bits are used for the first and the last DES
1607 box in the pipe, while the middle box is keyed independently. The
1608 two-key variant is believed to be secure, i.e. there are no known
1609 attacks significantly better than brute force.
1610
1611 Naturally, it's simple to implement triple-DES on top of Nettle's DES
1612 functions. Nettle includes an implementation of three-key ``ede''
1613 triple-DES, it is defined in the same place as plain DES,
1614 @file{<nettle/des.h>}.
1615
1616 @deftp {Context struct} {struct des3_ctx}
1617 @end deftp
1618
1619 @defvr Constant DES3_BLOCK_SIZE
1620 The DES3 block-size is the same as DES_BLOCK_SIZE, 8.
1621 @end defvr
1622
1623 @defvr Constant DES3_KEY_SIZE
1624 DES key size, 24.
1625 @end defvr
1626
1627 @deftypefun int des3_set_key (struct des3_ctx *@var{ctx}, const uint8_t *@var{key})
1628 Initialize the cipher. The same function is used for both encryption and
1629 decryption. Parity bits are ignored. Checks for weak keys, returning 1
1630 if all three keys are good keys, and 0 if one or more key is weak.
1631 Applications that don't care about weak keys can ignore the return
1632 value.
1633 @end deftypefun
1634
1635 For random-looking strings, you can use @code{des_fix_parity} to adjust
1636 the parity bits before calling @code{des3_set_key}.
1637
1638 @deftypefun void des3_encrypt (struct des3_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1639 Encryption function. @var{length} must be an integral multiple of the
1640 block size. If it is more than one block, the data is processed in ECB
1641 mode. @code{src} and @code{dst} may be equal, but they must not overlap
1642 in any other way.
1643 @end deftypefun
1644
1645 @deftypefun void des3_decrypt (struct des3_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1646 Analogous to @code{des_encrypt}
1647 @end deftypefun
1648
1649 @subsection Salsa20
1650 Salsa20 is a fairly recent stream cipher designed by D. J. Bernstein. It
1651 is built on the observation that a cryptographic hash function can be
1652 used for encryption: Form the hash input from the secret key and a
1653 counter, xor the hash output and the first block of the plaintext, then
1654 increment the counter to process the next block (similar to CTR mode, see
1655 @pxref{CTR}). Bernstein defined an encryption algorithm, Snuffle,
1656 in this way to ridicule United States export restrictions which treated hash
1657 functions as nice and harmless, but ciphers as dangerous munitions.
1658
1659 Salsa20 uses the same idea, but with a new specialized hash function to
1660 mix key, block counter, and a couple of constants. It's also designed
1661 for speed; on x86_64, it is currently the fastest cipher offered by
1662 nettle. It uses a block size of 512 bits (64 octets) and there are two
1663 specified key sizes, 128 and 256 bits (16 and 32 octets).
1664
1665 @strong{Caution:} The hash function used in Salsa20 is @emph{not}
1666 directly applicable for use as a general hash function. It's @emph{not}
1667 collision resistant if arbitrary inputs are allowed, and furthermore,
1668 the input and output is of fixed size.
1669
1670 When using Salsa20 to process a message, one specifies both a key and a
1671 @dfn{nonce}, the latter playing a similar rôle to the initialization
1672 vector (@acronym{IV}) used with @acronym{CBC} or @acronym{CTR} mode. One
1673 can use the same key for several messages, provided one uses a unique
1674 random @acronym{iv} for each message. The @acronym{iv} is 64 bits (8
1675 octets). The block counter is initialized to zero for each message, and
1676 is also 64 bits (8 octets). Nettle defines Salsa20 in
1677 @file{<nettle/salsa20.h>}.
1678
1679 @deftp {Context struct} {struct salsa20_ctx}
1680 @end deftp
1681
1682 @defvr Constant SALSA20_128_KEY_SIZE
1683 @defvrx Constant SALSA20_256_KEY_SIZE
1684 The two supported key sizes, 16 and 32 octets.
1685 @end defvr
1686
1687 @defvr Constant SALSA20_KEY_SIZE
1688 Recommended key size, 32.
1689 @end defvr
1690
1691 @defvr Constant SALSA20_BLOCK_SIZE
1692 Salsa20 block size, 64.
1693 @end defvr
1694
1695 @defvr Constant SALSA20_NONCE_SIZE
1696 Size of the nonce, 8.
1697 @end defvr
1698
1699 @deftypefun void salsa20_128_set_key (struct salsa20_ctx *@var{ctx}, const uint8_t *@var{key})
1700 @deftypefunx void salsa20_256_set_key (struct salsa20_ctx *@var{ctx}, const uint8_t *@var{key})
1701 @deftypefunx void salsa20_set_key (struct salsa20_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{key})
1702 Initialize the cipher. The same function is used for both encryption and
1703 decryption. @code{salsa20_128_set_key} and @code{salsa20_128_set_key}
1704 use a fix key size each, 16 and 32 octets, respectively. The function
1705 @code{salsa20_set_key} is provided for backwards compatibility, and the
1706 @var{length} argument must be either 16 or 32. Before using the cipher,
1707 you @emph{must} also call @code{salsa20_set_nonce}, see below.
1708 @end deftypefun
1709
1710 @deftypefun void salsa20_set_nonce (struct salsa20_ctx *@var{ctx}, const uint8_t *@var{nonce})
1711 Sets the nonce. It is always of size @code{SALSA20_NONCE_SIZE}, 8
1712 octets. This function also initializes the block counter, setting it to
1713 zero.
1714 @end deftypefun
1715
1716 @deftypefun void salsa20_crypt (struct salsa20_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1717 Encrypts or decrypts the data of a message, using salsa20. When a
1718 message is encrypted using a sequence of calls to @code{salsa20_crypt},
1719 all but the last call @emph{must} use a length that is a multiple of
1720 @code{SALSA20_BLOCK_SIZE}.
1721 @end deftypefun
1722
1723 The full salsa20 cipher uses 20 rounds of mixing. Variants of Salsa20
1724 with fewer rounds are possible, and the 12-round variant is specified by
1725 eSTREAM, see @url{http://www.ecrypt.eu.org/stream/finallist.html}.
1726 Nettle calls this variant @code{salsa20r12}. It uses the same context
1727 struct and key setup as the full salsa20 cipher, but a separate function
1728 for encryption and decryption.
1729
1730 @deftypefun void salsa20r12_crypt (struct salsa20_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1731 Encrypts or decrypts the data of a message, using salsa20 reduced to 12
1732 rounds.
1733 @end deftypefun
1734
1735 @subsection SERPENT
1736 SERPENT is one of the AES finalists, designed by Ross Anderson, Eli
1737 Biham and Lars Knudsen. Thus, the interface and properties are similar
1738 to AES'. One peculiarity is that it is quite pointless to use it with
1739 anything but the maximum key size, smaller keys are just padded to
1740 larger ones. Nettle defines SERPENT in @file{<nettle/serpent.h>}.
1741
1742 @deftp {Context struct} {struct serpent_ctx}
1743 @end deftp
1744
1745 @defvr Constant SERPENT_BLOCK_SIZE
1746 The SERPENT block-size, 16.
1747 @end defvr
1748
1749 @defvr Constant SERPENT_MIN_KEY_SIZE
1750 Minimum SERPENT key size, 16.
1751 @end defvr
1752
1753 @defvr Constant SERPENT_MAX_KEY_SIZE
1754 Maximum SERPENT key size, 32.
1755 @end defvr
1756
1757 @defvr Constant SERPENT_KEY_SIZE
1758 Default SERPENT key size, 32.
1759 @end defvr
1760
1761 @deftypefun void serpent_set_key (struct serpent_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{key})
1762 Initialize the cipher. The same function is used for both encryption and
1763 decryption. 
1764 @end deftypefun
1765
1766 @deftypefun void serpent_encrypt (struct serpent_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1767 Encryption function. @var{length} must be an integral multiple of the
1768 block size. If it is more than one block, the data is processed in ECB
1769 mode. @code{src} and @code{dst} may be equal, but they must not overlap
1770 in any other way.
1771 @end deftypefun
1772
1773 @deftypefun void serpent_decrypt (struct serpent_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1774 Analogous to @code{serpent_encrypt}
1775 @end deftypefun
1776
1777
1778 @subsection TWOFISH
1779 Another AES finalist, this one designed by Bruce Schneier and others.
1780 Nettle defines it in @file{<nettle/twofish.h>}.
1781
1782 @deftp {Context struct} {struct twofish_ctx}
1783 @end deftp
1784
1785 @defvr Constant TWOFISH_BLOCK_SIZE
1786 The TWOFISH block-size, 16.
1787 @end defvr
1788
1789 @defvr Constant TWOFISH_MIN_KEY_SIZE
1790 Minimum TWOFISH key size, 16.
1791 @end defvr
1792
1793 @defvr Constant TWOFISH_MAX_KEY_SIZE
1794 Maximum TWOFISH key size, 32.
1795 @end defvr
1796
1797 @defvr Constant TWOFISH_KEY_SIZE
1798 Default TWOFISH key size, 32.
1799 @end defvr
1800
1801 @deftypefun void twofish_set_key (struct twofish_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{key})
1802 Initialize the cipher. The same function is used for both encryption and
1803 decryption. 
1804 @end deftypefun
1805
1806 @deftypefun void twofish_encrypt (struct twofish_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1807 Encryption function. @var{length} must be an integral multiple of the
1808 block size. If it is more than one block, the data is processed in ECB
1809 mode. @code{src} and @code{dst} may be equal, but they must not overlap
1810 in any other way.
1811 @end deftypefun
1812
1813 @deftypefun void twofish_decrypt (struct twofish_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1814 Analogous to @code{twofish_encrypt}
1815 @end deftypefun
1816
1817 @c @node nettle_cipher, Cipher Block Chaining, Cipher functions, Reference
1818 @c @comment  node-name,  next,  previous,  up
1819 @subsection The @code{struct nettle_cipher} abstraction
1820 @cindex nettle_cipher
1821 @cindex nettle_ciphers
1822
1823 Nettle includes a struct including information about some of the more
1824 regular cipher functions. It can be useful for applications that need a
1825 simple way to handle various algorithms. Nettle defines these structs in
1826 @file{<nettle/nettle-meta.h>}.
1827
1828 @deftp {Meta struct} @code{struct nettle_cipher} name context_size block_size key_size set_encrypt_key set_decrypt_key encrypt decrypt
1829 The last four attributes are function pointers, of types
1830 @code{nettle_set_key_func *} and @code{nettle_cipher_func *}. The first
1831 argument to these functions is a @code{const void *} pointer to a context
1832 struct, which is of size @code{context_size}.
1833 @end deftp
1834
1835 @deftypevr {Constant Struct} {struct nettle_cipher} nettle_aes128
1836 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_aes192
1837 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_aes256
1838
1839 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arctwo40
1840 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arctwo64
1841 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arctwo128
1842 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arctwo_gutmann128
1843
1844 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arcfour128
1845
1846 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_camellia128
1847 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_camellia192
1848 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_camellia256
1849
1850 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_cast128
1851
1852 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_serpent128
1853 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_serpent192
1854 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_serpent256
1855
1856 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_twofish128
1857 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_twofish192
1858 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_twofish256
1859 Nettle includes such structs for all the @emph{regular} ciphers, i.e.
1860 ones without weak keys or other oddities.
1861 @end deftypevr
1862
1863 Nettle also exports a list of all these ciphers without weak keys or
1864 other oddities.
1865
1866 @deftypevr {Constant Array} {struct nettle_cipher **} nettle_ciphers
1867 This list can be used to dynamically enumerate or search the supported
1868 algorithms. NULL-terminated.
1869 @end deftypevr
1870
1871 @node Cipher modes, Authenticated encryption, Cipher functions, Reference
1872 @comment  node-name,  next,  previous,  up
1873 @section Cipher modes
1874
1875 Cipher modes of operation specifies the procedure to use when encrypting
1876 a message that is larger than the cipher's block size. As explained in
1877 @xref{Cipher functions}, splitting the message into blocks and
1878 processing them independently with the block cipher (Electronic Code
1879 Book mode, @acronym{ECB}), leaks information.
1880
1881 Besides @acronym{ECB}, Nettle provides a two other modes of operation:
1882 Cipher Block Chaining (@acronym{CBC}), Counter mode (@acronym{CTR}), and
1883 a couple of @acronym{AEAD} modes (@pxref{Authenticated encryption}).
1884 @acronym{CBC} is widely used, but there are a few subtle issues of
1885 information leakage, see, e.g.,
1886 @uref{http://www.kb.cert.org/vuls/id/958563, @acronym{SSH} @acronym{CBC}
1887 vulnerability}. Today, @acronym{CTR} is usually preferred over @acronym{CBC}.
1888
1889 Modes like @acronym{CBC} and @acronym{CTR} provide @emph{no} message
1890 authentication, and should always be used together with a @acronym{MAC}
1891 (@pxref{Keyed hash functions}) or signature to authenticate the message.
1892
1893 @menu
1894 * CBC::                         
1895 * CTR::                         
1896 @end menu
1897
1898 @node CBC, CTR, Cipher modes, Cipher modes
1899 @comment  node-name,  next,  previous,  up
1900 @subsection Cipher Block Chaining
1901
1902 @cindex Cipher Block Chaining
1903 @cindex CBC Mode
1904
1905 When using @acronym{CBC} mode, plaintext blocks are not encrypted
1906 independently of each other, like in Electronic Cook Book mode. Instead,
1907 when encrypting a block in @acronym{CBC} mode, the previous ciphertext
1908 block is XORed with the plaintext before it is fed to the block cipher.
1909 When encrypting the first block, a random block called an @dfn{IV}, or
1910 Initialization Vector, is used as the ``previous ciphertext block''. The
1911 IV should be chosen randomly, but it need not be kept secret, and can
1912 even be transmitted in the clear together with the encrypted data.
1913
1914 In symbols, if @code{E_k} is the encryption function of a block cipher,
1915 and @code{IV} is the initialization vector, then @code{n} plaintext blocks
1916 @code{M_1},@dots{} @code{M_n} are transformed into @code{n} ciphertext blocks
1917 @code{C_1},@dots{} @code{C_n} as follows:
1918
1919 @example
1920 C_1 = E_k(IV  XOR M_1)
1921 C_2 = E_k(C_1 XOR M_2)
1922
1923 @dots{}
1924
1925 C_n = E_k(C_(n-1) XOR M_n)
1926 @end example
1927
1928 Nettle's includes two functions for applying a block cipher in Cipher
1929 Block Chaining (@acronym{CBC}) mode, one for encryption and one for
1930 decryption. These functions uses @code{void *} to pass cipher contexts
1931 around.
1932
1933 @deftypefun {void} cbc_encrypt (const void *@var{ctx}, nettle_cipher_func *@var{f}, size_t @var{block_size}, uint8_t *@var{iv}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1934 @deftypefunx {void} cbc_decrypt (const void *@var{ctx}, nettle_cipher_func *@var{f}, size_t @var{block_size}, uint8_t *@var{iv}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1935
1936 Applies the encryption or decryption function @var{f} in @acronym{CBC}
1937 mode. The final ciphertext block processed is copied into @var{iv}
1938 before returning, so that large message be processed be a sequence of
1939 calls to @code{cbc_encrypt}. The function @var{f} is of type
1940
1941 @code{void f (void *@var{ctx}, size_t @var{length}, uint8_t @var{dst},
1942 const uint8_t *@var{src})},
1943
1944 @noindent and the @code{cbc_encrypt} and @code{cbc_decrypt} functions pass their
1945 argument @var{ctx} on to @var{f}.
1946 @end deftypefun
1947
1948 There are also some macros to help use these functions correctly.
1949
1950 @deffn Macro CBC_CTX (@var{context_type}, @var{block_size})
1951 Expands to
1952 @example
1953 @{
1954    context_type ctx;
1955    uint8_t iv[block_size];
1956 @}
1957 @end example
1958 @end deffn
1959
1960 It can be used to define a @acronym{CBC} context struct, either directly,
1961
1962 @example
1963 struct CBC_CTX(struct aes_ctx, AES_BLOCK_SIZE) ctx;
1964 @end example
1965
1966 or to give it a struct tag,
1967
1968 @example
1969 struct aes_cbc_ctx CBC_CTX (struct aes_ctx, AES_BLOCK_SIZE);
1970 @end example
1971
1972 @deffn Macro CBC_SET_IV (@var{ctx}, @var{iv})
1973 First argument is a pointer to a context struct as defined by @code{CBC_CTX},
1974 and the second is a pointer to an Initialization Vector (IV) that is
1975 copied into that context.
1976 @end deffn
1977
1978 @deffn Macro CBC_ENCRYPT (@var{ctx}, @var{f}, @var{length}, @var{dst}, @var{src})
1979 @deffnx Macro CBC_DECRYPT (@var{ctx}, @var{f}, @var{length}, @var{dst}, @var{src})
1980 A simpler way to invoke @code{cbc_encrypt} and @code{cbc_decrypt}. The
1981 first argument is a pointer to a context struct as defined by
1982 @code{CBC_CTX}, and the second argument is an encryption or decryption
1983 function following Nettle's conventions. The last three arguments define
1984 the source and destination area for the operation.
1985 @end deffn
1986
1987 These macros use some tricks to make the compiler display a warning if
1988 the types of @var{f} and @var{ctx} don't match, e.g. if you try to use
1989 an @code{struct aes_ctx} context with the @code{des_encrypt} function.
1990
1991 @node CTR, , CBC, Cipher modes
1992 @comment  node-name,  next,  previous,  up
1993 @subsection Counter mode
1994
1995 @cindex Counter Mode
1996 @cindex CTR Mode
1997
1998 Counter mode (@acronym{CTR}) uses the block cipher as a keyed
1999 pseudo-random generator. The output of the generator is XORed with the
2000 data to be encrypted. It can be understood as a way to transform a block
2001 cipher to a stream cipher.
2002
2003 The message is divided into @code{n} blocks @code{M_1},@dots{}
2004 @code{M_n}, where @code{M_n} is of size @code{m} which may be smaller
2005 than the block size. Except for the last block, all the message blocks
2006 must be of size equal to the cipher's block size.
2007
2008 If @code{E_k} is the encryption function of a block cipher, @code{IC} is
2009 the initial counter, then the @code{n} plaintext blocks are
2010 transformed into @code{n} ciphertext blocks @code{C_1},@dots{}
2011 @code{C_n} as follows:
2012
2013 @example
2014 C_1 = E_k(IC) XOR M_1
2015 C_2 = E_k(IC + 1) XOR M_2
2016
2017 @dots{}
2018
2019 C_(n-1) = E_k(IC + n - 2) XOR M_(n-1)
2020 C_n = E_k(IC + n - 1) [1..m] XOR M_n
2021 @end example
2022
2023 The @acronym{IC} is the initial value for the counter, it plays a
2024 similar rôle as the @acronym{IV} for @acronym{CBC}. When adding,
2025 @code{IC + x}, @acronym{IC} is interpreted as an integer, in network
2026 byte order. For the last block, @code{E_k(IC + n - 1) [1..m]} means that
2027 the cipher output is truncated to @code{m} bytes.
2028
2029 @deftypefun {void} ctr_crypt (const void *@var{ctx}, nettle_cipher_func *@var{f}, size_t @var{block_size}, uint8_t *@var{ctr}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2030
2031 Applies the encryption function @var{f} in @acronym{CTR} mode. Note that
2032 for @acronym{CTR} mode, encryption and decryption is the same operation,
2033 and hence @var{f} should always be the encryption function for the
2034 underlying block cipher.
2035
2036 When a message is encrypted using a sequence of calls to
2037 @code{ctr_crypt}, all but the last call @emph{must} use a length that is
2038 a multiple of the block size.
2039 @end deftypefun
2040
2041 Like for @acronym{CBC}, there are also a couple of helper macros.
2042
2043 @deffn Macro CTR_CTX (@var{context_type}, @var{block_size})
2044 Expands to
2045 @example
2046 @{
2047    context_type ctx;
2048    uint8_t ctr[block_size];
2049 @}
2050 @end example
2051 @end deffn
2052
2053 @deffn Macro CTR_SET_COUNTER (@var{ctx}, @var{iv})
2054 First argument is a pointer to a context struct as defined by
2055 @code{CTR_CTX}, and the second is a pointer to an initial counter that
2056 is copied into that context.
2057 @end deffn
2058
2059 @deffn Macro CTR_CRYPT (@var{ctx}, @var{f}, @var{length}, @var{dst}, @var{src})
2060 A simpler way to invoke @code{ctr_crypt}. The first argument is a
2061 pointer to a context struct as defined by @code{CTR_CTX}, and the second
2062 argument is an encryption function following Nettle's conventions. The
2063 last three arguments define the source and destination area for the
2064 operation.
2065 @end deffn
2066
2067 @node Authenticated encryption, Keyed hash functions, Cipher modes, Reference
2068 @comment  node-name,  next,  previous,  up
2069
2070 @section Authenticated encryption with associated data
2071 @cindex AEAD
2072 @cindex Authenticated encryption
2073
2074 Since there are some subtle design choices to be made when combining a
2075 block cipher mode with out authentication with a @acronym{MAC}. In
2076 recent years, several constructions that combine encryption and
2077 authentication have been defined. These constructions typically also
2078 have an additional input, the ``associated data'', which is
2079 authenticated but not included with the message. A simple example is an
2080 implicit message number which is available at both sender and receiver,
2081 and which needs authentication in order to detect deletions or replay of
2082 messages. This family of building blocks are therefore called
2083 @acronym{AEAD}, Authenticated encryption with associated data.
2084
2085 The aim is to provide building blocks that it is easier for designers of
2086 protocols and applications to use correctly. There is also some
2087 potential for improved performance, if encryption and authentication can
2088 be done in a single step, although that potential is not realized for
2089 the constructions currently supported by Nettle.
2090
2091 For encryption, the inputs are:
2092
2093 @itemize
2094 @item
2095 The key, which can be used for many messages.
2096 @item 
2097 A nonce, which must be unique for each message using the same key.
2098 @item
2099 Additional associated data to be authenticated, but not included in the
2100 message.
2101 @item
2102 The cleartext message to be encrypted.
2103 @end itemize
2104
2105 The outputs are:
2106
2107 @itemize
2108 @item
2109 The ciphertext, of the same size as the cleartext.
2110 @item
2111 A digest or ``authentication tag''.
2112 @end itemize
2113
2114 Decryption works the same, but with cleartext and ciphertext
2115 interchanged. All currently supported @acronym{AEAD} algorithms always
2116 use the encryption function of the underlying block cipher, for both
2117 encryption and decryption.
2118
2119 Usually, the authentication tag should be appended at the end of the
2120 ciphertext, producing an encrypted message which is slightly longer than
2121 the cleartext. However, Nettle's low level @acronym{AEAD} functions
2122 produce the authentication tag as a separate output for both encryption
2123 and decryption.
2124
2125 Both associated data and the message data (cleartext or ciphertext) can
2126 be processed incrementally. In general, all associated data must be
2127 processed before the message data, and all calls but the last one must
2128 use a length that is a multiple of the block size, although some
2129 @acronym{AEAD} may implement more liberal conventions. The @acronym{CCM}
2130 mode is a bit special in that it requires the message lengths up front,
2131 other @acronym{AEAD} constructions don't have this restriction.
2132
2133 The supported @acronym{AEAD} constructions are Galois/Counter mode
2134 (@acronym{GCM}), @acronym{EAX}, ChaCha-Poly1305, and Counter with
2135 @acronym{CBC}-@acronym{MAC} (@acronym{CCM}). There are some weaknesses
2136 in @acronym{GCM} authentication, see
2137 @uref{http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/comments/CWC-GCM/Ferguson2.pdf}.
2138 @acronym{CCM} and @acronym{EAX} use the same building blocks, but the
2139 @acronym{EAX} design is cleaner and avoids a couple of inconveniences of
2140 @acronym{CCM}. Therefore, @acronym{EAX} seems like a good conservative
2141 choice. The more recent ChaCha-Poly1305 may also be an attractive but
2142 more adventurous alternative, in particular if performance is important.
2143
2144 @menu
2145 * EAX::                         
2146 * GCM::                         
2147 * CCM::                         
2148 * ChaCha-Poly1305::
2149 * nettle_aead abstraction::
2150 @end menu
2151
2152 @node EAX, GCM, Authenticated encryption, Authenticated encryption
2153 @comment  node-name,  next,  previous,  up
2154 @subsection EAX
2155
2156 The @acronym{EAX} mode is an @acronym{AEAD} mode whichcombines
2157 @acronym{CTR} mode encryption, @xref{CTR}, with a message authentication
2158 based on @acronym{CBC}, @xref{CBC}. The implementation in Nettle is
2159 restricted to ciphers with a block size of 128 bits (16 octets).
2160 @acronym{EAX} was defined as a reaction to the @acronym{CCM} mode,
2161 @xref{CCM}, which uses the same primitives but has some undesirable and
2162 inelegant properties.
2163
2164 @acronym{EAX} supports arbitrary nonce size; it's even possible to use
2165 an empty nonce in case only a single message is encrypted for each key. 
2166
2167 Nettle's support for @acronym{EAX} consists of a low-level general
2168 interface, some convenience macros, and specific functions for
2169 @acronym{EAX} using @acronym{AES}-128 as the underlying cipher. These
2170 interfaces are defined in @file{<nettle/eax.h>}
2171
2172 @subsubsection General @acronym{EAX} interface
2173
2174 @deftp {Context struct} {struct eax_key}
2175 @acronym{EAX} state which depends only on the key, but not on the nonce
2176 or the message.
2177 @end deftp
2178
2179 @deftp {Context struct} {struct eax_ctx}
2180 Holds state corresponding to a particular message.
2181 @end deftp
2182
2183 @defvr Constant EAX_BLOCK_SIZE
2184 @acronym{EAX}'s block size, 16.
2185 @end defvr
2186
2187 @defvr Constant EAX_DIGEST_SIZE
2188 Size of the @acronym{EAX} digest, also 16.
2189 @end defvr
2190
2191 @deftypefun void eax_set_key (struct eax_key *@var{key}, const void *@var{cipher}, nettle_cipher_func *@var{f})
2192 Initializes @var{key}. @var{cipher} gives a context struct for the
2193 underlying cipher, which must have been previously initialized for
2194 encryption, and @var{f} is the encryption function.
2195 @end deftypefun
2196
2197 @deftypefun void eax_set_nonce (struct eax_ctx *@var{eax}, const struct eax_key *@var{key}, const void *@var{cipher}, nettle_cipher_func *@var{f}, size_t @var{nonce_length}, const uint8_t *@var{nonce})
2198 Initializes @var{ctx} for processing a new message, using the given
2199 nonce.
2200 @end deftypefun
2201
2202 @deftypefun void eax_update (struct eax_ctx *@var{eax}, const struct eax_key *@var{key}, const void *@var{cipher}, nettle_cipher_func *@var{f}, size_t @var{data_length}, const uint8_t *@var{data})
2203 Process associated data for authentication. All but the last call for
2204 each message @emph{must} use a length that is a multiple of the block
2205 size. Unlike many other @acronym{AEAD} constructions, for @acronym{EAX}
2206 it's not necessary to complete the processing of all associated data
2207 before encrypting or decrypting the message data.
2208 @end deftypefun
2209
2210 @deftypefun void eax_encrypt (struct eax_ctx *@var{eax}, const struct eax_key *@var{key}, const void *@var{cipher}, nettle_cipher_func *@var{f}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2211 @deftypefunx void eax_decrypt (struct eax_ctx *@var{eax}, const struct eax_key *@var{key}, const void *@var{cipher}, nettle_cipher_func *@var{f}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2212 Encrypts or decrypts the data of a message. @var{cipher} is the context
2213 struct for the underlying cipher and @var{f} is the encryption function.
2214 All but the last call for each message @emph{must} use a length that is
2215 a multiple of the block size.
2216 @end deftypefun
2217
2218 @deftypefun void eax_digest (struct eax_ctx *@var{eax}, const struct eax_key *@var{key}, const void *@var{cipher}, nettle_cipher_func *@var{f}, size_t @var{length}, uint8_t *@var{digest});
2219 Extracts the message digest (also known ``authentication tag''). This is
2220 the final operation when processing a message. If @var{length} is
2221 smaller than @code{EAX_DIGEST_SIZE}, only the first @var{length} octets
2222 of the digest are written.
2223 @end deftypefun
2224
2225
2226 @subsubsection @acronym{EAX} helper macros
2227
2228 The following macros are defined.
2229
2230 @deffn Macro EAX_CTX (@var{context_type})
2231 This defines an all-in-one context struct, including the context of the
2232 underlying cipher and all @acronym{EAX} state. It expands
2233 to
2234 @example
2235 @{
2236    struct eax_key key;
2237    struct eax_ctx eax;
2238    context_type cipher;
2239 @}
2240 @end example
2241 @end deffn
2242
2243 For all these macros, @var{ctx}, is a context struct as defined by
2244 @code{EAX_CTX}, and @var{encrypt} is the encryption function of the
2245 underlying cipher.
2246
2247 @deffn Macro EAX_SET_KEY (@var{ctx}, @var{set_key}, @var{encrypt}, @var{key})
2248 @var{set_key} is the function for setting the encryption key for the
2249 underlying cipher, and @var{key} is the key.
2250 @end deffn
2251
2252 @deffn Macro EAX_SET_NONCE (@var{ctx}, @var{encrypt}, @var{length}, @var{nonce})
2253 Sets the nonce to be used for the message.
2254 @end deffn
2255
2256 @deffn Macro EAX_UPDATE (@var{ctx}, @var{encrypt}, @var{length}, @var{data})
2257 Process associated data for authentication.
2258 @end deffn
2259
2260 @deffn Macro EAX_ENCRYPT (@var{ctx}, @var{encrypt}, @var{length}, @var{dst}, @var{src})
2261 @deffnx Macro EAX_DECRYPT (@var{ctx}, @var{encrypt}, @var{length}, @var{dst}, @var{src})
2262 Process message data for encryption or decryption.
2263 @end deffn
2264
2265 @deffn Macro EAX_DIGEST (@var{ctx}, @var{encrypt}, @var{length}, @var{digest})
2266 Extract te authentication tag for the message.
2267 @end deffn
2268
2269
2270 @subsubsection @acronym{EAX}-@acronym{AES}128 interface
2271
2272 The following functions implement @acronym{EAX} using @acronym{AES}-128
2273 as the underlying cipher.
2274
2275 @deftp {Context struct} {struct eax_aes128_ctx}
2276 The context struct, defined using @code{EAX_CTX}.
2277 @end deftp
2278
2279 @deftypefun void eax_aes128_set_key (struct eax_aes128_ctx *@var{ctx}, const uint8_t *@var{key})
2280 Initializes @var{ctx} using the given key.
2281 @end deftypefun
2282
2283 @deftypefun void eax_aes128_set_nonce (struct eax_aes128_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{iv})
2284 Initializes the per-message state, using the given nonce.
2285 @end deftypefun
2286
2287 @deftypefun void eax_aes128_update (struct eax_aes128_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
2288 Process associated data for authentication. All but the last call for
2289 each message @emph{must} use a length that is a multiple of the block
2290 size.
2291 @end deftypefun
2292
2293 @deftypefun void eax_aes128_encrypt (struct eax_aes128_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2294 @deftypefunx void eax_aes128_decrypt (struct eax_aes128_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2295 Encrypts or decrypts the data of a message. All but the last call for
2296 each message @emph{must} use a length that is a multiple of the block
2297 size.
2298 @end deftypefun
2299
2300 @deftypefun void eax_aes128_digest (struct eax_aes128_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest});
2301 Extracts the message digest (also known ``authentication tag''). This is
2302 the final operation when processing a message. If @var{length} is
2303 smaller than @code{EAX_DIGEST_SIZE}, only the first @var{length} octets
2304 of the digest are written.
2305 @end deftypefun
2306
2307 @node GCM, CCM, EAX, Authenticated encryption
2308 @comment  node-name,  next,  previous,  up
2309 @subsection Galois counter mode
2310
2311 @cindex Galois Counter Mode
2312 @cindex GCM
2313
2314 Galois counter mode is an @acronym{AEAD} constructions combining counter
2315 mode with message authentication based on universal hashing. The main
2316 objective of the design is to provide high performance for hardware
2317 implementations, where other popular @acronym{MAC} algorithms
2318 (@pxref{Keyed hash functions}) become a bottleneck for high-speed
2319 hardware implementations. It was proposed by David A. McGrew and John
2320 Viega in 2005, and recommended by NIST in 2007,
2321 @uref{http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf,
2322 NIST Special Publication 800-38D}. It is constructed on top of a block
2323 cipher which must have a block size of 128 bits.
2324
2325 The authentication in @acronym{GCM} has some known weaknesses, see
2326 @uref{http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/comments/CWC-GCM/Ferguson2.pdf}.
2327 In particular, don't use @acronym{GCM} with short authentication tags.
2328
2329 Nettle's support for @acronym{GCM} consists of a low-level general
2330 interface, some convenience macros, and specific functions for
2331 @acronym{GCM} using @acronym{AES} or Camellia as the underlying cipher.
2332 These interfaces are defined in @file{<nettle/gcm.h>}
2333
2334 @subsubsection General @acronym{GCM} interface
2335
2336 @deftp {Context struct} {struct gcm_key}
2337 Message independent hash sub-key, and related tables.
2338 @end deftp
2339
2340 @deftp {Context struct} {struct gcm_ctx}
2341 Holds state corresponding to a particular message.
2342 @end deftp
2343
2344 @defvr Constant GCM_BLOCK_SIZE
2345 @acronym{GCM}'s block size, 16.
2346 @end defvr
2347
2348 @defvr Constant GCM_DIGEST_SIZE
2349 Size of the @acronym{GCM} digest, also 16.
2350 @end defvr
2351
2352 @defvr Constant GCM_IV_SIZE
2353 Recommended size of the @acronym{IV}, 12. Arbitrary sizes are allowed.
2354 @end defvr
2355
2356 @deftypefun void gcm_set_key (struct gcm_key *@var{key}, const void *@var{cipher}, nettle_cipher_func *@var{f})
2357 Initializes @var{key}. @var{cipher} gives a context struct for the
2358 underlying cipher, which must have been previously initialized for
2359 encryption, and @var{f} is the encryption function.
2360 @end deftypefun
2361
2362 @deftypefun void gcm_set_iv (struct gcm_ctx *@var{ctx}, const struct gcm_key *@var{key}, size_t @var{length}, const uint8_t *@var{iv})
2363 Initializes @var{ctx} using the given @acronym{IV}. The @var{key}
2364 argument is actually needed only if @var{length} differs from
2365 @code{GCM_IV_SIZE}.
2366 @end deftypefun
2367
2368 @deftypefun void gcm_update (struct gcm_ctx *@var{ctx}, const struct gcm_key *@var{key}, size_t @var{length}, const uint8_t *@var{data})
2369 Provides associated data to be authenticated. If used, must be called
2370 before @code{gcm_encrypt} or @code{gcm_decrypt}. All but the last call
2371 for each message @emph{must} use a length that is a multiple of the
2372 block size.
2373 @end deftypefun
2374
2375 @deftypefun void gcm_encrypt (struct gcm_ctx *@var{ctx}, const struct gcm_key *@var{key}, const void *@var{cipher}, nettle_cipher_func *@var{f}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2376 @deftypefunx void gcm_decrypt (struct gcm_ctx *@var{ctx}, const struct gcm_key *@var{key}, const void *@var{cipher}, nettle_cipher_func *@var{f}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2377 Encrypts or decrypts the data of a message. @var{cipher} is the context
2378 struct for the underlying cipher and @var{f} is the encryption function.
2379 All but the last call for each message @emph{must} use a length that is
2380 a multiple of the block size.
2381 @end deftypefun
2382
2383 @deftypefun void gcm_digest (struct gcm_ctx *@var{ctx}, const struct gcm_key *@var{key}, const void *@var{cipher}, nettle_cipher_func *@var{f}, size_t @var{length}, uint8_t *@var{digest})
2384 Extracts the message digest (also known ``authentication tag''). This is
2385 the final operation when processing a message. It's strongly recommended
2386 that @var{length} is @code{GCM_DIGEST_SIZE}, but if you provide a smaller
2387 value, only the first @var{length} octets of the digest are written.
2388 @end deftypefun
2389
2390 To encrypt a message using @acronym{GCM}, first initialize a context for
2391 the underlying block cipher with a key to use for encryption. Then call
2392 the above functions in the following order: @code{gcm_set_key},
2393 @code{gcm_set_iv}, @code{gcm_update}, @code{gcm_encrypt},
2394 @code{gcm_digest}. The decryption procedure is analogous, just calling
2395 @code{gcm_decrypt} instead of @code{gcm_encrypt} (note that
2396 @acronym{GCM} decryption still uses the encryption function of the
2397 underlying block cipher). To process a new message, using the same key,
2398 call @code{gcm_set_iv} with a new @acronym{iv}.
2399
2400 @subsubsection @acronym{GCM} helper macros
2401
2402 The following macros are defined.
2403
2404 @deffn Macro GCM_CTX (@var{context_type})
2405 This defines an all-in-one context struct, including the context of the
2406 underlying cipher, the hash sub-key, and the per-message state. It expands
2407 to
2408 @example
2409 @{
2410    struct gcm_key key; 
2411    struct gcm_ctx gcm;
2412    context_type cipher;
2413 @}
2414 @end example
2415 @end deffn
2416
2417 Example use:
2418 @example
2419 struct gcm_aes128_ctx GCM_CTX(struct aes128_ctx);
2420 @end example
2421
2422 The following macros operate on context structs of this form.
2423
2424 @deffn Macro GCM_SET_KEY (@var{ctx}, @var{set_key}, @var{encrypt}, @var{key})
2425 First argument, @var{ctx}, is a context struct as defined
2426 by @code{GCM_CTX}. @var{set_key} and @var{encrypt} are functions for
2427 setting the encryption key and for encrypting data using the underlying
2428 cipher.
2429 @end deffn
2430
2431 @deffn Macro GCM_SET_IV (@var{ctx}, @var{length}, @var{data})
2432 First argument is a context struct as defined by
2433 @code{GCM_CTX}. @var{length} and @var{data} give the initialization
2434 vector (@acronym{IV}).
2435 @end deffn
2436
2437 @deffn Macro GCM_UPDATE (@var{ctx}, @var{length}, @var{data})
2438 Simpler way to call @code{gcm_update}. First argument is a context
2439 struct as defined by @code{GCM_CTX}
2440 @end deffn
2441
2442 @deffn Macro GCM_ENCRYPT (@var{ctx}, @var{encrypt}, @var{length}, @var{dst}, @var{src})
2443 @deffnx Macro GCM_DECRYPT (@var{ctx}, @var{encrypt}, @var{length}, @var{dst}, @var{src})
2444 @deffnx Macro GCM_DIGEST (@var{ctx}, @var{encrypt}, @var{length}, @var{digest})
2445 Simpler way to call @code{gcm_encrypt}, @code{gcm_decrypt} or
2446 @code{gcm_digest}. First argument is a context struct as defined by
2447 @code{GCM_CTX}. Second argument, @var{encrypt}, is the encryption
2448 function of the underlying cipher.
2449 @end deffn
2450
2451 @subsubsection @acronym{GCM}-@acronym{AES} interface
2452
2453 The following functions implement the common case of @acronym{GCM} using
2454 @acronym{AES} as the underlying cipher. The variants with a specific
2455 @acronym{AES} flavor are recommended, while the fucntinos using
2456 @code{struct gcm_aes_ctx} are kept for compatibility with older versiosn
2457 of Nettle.
2458
2459 @deftp {Context struct} {struct gcm_aes128_ctx}
2460 @deftpx {Context struct} {struct gcm_aes192_ctx}
2461 @deftpx {Context struct} {struct gcm_aes256_ctx}
2462 Context structs, defined using @code{GCM_CTX}.
2463 @end deftp
2464
2465 @deftp {Context struct} {struct gcm_aes_ctx}
2466 Alternative context struct, usign the old @acronym{AES} interface.
2467 @end deftp
2468
2469 @deftypefun void gcm_aes128_set_key (struct gcm_aes128_ctx *@var{ctx}, const uint8_t *@var{key})
2470 @deftypefunx void gcm_aes192_set_key (struct gcm_aes192_ctx *@var{ctx}, const uint8_t *@var{key})
2471 @deftypefunx void gcm_aes256_set_key (struct gcm_aes256_ctx *@var{ctx}, const uint8_t *@var{key})
2472 Initializes @var{ctx} using the given key.
2473 @end deftypefun
2474
2475 @deftypefun void gcm_aes_set_key (struct gcm_aes_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{key})
2476 Corresponding function, using the old @acronym{AES} interface. All valid
2477 @acronym{AES} key sizes can be used.
2478 @end deftypefun
2479
2480 @deftypefun void gcm_aes128_set_iv (struct gcm_aes128_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{iv})
2481 @deftypefunx void gcm_aes192_set_iv (struct gcm_aes192_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{iv})
2482 @deftypefunx void gcm_aes256_set_iv (struct gcm_aes256_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{iv})
2483 @deftypefunx void gcm_aes_set_iv (struct gcm_aes_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{iv})
2484 Initializes the per-message state, using the given @acronym{IV}.
2485 @end deftypefun
2486
2487 @deftypefun void gcm_aes128_update (struct gcm_aes128_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
2488 @deftypefunx void gcm_aes192_update (struct gcm_aes192_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
2489 @deftypefunx void gcm_aes256_update (struct gcm_aes256_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
2490 @deftypefunx void gcm_aes_update (struct gcm_aes_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
2491 Provides associated data to be authenticated. If used, must be called
2492 before @code{gcm_aes_encrypt} or @code{gcm_aes_decrypt}. All but the
2493 last call for each message @emph{must} use a length that is a multiple
2494 of the block size.
2495 @end deftypefun
2496
2497 @deftypefun void gcm_aes128_encrypt (struct gcm_aes128_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2498 @deftypefunx void gcm_aes192_encrypt (struct gcm_aes192_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2499 @deftypefunx void gcm_aes256_encrypt (struct gcm_aes256_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2500 @deftypefunx void gcm_aes_encrypt (struct gcm_aes_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2501 @deftypefunx void gcm_aes128_decrypt (struct gcm_aes128_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2502 @deftypefunx void gcm_aes192_decrypt (struct gcm_aes192_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2503 @deftypefunx void gcm_aes256_decrypt (struct gcm_aes256_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2504 @deftypefunx void gcm_aes_decrypt (struct gcm_aes_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2505 Encrypts or decrypts the data of a message. All but the last call for
2506 each message @emph{must} use a length that is a multiple of the block
2507 size.
2508 @end deftypefun
2509
2510 @deftypefun void gcm_aes128_digest (struct gcm_aes128_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
2511 @deftypefunx void gcm_aes192_digest (struct gcm_aes192_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
2512 @deftypefunx void gcm_aes256_digest (struct gcm_aes256_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
2513 @deftypefunx void gcm_aes_digest (struct gcm_aes_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
2514 Extracts the message digest (also known ``authentication tag''). This is
2515 the final operation when processing a message. It's strongly recommended
2516 that @var{length} is @code{GCM_DIGEST_SIZE}, but if you provide a smaller
2517 value, only the first @var{length} octets of the digest are written.
2518 @end deftypefun
2519
2520 @subsubsection @acronym{GCM}-Camellia interface
2521
2522 The following functions implement the case of @acronym{GCM} using
2523 Camellia as the underlying cipher.
2524
2525 @deftp {Context struct} {struct gcm_camellia128_ctx}
2526 @deftpx {Context struct} {struct gcm_camellia256_ctx}
2527 Context structs, defined using @code{GCM_CTX}.
2528 @end deftp
2529
2530 @deftypefun void gcm_camellia128_set_key (struct gcm_camellia128_ctx *@var{ctx}, const uint8_t *@var{key})
2531 @deftypefunx void gcm_camellia256_set_key (struct gcm_camellia256_ctx *@var{ctx}, const uint8_t *@var{key})
2532 Initializes @var{ctx} using the given key.
2533 @end deftypefun
2534
2535 @deftypefun void gcm_camellia128_set_iv (struct gcm_camellia128_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{iv})
2536 @deftypefunx void gcm_camellia256_set_iv (struct gcm_camellia256_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{iv})
2537 Initializes the per-message state, using the given @acronym{IV}.
2538 @end deftypefun
2539
2540 @deftypefun void gcm_camellia128_update (struct gcm_camellia128_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
2541 @deftypefunx void gcm_camellia256_update (struct gcm_camellia256_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
2542 Provides associated data to be authenticated. If used, must be called
2543 before @code{gcm_camellia_encrypt} or @code{gcm_camellia_decrypt}. All but the
2544 last call for each message @emph{must} use a length that is a multiple
2545 of the block size.
2546 @end deftypefun
2547
2548 @deftypefun void gcm_camellia128_encrypt (struct gcm_camellia128_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2549 @deftypefunx void gcm_camellia256_encrypt (struct gcm_camellia256_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2550 @deftypefunx void gcm_camellia128_decrypt (struct gcm_camellia128_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2551 @deftypefunx void gcm_camellia256_decrypt (struct gcm_camellia256_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2552 Encrypts or decrypts the data of a message. All but the last call for
2553 each message @emph{must} use a length that is a multiple of the block
2554 size.
2555 @end deftypefun
2556
2557 @deftypefun void gcm_camellia128_digest (struct gcm_camellia128_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
2558 @deftypefunx void gcm_camellia192_digest (struct gcm_camellia192_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
2559 @deftypefunx void gcm_camellia256_digest (struct gcm_camellia256_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
2560 @deftypefunx void gcm_camellia_digest (struct gcm_camellia_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
2561 Extracts the message digest (also known ``authentication tag''). This is
2562 the final operation when processing a message. It's strongly recommended
2563 that @var{length} is @code{GCM_DIGEST_SIZE}, but if you provide a smaller
2564 value, only the first @var{length} octets of the digest are written.
2565 @end deftypefun
2566
2567 @node CCM, ChaCha-Poly1305, GCM, Authenticated encryption
2568 @comment  node-name,  next,  previous,  up
2569 @subsection Counter with CBC-MAC mode
2570
2571 @cindex Counter with CBC-MAC Mode
2572 @cindex CCM Mode
2573
2574 @acronym{CCM} mode is a combination of counter mode with message
2575 authentication based on cipher block chaining, the same building blocks
2576 as @acronym{EAX}, @pxref{EAX}. It is constructed on top of a block cipher
2577 which must have a block size of 128 bits. @acronym{CCM} mode is
2578 recommended by NIST in
2579 @uref{http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C_updated-July20_2007.pdf,
2580 NIST Special Publication 800-38C}. Nettle's support for CCM consists of
2581 a low-level general interface, a message encryption and authentication
2582 interface, and specific functions for CCM using AES as the underlying
2583 block cipher. These interfaces are defined in @file{<nettle/ccm.h>}.
2584
2585 In @acronym{CCM}, the length of the message must be known before
2586 processing. The maximum message size depends on the size of the nonce,
2587 since the message size is encoded in a field which must fit in a single
2588 block, together with the nonce and a flag byte. E.g., with a nonce size
2589 of 12 octets, there are three octets left for encoding the message
2590 length, the maximum message length is @math{2^24 - 1} octets.
2591
2592 @acronym{CCM} mode encryption operates as follows:
2593 @itemize
2594 @item The nonce and message length are concatenated to create
2595 @code{B_0 = flags | nonce | mlength}
2596
2597 @item The authenticated data and plaintext is formatted into the string
2598 @code{B = L(adata) | adata | padding | plaintext | padding} with
2599 @code{padding} being the shortest string of zero bytes such that the
2600 length of the string is a multiple of the block size, and
2601 @code{L(adata)} is an encoding of the length of @code{adata}.
2602
2603 @item The string @code{B} is separated into blocks @code{B_1} ...
2604 @code{B_n}
2605 @item The authentication tag @code{T} is calculated as
2606 @code{T=0, for i=0 to n, do T = E_k(B_i XOR T)}
2607
2608 @item An initial counter is then initialized from the nonce to create
2609 @code{IC = flags | nonce | padding}, where @code{padding} is the
2610 shortest string of zero bytes such that @code{IC} is exactly one block
2611 in length.
2612
2613 @item The authentication tag is encrypted using using @acronym{CTR} mode:
2614 @code{MAC = E_k(IC) XOR T}
2615
2616 @item The plaintext is then encrypted using @acronym{CTR} mode with an
2617 initial counter of @code{IC+1}.
2618 @end itemize
2619
2620 @acronym{CCM} mode decryption operates similarly, except that the
2621 ciphertext and @acronym{MAC} are first decrypted using CTR mode to
2622 retreive the plaintext and authentication tag. The authentication tag
2623 can then be recalucated from the authenticated data and plantext, and
2624 compared to the value in the message to check for authenticity.
2625
2626 @subsubsection General @acronym{CCM} interface
2627
2628 For all of the functions in the @acronym{CCM} interface, @var{cipher} is
2629 the context struct for the underlying cipher and @var{f} is the
2630 encryption function. The cipher's encryption key must be set before
2631 calling any of the @acronym{CCM} functions. The cipher's decryption
2632 function and key are never used.
2633
2634 @deftp {Context struct} {struct ccm_ctx}
2635 Holds state corresponding to a particular message.
2636 @end deftp
2637
2638 @defvr Constant CCM_BLOCK_SIZE
2639 @acronym{CCM}'s block size, 16.
2640 @end defvr
2641
2642 @defvr Constant CCM_DIGEST_SIZE
2643 Size of the @acronym{CCM} digest, 16.
2644 @end defvr
2645
2646 @defvr Constant CCM_MIN_NONCE_SIZE
2647 @defvrx Constant CCM_MAX_NONCE_SIZE
2648 The the minimum and maximum sizes for an @acronym{CCM} nonce, 7 and 14,
2649 respectively.
2650 @end defvr
2651
2652 @deffn Macro CCM_MAX_MSG_SIZE (@var{nonce_size})
2653 The largest allowed plaintext length, when using @acronym{CCM} with a
2654 nonce of the given size.
2655 @end deffn
2656
2657 @deftypefun void ccm_set_nonce (struct ccm_ctx *@var{ctx}, const void *@var{cipher}, nettle_cipher_func *@var{f}, size_t @var{noncelen}, const uint8_t *@var{nonce}, size_t @var{authlen}, size_t @var{msglen}, size_t @var{taglen})
2658 Initializes @var{ctx} using the given nonce and the sizes of the
2659 authenticated data, message, and @acronym{MAC} to be processed.
2660 @end deftypefun
2661
2662 @deftypefun void ccm_update (struct ccm_ctx *@var{ctx}, const void *@var{cipher}, nettle_cipher_func *@var{f}, size_t @var{length}, const uint8_t *@var{data})
2663 Provides associated data to be authenticated. Must be called after
2664 @code{ccm_set_nonce}, and before @code{ccm_encrypt}, @code{ccm_decrypt}, or
2665 @code{ccm_digest}.
2666 @end deftypefun
2667
2668 @deftypefun void ccm_encrypt (struct ccm_ctx *@var{ctx}, const void *@var{cipher}, nettle_cipher_func *@var{f}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2669 @deftypefunx void ccm_decrypt (struct ccm_ctx *@var{ctx}, const void *@var{cipher}, nettle_cipher_func *@var{f}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2670 Encrypts or decrypts the message data. Must be called after
2671 @code{ccm_set_nonce} and before @code{ccm_digest}. All but the last call
2672 for each message @emph{must} use a length that is a multiple of the
2673 block size.
2674 @end deftypefun
2675
2676 @deftypefun void ccm_digest (struct ccm_ctx *@var{ctx}, const void *@var{cipher}, nettle_cipher_func *@var{f}, size_t @var{length}, uint8_t *@var{digest})
2677 Extracts the message digest (also known ``authentication tag''). This is
2678 the final operation when processing a message. @var{length} is usually
2679 equal to the @var{taglen} parameter supplied to @code{ccm_set_nonce},
2680 but if you provide a smaller value, only the first @var{length} octets
2681 of the digest are written.
2682 @end deftypefun
2683
2684 To encrypt a message using the general @acronym{CCM} interface, set the
2685 message nonce and length using @code{ccm_set_nonce} and then call
2686 @code{ccm_update} to generate the digest of any authenticated data.
2687 After all of the authenticated data has been digested use
2688 @code{ccm_encrypt} to encrypt the plaintext. Finally, use
2689 @code{ccm_digest} to return the encrypted @acronym{MAC}.
2690
2691 To decrypt a message, use @code{ccm_set_nonce} and @code{ccm_update} the
2692 same as you would for encryption, and then call @code{ccm_decrypt} to
2693 decrypt the ciphertext. After decrypting the ciphertext
2694 @code{ccm_digest} will return the encrypted @acronym{MAC} which should
2695 be identical to the @acronym{MAC} in the received message.
2696
2697 @subsubsection @acronym{CCM} message interface
2698
2699 The @acronym{CCM} message fuctions provides a simple interface that will
2700 perform authentication and message encryption in a single function call.
2701 The length of the cleartext is given by @var{mlength} and the length of
2702 the ciphertext is given by @var{clength}, always exactly @var{tlength}
2703 bytes longer than the corresponding plaintext. The length argument
2704 passed to a function is always the size for the result, @var{clength}
2705 for the encryption functions, and @var{mlength} for the decryption
2706 functions.
2707
2708 @deftypefun void ccm_encrypt_message (void *@var{cipher}, nettle_cipher_func *@var{f}, size_t @var{nlength}, const uint8_t *@var{nonce}, size_t @var{alength}, const uint8_t *@var{adata}, size_t @var{tlength}, size_t @var{clength}, uint8_t *@var{dst}, const uint8_t *@var{src})
2709 Computes the message digest from the @var{adata} and @var{src}
2710 parameters, encrypts the plaintext from @var{src}, appends the encrypted
2711 @acronym{MAC} to ciphertext and outputs it to @var{dst}.
2712 @end deftypefun
2713
2714 @deftypefun int ccm_decrypt_message (void *@var{cipher}, nettle_cipher_func *@var{f}, size_t @var{nlength}, const uint8_t *@var{nonce}, size_t @var{alength}, const uint8_t *@var{adata}, size_t @var{tlength}, size_t @var{mlength}, uint8_t *@var{dst}, const uint8_t *@var{src})
2715 Decrypts the ciphertext from @var{src}, outputs the plaintext to
2716 @var{dst}, recalculates the @acronym{MAC} from @var{adata} and the
2717 plaintext, and compares it to the final @var{tlength} bytes of
2718 @var{src}. If the values of the received and calculated @acronym{MAC}s
2719 are equal, this will return 1 indicating a valid and authenticated
2720 message. Otherwise, this function will return zero.
2721 @end deftypefun
2722
2723 @subsubsection @acronym{CCM}-@acronym{AES} interface
2724
2725 The @acronym{AES} @acronym{CCM} functions provide an API for using
2726 @acronym{CCM} mode with the @acronym{AES} block ciphers. The parameters
2727 all have the same meaning as the general and message interfaces, except
2728 that the @var{cipher}, @var{f}, and @var{ctx} parameters are replaced
2729 with an @acronym{AES} context structure, and a set-key function must be
2730 called before using any of the other functions in this interface.
2731
2732 @deftp {Context struct} {struct ccm_aes128_ctx}
2733 Holds state corresponding to a particular message encrypted using the
2734 AES-128 block cipher.
2735 @end deftp
2736
2737 @deftp {Context struct} {struct ccm_aes192_ctx}
2738 Holds state corresponding to a particular message encrypted using the
2739 AES-192 block cipher.
2740 @end deftp
2741
2742 @deftp {Context struct} {struct ccm_aes256_ctx}
2743 Holds state corresponding to a particular message encrypted using the
2744 AES-256 block cipher.
2745 @end deftp
2746
2747 @deftypefun void ccm_aes128_set_key (struct ccm_aes128_ctx *@var{ctx}, const uint8_t *@var{key})
2748 @deftypefunx void ccm_aes192_set_key (struct ccm_aes192_ctx *@var{ctx}, const uint8_t *@var{key})
2749 @deftypefunx void ccm_aes256_set_key (struct ccm_aes256_ctx *@var{ctx}, const uint8_t *@var{key})
2750 Initializes the encryption key for the AES block cipher. One of these
2751 functions must be called before any of the other functions in the
2752 @acronym{AES} @acronym{CCM} interface.
2753 @end deftypefun
2754
2755 @deftypefun void ccm_aes128_set_nonce (struct ccm_aes128_ctx *@var{ctx}, size_t @var{noncelen}, const uint8_t *@var{nonce}, size_t @var{authlen}, size_t @var{msglen}, size_t @var{taglen})
2756 @deftypefunx void ccm_aes192_set_nonce (struct ccm_aes192_ctx *@var{ctx}, size_t @var{noncelen}, const uint8_t *@var{nonce}, size_t @var{authlen}, size_t @var{msglen}, size_t @var{taglen})
2757 @deftypefunx void ccm_aes256_set_nonce (struct ccm_aes256_ctx *@var{ctx}, size_t @var{noncelen}, const uint8_t *@var{nonce}, size_t @var{authlen}, size_t @var{msglen}, size_t @var{taglen})
2758 These are identical to @code{ccm_set_nonce}, except that @var{cipher},
2759 @var{f}, and @var{ctx} are replaced with a context structure.
2760 @end deftypefun
2761
2762 @deftypefun void ccm_aes128_update (struct ccm_aes128_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
2763 @deftypefunx void ccm_aes192_update (struct ccm_aes192_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
2764 @deftypefunx void ccm_aes256_update (struct ccm_aes256_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
2765 These are identical to @code{ccm_set_update}, except that @var{cipher},
2766 @var{f}, and @var{ctx} are replaced with a context structure.
2767 @end deftypefun
2768
2769 @deftypefun void ccm_aes128_encrypt (struct ccm_aes128_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2770 @deftypefunx void ccm_aes192_encrypt (struct ccm_aes192_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2771 @deftypefunx void ccm_aes256_encrypt (struct ccm_aes256_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2772 @deftypefunx void ccm_aes128_decrypt (struct ccm_aes128_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2773 @deftypefunx void ccm_aes192_decrypt (struct ccm_aes192_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2774 @deftypefunx void ccm_aes256_decrypt (struct ccm_aes256_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2775 These are identical to @code{ccm_set_encrypt} and @code{ccm_set_decrypt}, except
2776 that @var{cipher}, @var{f}, and @var{ctx} are replaced with a context structure.
2777 @end deftypefun
2778
2779 @deftypefun void ccm_aes128_digest (struct ccm_aes128_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
2780 @deftypefunx void ccm_aes192_digest (struct ccm_aes192_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
2781 @deftypefunx void ccm_aes256_digest (struct ccm_aes256_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
2782 These are identical to @code{ccm_set_digest}, except that @var{cipher},
2783 @var{f}, and @var{ctx} are replaced with a context structure.
2784 @end deftypefun
2785
2786 @deftypefun void ccm_aes128_encrypt_message (struct ccm_aes128_ctx *@var{ctx}, size_t @var{nlength}, const uint8_t *@var{nonce}, size_t @var{alength}, const uint8_t *@var{adata}, size_t @var{tlength}, size_t @var{clength}, uint8_t *@var{dst}, const uint8_t *@var{src})
2787 @deftypefunx void ccm_aes192_encrypt_message (struct ccm_aes192_ctx *@var{ctx}, size_t @var{nlength}, const uint8_t *@var{nonce}, size_t @var{alength}, const uint8_t *@var{adata}, size_t @var{tlength}, size_t @var{clength}, uint8_t *@var{dst}, const uint8_t *@var{src})
2788 @deftypefunx void ccm_aes256_encrypt_message (struct ccm_aes256_ctx *@var{ctx}, size_t @var{nlength}, const uint8_t *@var{nonce}, size_t @var{alength}, const uint8_t *@var{adata}, size_t @var{tlength}, size_t @var{clength}, uint8_t *@var{dst}, const uint8_t *@var{src})
2789 @deftypefunx int ccm_aes128_decrypt_message (struct ccm_aes128_ctx *@var{ctx}, size_t @var{nlength}, const uint8_t *@var{nonce}, size_t @var{alength}, const uint8_t *@var{adata}, size_t @var{tlength}, size_t @var{mlength}, uint8_t *@var{dst}, const uint8_t *@var{src})
2790 @deftypefunx int ccm_aes192_decrypt_message (struct ccm_aes192_ctx *@var{ctx}, size_t @var{nlength}, const uint8_t *@var{nonce}, size_t @var{alength}, const uint8_t *@var{adata}, size_t @var{tlength}, size_t @var{mlength}, uint8_t *@var{dst}, const uint8_t *@var{src})
2791 @deftypefunx int ccm_aes192_decrypt_message (struct ccm_aes256_ctx *@var{ctx}, size_t @var{nlength}, const uint8_t *@var{nonce}, size_t @var{alength}, const uint8_t *@var{adata}, size_t @var{tlength}, size_t @var{mlength}, uint8_t *@var{dst}, const uint8_t *@var{src})
2792 These are identical to @code{ccm_encrypt_message} and @code{ccm_decrypt_message}
2793 except that @var{cipher} and @var{f} are replaced with a context structure.
2794 @end deftypefun
2795
2796 @node ChaCha-Poly1305, nettle_aead abstraction, CCM, Authenticated encryption
2797 @comment  node-name,  next,  previous,  up
2798 @subsection ChaCha-Poly1305
2799
2800 ChaCha-Poly1305 is a combination of the ChaCha stream cipher and the
2801 poly1305 message authentication code (@pxref{Poly1305}). It originates
2802 from the NaCl cryptographic library by D. J. Bernstein et al, which
2803 defines a similar construction but with Salsa20 instead of ChaCha. 
2804
2805 Nettle's implementation ChaCha-Poly1305 should be considered
2806 @strong{experimental}. At the time of this writing, there is no
2807 authoritative specification for ChaCha-Poly1305, and a couple of
2808 different incompatible variants. Nettle implements it using the original
2809 definition of ChaCha, with 64 bits (8 octets) each for the nonce and the
2810 block counter. Some protocols prefer to use nonces of 12 bytes, and it's
2811 a small change to ChaCha to use the upper 32 bits of the block counter
2812 as a nonce, instead limiting message size to @math{2^32} blocks or 256
2813 GBytes, but that variant is currently not supported.
2814
2815 For ChaCha-Poly1305, the ChaCha cipher is initialized with a key, of 256
2816 bits, and a per-message nonce. The first block of the key stream
2817 (counter all zero) is set aside for the authentication subkeys. Of this
2818 64-octet block, the first 16 octets specify the poly1305 evaluation
2819 point, and the next 16 bytes specify the value to add in for the final
2820 digest. The final 32 bytes of this block are unused. Note that unlike
2821 poly1305-aes, the evaluation point depends on the nonce. This is
2822 preferable, because it leaks less information in case the attacker for
2823 some reason is lucky enough to forge a valid authentication tag, and
2824 observe (from the receiver's behaviour) that the forgery succeeded.
2825
2826 The ChaCha key stream, starting with counter value 1, is then used to
2827 encrypt the message. For authentication, poly1305 is applied to the
2828 concatenation of the associated data, the cryptotext, and the lengths of
2829 the associated data and the message, each a 64-bit number (eight octets,
2830 little-endian). Nettle defines ChaCha-Poly1305 in
2831 @file{<nettle/chacha-poly1305.h>}.
2832
2833 @defvr Constant CHACHA_POLY1305_BLOCK_SIZE
2834 Same as the ChaCha block size, 64.
2835 @end defvr
2836
2837 @defvr Constant CHACHA_POLY1305_KEY_SIZE
2838 ChaCha-Poly1305 key size, 32.
2839 @end defvr
2840
2841 @defvr Constant CHACHA_POLY1305_NONCE_SIZE
2842 Same as the ChaCha nonce size, 16.
2843 @end defvr
2844
2845 @defvr Constant CHACHA_POLY1305_DIGEST_SIZE
2846 Digest size, 16.
2847 @end defvr
2848
2849 @deftp {Context struct} {struct chacha_poly1305_ctx}
2850 @end deftp
2851
2852 @deftypefun void chacha_poly1305_set_key (struct chacha_poly1305_ctx *@var{ctx}, const uint8_t *@var{key})
2853 Initializes @var{ctx} using the given key. Before using the context, you
2854 @emph{must} also call @code{chacha_poly1305_set_nonce}, see below.
2855 @end deftypefun
2856
2857 @deftypefun void chacha_poly1305_set_nonce (struct chacha_poly1305_ctx *@var{ctx}, const uint8_t *@var{nonce})
2858 Initializes the per-message state, using the given nonce.
2859 @end deftypefun
2860
2861 @deftypefun void chacha_poly1305_update (struct chacha_poly1305_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
2862 Process associated data for authentication.
2863 @end deftypefun
2864
2865 @deftypefun void chacha_poly1305_encrypt (struct chacha_poly1305_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2866 @deftypefunx void chacha_poly1305_decrypt (struct chacha_poly1305_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
2867 Encrypts or decrypts the data of a message. All but the last call for
2868 each message @emph{must} use a length that is a multiple of the block
2869 size.
2870 @end deftypefun
2871
2872 @deftypefun void chacha_poly1305_digest (struct chacha_poly1305_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
2873 Extracts the message digest (also known ``authentication tag''). This is
2874 the final operation when processing a message. If @var{length} is
2875 smaller than @code{CHACHA_POLY1305_DIGEST_SIZE}, only the first
2876 @var{length} octets of the digest are written.
2877 @end deftypefun
2878
2879 @node nettle_aead abstraction, , ChaCha-Poly1305, Authenticated encryption
2880 @comment  node-name,  next,  previous,  up
2881 @subsection The @code{struct nettle_aead} abstraction
2882 @cindex nettle_aead
2883 @cindex nettle_aeads
2884
2885 Nettle includes a struct including information about the supported hash
2886 functions. It is defined in @file{<nettle/nettle-meta.h>}.
2887
2888 @deftp {Meta struct} @code{struct nettle_aead} name context_size block_size key_size nonce_size digest_size set_encrypt_key set_decrypt_key set_nonce update encrypt decrypt digest
2889 The last seven attributes are function pointers.
2890 @end deftp
2891
2892 @deftypevr {Constant Struct} {struct nettle_aead} nettle_gcm_aes128
2893 @deftypevrx {Constant Struct} {struct nettle_aead} nettle_gcm_aes192
2894 @deftypevrx {Constant Struct} {struct nettle_aead} nettle_gcm_aes256
2895 @deftypevrx {Constant Struct} {struct nettle_aead} nettle_gcm_camellia128
2896 @deftypevrx {Constant Struct} {struct nettle_aead} nettle_gcm_camellia256
2897 @deftypevrx {Constant Struct} {struct nettle_aead} nettle_eax_aes128
2898 @deftypevrx {Constant Struct} {struct nettle_aead} nettle_chacha_poly1305
2899 These are most of the @acronym{AEAD} constructions that Nettle
2900 implements. Note that @acronym{CCM} is missing; it requirement that the
2901 message size is specified in advance makes it incompatible with the
2902 @code{nettle_aead} abstraction.
2903 @end deftypevr
2904
2905 Nettle also exports a list of all these constructions.
2906
2907 @deftypevr {Constant Array} {struct nettle_aead **} nettle_aeads
2908 This list can be used to dynamically enumerate or search the supported
2909 algorithms. NULL-terminated.
2910 @end deftypevr
2911
2912 @node Keyed hash functions, Key derivation functions, Authenticated encryption, Reference
2913 @comment  node-name,  next,  previous,  up
2914 @section Keyed Hash Functions
2915
2916 @cindex Keyed Hash Function
2917 @cindex Message Authentication Code
2918 @cindex MAC
2919
2920 A @dfn{keyed hash function}, or @dfn{Message Authentication Code}
2921 (@acronym{MAC}) is a function that takes a key and a message, and
2922 produces fixed size @acronym{MAC}. It should be hard to compute a
2923 message and a matching @acronym{MAC} without knowledge of the key. It
2924 should also be hard to compute the key given only messages and
2925 corresponding @acronym{MAC}s.
2926
2927 Keyed hash functions are useful primarily for message authentication,
2928 when Alice and Bob shares a secret: The sender, Alice, computes the
2929 @acronym{MAC} and attaches it to the message. The receiver, Bob, also computes
2930 the @acronym{MAC} of the message, using the same key, and compares that
2931 to Alice's value. If they match, Bob can be assured that
2932 the message has not been modified on its way from Alice.
2933
2934 However, unlike digital signatures, this assurance is not transferable.
2935 Bob can't show the message and the @acronym{MAC} to a third party and
2936 prove that Alice sent that message. Not even if he gives away the key to
2937 the third party. The reason is that the @emph{same} key is used on both
2938 sides, and anyone knowing the key can create a correct @acronym{MAC} for
2939 any message. If Bob believes that only he and Alice knows the key, and
2940 he knows that he didn't attach a @acronym{MAC} to a particular message,
2941 he knows it must be Alice who did it. However, the third party can't
2942 distinguish between a @acronym{MAC} created by Alice and one created by
2943 Bob.
2944
2945 Keyed hash functions are typically a lot faster than digital signatures
2946 as well.
2947
2948 @menu
2949 * HMAC::
2950 * UMAC::
2951 * Poly1305::
2952 @end menu
2953
2954 @node HMAC, UMAC, Keyed hash functions, Keyed hash functions
2955 @comment  node-name,  next,  previous,  up
2956
2957 @subsection @acronym{HMAC}
2958 @cindex HMAC
2959
2960 One can build keyed hash functions from ordinary hash functions. Older
2961 constructions simply concatenate secret key and message and hashes that, but
2962 such constructions have weaknesses. A better construction is
2963 @acronym{HMAC}, described in @cite{RFC 2104}.
2964
2965 For an underlying hash function @code{H}, with digest size @code{l} and
2966 internal block size @code{b}, @acronym{HMAC-H} is constructed as
2967 follows: From a given key @code{k}, two distinct subkeys @code{k_i} and
2968 @code{k_o} are constructed, both of length @code{b}. The
2969 @acronym{HMAC-H} of a message @code{m} is then computed as @code{H(k_o |
2970 H(k_i | m))}, where @code{|} denotes string concatenation.
2971
2972 @acronym{HMAC} keys can be of any length, but it is recommended to use
2973 keys of length @code{l}, the digest size of the underlying hash function
2974 @code{H}. Keys that are longer than @code{b} are shortened to length
2975 @code{l} by hashing with @code{H}, so arbitrarily long keys aren't
2976 very useful. 
2977
2978 Nettle's @acronym{HMAC} functions are defined in @file{<nettle/hmac.h>}.
2979 There are abstract functions that use a pointer to a @code{struct
2980 nettle_hash} to represent the underlying hash function and @code{void *}
2981 pointers that point to three different context structs for that hash
2982 function. There are also concrete functions for @acronym{HMAC-MD5},
2983 @acronym{HMAC-RIPEMD160} @acronym{HMAC-SHA1}, @acronym{HMAC-SHA256}, and
2984 @acronym{HMAC-SHA512}. First, the abstract functions:
2985
2986 @deftypefun void hmac_set_key (void *@var{outer}, void *@var{inner}, void *@var{state}, const struct nettle_hash *@var{H}, size_t @var{length}, const uint8_t *@var{key})
2987 Initializes the three context structs from the key. The @var{outer} and
2988 @var{inner} contexts corresponds to the subkeys @code{k_o} and
2989 @code{k_i}. @var{state} is used for hashing the message, and is
2990 initialized as a copy of the @var{inner} context.
2991 @end deftypefun
2992
2993 @deftypefun void hmac_update (void *@var{state}, const struct nettle_hash *@var{H}, size_t @var{length}, const uint8_t *@var{data})
2994 This function is called zero or more times to process the message.
2995 Actually, @code{hmac_update(state, H, length, data)} is equivalent to
2996 @code{H->update(state, length, data)}, so if you wish you can use the
2997 ordinary update function of the underlying hash function instead.
2998 @end deftypefun
2999
3000 @deftypefun void hmac_digest (const void *@var{outer}, const void *@var{inner}, void *@var{state}, const struct nettle_hash *@var{H}, size_t @var{length}, uint8_t *@var{digest})
3001 Extracts the @acronym{MAC} of the message, writing it to @var{digest}.
3002 @var{outer} and @var{inner} are not modified. @var{length} is usually
3003 equal to @code{H->digest_size}, but if you provide a smaller value,
3004 only the first @var{length} octets of the @acronym{MAC} are written.
3005
3006 This function also resets the @var{state} context so that you can start
3007 over processing a new message (with the same key).
3008 @end deftypefun
3009
3010 Like for @acronym{CBC}, there are some macros to help use these
3011 functions correctly.
3012
3013 @deffn Macro HMAC_CTX (@var{type})
3014 Expands to
3015 @example
3016 @{
3017    type outer;
3018    type inner;
3019    type state;
3020 @}
3021 @end example
3022 @end deffn
3023
3024 It can be used to define a @acronym{HMAC} context struct, either
3025 directly,
3026
3027 @example
3028 struct HMAC_CTX(struct md5_ctx) ctx;
3029 @end example
3030
3031 or to give it a struct tag,
3032
3033 @example
3034 struct hmac_md5_ctx HMAC_CTX (struct md5_ctx);
3035 @end example
3036
3037 @deffn Macro HMAC_SET_KEY (@var{ctx}, @var{H}, @var{length}, @var{key})
3038 @var{ctx} is a pointer to a context struct as defined by
3039 @code{HMAC_CTX}, @var{H} is a pointer to a @code{const struct
3040 nettle_hash} describing the underlying hash function (so it must match
3041 the type of the components of @var{ctx}). The last two arguments specify
3042 the secret key.
3043 @end deffn
3044
3045 @deffn Macro HMAC_DIGEST (@var{ctx}, @var{H}, @var{length}, @var{digest})
3046 @var{ctx} is a pointer to a context struct as defined by
3047 @code{HMAC_CTX}, @var{H} is a pointer to a @code{const struct
3048 nettle_hash} describing the underlying hash function. The last two
3049 arguments specify where the digest is written.
3050 @end deffn
3051
3052 Note that there is no @code{HMAC_UPDATE} macro; simply call
3053 @code{hmac_update} function directly, or the update function of the
3054 underlying hash function.
3055
3056 @subsection Concrete @acronym{HMAC} functions
3057 Now we come to the specialized @acronym{HMAC} functions, which are
3058 easier to use than the general @acronym{HMAC} functions.
3059
3060 @subsubsection @acronym{HMAC-MD5}
3061
3062 @deftp {Context struct} {struct hmac_md5_ctx}
3063 @end deftp
3064
3065 @deftypefun void hmac_md5_set_key (struct hmac_md5_ctx *@var{ctx}, size_t @var{key_length}, const uint8_t *@var{key})
3066 Initializes the context with the key.
3067 @end deftypefun
3068
3069 @deftypefun void hmac_md5_update (struct hmac_md5_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
3070 Process some more data.
3071 @end deftypefun
3072
3073 @deftypefun void hmac_md5_digest (struct hmac_md5_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
3074 Extracts the @acronym{MAC}, writing it to @var{digest}. @var{length} may be smaller than
3075 @code{MD5_DIGEST_SIZE}, in which case only the first @var{length}
3076 octets of the @acronym{MAC} are written.
3077
3078 This function also resets the context for processing new messages, with
3079 the same key.
3080 @end deftypefun
3081
3082 @subsubsection @acronym{HMAC-RIPEMD160}
3083
3084 @deftp {Context struct} {struct hmac_ripemd160_ctx}
3085 @end deftp
3086
3087 @deftypefun void hmac_ripemd160_set_key (struct hmac_ripemd160_ctx *@var{ctx}, size_t @var{key_length}, const uint8_t *@var{key})
3088 Initializes the context with the key.
3089 @end deftypefun
3090
3091 @deftypefun void hmac_ripemd160_update (struct hmac_ripemd160_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
3092 Process some more data.
3093 @end deftypefun
3094
3095 @deftypefun void hmac_ripemd160_digest (struct hmac_ripemd160_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
3096 Extracts the @acronym{MAC}, writing it to @var{digest}. @var{length} may be smaller than
3097 @code{RIPEMD160_DIGEST_SIZE}, in which case only the first @var{length}
3098 octets of the @acronym{MAC} are written.
3099
3100 This function also resets the context for processing new messages, with
3101 the same key.
3102 @end deftypefun
3103
3104 @subsubsection @acronym{HMAC-SHA1}
3105
3106 @deftp {Context struct} {struct hmac_sha1_ctx}
3107 @end deftp
3108
3109 @deftypefun void hmac_sha1_set_key (struct hmac_sha1_ctx *@var{ctx}, size_t @var{key_length}, const uint8_t *@var{key})
3110 Initializes the context with the key.
3111 @end deftypefun
3112
3113 @deftypefun void hmac_sha1_update (struct hmac_sha1_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
3114 Process some more data.
3115 @end deftypefun
3116
3117 @deftypefun void hmac_sha1_digest (struct hmac_sha1_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
3118 Extracts the @acronym{MAC}, writing it to @var{digest}. @var{length} may be smaller than
3119 @code{SHA1_DIGEST_SIZE}, in which case only the first @var{length}
3120 octets of the @acronym{MAC} are written.
3121
3122 This function also resets the context for processing new messages, with
3123 the same key.
3124 @end deftypefun
3125
3126
3127 @subsubsection @acronym{HMAC-SHA256}
3128
3129 @deftp {Context struct} {struct hmac_sha256_ctx}
3130 @end deftp
3131
3132 @deftypefun void hmac_sha256_set_key (struct hmac_sha256_ctx *@var{ctx}, size_t @var{key_length}, const uint8_t *@var{key})
3133 Initializes the context with the key.
3134 @end deftypefun
3135
3136 @deftypefun void hmac_sha256_update (struct hmac_sha256_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
3137 Process some more data.
3138 @end deftypefun
3139
3140 @deftypefun void hmac_sha256_digest (struct hmac_sha256_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
3141 Extracts the @acronym{MAC}, writing it to @var{digest}. @var{length} may be smaller than
3142 @code{SHA256_DIGEST_SIZE}, in which case only the first @var{length}
3143 octets of the @acronym{MAC} are written.
3144
3145 This function also resets the context for processing new messages, with
3146 the same key.
3147 @end deftypefun
3148
3149
3150 @subsubsection @acronym{HMAC-SHA512}
3151
3152 @deftp {Context struct} {struct hmac_sha512_ctx}
3153 @end deftp
3154
3155 @deftypefun void hmac_sha512_set_key (struct hmac_sha512_ctx *@var{ctx}, size_t @var{key_length}, const uint8_t *@var{key})
3156 Initializes the context with the key.
3157 @end deftypefun
3158
3159 @deftypefun void hmac_sha512_update (struct hmac_sha512_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
3160 Process some more data.
3161 @end deftypefun
3162
3163 @deftypefun void hmac_sha512_digest (struct hmac_sha512_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
3164 Extracts the @acronym{MAC}, writing it to @var{digest}. @var{length} may be smaller than
3165 @code{SHA512_DIGEST_SIZE}, in which case only the first @var{length}
3166 octets of the @acronym{MAC} are written.
3167
3168 This function also resets the context for processing new messages, with
3169 the same key.
3170 @end deftypefun
3171
3172 @node UMAC, Poly1305 , HMAC, Keyed hash functions
3173 @comment  node-name,  next,  previous,  up
3174
3175 @subsection @acronym{UMAC}
3176 @cindex UMAC
3177
3178 @acronym{UMAC} is a message authentication code based on universal
3179 hashing, and designed for high performance on modern processors (in
3180 contrast to GCM, @xref{GCM}, which is designed primarily for hardware
3181 performance). On processors with good integer multiplication
3182 performance, it can be 10 times faster than SHA256 and SHA512.
3183 @acronym{UMAC} is specified in @cite{RFC 4418}.
3184
3185 The secret key is always 128 bits (16 octets). The key is used as an
3186 encryption key for the @acronym{AES} block cipher. This cipher is used
3187 in counter mode to generate various internal subkeys needed in
3188 @acronym{UMAC}. Messages are of arbitrary size, and for each message,
3189 @acronym{UMAC} also needs a unique nonce. Nonce values must not be
3190 reused for two messages with the same key, but they need not be kept
3191 secret.
3192
3193 The nonce must be at least one octet, and at most 16; nonces shorter
3194 than 16 octets are zero-padded. Nettle's implementation of
3195 @acronym{UMAC} increments the nonce automatically for each message, so
3196 explicitly setting the nonce for each message is optional. This
3197 auto-increment uses network byte order and it takes the length of the
3198 nonce into account. E.g., if the initial nonce is ``abc'' (3 octets),
3199 this value is zero-padded to 16 octets for the first message. For the
3200 next message, the nonce is incremented to ``abd'', and this incremented
3201 value is zero-padded to 16 octets.
3202
3203 @acronym{UMAC} is defined in four variants, for different output sizes:
3204 32 bits (4 octets), 64 bits (8 octets), 96 bits (12 octets) and 128 bits
3205 (16 octets), corresponding to different trade-offs between speed and
3206 security. Using a shorter output size sometimes (but not always!) gives
3207 the same result as using a longer output size and truncating the result.
3208 So it is important to use the right variant. For consistency with other
3209 hash and @acronym{MAC} functions, Nettle's @code{_digest} functions for
3210 @acronym{UMAC} accept a length parameter so that the output can be
3211 truncated to any desired size, but it is recommended to stick to the
3212 specified output size and select the @acronym{umac} variant
3213 corresponding to the desired size.
3214
3215 The internal block size of @acronym{UMAC} is 1024 octets, and it also
3216 generates more than 1024 bytes of subkeys. This makes the size of the
3217 context struct quite a bit larger than other hash functions and
3218 @acronym{MAC} algorithms in Nettle.
3219
3220 Nettle defines @acronym{UMAC} in @file{<nettle/umac.h>}.
3221
3222 @deftp {Context struct} {struct umac32_ctx}
3223 @deftpx {Context struct} {struct umac64_ctx}
3224 @deftpx {Context struct} {struct umac96_ctx}
3225 @deftpx {Context struct} {struct umac128_ctx}
3226 Each @acronym{UMAC} variant uses its own context struct.
3227 @end deftp
3228
3229 @defvr Constant UMAC_KEY_SIZE
3230 The UMAC key size, 16.
3231 @end defvr
3232 @defvr Constant UMAC_MIN_NONCE_SIZE
3233 @defvrx Constant UMAC_MAX_NONCE_SIZE
3234 The the minimum and maximum sizes for an UMAC nonce, 1 and 16,
3235 respectively.
3236 @end defvr
3237 @defvr Constant UMAC32_DIGEST_SIZE
3238 The size of an UMAC32 digest, 4.
3239 @end defvr
3240 @defvr Constant UMAC64_DIGEST_SIZE
3241 The size of an UMAC64 digest, 8.
3242 @end defvr
3243 @defvr Constant UMAC96_DIGEST_SIZE
3244 The size of an UMAC96 digest, 12.
3245 @end defvr
3246 @defvr Constant UMAC128_DIGEST_SIZE
3247 The size of an UMAC128 digest, 16.
3248 @end defvr
3249 @defvr Constant UMAC_BLOCK_SIZE
3250 The internal block size of UMAC.
3251 @end defvr
3252
3253 @deftypefun void umac32_set_key (struct umac32_ctx *@var{ctx}, const uint8_t *@var{key})
3254 @deftypefunx void umac64_set_key (struct umac64_ctx *@var{ctx}, const uint8_t *@var{key})
3255 @deftypefunx void umac96_set_key (struct umac96_ctx *@var{ctx}, const uint8_t *@var{key})
3256 @deftypefunx void umac128_set_key (struct umac128_ctx *@var{ctx}, const uint8_t *@var{key})
3257 These functions initialize the @acronym{UMAC} context struct. They also
3258 initialize the nonce to zero (with length 16, for auto-increment).
3259 @end deftypefun
3260
3261 @deftypefun void umac32_set_nonce (struct umac32_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{nonce})
3262 @deftypefunx void umac64_set_nonce (struct umac64_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{nonce})
3263 @deftypefunx void umac96_set_nonce (struct umac96_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{nonce})
3264 @deftypefunx void umac128_set_nonce (struct umac128_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{nonce})
3265 Sets the nonce to be used for the next message. In general, nonces
3266 should be set before processing of the message. This is not strictly
3267 required for @acronym{UMAC} (the nonce only affects the final processing
3268 generating the digest), but it is nevertheless recommended that this
3269 function is called @emph{before} the first @code{_update} call for the
3270 message.
3271 @end deftypefun
3272
3273 @deftypefun void umac32_update (struct umac32_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
3274 @deftypefunx void umac64_update (struct umac64_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
3275 @deftypefunx void umac96_update (struct umac96_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
3276 @deftypefunx void umac128_update (struct umac128_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
3277 These functions are called zero or more times to process the message.
3278 @end deftypefun
3279
3280 @deftypefun void umac32_digest (struct umac32_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
3281 @deftypefunx void umac64_digest (struct umac64_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
3282 @deftypefunx void umac96_digest (struct umac96_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
3283 @deftypefunx void umac128_digest (struct umac128_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
3284 Extracts the @acronym{MAC} of the message, writing it to @var{digest}.
3285 @var{length} is usually equal to the specified output size, but if you
3286 provide a smaller value, only the first @var{length} octets of the
3287 @acronym{MAC} are written. These functions reset the context for
3288 processing of a new message with the same key. The nonce is incremented
3289 as described above, the new value is used unless you call the
3290 @code{_set_nonce} function explicitly for each message.
3291 @end deftypefun
3292
3293 @node Poly1305,, UMAC, Keyed hash functions
3294 @comment  node-name,  next,  previous,  up
3295 @subsection Poly1305
3296
3297 Poly1305-@acronym{AES} is a message authentication code designed by D. J.
3298 Bernstein. It treats the message as a polynomial modulo the prime number
3299 @math{2^130 - 5}.
3300
3301 The key, 256 bits, consists of two parts, where the first half is an
3302 @acronym{AES}-128 key, and the second half specifies the point where the
3303 polynomial is evaluated. Of the latter half, 22 bits are set to zero, to
3304 enable high-performance implementation, leaving 106 bits for specifying
3305 an evaluation point @code{r}. For each message, one must also provide a
3306 128-bit nonce. The nonce is encrypted using the @acronym{AES} key, and
3307 that's the only thing @acronym{AES} is used for.
3308
3309 The message is split into 128-bit chunks (with final chunk possibly
3310 being shorter), each read as a little-endian integer. Each chunk has a
3311 one-bit appended at the high end. The resulting integers are treated as
3312 polynomial coefficients modulo @math{2^130 - 5}, and the polynomial is
3313 evaluated at the point @code{r}. Finally, this value is reduced modulo
3314 @math{2^128}, and added (also modulo @math{2^128}) to the encrypted
3315 nonce, to produce an 128-bit authenticator for the message. See
3316 @uref{http://cr.yp.to/mac/poly1305-20050329.pdf} for further details.
3317
3318 Clearly, variants using a different cipher than @acronym{AES} could be
3319 defined. Another variant is the ChaCha-Poly1305 @acronym{AEAD}
3320 construction (@pxref{ChaCha-Poly1305}). Nettle defines
3321 Poly1305-@acronym{AES} in @file{nettle/poly1305.h}.
3322
3323 @defvr Constant POLY1305_AES_KEY_SIZE
3324 Key size, 32 octets.
3325 @end defvr
3326
3327 @defvr Constant POLY1305_AES_DIGEST_SIZE
3328 Size of the digest or ``authenticator'', 16 octets.
3329 @end defvr
3330
3331 @defvr Constant POLY1305_AES_NONCE_SIZE
3332 Nonce size, 16 octets.
3333 @end defvr
3334
3335 @deftp {Context struct} {struct poly1305_aes_ctx}
3336 The poly1305-aes context struct.
3337 @end deftp
3338
3339 @deftypefun void poly1305_aes_set_key (struct poly1305_aes_ctx *@var{ctx}, const uint8_t *@var{key})
3340 Initialize the context struct. Also sets the nonce to zero.
3341 @end deftypefun
3342
3343 @deftypefun void poly1305_aes_set_nonce (struct poly1305_aes_ctx *@var{ctx}, const uint8_t *@var{nonce})
3344 Sets the nonce. Calling this function is optional, since the nonce is
3345 incremented automatically for each message.
3346 @end deftypefun
3347
3348 @deftypefun void poly1305_aes_update (struct poly1305_aes_ctx *@var{ctx}, size_t @var{length}, const uint8_t *@var{data})
3349 Process more data.
3350 @end deftypefun
3351
3352 @deftypefun void poly1305_aes_digest (struct poly1305_aes_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{digest})
3353 Extracts the digest. If @var{length} is smaller than
3354 @code{POLY1305_AES_DIGEST_SIZE}, only the first @var{length} octets are
3355 written. Also increments the nonce, and prepares the context for
3356 processing a new message.
3357 @end deftypefun
3358
3359
3360 @node Key derivation functions, Public-key algorithms, Keyed hash functions, Reference
3361 @comment  node-name,  next,  previous,  up
3362 @section Key derivation Functions
3363
3364 @cindex Key Derivation Function
3365 @cindex Password Based Key Derivation Function
3366 @cindex PKCS #5
3367 @cindex KDF
3368 @cindex PBKDF
3369
3370 A @dfn{key derivation function} (@acronym{KDF}) is a function that from
3371 a given symmetric key derives other symmetric keys.  A sub-class of KDFs
3372 is the @dfn{password-based key derivation functions} (@acronym{PBKDFs}),
3373 which take as input a password or passphrase, and its purpose is
3374 typically to strengthen it and protect against certain pre-computation
3375 attacks by using salting and expensive computation.
3376
3377 @subsection @acronym{PBKDF2}
3378 The most well known PBKDF is the @code{PKCS #5 PBKDF2} described in
3379 @cite{RFC 2898} which uses a pseudo-random function such as
3380 @acronym{HMAC-SHA1}.
3381
3382 Nettle's @acronym{PBKDF2} functions are defined in
3383 @file{<nettle/pbkdf2.h>}.  There is an abstract function that operate on
3384 any PRF implemented via the @code{nettle_hash_update_func},
3385 @code{nettle_hash_digest_func} interfaces.  There is also helper macros
3386 and concrete functions PBKDF2-HMAC-SHA1 and PBKDF2-HMAC-SHA256.  First,
3387 the abstract function:
3388
3389 @deftypefun void pbkdf2 (void *mac_ctx, nettle_hash_update_func *update, nettle_hash_digest_func *digest, size_t digest_size, unsigned iterations, size_t salt_length, const uint8_t *salt, size_t length, uint8_t *dst)
3390 Derive symmetric key from a password according to PKCS #5 PBKDF2.  The
3391 PRF is assumed to have been initialized and this function will call the
3392 @var{update} and @var{digest} functions passing the @var{mac_ctx}
3393 context parameter as an argument in order to compute digest of size
3394 @var{digest_size}.  Inputs are the salt @var{salt} of length
3395 @var{salt_length}, the iteration counter @var{iterations} (> 0), and the
3396 desired derived output length @var{length}.  The output buffer is
3397 @var{dst} which must have room for at least @var{length} octets.
3398 @end deftypefun
3399
3400 Like for CBC and HMAC, there is a macro to help use the function
3401 correctly.
3402
3403 @deffn Macro PBKDF2 (@var{ctx}, @var{update}, @var{digest}, @var{digest_size}, @var{iterations}, @var{salt_length}, @var{salt}, @var{length}, @var{dst})
3404 @var{ctx} is a pointer to a context struct passed to the @var{update}
3405 and @var{digest} functions (of the types @code{nettle_hash_update_func}
3406 and @code{nettle_hash_digest_func} respectively) to implement the
3407 underlying PRF with digest size of @var{digest_size}.  Inputs are the
3408 salt @var{salt} of length @var{salt_length}, the iteration counter
3409 @var{iterations} (> 0), and the desired derived output length
3410 @var{length}.  The output buffer is @var{dst} which must have room for
3411 at least @var{length} octets.
3412 @end deffn
3413
3414 @subsection Concrete @acronym{PBKDF2} functions
3415 Now we come to the specialized @acronym{PBKDF2} functions, which are
3416 easier to use than the general @acronym{PBKDF2} function.
3417
3418 @subsubsection @acronym{PBKDF2-HMAC-SHA1}
3419
3420 @deftypefun void pbkdf2_hmac_sha1 (size_t @var{key_length}, const uint8_t *@var{key}, unsigned @var{iterations}, size_t @var{salt_length}, const uint8_t *@var{salt}, size_t @var{length}, uint8_t *@var{dst})
3421 PBKDF2 with HMAC-SHA1.  Derive @var{length} bytes of key into buffer
3422 @var{dst} using the password @var{key} of length @var{key_length} and
3423 salt @var{salt} of length @var{salt_length}, with iteration counter
3424 @var{iterations} (> 0).  The output buffer is @var{dst} which must have
3425 room for at least @var{length} octets.
3426 @end deftypefun
3427
3428 @subsubsection @acronym{PBKDF2-HMAC-SHA256}
3429
3430 @deftypefun void pbkdf2_hmac_sha256 (size_t @var{key_length}, const uint8_t *@var{key}, unsigned @var{iterations}, size_t @var{salt_length}, const uint8_t *@var{salt}, size_t @var{length}, uint8_t *@var{dst})
3431 PBKDF2 with HMAC-SHA256.  Derive @var{length} bytes of key into buffer
3432 @var{dst} using the password @var{key} of length @var{key_length} and
3433 salt @var{salt} of length @var{salt_length}, with iteration counter
3434 @var{iterations} (> 0).  The output buffer is @var{dst} which must have
3435 room for at least @var{length} octets.
3436 @end deftypefun
3437
3438 @node Public-key algorithms, Randomness, Key derivation functions, Reference
3439 @comment  node-name,  next,  previous,  up
3440 @section Public-key algorithms
3441
3442 Nettle uses @acronym{GMP}, the GNU bignum library, for all calculations
3443 with large numbers. In order to use the public-key features of Nettle,
3444 you must install @acronym{GMP}, at least version 3.0, before compiling
3445 Nettle, and you need to link your programs with @code{-lhogweed -lnettle
3446 -lgmp}.
3447
3448 The concept of @dfn{Public-key} encryption and digital signatures was
3449 discovered by Whitfield Diffie and Martin E. Hellman and described in a
3450 paper 1976. In traditional, ``symmetric'', cryptography, sender and
3451 receiver share the same keys, and these keys must be distributed in a
3452 secure way. And if there are many users or entities that need to
3453 communicate, each @emph{pair} needs a shared secret key known by nobody
3454 else.
3455
3456 @cindex Public Key Cryptography
3457 @cindex One-way function
3458
3459 Public-key cryptography uses trapdoor one-way functions. A
3460 @dfn{one-way function} is a function @code{F} such that it is easy to
3461 compute the value @code{F(x)} for any @code{x}, but given a value
3462 @code{y}, it is hard to compute a corresponding @code{x} such that
3463 @code{y = F(x)}. Two examples are cryptographic hash functions, and
3464 exponentiation in certain groups.
3465
3466 A @dfn{trapdoor one-way function} is a function @code{F} that is
3467 one-way, unless one knows some secret information about @code{F}. If one
3468 knows the secret, it is easy to compute both @code{F} and it's inverse.
3469 If this sounds strange, look at the @acronym{RSA} example below.
3470
3471 Two important uses for one-way functions with trapdoors are public-key
3472 encryption, and digital signatures. The public-key encryption functions
3473 in Nettle are not yet documented; the rest of this chapter is about
3474 digital signatures.
3475
3476 To use a digital signature algorithm, one must first create a
3477 @dfn{key-pair}: A public key and a corresponding private key. The private
3478 key is used to sign messages, while the public key is used for verifying
3479 that that signatures and messages match. Some care must be taken when
3480 distributing the public key; it need not be kept secret, but if a bad
3481 guy is able to replace it (in transit, or in some user's list of known
3482 public keys), bad things may happen.
3483
3484 There are two operations one can do with the keys. The signature
3485 operation takes a message and a private key, and creates a signature for
3486 the message. A signature is some string of bits, usually at most a few
3487 thousand bits or a few hundred octets. Unlike paper-and-ink signatures,
3488 the digital signature depends on the message, so one can't cut it out of
3489 context and glue it to a different message.
3490
3491 The verification operation takes a public key, a message, and a string
3492 that is claimed to be a signature on the message, and returns true or
3493 false. If it returns true, that means that the three input values
3494 matched, and the verifier can be sure that someone went through with the
3495 signature operation on that very message, and that the ``someone'' also
3496 knows the private key corresponding to the public key.
3497
3498 The desired properties of a digital signature algorithm are as follows:
3499 Given the public key and pairs of messages and valid signatures on them,
3500 it should be hard to compute the private key, and it should also be hard
3501 to create a new message and signature that is accepted by the
3502 verification operation.
3503
3504 Besides signing meaningful messages, digital signatures can be used for
3505 authorization. A server can be configured with a public key, such that
3506 any client that connects to the service is given a random nonce message.
3507 If the server gets a reply with a correct signature matching the nonce
3508 message and the configured public key, the client is granted access. So
3509 the configuration of the server can be understood as ``grant access to
3510 whoever knows the private key corresponding to this particular public
3511 key, and to no others''.
3512
3513
3514 @menu
3515 * RSA::                         The RSA public key algorithm.
3516 * DSA::                         The DSA digital signature algorithm.
3517 * Elliptic curves::             Elliptic curves and ECDSA
3518 @end menu
3519
3520 @node RSA, DSA, Public-key algorithms, Public-key algorithms
3521 @comment  node-name,  next,  previous,  up
3522 @subsection @acronym{RSA}
3523
3524 The @acronym{RSA} algorithm was the first practical digital signature
3525 algorithm that was constructed. It was described 1978 in a paper by
3526 Ronald Rivest, Adi Shamir and L.M. Adleman, and the technique was also
3527 patented in the @acronym{USA} in 1983. The patent expired on September 20, 2000, and since
3528 that day, @acronym{RSA} can be used freely, even in the @acronym{USA}.
3529
3530 It's remarkably simple to describe the trapdoor function behind
3531 @acronym{RSA}. The ``one-way''-function used is
3532
3533 @example
3534 F(x) = x^e mod n
3535 @end example
3536
3537 I.e. raise x to the @code{e}'th power, while discarding all multiples of
3538 @code{n}. The pair of numbers @code{n} and @code{e} is the public key.
3539 @code{e} can be quite small, even @code{e = 3} has been used, although
3540 slightly larger numbers are recommended. @code{n} should be about 2000
3541 bits or larger.
3542
3543 If @code{n} is large enough, and properly chosen, the inverse of F,
3544 the computation of @code{e}'th roots modulo @code{n}, is very difficult.
3545 But, where's the trapdoor?
3546
3547 Let's first look at how @acronym{RSA} key-pairs are generated. First
3548 @code{n} is chosen as the product of two large prime numbers @code{p}
3549 and @code{q} of roughly the same size (so if @code{n} is 2000 bits,
3550 @code{p} and @code{q} are about 1000 bits each). One also computes the
3551 number @code{phi = (p-1)(q-1)}, in mathematical speak, @code{phi} is the
3552 order of the multiplicative group of integers modulo n.
3553
3554 Next, @code{e} is chosen. It must have no factors in common with @code{phi} (in
3555 particular, it must be odd), but can otherwise be chosen more or less
3556 randomly. @code{e = 65537} is a popular choice, because it makes raising
3557 to the @code{e}'th power particularly efficient, and being prime, it
3558 usually has no factors common with @code{phi}.
3559
3560 Finally, a number @code{d}, @code{d < n} is computed such that @code{e d
3561 mod phi = 1}. It can be shown that such a number exists (this is why
3562 @code{e} and @code{phi} must have no common factors), and that for all x,
3563
3564 @example
3565 (x^e)^d mod n = x^(ed) mod n = (x^d)^e mod n = x
3566 @end example
3567
3568 Using Euclid's algorithm, @code{d} can be computed quite easily from
3569 @code{phi} and @code{e}. But it is still hard to get @code{d} without
3570 knowing @code{phi}, which depends on the factorization of @code{n}.
3571
3572 So @code{d} is the trapdoor, if we know @code{d} and @code{y = F(x)}, we can
3573 recover x as @code{y^d mod n}. @code{d} is also the private half of
3574 the @acronym{RSA} key-pair.
3575
3576 The most common signature operation for @acronym{RSA} is defined in
3577 @cite{PKCS#1}, a specification by RSA Laboratories. The message to be
3578 signed is first hashed using a cryptographic hash function, e.g.
3579 @acronym{MD5} or @acronym{SHA1}. Next, some padding, the @acronym{ASN.1}
3580 ``Algorithm Identifier'' for the hash function, and the message digest
3581 itself, are concatenated and converted to a number @code{x}. The
3582 signature is computed from @code{x} and the private key as @code{s = x^d
3583 mod n}@footnote{Actually, the computation is not done like this, it is
3584 done more efficiently using @code{p}, @code{q} and the Chinese remainder
3585 theorem (@acronym{CRT}). But the result is the same.}. The signature, @code{s} is a
3586 number of about the same size of @code{n}, and it usually encoded as a
3587 sequence of octets, most significant octet first.
3588
3589 The verification operation is straight-forward, @code{x} is computed
3590 from the message in the same way as above. Then @code{s^e mod n} is
3591 computed, the operation returns true if and only if the result equals
3592 @code{x}.
3593
3594 The @acronym{RSA} algorithm can also be used for encryption. RSA encryption uses
3595 the public key @code{(n,e)} to compute the ciphertext @code{m^e mod n}.
3596 The @cite{PKCS#1} padding scheme will use at least 8 random and non-zero
3597 octets, using @var{m} of the form @code{[00 02 padding 00 plaintext]}.
3598 It is required that @code{m < n}, and therefor the plaintext must be
3599 smaller than the octet size of the modulo @code{n}, with some margin.
3600
3601 To decrypt the message, one needs the private key to compute @code{m =
3602 c^e mod n} followed by checking and removing the padding.
3603
3604 @subsubsection Nettle's @acronym{RSA} support
3605
3606 Nettle represents @acronym{RSA} keys using two structures that contain
3607 large numbers (of type @code{mpz_t}).
3608
3609 @deftp {Context struct} {rsa_public_key} size n e
3610 @code{size} is the size, in octets, of the modulo, and is used internally.
3611 @code{n} and @code{e} is the public key.
3612 @end deftp
3613
3614 @deftp {Context struct} {rsa_private_key} size d p q a b c
3615 @code{size} is the size, in octets, of the modulo, and is used internally.
3616 @code{d} is the secret exponent, but it is not actually used when
3617 signing. Instead, the factors @code{p} and @code{q}, and the parameters
3618 @code{a}, @code{b} and @code{c} are used. They are computed from @code{p},
3619 @code{q} and @code{e} such that @code{a e mod (p - 1) = 1, b e mod (q -
3620 1) = 1, c q mod p = 1}.
3621 @end deftp
3622
3623 Before use, these structs must be initialized by calling one of
3624
3625 @deftypefun void rsa_public_key_init (struct rsa_public_key *@var{pub})
3626 @deftypefunx void rsa_private_key_init (struct rsa_private_key *@var{key})
3627 Calls @code{mpz_init} on all numbers in the key struct.
3628 @end deftypefun
3629
3630 and when finished with them, the space for the numbers must be
3631 deallocated by calling one of
3632
3633 @deftypefun void rsa_public_key_clear (struct rsa_public_key *@var{pub})
3634 @deftypefunx void rsa_private_key_clear (struct rsa_private_key *@var{key})
3635 Calls @code{mpz_clear} on all numbers in the key struct.
3636 @end deftypefun
3637
3638 In general, Nettle's @acronym{RSA} functions deviates from Nettle's ``no
3639 memory allocation''-policy. Space for all the numbers, both in the key structs
3640 above, and temporaries, are allocated dynamically. For information on how
3641 to customize allocation, see
3642 @xref{Custom Allocation,,GMP Allocation,gmp, GMP Manual}.
3643
3644 When you have assigned values to the attributes of a key, you must call
3645
3646 @deftypefun int rsa_public_key_prepare (struct rsa_public_key *@var{pub})
3647 @deftypefunx int rsa_private_key_prepare (struct rsa_private_key *@var{key})
3648 Computes the octet size of the key (stored in the @code{size} attribute,
3649 and may also do other basic sanity checks. Returns one if successful, or
3650 zero if the key can't be used, for instance if the modulo is smaller
3651 than the minimum size needed for @acronym{RSA} operations specified by PKCS#1.
3652 @end deftypefun
3653
3654 For each operation using the private key, there are two variants, e.g.,
3655 @code{rsa_sha256_sign} and @code{rsa_sha256_sign_tr}. The former
3656 function is older, and it should be avoided, because it provides no
3657 defenses against side-channel attacks. The latter function use
3658 randomized @acronym{RSA} blinding, which defends against timing attacks
3659 using chosen-ciphertext, and it also checks the correctness of the
3660 private key computation using the public key, which defends against
3661 software or hardware errors which could leak the private key.
3662
3663 Before signing or verifying a message, you first hash it with the
3664 appropriate hash function. You pass the hash function's context struct
3665 to the @acronym{RSA} signature function, and it will extract the message
3666 digest and do the rest of the work. There are also alternative functions
3667 that take the hash digest as argument.
3668
3669 There is currently no support for using SHA224 or SHA384 with
3670 @acronym{RSA} signatures, since there's no gain in either computation
3671 time nor message size compared to using SHA256 and SHA512, respectively.
3672
3673 Creating an @acronym{RSA} signature is done with one of the following
3674 functions:
3675
3676 @deftypefun int rsa_md5_sign_tr(const struct rsa_public_key *@var{pub}, const struct rsa_private_key *@var{key}, void *@var{random_ctx}, nettle_random_func *@var{random}, struct md5_ctx *@var{hash}, mpz_t @var{signature})
3677 @deftypefunx int rsa_sha1_sign_tr(const struct rsa_public_key *@var{pub}, const struct rsa_private_key *@var{key}, void *@var{random_ctx}, nettle_random_func *@var{random}, struct sha1_ctx *@var{hash}, mpz_t @var{signature})
3678 @deftypefunx int rsa_sha256_sign_tr(const struct rsa_public_key *@var{pub}, const struct rsa_private_key *@var{key}, void *@var{random_ctx}, nettle_random_func *@var{random}, struct sha256_ctx *@var{hash}, mpz_t @var{signature})
3679 @deftypefunx int rsa_sha512_sign_tr(const struct rsa_public_key *@var{pub}, const struct rsa_private_key *@var{key}, void *@var{random_ctx}, nettle_random_func *@var{random}, struct sha512_ctx *@var{hash}, mpz_t @var{signature})
3680 The signature is stored in @var{signature} (which must have been
3681 @code{mpz_init}'ed earlier). The hash context is reset so that it can be
3682 used for new messages. The @var{random_ctx} and @var{random} pointers
3683 are used to generate the @acronym{RSA} blinding. Returns one on success,
3684 or zero on failure. Signing fails if an error in the computation was
3685 detected, or if the key is too small for the given hash size, e.g., it's
3686 not possible to create a signature using SHA512 and a 512-bit
3687 @acronym{RSA} key.
3688 @end deftypefun
3689
3690 @deftypefun int rsa_md5_sign_digest_tr(const struct rsa_public_key *@var{pub}, const struct rsa_private_key *@var{key}, void *@var{random_ctx}, nettle_random_func *@var{random}, const uint8_t *@var{digest}, mpz_t @var{signature})
3691 @deftypefunx int rsa_sha1_sign_digest_tr(const struct rsa_public_key *@var{pub}, const struct rsa_private_key *@var{key}, void *@var{random_ctx}, nettle_random_func *@var{random}, const uint8_t *@var{digest}, mpz_t @var{signature})
3692 @deftypefunx int rsa_sha256_sign_digest_tr(const struct rsa_public_key *@var{pub}, const struct rsa_private_key *@var{key}, void *@var{random_ctx}, nettle_random_func *@var{random}, const uint8_t *@var{digest}, mpz_t @var{signature})
3693 @deftypefunx int rsa_sha512_sign_digest_tr(const struct rsa_public_key *@var{pub}, const struct rsa_private_key *@var{key}, void *@var{random_ctx}, nettle_random_func *@var{random}, const uint8_t *@var{digest}, mpz_t @var{signature})
3694 Creates a signature from the given hash digest. @var{digest} should
3695 point to a digest of size @code{MD5_DIGEST_SIZE},
3696 @code{SHA1_DIGEST_SIZE}, @code{SHA256_DIGEST_SIZE}, or
3697 @code{SHA512_DIGEST_SIZE}respectively. The signature is stored in
3698 @var{signature} (which must have been @code{mpz_init}:ed earlier).
3699 Returns one on success, or zero on failure.
3700 @end deftypefun
3701
3702 @deftypefun int rsa_pkcs1_sign_tr(const struct rsa_public_key *@var{pub}, const struct rsa_private_key *@var{key}, void *@var{random_ctx}, nettle_random_func *@var{random}, size_t @var{length}, const uint8_t *@var{digest_info}, mpz_t @var{signature})
3703 Similar to the above @code{_sign_digest_tr} functions, but the input is not the
3704 plain hash digest, but a PKCS#1 ``DigestInfo'', an ASN.1 DER-encoding
3705 of the digest together with an object identifier for the used hash
3706 algorithm.
3707 @end deftypefun
3708
3709 @deftypefun int rsa_md5_sign (const struct rsa_private_key *@var{key}, struct md5_ctx *@var{hash}, mpz_t @var{signature})
3710 @deftypefunx int rsa_sha1_sign (const struct rsa_private_key *@var{key}, struct sha1_ctx *@var{hash}, mpz_t @var{signature})
3711 @deftypefunx int rsa_sha256_sign (const struct rsa_private_key *@var{key}, struct sha256_ctx *@var{hash}, mpz_t @var{signature})
3712 @deftypefunx int rsa_sha512_sign (const struct rsa_private_key *@var{key}, struct sha512_ctx *@var{hash}, mpz_t @var{signature})
3713 The signature is stored in @var{signature} (which must have been
3714 @code{mpz_init}'ed earlier). The hash context is reset so that it can be
3715 used for new messages. Returns one on success, or zero on failure.
3716 Signing fails if the key is too small for the given hash size, e.g.,
3717 it's not possible to create a signature using SHA512 and a 512-bit
3718 @acronym{RSA} key.
3719 @end deftypefun
3720
3721 @deftypefun int rsa_md5_sign_digest (const struct rsa_private_key *@var{key}, const uint8_t *@var{digest}, mpz_t @var{signature})
3722 @deftypefunx int rsa_sha1_sign_digest (const struct rsa_private_key *@var{key}, const uint8_t *@var{digest}, mpz_t @var{signature});
3723 @deftypefunx int rsa_sha256_sign_digest (const struct rsa_private_key *@var{key}, const uint8_t *@var{digest}, mpz_t @var{signature});
3724 @deftypefunx int rsa_sha512_sign_digest (const struct rsa_private_key *@var{key}, const uint8_t *@var{digest}, mpz_t @var{signature});
3725 Creates a signature from the given hash digest; otherwise analoguous to
3726 the above signing functions. @var{digest} should point to a digest of
3727 size @code{MD5_DIGEST_SIZE}, @code{SHA1_DIGEST_SIZE},
3728 @code{SHA256_DIGEST_SIZE}, or @code{SHA512_DIGEST_SIZE}, respectively.
3729 The signature is stored in @var{signature} (which must have been
3730 @code{mpz_init}:ed earlier). Returns one on success, or zero on failure.
3731 @end deftypefun
3732
3733 @deftypefun int rsa_pkcs1_sign(const struct rsa_private_key *@var{key}, size_t @var{length}, const uint8_t *@var{digest_info}, mpz_t @var{s})
3734 Similar to the above _sign_digest functions, but the input is not the
3735 plain hash digest, but a PKCS#1 ``DigestInfo'', an ASN.1 DER-encoding
3736 of the digest together with an object identifier for the used hash
3737 algorithm.
3738 @end deftypefun
3739
3740 Verifying an RSA signature is done with one of the following functions:
3741
3742 @deftypefun int rsa_md5_verify (const struct rsa_public_key *@var{key}, struct md5_ctx *@var{hash}, const mpz_t @var{signature})
3743 @deftypefunx int rsa_sha1_verify (const struct rsa_public_key *@var{key}, struct sha1_ctx *@var{hash}, const mpz_t @var{signature})
3744 @deftypefunx int rsa_sha256_verify (const struct rsa_public_key *@var{key}, struct sha256_ctx *@var{hash}, const mpz_t @var{signature})
3745 @deftypefunx int rsa_sha512_verify (const struct rsa_public_key *@var{key}, struct sha512_ctx *@var{hash}, const mpz_t @var{signature})
3746 Returns 1 if the signature is valid, or 0 if it isn't. In either case,
3747 the hash context is reset so that it can be used for new messages.
3748 @end deftypefun
3749
3750 @deftypefun int rsa_md5_verify_digest (const struct rsa_public_key *@var{key}, const uint8_t *@var{digest}, const mpz_t @var{signature})
3751 @deftypefunx int rsa_sha1_verify_digest (const struct rsa_public_key *@var{key}, const uint8_t *@var{digest}, const mpz_t @var{signature})
3752 @deftypefunx int rsa_sha256_verify_digest (const struct rsa_public_key *@var{key}, const uint8_t *@var{digest}, const mpz_t @var{signature})
3753 @deftypefunx int rsa_sha512_verify_digest (const struct rsa_public_key *@var{key}, const uint8_t *@var{digest}, const mpz_t @var{signature})
3754 Returns 1 if the signature is valid, or 0 if it isn't. @var{digest}
3755 should point to a digest of size @code{MD5_DIGEST_SIZE},
3756 @code{SHA1_DIGEST_SIZE}, @code{SHA256_DIGEST_SIZE}, or
3757 @code{SHA512_DIGEST_SIZE} respectively.
3758 @end deftypefun
3759
3760 @deftypefun int rsa_pkcs1_verify(const struct rsa_public_key *@var{key}, size_t @var{length}, const uint8_t *@var{digest_info}, const mpz_t @var{signature})
3761 Similar to the above _verify_digest functions, but the input is not the
3762 plain hash digest, but a PKCS#1 ``DigestInfo'', and ASN.1 DER-encoding
3763 of the digest together with an object identifier for the used hash
3764 algorithm.
3765 @end deftypefun
3766
3767 The following function is used to encrypt a clear text message using RSA.
3768 @deftypefun int rsa_encrypt (const struct rsa_public_key *@var{key}, void *@var{random_ctx}, nettle_random_func *@var{random}, size_t @var{length}, const uint8_t *@var{cleartext}, mpz_t @var{ciphertext})
3769 Returns 1 on success, 0 on failure. If the message is too long then this
3770 will lead to a failure.
3771 @end deftypefun
3772 The following function is used to decrypt a cipher text message using RSA.
3773 @deftypefun int rsa_decrypt (const struct rsa_private_key *@var{key}, size_t *@var{length}, uint8_t *@var{cleartext}, const mpz_t @var{ciphertext})
3774 Returns 1 on success, 0 on failure. Causes of failure include decryption
3775 failing or the resulting message being to large. The message buffer
3776 pointed to by @var{cleartext} must be of size *@var{length}. After
3777 decryption, *@var{length} will be updated with the size of the
3778 message.
3779 @end deftypefun
3780 There is also a timing resistant version of decryption that utilizes
3781 randomized RSA blinding.
3782 @deftypefun int rsa_decrypt_tr (const struct rsa_public_key *@var{pub}, const struct rsa_private_key *@var{key}, void *@var{random_ctx}, nettle_random_func *@var{random}, size_t *@var{length}, uint8_t *@var{message}, const mpz_t @var{ciphertext})
3783 Returns 1 on success, 0 on failure.
3784 @end deftypefun
3785
3786 If you need to use the @acronym{RSA} trapdoor, the private key, in a way
3787 that isn't supported by the above functions Nettle also includes a
3788 function that computes @code{x^d mod n} and nothing more, using the
3789 @acronym{CRT} optimization.
3790
3791 @deftypefun int rsa_compute_root_tr(const struct rsa_public_key *@var{pub}, const struct rsa_private_key *@var{key}, void *@var{random_ctx}, nettle_random_func *@var{random}, mpz_t @var{x}, const mpz_t @var{m})
3792 Computes @code{x = m^d}. Returns one on success, or zero if a failure in
3793 the computation was detected.
3794 @end deftypefun
3795
3796 @deftypefun void rsa_compute_root (struct rsa_private_key *@var{key}, mpz_t @var{x}, const mpz_t @var{m})
3797 Computes @code{x = m^d}.
3798 @end deftypefun
3799
3800 At last, how do you create new keys?
3801
3802 @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});
3803 There are lots of parameters. @var{pub} and @var{key} is where the
3804 resulting key pair is stored. The structs should be initialized, but you
3805 don't need to call @code{rsa_public_key_prepare} or
3806 @code{rsa_private_key_prepare} after key generation.
3807
3808 @var{random_ctx} and @var{random} is a randomness generator.
3809 @code{random(random_ctx, length, dst)} should generate @code{length}
3810 random octets and store them at @code{dst}. For advice, see
3811 @xref{Randomness}.
3812
3813 @var{progress} and @var{progress_ctx} can be used to get callbacks
3814 during the key generation process, in order to uphold an illusion of
3815 progress. @var{progress} can be NULL, in that case there are no
3816 callbacks.
3817
3818 @var{size_n} is the desired size of the modulo, in bits. If @var{size_e}
3819 is non-zero, it is the desired size of the public exponent and a random
3820 exponent of that size is selected. But if @var{e_size} is zero, it is
3821 assumed that the caller has already chosen a value for @code{e}, and
3822 stored it in @var{pub}.
3823 Returns one on success, and zero on failure. The function can fail for
3824 example if if @var{n_size} is too small, or if @var{e_size} is zero and
3825 @code{pub->e} is an even number.
3826 @end deftypefun
3827
3828 @node DSA, Elliptic curves, RSA, Public-key algorithms
3829 @comment  node-name,  next,  previous,  up
3830 @subsection @acronym{DSA}
3831
3832 The @acronym{DSA} digital signature algorithm is more complex than
3833 @acronym{RSA}. It was specified during the early 1990s, and in 1994 NIST
3834 published @acronym{FIPS} 186 which is the authoritative specification.
3835 Sometimes @acronym{DSA} is referred to using the acronym @acronym{DSS},
3836 for Digital Signature Standard. The most recent revision of the
3837 specification, FIPS186-3, was issued in 2009, and it adds support for
3838 larger hash functions than @acronym{sha1}.
3839
3840 For @acronym{DSA}, the underlying mathematical problem is the
3841 computation of discrete logarithms. The public key consists of a large
3842 prime @code{p}, a small prime @code{q} which is a factor of @code{p-1},
3843 a number @code{g} which generates a subgroup of order @code{q} modulo
3844 @code{p}, and an element @code{y} in that subgroup.
3845
3846 In the original @acronym{DSA}, the size of @code{q} is fixed to 160
3847 bits, to match with the @acronym{SHA1} hash algorithm. The size of
3848 @code{p} is in principle unlimited, but the
3849 standard specifies only nine specific sizes: @code{512 + l*64}, where
3850 @code{l} is between 0 and 8. Thus, the maximum size of @code{p} is 1024
3851 bits, and sizes less than 1024 bits are considered obsolete and not
3852 secure.
3853
3854 The subgroup requirement means that if you compute 
3855
3856 @example
3857 g^t mod p
3858 @end example
3859
3860 for all possible integers @code{t}, you will get precisely @code{q}
3861 distinct values.
3862
3863 The private key is a secret exponent @code{x}, such that
3864
3865 @example
3866 g^x = y mod p
3867 @end example
3868
3869 In mathematical speak, @code{x} is the @dfn{discrete logarithm} of
3870 @code{y} mod @code{p}, with respect to the generator @code{g}. The size
3871 of @code{x} will also be about the same size as @code{q}. The security of the
3872 @acronym{DSA} algorithm relies on the difficulty of the discrete
3873 logarithm problem. Current algorithms to compute discrete logarithms in
3874 this setting, and hence crack @acronym{DSA}, are of two types. The first
3875 type works directly in the (multiplicative) group of integers mod
3876 @code{p}. The best known algorithm of this type is the Number Field
3877 Sieve, and it's complexity is similar to the complexity of factoring
3878 numbers of the same size as @code{p}. The other type works in the
3879 smaller @code{q}-sized subgroup generated by @code{g}, which has a more
3880 difficult group structure. One good algorithm is Pollard-rho, which has
3881 complexity @code{sqrt(q)}.
3882
3883 The important point is that security depends on the size of @emph{both}
3884 @code{p} and @code{q}, and they should be chosen so that the difficulty
3885 of both discrete logarithm methods are comparable. Today, the security
3886 margin of the original @acronym{DSA} may be uncomfortably small. Using a
3887 @code{p} of 1024 bits implies that cracking using the number field sieve
3888 is expected to take about the same time as factoring a 1024-bit
3889 @acronym{RSA} modulo, and using a @code{q} of size 160 bits implies
3890 that cracking using Pollard-rho will take roughly @code{2^80} group
3891 operations. With the size of @code{q} fixed, tied to the @acronym{SHA1}
3892 digest size, it may be tempting to increase the size of @code{p} to,
3893 say, 4096 bits. This will provide excellent resistance against attacks
3894 like the number field sieve which works in the large group. But it will
3895 do very little to defend against Pollard-rho attacking the small
3896 subgroup; the attacker is slowed down at most by a single factor of 10
3897 due to the more expensive group operation. And the attacker will surely
3898 choose the latter attack.
3899
3900 The signature generation algorithm is randomized; in order to create a
3901 @acronym{DSA} signature, you need a good source for random numbers
3902 (@pxref{Randomness}). Let us describe the common case of a 160-bit
3903 @code{q}.
3904
3905 To create a signature, one starts with the hash digest of the message,
3906 @code{h}, which is a 160 bit number, and a random number @code{k,
3907 0<k<q}, also 160 bits. Next, one computes 
3908
3909 @example
3910 r = (g^k mod p) mod q
3911 s = k^-1 (h + x r) mod q
3912 @end example
3913
3914 The signature is the pair @code{(r, s)}, two 160 bit numbers. Note the
3915 two different mod operations when computing @code{r}, and the use of the
3916 secret exponent @code{x}.
3917
3918 To verify a signature, one first checks that @code{0 < r,s < q}, and
3919 then one computes backwards,
3920
3921 @example
3922 w = s^-1 mod q
3923 v = (g^(w h) y^(w r) mod p) mod q
3924 @end example
3925
3926 The signature is valid if @code{v = r}. This works out because @code{w =
3927 s^-1 mod q = k (h + x r)^-1 mod q}, so that
3928
3929 @example
3930 g^(w h) y^(w r) = g^(w h) (g^x)^(w r) = g^(w (h + x r)) = g^k 
3931 @end example
3932
3933 When reducing mod @code{q} this yields @code{r}. Note that when
3934 verifying a signature, we don't know either @code{k} or @code{x}: those
3935 numbers are secret.
3936
3937 If you can choose between @acronym{RSA} and @acronym{DSA}, which one is
3938 best? Both are believed to be secure. @acronym{DSA} gained popularity in
3939 the late 1990s, as a patent free alternative to @acronym{RSA}. Now that
3940 the @acronym{RSA} patents have expired, there's no compelling reason to
3941 want to use @acronym{DSA}. Today, the original @acronym{DSA} key size
3942 does not provide a large security margin, and it should probably be
3943 phased out together with @acronym{RSA} keys of 1024 bits. Using the
3944 revised @acronym{DSA} algorithm with a larger hash function, in
3945 particular, @acronym{SHA256}, a 256-bit @code{q}, and @code{p} of size
3946 2048 bits or more, should provide for a more comfortable security
3947 margin, but these variants are not yet in wide use.
3948
3949 @acronym{DSA} signatures are smaller than @acronym{RSA} signatures,
3950 which is important for some specialized applications.
3951
3952 From a practical point of view, @acronym{DSA}'s need for a good
3953 randomness source is a serious disadvantage. If you ever use the same
3954 @code{k} (and @code{r}) for two different message, you leak your private
3955 key.
3956
3957 @subsubsection Nettle's @acronym{DSA} support
3958
3959 Like for @acronym{RSA}, Nettle represents @acronym{DSA} keys using two
3960 structures, containing values of type @code{mpz_t}. For information on
3961 how to customize allocation, see @xref{Custom Allocation,,GMP
3962 Allocation,gmp, GMP Manual}. Nettle's @acronym{DSA} interface is defined
3963 in @file{<nettle/dsa.h>}.
3964
3965 A @acronym{DSA} group is represented using the following struct.
3966
3967 @deftp {Context struct} {dsa_params} p q g
3968 Parameters of the @acronym{DSA} group.
3969 @end deftp
3970
3971 @deftypefun void dsa_params_init (struct dsa_params *@var{params})
3972 Calls @code{mpz_init} on all numbers in the struct.
3973 @end deftypefun
3974
3975 @deftypefun void dsa_params_clear (struct dsa_params *@var{params}params)
3976 Calls @code{mpz_clear} on all numbers in the struct.
3977 @end deftypefun
3978
3979 @deftypefun int dsa_generate_params (struct dsa_params *@var{params}, 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})
3980 Generates paramaters of a new group. The @var{params} struct should be
3981 initialized before you call this function.
3982
3983 @var{random_ctx} and @var{random} is a randomness generator.
3984 @code{random(random_ctx, length, dst)} should generate @code{length}
3985 random octets and store them at @code{dst}. For advice, see
3986 @xref{Randomness}.
3987
3988 @var{progress} and @var{progress_ctx} can be used to get callbacks
3989 during the key generation process, in order to uphold an illusion of
3990 progress. @var{progress} can be NULL, in that case there are no
3991 callbacks.
3992
3993 @var{p_bits} and @var{q_bits} are the desired sizes of @code{p} and
3994 @code{q}. To generate keys that conform to the original @acronym{DSA}
3995 standard, you must use @code{q_bits = 160} and select @var{p_bits} of
3996 the form @code{p_bits = 512 + l*64}, for @code{0 <= l <= 8}, where the
3997 smaller sizes are no longer recommended, so you should most likely stick
3998 to @code{p_bits = 1024}. Non-standard sizes are possible, in particular
3999 @code{p_bits} larger than 1024, although @acronym{DSA} implementations
4000 can not in general be expected to support such keys. Also note that
4001 using very large @var{p_bits}, with @var{q_bits} fixed at 160, doesn't
4002 make much sense, because the security is also limited by the size of the
4003 smaller prime. To generate @acronym{DSA} keys for use with
4004 @acronym{SHA256}, use @code{q_bits = 256} and, e.g., @code{p_bits =
4005 2048}.
4006
4007 Returns one on success, and zero on failure. The function will fail if
4008 @var{q_bits} is too small, or too close to @var{p_bits}.
4009 @end deftypefun
4010
4011 Signatures are represented using the structure below.
4012
4013 @deftp {Context struct} {dsa_signature} r s
4014 @end deftp
4015
4016 @deftypefun void dsa_signature_init (struct dsa_signature *@var{signature})
4017 @deftypefunx void dsa_signature_clear (struct dsa_signature *@var{signature})
4018 You must call @code{dsa_signature_init} before creating or using a
4019 signature, and call @code{dsa_signature_clear} when you are finished
4020 with it.
4021 @end deftypefun
4022
4023 Keys are represented as bignums, of type @code{mpz_t}. A public keys
4024 represent a group element, and is of the same size as @code{p}, while a
4025 private key is an exponent, of the same size as @code{q}.
4026
4027 @deftypefun int dsa_sign (const struct dsa_params *@var{params}, const mpz_t @var{x}, void *@var{random_ctx}, nettle_random_func *@var{random}, size_t @var{digest_size}, const uint8_t *@var{digest}, struct dsa_signature *@var{signature})
4028 Creates a signature from the given hash digest, using the private key
4029 @var{x}. @var{random_ctx} and @var{random} is a randomness generator.
4030 @code{random(random_ctx, length, dst)} should generate @code{length}
4031 random octets and store them at @code{dst}. For advice, see
4032 @xref{Randomness}. Returns one on success, or zero on failure. Signing
4033 can fail only if the key is invalid, so that inversion modulo @code{q}
4034 fails.
4035 @end deftypefun
4036
4037 @deftypefun int dsa_verify (const struct dsa_params *@var{params}, const mpz_t @var{y}, size_t @var{digest_size}, const uint8_t *@var{digest}, const struct dsa_signature *@var{signature})
4038 Verifies a signature, using the public key y. Returns 1 if the signature
4039 is valid, otherwise 0.
4040 @end deftypefun
4041
4042 To generate a keypair, first generate a @acronym{DSA} group using
4043 @code{dsa_generate_params}. A keypair in this group is then created
4044 using
4045
4046 @deftypefun void dsa_generate_keypair (const struct dsa_params *@var{params}, mpz_t @var{pub}, mpz_t @var{key}, void *@var{random_ctx}, nettle_random_func *@var{random})
4047 Generates a new keypair, using the group @var{params}. The public key is
4048 stored in @var{pub}, and the private key in @var{key}. Both variables
4049 must be initialized using @code{mpz_init} before this call.
4050
4051 @var{random_ctx} and @var{random} is a randomness generator.
4052 @code{random(random_ctx, length, dst)} should generate @code{length}
4053 random octets and store them at @code{dst}. For advice, see
4054 @xref{Randomness}.
4055 @end deftypefun
4056
4057 @subsubsection Old, deprecated, @acronym{DSA} interface
4058
4059 Versions before nettle-3.0 used a different interface for @acronym{DSA}
4060 signatures, where the group parameters and the public key was packed
4061 together as @code{struct dsa_public_key}. Most of this interface is kept
4062 for backwards compatibility, and declared in @file{nettle/dsa-compat.h}.
4063 Below is the old documentation. The old and new interface use distinct
4064 names and don't confict, with one exception: The key generation
4065 function. The @file{nettle/dsa-compat.h} redefines
4066 @code{dsa_generate_keypair} as an alias for
4067 @code{dsa_compat_generate_keypair}, compatible with the old interface
4068 and documented below.
4069
4070 The old @acronym{DSA} functions are very similar to the corresponding
4071 @acronym{RSA} functions, but there are a few differences pointed out
4072 below. For a start, there are no functions corresponding to
4073 @code{rsa_public_key_prepare} and @code{rsa_private_key_prepare}.
4074
4075 @deftp {Context struct} {dsa_public_key} p q g y
4076 The public parameters described above.
4077 @end deftp
4078
4079 @deftp {Context struct} {dsa_private_key} x
4080 The private key @code{x}.
4081 @end deftp
4082
4083 Before use, these structs must be initialized by calling one of
4084
4085 @deftypefun void dsa_public_key_init (struct dsa_public_key *@var{pub})
4086 @deftypefunx void dsa_private_key_init (struct dsa_private_key *@var{key})
4087 Calls @code{mpz_init} on all numbers in the key struct.
4088 @end deftypefun
4089
4090 When finished with them, the space for the numbers must be
4091 deallocated by calling one of
4092
4093 @deftypefun void dsa_public_key_clear (struct dsa_public_key *@var{pub})
4094 @deftypefunx void dsa_private_key_clear (struct dsa_private_key *@var{key})
4095 Calls @code{mpz_clear} on all numbers in the key struct.
4096 @end deftypefun
4097
4098 Signatures are represented using @code{struct dsa_signature}, described
4099 earlier.
4100
4101 For signing, you need to provide both the public and the private key
4102 (unlike @acronym{RSA}, where the private key struct includes all
4103 information needed for signing), and a source for random numbers.
4104 Signatures can use the @acronym{SHA1} or the @acronym{SHA256} hash
4105 function, although the implementation of @acronym{DSA} with
4106 @acronym{SHA256} should be considered somewhat experimental due to lack
4107 of official test vectors and interoperability testing.
4108
4109 @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})
4110 @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})
4111 @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})
4112 @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})
4113 Creates a signature from the given hash context or digest.
4114 @var{random_ctx} and @var{random} is a randomness generator.
4115 @code{random(random_ctx, length, dst)} should generate @code{length}
4116 random octets and store them at @code{dst}. For advice, see
4117 @xref{Randomness}. Returns one on success, or zero on failure.
4118 Signing fails if the key size and the hash size don't match.
4119 @end deftypefun
4120
4121 Verifying signatures is a little easier, since no randomness generator is
4122 needed. The functions are
4123
4124 @deftypefun int dsa_sha1_verify (const struct dsa_public_key *@var{key}, struct sha1_ctx *@var{hash}, const struct dsa_signature *@var{signature})
4125 @deftypefunx int dsa_sha1_verify_digest (const struct dsa_public_key *@var{key}, const uint8_t *@var{digest}, const struct dsa_signature *@var{signature})
4126 @deftypefunx int dsa_sha256_verify (const struct dsa_public_key *@var{key}, struct sha256_ctx *@var{hash}, const struct dsa_signature *@var{signature})
4127 @deftypefunx int dsa_sha256_verify_digest (const struct dsa_public_key *@var{key}, const uint8_t *@var{digest}, const struct dsa_signature *@var{signature})
4128 Verifies a signature. Returns 1 if the signature is valid, otherwise 0.
4129 @end deftypefun
4130
4131 Key generation uses mostly the same parameters as the corresponding
4132 @acronym{RSA} function.
4133
4134 @deftypefun int dsa_compat_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})
4135 @var{pub} and @var{key} is where the resulting key pair is stored. The
4136 structs should be initialized before you call this function. 
4137
4138 @var{random_ctx} and @var{random} is a randomness generator.
4139 @code{random(random_ctx, length, dst)} should generate @code{length}
4140 random octets and store them at @code{dst}. For advice, see
4141 @xref{Randomness}.
4142
4143 @var{progress} and @var{progress_ctx} can be used to get callbacks
4144 during the key generation process, in order to uphold an illusion of
4145 progress. @var{progress} can be NULL, in that case there are no
4146 callbacks.
4147
4148 @var{p_bits} and @var{q_bits} are the desired sizes of @code{p} and
4149 @code{q}. See @code{dsa_generate_keypair} for details.
4150 @end deftypefun
4151
4152 @node Elliptic curves,, DSA, Public-key algorithms
4153 @comment  node-name,  next,  previous,  up
4154 @subsection @acronym{Elliptic curves}
4155
4156 For cryptographic purposes, an elliptic curve is a mathematical group of
4157 points, and computing logarithms in this group is computationally
4158 difficult problem. Nettle uses additive notation for elliptic curve
4159 groups. If @math{P} and @math{Q} are two points, and @math{k} is an
4160 integer, the point sum, @math{P + Q}, and the multiple @math{k P} can be
4161 computed efficiently, but given only two points @math{P} and @math{Q},
4162 finding an integer @math{k} such that @math{Q = k P} is the elliptic
4163 curve discrete logarithm problem.
4164
4165 Nettle supports standard curves which are all of the form @math{y^2 =
4166 x^3 - 3 x + b @pmod{p}}, i.e., the points have coordinates @math{(x,y)},
4167 both considered as integers modulo a specified prime @math{p}. Curves
4168 are represented as a @code{struct ecc_curve}. It also supports
4169 curve25519, which uses a different form of curve. Supported curves are
4170 declared in @file{<nettle/ecc-curve.h>}, e.g., @code{nettle_secp_256r1}
4171 for a standardized curve using the 256-bit prime @math{p = 2^{256} -
4172 2^{224} + 2^{192} + 2^{96} - 1}. The contents of these structs is not
4173 visible to nettle users. The ``bitsize of the curve'' is used as a
4174 shorthand for the bitsize of the curve's prime @math{p}, e.g., 256 bits
4175 for @code{nettle_secp_256r1}.
4176
4177 @subsubsection Side-channel silence
4178 Nettle's implementation of the elliptic curve operations is intended to
4179 be side-channel silent. The side-channel attacks considered are:
4180
4181 @itemize
4182 @item Timing attacks
4183 If the timing of operations depends on secret values, an attacker
4184 interacting with your system can measure the response time, and infer
4185 information about your secrets, e.g., a private signature key.
4186
4187 @item Attacks using memory caches
4188 Assume you have some secret data on a multi-user system, and that this
4189 data is properly protected so that other users get no direct access to
4190 it. If you have a process operating on the secret data, and this process
4191 does memory accesses depending on the data, e.g, an internal lookup
4192 table in some cryptographic algorithm, an attacker running a separate
4193 process on the same system may use behavior of internal CPU caches to
4194 get information about your secrets.
4195 @end itemize
4196
4197 Nettle's ECC implementation is designed to be @dfn{side-channel silent},
4198 and not leak any information to these attacks. Timing and memory
4199 accesses depend only on the size of the input data and its location in
4200 memory, not on the actual data bits. This implies a performance penalty
4201 in several of the building blocks.
4202
4203 @subsubsection ECDSA
4204
4205 ECDSA is a variant of the DSA digital signature scheme (@pxref{DSA}),
4206 which works over an elliptic curve group rather than over a (subgroup
4207 of) integers modulo @math{p}. Like DSA, creating a signature requires a unique
4208 random nonce (repeating the nonce with two different messages reveals
4209 the private key, and any leak or bias in the generation of the nonce
4210 also leaks information about the key).
4211
4212 Unlike DSA, signatures are in general not tied to any particular hash
4213 function or even hash size. Any hash function can be used, and the hash
4214 value is truncated or padded as needed to get a size matching the curve
4215 being used. It is recommended to use a strong cryptographic hash
4216 function with digest size close to the bit size of the curve, e.g.,
4217 SHA256 is a reasonable choice when using ECDSA signature over the curve
4218 secp256r1. A protocol or application using ECDSA has to specify which
4219 curve and which hash function to use, or provide some mechanism for
4220 negotiating.
4221
4222 Nettle defines ECDSA in @file{<nettle/ecdsa.h>}. We first need
4223 to define the data types used to represent public and private keys.
4224
4225 @deftp {struct} {struct ecc_point}
4226 Represents a point on an elliptic curve. In particular, it is used to
4227 represent an ECDSA public key.
4228 @end deftp
4229
4230 @deftypefun void ecc_point_init (struct ecc_point *@var{p}, const structecc_curve *@var{ecc})
4231 Initializes @var{p} to represent points on the given curve @var{ecc}.
4232 Allocates storage for the coordinates, using the same allocation
4233 functions as GMP.
4234 @end deftypefun
4235
4236 @deftypefun void ecc_point_clear (struct ecc_point *@var{p})
4237 Deallocate storage.
4238 @end deftypefun
4239
4240 @deftypefun int ecc_point_set (struct ecc_point *@var{p}, const mpz_t @var{x}, const mpz_t @var{y})
4241 Check that the given coordinates represent a point on the curve. If so,
4242 the coordinates are copied and converted to internal representation, and
4243 the function returns 1. Otherwise, it returns 0. Currently, the
4244 infinity point (or zero point, with additive notation) i snot allowed.
4245 @end deftypefun
4246
4247 @deftypefun void ecc_point_get (const struct ecc_point *@var{p}, mpz_t @var{x}, mpz_t @var{y})
4248 Extracts the coordinate of the point @var{p}. The output parameters
4249 @var{x} or @var{y} may be NULL if the caller doesn't want that
4250 coordinate.
4251 @end deftypefun
4252
4253 @deftp {struct} {struct ecc_scalar}
4254 Represents an integer in the range @math{0 < x < group order}, where the
4255 ``group order'' refers to the order of an ECC group. In particular, it
4256 is used to represent an ECDSA private key.
4257 @end deftp
4258
4259 @deftypefun void ecc_scalar_init (struct ecc_scalar *@var{s}, const struct ecc_curve *@var{ecc})
4260 Initializes @var{s} to represent a scalar suitable for the given curve
4261 @var{ecc}. Allocates storage using the same allocation functions as GMP.
4262 @end deftypefun
4263
4264 @deftypefun void ecc_scalar_clear (struct ecc_scalar *@var{s})
4265 Deallocate storage.
4266 @end deftypefun
4267
4268 @deftypefun int ecc_scalar_set (struct ecc_scalar *@var{s}, const mpz_t @var{z})
4269 Check that @var{z} is in the correct range. If so, copies the value to
4270 @var{s} and returns 1, otherwise returns 0.
4271 @end deftypefun
4272
4273 @deftypefun void ecc_scalar_get (const struct ecc_scalar *@var{s}, mpz_t @var{z})
4274 Extracts the scalar, in GMP @code{mpz_t} representation.
4275 @end deftypefun
4276
4277 To create and verify ECDSA signatures, the following functions are used.
4278
4279 @deftypefun void ecdsa_sign (const struct ecc_scalar *@var{key}, void *@var{random_ctx}, nettle_random_func *@var{random}, size_t @var{digest_length}, const uint8_t *@var{digest}, struct dsa_signature *@var{signature})
4280 Uses the private key @var{key} to create a signature on @var{digest}.
4281 @var{random_ctx} and @var{random} is a randomness generator.
4282 @code{random(random_ctx, length, dst)} should generate @code{length}
4283 random octets and store them at @code{dst}. The signature is stored in
4284 @var{signature}, in the same was as for plain DSA.
4285 @end deftypefun
4286
4287 @deftypefun int ecdsa_verify (const struct ecc_point *@var{pub}, size_t @var{length}, const uint8_t *@var{digest}, const struct dsa_signature *@var{signature})
4288 Uses the public key @var{pub} to verify that @var{signature} is a valid
4289 signature for the message digest @var{digest} (of @var{length} octets).
4290 Returns 1 if the signature is valid, otherwise 0.
4291 @end deftypefun
4292
4293 Finally, to generation of new an ECDSA key pairs
4294
4295 @deftypefun void ecdsa_generate_keypair (struct ecc_point *@var{pub}, struct ecc_scalar *@var{key}, void *@var{random_ctx}, nettle_random_func *@var{random});
4296 @var{pub} and @var{key} is where the resulting key pair is stored. The
4297 structs should be initialized, for the desired ECC curve, before you call this function.
4298
4299 @var{random_ctx} and @var{random} is a randomness generator.
4300 @code{random(random_ctx, length, dst)} should generate @code{length}
4301 random octets and store them at @code{dst}. For advice, see
4302 @xref{Randomness}.
4303 @end deftypefun
4304
4305 @subsubsection Curve25519
4306
4307 Curve25519 is an elliptic curve of Montgomery type, @math{y^2 = x^3 +
4308 486662 x^2 + x @pmod{p}}, with @math{p = 2^255 - 19}. Montgomery curves
4309 have the advantage of simple and efficient point addition based on the
4310 x-coordinate only. This particular curve was proposed by D.~J.~Bernstein
4311 in 2006, for fast Diffie-Hellman key exchange. The group generator is
4312 defined by @math{x = 9} (there are actually two points with @math{x =
4313 9}, differing by the sign of the y-coordinate, but that doesn't matter
4314 for the curve25519 operations which work with the x-coordinate only).
4315
4316 The curve25519 functions are defined as operations on octet strings,
4317 which are interpreted as x-coordinates in little-endian byte order.
4318
4319 Of all the possible input strings, only about half correspond to points
4320 on curve25519, i.e., a value that can be produced by
4321 @code{curve25519_mul_g}. The other half corresponds to points on a
4322 related ``twist curve''. The current implementation of
4323 @code{curve25519_mul} uses a Montgomery ladder for the scalar
4324 multiplication, as suggested in the curve25519 literature, and produces
4325 a well defined output for all possible inputs, no matter if points are
4326 on the proper curve or on its twist. However, at the time of writing, it
4327 is not yet ruled out that other implementations could be faster, and
4328 therefore the behaviour for inputs corresponding to points on the twist
4329 curve must be considered an implementation idiosyncrasy, and may change
4330 in future versions.
4331
4332 @defvr Constant CURVE25519_SIZE
4333 The size of the strings representing curve25519 points and scalars, 32.
4334 @end defvr
4335
4336 @deftypefun void curve25519_mul_g (uint8_t *@var{q}, const uint8_t *@var{n})
4337 Computes @math{Q = N G}, where @math{G} is the group generator and
4338 @math{N} is an integer. The input argument @var{n} and the output
4339 argument @var{q} use a little-endian representation of the scalar and
4340 the x-coordinate, respectively. They are both of size
4341 @code{CURVE25519_SIZE}.
4342
4343 This function is intended to be compatible with the function
4344 @code{crypto_scalar_mult_base} in the NaCl library.
4345 @end deftypefun
4346
4347 @deftypefun void curve25519_mul (uint8_t *@var{q}, const uint8_t *@var{n}, const uint8_t *@var{p})
4348 Computes @math{Q = N P}, where @math{P} is an input point and @math{N}
4349 is an integer. The input arguments @var{n} and @var{p} and the output
4350 argument @var{q} use a little-endian representation of the scalar and
4351 the x-coordinates, respectively. They are all of size
4352 @code{CURVE25519_SIZE}.
4353
4354 The output value is defined only when the input @var{p} is a string
4355 produced by @code{curve25519_mul_g}. (See discussion above, about the
4356 twist curve).
4357
4358 This function is intended to be compatible with the function
4359 @code{crypto_scalar_mult} in the NaCl library.
4360 @end deftypefun
4361
4362 @subsubsection EdDSA
4363 @cindex eddsa
4364
4365 EdDSA is a signature scheme proposed by D.~J.~Bernstein et al. in 2011.
4366 It is defined using a ``Twisted Edwards curve'', of the form @math{-x^2
4367 + y^2 = 1 + d x^2 y^2}. The specific signature scheme Ed25519 uses a
4368 curve which is equivalent to curve25519: The two groups used differ only
4369 by a simple change of coordinates, so that the discrete logarithm
4370 problem is of equal difficulty in both groups.
4371
4372 Unlike other signature schemes in Nettle, the input to the EdDSA sign
4373 and verify functions is the possibly large message itself, not a hash
4374 digest. EdDSA is a variant of Schnorr signatures, where the message is
4375 hashed together with other data during the signature process, providing
4376 resilience to hash-collisions: A successful attack finding collisions in
4377 the hash function does not automatically translate into an attack to
4378 forge signatures. EdDSA also avoids the use of a randomness source by
4379 generating the needed signature nonce from a hash of the private key and
4380 the message, which means that the message is actually hashed twice when
4381 creating a signature. If signing huge messages, it is possible to hash
4382 the message first and pass the short message digest as input to the sign
4383 and verify functions, however, the resilience to hash collision is then
4384 lost.
4385
4386 @defvr Constant ED25519_KEY_SIZE
4387 The size of a private or public Ed25519 key, 32 octets.
4388 @end defvr
4389
4390 @defvr Constant ED25519_SIGNATURE_SIZE
4391 The size of an Ed25519 signature, 64 octets.
4392 @end defvr
4393
4394 @deftypefun void ed25519_sha512_public_key (uint8_t *@var{pub}, const uint8_t *@var{priv})
4395 Computes the public key corresponding to the given private key. Both
4396 input and output are of size @code{ED25519_KEY_SIZE}.
4397 @end deftypefun
4398
4399 @deftypefun void ed25519_sha512_sign (const uint8_t *@var{pub}, const uint8_t *@var{priv}, size_t @var{length}, const uint8_t *@var{msg}, uint8_t *@var{signature})
4400 Signs a message using the provided key pair.
4401 @end deftypefun
4402
4403 @deftypefun int ed25519_sha512_verify (const uint8_t *@var{pub}, size_t @var{length}, const uint8_t *@var{msg}, const uint8_t *@var{signature})
4404 Verifies a message using the provided public key. Returns 1 if the
4405 signature is valid, otherwise 0.
4406 @end deftypefun
4407
4408 @node Randomness, ASCII encoding, Public-key algorithms, Reference
4409 @comment  node-name,  next,  previous,  up
4410 @section Randomness
4411
4412 @cindex Randomness
4413
4414 A crucial ingredient in many cryptographic contexts is randomness: Let
4415 @code{p} be a random prime, choose a random initialization vector
4416 @code{iv}, a random key @code{k} and a random exponent @code{e}, etc. In
4417 the theories, it is assumed that you have plenty of randomness around.
4418 If this assumption is not true in practice, systems that are otherwise
4419 perfectly secure, can be broken. Randomness has often turned out to be
4420 the weakest link in the chain.
4421
4422 In non-cryptographic applications, such as games as well as scientific
4423 simulation, a good randomness generator usually means a generator that
4424 has good statistical properties, and is seeded by some simple function
4425 of things like the current time, process id, and host name.
4426
4427 However, such a generator is inadequate for cryptography, for at least
4428 two reasons:
4429
4430
4431 @itemize
4432
4433 @item
4434 It's too easy for an attacker to guess the initial seed. Even if it will
4435 take some 2^32 tries before he guesses right, that's far too easy. For
4436 example, if the process id is 16 bits, the resolution of ``current time''
4437 is one second, and the attacker knows what day the generator was seeded,
4438 there are only about 2^32 possibilities to try if all possible values
4439 for the process id and time-of-day are tried.
4440
4441 @item
4442 The generator output reveals too much. By observing only a small segment
4443 of the generator's output, its internal state can be recovered, and from
4444 there, all previous output and all future output can be computed by the
4445 attacker. 
4446 @end itemize
4447
4448 A randomness generator that is used for cryptographic purposes must have
4449 better properties. Let's first look at the seeding, as the issues here
4450 are mostly independent of the rest of the generator. The initial state
4451 of the generator (its seed) must be unguessable by the attacker. So
4452 what's unguessable? It depends on what the attacker already knows. The
4453 concept used in information theory to reason about such things is called
4454 ``entropy'', or ``conditional entropy'' (not to be confused with the
4455 thermodynamic concept with the same name). A reasonable requirement is
4456 that the seed contains a conditional entropy of at least some 80-100
4457 bits. This property can be explained as follows: Allow the attacker to
4458 ask @code{n} yes-no-questions, of his own choice, about the seed. If
4459 the attacker, using this question-and-answer session, as well as any
4460 other information he knows about the seeding process, still can't guess
4461 the seed correctly, then the conditional entropy is more than @code{n}
4462 bits.
4463
4464 @cindex Entropy
4465 @cindex Conditional entropy
4466
4467 Let's look at an example. Say information about timing of received
4468 network packets is used in the seeding process. If there is some random
4469 network traffic going on, this will contribute some bits of entropy or
4470 ``unguessability'' to the seed. However, if the attacker can listen in to
4471 the local network, or if all but a small number of the packets were
4472 transmitted by machines that the attacker can monitor, this additional
4473 information makes the seed easier for the attacker to figure out. Even
4474 if the information is exactly the same, the conditional entropy, or
4475 unguessability, is smaller for an attacker that knows some of it already
4476 before the hypothetical question-and-answer session.
4477
4478 Seeding of good generators is usually based on several sources. The key
4479 point here is that the amount of unguessability that each source
4480 contributes, depends on who the attacker is. Some sources that have been
4481 used are:
4482
4483 @table @asis
4484 @item High resolution timing of i/o activities
4485 Such as completed blocks from spinning hard disks, network packets, etc.
4486 Getting access to such information is quite system dependent, and not
4487 all systems include suitable hardware. If available, it's one of the
4488 better randomness source one can find in a digital, mostly predictable,
4489 computer.
4490
4491 @item User activity
4492 Timing and contents of user interaction events is another popular source
4493 that is available for interactive programs (even if I suspect that it is
4494 sometimes used in order to make the user feel good, not because the
4495 quality of the input is needed or used properly). Obviously, not
4496 available when a machine is unattended. Also beware of networks: User
4497 interaction that happens across a long serial cable, @acronym{TELNET}
4498 session, or even @acronym{SSH} session may be visible to an attacker, in
4499 full or partially.
4500
4501 @item Audio input
4502 Any room, or even a microphone input that's left unconnected, is a
4503 source of some random background noise, which can be fed into the
4504 seeding process.
4505
4506 @item Specialized hardware
4507 Hardware devices with the sole purpose of generating random data have
4508 been designed. They range from radioactive samples with an attached
4509 Geiger counter, to amplification of the inherent noise in electronic
4510 components such as diodes and resistors, to low-frequency sampling of
4511 chaotic systems. Hashing successive images of a Lava lamp is a
4512 spectacular example of the latter type.
4513
4514 @item Secret information
4515 Secret information, such as user passwords or keys, or private files
4516 stored on disk, can provide some unguessability. A problem is that if
4517 the information is revealed at a later time, the unguessability
4518 vanishes. Another problem is that this kind of information tends to be
4519 fairly constant, so if you rely on it and seed your generator regularly,
4520 you risk constructing almost similar seeds or even constructing the same
4521 seed more than once.
4522 @end table
4523
4524 For all practical sources, it's difficult but important to provide a
4525 reliable lower bound on the amount of unguessability that it provides.
4526 Two important points are to make sure that the attacker can't observe
4527 your sources (so if you like the Lava lamp idea, remember that you have
4528 to get your own lamp, and not put it by a window or anywhere else where
4529 strangers can see it), and that hardware failures are detected. What if
4530 the bulb in the Lava lamp, which you keep locked into a cupboard
4531 following the above advice, breaks after a few months?
4532
4533 So let's assume that we have been able to find an unguessable seed,
4534 which contains at least 80 bits of conditional entropy, relative to all
4535 attackers that we care about (typically, we must at the very least
4536 assume that no attacker has root privileges on our machine).
4537
4538 How do we generate output from this seed, and how much can we get? Some
4539 generators (notably the Linux @file{/dev/random} generator) tries to
4540 estimate available entropy and restrict the amount of output. The goal
4541 is that if you read 128 bits from @file{/dev/random}, you should get 128
4542 ``truly random'' bits. This is a property that is useful in some
4543 specialized circumstances, for instance when generating key material for
4544 a one time pad, or when working with unconditional blinding, but in most
4545 cases, it doesn't matter much. For most application, there's no limit on
4546 the amount of useful ``random'' data that we can generate from a small
4547 seed; what matters is that the seed is unguessable and that the
4548 generator has good cryptographic properties.
4549
4550 At the heart of all generators lies its internal state. Future output
4551 is determined by the internal state alone. Let's call it the generator's
4552 key. The key is initialized from the unguessable seed. Important
4553 properties of a generator are:
4554
4555 @table @dfn
4556
4557 @item Key-hiding
4558 An attacker observing the output should not be able to recover the
4559 generator's key.
4560
4561 @item Independence of outputs
4562 Observing some of the output should not help the attacker to guess
4563 previous or future output.
4564
4565 @item Forward secrecy
4566 Even if an attacker compromises the generator's key, he should not be
4567 able to guess the generator output @emph{before} the key compromise.
4568
4569 @item Recovery from key compromise
4570 If an attacker compromises the generator's key, he can compute
4571 @emph{all} future output. This is inevitable if the generator is seeded
4572 only once, at startup. However, the generator can provide a reseeding
4573 mechanism, to achieve recovery from key compromise. More precisely: If
4574 the attacker compromises the key at a particular time @code{t_1}, there
4575 is another later time @code{t_2}, such that if the attacker observes all
4576 output generated between @code{t_1} and @code{t_2}, he still can't guess
4577 what output is generated after @code{t_2}.
4578
4579 @end table
4580
4581 Nettle includes one randomness generator that is believed to have all
4582 the above properties, and two simpler ones.
4583
4584 @acronym{ARCFOUR}, like any stream cipher, can be used as a randomness
4585 generator. Its output should be of reasonable quality, if the seed is
4586 hashed properly before it is used with @code{arcfour_set_key}. There's
4587 no single natural way to reseed it, but if you need reseeding, you
4588 should be using Yarrow instead.
4589
4590 The ``lagged Fibonacci'' generator in @file{<nettle/knuth-lfib.h>} is a
4591 fast generator with good statistical properties, but is @strong{not} for
4592 cryptographic use, and therefore not documented here. It is included
4593 mostly because the Nettle test suite needs to generate some test data
4594 from a small seed.
4595
4596 The recommended generator to use is Yarrow, described below.
4597
4598 @subsection Yarrow
4599
4600 Yarrow is a family of pseudo-randomness generators, designed for
4601 cryptographic use, by John Kelsey, Bruce Schneier and Niels Ferguson.
4602 Yarrow-160 is described in a paper at
4603 @url{http://www.counterpane.com/yarrow.html}, and it uses @acronym{SHA1}
4604 and triple-DES, and has a 160-bit internal state. Nettle implements
4605 Yarrow-256, which is similar, but uses @acronym{SHA256} and
4606 @acronym{AES} to get an internal state of 256 bits.
4607
4608 Yarrow was an almost finished project, the paper mentioned above is the
4609 closest thing to a specification for it, but some smaller details are
4610 left out. There is no official reference implementation or test cases.
4611 This section includes an overview of Yarrow, but for the details of
4612 Yarrow-256, as implemented by Nettle, you have to consult the source
4613 code. Maybe a complete specification can be written later.
4614
4615 Yarrow can use many sources (at least two are needed for proper
4616 reseeding), and two randomness ``pools'', referred to as the ``slow pool'' and
4617 the ``fast pool''. Input from the sources is fed alternatingly into the
4618 two pools. When one of the sources has contributed 100 bits of entropy
4619 to the fast pool, a ``fast reseed'' happens and the fast pool is mixed
4620 into the internal state. When at least two of the sources have
4621 contributed at least 160 bits each to the slow pool, a ``slow reseed''
4622 takes place. The contents of both pools are mixed into the internal
4623 state. These procedures should ensure that the generator will eventually
4624 recover after a key compromise.
4625
4626 The output is generated by using @acronym{AES} to encrypt a counter,
4627 using the generator's current key. After each request for output,
4628 another 256 bits are generated which replace the key. This ensures
4629 forward secrecy.
4630
4631 Yarrow can also use a @dfn{seed file} to save state across restarts.
4632 Yarrow is seeded by either feeding it the contents of the previous seed
4633 file, or feeding it input from its sources until a slow reseed happens.
4634
4635 Nettle defines Yarrow-256 in @file{<nettle/yarrow.h>}. 
4636
4637 @deftp {Context struct} {struct yarrow256_ctx}
4638 @end deftp
4639
4640 @deftp {Context struct} {struct yarrow_source}
4641 Information about a single source.
4642 @end deftp
4643
4644 @defvr Constant YARROW256_SEED_FILE_SIZE
4645 Recommended size of the Yarrow-256 seed file.
4646 @end defvr
4647
4648 @deftypefun void yarrow256_init (struct yarrow256_ctx *@var{ctx}, unsigned @var{nsources}, struct yarrow_source *@var{sources})
4649 Initializes the yarrow context, and its @var{nsources} sources. It's
4650 possible to call it with @var{nsources}=0 and @var{sources}=NULL, if
4651 you don't need the update features.
4652 @end deftypefun
4653
4654 @deftypefun void yarrow256_seed (struct yarrow256_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{seed_file})
4655 Seeds Yarrow-256 from a previous seed file. @var{length} should be at least
4656 @code{YARROW256_SEED_FILE_SIZE}, but it can be larger.
4657
4658 The generator will trust you that the @var{seed_file} data really is
4659 unguessable. After calling this function, you @emph{must} overwrite the old
4660 seed file with newly generated data from @code{yarrow256_random}. If it's
4661 possible for several processes to read the seed file at about the same
4662 time, access must be coordinated using some locking mechanism.
4663 @end deftypefun
4664
4665 @deftypefun int yarrow256_update (struct yarrow256_ctx *@var{ctx}, unsigned @var{source}, unsigned @var{entropy}, size_t @var{length}, const uint8_t *@var{data})
4666 Updates the generator with data from source @var{SOURCE} (an index that
4667 must be smaller than the number of sources). @var{entropy} is your
4668 estimated lower bound for the entropy in the data, measured in bits.
4669 Calling update with zero @var{entropy} is always safe, no matter if the
4670 data is random or not.
4671
4672 Returns 1 if a reseed happened, in which case an application using a
4673 seed file may want to generate new seed data with
4674 @code{yarrow256_random} and overwrite the seed file. Otherwise, the
4675 function returns 0.
4676 @end deftypefun
4677
4678 @deftypefun void yarrow256_random (struct yarrow256_ctx *@var{ctx}, size_t @var{length}, uint8_t *@var{dst})
4679 Generates @var{length} octets of output. The generator must be seeded
4680 before you call this function.
4681
4682 If you don't need forward secrecy, e.g. if you need non-secret
4683 randomness for initialization vectors or padding, you can gain some
4684 efficiency by buffering, calling this function for reasonably large
4685 blocks of data, say 100-1000 octets at a time.
4686 @end deftypefun
4687
4688 @deftypefun int yarrow256_is_seeded (struct yarrow256_ctx *@var{ctx})
4689 Returns 1 if the generator is seeded and ready to generate output,
4690 otherwise 0.
4691 @end deftypefun
4692
4693 @deftypefun unsigned yarrow256_needed_sources (struct yarrow256_ctx *@var{ctx})
4694 Returns the number of sources that must reach the threshold before a
4695 slow reseed will happen. Useful primarily when the generator is unseeded.
4696 @end deftypefun
4697
4698 @deftypefun void yarrow256_fast_reseed (struct yarrow256_ctx *@var{ctx})
4699 @deftypefunx void yarrow256_slow_reseed (struct yarrow256_ctx *@var{ctx})
4700 Causes a fast or slow reseed to take place immediately, regardless of the
4701 current entropy estimates of the two pools. Use with care.
4702 @end deftypefun
4703
4704 Nettle includes an entropy estimator for one kind of input source: User
4705 keyboard input.
4706
4707 @deftp {Context struct} {struct yarrow_key_event_ctx}
4708 Information about recent key events.
4709 @end deftp
4710
4711 @deftypefun void yarrow_key_event_init (struct yarrow_key_event_ctx *@var{ctx})
4712 Initializes the context.
4713 @end deftypefun
4714
4715 @deftypefun unsigned yarrow_key_event_estimate (struct yarrow_key_event_ctx *@var{ctx}, unsigned @var{key}, unsigned @var{time})
4716 @var{key} is the id of the key (ASCII value, hardware key code, X
4717 keysym, @dots{}, it doesn't matter), and @var{time} is the timestamp of
4718 the event. The time must be given in units matching the resolution by
4719 which you read the clock. If you read the clock with microsecond
4720 precision, @var{time} should be provided in units of microseconds. But
4721 if you use @code{gettimeofday} on a typical Unix system where the clock
4722 ticks 10 or so microseconds at a time, @var{time} should be given in
4723 units of 10 microseconds.
4724
4725 Returns an entropy estimate, in bits, suitable for calling
4726 @code{yarrow256_update}. Usually, 0, 1 or 2 bits.
4727 @end deftypefun
4728
4729 @node ASCII encoding, Miscellaneous functions, Randomness, Reference
4730 @comment  node-name,  next,  previous,  up
4731 @section ASCII encoding
4732
4733 Encryption will transform your data from text into binary format, and that
4734 may be a problem if, for example, you want to send the data as if it was
4735 plain text in an email, or store it along with descriptive text in a
4736 file. You may then use an encoding from binary to text: each binary byte
4737 is translated into a number of bytes of plain text.
4738
4739 A base-N encoding of data is one representation of data that only uses N
4740 different symbols (instead of the 256 possible values of a byte).
4741
4742 The base64 encoding will always use alphanumeric (upper and lower case)
4743 characters and the '+', '/' and '=' symbols to represent the data. Four
4744 output characters are generated for each three bytes of input. In case
4745 the length of the input is not a multiple of three, padding characters
4746 are added at the end. There's also a ``URL safe'' variant, which is
4747 useful for encoding binary data into URLs and filenames. See @cite{RFC
4748 4648}.
4749
4750 The base16 encoding, also known as ``hexadecimal'', uses the decimal
4751 digits and the letters from A to F. Two hexadecimal digits are generated
4752 for each input byte.
4753
4754 Nettle supports both base64 and base16 encoding and decoding.
4755
4756 Encoding and decoding uses a context struct to maintain its state (with
4757 the exception of base16 encoding, which doesn't need any). To encode or
4758 decode the data, first initialize the context, then call the update
4759 function as many times as necessary, and complete the operation by
4760 calling the final function.
4761
4762 The following functions can be used to perform base64 encoding and decoding.
4763 They are defined in @file{<nettle/base64.h>}.
4764
4765 @deftp {Context struct} {struct base64_encode_ctx}
4766 @end deftp
4767
4768 @deftypefun {void} base64_encode_init (struct base64_encode_ctx *@var{ctx})
4769 @deftypefunx {void} base64url_encode_init (struct base64_encode_ctx *@var{ctx})
4770 Initializes a base64 context. This is necessary before starting an
4771 encoding session. @code{base64_encode_init} selects the standard base64
4772 alphabet, while @code{base64url_encode_init} selects the URL safe
4773 alphabet.
4774 @end deftypefun
4775
4776
4777 @deftypefun {size_t} base64_encode_single (struct base64_encode_ctx *@var{ctx}, uint8_t *@var{dst}, uint8_t @var{src})
4778 Encodes a single byte. Returns amount of output (always 1 or 2).
4779 @end deftypefun
4780
4781 @deffn Macro BASE64_ENCODE_LENGTH (@var{length})
4782 The maximum number of output bytes when passing @var{length} input bytes
4783 to @code{base64_encode_update}.
4784 @end deffn
4785
4786 @deftypefun {size_t} base64_encode_update (struct base64_encode_ctx *@var{ctx}, uint8_t *@var{dst}, size_t @var{length}, const uint8_t *@var{src})
4787 After @var{ctx} is initialized, this function may be called to encode @var{length}
4788 bytes from @var{src}. The result will be placed in @var{dst}, and the return value
4789 will be the number of bytes generated. Note that @var{dst} must be at least of size
4790 BASE64_ENCODE_LENGTH(@var{length}).
4791 @end deftypefun
4792
4793 @defvr Constant BASE64_ENCODE_FINAL_LENGTH
4794 The maximum amount of output from @code{base64_encode_final}.
4795 @end defvr
4796
4797 @deftypefun {size_t} base64_encode_final (struct base64_encode_ctx *@var{ctx}, uint8_t *@var{dst})
4798 After calling base64_encode_update one or more times, this function
4799 should be called to generate the final output bytes, including any
4800 needed paddding. The return value is the number of output bytes
4801 generated.
4802 @end deftypefun
4803
4804 @deftp {Context struct} {struct base64_decode_ctx}
4805 @end deftp
4806
4807 @deftypefun {void} base64_decode_init (struct base64_decode_ctx *@var{ctx})
4808 @deftypefunx {void} base64url_decode_init (struct base64_decode_ctx *@var{ctx})
4809 Initializes a base64 decoding context. This is necessary before starting
4810 a decoding session. @code{base64_decode_init} selects the standard
4811 base64 alphabet, while @code{base64url_decode_init} selects the URL safe
4812 alphabet.
4813 @end deftypefun
4814
4815 @deftypefun {int} base64_decode_single (struct base64_decode_ctx *@var{ctx}, uint8_t *@var{dst}, uint8_t @var{src})
4816 Decodes a single byte (@var{src}) and stores the result in @var{dst}.
4817 Returns amount of output (0 or 1), or -1 on errors.
4818 @end deftypefun
4819
4820 @deffn Macro BASE64_DECODE_LENGTH (@var{length})
4821 The maximum number of output bytes when passing @var{length} input bytes
4822 to @code{base64_decode_update}.
4823 @end deffn
4824
4825 @deftypefun {void} base64_decode_update (struct base64_decode_ctx *@var{ctx}, size_t *@var{dst_length}, uint8_t *@var{dst}, size_t @var{src_length}, const uint8_t *@var{src})
4826 After @var{ctx} is initialized, this function may be called to decode
4827 @var{src_length} bytes from @var{src}. @var{dst} should point to an area
4828 of size at least BASE64_DECODE_LENGTH(@var{src_length}). The amount of data
4829 generated is returned in *@var{dst_length}. Returns 1 on success
4830 and 0 on error.
4831 @end deftypefun
4832
4833 @deftypefun {int} base64_decode_final (struct base64_decode_ctx *@var{ctx})
4834 Check that final padding is correct. Returns 1 on success, and 0 on
4835 error.
4836 @end deftypefun
4837
4838 Similarly to the base64 functions, the following functions perform base16 encoding,
4839 and are defined in @file{<nettle/base16.h>}. Note that there is no encoding context
4840 necessary for doing base16 encoding.
4841
4842 @deftypefun {void} base16_encode_single (uint8_t *@var{dst}, uint8_t @var{src})
4843 Encodes a single byte. Always stores two digits in @var{dst}[0] and @var{dst}[1].
4844 @end deftypefun
4845
4846 @deffn Macro BASE16_ENCODE_LENGTH (@var{length})
4847 The number of output bytes when passing @var{length} input bytes to
4848 @code{base16_encode_update}.
4849 @end deffn
4850
4851 @deftypefun {void} base16_encode_update (uint8_t *@var{dst}, size_t @var{length}, const uint8_t *@var{src})
4852 Always stores BASE16_ENCODE_LENGTH(@var{length}) digits in @var{dst}.
4853 @end deftypefun
4854
4855 @deftp {Context struct} {struct base16_decode_ctx}
4856 @end deftp
4857
4858 @deftypefun {void} base16_decode_init (struct base16_decode_ctx *@var{ctx})
4859 Initializes a base16 decoding context. This is necessary before starting a decoding
4860 session.
4861 @end deftypefun
4862
4863 @deftypefun {int} base16_decode_single (struct base16_decode_ctx *@var{ctx}, uint8_t *@var{dst}, uint8_t @var{src})
4864 Decodes a single byte from @var{src} into @var{dst}. Returns amount of output (0 or 1), or -1 on errors.
4865 @end deftypefun
4866
4867 @deffn Macro BASE16_DECODE_LENGTH (@var{length})
4868 The maximum number of output bytes when passing @var{length} input bytes
4869 to @code{base16_decode_update}.
4870 @end deffn
4871
4872 @deftypefun {int} base16_decode_update (struct base16_decode_ctx *@var{ctx}, size_t *@var{dst_length}, uint8_t *@var{dst}, size_t @var{src_length}, const uint8_t *@var{src})
4873 After @var{ctx} is initialized, this function may be called to decode
4874 @var{src_length} bytes from @var{src}. @var{dst} should point to an area
4875 of size at least BASE16_DECODE_LENGTH(@var{src_length}). The amount of data
4876 generated is returned in *@var{dst_length}. Returns 1 on success
4877 and 0 on error.
4878 @end deftypefun
4879
4880 @deftypefun {int} base16_decode_final (struct base16_decode_ctx *@var{ctx})
4881 Checks that the end of data is correct (i.e., an even number of
4882 hexadecimal digits have been seen). Returns 1 on success, and 0 on
4883 error.
4884 @end deftypefun
4885
4886 @node Miscellaneous functions, Compatibility functions, ASCII encoding, Reference
4887 @comment  node-name,  next,  previous,  up
4888 @section Miscellaneous functions
4889
4890 @deftypefun {void *} memxor (void *@var{dst}, const void *@var{src}, size_t @var{n})
4891 XORs the source area on top of the destination area. The interface
4892 doesn't follow the Nettle conventions, because it is intended to be
4893 similar to the ANSI-C @code{memcpy} function.
4894 @end deftypefun
4895
4896 @deftypefun {void *} memxor3 (void *@var{dst}, const void *@var{a}, const void *@var{b}, size_t @var{n})
4897 Like @code{memxor}, but takes two source areas and separate
4898 destination area.
4899 @end deftypefun
4900
4901
4902 @code{memxor} is declared in @file{<nettle/memxor.h>}.
4903
4904 @node Compatibility functions,  , Miscellaneous functions, Reference
4905 @comment  node-name,  next,  previous,  up
4906 @section Compatibility functions
4907
4908 For convenience, Nettle includes alternative interfaces to some
4909 algorithms, for compatibility with some other popular crypto toolkits.
4910 These are not fully documented here; refer to the source or to the
4911 documentation for the original implementation.
4912
4913 MD5 is defined in [RFC 1321], which includes a reference implementation.
4914 Nettle defines a compatible interface to MD5 in
4915 @file{<nettle/md5-compat.h>}. This file defines the typedef
4916 @code{MD5_CTX}, and declares the functions @code{MD5Init}, @code{MD5Update} and
4917 @code{MD5Final}.
4918
4919 Eric Young's ``libdes'' (also part of OpenSSL) is a quite popular DES
4920 implementation. Nettle includes a subset if its interface in
4921 @file{<nettle/des-compat.h>}. This file defines the typedefs
4922 @code{des_key_schedule} and @code{des_cblock}, two constants
4923 @code{DES_ENCRYPT} and @code{DES_DECRYPT}, and declares one global
4924 variable @code{des_check_key}, and the functions @code{des_cbc_cksum}
4925 @code{des_cbc_encrypt}, @code{des_ecb2_encrypt},
4926 @code{des_ecb3_encrypt}, @code{des_ecb_encrypt},
4927 @code{des_ede2_cbc_encrypt}, @code{des_ede3_cbc_encrypt},
4928 @code{des_is_weak_key}, @code{des_key_sched}, @code{des_ncbc_encrypt}
4929 @code{des_set_key}, and @code{des_set_odd_parity}.
4930
4931 @node Nettle soup, Installation, Reference, Top
4932 @comment  node-name,  next,  previous,  up
4933 @chapter Traditional Nettle Soup
4934 For the serious nettle hacker, here is a recipe for nettle soup. 4 servings.
4935
4936 @itemize @w{}
4937 @item
4938 1 liter fresh nettles (urtica dioica)
4939 @item
4940 2 tablespoons butter
4941 @item
4942 3 tablespoons flour
4943 @item
4944 1 liter stock (meat or vegetable)
4945 @item
4946 1/2 teaspoon salt
4947 @item
4948 a tad white pepper
4949 @item
4950 some cream or milk
4951 @end itemize
4952
4953 Gather 1 liter fresh nettles. Use gloves! Small, tender shoots are
4954 preferable but the tops of larger nettles can also be used.
4955
4956 Rinse the nettles very well. Boil them for 10 minutes in lightly salted
4957 water. Strain the nettles and save the water. Hack the nettles. Melt the
4958 butter and mix in the flour. Dilute with stock and the nettle-water you
4959 saved earlier. Add the hacked nettles. If you wish you can add some milk
4960 or cream at this stage. Bring to a boil and let boil for a few minutes.
4961 Season with salt and pepper.
4962
4963 Serve with boiled egg-halves.
4964
4965 @c And the original Swedish version.
4966 @ignore
4967
4968 Recept på nässelsoppa
4969 4 portioner
4970
4971 1 l färska nässlor
4972 2 msk smör
4973 3 msk vetemjöl
4974 1 l kött- eller grönsaksbuljong
4975 1/2 tsk salt
4976 1-2 krm peppar
4977 (lite grädde eller mjölk)
4978
4979 Plocka 1 liter färska nässlor. Använd handskar! Helst små och späda
4980 skott, men topparna av större nässlor går också bra.
4981
4982 Skölj nässlorna väl. Förväll dem ca 10 minuter i lätt saltat vatten.
4983 Häll av och spara spadet. Hacka nässlorna. Smält smöret, rör i mjöl och
4984 späd med buljong och nässelspad. Lägg i de hackade nässlorna. Om så
4985 önskas, häll i en skvätt mjölk eller grädde. Koka några minuter, och
4986 smaksätt med salt och peppar.
4987
4988 Servera med kokta ägghalvor.
4989 @end ignore
4990
4991 @node Installation, Index, Nettle soup, Top
4992 @comment  node-name,  next,  previous,  up
4993 @chapter Installation
4994
4995 Nettle uses @command{autoconf}. To build it, unpack the source and run
4996
4997 @example
4998 ./configure
4999 make
5000 make check
5001 make install
5002 @end example
5003
5004 @noindent
5005 to install it under the default prefix, @file{/usr/local}. Using GNU
5006 make is strongly recommended. By default, both static and shared
5007 libraries are built and installed.
5008
5009 To get a list of configure options, use @code{./configure --help}. Some
5010 of the more interesting are:
5011
5012 @table @option
5013 @item --enable-fat
5014 Include multiple versions of certain functions in the library, and
5015 select the ones to use at run-time, depending on available processor
5016 features. Supported for ARM and x86_64.
5017
5018 @item --enable-mini-gmp
5019 Use the smaller and slower ``mini-gmp'' implementation of the bignum
5020 functions needed for public-key cryptography, instead of the real GNU
5021 GMP library. This option is intended primarily for smaller embedded
5022 systems. Note that builds using mini-gmp are @strong{not} binary compatible
5023 with regular builds of Nettle, and more likely to leak side-channel
5024 information.
5025
5026 @item --disable-shared
5027 Omit building the shared libraries.
5028
5029 @item --disable-dependency-tracking
5030 Disable the automatic dependency tracking. You will likely need this
5031 option to be able to build with BSD make.
5032
5033 @end table
5034
5035 @node Index,  , Installation, Top
5036 @comment  node-name,  next,  previous,  up
5037 @unnumbered Function and Concept Index
5038
5039 @printindex cp
5040
5041 @bye
5042 \f
5043 Local Variables:
5044 ispell-local-dictionary: "american"
5045 ispell-skip-region-alist: (
5046  (ispell-words-keyword forward-line)
5047  ("^@example" . "^@end.*example")
5048  ("^@ignore" . "^@end.*ignore")
5049  ("^@\\(end\\|syncodeindex\\|vskip\\|\\(un\\)?macro\\|node\\|deftp\\) .*$")
5050  ("^@\\(printindex\\|set\\) .*$")
5051  ("^@def.*$")
5052  ;; Allows one level of nested braces in the argument 
5053  ("@\\(uref\\|value\\|badspell\\|code\\|file\\|var\\|url\\){[^{}]*\\({[^{}]*}[^{}]*\\)*}")
5054  ("@[a-z]+[{ ]")
5055  ("@[a-z]+$")
5056  ("\input texinfo.*$")
5057  ("ispell-ignore" . "ispell-end-ignore")
5058  ("^Local Variables:$" . "^End:$"))
5059 End:
5060
5061 @c  LocalWords:  cryptographics crypto LSH GNUPG API GPL LGPL aes rijndael ller
5062 @c  LocalWords:  Sevilla arcfour RC Niels Dassen Colin Kuchling Biham sha Ruud
5063 @c  LocalWords:  Gutmann twofish de Rooij struct MB Rivest RFC Nettle's ECB CBC
5064 @c  LocalWords:  RSA Daemen Rijnmen Schneier DES's ede structs oddnesses HMAC
5065 @c  LocalWords:  NIST Alice's GMP bignum Diffie Adi Shamir Adleman Euclid's ASN
5066 @c  LocalWords:  PKCS callbacks Young's urtica dioica autoconf SSH tad
5067 @c  LocalWords:  unguessability reseeding reseed alternatingly keysym subkeys
5068 @c  LocalWords:  DSA gmp FIPS DSS libdes OpenSSL ARCTWO Josefsson Nikos Andreas
5069 @c  LocalWords:  Mavroyanopoulos Sigfridsson Comstedt interoperability Sparc IC
5070 @c  LocalWords:  DES FIXME Rivest's plaintext ciphertext CTR XORed timestamp
5071 @c  LocalWords:  XORs cryptologists libnettle libhogweed GCM ECDSA NTT
5072 @c  LocalWords:  toolkits BLOWFISH Möller RIPEMD libgcrypt PBKDF Shishi
5073 @c  LocalWords:  GnuTLS Gutmann's GOSTHASH GOST Aleksey Kravchenko ECC
5074 @c  LocalWords:  rhash Mavrogiannopoulos Keccak Bertoni
5075 @c  LocalWords:  Michaël Peeters Assche Dobbertin Antoon Bosselaers KDF
5076 @c  LocalWords:  Preneel rôle McGrew Viega KDFs PBKDFs passphrase PRF
5077 @c  LocalWords:  th deallocate pre bitsize multi lookup secp startup
5078 @c  LocalWords:  typedef typedef