1 \input texinfo @c -*-texinfo-*-
3 @setfilename nettle.info
4 @settitle Nettle: a low-level cryptographic library
5 @documentencoding ISO-8859-1
6 @footnotestyle separate
11 @set AUTHOR Niels Möller
14 This manual is for the Nettle library (version @value{UPDATED-FOR}), a
15 low-level cryptographic library.
17 Originally written 2001 by @value{AUTHOR}, updated 2010.
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.
28 @subtitle For the Nettle Library version @value{UPDATED-FOR}
29 @author @value{AUTHOR}
31 @vskip 0pt plus 1filll
35 @dircategory Encryption
37 * Nettle: (nettle). A low-level cryptographic library.
43 @node Top, Introduction, (dir), (dir)
44 @comment node-name, next, previous, up
47 This document describes the Nettle low-level cryptographic library. You
48 can use the library directly from your C programs, or write or use an
49 object-oriented wrapper for your favorite language or application.
54 * Introduction:: What is Nettle?
55 * Copyright:: Your rights.
56 * Conventions:: General interface conventions.
57 * Example:: An example program.
58 * Linking:: Linking with the libnettle and libhogweed.
59 * Reference:: All Nettle functions and features.
60 * Nettle soup:: For the serious nettle hacker.
61 * Installation:: How to install Nettle.
62 * Index:: Function and concept index.
67 @node Introduction, Copyright, Top, Top
68 @comment node-name, next, previous, up
71 Nettle is a cryptographic library that is designed to fit easily in more
72 or less any context: In crypto toolkits for object-oriented languages
73 (C++, Python, Pike, ...), in applications like LSH or GNUPG, or even in
74 kernel space. In most contexts, you need more than the basic
75 cryptographic algorithms, you also need some way to keep track of available
76 algorithms, their properties and variants. You often have some algorithm
77 selection process, often dictated by a protocol you want to implement.
79 And as the requirements of applications differ in subtle and not so
80 subtle ways, an API that fits one application well can be a pain to use
81 in a different context. And that is why there are so many different
82 cryptographic libraries around.
84 Nettle tries to avoid this problem by doing one thing, the low-level
85 crypto stuff, and providing a @emph{simple} but general interface to it.
86 In particular, Nettle doesn't do algorithm selection. It doesn't do
87 memory allocation. It doesn't do any I/O.
89 The idea is that one can build several application and context specific
90 interfaces on top of Nettle, and share the code, test cases, benchmarks,
91 documentation, etc. Examples are the Nettle module for the Pike
92 language, and LSH, which both use an object-oriented abstraction on top
95 This manual explains how to use the Nettle library. It also tries to
96 provide some background on the cryptography, and advice on how to best
99 @node Copyright, Conventions, Introduction, Top
100 @comment node-name, next, previous, up
103 Nettle is distributed under the GNU General Public License (GPL) (see
104 the file COPYING for details). However, most of the individual files
105 are dual licensed under less restrictive licenses like the GNU Lesser
106 General Public License (LGPL), or are in the public domain. This means
107 that if you don't use the parts of nettle that are GPL-only, you have
108 the option to use the Nettle library just as if it were licensed under
109 the LGPL. To find the current status of particular files, you have to
110 read the copyright notices at the top of the files.
112 This manual is in the public domain. You may freely copy it in whole or
113 in part, e.g., into documentation of programs that build on Nettle.
114 Attribution, as well as contribution of improvements to the text, is of
115 course appreciated, but it is not required.
117 A list of the supported algorithms, their origins and licenses:
121 The implementation of the AES cipher (also known as rijndael) is written
122 by Rafael Sevilla. Assembler for x86 by Rafael Sevilla and
123 @value{AUTHOR}, Sparc assembler by @value{AUTHOR}. Released under the
127 The implementation of the ARCFOUR (also known as RC4) cipher is written
128 by @value{AUTHOR}. Released under the LGPL.
131 The implementation of the ARCTWO (also known as RC2) cipher is written
132 by Nikos Mavroyanopoulos and modified by Werner Koch and Simon
133 Josefsson. Released under the LGPL.
136 The implementation of the BLOWFISH cipher is written by Werner Koch,
137 copyright owned by the Free Software Foundation. Also hacked by Ray
138 Dassen and @value{AUTHOR}. Released under the GPL.
141 The C implementation is by Nippon Telegraph and Telephone Corporation
142 (NTT), heavily modified by @value{AUTHOR}. Assembler for x86 by
143 @value{AUTHOR}. Released under the LGPL.
146 The implementation of the CAST128 cipher is written by Steve Reid.
147 Released into the public domain.
150 The implementation of the DES cipher is written by Dana L. How, and
151 released under the LGPL.
154 The implementation of MD2 is written by Andrew Kuchling, and hacked
155 some by Andreas Sigfridsson and @value{AUTHOR}. Python Cryptography
156 Toolkit license (essentially public domain).
159 This is almost the same code as for MD5 below, with modifications by
160 Marcus Comstedt. Released into the public domain.
163 The implementation of the MD5 message digest is written by Colin Plumb.
164 It has been hacked some more by Andrew Kuchling and @value{AUTHOR}.
165 Released into the public domain.
168 The implementation of the SERPENT cipher is written by Ross Anderson,
169 Eli Biham, and Lars Knudsen, adapted to LSH by Rafael Sevilla, and to
170 Nettle by @value{AUTHOR}. Released under the GPL.
173 The C implementation of the SHA1 message digest is written by Peter
174 Gutmann, and hacked some more by Andrew Kuchling and @value{AUTHOR}.
175 Released into the public domain. Assembler for x86 by @value{AUTHOR},
176 released under the LGPL.
178 @item SHA224, SHA256, SHA384, and SHA512
179 Written by @value{AUTHOR}, using Peter Gutmann's SHA1 code as a model.
180 Released under the LGPL.
183 The implementation of the TWOFISH cipher is written by Ruud de Rooij.
184 Released under the LGPL.
187 Written by @value{AUTHOR}, released under the LGPL. Uses the GMP library
188 for bignum operations.
191 Written by @value{AUTHOR}, released under the LGPL. Uses the GMP library
192 for bignum operations.
195 @node Conventions, Example, Copyright, Top
196 @comment node-name, next, previous, up
199 For each supported algorithm, there is an include file that defines a
200 @emph{context struct}, a few constants, and declares functions for
201 operating on the context. The context struct encapsulates all information
202 needed by the algorithm, and it can be copied or moved in memory with no
205 For consistency, functions for different algorithms are very similar,
206 but there are some differences, for instance reflecting if the key setup
207 or encryption function differ for encryption and decryption, and whether
208 or not key setup can fail. There are also differences between algorithms
209 that don't show in function prototypes, but which the application must
210 nevertheless be aware of. There is no big difference between the
211 functions for stream ciphers and for block ciphers, although they should
212 be used quite differently by the application.
214 If your application uses more than one algorithm of the same type, you
215 should probably create an interface that is tailor-made for your needs,
216 and then write a few lines of glue code on top of Nettle.
218 By convention, for an algorithm named @code{foo}, the struct tag for the
219 context struct is @code{foo_ctx}, constants and functions uses prefixes
220 like @code{FOO_BLOCK_SIZE} (a constant) and @code{foo_set_key} (a
223 In all functions, strings are represented with an explicit length, of
224 type @code{unsigned}, and a pointer of type @code{uint8_t *} or
225 @code{const uint8_t *}. For functions that transform one string to
226 another, the argument order is length, destination pointer and source
227 pointer. Source and destination areas are of the same length. Source and
228 destination may be the same, so that you can process strings in place,
229 but they @emph{must not} overlap in any other way.
231 Many of the functions lack return value and can never fail. Those
232 functions which can fail, return one on success and zero on failure.
234 @c FIXME: Say something about the name mangling.
236 @node Example, Linking, Conventions, Top
237 @comment node-name, next, previous, up
240 A simple example program that reads a file from standard input and
241 writes its SHA1 checksum on standard output should give the flavor of
245 @verbatiminclude sha-example.c
248 On a typical Unix system, this program can be compiled and linked with
251 cc sha-example.c -o sha-example -lnettle
254 @node Linking, Reference, Example, Top
255 @comment node-name, next, previous, up
258 Nettle actually consists of two libraries, @file{libnettle} and
259 @file{libhogweed}. The @file{libhogweed} library contains those
260 functions of Nettle that uses bignum operations, and depends on the GMP
261 library. With this division, linking works the same for both static and
264 If an application uses only the symmetric crypto algorithms of Nettle
265 (i.e., block ciphers, hash functions, and the like), it's sufficient to
266 link with @code{-lnettle}. If an application also uses public-key
267 algorithms, the recommended linker flags are @code{-lhogweed -lnettle
268 -lgmp}. If the involved libraries are installed as dynamic libraries, it
269 may be sufficient to link with just @code{-lhogweed}, and the loader
270 will resolve the dependencies automatically.
272 @node Reference, Nettle soup, Linking, Top
273 @comment node-name, next, previous, up
276 This chapter describes all the Nettle functions, grouped by family.
282 * Keyed hash functions::
283 * Public-key algorithms::
285 * Miscellaneous functions::
286 * Compatibility functions::
289 @node Hash functions, Cipher functions, Reference, Reference
290 @comment node-name, next, previous, up
291 @section Hash functions
292 @cindex Hash function
293 A cryptographic @dfn{hash function} is a function that takes variable
294 size strings, and maps them to strings of fixed, short, length. There
295 are naturally lots of collisions, as there are more possible 1MB files
296 than 20 byte strings. But the function is constructed such that is hard
297 to find the collisions. More precisely, a cryptographic hash function
298 @code{H} should have the following properties:
304 Given a hash value @code{H(x)} it is hard to find a string @code{x}
305 that hashes to that value.
307 @item Collision-resistant
308 @cindex Collision-resistant
309 It is hard to find two different strings, @code{x} and @code{y}, such
310 that @code{H(x)} = @code{H(y)}.
314 Hash functions are useful as building blocks for digital signatures,
315 message authentication codes, pseudo random generators, association of
316 unique ids to documents, and many other things.
318 The most commonly used hash functions are MD5 and SHA1. Unfortunately,
319 both these fail the collision-resistance requirement; cryptologists have
320 found ways to construct colliding inputs. The recommended hash function
321 for new applications is SHA256, even though it uses a structure similar
322 to MD5 and SHA1. Constructing better hash functions is an urgent research
325 @subsection @acronym{MD5}
327 MD5 is a message digest function constructed by Ronald Rivest, and
328 described in @cite{RFC 1321}. It outputs message digests of 128 bits, or
329 16 octets. Nettle defines MD5 in @file{<nettle/md5.h>}.
331 @deftp {Context struct} {struct md5_ctx}
334 @defvr Constant MD5_DIGEST_SIZE
335 The size of an MD5 digest, i.e. 16.
338 @defvr Constant MD5_DATA_SIZE
339 The internal block size of MD5. Useful for some special constructions,
340 in particular HMAC-MD5.
343 @deftypefun void md5_init (struct md5_ctx *@var{ctx})
344 Initialize the MD5 state.
347 @deftypefun void md5_update (struct md5_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
351 @deftypefun void md5_digest (struct md5_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
352 Performs final processing and extracts the message digest, writing it
353 to @var{digest}. @var{length} may be smaller than
354 @code{MD5_DIGEST_SIZE}, in which case only the first @var{length}
355 octets of the digest are written.
357 This function also resets the context in the same way as
361 The normal way to use MD5 is to call the functions in order: First
362 @code{md5_init}, then @code{md5_update} zero or more times, and finally
363 @code{md5_digest}. After @code{md5_digest}, the context is reset to
364 its initial state, so you can start over calling @code{md5_update} to
367 To start over, you can call @code{md5_init} at any time.
369 @subsection @acronym{MD2}
371 MD2 is another hash function of Ronald Rivest's, described in
372 @cite{RFC 1319}. It outputs message digests of 128 bits, or 16 octets.
373 Nettle defines MD2 in @file{<nettle/md2.h>}.
375 @deftp {Context struct} {struct md2_ctx}
378 @defvr Constant MD2_DIGEST_SIZE
379 The size of an MD2 digest, i.e. 16.
382 @defvr Constant MD2_DATA_SIZE
383 The internal block size of MD2.
386 @deftypefun void md2_init (struct md2_ctx *@var{ctx})
387 Initialize the MD2 state.
390 @deftypefun void md2_update (struct md2_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
394 @deftypefun void md2_digest (struct md2_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
395 Performs final processing and extracts the message digest, writing it
396 to @var{digest}. @var{length} may be smaller than
397 @code{MD2_DIGEST_SIZE}, in which case only the first @var{length}
398 octets of the digest are written.
400 This function also resets the context in the same way as
404 @subsection @acronym{MD4}
406 MD4 is a predecessor of MD5, described in @cite{RFC 1320}. Like MD5, it
407 is constructed by Ronald Rivest. It outputs message digests of 128 bits,
408 or 16 octets. Nettle defines MD4 in @file{<nettle/md4.h>}. Use of MD4 is
409 not recommended, but it is sometimes needed for compatibility with
410 existing applications and protocols.
412 @deftp {Context struct} {struct md4_ctx}
415 @defvr Constant MD4_DIGEST_SIZE
416 The size of an MD4 digest, i.e. 16.
419 @defvr Constant MD4_DATA_SIZE
420 The internal block size of MD4.
423 @deftypefun void md4_init (struct md4_ctx *@var{ctx})
424 Initialize the MD4 state.
427 @deftypefun void md4_update (struct md4_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
431 @deftypefun void md4_digest (struct md4_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
432 Performs final processing and extracts the message digest, writing it
433 to @var{digest}. @var{length} may be smaller than
434 @code{MD4_DIGEST_SIZE}, in which case only the first @var{length}
435 octets of the digest are written.
437 This function also resets the context in the same way as
441 @subsection @acronym{SHA1}
443 SHA1 is a hash function specified by @dfn{NIST} (The U.S. National Institute
444 for Standards and Technology). It outputs hash values of 160 bits, or 20
445 octets. Nettle defines SHA1 in @file{<nettle/sha.h>}.
447 The functions are analogous to the MD5 ones.
449 @deftp {Context struct} {struct sha1_ctx}
452 @defvr Constant SHA1_DIGEST_SIZE
453 The size of an SHA1 digest, i.e. 20.
456 @defvr Constant SHA1_DATA_SIZE
457 The internal block size of SHA1. Useful for some special constructions,
458 in particular HMAC-SHA1.
461 @deftypefun void sha1_init (struct sha1_ctx *@var{ctx})
462 Initialize the SHA1 state.
465 @deftypefun void sha1_update (struct sha1_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
469 @deftypefun void sha1_digest (struct sha1_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
470 Performs final processing and extracts the message digest, writing it
471 to @var{digest}. @var{length} may be smaller than
472 @code{SHA1_DIGEST_SIZE}, in which case only the first @var{length}
473 octets of the digest are written.
475 This function also resets the context in the same way as
479 @subsection @acronym{SHA256}
481 SHA256 is another hash function specified by @dfn{NIST}, intended as a
482 replacement for @acronym{SHA1}, generating larger digests. It outputs
483 hash values of 256 bits, or 32 octets. Nettle defines SHA256 in
484 @file{<nettle/sha.h>}.
486 The functions are analogous to the MD5 ones.
488 @deftp {Context struct} {struct sha256_ctx}
491 @defvr Constant SHA256_DIGEST_SIZE
492 The size of an SHA256 digest, i.e. 32.
495 @defvr Constant SHA256_DATA_SIZE
496 The internal block size of SHA256. Useful for some special constructions,
497 in particular HMAC-SHA256.
500 @deftypefun void sha256_init (struct sha256_ctx *@var{ctx})
501 Initialize the SHA256 state.
504 @deftypefun void sha256_update (struct sha256_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
508 @deftypefun void sha256_digest (struct sha256_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
509 Performs final processing and extracts the message digest, writing it
510 to @var{digest}. @var{length} may be smaller than
511 @code{SHA256_DIGEST_SIZE}, in which case only the first @var{length}
512 octets of the digest are written.
514 This function also resets the context in the same way as
518 @subsection @acronym{SHA224}
520 SHA224 is a variant of SHA256, with a different initial state, and with
521 the output truncated to 224 bits, or 28 octets. Nettle defines SHA224 in
522 @file{<nettle/sha.h>}.
524 The functions are analogous to the MD5 ones.
526 @deftp {Context struct} {struct sha224_ctx}
529 @defvr Constant SHA224_DIGEST_SIZE
530 The size of an SHA224 digest, i.e. 28.
533 @defvr Constant SHA224_DATA_SIZE
534 The internal block size of SHA224. Useful for some special constructions,
535 in particular HMAC-SHA224.
538 @deftypefun void sha224_init (struct sha224_ctx *@var{ctx})
539 Initialize the SHA224 state.
542 @deftypefun void sha224_update (struct sha224_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
546 @deftypefun void sha224_digest (struct sha224_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
547 Performs final processing and extracts the message digest, writing it
548 to @var{digest}. @var{length} may be smaller than
549 @code{SHA224_DIGEST_SIZE}, in which case only the first @var{length}
550 octets of the digest are written.
552 This function also resets the context in the same way as
556 @subsection @acronym{SHA512}
558 SHA512 is a larger sibling to SHA256, with a very similar structure but
559 with both the output and the internal variables of twice the size. The
560 internal variables are 64 bits rather than 32, making it significantly
561 slower on 32-bit computers. It outputs hash values of 512 bits, or 64
562 octets. Nettle defines SHA512 in @file{<nettle/sha.h>}.
564 The functions are analogous to the MD5 ones.
566 @deftp {Context struct} {struct sha512_ctx}
569 @defvr Constant SHA512_DIGEST_SIZE
570 The size of an SHA512 digest, i.e. 64.
573 @defvr Constant SHA512_DATA_SIZE
574 The internal block size of SHA512. Useful for some special constructions,
575 in particular HMAC-SHA512.
578 @deftypefun void sha512_init (struct sha512_ctx *@var{ctx})
579 Initialize the SHA512 state.
582 @deftypefun void sha512_update (struct sha512_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
586 @deftypefun void sha512_digest (struct sha512_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
587 Performs final processing and extracts the message digest, writing it
588 to @var{digest}. @var{length} may be smaller than
589 @code{SHA512_DIGEST_SIZE}, in which case only the first @var{length}
590 octets of the digest are written.
592 This function also resets the context in the same way as
596 @subsection @acronym{SHA384}
598 SHA384 is a variant of SHA512, with a different initial state, and with
599 the output truncated to 384 bits, or 48 octets. Nettle defines SHA384 in
600 @file{<nettle/sha.h>}.
602 The functions are analogous to the MD5 ones.
604 @deftp {Context struct} {struct sha384_ctx}
607 @defvr Constant SHA384_DIGEST_SIZE
608 The size of an SHA384 digest, i.e. 48.
611 @defvr Constant SHA384_DATA_SIZE
612 The internal block size of SHA384. Useful for some special constructions,
613 in particular HMAC-SHA384.
616 @deftypefun void sha384_init (struct sha384_ctx *@var{ctx})
617 Initialize the SHA384 state.
620 @deftypefun void sha384_update (struct sha384_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
624 @deftypefun void sha384_digest (struct sha384_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
625 Performs final processing and extracts the message digest, writing it
626 to @var{digest}. @var{length} may be smaller than
627 @code{SHA384_DIGEST_SIZE}, in which case only the first @var{length}
628 octets of the digest are written.
630 This function also resets the context in the same way as
634 @subsection @code{struct nettle_hash}
636 Nettle includes a struct including information about the supported hash
637 functions. It is defined in @file{<nettle/nettle-meta.h>}, and is used
638 by Nettle's implementation of @acronym{HMAC} @pxref{Keyed hash
641 @deftp {Meta struct} @code{struct nettle_hash} name context_size digest_size block_size init update digest
642 The last three attributes are function pointers, of types
643 @code{nettle_hash_init_func}, @code{nettle_hash_update_func}, and
644 @code{nettle_hash_digest_func}. The first argument to these functions is
645 @code{void *} pointer to a context struct, which is of size
649 @deftypevr {Constant Struct} {struct nettle_hash} nettle_md2
650 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_md4
651 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_md5
652 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_sha1
653 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_sha224
654 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_sha256
655 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_sha384
656 @deftypevrx {Constant Struct} {struct nettle_hash} nettle_sha512
658 These are all the hash functions that Nettle implements.
661 @node Cipher functions, Cipher modes, Hash functions, Reference
662 @comment node-name, next, previous, up
663 @section Cipher functions
666 A @dfn{cipher} is a function that takes a message or @dfn{plaintext}
667 and a secret @dfn{key} and transforms it to a @dfn{ciphertext}. Given
668 only the ciphertext, but not the key, it should be hard to find the
669 plaintext. Given matching pairs of plaintext and ciphertext, it should
670 be hard to find the key.
673 @cindex Stream Cipher
675 There are two main classes of ciphers: Block ciphers and stream ciphers.
677 A block cipher can process data only in fixed size chunks, called
678 @dfn{blocks}. Typical block sizes are 8 or 16 octets. To encrypt
679 arbitrary messages, you usually have to pad it to an integral number of
680 blocks, split it into blocks, and then process each block. The simplest
681 way is to process one block at a time, independent of each other. That
682 mode of operation is called @dfn{ECB}, Electronic Code Book mode.
683 However, using @acronym{ECB} is usually a bad idea. For a start, plaintext blocks
684 that are equal are transformed to ciphertext blocks that are equal; that
685 leaks information about the plaintext. Usually you should apply the
686 cipher is some ``feedback mode'', @dfn{CBC} (Cipher Block Chaining) and
687 @dfn{CTR} (Counter mode) being two of
688 of the most popular. See @xref{Cipher modes}, for information on
689 how to apply @acronym{CBC} and @acronym{CTR} with Nettle.
691 A stream cipher can be used for messages of arbitrary length. A typical
692 stream cipher is a keyed pseudo-random generator. To encrypt a plaintext
693 message of @var{n} octets, you key the generator, generate @var{n}
694 octets of pseudo-random data, and XOR it with the plaintext. To decrypt,
695 regenerate the same stream using the key, XOR it to the ciphertext, and
696 the plaintext is recovered.
698 @strong{Caution:} The first rule for this kind of cipher is the
699 same as for a One Time Pad: @emph{never} ever use the same key twice.
701 A common misconception is that encryption, by itself, implies
702 authentication. Say that you and a friend share a secret key, and you
703 receive an encrypted message. You apply the key, and get a plaintext
704 message that makes sense to you. Can you then be sure that it really was
705 your friend that wrote the message you're reading? The answer is no. For
706 example, if you were using a block cipher in ECB mode, an attacker may
707 pick up the message on its way, and reorder, delete or repeat some of
708 the blocks. Even if the attacker can't decrypt the message, he can
709 change it so that you are not reading the same message as your friend
710 wrote. If you are using a block cipher in @acronym{CBC} mode rather than
711 ECB, or are using a stream cipher, the possibilities for this sort of
712 attack are different, but the attacker can still make predictable
713 changes to the message.
715 It is recommended to @emph{always} use an authentication mechanism in
716 addition to encrypting the messages. Popular choices are Message
717 Authentication Codes like @acronym{HMAC-SHA1} @pxref{Keyed hash
718 functions}, or digital signatures like @acronym{RSA}.
720 Some ciphers have so called ``weak keys'', keys that results in
721 undesirable structure after the key setup processing, and should be
722 avoided. In Nettle, most key setup functions have no return value, but
723 for ciphers with weak keys, the return value indicates whether or not
724 the given key is weak. For good keys, key setup returns 1, and for weak
725 keys, it returns 0. When possible, avoid algorithms that
726 have weak keys. There are several good ciphers that don't have any weak
729 To encrypt a message, you first initialize a cipher context for
730 encryption or decryption with a particular key. You then use the context
731 to process plaintext or ciphertext messages. The initialization is known
732 as @dfn{key setup}. With Nettle, it is recommended to use each
733 context struct for only one direction, even if some of the ciphers use a
734 single key setup function that can be used for both encryption and
738 AES is a block cipher, specified by NIST as a replacement for
739 the older DES standard. The standard is the result of a competition
740 between cipher designers. The winning design, also known as RIJNDAEL,
741 was constructed by Joan Daemen and Vincent Rijnmen.
743 Like all the AES candidates, the winning design uses a block size of 128
744 bits, or 16 octets, and variable key-size, 128, 192 and 256 bits (16, 24
745 and 32 octets) being the allowed key sizes. It does not have any weak
746 keys. Nettle defines AES in @file{<nettle/aes.h>}.
748 @deftp {Context struct} {struct aes_ctx}
751 @defvr Constant AES_BLOCK_SIZE
752 The AES block-size, 16
755 @defvr Constant AES_MIN_KEY_SIZE
758 @defvr Constant AES_MAX_KEY_SIZE
761 @defvr Constant AES_KEY_SIZE
762 Default AES key size, 32
765 @deftypefun void aes_set_encrypt_key (struct aes_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
766 @deftypefunx void aes_set_decrypt_key (struct aes_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
767 Initialize the cipher, for encryption or decryption, respectively.
770 @deftypefun void aes_invert_key (struct aes_ctx *@var{dst}, const struct aes_ctx *@var{src})
771 Given a context @var{src} initialized for encryption, initializes the
772 context struct @var{dst} for decryption, using the same key. If the same
773 context struct is passed for both @code{src} and @code{dst}, it is
774 converted in place. Calling @code{aes_set_encrypt_key} and
775 @code{aes_invert_key} is more efficient than calling
776 @code{aes_set_encrypt_key} and @code{aes_set_decrypt_key}. This function
777 is mainly useful for applications which needs to both encrypt and
778 decrypt using the @emph{same} key.
781 @deftypefun void aes_encrypt (struct aes_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
782 Encryption function. @var{length} must be an integral multiple of the
783 block size. If it is more than one block, the data is processed in ECB
784 mode. @code{src} and @code{dst} may be equal, but they must not overlap
788 @deftypefun void aes_decrypt (struct aes_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
789 Analogous to @code{aes_encrypt}
793 ARCFOUR is a stream cipher, also known under the trade marked name RC4,
794 and it is one of the fastest ciphers around. A problem is that the key
795 setup of ARCFOUR is quite weak, you should never use keys with
796 structure, keys that are ordinary passwords, or sequences of keys like
797 ``secret:1'', ``secret:2'', @enddots{}. If you have keys that don't look
798 like random bit strings, and you want to use ARCFOUR, always hash the
799 key before feeding it to ARCFOUR. Furthermore, the initial bytes of the
800 generated key stream leak information about the key; for this reason, it
801 is recommended to discard the first 512 bytes of the key stream.
804 /* A more robust key setup function for ARCFOUR */
806 arcfour_set_key_hashed(struct arcfour_ctx *ctx,
807 unsigned length, const uint8_t *key)
809 struct sha256_ctx hash;
810 uint8_t digest[SHA256_DIGEST_SIZE];
811 uint8_t buffer[0x200];
814 sha256_update(&hash, length, key);
815 sha256_digest(&hash, SHA256_DIGEST_SIZE, digest);
817 arcfour_set_key(ctx, SHA256_DIGEST_SIZE, digest);
818 arcfour_crypt(ctx, sizeof(buffer), buffer, buffer);
822 Nettle defines ARCFOUR in @file{<nettle/arcfour.h>}.
824 @deftp {Context struct} {struct arcfour_ctx}
827 @defvr Constant ARCFOUR_MIN_KEY_SIZE
831 @defvr Constant ARCFOUR_MAX_KEY_SIZE
832 Maximum key size, 256
835 @defvr Constant ARCFOUR_KEY_SIZE
836 Default ARCFOUR key size, 16
839 @deftypefun void arcfour_set_key (struct arcfour_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
840 Initialize the cipher. The same function is used for both encryption and
844 @deftypefun void arcfour_crypt (struct arcfour_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
845 Encrypt some data. The same function is used for both encryption and
846 decryption. Unlike the block ciphers, this function modifies the
847 context, so you can split the data into arbitrary chunks and encrypt
848 them one after another. The result is the same as if you had called
849 @code{arcfour_crypt} only once with all the data.
853 ARCTWO (also known as the trade marked name RC2) is a block cipher
854 specified in RFC 2268. Nettle also include a variation of the ARCTWO
855 set key operation that lack one step, to be compatible with the
856 reverse engineered RC2 cipher description, as described in a Usenet
857 post to @code{sci.crypt} by Peter Gutmann.
859 ARCTWO uses a block size of 64 bits, and variable key-size ranging
860 from 1 to 128 octets. Besides the key, ARCTWO also has a second
861 parameter to key setup, the number of effective key bits, @code{ekb}.
862 This parameter can be used to artificially reduce the key size. In
863 practice, @code{ekb} is usually set equal to the input key size.
864 Nettle defines ARCTWO in @file{<nettle/arctwo.h>}.
866 We do not recommend the use of ARCTWO; the Nettle implementation is
867 provided primarily for interoperability with existing applications and
870 @deftp {Context struct} {struct arctwo_ctx}
873 @defvr Constant ARCTWO_BLOCK_SIZE
874 The AES block-size, 8
877 @defvr Constant ARCTWO_MIN_KEY_SIZE
880 @defvr Constant ARCTWO_MAX_KEY_SIZE
883 @defvr Constant ARCTWO_KEY_SIZE
884 Default ARCTWO key size, 8
887 @deftypefun void arctwo_set_key_ekb (struct arctwo_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key}, unsigned @var{ekb})
888 @deftypefunx void arctwo_set_key (struct arctwo_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
889 @deftypefunx void arctwo_set_key_gutmann (struct arctwo_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
890 Initialize the cipher. The same function is used for both encryption
891 and decryption. The first function is the most general one, which lets
892 you provide both the variable size key, and the desired effective key
893 size (in bits). The maximum value for @var{ekb} is 1024, and for
894 convenience, @code{ekb = 0} has the same effect as @code{ekb = 1024}.
896 @code{arctwo_set_key(ctx, length, key)} is equivalent to
897 @code{arctwo_set_key_ekb(ctx, length, key, 8*length)}, and
898 @code{arctwo_set_key_gutmann(ctx, length, key)} is equivalent to
899 @code{arctwo_set_key_ekb(ctx, length, key, 1024)}
902 @deftypefun void arctwo_encrypt (struct arctwo_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
903 Encryption function. @var{length} must be an integral multiple of the
904 block size. If it is more than one block, the data is processed in ECB
905 mode. @code{src} and @code{dst} may be equal, but they must not
906 overlap in any other way.
909 @deftypefun void arctwo_decrypt (struct arctwo_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
910 Analogous to @code{arctwo_encrypt}
915 BLOWFISH is a block cipher designed by Bruce Schneier. It uses a block
916 size of 64 bits (8 octets), and a variable key size, up to 448 bits. It
917 has some weak keys. Nettle defines BLOWFISH in @file{<nettle/blowfish.h>}.
919 @deftp {Context struct} {struct blowfish_ctx}
922 @defvr Constant BLOWFISH_BLOCK_SIZE
923 The BLOWFISH block-size, 8
926 @defvr Constant BLOWFISH_MIN_KEY_SIZE
927 Minimum BLOWFISH key size, 8
930 @defvr Constant BLOWFISH_MAX_KEY_SIZE
931 Maximum BLOWFISH key size, 56
934 @defvr Constant BLOWFISH_KEY_SIZE
935 Default BLOWFISH key size, 16
938 @deftypefun int blowfish_set_key (struct blowfish_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
939 Initialize the cipher. The same function is used for both encryption and
940 decryption. Checks for weak keys, returning 1
941 for good keys and 0 for weak keys. Applications that don't care about
942 weak keys can ignore the return value.
944 @code{blowfish_encrypt} or @code{blowfish_decrypt} with a weak key will
945 crash with an assert violation.
948 @deftypefun void blowfish_encrypt (struct blowfish_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
949 Encryption function. @var{length} must be an integral multiple of the
950 block size. If it is more than one block, the data is processed in ECB
951 mode. @code{src} and @code{dst} may be equal, but they must not overlap
955 @deftypefun void blowfish_decrypt (struct blowfish_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
956 Analogous to @code{blowfish_encrypt}
961 Camellia is a block cipher developed by Mitsubishi and Nippon Telegraph
962 and Telephone Corporation, described in @cite{RFC3713}, and recommended
963 by some Japanese and European authorities as an alternative to AES. The
964 algorithm is patented. The implementation in Nettle is derived from the
965 implementation released by NTT under the GNU LGPL (v2.1 or later), and
966 relies on the implicit patent license of the LGPL. There is also a
967 statement of royalty-free licensing for Camellia at
968 @url{http://www.ntt.co.jp/news/news01e/0104/010417.html}, but this
969 statement has some limitations which seem problematic for free software.
971 Camellia uses a the same block size and key sizes as AES: The block size
972 is 128 bits (16 octets), and the supported key sizes are 128, 192, and
973 256 bits. Nettle defines Camellia in @file{<nettle/camellia.h>}.
975 @deftp {Context struct} {struct camellia_ctx}
978 @defvr Constant CAMELLIA_BLOCK_SIZE
979 The CAMELLIA block-size, 16
982 @defvr Constant CAMELLIA_MIN_KEY_SIZE
985 @defvr Constant CAMELLIA_MAX_KEY_SIZE
988 @defvr Constant CAMELLIA_KEY_SIZE
989 Default CAMELLIA key size, 32
992 @deftypefun void camellia_set_encrypt_key (struct camellia_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
993 @deftypefunx void camellia_set_decrypt_key (struct camellia_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
994 Initialize the cipher, for encryption or decryption, respectively.
997 @deftypefun void camellia_invert_key (struct camellia_ctx *@var{dst}, const struct camellia_ctx *@var{src})
998 Given a context @var{src} initialized for encryption, initializes the
999 context struct @var{dst} for decryption, using the same key. If the same
1000 context struct is passed for both @code{src} and @code{dst}, it is
1001 converted in place. Calling @code{camellia_set_encrypt_key} and
1002 @code{camellia_invert_key} is more efficient than calling
1003 @code{camellia_set_encrypt_key} and @code{camellia_set_decrypt_key}. This function
1004 is mainly useful for applications which needs to both encrypt and
1005 decrypt using the @emph{same} key.
1008 @deftypefun void camellia_crypt (struct camellia_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
1009 The same function is used for both encryption and decryption.
1010 @var{length} must be an integral multiple of the block size. If it is
1011 more than one block, the data is processed in ECB mode. @code{src} and
1012 @code{dst} may be equal, but they must not overlap in any other way.
1017 CAST-128 is a block cipher, specified in @cite{RFC 2144}. It uses a 64
1018 bit (8 octets) block size, and a variable key size of up to 128 bits.
1019 Nettle defines cast128 in @file{<nettle/cast128.h>}.
1021 @deftp {Context struct} {struct cast128_ctx}
1024 @defvr Constant CAST128_BLOCK_SIZE
1025 The CAST128 block-size, 8
1028 @defvr Constant CAST128_MIN_KEY_SIZE
1029 Minimum CAST128 key size, 5
1032 @defvr Constant CAST128_MAX_KEY_SIZE
1033 Maximum CAST128 key size, 16
1036 @defvr Constant CAST128_KEY_SIZE
1037 Default CAST128 key size, 16
1040 @deftypefun void cast128_set_key (struct cast128_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
1041 Initialize the cipher. The same function is used for both encryption and
1045 @deftypefun void cast128_encrypt (struct cast128_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
1046 Encryption function. @var{length} must be an integral multiple of the
1047 block size. If it is more than one block, the data is processed in ECB
1048 mode. @code{src} and @code{dst} may be equal, but they must not overlap
1052 @deftypefun void cast128_decrypt (struct cast128_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
1053 Analogous to @code{cast128_encrypt}
1057 DES is the old Data Encryption Standard, specified by NIST. It uses a
1058 block size of 64 bits (8 octets), and a key size of 56 bits. However,
1059 the key bits are distributed over 8 octets, where the least significant
1060 bit of each octet may be used for parity. A common way to use DES is to
1061 generate 8 random octets in some way, then set the least significant bit
1062 of each octet to get odd parity, and initialize DES with the resulting
1065 The key size of DES is so small that keys can be found by brute force,
1066 using specialized hardware or lots of ordinary work stations in
1067 parallel. One shouldn't be using plain DES at all today, if one uses
1068 DES at all one should be using ``triple DES'', see DES3 below.
1070 DES also has some weak keys. Nettle defines DES in @file{<nettle/des.h>}.
1072 @deftp {Context struct} {struct des_ctx}
1075 @defvr Constant DES_BLOCK_SIZE
1076 The DES block-size, 8
1079 @defvr Constant DES_KEY_SIZE
1083 @deftypefun int des_set_key (struct des_ctx *@var{ctx}, const uint8_t *@var{key})
1084 Initialize the cipher. The same function is used for both encryption and
1085 decryption. Parity bits are ignored. Checks for weak keys, returning 1
1086 for good keys and 0 for weak keys. Applications that don't care about
1087 weak keys can ignore the return value.
1090 @deftypefun void des_encrypt (struct des_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
1091 Encryption function. @var{length} must be an integral multiple of the
1092 block size. If it is more than one block, the data is processed in ECB
1093 mode. @code{src} and @code{dst} may be equal, but they must not overlap
1097 @deftypefun void des_decrypt (struct des_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
1098 Analogous to @code{des_encrypt}
1101 @deftypefun int des_check_parity (unsigned @var{length}, const uint8_t *@var{key});
1102 Checks that the given key has correct, odd, parity. Returns 1 for
1103 correct parity, and 0 for bad parity.
1106 @deftypefun void des_fix_parity (unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1107 Adjusts the parity bits to match DES's requirements. You need this
1108 function if you have created a random-looking string by a key agreement
1109 protocol, and want to use it as a DES key. @var{dst} and @var{src} may
1114 The inadequate key size of DES has already been mentioned. One way to
1115 increase the key size is to pipe together several DES boxes with
1116 independent keys. It turns out that using two DES ciphers is not as
1117 secure as one might think, even if the key size of the combination is a
1118 respectable 112 bits.
1120 The standard way to increase DES's key size is to use three DES boxes.
1121 The mode of operation is a little peculiar: the middle DES box is wired
1122 in the reverse direction. To encrypt a block with DES3, you encrypt it
1123 using the first 56 bits of the key, then @emph{decrypt} it using the
1124 middle 56 bits of the key, and finally encrypt it again using the last
1125 56 bits of the key. This is known as ``ede'' triple-DES, for
1126 ``encrypt-decrypt-encrypt''.
1128 The ``ede'' construction provides some backward compatibility, as you get
1129 plain single DES simply by feeding the same key to all three boxes. That
1130 should help keeping down the gate count, and the price, of hardware
1131 circuits implementing both plain DES and DES3.
1133 DES3 has a key size of 168 bits, but just like plain DES, useless parity
1134 bits are inserted, so that keys are represented as 24 octets (192 bits).
1135 As a 112 bit key is large enough to make brute force attacks
1136 impractical, some applications uses a ``two-key'' variant of triple-DES.
1137 In this mode, the same key bits are used for the first and the last DES
1138 box in the pipe, while the middle box is keyed independently. The
1139 two-key variant is believed to be secure, i.e. there are no known
1140 attacks significantly better than brute force.
1142 Naturally, it's simple to implement triple-DES on top of Nettle's DES
1143 functions. Nettle includes an implementation of three-key ``ede''
1144 triple-DES, it is defined in the same place as plain DES,
1145 @file{<nettle/des.h>}.
1147 @deftp {Context struct} {struct des3_ctx}
1150 @defvr Constant DES3_BLOCK_SIZE
1151 The DES3 block-size is the same as DES_BLOCK_SIZE, 8
1154 @defvr Constant DES3_KEY_SIZE
1158 @deftypefun int des3_set_key (struct des3_ctx *@var{ctx}, const uint8_t *@var{key})
1159 Initialize the cipher. The same function is used for both encryption and
1160 decryption. Parity bits are ignored. Checks for weak keys, returning 1
1161 if all three keys are good keys, and 0 if one or more key is weak.
1162 Applications that don't care about weak keys can ignore the return
1166 For random-looking strings, you can use @code{des_fix_parity} to adjust
1167 the parity bits before calling @code{des3_set_key}.
1169 @deftypefun void des3_encrypt (struct des3_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
1170 Encryption function. @var{length} must be an integral multiple of the
1171 block size. If it is more than one block, the data is processed in ECB
1172 mode. @code{src} and @code{dst} may be equal, but they must not overlap
1176 @deftypefun void des3_decrypt (struct des3_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
1177 Analogous to @code{des_encrypt}
1181 SERPENT is one of the AES finalists, designed by Ross Anderson, Eli
1182 Biham and Lars Knudsen. Thus, the interface and properties are similar
1183 to AES'. One peculiarity is that it is quite pointless to use it with
1184 anything but the maximum key size, smaller keys are just padded to
1185 larger ones. Nettle defines SERPENT in @file{<nettle/serpent.h>}.
1187 @deftp {Context struct} {struct serpent_ctx}
1190 @defvr Constant SERPENT_BLOCK_SIZE
1191 The SERPENT block-size, 16
1194 @defvr Constant SERPENT_MIN_KEY_SIZE
1195 Minimum SERPENT key size, 16
1198 @defvr Constant SERPENT_MAX_KEY_SIZE
1199 Maximum SERPENT key size, 32
1202 @defvr Constant SERPENT_KEY_SIZE
1203 Default SERPENT key size, 32
1206 @deftypefun void serpent_set_key (struct serpent_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
1207 Initialize the cipher. The same function is used for both encryption and
1211 @deftypefun void serpent_encrypt (struct serpent_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
1212 Encryption function. @var{length} must be an integral multiple of the
1213 block size. If it is more than one block, the data is processed in ECB
1214 mode. @code{src} and @code{dst} may be equal, but they must not overlap
1218 @deftypefun void serpent_decrypt (struct serpent_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
1219 Analogous to @code{serpent_encrypt}
1224 Another AES finalist, this one designed by Bruce Schneier and others.
1225 Nettle defines it in @file{<nettle/twofish.h>}.
1227 @deftp {Context struct} {struct twofish_ctx}
1230 @defvr Constant TWOFISH_BLOCK_SIZE
1231 The TWOFISH block-size, 16
1234 @defvr Constant TWOFISH_MIN_KEY_SIZE
1235 Minimum TWOFISH key size, 16
1238 @defvr Constant TWOFISH_MAX_KEY_SIZE
1239 Maximum TWOFISH key size, 32
1242 @defvr Constant TWOFISH_KEY_SIZE
1243 Default TWOFISH key size, 32
1246 @deftypefun void twofish_set_key (struct twofish_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
1247 Initialize the cipher. The same function is used for both encryption and
1251 @deftypefun void twofish_encrypt (struct twofish_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
1252 Encryption function. @var{length} must be an integral multiple of the
1253 block size. If it is more than one block, the data is processed in ECB
1254 mode. @code{src} and @code{dst} may be equal, but they must not overlap
1258 @deftypefun void twofish_decrypt (struct twofish_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
1259 Analogous to @code{twofish_encrypt}
1262 @c @node nettle_cipher, Cipher Block Chaining, Cipher functions, Reference
1263 @c @comment node-name, next, previous, up
1264 @subsection @code{struct nettle_cipher}
1266 Nettle includes a struct including information about some of the more
1267 regular cipher functions. It should be considered a little experimental,
1268 but can be useful for applications that need a simple way to handle
1269 various algorithms. Nettle defines these structs in
1270 @file{<nettle/nettle-meta.h>}.
1272 @deftp {Meta struct} @code{struct nettle_cipher} name context_size block_size key_size set_encrypt_key set_decrypt_key encrypt decrypt
1273 The last four attributes are function pointers, of types
1274 @code{nettle_set_key_func} and @code{nettle_crypt_func}. The first
1275 argument to these functions is a @code{void *} pointer to a context
1276 struct, which is of size @code{context_size}.
1279 @deftypevr {Constant Struct} {struct nettle_cipher} nettle_aes128
1280 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_aes192
1281 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_aes256
1283 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arctwo40;
1284 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arctwo64;
1285 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arctwo128;
1286 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arctwo_gutmann128;
1288 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arcfour128
1290 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_camellia128
1291 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_camellia192
1292 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_camellia256
1294 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_cast128
1296 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_serpent128
1297 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_serpent192
1298 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_serpent256
1300 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_twofish128
1301 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_twofish192
1302 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_twofish256
1304 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arctwo40;
1305 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arctwo64;
1306 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arctwo128;
1307 @deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arctwo_gutmann128;
1309 Nettle includes such structs for all the @emph{regular} ciphers, i.e.
1310 ones without weak keys or other oddities.
1313 @node Cipher modes, Keyed hash functions, Cipher functions, Reference
1314 @comment node-name, next, previous, up
1315 @section Cipher modes
1317 Cipher modes of operation specifies the procedure to use when
1318 encrypting a message that is larger than the cipher's block size. As
1319 explained in @xref{Cipher functions}, splitting the message into blocks
1320 and processing them independently with the block cipher (Electronic Code
1321 Book mode, @acronym{ECB}) leaks information. Besides @acronym{ECB},
1322 Nettle provides two other modes of operation: Cipher Block Chaining
1323 (@acronym{CBC}) and Counter mode (@acronym{CTR}). @acronym{CBC} is
1324 widely used, but there are a few subtle issues of information leakage.
1325 @acronym{CTR} was standardized more recently, and is believed to be more
1328 @subsection Cipher Block Chaining
1330 @cindex Cipher Block Chaining
1333 When using @acronym{CBC} mode, plaintext blocks are not encrypted
1334 independently of each other, like in Electronic Cook Book mode. Instead,
1335 when encrypting a block in @acronym{CBC} mode, the previous ciphertext
1336 block is XORed with the plaintext before it is fed to the block cipher.
1337 When encrypting the first block, a random block called an @dfn{IV}, or
1338 Initialization Vector, is used as the ``previous ciphertext block''. The
1339 IV should be chosen randomly, but it need not be kept secret, and can
1340 even be transmitted in the clear together with the encrypted data.
1342 In symbols, if @code{E_k} is the encryption function of a block cipher,
1343 and @code{IV} is the initialization vector, then @code{n} plaintext blocks
1344 @code{M_1},@dots{} @code{M_n} are transformed into @code{n} ciphertext blocks
1345 @code{C_1},@dots{} @code{C_n} as follows:
1348 C_1 = E_k(IV XOR M_1)
1349 C_2 = E_k(C_1 XOR M_2)
1353 C_n = E_k(C_(n-1) XOR M_n)
1356 Nettle's includes two functions for applying a block cipher in Cipher
1357 Block Chaining (@acronym{CBC}) mode, one for encryption and one for
1358 decryption. These functions uses @code{void *} to pass cipher contexts
1361 @deftypefun {void} cbc_encrypt (void *@var{ctx}, nettle_crypt_func @var{f}, unsigned @var{block_size}, uint8_t *@var{iv}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1362 @deftypefunx {void} cbc_decrypt (void *@var{ctx}, void (*@var{f})(), unsigned @var{block_size}, uint8_t *@var{iv}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1364 Applies the encryption or decryption function @var{f} in @acronym{CBC}
1365 mode. The final ciphertext block processed is copied into @var{iv}
1366 before returning, so that large message be processed be a sequence of
1367 calls to @code{cbc_encrypt}. The function @var{f} is of type
1369 @code{void f (void *@var{ctx}, unsigned @var{length}, uint8_t @var{dst},
1370 const uint8_t *@var{src})},
1372 @noindent and the @code{cbc_encrypt} and @code{cbc_decrypt} functions pass their
1373 argument @var{ctx} on to @var{f}.
1376 There are also some macros to help use these functions correctly.
1378 @deffn Macro CBC_CTX (@var{context_type}, @var{block_size})
1383 uint8_t iv[block_size];
1388 It can be used to define a @acronym{CBC} context struct, either directly,
1391 struct CBC_CTX(struct aes_ctx, AES_BLOCK_SIZE) ctx;
1394 or to give it a struct tag,
1397 struct aes_cbc_ctx CBC_CTX (struct aes_ctx, AES_BLOCK_SIZE);
1400 @deffn Macro CBC_SET_IV (@var{ctx}, @var{iv})
1401 First argument is a pointer to a context struct as defined by @code{CBC_CTX},
1402 and the second is a pointer to an Initialization Vector (IV) that is
1403 copied into that context.
1406 @deffn Macro CBC_ENCRYPT (@var{ctx}, @var{f}, @var{length}, @var{dst}, @var{src})
1407 @deffnx Macro CBC_DECRYPT (@var{ctx}, @var{f}, @var{length}, @var{dst}, @var{src})
1408 A simpler way to invoke @code{cbc_encrypt} and @code{cbc_decrypt}. The
1409 first argument is a pointer to a context struct as defined by
1410 @code{CBC_CTX}, and the second argument is an encryption or decryption
1411 function following Nettle's conventions. The last three arguments define
1412 the source and destination area for the operation.
1415 These macros use some tricks to make the compiler display a warning if
1416 the types of @var{f} and @var{ctx} don't match, e.g. if you try to use
1417 an @code{struct aes_ctx} context with the @code{des_encrypt} function.
1419 @subsection Counter mode
1421 @cindex Counter Mode
1424 Counter mode (@acronym{CTR}) uses the block cipher as a keyed
1425 pseudo-random generator. The output of the generator is XORed with the
1426 data to be encrypted. It can be understood as a way to transform a block
1427 cipher to a stream cipher.
1429 The message is divided into @code{n} blocks @code{M_1},@dots{}
1430 @code{M_n}, where @code{M_n} is of size @code{m} which may be smaller
1431 than the block size. Except for the last block, all the message blocks
1432 must be of size equal to the cipher's block size.
1434 If @code{E_k} is the encryption function of a block cipher, @code{IC} is
1435 the initial counter, then the @code{n} plaintext blocks are
1436 transformed into @code{n} ciphertext blocks @code{C_1},@dots{}
1437 @code{C_n} as follows:
1440 C_1 = E_k(IC) XOR M_1
1441 C_2 = E_k(IC + 1) XOR M_2
1445 C_(n-1) = E_k(IC + n - 2) XOR M_(n-1)
1446 C_n = E_k(IC + n - 1) [1..m] XOR M_n
1449 The @acronym{IC} is the initial value for the counter, it plays a
1450 similar role as the @acronym{IV} for @acronym{CBC}. When adding,
1451 @code{IC + x}, @acronym{IC} is interpreted as an integer, in network
1452 byte order. For the last block, @code{E_k(IC + n - 1) [1..m]} means that
1453 the cipher output is truncated to @code{m} bytes.
1455 @deftypefun {void} ctr_crypt (void *@var{ctx}, nettle_crypt_func @var{f}, unsigned @var{block_size}, uint8_t *@var{ctr}, unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
1457 Applies the encryption function @var{f} in @acronym{CTR} mode. Note that
1458 for @acronym{CTR} mode, encryption and decryption is the same operation,
1459 and hence @var{f} should always be the encryption function for the
1460 underlying block cipher.
1462 When a message is encrypted using a sequence of calls to
1463 @code{ctr_crypt}, all but the last call @emph{must} use a length that is
1464 a multiple of the block size.
1467 Like for @acronym{CBC}, there are also a couple of helper macros.
1469 @deffn Macro CTR_CTX (@var{context_type}, @var{block_size})
1474 uint8_t ctr[block_size];
1479 @deffn Macro CTR_SET_COUNTER (@var{ctx}, @var{iv})
1480 First argument is a pointer to a context struct as defined by
1481 @code{CTR_CTX}, and the second is a pointer to an initial counter that
1482 is copied into that context.
1485 @deffn Macro CTR_CRYPT (@var{ctx}, @var{f}, @var{length}, @var{dst}, @var{src})
1486 A simpler way to invoke @code{ctr_crypt}. The first argument is a
1487 pointer to a context struct as defined by @code{CTR_CTX}, and the second
1488 argument is an encryption function following Nettle's conventions. The
1489 last three arguments define the source and destination area for the
1494 @node Keyed hash functions, Public-key algorithms, Cipher modes, Reference
1495 @comment node-name, next, previous, up
1496 @section Keyed Hash Functions
1498 @cindex Keyed Hash Function
1499 @cindex Message Authentication Code
1502 A @dfn{keyed hash function}, or @dfn{Message Authentication Code}
1503 (@acronym{MAC}) is a function that takes a key and a message, and
1504 produces fixed size @acronym{MAC}. It should be hard to compute a
1505 message and a matching @acronym{MAC} without knowledge of the key. It
1506 should also be hard to compute the key given only messages and
1507 corresponding @acronym{MAC}s.
1509 Keyed hash functions are useful primarily for message authentication,
1510 when Alice and Bob shares a secret: The sender, Alice, computes the
1511 @acronym{MAC} and attaches it to the message. The receiver, Bob, also computes
1512 the @acronym{MAC} of the message, using the same key, and compares that
1513 to Alice's value. If they match, Bob can be assured that
1514 the message has not been modified on its way from Alice.
1516 However, unlike digital signatures, this assurance is not transferable.
1517 Bob can't show the message and the @acronym{MAC} to a third party and
1518 prove that Alice sent that message. Not even if he gives away the key to
1519 the third party. The reason is that the @emph{same} key is used on both
1520 sides, and anyone knowing the key can create a correct @acronym{MAC} for
1521 any message. If Bob believes that only he and Alice knows the key, and
1522 he knows that he didn't attach a @acronym{MAC} to a particular message,
1523 he knows it must be Alice who did it. However, the third party can't
1524 distinguish between a @acronym{MAC} created by Alice and one created by
1527 Keyed hash functions are typically a lot faster than digital signatures
1530 @subsection @acronym{HMAC}
1532 One can build keyed hash functions from ordinary hash functions. Older
1533 constructions simply concatenate secret key and message and hashes that, but
1534 such constructions have weaknesses. A better construction is
1535 @acronym{HMAC}, described in @cite{RFC 2104}.
1537 For an underlying hash function @code{H}, with digest size @code{l} and
1538 internal block size @code{b}, @acronym{HMAC-H} is constructed as
1539 follows: From a given key @code{k}, two distinct subkeys @code{k_i} and
1540 @code{k_o} are constructed, both of length @code{b}. The
1541 @acronym{HMAC-H} of a message @code{m} is then computed as @code{H(k_o |
1542 H(k_i | m))}, where @code{|} denotes string concatenation.
1544 @acronym{HMAC} keys can be of any length, but it is recommended to use
1545 keys of length @code{l}, the digest size of the underlying hash function
1546 @code{H}. Keys that are longer than @code{b} are shortened to length
1547 @code{l} by hashing with @code{H}, so arbitrarily long keys aren't
1550 Nettle's @acronym{HMAC} functions are defined in @file{<nettle/hmac.h>}.
1551 There are abstract functions that use a pointer to a @code{struct
1552 nettle_hash} to represent the underlying hash function and @code{void
1553 *} pointers that point to three different context structs for that hash
1554 function. There are also concrete functions for @acronym{HMAC-MD5},
1555 @acronym{HMAC-SHA1}, @acronym{HMAC-SHA256}, and @acronym{HMAC-SHA512}.
1556 First, the abstract functions:
1558 @deftypefun void hmac_set_key (void *@var{outer}, void *@var{inner}, void *@var{state}, const struct nettle_hash *@var{H}, unsigned @var{length}, const uint8_t *@var{key})
1559 Initializes the three context structs from the key. The @var{outer} and
1560 @var{inner} contexts corresponds to the subkeys @code{k_o} and
1561 @code{k_i}. @var{state} is used for hashing the message, and is
1562 initialized as a copy of the @var{inner} context.
1565 @deftypefun void hmac_update (void *@var{state}, const struct nettle_hash *@var{H}, unsigned @var{length}, const uint8_t *@var{data})
1566 This function is called zero or more times to process the message.
1567 Actually, @code{hmac_update(state, H, length, data)} is equivalent to
1568 @code{H->update(state, length, data)}, so if you wish you can use the
1569 ordinary update function of the underlying hash function instead.
1572 @deftypefun void hmac_digest (const void *@var{outer}, const void *@var{inner}, void *@var{state}, const struct nettle_hash *@var{H}, unsigned @var{length}, uint8_t *@var{digest})
1573 Extracts the @acronym{MAC} of the message, writing it to @var{digest}.
1574 @var{outer} and @var{inner} are not modified. @var{length} is usually
1575 equal to @code{H->digest_size}, but if you provide a smaller value,
1576 only the first @var{length} octets of the @acronym{MAC} are written.
1578 This function also resets the @var{state} context so that you can start
1579 over processing a new message (with the same key).
1582 Like for @acronym{CBC}, there are some macros to help use these
1583 functions correctly.
1585 @deffn Macro HMAC_CTX (@var{type})
1596 It can be used to define a @acronym{HMAC} context struct, either
1600 struct HMAC_CTX(struct md5_ctx) ctx;
1603 or to give it a struct tag,
1606 struct hmac_md5_ctx HMAC_CTX (struct md5_ctx);
1609 @deffn Macro HMAC_SET_KEY (@var{ctx}, @var{H}, @var{length}, @var{key})
1610 @var{ctx} is a pointer to a context struct as defined by
1611 @code{HMAC_CTX}, @var{H} is a pointer to a @code{const struct
1612 nettle_hash} describing the underlying hash function (so it must match
1613 the type of the components of @var{ctx}). The last two arguments specify
1617 @deffn Macro HMAC_DIGEST (@var{ctx}, @var{H}, @var{length}, @var{digest})
1618 @var{ctx} is a pointer to a context struct as defined by
1619 @code{HMAC_CTX}, @var{H} is a pointer to a @code{const struct
1620 nettle_hash} describing the underlying hash function. The last two
1621 arguments specify where the digest is written.
1624 Note that there is no @code{HMAC_UPDATE} macro; simply call
1625 @code{hmac_update} function directly, or the update function of the
1626 underlying hash function.
1628 @subsection Concrete @acronym{HMAC} functions
1629 Now we come to the specialized @acronym{HMAC} functions, which are
1630 easier to use than the general @acronym{HMAC} functions.
1632 @subsubsection @acronym{HMAC-MD5}
1634 @deftp {Context struct} {struct hmac_md5_ctx}
1637 @deftypefun void hmac_md5_set_key (struct hmac_md5_ctx *@var{ctx}, unsigned @var{key_length}, const uint8_t *@var{key})
1638 Initializes the context with the key.
1641 @deftypefun void hmac_md5_update (struct hmac_md5_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
1642 Process some more data.
1645 @deftypefun void hmac_md5_digest (struct hmac_md5_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
1646 Extracts the @acronym{MAC}, writing it to @var{digest}. @var{length} may be smaller than
1647 @code{MD5_DIGEST_SIZE}, in which case only the first @var{length}
1648 octets of the @acronym{MAC} are written.
1650 This function also resets the context for processing new messages, with
1654 @subsubsection @acronym{HMAC-SHA1}
1656 @deftp {Context struct} {struct hmac_sha1_ctx}
1659 @deftypefun void hmac_sha1_set_key (struct hmac_sha1_ctx *@var{ctx}, unsigned @var{key_length}, const uint8_t *@var{key})
1660 Initializes the context with the key.
1663 @deftypefun void hmac_sha1_update (struct hmac_sha1_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
1664 Process some more data.
1667 @deftypefun void hmac_sha1_digest (struct hmac_sha1_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
1668 Extracts the @acronym{MAC}, writing it to @var{digest}. @var{length} may be smaller than
1669 @code{SHA1_DIGEST_SIZE}, in which case only the first @var{length}
1670 octets of the @acronym{MAC} are written.
1672 This function also resets the context for processing new messages, with
1677 @subsubsection @acronym{HMAC-SHA256}
1679 @deftp {Context struct} {struct hmac_sha256_ctx}
1682 @deftypefun void hmac_sha256_set_key (struct hmac_sha256_ctx *@var{ctx}, unsigned @var{key_length}, const uint8_t *@var{key})
1683 Initializes the context with the key.
1686 @deftypefun void hmac_sha256_update (struct hmac_sha256_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
1687 Process some more data.
1690 @deftypefun void hmac_sha256_digest (struct hmac_sha256_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
1691 Extracts the @acronym{MAC}, writing it to @var{digest}. @var{length} may be smaller than
1692 @code{SHA256_DIGEST_SIZE}, in which case only the first @var{length}
1693 octets of the @acronym{MAC} are written.
1695 This function also resets the context for processing new messages, with
1700 @subsubsection @acronym{HMAC-SHA512}
1702 @deftp {Context struct} {struct hmac_sha512_ctx}
1705 @deftypefun void hmac_sha512_set_key (struct hmac_sha512_ctx *@var{ctx}, unsigned @var{key_length}, const uint8_t *@var{key})
1706 Initializes the context with the key.
1709 @deftypefun void hmac_sha512_update (struct hmac_sha512_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
1710 Process some more data.
1713 @deftypefun void hmac_sha512_digest (struct hmac_sha512_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
1714 Extracts the @acronym{MAC}, writing it to @var{digest}. @var{length} may be smaller than
1715 @code{SHA512_DIGEST_SIZE}, in which case only the first @var{length}
1716 octets of the @acronym{MAC} are written.
1718 This function also resets the context for processing new messages, with
1722 @node Public-key algorithms, Randomness, Keyed hash functions, Reference
1723 @comment node-name, next, previous, up
1724 @section Public-key algorithms
1726 Nettle uses @acronym{GMP}, the GNU bignum library, for all calculations
1727 with large numbers. In order to use the public-key features of Nettle,
1728 you must install @acronym{GMP}, at least version 3.0, before compiling
1729 Nettle, and you need to link your programs with @code{-lhogweed -lnettle
1732 The concept of @dfn{Public-key} encryption and digital signatures was
1733 discovered by Whitfield Diffie and Martin E. Hellman and described in a
1734 paper 1976. In traditional, ``symmetric'', cryptography, sender and
1735 receiver share the same keys, and these keys must be distributed in a
1736 secure way. And if there are many users or entities that need to
1737 communicate, each @emph{pair} needs a shared secret key known by nobody
1740 @cindex Public Key Cryptography
1741 @cindex One-way function
1743 Public-key cryptography uses trapdoor one-way functions. A
1744 @dfn{one-way function} is a function @code{F} such that it is easy to
1745 compute the value @code{F(x)} for any @code{x}, but given a value
1746 @code{y}, it is hard to compute a corresponding @code{x} such that
1747 @code{y = F(x)}. Two examples are cryptographic hash functions, and
1748 exponentiation in certain groups.
1750 A @dfn{trapdoor one-way function} is a function @code{F} that is
1751 one-way, unless one knows some secret information about @code{F}. If one
1752 knows the secret, it is easy to compute both @code{F} and it's inverse.
1753 If this sounds strange, look at the @acronym{RSA} example below.
1755 Two important uses for one-way functions with trapdoors are public-key
1756 encryption, and digital signatures. The public-key encryption functions
1757 in Nettle are not yet documented; the rest of this chapter is about
1760 To use a digital signature algorithm, one must first create a
1761 @dfn{key-pair}: A public key and a corresponding private key. The private
1762 key is used to sign messages, while the public key is used for verifying
1763 that that signatures and messages match. Some care must be taken when
1764 distributing the public key; it need not be kept secret, but if a bad
1765 guy is able to replace it (in transit, or in some user's list of known
1766 public keys), bad things may happen.
1768 There are two operations one can do with the keys. The signature
1769 operation takes a message and a private key, and creates a signature for
1770 the message. A signature is some string of bits, usually at most a few
1771 thousand bits or a few hundred octets. Unlike paper-and-ink signatures,
1772 the digital signature depends on the message, so one can't cut it out of
1773 context and glue it to a different message.
1775 The verification operation takes a public key, a message, and a string
1776 that is claimed to be a signature on the message, and returns true or
1777 false. If it returns true, that means that the three input values
1778 matched, and the verifier can be sure that someone went through with the
1779 signature operation on that very message, and that the ``someone'' also
1780 knows the private key corresponding to the public key.
1782 The desired properties of a digital signature algorithm are as follows:
1783 Given the public key and pairs of messages and valid signatures on them,
1784 it should be hard to compute the private key, and it should also be hard
1785 to create a new message and signature that is accepted by the
1786 verification operation.
1788 Besides signing meaningful messages, digital signatures can be used for
1789 authorization. A server can be configured with a public key, such that
1790 any client that connects to the service is given a random nonce message.
1791 If the server gets a reply with a correct signature matching the nonce
1792 message and the configured public key, the client is granted access. So
1793 the configuration of the server can be understood as ``grant access to
1794 whoever knows the private key corresponding to this particular public
1795 key, and to no others''.
1799 * RSA:: The RSA public key algorithm.
1800 * DSA:: The DSA digital signature algorithm.
1803 @node RSA, DSA, Public-key algorithms, Public-key algorithms
1804 @comment node-name, next, previous, up
1805 @subsection @acronym{RSA}
1807 The @acronym{RSA} algorithm was the first practical digital signature
1808 algorithm that was constructed. It was described 1978 in a paper by
1809 Ronald Rivest, Adi Shamir and L.M. Adleman, and the technique was also
1810 patented in the @acronym{USA} in 1983. The patent expired on September 20, 2000, and since
1811 that day, @acronym{RSA} can be used freely, even in the @acronym{USA}.
1813 It's remarkably simple to describe the trapdoor function behind
1814 @acronym{RSA}. The ``one-way''-function used is
1820 I.e. raise x to the @code{e}:th power, while discarding all multiples of
1821 @code{n}. The pair of numbers @code{n} and @code{e} is the public key.
1822 @code{e} can be quite small, even @code{e = 3} has been used, although
1823 slightly larger numbers are recommended. @code{n} should be about 1000
1826 If @code{n} is large enough, and properly chosen, the inverse of F,
1827 the computation of @code{e}:th roots modulo @code{n}, is very difficult.
1828 But, where's the trapdoor?
1830 Let's first look at how @acronym{RSA} key-pairs are generated. First
1831 @code{n} is chosen as the product of two large prime numbers @code{p}
1832 and @code{q} of roughly the same size (so if @code{n} is 1000 bits,
1833 @code{p} and @code{q} are about 500 bits each). One also computes the
1834 number @code{phi = (p-1)(q-1)}, in mathematical speak, @code{phi} is the
1835 order of the multiplicative group of integers modulo n.
1837 Next, @code{e} is chosen. It must have no factors in common with @code{phi} (in
1838 particular, it must be odd), but can otherwise be chosen more or less
1839 randomly. @code{e = 65537} is a popular choice, because it makes raising
1840 to the @code{e}'th power particularly efficient, and being prime, it
1841 usually has no factors common with @code{phi}.
1843 Finally, a number @code{d}, @code{d < n} is computed such that @code{e d
1844 mod phi = 1}. It can be shown that such a number exists (this is why
1845 @code{e} and @code{phi} must have no common factors), and that for all x,
1848 (x^e)^d mod n = x^(ed) mod n = (x^d)^e mod n = x
1851 Using Euclid's algorithm, @code{d} can be computed quite easily from
1852 @code{phi} and @code{e}. But it is still hard to get @code{d} without
1853 knowing @code{phi}, which depends on the factorization of @code{n}.
1855 So @code{d} is the trapdoor, if we know @code{d} and @code{y = F(x)}, we can
1856 recover x as @code{y^d mod n}. @code{d} is also the private half of
1857 the @acronym{RSA} key-pair.
1859 The most common signature operation for @acronym{RSA} is defined in
1860 @cite{PKCS#1}, a specification by RSA Laboratories. The message to be
1861 signed is first hashed using a cryptographic hash function, e.g.
1862 @acronym{MD5} or @acronym{SHA1}. Next, some padding, the @acronym{ASN.1}
1863 ``Algorithm Identifier'' for the hash function, and the message digest
1864 itself, are concatenated and converted to a number @code{x}. The
1865 signature is computed from @code{x} and the private key as @code{s = x^d
1866 mod n}@footnote{Actually, the computation is not done like this, it is
1867 done more efficiently using @code{p}, @code{q} and the Chinese remainder
1868 theorem (@acronym{CRT}). But the result is the same.}. The signature, @code{s} is a
1869 number of about the same size of @code{n}, and it usually encoded as a
1870 sequence of octets, most significant octet first.
1872 The verification operation is straight-forward, @code{x} is computed
1873 from the message in the same way as above. Then @code{s^e mod n} is
1874 computed, the operation returns true if and only if the result equals
1877 @subsection Nettle's @acronym{RSA} support
1879 Nettle represents @acronym{RSA} keys using two structures that contain
1880 large numbers (of type @code{mpz_t}).
1882 @deftp {Context struct} {rsa_public_key} size n e
1883 @code{size} is the size, in octets, of the modulo, and is used internally.
1884 @code{n} and @code{e} is the public key.
1887 @deftp {Context struct} {rsa_private_key} size d p q a b c
1888 @code{size} is the size, in octets, of the modulo, and is used internally.
1889 @code{d} is the secret exponent, but it is not actually used when
1890 signing. Instead, the factors @code{p} and @code{q}, and the parameters
1891 @code{a}, @code{b} and @code{c} are used. They are computed from @code{p},
1892 @code{q} and @code{e} such that @code{a e mod (p - 1) = 1, b e mod (q -
1893 1) = 1, c q mod p = 1}.
1896 Before use, these structs must be initialized by calling one of
1898 @deftypefun void rsa_public_key_init (struct rsa_public_key *@var{pub})
1899 @deftypefunx void rsa_private_key_init (struct rsa_private_key *@var{key})
1900 Calls @code{mpz_init} on all numbers in the key struct.
1903 and when finished with them, the space for the numbers must be
1904 deallocated by calling one of
1906 @deftypefun void rsa_public_key_clear (struct rsa_public_key *@var{pub})
1907 @deftypefunx void rsa_private_key_clear (struct rsa_private_key *@var{key})
1908 Calls @code{mpz_clear} on all numbers in the key struct.
1911 In general, Nettle's @acronym{RSA} functions deviates from Nettle's ``no
1912 memory allocation''-policy. Space for all the numbers, both in the key structs
1913 above, and temporaries, are allocated dynamically. For information on how
1914 to customize allocation, see
1915 @xref{Custom Allocation,,GMP Allocation,gmp, GMP Manual}.
1917 When you have assigned values to the attributes of a key, you must call
1919 @deftypefun int rsa_public_key_prepare (struct rsa_public_key *@var{pub})
1920 @deftypefunx int rsa_private_key_prepare (struct rsa_private_key *@var{key})
1921 Computes the octet size of the key (stored in the @code{size} attribute,
1922 and may also do other basic sanity checks. Returns one if successful, or
1923 zero if the key can't be used, for instance if the modulo is smaller
1924 than the minimum size needed for @acronym{RSA} operations specified by PKCS#1.
1927 Before signing or verifying a message, you first hash it with the
1928 appropriate hash function. You pass the hash function's context struct
1929 to the @acronym{RSA} signature function, and it will extract the message
1930 digest and do the rest of the work. There are also alternative functions
1931 that take the hash digest as argument.
1933 There is currently no support for using SHA224 or SHA384 with
1934 @acronym{RSA} signatures, since there's no gain in either computation
1935 time nor message size compared to using SHA256 and SHA512, respectively.
1937 Creation and verification of signatures is done with the following functions:
1939 @deftypefun int rsa_md5_sign (const struct rsa_private_key *@var{key}, struct md5_ctx *@var{hash}, mpz_t @var{signature})
1940 @deftypefunx int rsa_sha1_sign (const struct rsa_private_key *@var{key}, struct sha1_ctx *@var{hash}, mpz_t @var{signature})
1941 @deftypefunx int rsa_sha256_sign (const struct rsa_private_key *@var{key}, struct sha256_ctx *@var{hash}, mpz_t @var{signature})
1942 @deftypefunx int rsa_sha512_sign (const struct rsa_private_key *@var{key}, struct sha512_ctx *@var{hash}, mpz_t @var{signature})
1943 The signature is stored in @var{signature} (which must have been
1944 @code{mpz_init}'ed earlier). The hash context is reset so that it can be
1945 used for new messages. Returns one on success, or zero on failure.
1946 Signing fails if the key is too small for the given hash size, e.g.,
1947 it's not possible to create a signature using SHA512 and a 512-bit
1951 @deftypefun int rsa_md5_sign_digest (const struct rsa_private_key *@var{key}, const uint8_t *@var{digest}, mpz_t @var{signature})
1952 @deftypefunx int rsa_sha1_sign_digest (const struct rsa_private_key *@var{key}, const uint8_t *@var{digest}, mpz_t @var{signature});
1953 @deftypefunx int rsa_sha256_sign_digest (const struct rsa_private_key *@var{key}, const uint8_t *@var{digest}, mpz_t @var{signature});
1954 @deftypefunx int rsa_sha512_sign_digest (const struct rsa_private_key *@var{key}, const uint8_t *@var{digest}, mpz_t @var{signature});
1955 Creates a signature from the given hash digest. @var{digest} should
1956 point to a digest of size @code{MD5_DIGEST_SIZE},
1957 @code{SHA1_DIGEST_SIZE}, or @code{SHA256_DIGEST_SIZE}, respectively. The
1958 signature is stored in @var{signature} (which must have been
1959 @code{mpz_init}:ed earlier). Returns one on success, or zero on failure.
1962 @deftypefun int rsa_md5_verify (const struct rsa_public_key *@var{key}, struct md5_ctx *@var{hash}, const mpz_t @var{signature})
1963 @deftypefunx int rsa_sha1_verify (const struct rsa_public_key *@var{key}, struct sha1_ctx *@var{hash}, const mpz_t @var{signature})
1964 @deftypefunx int rsa_sha256_verify (const struct rsa_public_key *@var{key}, struct sha256_ctx *@var{hash}, const mpz_t @var{signature})
1965 @deftypefunx int rsa_sha512_verify (const struct rsa_public_key *@var{key}, struct sha512_ctx *@var{hash}, const mpz_t @var{signature})
1966 Returns 1 if the signature is valid, or 0 if it isn't. In either case,
1967 the hash context is reset so that it can be used for new messages.
1970 @deftypefun int rsa_md5_verify_digest (const struct rsa_public_key *@var{key}, const uint8_t *@var{digest}, const mpz_t @var{signature})
1971 @deftypefunx int rsa_sha1_verify_digest (const struct rsa_public_key *@var{key}, const uint8_t *@var{digest}, const mpz_t @var{signature})
1972 @deftypefunx int rsa_sha256_verify_digest (const struct rsa_public_key *@var{key}, const uint8_t *@var{digest}, const mpz_t @var{signature})
1973 @deftypefunx int rsa_sha512_verify_digest (const struct rsa_public_key *@var{key}, const uint8_t *@var{digest}, const mpz_t @var{signature})
1974 Returns 1 if the signature is valid, or 0 if it isn't. @var{digest} should
1975 point to a digest of size @code{MD5_DIGEST_SIZE},
1976 @code{SHA1_DIGEST_SIZE}, or @code{SHA256_DIGEST_SIZE}, respectively.
1979 If you need to use the @acronym{RSA} trapdoor, the private key, in a way
1980 that isn't supported by the above functions Nettle also includes a
1981 function that computes @code{x^d mod n} and nothing more, using the
1982 @acronym{CRT} optimization.
1984 @deftypefun void rsa_compute_root (struct rsa_private_key *@var{key}, mpz_t @var{x}, const mpz_t @var{m})
1985 Computes @code{x = m^d}, efficiently.
1988 At last, how do you create new keys?
1990 @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});
1991 There are lots of parameters. @var{pub} and @var{key} is where the
1992 resulting key pair is stored. The structs should be initialized, but you
1993 don't need to call @code{rsa_public_key_prepare} or
1994 @code{rsa_private_key_prepare} after key generation.
1996 @var{random_ctx} and @var{random} is a randomness generator.
1997 @code{random(random_ctx, length, dst)} should generate @code{length}
1998 random octets and store them at @code{dst}. For advice, see
2001 @var{progress} and @var{progress_ctx} can be used to get callbacks
2002 during the key generation process, in order to uphold an illusion of
2003 progress. @var{progress} can be NULL, in that case there are no
2006 @var{size_n} is the desired size of the modulo, in bits. If @var{size_e}
2007 is non-zero, it is the desired size of the public exponent and a random
2008 exponent of that size is selected. But if @var{e_size} is zero, it is
2009 assumed that the caller has already chosen a value for @code{e}, and
2010 stored it in @var{pub}.
2011 Returns one on success, and zero on failure. The function can fail for
2012 example if if @var{n_size} is too small, or if @var{e_size} is zero and
2013 @code{pub->e} is an even number.
2016 @node DSA, , RSA, Public-key algorithms
2017 @comment node-name, next, previous, up
2018 @subsection Nettle's @acronym{DSA} support
2020 The @acronym{DSA} digital signature algorithm is more complex than
2021 @acronym{RSA}. It was specified during the early 1990s, and in 1994 NIST
2022 published @acronym{FIPS} 186 which is the authoritative specification.
2023 Sometimes @acronym{DSA} is referred to using the acronym @acronym{DSS},
2024 for Digital Signature Standard. The most recent revision of the
2025 specification, FIPS186-3, was issueed in 2009, and it adds support for
2026 larger hash functions than @acronym{sha1}.
2028 For @acronym{DSA}, the underlying mathematical problem is the
2029 computation of discreet logarithms. The public key consists of a large
2030 prime @code{p}, a small prime @code{q} which is a factor of @code{p-1},
2031 a number @code{g} which generates a subgroup of order @code{q} modulo
2032 @code{p}, and an element @code{y} in that subgroup.
2034 In the original @acronym{DSA}, the size of @code{q} is fixed to 160
2035 bits, to match with the @acronym{SHA1} hash algorithm. The size of
2036 @code{p} is in principle unlimited, but the
2037 standard specifies only nine specific sizes: @code{512 + l*64}, where
2038 @code{l} is between 0 and 8. Thus, the maximum size of @code{p} is 1024
2039 bits, and sizes less than 1024 bits are considered obsolete and not
2042 The subgroup requirement means that if you compute
2048 for all possible integers @code{t}, you will get precisely @code{q}
2051 The private key is a secret exponent @code{x}, such that
2057 In mathematical speak, @code{x} is the @dfn{discrete logarithm} of
2058 @code{y} mod @code{p}, with respect to the generator @code{g}. The size
2059 of @code{x} will also be about the same size as @code{q}. The security of the
2060 @acronym{DSA} algorithm relies on the difficulty of the discrete
2061 logarithm problem. Current algorithms to compute discrete logarithms in
2062 this setting, and hence crack @acronym{DSA}, are of two types. The first
2063 type works directly in the (multiplicative) group of integers mod
2064 @code{p}. The best known algorithm of this type is the Number Field
2065 Sieve, and it's complexity is similar to the complexity of factoring
2066 numbers of the same size as @code{p}. The other type works in the
2067 smaller @code{q}-sized subgroup generated by @code{g}, which has a more
2068 difficult group structure. One good algorithm is Pollard-rho, which has
2069 complexity @code{sqrt(q)}.
2071 The important point is that security depends on the size of @emph{both}
2072 @code{p} and @code{q}, and they should be choosen so that the difficulty
2073 of both discrete logarithm methods are comparable. Today, the security
2074 margin of the original @acronym{DSA} may be uncomfortably small. Using a
2075 @code{p} of 1024 bits implies that cracking using the number field sieve
2076 is expected to take about the same time as factoring a 1024-bit
2077 @acronym{RSA} modulo, and using a @code{q} of size 160 bits implies
2078 that cracking using Pollard-rho will take roughly @code{2^80} group
2079 operations. With the size of @code{q} fixed, tied to the @acronym{SHA1}
2080 digest size, it may be tempting to increase the size of @code{p} to,
2081 say, 4096 bits. This will provide excellent resistance against attacks
2082 like the number field sieve which works in the large group. But it will
2083 do very little to defend against Pollard-rho attacking the small
2084 subgroup; the attacker is slowed down at most by a single factor of 10
2085 due to the more expensive group operation. And the attacker will surely
2086 choose the latter attack.
2088 The signature generation algorithm is randomized; in order to create a
2089 @acronym{DSA} signature, you need a good source for random numbers
2090 (@pxref{Randomness}). Let us describe the common case of a 160-bit
2093 To create a signature, one starts with the hash digest of the message,
2094 @code{h}, which is a 160 bit number, and a random number @code{k,
2095 0<k<q}, also 160 bits. Next, one computes
2098 r = (g^k mod p) mod q
2099 s = k^-1 (h + x r) mod q
2102 The signature is the pair @code{(r, s)}, two 160 bit numbers. Note the
2103 two different mod operations when computing @code{r}, and the use of the
2104 secret exponent @code{x}.
2106 To verify a signature, one first checks that @code{0 < r,s < q}, and
2107 then one computes backwards,
2111 v = (g^(w h) y^(w r) mod p) mod q
2114 The signature is valid if @code{v = r}. This works out because @code{w =
2115 s^-1 mod q = k (h + x r)^-1 mod q}, so that
2118 g^(w h) y^(w r) = g^(w h) (g^x)^(w r) = g^(w (h + x r)) = g^k
2121 When reducing mod @code{q} this yields @code{r}. Note that when
2122 verifying a signature, we don't know either @code{k} or @code{x}: those
2125 If you can choose between @acronym{RSA} and @acronym{DSA}, which one is
2126 best? Both are believed to be secure. @acronym{DSA} gained popularity in
2127 the late 1990s, as a patent free alternative to @acronym{RSA}. Now that
2128 the @acronym{RSA} patents have expired, there's no compelling reason to
2129 want to use @acronym{DSA}. Today, the original @acronym{DSA} key size
2130 does not provide a large security margin, and it should probably be
2131 phased out together with @acronym{RSA} keys of 1024 bits. Using the
2132 revised @acronym{DSA} algorithm with a larger hash function, in
2133 particular, @acronym{SHA256}, a 256-bit @code{q}, and @code{p} of size
2134 2048 bits or more, should provide for a more comfortable security
2135 margin, but these variants are not yet in wide use.
2137 @acronym{DSA} signatures are smaller than @acronym{RSA} signatures,
2138 which is important for some specialized applications.
2140 From a practical point of view, @acronym{DSA}'s need for a good
2141 randomness source is a serious disadvantage. If you ever use the same
2142 @code{k} (and @code{r}) for two different message, you leak your private
2145 @subsection Nettle's @acronym{DSA} support
2147 Like for @acronym{RSA}, Nettle represents @acronym{DSA} keys using two
2148 structures, containing values of type @code{mpz_t}. For information on
2149 how to customize allocation, see @xref{Custom Allocation,,GMP
2150 Allocation,gmp, GMP Manual}.
2152 Most of the @acronym{DSA} functions are very similar to the
2153 corresponding @acronym{RSA} functions, but there are a few differences
2154 pointed out below. For a start, there are no functions corresponding to
2155 @code{rsa_public_key_prepare} and @code{rsa_private_key_prepare}.
2157 @deftp {Context struct} {dsa_public_key} p q g y
2158 The public parameters described above.
2161 @deftp {Context struct} {dsa_private_key} x
2162 The private key @code{x}.
2165 Before use, these structs must be initialized by calling one of
2167 @deftypefun void dsa_public_key_init (struct dsa_public_key *@var{pub})
2168 @deftypefunx void dsa_private_key_init (struct dsa_private_key *@var{key})
2169 Calls @code{mpz_init} on all numbers in the key struct.
2172 When finished with them, the space for the numbers must be
2173 deallocated by calling one of
2175 @deftypefun void dsa_public_key_clear (struct dsa_public_key *@var{pub})
2176 @deftypefunx void dsa_private_key_clear (struct dsa_private_key *@var{key})
2177 Calls @code{mpz_clear} on all numbers in the key struct.
2180 Signatures are represented using the structure below, and need to be
2181 initialized and cleared in the same way as the key structs.
2183 @deftp {Context struct} {dsa_signature} r s
2186 @deftypefun void dsa_signature_init (struct dsa_signature *@var{signature})
2187 @deftypefunx void dsa_signature_clear (struct dsa_signature *@var{signature})
2188 You must call @code{dsa_signature_init} before creating or using a
2189 signature, and call @code{dsa_signature_clear} when you are finished
2193 For signing, you need to provide both the public and the private key
2194 (unlike @acronym{RSA}, where the private key struct includes all
2195 information needed for signing), and a source for random numbers.
2196 Signatures can use the @acronym{SHA1} or the @acronym{SHA256} hash
2197 function, although the implementation of @acronym{DSA} with
2198 @acronym{SHA256} should be considered somewhat experimental due to lack
2199 of official test vectors and interoperability testing.
2201 @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})
2202 @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})
2203 @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})
2204 @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})
2205 Creates a signature from the given hash context or digest.
2206 @var{random_ctx} and @var{random} is a randomness generator.
2207 @code{random(random_ctx, length, dst)} should generate @code{length}
2208 random octets and store them at @code{dst}. For advice, see
2209 @xref{Randomness}. Returns one on success, or zero on failure.
2210 Signing fails if the key size and the hash size don't match.
2213 Verifying signatures is a little easier, since no randomness generator is
2214 needed. The functions are
2216 @deftypefun int dsa_sha1_verify (const struct dsa_public_key *@var{key}, struct sha1_ctx *@var{hash}, const struct dsa_signature *@var{signature})
2217 @deftypefunx int dsa_sha1_verify_digest (const struct dsa_public_key *@var{key}, const uint8_t *@var{digest}, const struct dsa_signature *@var{signature})
2218 @deftypefunx int dsa_sha256_verify (const struct dsa_public_key *@var{key}, struct sha256_ctx *@var{hash}, const struct dsa_signature *@var{signature})
2219 @deftypefunx int dsa_sha256_verify_digest (const struct dsa_public_key *@var{key}, const uint8_t *@var{digest}, const struct dsa_signature *@var{signature})
2220 Verifies a signature. Returns 1 if the signature is valid, otherwise 0.
2223 Key generation uses mostly the same parameters as the corresponding
2224 @acronym{RSA} function.
2226 @deftypefun int dsa_generate_keypair (struct dsa_public_key *@var{pub}, struct dsa_private_key *@var{key}, void *@var{random_ctx}, nettle_random_func @var{random}, void *@var{progress_ctx}, nettle_progress_func @var{progress}, unsigned @var{p_bits}, unsigned @var{q_bits})
2227 @var{pub} and @var{key} is where the resulting key pair is stored. The
2228 structs should be initialized before you call this function.
2230 @var{random_ctx} and @var{random} is a randomness generator.
2231 @code{random(random_ctx, length, dst)} should generate @code{length}
2232 random octets and store them at @code{dst}. For advice, see
2235 @var{progress} and @var{progress_ctx} can be used to get callbacks
2236 during the key generation process, in order to uphold an illusion of
2237 progress. @var{progress} can be NULL, in that case there are no
2240 @var{p_bits} and @var{q_bits} are the desired sizes of @code{p} and
2241 @code{q}. To generate keys that conform to the original @acronym{DSA}
2242 standard, you must use @code{q_bits = 160} and select @var{p_bits} of
2243 the form @code{p_bits = 512 + l*64}, for @code{0 <= l <= 8}, where the
2244 smaller sizes are no longer recommended, so you should most likely stick
2245 to @code{p_bits = 1024}. Non-standard sizes are possible, in particular
2246 @code{p_bits} larger than 1024, although @acronym{DSA} implementations
2247 can not in general be expected to support such keys. Also note that
2248 using very large @var{p_bits}, with @var{q_bits} fixed at 160, doesn't
2249 make much sense, because the security is also limited by the size of the
2250 smaller prime. Using a larger @code{q_bits} requires switchign to a
2251 larger hash function. To generate @acronym{DSA} keys for use with
2252 @acronym{SHA256}, use @code{q_bits = 256} and, e.g., @code{p_bits =
2255 Returns one on success, and zero on failure. The function will fail if
2256 @var{q_bits} is neither 160 nor 256, or if @var{p_bits} is unreasonably
2260 @node Randomness, Miscellaneous functions, Public-key algorithms, Reference
2261 @comment node-name, next, previous, up
2266 A crucial ingredient in many cryptographic contexts is randomness: Let
2267 @code{p} be a random prime, choose a random initialization vector
2268 @code{iv}, a random key @code{k} and a random exponent @code{e}, etc. In
2269 the theories, it is assumed that you have plenty of randomness around.
2270 If this assumption is not true in practice, systems that are otherwise
2271 perfectly secure, can be broken. Randomness has often turned out to be
2272 the weakest link in the chain.
2274 In non-cryptographic applications, such as games as well as scientific
2275 simulation, a good randomness generator usually means a generator that
2276 has good statistical properties, and is seeded by some simple function
2277 of things like the current time, process id, and host name.
2279 However, such a generator is inadequate for cryptography, for at least
2285 It's too easy for an attacker to guess the initial seed. Even if it will
2286 take some 2^32 tries before he guesses right, that's far too easy. For
2287 example, if the process id is 16 bits, the resolution of ``current time''
2288 is one second, and the attacker knows what day the generator was seeded,
2289 there are only about 2^32 possibilities to try if all possible values
2290 for the process id and time-of-day are tried.
2293 The generator output reveals too much. By observing only a small segment
2294 of the generator's output, its internal state can be recovered, and from
2295 there, all previous output and all future output can be computed by the
2299 A randomness generator that is used for cryptographic purposes must have
2300 better properties. Let's first look at the seeding, as the issues here
2301 are mostly independent of the rest of the generator. The initial state
2302 of the generator (its seed) must be unguessable by the attacker. So
2303 what's unguessable? It depends on what the attacker already knows. The
2304 concept used in information theory to reason about such things is called
2305 ``entropy'', or ``conditional entropy'' (not to be confused with the
2306 thermodynamic concept with the same name). A reasonable requirement is
2307 that the seed contains a conditional entropy of at least some 80-100
2308 bits. This property can be explained as follows: Allow the attacker to
2309 ask @code{n} yes-no-questions, of his own choice, about the seed. If
2310 the attacker, using this question-and-answer session, as well as any
2311 other information he knows about the seeding process, still can't guess
2312 the seed correctly, then the conditional entropy is more than @code{n}
2316 @cindex Conditional entropy
2318 Let's look at an example. Say information about timing of received
2319 network packets is used in the seeding process. If there is some random
2320 network traffic going on, this will contribute some bits of entropy or
2321 ``unguessability'' to the seed. However, if the attacker can listen in to
2322 the local network, or if all but a small number of the packets were
2323 transmitted by machines that the attacker can monitor, this additional
2324 information makes the seed easier for the attacker to figure out. Even
2325 if the information is exactly the same, the conditional entropy, or
2326 unguessability, is smaller for an attacker that knows some of it already
2327 before the hypothetical question-and-answer session.
2329 Seeding of good generators is usually based on several sources. The key
2330 point here is that the amount of unguessability that each source
2331 contributes, depends on who the attacker is. Some sources that have been
2335 @item High resolution timing of i/o activities
2336 Such as completed blocks from spinning hard disks, network packets, etc.
2337 Getting access to such information is quite system dependent, and not
2338 all systems include suitable hardware. If available, it's one of the
2339 better randomness source one can find in a digital, mostly predictable,
2343 Timing and contents of user interaction events is another popular source
2344 that is available for interactive programs (even if I suspect that it is
2345 sometimes used in order to make the user feel good, not because the
2346 quality of the input is needed or used properly). Obviously, not
2347 available when a machine is unattended. Also beware of networks: User
2348 interaction that happens across a long serial cable, @acronym{TELNET}
2349 session, or even @acronym{SSH} session may be visible to an attacker, in
2353 Any room, or even a microphone input that's left unconnected, is a
2354 source of some random background noise, which can be fed into the
2357 @item Specialized hardware
2358 Hardware devices with the sole purpose of generating random data have
2359 been designed. They range from radioactive samples with an attached
2360 Geiger counter, to amplification of the inherent noise in electronic
2361 components such as diodes and resistors, to low-frequency sampling of
2362 chaotic systems. Hashing successive images of a Lava lamp is a
2363 spectacular example of the latter type.
2365 @item Secret information
2366 Secret information, such as user passwords or keys, or private files
2367 stored on disk, can provide some unguessability. A problem is that if
2368 the information is revealed at a later time, the unguessability
2369 vanishes. Another problem is that this kind of information tends to be
2370 fairly constant, so if you rely on it and seed your generator regularly,
2371 you risk constructing almost similar seeds or even constructing the same
2372 seed more than once.
2375 For all practical sources, it's difficult but important to provide a
2376 reliable lower bound on the amount of unguessability that it provides.
2377 Two important points are to make sure that the attacker can't observe
2378 your sources (so if you like the Lava lamp idea, remember that you have
2379 to get your own lamp, and not put it by a window or anywhere else where
2380 strangers can see it), and that hardware failures are detected. What if
2381 the bulb in the Lava lamp, which you keep locked into a cupboard
2382 following the above advice, breaks after a few months?
2384 So let's assume that we have been able to find an unguessable seed,
2385 which contains at least 80 bits of conditional entropy, relative to all
2386 attackers that we care about (typically, we must at the very least
2387 assume that no attacker has root privileges on our machine).
2389 How do we generate output from this seed, and how much can we get? Some
2390 generators (notably the Linux @file{/dev/random} generator) tries to
2391 estimate available entropy and restrict the amount of output. The goal
2392 is that if you read 128 bits from @file{/dev/random}, you should get 128
2393 ``truly random'' bits. This is a property that is useful in some
2394 specialized circumstances, for instance when generating key material for
2395 a one time pad, or when working with unconditional blinding, but in most
2396 cases, it doesn't matter much. For most application, there's no limit on
2397 the amount of useful ``random'' data that we can generate from a small
2398 seed; what matters is that the seed is unguessable and that the
2399 generator has good cryptographic properties.
2401 At the heart of all generators lies its internal state. Future output
2402 is determined by the internal state alone. Let's call it the generator's
2403 key. The key is initialized from the unguessable seed. Important
2404 properties of a generator are:
2409 An attacker observing the output should not be able to recover the
2412 @item Independence of outputs
2413 Observing some of the output should not help the attacker to guess
2414 previous or future output.
2416 @item Forward secrecy
2417 Even if an attacker compromises the generator's key, he should not be
2418 able to guess the generator output @emph{before} the key compromise.
2420 @item Recovery from key compromise
2421 If an attacker compromises the generator's key, he can compute
2422 @emph{all} future output. This is inevitable if the generator is seeded
2423 only once, at startup. However, the generator can provide a reseeding
2424 mechanism, to achieve recovery from key compromise. More precisely: If
2425 the attacker compromises the key at a particular time @code{t_1}, there
2426 is another later time @code{t_2}, such that if the attacker observes all
2427 output generated between @code{t_1} and @code{t_2}, he still can't guess
2428 what output is generated after @code{t_2}.
2432 Nettle includes one randomness generator that is believed to have all
2433 the above properties, and two simpler ones.
2435 @acronym{ARCFOUR}, like any stream cipher, can be used as a randomness
2436 generator. Its output should be of reasonable quality, if the seed is
2437 hashed properly before it is used with @code{arcfour_set_key}. There's
2438 no single natural way to reseed it, but if you need reseeding, you
2439 should be using Yarrow instead.
2441 The ``lagged Fibonacci'' generator in @file{<nettle/knuth-lfib.h>} is a
2442 fast generator with good statistical properties, but is @strong{not} for
2443 cryptographic use, and therefore not documented here. It is included
2444 mostly because the Nettle test suite needs to generate some test data
2447 The recommended generator to use is Yarrow, described below.
2451 Yarrow is a family of pseudo-randomness generators, designed for
2452 cryptographic use, by John Kelsey, Bruce Schneier and Niels Ferguson.
2453 Yarrow-160 is described in a paper at
2454 @url{http://www.counterpane.com/yarrow.html}, and it uses @acronym{SHA1}
2455 and triple-DES, and has a 160-bit internal state. Nettle implements
2456 Yarrow-256, which is similar, but uses @acronym{SHA256} and
2457 @acronym{AES} to get an internal state of 256 bits.
2459 Yarrow was an almost finished project, the paper mentioned above is the
2460 closest thing to a specification for it, but some smaller details are
2461 left out. There is no official reference implementation or test cases.
2462 This section includes an overview of Yarrow, but for the details of
2463 Yarrow-256, as implemented by Nettle, you have to consult the source
2464 code. Maybe a complete specification can be written later.
2466 Yarrow can use many sources (at least two are needed for proper
2467 reseeding), and two randomness ``pools'', referred to as the ``slow pool'' and
2468 the ``fast pool''. Input from the sources is fed alternatingly into the
2469 two pools. When one of the sources has contributed 100 bits of entropy
2470 to the fast pool, a ``fast reseed'' happens and the fast pool is mixed
2471 into the internal state. When at least two of the sources have
2472 contributed at least 160 bits each to the slow pool, a ``slow reseed''
2473 takes place. The contents of both pools are mixed into the internal
2474 state. These procedures should ensure that the generator will eventually
2475 recover after a key compromise.
2477 The output is generated by using @acronym{AES} to encrypt a counter,
2478 using the generator's current key. After each request for output,
2479 another 256 bits are generated which replace the key. This ensures
2482 Yarrow can also use a @dfn{seed file} to save state across restarts.
2483 Yarrow is seeded by either feeding it the contents of the previous seed
2484 file, or feeding it input from its sources until a slow reseed happens.
2486 Nettle defines Yarrow-256 in @file{<nettle/yarrow.h>}.
2488 @deftp {Context struct} {struct yarrow256_ctx}
2491 @deftp {Context struct} {struct yarrow_source}
2492 Information about a single source.
2495 @defvr Constant YARROW256_SEED_FILE_SIZE
2496 Recommanded size of the Yarrow-256 seed file.
2499 @deftypefun void yarrow256_init (struct yarrow256_ctx *@var{ctx}, unsigned @var{nsources}, struct yarrow_source *@var{sources})
2500 Initializes the yarrow context, and its @var{nsources} sources. It's
2501 possible to call it with @var{nsources}=0 and @var{sources}=NULL, if
2502 you don't need the update features.
2505 @deftypefun void yarrow256_seed (struct yarrow256_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{seed_file})
2506 Seeds Yarrow-256 from a previous seed file. @var{length} should be at least
2507 @code{YARROW256_SEED_FILE_SIZE}, but it can be larger.
2509 The generator will trust you that the @var{seed_file} data really is
2510 unguessable. After calling this function, you @emph{must} overwrite the old
2511 seed file with newly generated data from @code{yarrow256_random}. If it's
2512 possible for several processes to read the seed file at about the same
2513 time, access must be coordinated using some locking mechanism.
2516 @deftypefun int yarrow256_update (struct yarrow256_ctx *@var{ctx}, unsigned @var{source}, unsigned @var{entropy}, unsigned @var{length}, const uint8_t *@var{data})
2517 Updates the generator with data from source @var{SOURCE} (an index that
2518 must be smaller than the number of sources). @var{entropy} is your
2519 estimated lower bound for the entropy in the data, measured in bits.
2520 Calling update with zero @var{entropy} is always safe, no matter if the
2521 data is random or not.
2523 Returns 1 if a reseed happened, in which case an application using a
2524 seed file may want to generate new seed data with
2525 @code{yarrow256_random} and overwrite the seed file. Otherwise, the
2529 @deftypefun void yarrow256_random (struct yarrow256_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{dst})
2530 Generates @var{length} octets of output. The generator must be seeded
2531 before you call this function.
2533 If you don't need forward secrecy, e.g. if you need non-secret
2534 randomness for initialization vectors or padding, you can gain some
2535 efficiency by buffering, calling this function for reasonably large
2536 blocks of data, say 100-1000 octets at a time.
2539 @deftypefun int yarrow256_is_seeded (struct yarrow256_ctx *@var{ctx})
2540 Returns 1 if the generator is seeded and ready to generate output,
2544 @deftypefun unsigned yarrow256_needed_sources (struct yarrow256_ctx *@var{ctx})
2545 Returns the number of sources that must reach the threshold before a
2546 slow reseed will happen. Useful primarily when the generator is unseeded.
2549 @deftypefun void yarrow256_fast_reseed (struct yarrow256_ctx *@var{ctx})
2550 @deftypefunx void yarrow256_slow_reseed (struct yarrow256_ctx *@var{ctx})
2551 Causes a fast or slow reseed to take place immediately, regardless of the
2552 current entropy estimates of the two pools. Use with care.
2555 Nettle includes an entropy estimator for one kind of input source: User
2558 @deftp {Context struct} {struct yarrow_key_event_ctx}
2559 Information about recent key events.
2562 @deftypefun void yarrow_key_event_init (struct yarrow_key_event_ctx *@var{ctx})
2563 Initializes the context.
2566 @deftypefun unsigned yarrow_key_event_estimate (struct yarrow_key_event_ctx *@var{ctx}, unsigned @var{key}, unsigned @var{time})
2567 @var{key} is the id of the key (ASCII value, hardware key code, X
2568 keysym, @dots{}, it doesn't matter), and @var{time} is the timestamp of
2569 the event. The time must be given in units matching the resolution by
2570 which you read the clock. If you read the clock with microsecond
2571 precision, @var{time} should be provided in units of microseconds. But
2572 if you use @code{gettimeofday} on a typical Unix system where the clock
2573 ticks 10 or so microseconds at a time, @var{time} should be given in
2574 units of 10 microseconds.
2576 Returns an entropy estimate, in bits, suitable for calling
2577 @code{yarrow256_update}. Usually, 0, 1 or 2 bits.
2580 @node Miscellaneous functions, Compatibility functions, Randomness, Reference
2581 @comment node-name, next, previous, up
2582 @section Miscellaneous functions
2584 @deftypefun {uint8_t *} memxor (uint8_t *@var{dst}, const uint8_t *@var{src}, size_t @var{n})
2585 XORs the source area on top of the destination area. The interface
2586 doesn't follow the Nettle conventions, because it is intended to be
2587 similar to the ANSI-C @code{memcpy} function.
2590 @code{memxor} is declared in @file{<nettle/memxor.h>}.
2592 @node Compatibility functions, , Miscellaneous functions, Reference
2593 @comment node-name, next, previous, up
2594 @section Compatibility functions
2596 For convenience, Nettle includes alternative interfaces to some
2597 algorithms, for compatibility with some other popular crypto toolkits.
2598 These are not fully documented here; refer to the source or to the
2599 documentation for the original implementation.
2601 MD5 is defined in [RFC 1321], which includes a reference implementation.
2602 Nettle defines a compatible interface to MD5 in
2603 @file{<nettle/md5-compat.h>}. This file defines the typedef
2604 @code{MD5_CTX}, and declares the functions @code{MD5Init}, @code{MD5Update} and
2607 Eric Young's ``libdes'' (also part of OpenSSL) is a quite popular DES
2608 implementation. Nettle includes a subset if its interface in
2609 @file{<nettle/des-compat.h>}. This file defines the typedefs
2610 @code{des_key_schedule} and @code{des_cblock}, two constants
2611 @code{DES_ENCRYPT} and @code{DES_DECRYPT}, and declares one global
2612 variable @code{des_check_key}, and the functions @code{des_cbc_cksum}
2613 @code{des_cbc_encrypt}, @code{des_ecb2_encrypt},
2614 @code{des_ecb3_encrypt}, @code{des_ecb_encrypt},
2615 @code{des_ede2_cbc_encrypt}, @code{des_ede3_cbc_encrypt},
2616 @code{des_is_weak_key}, @code{des_key_sched}, @code{des_ncbc_encrypt}
2617 @code{des_set_key}, and @code{des_set_odd_parity}.
2619 @node Nettle soup, Installation, Reference, Top
2620 @comment node-name, next, previous, up
2621 @chapter Traditional Nettle Soup
2622 For the serious nettle hacker, here is a recipe for nettle soup. 4 servings.
2626 1 liter fresh nettles (urtica dioica)
2628 2 tablespoons butter
2632 1 liter stock (meat or vegetable)
2641 Gather 1 liter fresh nettles. Use gloves! Small, tender shoots are
2642 preferable but the tops of larger nettles can also be used.
2644 Rinse the nettles very well. Boil them for 10 minutes in lightly salted
2645 water. Strain the nettles and save the water. Hack the nettles. Melt the
2646 butter and mix in the flour. Dilute with stock and the nettle-water you
2647 saved earlier. Add the hacked nettles. If you wish you can add some milk
2648 or cream at this stage. Bring to a boil and let boil for a few minutes.
2649 Season with salt and pepper.
2651 Serve with boiled egg-halves.
2653 @c And the original Swedish version.
2656 Recept på nässelsoppa
2662 1 l kött- eller grönsaksbuljong
2665 (lite grädde eller mjölk)
2667 Plocka 1 liter färska nässlor. Använd handskar! Helst små och späda
2668 skott, men topparna av större nässlor går också bra.
2670 Skölj nässlorna väl. Förväll dem ca 10 minuter i lätt saltat vatten.
2671 Häll av och spara spadet. Hacka nässlorna. Smält smöret, rör i mjöl och
2672 späd med buljong och nässelspad. Lägg i de hackade nässlorna. Om så
2673 önskas, häll i en skvätt mjölk eller grädde. Koka några minuter, och
2674 smaksätt med salt och peppar.
2676 Servera med kokta ägghalvor.
2679 @node Installation, Index, Nettle soup, Top
2680 @comment node-name, next, previous, up
2681 @chapter Installation
2683 Nettle uses @command{autoconf}. To build it, unpack the source and run
2693 to install in the default location, @file{/usr/local}. The library files
2694 are installed in @file{/use/local/lib/libnettle.a}
2695 @file{/use/local/lib/libhogweed.a} and the include files are installed
2696 in @file{/use/local/include/nettle/}.
2698 To get a list of configure options, use @code{./configure --help}.
2700 By default, only static libraries are built and installed. To also build
2701 and install shared libraries, use the @option{ --enable-shared} option
2702 to @command{./configure}.
2704 Using GNU make is recommended. For other make programs, in particular
2705 BSD make, you may have to use the @option{--disable-dependency-tracking}
2706 option to @command{./configure}.
2708 @node Index, , Installation, Top
2709 @comment node-name, next, previous, up
2710 @unnumbered Function and Concept Index
2717 ispell-local-dictionary: "american"
2718 ispell-skip-region-alist: (
2719 (ispell-words-keyword forward-line)
2720 ("^@example" . "^@end.*example")
2721 ("^@ignore" . "^@end.*ignore")
2722 ("^@\\(end\\|syncodeindex\\|vskip\\|\\(un\\)?macro\\|node\\|deftp\\) .*$")
2723 ("^@\\(printindex\\|set\\) .*$")
2725 ;; Allows one level of nested braces in the argument
2726 ("@\\(uref\\|value\\|badspell\\|code\\|file\\|var\\|url\\){[^{}]*\\({[^{}]*}[^{}]*\\)*}")
2729 ("\input texinfo.*$")
2730 ("ispell-ignore" . "ispell-end-ignore")
2731 ("^Local Variables:$" . "^End:$"))
2734 @c LocalWords: cryptographics crypto LSH GNUPG API GPL LGPL aes rijndael ller
2735 @c LocalWords: Sevilla arcfour RC Niels Dassen Colin Kuchling Biham sha Ruud
2736 @c LocalWords: Gutmann twofish de Rooij struct MB Rivest RFC Nettle's ECB CBC
2737 @c LocalWords: RSA Daemen Rijnmen Schneier DES's ede structs oddnesses HMAC
2738 @c LocalWords: NIST Alice's GMP bignum Diffie Adi Shamir Adleman Euclid's ASN
2739 @c LocalWords: PKCS callbacks Young's urtica dioica autoconf SSH tad
2740 @c LocalWords: unguessability reseeding reseed alternatingly keysym subkeys
2741 @c LocalWords: DSA gmp FIPS DSS libdes OpenSSL ARCTWO Josefsson Nikos Andreas
2742 @c LocalWords: Mavroyanopoulos Sigfridsson Comstedt interoperability Sparc IC
2743 @c LocalWords: DES FIXME Rivest's plaintext ciphertext CTR XORed timestamp
2744 @c LocalWords: XORs cryptologists