nettle.texinfo 98.3 KB
Newer Older
Niels Möller's avatar
Niels Möller committed
1
2
3
4
5
6
7
\input texinfo          @c -*-texinfo-*-

@c %**start of header
@setfilename nettle.info
@settitle The Nettle low-level cryptographic library.
@c %**end of header

8
9
@documentencoding ISO-8859-1

10
@footnotestyle end
Niels Möller's avatar
Niels Möller committed
11
12
13
14
15
16
17
@syncodeindex fn cp

@dircategory GNU Libraries
@direntry
* Nettle: (nettle).           A low-level cryptographics library.
@end direntry

18
19
@set COPYRIGHT-YEARS 2001, 2004, 2005
@set UPDATED-FOR 1.13
Niels Möller's avatar
Niels Möller committed
20

Niels Möller's avatar
Niels Möller committed
21
@c Latin-1 doesn't work with TeX output.
Niels Möller's avatar
Niels Möller committed
22
23
@c Also lookout for é characters.

24
25
26
27
@iftex
@set AUTHOR Niels M@"oller
@end iftex
@ifnottex
Niels Möller's avatar
Niels Möller committed
28
@set AUTHOR Niels Möller
29
30
@end ifnottex

Niels Möller's avatar
Niels Möller committed
31
@ifinfo
32
Manual for the Nettle library. This manual corresponds to version
Niels Möller's avatar
Niels Möller committed
33
34
@value{UPDATED-FOR}.

35
Copyright @value{COPYRIGHT-YEARS} @value{AUTHOR}
Niels Möller's avatar
Niels Möller committed
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

Permission is granted to make and distribute verbatim
copies of this manual provided the copyright notice and
this permission notice are preserved on all copies.

@ignore
Permission is granted to process this file through TeX
and print the results, provided the printed document
carries a copying permission notice identical to this
one except for the removal of this paragraph (this
paragraph not being relevant to the printed manual).

@end ignore
Permission is granted to copy and distribute modified
versions of this manual under the conditions for
verbatim copying, provided also that the sections
entitled ``Copying'' and ``GNU General Public License''
are included exactly as in the original, and provided
that the entire resulting derived work is distributed
under the terms of a permission notice identical to this
one.

Permission is granted to copy and distribute
translations of this manual into another language,
under the above conditions for modified versions,
except that this permission notice may be stated in a
translation approved by the Free Software Foundation.

@end ifinfo

@titlepage
@sp 10
@c @center @titlefont{Nettle Manual}

@title Nettle Manual
@subtitle For the Nettle Library version @value{UPDATED-FOR}

@author @value{AUTHOR}

@c The following two commands start the copyright page.
@page
@vskip 0pt plus 1filll
78
Copyright @copyright{} @value{COPYRIGHT-YEARS} @value{AUTHOR}
Niels Möller's avatar
Niels Möller committed
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100

Permission is granted to make and distribute verbatim
copies of this manual provided the copyright notice and
this permission notice are preserved on all copies.

Permission is granted to copy and distribute modified
versions of this manual under the conditions for
verbatim copying, provided also that the sections
entitled ``Copying'' and ``GNU General Public License''
are included exactly as in the original, and provided
that the entire resulting derived work is distributed
under the terms of a permission notice identical to this
one.

Permission is granted to copy and distribute
translations of this manual into another language,
under the above conditions for modified versions,
except that this permission notice may be stated in a
translation approved by the Free Software Foundation.

@end titlepage

101
102
@contents

Niels Möller's avatar
Niels Möller committed
103
104
105
@ifnottex
@node     Top, Introduction, (dir), (dir)
@comment  node-name,  next,  previous,  up
106
@top Nettle
Niels Möller's avatar
Niels Möller committed
107
108

This document describes the nettle low-level cryptographic library. You
Niels Möller's avatar
Niels Möller committed
109
can use the library directly from your C programs, or (recommended)
Niels Möller's avatar
Niels Möller committed
110
write or use an object-oriented wrapper for your favorite language or
Niels Möller's avatar
Niels Möller committed
111
112
application.

Niels Möller's avatar
Niels Möller committed
113
This manual corresponds to version @value{UPDATED-FOR} of the library.
Niels Möller's avatar
Niels Möller committed
114
115

@menu
Niels Möller's avatar
Niels Möller committed
116
117
* Introduction::                What is Nettle?
* Copyright::                   Your rights.
Niels Möller's avatar
Niels Möller committed
118
119
* Conventions::                 
* Example::                     
Niels Möller's avatar
Niels Möller committed
120
121
122
* Reference::                   All Nettle functions and features.
* Nettle soup::                 For the serious nettle hacker.
* Installation::                How to install Nettle.
Niels Möller's avatar
Niels Möller committed
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
* Index::                       
@end menu

@end ifnottex

@node Introduction, Copyright, Top, Top
@comment  node-name,  next,  previous,  up
@chapter Introduction

Nettle is a cryptographic library that is designed to fit easily in more
or less any context: In crypto toolkits for object-oriented languages
(C++, Python, Pike, ...), in applications like LSH or GNUPG, or even in
kernel space. In most contexts, you need more than the basic
cryptographic algorithms, you also need some way to keep track of available
algorithms, their properties and variants. You often have some algorithm
selection process, often dictated by a protocol you want to implement.

140
And as the requirements of applications differ in subtle and not so
Niels Möller's avatar
Niels Möller committed
141
142
143
144
145
146
147
148
149
150
subtle ways, an API that fits one application well can be a pain to use
in a different context. And that is why there are so many different
cryptographic libraries around.

Nettle tries to avoid this problem by doing one thing, the low-level
crypto stuff, and providing a @emph{simple} but general interface to it.
In particular, Nettle doesn't do algorithm selection. It doesn't do
memory allocation. It doesn't do any I/O.

The idea is that one can build several application and context specific
Niels Möller's avatar
Niels Möller committed
151
interfaces on top of Nettle, and share the code, test cases, benchmarks,
Niels Möller's avatar
Niels Möller committed
152
153
154
155
documentation, etc. For this first version, the only application using
Nettle is LSH, and it uses an object-oriented abstraction on top of the
library. 

156
157
158
159
This manual explains how to use the Nettle library. It also tries to
provide some background on the cryptography, and advice on how to best
put it to use.

Niels Möller's avatar
Niels Möller committed
160
161
162
163
@node Copyright, Conventions, Introduction, Top
@comment  node-name,  next,  previous,  up
@chapter Copyright

164
165
166
167
168
169
170
171
Nettle is distributed under the GNU General Public License (GPL) (see
the file COPYING for details). However, most of the individual files
are dual licensed under less restrictive licenses like the GNU Lesser
General Public License (LGPL), or are in the public domain. This means
that if you don't use the parts of nettle that are GPL-only, you have
the option to use the Nettle library just as if it were licensed under
the LGPL. To find the current status of particular files, you have to
read the copyright notices at the top of the files.
Niels Möller's avatar
Niels Möller committed
172
173
174
175
176
177

A list of the supported algorithms, their origins and licenses:

@table @emph
@item AES
The implementation of the AES cipher (also known as rijndael) is written
178
179
180
by Rafael Sevilla. Assembler for x86 by Rafael Sevilla and
@value{AUTHOR}, Sparc assembler by @value{AUTHOR}. Released under the
LGPL.
Niels Möller's avatar
Niels Möller committed
181
182
183

@item ARCFOUR
The implementation of the ARCFOUR (also known as RC4) cipher is written
184
by @value{AUTHOR}. Released under the LGPL.
Niels Möller's avatar
Niels Möller committed
185

Niels Möller's avatar
Niels Möller committed
186
187
188
189
190
@item ARCTWO
The implementation of the ARCTWO (also known as RC2) cipher is written
by Nikos Mavroyanopoulos and modified by Werner Koch and Simon
Josefsson. Released under the LGPL.

Niels Möller's avatar
Niels Möller committed
191
192
193
@item BLOWFISH
The implementation of the BLOWFISH cipher is written by Werner Koch,
copyright owned by the Free Software Foundation. Also hacked by Ray
194
Dassen and @value{AUTHOR}. Released under the GPL.
Niels Möller's avatar
Niels Möller committed
195
196
197
198
199
200
201
202
203

@item CAST128
The implementation of the CAST128 cipher is written by Steve Reid.
Released into the public domain.

@item DES
The implementation of the DES cipher is written by Dana L. How, and
released under the LGPL.

204
205
@item MD2
The implementation of MD2 is written by Andrew Kuchling, and hacked
206
some by Andreas Sigfridsson and @value{AUTHOR}. Python Cryptography
207
208
209
210
211
212
Toolkit license (essentially public domain).

@item MD4
This is almost the same code as for MD5 below, with modifications by
Marcus Comstedt. Released into the public domain.

Niels Möller's avatar
Niels Möller committed
213
214
@item MD5
The implementation of the MD5 message digest is written by Colin Plumb.
215
It has been hacked some more by Andrew Kuchling and @value{AUTHOR}.
Niels Möller's avatar
Niels Möller committed
216
217
218
219
220
Released into the public domain.

@item SERPENT
The implementation of the SERPENT cipher is written by Ross Anderson,
Eli Biham, and Lars Knudsen, adapted to LSH by Rafael Sevilla, and to
221
Nettle by @value{AUTHOR}. Released under the GPL.
Niels Möller's avatar
Niels Möller committed
222
223

@item SHA1
224
225
226
227
The C implementation of the SHA1 message digest is written by Peter
Gutmann, and hacked some more by Andrew Kuchling and @value{AUTHOR}.
Released into the public domain. Assembler for x86 by @value{AUTHOR},
released under the LGPL.
Niels Möller's avatar
Niels Möller committed
228
229
230
231
232
233
234
235
236
237
238
239

@item TWOFISH
The implementation of the TWOFISH cipher is written by Ruud de Rooij.
Released under the LGPL.
@end table

@node Conventions, Example, Copyright, Top
@comment  node-name,  next,  previous,  up
@chapter Conventions

For each supported algorithm, there is an include file that defines a
@emph{context struct}, a few constants, and declares functions for
240
operating on the context. The context struct encapsulates all information
Niels Möller's avatar
Niels Möller committed
241
242
243
needed by the algorithm, and it can be copied or moved in memory with no
unexpected effects.

244
245
246
247
248
249
250
251
For consistency, functions for different algorithms are very similar,
but there are some differences, for instance reflecting if the key setup
or encryption function differ for encryption and encryption, and whether
or not key setup can fail. There are also differences between algorithms
that don't show in function prototypes, but which the application must
nevertheless be aware of. There is no big difference between the
functions for stream ciphers and for block ciphers, although they should
be used quite differently by the application.
Niels Möller's avatar
Niels Möller committed
252
253
254
255
256
257
258
259
260
261
262

If your application uses more than one algorithm, you should probably
create an interface that is tailor-made for your needs, and then write a
few lines of glue code on top of Nettle.

By convention, for an algorithm named @code{foo}, the struct tag for the
context struct is @code{foo_ctx}, constants and functions uses prefixes
like @code{FOO_BLOCK_SIZE} (a constant) and @code{foo_set_key} (a
function).

In all functions, strings are represented with an explicit length, of
263
type @code{unsigned}, and a pointer of type @code{uint8_t *} or
Niels Möller's avatar
Niels Möller committed
264
265
266
267
@code{const uint8_t *}. For functions that transform one string to
another, the argument order is length, destination pointer and source
pointer. Source and destination areas are of the same length. Source and
destination may be the same, so that you can process strings in place,
268
but they @emph{must not} overlap in any other way.
Niels Möller's avatar
Niels Möller committed
269

270
271
@c FIXME: Say something about the name mangling.

Niels Möller's avatar
Niels Möller committed
272
273
274
275
276
@node Example, Reference, Conventions, Top
@comment  node-name,  next,  previous,  up
@chapter Example

A simple example program that reads a file from standard in and writes
Niels Möller's avatar
Niels Möller committed
277
its SHA1 checksum on standard output should give the flavor of Nettle.
Niels Möller's avatar
Niels Möller committed
278
279

@example
280
@verbatiminclude sha-example.c
Niels Möller's avatar
Niels Möller committed
281
282
@end example

Niels Möller's avatar
Niels Möller committed
283
@node Reference, Nettle soup, Example, Top
Niels Möller's avatar
Niels Möller committed
284
285
286
287
288
289
290
291
@comment  node-name,  next,  previous,  up
@chapter Reference

This chapter describes all the Nettle functions, grouped by family.

@menu
* Hash functions::              
* Cipher functions::            
292
* Cipher modes::                
Niels Möller's avatar
Niels Möller committed
293
* Keyed hash functions::        
294
295
* Public-key algorithms::       
* Randomness::                  
Niels Möller's avatar
Niels Möller committed
296
* Miscellaneous functions::     
297
* Compatibility functions::     
Niels Möller's avatar
Niels Möller committed
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
@end menu

@node Hash functions, Cipher functions, Reference, Reference
@comment  node-name,  next,  previous,  up
@section Hash functions

A cryptographic @dfn{hash function} is a function that takes variable
size strings, and maps them to strings of fixed, short, length. There
are naturally lots of collisions, as there are more possible 1MB files
than 20 byte strings. But the function is constructed such that is hard
to find the collisions. More precisely, a cryptographic hash function
@code{H} should have the following properties:

@table @emph

@item One-way
Given a hash value @code{H(x)} it is hard to find a string @code{x}
that hashes to that value.

@item Collision-resistant
It is hard to find two different strings, @code{x} and @code{y}, such
that @code{H(x)} = @code{H(y)}.

@end table

Hash functions are useful as building blocks for digital signatures,
324
message authentication codes, pseudo random generators, association of
Niels Möller's avatar
Niels Möller committed
325
326
unique id:s to documents, and many other things.

327
328
329
330
331
There are several fairly popular hash functions. Collisions have been
found the the compression function of MD4, and in variants of MD5.
These functions are therefore not recommended for new applications.
The recommended hash function for new applications is SHA1.

Niels Möller's avatar
Niels Möller committed
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
@subsection @acronym{MD5}

MD5 is a message digest function constructed by Ronald Rivest, and
described in @cite{RFC 1321}. It outputs message digests of 128 bits, or
16 octets. Nettle defines MD5 in @file{<nettle/md5.h>}.

@deftp {Context struct} {struct md5_ctx}
@end deftp

@defvr Constant MD5_DIGEST_SIZE
The size of an MD5 digest, i.e. 16.
@end defvr

@defvr Constant MD5_DATA_SIZE
The internal block size of MD5. Useful for some special constructions,
in particular HMAC-MD5.
@end defvr

@deftypefun void md5_init (struct md5_ctx *@var{ctx})
Initialize the MD5 state.
@end deftypefun

@deftypefun void md5_update (struct md5_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
Hash some more data.
@end deftypefun

@deftypefun void md5_digest (struct md5_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
359
360
361
362
Performs final processing and extracts the message digest, writing it
to @var{digest}. @var{length} may be smaller than
@code{MD5_DIGEST_SIZE}, in which case only the first @var{length}
octets of the digest are written.
Niels Möller's avatar
Niels Möller committed
363

364
365
This function also resets the context in the same way as
@code{md5_init}.
Niels Möller's avatar
Niels Möller committed
366
367
368
@end deftypefun

The normal way to use MD5 is to call the functions in order: First
369
370
371
372
@code{md5_init}, then @code{md5_update} zero or more times, and finally
@code{md5_digest}. After @code{md5_digest}, the context is reset to
its initial state, so you can start over calling @code{md5_update} to
hash new data.
Niels Möller's avatar
Niels Möller committed
373
374
375

To start over, you can call @code{md5_init} at any time.

376
377
@subsection @acronym{MD2}

Niels Möller's avatar
Niels Möller committed
378
MD2 is another hash function of Ronald Rivest's, described in
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
@cite{RFC 1319}. It outputs message digests of 128 bits, or 16 octets.
Nettle defines MD2 in @file{<nettle/md2.h>}.

@deftp {Context struct} {struct md2_ctx}
@end deftp

@defvr Constant MD2_DIGEST_SIZE
The size of an MD2 digest, i.e. 16.
@end defvr

@defvr Constant MD2_DATA_SIZE
The internal block size of MD2.
@end defvr

@deftypefun void md2_init (struct md2_ctx *@var{ctx})
Initialize the MD2 state.
@end deftypefun

@deftypefun void md2_update (struct md2_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
Hash some more data.
@end deftypefun

@deftypefun void md2_digest (struct md2_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
Performs final processing and extracts the message digest, writing it
to @var{digest}. @var{length} may be smaller than
@code{MD2_DIGEST_SIZE}, in which case only the first @var{length}
octets of the digest are written.

This function also resets the context in the same way as
@code{md2_init}.
@end deftypefun

@subsection @acronym{MD4}

MD4 is a predecessor of MD5, described in @cite{RFC 1320}. Like MD5,
it is constructed by Ronald Rivest. It outputs message digests of 128
bits, or 16 octets. Nettle defines MD4 in @file{<nettle/md4.h>}.
Because of discovered weaknesses, use of MD4 is not recommended, but
it is sometimes needed for compatibility with existing applications
and protocols.

@deftp {Context struct} {struct md4_ctx}
@end deftp

@defvr Constant MD4_DIGEST_SIZE
The size of an MD4 digest, i.e. 16.
@end defvr

@defvr Constant MD4_DATA_SIZE
The internal block size of MD4.
@end defvr

@deftypefun void md4_init (struct md4_ctx *@var{ctx})
Initialize the MD4 state.
@end deftypefun

@deftypefun void md4_update (struct md4_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
Hash some more data.
@end deftypefun

@deftypefun void md4_digest (struct md4_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
Performs final processing and extracts the message digest, writing it
to @var{digest}. @var{length} may be smaller than
@code{MD4_DIGEST_SIZE}, in which case only the first @var{length}
octets of the digest are written.

This function also resets the context in the same way as
@code{md4_init}.
@end deftypefun

Niels Möller's avatar
Niels Möller committed
449
450
451
@subsection @acronym{SHA1}

SHA1 is a hash function specified by @dfn{NIST} (The U.S. National Institute
452
453
for Standards and Technology). It outputs hash values of 160 bits, or 20
octets. Nettle defines SHA1 in @file{<nettle/sha.h>}.
Niels Möller's avatar
Niels Möller committed
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476

The functions are analogous to the MD5 ones.

@deftp {Context struct} {struct sha1_ctx}
@end deftp

@defvr Constant SHA1_DIGEST_SIZE
The size of an SHA1 digest, i.e. 20.
@end defvr

@defvr Constant SHA1_DATA_SIZE
The internal block size of SHA1. Useful for some special constructions,
in particular HMAC-SHA1.
@end defvr

@deftypefun void sha1_init (struct sha1_ctx *@var{ctx})
Initialize the SHA1 state.
@end deftypefun

@deftypefun void sha1_update (struct sha1_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
Hash some more data.
@end deftypefun

477
478
479
480
481
482
483
484
@deftypefun void sha1_digest (struct sha1_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
Performs final processing and extracts the message digest, writing it
to @var{digest}. @var{length} may be smaller than
@code{SHA1_DIGEST_SIZE}, in which case only the first @var{length}
octets of the digest are written.

This function also resets the context in the same way as
@code{sha1_init}.
Niels Möller's avatar
Niels Möller committed
485
486
@end deftypefun

487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
@subsection @acronym{SHA256}

SHA256 is another hash function specified by @dfn{NIST}, intended as a
replacement for @acronym{SHA1}, generating larger digests. It outputs
hash values of 256 bits, or 32 octets. Nettle defines SHA256 in
@file{<nettle/sha.h>}.

The functions are analogous to the MD5 ones.

@deftp {Context struct} {struct sha256_ctx}
@end deftp

@defvr Constant SHA256_DIGEST_SIZE
The size of an SHA256 digest, i.e. 20.
@end defvr

@defvr Constant SHA256_DATA_SIZE
The internal block size of SHA256. Useful for some special constructions,
in particular HMAC-SHA256.
@end defvr

@deftypefun void sha256_init (struct sha256_ctx *@var{ctx})
Initialize the SHA256 state.
@end deftypefun

@deftypefun void sha256_update (struct sha256_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
Hash some more data.
@end deftypefun

@deftypefun void sha256_digest (struct sha256_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
Performs final processing and extracts the message digest, writing it
to @var{digest}. @var{length} may be smaller than
@code{SHA256_DIGEST_SIZE}, in which case only the first @var{length}
octets of the digest are written.
Niels Möller's avatar
Niels Möller committed
521

522
523
This function also resets the context in the same way as
@code{sha256_init}.
Niels Möller's avatar
Niels Möller committed
524
525
@end deftypefun

Niels Möller's avatar
Niels Möller committed
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
@subsection @code{struct nettle_hash}

Nettle includes a struct including information about the supported hash
functions. It is defined in @file{<nettle/nettle-meta.h>}, and is used
by Nettle's implementation of @acronym{HMAC} @pxref{Keyed hash
functions}.

@deftp {Meta struct} @code{struct nettle_hash} name context_size digest_size block_size init update digest
The last three attributes are function pointers, of types
@code{nettle_hash_init_func}, @code{nettle_hash_update_func}, and
@code{nettle_hash_digest_func}. The first argument to these functions is
@code{void *} pointer so a context struct, which is of size
@code{context_size}. 
@end deftp

@deftypevr {Constant Struct} {struct nettle_cipher} nettle_md5
@deftypevrx {Constant Struct} {struct nettle_cipher} nettle_sha1
@deftypevrx {Constant Struct} {struct nettle_cipher} nettle_sha256

These are all the hash functions that Nettle implements.
@end deftypevr

548
@node Cipher functions, Cipher modes, Hash functions, Reference
Niels Möller's avatar
Niels Möller committed
549
550
551
552
553
554
@comment  node-name,  next,  previous,  up
@section Cipher functions

A @dfn{cipher} is a function that takes a message or @dfn{plaintext}
and a secret @dfn{key} and transforms it to a @dfn{ciphertext}. Given
only the ciphertext, but not the key, it should be hard to find the
Niels Möller's avatar
Niels Möller committed
555
plaintext. Given matching pairs of plaintext and ciphertext, it should
Niels Möller's avatar
Niels Möller committed
556
557
558
559
560
561
562
563
564
565
be hard to find the key.

There are two main classes of ciphers: Block ciphers and stream ciphers.

A block cipher can process data only in fixed size chunks, called
@dfn{blocks}. Typical block sizes are 8 or 16 octets. To encrypt
arbitrary messages, you usually have to pad it to an integral number of
blocks, split it into blocks, and then process each block. The simplest
way is to process one block at a time, independent of each other. That
mode of operation is called @dfn{ECB}, Electronic Code Book mode.
566
However, using @acronym{ECB} is usually a bad idea. For a start, plaintext blocks
Niels Möller's avatar
Niels Möller committed
567
568
that are equal are transformed to ciphertext blocks that are equal; that
leaks information about the plaintext. Usually you should apply the
569
570
571
572
cipher is some ``feedback mode'', @dfn{CBC} (Cipher Block Chaining) and
@dfn{CTR} (Counter mode) being two of
of the most popular. See @xref{Cipher modes}, for information on
how to apply @acronym{CBC} and @acronym{CTR} with Nettle.
Niels Möller's avatar
Niels Möller committed
573
574

A stream cipher can be used for messages of arbitrary length; a typical
Niels Möller's avatar
Niels Möller committed
575
stream cipher is a keyed pseudo-random generator. To encrypt a plaintext
Niels Möller's avatar
Niels Möller committed
576
message of @var{n} octets, you key the generator, generate @var{n}
Niels Möller's avatar
Niels Möller committed
577
octets of pseudo-random data, and XOR it with the plaintext. To decrypt,
Niels Möller's avatar
Niels Möller committed
578
579
580
581
582
583
584
585
regenerate the same stream using the key, XOR it to the ciphertext, and
the plaintext is recovered.

@strong{Caution:} The first rule for this kind of cipher is the
same as for a One Time Pad: @emph{never} ever use the same key twice.

A common misconception is that encryption, by itself, implies
authentication. Say that you and a friend share a secret key, and you
Niels Möller's avatar
Niels Möller committed
586
receive an encrypted message. You apply the key, and get a plaintext
587
message that makes sense to you. Can you then be sure that it really was
Niels Möller's avatar
Niels Möller committed
588
your friend that wrote the message you're reading? The answer is no. For
Niels Möller's avatar
Niels Möller committed
589
590
591
592
example, if you were using a block cipher in ECB mode, an attacker may
pick up the message on its way, and reorder, delete or repeat some of
the blocks. Even if the attacker can't decrypt the message, he can
change it so that you are not reading the same message as your friend
Niels Möller's avatar
Niels Möller committed
593
594
595
596
wrote. If you are using a block cipher in @acronym{CBC} mode rather than
ECB, or are using a stream cipher, the possibilities for this sort of
attack are different, but the attacker can still make predictable
changes to the message.
Niels Möller's avatar
Niels Möller committed
597
598
599

It is recommended to @emph{always} use an authentication mechanism in
addition to encrypting the messages. Popular choices are Message
Niels Möller's avatar
Niels Möller committed
600
Authentication Codes like @acronym{HMAC-SHA1} @pxref{Keyed hash
601
functions}, or digital signatures like @acronym{RSA}.
Niels Möller's avatar
Niels Möller committed
602

603
Some ciphers have so called ``weak keys'', keys that results in
Niels Möller's avatar
Niels Möller committed
604
605
606
607
608
609
610
611
undesirable structure after the key setup processing, and should be
avoided. In Nettle, the presence of weak keys for a cipher mean that the
key setup function can fail, so you have to check its return value. In
addition, the context struct has a field @code{status}, that is set to a
non-zero value if key setup fails. When possible, avoid algorithm that
have weak keys. There are several good ciphers that don't have any weak
keys.

612
613
614
615
616
617
618
619
To encrypt a message, you first initialize a cipher context for
encryption or decryption with a particular key. You then use the context
to process plaintext or ciphertext messages. The initialization is known
as called @dfn{key setup}. With Nettle, it is recommended to use each
context struct for only one direction, even if some of the ciphers use a
single key setup function that can be used for both encryption and
decryption.

Niels Möller's avatar
Niels Möller committed
620
621
@subsection AES
AES is a quite new block cipher, specified by NIST as a replacement for
Niels Möller's avatar
Niels Möller committed
622
the older DES standard. The standard is the result of a competition
623
624
between cipher designers. The winning design, also known as RIJNDAEL,
was constructed by Joan Daemen and Vincent Rijnmen.
Niels Möller's avatar
Niels Möller committed
625
626

Like all the AES candidates, the winning design uses a block size of 128
Niels Möller's avatar
Niels Möller committed
627
bits, or 16 octets, and variable key-size, 128, 192 and 256 bits (16, 24
Niels Möller's avatar
Niels Möller committed
628
629
630
631
632
633
634
and 32 octets) being the allowed key sizes. It does not have any weak
keys. Nettle defines AES in @file{<nettle/aes.h>}.
 
@deftp {Context struct} {struct aes_ctx}
@end deftp

@defvr Constant AES_BLOCK_SIZE
Niels Möller's avatar
Niels Möller committed
635
The AES block-size, 16
Niels Möller's avatar
Niels Möller committed
636
637
638
639
640
641
642
643
644
645
646
647
@end defvr

@defvr Constant AES_MIN_KEY_SIZE
@end defvr

@defvr Constant AES_MAX_KEY_SIZE
@end defvr

@defvr Constant AES_KEY_SIZE
Default AES key size, 32
@end defvr

648
649
650
@deftypefun void aes_set_encrypt_key (struct aes_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
@deftypefunx void aes_set_decrypt_key (struct aes_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
Initialize the cipher, for encryption or decryption, respectively.
Niels Möller's avatar
Niels Möller committed
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
@end deftypefun

@deftypefun void aes_encrypt (struct aes_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
Encryption function. @var{length} must be an integral multiple of the
block size. If it is more than one block, the data is processed in ECB
mode. @code{src} and @code{dst} may be equal, but they must not overlap
in any other way.
@end deftypefun

@deftypefun void aes_decrypt (struct aes_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
Analogous to @code{aes_encrypt}
@end deftypefun

@subsection ARCFOUR
ARCFOUR is a stream cipher, also known under the trade marked name RC4,
and it is one of the fastest ciphers around. A problem is that the key
setup of ARCFOUR is quite weak, you should never use keys with
structure, keys that are ordinary passwords, or sequences of keys like
669
``secret:1'', ``secret:2'', @enddots{}. If you have keys that don't look
Niels Möller's avatar
Niels Möller committed
670
671
672
673
674
675
like random bit strings, and you want to use ARCFOUR, always hash the
key before feeding it to ARCFOUR. For example

@example
/* A more robust key setup function for ARCFOUR */
void
676
677
arcfour_set_key_hashed(struct arcfour_ctx *ctx,
                       unsigned length, const uint8_t *key)
Niels Möller's avatar
Niels Möller committed
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
@{
  struct sha1_ctx hash;
  uint8_t digest[SHA1_DIGEST_SIZE];

  sha1_init(&hash);
  sha1_update(&hash, length, key);
  sha1_digest(&hash, SHA1_DIGEST_SIZE, digest);

  arcfour_set_key(ctx, SHA1_DIGEST_SIZE, digest);
@}
@end example

Nettle defines ARCFOUR in @file{<nettle/arcfour.h>}.

@deftp {Context struct} {struct arcfour_ctx}
@end deftp

@defvr Constant ARCFOUR_MIN_KEY_SIZE
Minimum key size, 1
@end defvr

@defvr Constant ARCFOUR_MAX_KEY_SIZE
Maximum key size, 256
@end defvr

@defvr Constant ARCFOUR_KEY_SIZE
Default ARCFOUR key size, 16
@end defvr

@deftypefun void arcfour_set_key (struct arcfour_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
Initialize the cipher. The same function is used for both encryption and
decryption. 
@end deftypefun

712
@deftypefun void arcfour_crypt (struct arcfour_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
Niels Möller's avatar
Niels Möller committed
713
714
715
716
717
718
719
Encrypt some data. The same function is used for both encryption and
decryption. Unlike the block ciphers, this function modifies the
context, so you can split the data into arbitrary chunks and encrypt
them one after another. The result is the same as if you had called
@code{arcfour_crypt} only once with all the data.
@end deftypefun

Niels Möller's avatar
Niels Möller committed
720
721
722
723
@subsection ARCTWO
ARCTWO (also known as the trade marked name RC2) is a block cipher
specified in RFC 2268. Nettle also include a variation of the ARCTWO
set key operation that lack one step, to be compatible with the
724
reverse engineered RC2 cipher description, as described in a Usenet
Niels Möller's avatar
Niels Möller committed
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
post to @code{sci.crypt} by Peter Gutmann.

ARCTWO uses a block size of 64 bits, and variable key-size ranging
from 1 to 128 octets. Besides the key, ARCTWO also has a second
parameter to key setup, the number of effective key bits, @code{ekb}.
This parameter can be used to artificially reduce the key size. In
practice, @code{ekb} is usually set equal to the input key size.
Nettle defines ARCTWO in @file{<nettle/arctwo.h>}.

We do not recommend the use of ARCTWO; the Nettle implementation is
provided primarily for interoperability with existing applications and
standards.

@deftp {Context struct} {struct arctwo_ctx}
@end deftp

@defvr Constant ARCTWO_BLOCK_SIZE
The AES block-size, 8
@end defvr

@defvr Constant ARCTWO_MIN_KEY_SIZE
@end defvr

@defvr Constant ARCTWO_MAX_KEY_SIZE
@end defvr

@defvr Constant ARCTWO_KEY_SIZE
Default ARCTWO key size, 8
@end defvr

@deftypefun void arctwo_set_key_ekb (struct arctwo_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key}, unsigned @var{ekb})
@deftypefunx void arctwo_set_key (struct arctwo_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
@deftypefunx void arctwo_set_key_gutmann (struct arctwo_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
Initialize the cipher. The same function is used for both encryption
and decryption. The first function is the most general one, which lets
you provide both the variable size key, and the desired effective key
size (in bits). The maximum value for @var{ekb} is 1024, and for
convenience, @code{ekb = 0} has the same effect as @code{ekb = 1024}.

@code{arctwo_set_key(ctx, length, key)} is equivalent to
@code{arctwo_set_key_ekb(ctx, length, key, 8*length)}, and
@code{arctwo_set_key_gutmann(ctx, length, key)} is equivalent to
@code{arctwo_set_key_ekb(ctx, length, key, 1024)}
@end deftypefun

@deftypefun void arctwo_encrypt (struct arctwo_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
Encryption function. @var{length} must be an integral multiple of the
block size. If it is more than one block, the data is processed in ECB
mode. @code{src} and @code{dst} may be equal, but they must not
overlap in any other way.
@end deftypefun

@deftypefun void arctwo_decrypt (struct arctwo_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
Analogous to @code{arctwo_encrypt}
@end deftypefun

Niels Möller's avatar
Niels Möller committed
781
782
@subsection CAST128

783
784
785
786
787
788
789
790
CAST-128 is a block cipher, specified in @cite{RFC 2144}. It uses a 64
bit (8 octets) block size, and a variable key size of up to 128 bits.
Nettle defines cast128 in @file{<nettle/cast128.h>}.

@deftp {Context struct} {struct cast128_ctx}
@end deftp

@defvr Constant CAST128_BLOCK_SIZE
Niels Möller's avatar
Niels Möller committed
791
The CAST128 block-size, 8
792
793
794
@end defvr

@defvr Constant CAST128_MIN_KEY_SIZE
Niels Möller's avatar
Niels Möller committed
795
Minimum CAST128 key size, 5
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
@end defvr

@defvr Constant CAST128_MAX_KEY_SIZE
Maximum CAST128 key size, 16
@end defvr

@defvr Constant CAST128_KEY_SIZE
Default CAST128 key size, 16
@end defvr

@deftypefun void cast128_set_key (struct cast128_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
Initialize the cipher. The same function is used for both encryption and
decryption. 
@end deftypefun

@deftypefun void cast128_encrypt (struct cast128_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
Encryption function. @var{length} must be an integral multiple of the
block size. If it is more than one block, the data is processed in ECB
mode. @code{src} and @code{dst} may be equal, but they must not overlap
in any other way.
@end deftypefun

@deftypefun void cast128_decrypt (struct cast128_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
Analogous to @code{cast128_encrypt}
@end deftypefun

Niels Möller's avatar
Niels Möller committed
822
823
@subsection BLOWFISH

824
825
826
827
828
829
830
831
BLOWFISH is a block cipher designed by Bruce Schneier. It uses a block
size of 64 bits (8 octets), and a variable key size, up to 448 bits. It
has some weak keys. Nettle defines BLOWFISH in @file{<nettle/blowfish.h>}.

@deftp {Context struct} {struct blowfish_ctx}
@end deftp

@defvr Constant BLOWFISH_BLOCK_SIZE
Niels Möller's avatar
Niels Möller committed
832
The BLOWFISH block-size, 8
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
@end defvr

@defvr Constant BLOWFISH_MIN_KEY_SIZE
Minimum BLOWFISH key size, 8
@end defvr

@defvr Constant BLOWFISH_MAX_KEY_SIZE
Maximum BLOWFISH key size, 56
@end defvr

@defvr Constant BLOWFISH_KEY_SIZE
Default BLOWFISH key size, 16
@end defvr

@deftypefun int blowfish_set_key (struct blowfish_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
Initialize the cipher. The same function is used for both encryption and
decryption. Returns 1 on success, and 0 if the key was weak. Calling
@code{blowfish_encrypt} or @code{blowfish_decrypt} with a weak key will
crash with an assert violation.
@end deftypefun

@deftypefun void blowfish_encrypt (struct blowfish_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
Encryption function. @var{length} must be an integral multiple of the
block size. If it is more than one block, the data is processed in ECB
mode. @code{src} and @code{dst} may be equal, but they must not overlap
in any other way.
@end deftypefun

@deftypefun void blowfish_decrypt (struct blowfish_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
Analogous to @code{blowfish_encrypt}
@end deftypefun

Niels Möller's avatar
Niels Möller committed
865
@subsection DES
866
867
868
869
870
871
872
873
874
875
DES is the old Data Encryption Standard, specified by NIST. It uses a
block size of 64 bits (8 octets), and a key size of 56 bits. However,
the key bits are distributed over 8 octets, where the least significant
bit of each octet is used for parity. A common way to use DES is to
generate 8 random octets in some way, then set the least significant bit
of each octet to get odd parity, and initialize DES with the resulting
key.

The key size of DES is so small that keys can be found by brute force,
using specialized hardware or lots of ordinary work stations in
Niels Möller's avatar
Niels Möller committed
876
parallel. One shouldn't be using plain DES at all today, if one uses
877
DES at all one should be using DES3 or ``triple DES'', see below.
878
879
880
881
882
883
884

DES also has some weak keys. Nettle defines DES in @file{<nettle/des.h>}.

@deftp {Context struct} {struct des_ctx}
@end deftp

@defvr Constant DES_BLOCK_SIZE
Niels Möller's avatar
Niels Möller committed
885
The DES block-size, 8
886
887
888
889
890
891
@end defvr

@defvr Constant DES_KEY_SIZE
DES key size, 8
@end defvr

892
@deftypefun int des_set_key (struct des_ctx *@var{ctx}, const uint8_t *@var{key})
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
Initialize the cipher. The same function is used for both encryption and
decryption. Returns 1 on success, and 0 if the key was weak or had bad
parity. Calling @code{des_encrypt} or @code{des_decrypt} with a bad key
will crash with an assert violation.
@end deftypefun

@deftypefun void des_encrypt (struct des_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
Encryption function. @var{length} must be an integral multiple of the
block size. If it is more than one block, the data is processed in ECB
mode. @code{src} and @code{dst} may be equal, but they must not overlap
in any other way.
@end deftypefun

@deftypefun void des_decrypt (struct des_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
Analogous to @code{des_encrypt}
@end deftypefun
Niels Möller's avatar
Niels Möller committed
909

910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
@deftypefun void des_fix_parity (unsigned @var{length}, uint8_t *@var{dst}, const uint8_t *@var{src})
Adjusts the parity bits to match DES's requirements. You need this
function if you have created a random-looking string by a key agreement
protocol, and want to use it as a DES key. @var{dst} and @var{src} may
be equal.
@end deftypefun

@subsection DES3
The inadequate key size of DES has already been mentioned. One way to
increase the key size is to pipe together several DES boxes with
independent keys. It turns out that using two DES ciphers is not as
secure as one might think, even if the key size of the combination is a
respectable 112 bits.

The standard way to increase DES's key size is to use three DES boxes.
The mode of operation is a little peculiar: the middle DES box is wired
in the reverse direction. To encrypt a block with DES3, you encrypt it
using the first 56 bits of the key, then @emph{decrypt} it using the
middle 56 bits of the key, and finally encrypt it again using the last
929
930
56 bits of the key. This is known as ``ede'' triple-DES, for
``encrypt-decrypt-encrypt''.
931

932
The ``ede'' construction provides some backward compatibility, as you get
933
934
935
936
937
938
939
plain single DES simply by feeding the same key to all three boxes. That
should help keeping down the gate count, and the price, of hardware
circuits implementing both plain DES and DES3.

DES3 has a key size of 168 bits, but just like plain DES, useless parity
bits are inserted, so that keys are represented as 24 octets (192 bits).
As a 112 bit key is large enough to make brute force attacks
940
impractical, some applications uses a ``two-key'' variant of triple-DES.
941
942
943
944
945
946
In this mode, the same key bits are used for the first and the last DES
box in the pipe, while the middle box is keyed independently. The
two-key variant is believed to be secure, i.e. there are no known
attacks significantly better than brute force.

Naturally, it's simple to implement triple-DES on top of Nettle's DES
947
functions. Nettle includes an implementation of three-key ``ede''
948
949
950
951
952
953
954
triple-DES, it is defined in the same place as plain DES,
@file{<nettle/des.h>}.

@deftp {Context struct} {struct des3_ctx}
@end deftp

@defvr Constant DES3_BLOCK_SIZE
Niels Möller's avatar
Niels Möller committed
955
The DES3 block-size is the same as DES_BLOCK_SIZE, 8
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
@end defvr

@defvr Constant DES3_KEY_SIZE
DES key size, 24
@end defvr

@deftypefun int des3_set_key (struct des3_ctx *@var{ctx}, const uint8_t *@var{key})
Initialize the cipher. The same function is used for both encryption and
decryption. Returns 1 on success, and 0 if the key was weak or had bad
parity. Calling @code{des_encrypt} or @code{des_decrypt} with a bad key
will crash with an assert violation.
@end deftypefun

For random-looking strings, you can use @code{des_fix_parity} to adjust
the parity bits before calling @code{des3_set_key}.

@deftypefun void des3_encrypt (struct des3_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
Encryption function. @var{length} must be an integral multiple of the
block size. If it is more than one block, the data is processed in ECB
mode. @code{src} and @code{dst} may be equal, but they must not overlap
in any other way.
@end deftypefun

@deftypefun void des3_decrypt (struct des3_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
Analogous to @code{des_encrypt}
@end deftypefun

Niels Möller's avatar
Niels Möller committed
983
@subsection SERPENT
984
985
SERPENT is one of the AES finalists, designed by Ross Anderson, Eli
Biham and Lars Knudsen. Thus, the interface and properties are similar
Niels Möller's avatar
Niels Möller committed
986
to AES'. One peculiarity is that it is quite pointless to use it with
987
988
989
990
991
992
993
anything but the maximum key size, smaller keys are just padded to
larger ones. Nettle defines SERPENT in @file{<nettle/serpent.h>}.

@deftp {Context struct} {struct serpent_ctx}
@end deftp

@defvr Constant SERPENT_BLOCK_SIZE
Niels Möller's avatar
Niels Möller committed
994
The SERPENT block-size, 16
995
996
997
@end defvr

@defvr Constant SERPENT_MIN_KEY_SIZE
Niels Möller's avatar
Niels Möller committed
998
Minimum SERPENT key size, 16
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
@end defvr

@defvr Constant SERPENT_MAX_KEY_SIZE
Maximum SERPENT key size, 32
@end defvr

@defvr Constant SERPENT_KEY_SIZE
Default SERPENT key size, 32
@end defvr

@deftypefun void serpent_set_key (struct serpent_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
Initialize the cipher. The same function is used for both encryption and
decryption. 
@end deftypefun

@deftypefun void serpent_encrypt (struct serpent_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
Encryption function. @var{length} must be an integral multiple of the
block size. If it is more than one block, the data is processed in ECB
mode. @code{src} and @code{dst} may be equal, but they must not overlap
in any other way.
@end deftypefun

@deftypefun void serpent_decrypt (struct serpent_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
Analogous to @code{serpent_encrypt}
@end deftypefun

Niels Möller's avatar
Niels Möller committed
1025
1026

@subsection TWOFISH
1027
1028
1029
1030
1031
1032
1033
Another AES finalist, this one designed by Bruce Schneier and others.
Nettle defines it in @file{<nettle/twofish.h>}.

@deftp {Context struct} {struct twofish_ctx}
@end deftp

@defvr Constant TWOFISH_BLOCK_SIZE
Niels Möller's avatar
Niels Möller committed
1034
The TWOFISH block-size, 16
1035
1036
1037
@end defvr

@defvr Constant TWOFISH_MIN_KEY_SIZE
Niels Möller's avatar
Niels Möller committed
1038
Minimum TWOFISH key size, 16
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
@end defvr

@defvr Constant TWOFISH_MAX_KEY_SIZE
Maximum TWOFISH key size, 32
@end defvr

@defvr Constant TWOFISH_KEY_SIZE
Default TWOFISH key size, 32
@end defvr

@deftypefun void twofish_set_key (struct twofish_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{key})
Initialize the cipher. The same function is used for both encryption and
decryption. 
@end deftypefun

@deftypefun void twofish_encrypt (struct twofish_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
Encryption function. @var{length} must be an integral multiple of the
block size. If it is more than one block, the data is processed in ECB
mode. @code{src} and @code{dst} may be equal, but they must not overlap
in any other way.
@end deftypefun

@deftypefun void twofish_decrypt (struct twofish_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{dst}, uint8_t *@var{src})
Analogous to @code{twofish_encrypt}
@end deftypefun

Niels Möller's avatar
Niels Möller committed
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
@c @node nettle_cipher, Cipher Block Chaining, Cipher functions, Reference
@c @comment  node-name,  next,  previous,  up
@subsection @code{struct nettle_cipher}

Nettle includes a struct including information about some of the more
regular cipher functions. It should be considered a little experimental,
but can be useful for applications that need a simple way to handle
various algorithms. Nettle defines these structs in
@file{<nettle/nettle-meta.h>}. 

@deftp {Meta struct} @code{struct nettle_cipher} name context_size block_size key_size set_encrypt_key set_decrypt_key encrypt decrypt
The last four attributes are function pointers, of types
@code{nettle_set_key_func} and @code{nettle_crypt_func}. The first
argument to these functions is a @code{void *} pointer to a context
struct, which is of size @code{context_size}.
@end deftp

@deftypevr {Constant Struct} {struct nettle_cipher} nettle_aes128
@deftypevrx {Constant Struct} {struct nettle_cipher} nettle_aes192
@deftypevrx {Constant Struct} {struct nettle_cipher} nettle_aes256

@deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arcfour128
@deftypevrx {Constant Struct} {struct nettle_cipher} nettle_cast128

@deftypevrx {Constant Struct} {struct nettle_cipher} nettle_serpent128
@deftypevrx {Constant Struct} {struct nettle_cipher} nettle_serpent192
@deftypevrx {Constant Struct} {struct nettle_cipher} nettle_serpent256

@deftypevrx {Constant Struct} {struct nettle_cipher} nettle_twofish128
@deftypevrx {Constant Struct} {struct nettle_cipher} nettle_twofish192
@deftypevrx {Constant Struct} {struct nettle_cipher} nettle_twofish256

Niels Möller's avatar
Niels Möller committed
1097
1098
1099
1100
1101
@deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arctwo40;
@deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arctwo64;
@deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arctwo128;
@deftypevrx {Constant Struct} {struct nettle_cipher} nettle_arctwo_gutmann128;

Niels Möller's avatar
Niels Möller committed
1102
Nettle includes such structs for all the @emph{regular} ciphers, i.e.
Niels Möller's avatar
Niels Möller committed
1103
ones without weak keys or other oddities.
Niels Möller's avatar
Niels Möller committed
1104
1105
@end deftypevr

1106
@node Cipher modes, Keyed hash functions, Cipher functions, Reference
1107
@comment  node-name,  next,  previous,  up
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
@section Cipher modes

Cipher modes of of operation specifies the procedure to use when
encrypting a message that is larger than the cipher's block size. As
explained in @xref{Cipher functions}, splitting the message into blocks
and processing them independently with the block cipher (Electronic Code
Book mode, @acronym{ECB}) leaks information. Besides @acronym{ECB},
Nettle provides two other modes of operation: Cipher Block Chaining
(@acronym{CBC}) and Counter mode (@acronym{CTR}). @acronym{CBC} is
widely used, but there are a few subtle issues of information leakage.
@acronym{CTR} was standardized more recently, and is believed to be more
secure.

@subsection Cipher Block Chaining
1122

Niels Möller's avatar
Niels Möller committed
1123
When using @acronym{CBC} mode, plaintext blocks are not encrypted
Niels Möller's avatar
Niels Möller committed
1124
1125
independently of each other, like in Electronic Cook Book mode. Instead,
when encrypting a block in @acronym{CBC} mode, the previous ciphertext
1126
block is XORed with the plaintext before it is fed to the block cipher.
Niels Möller's avatar
Niels Möller committed
1127
1128
1129
1130
When encrypting the first block, a random block called an @dfn{IV}, or
Initialization Vector, is used as the ``previous ciphertext block''. The
IV should be chosen randomly, but it need not be kept secret, and can
even be transmitted in the clear together with the encrypted data.
1131

Niels Möller's avatar
Niels Möller committed
1132
1133
In symbols, if @code{E_k} is the encryption function of a block cipher,
and @code{IV} is the initialization vector, then @code{n} plaintext blocks
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
@code{M_1},@dots{} @code{M_n} are transformed into @code{n} ciphertext blocks
@code{C_1},@dots{} @code{C_n} as follows:

@example
C_1 = E_k(IV  XOR M_1)
C_2 = E_k(C_1 XOR M_2)

@dots{}

C_n = E_k(C_(n-1) XOR M_n)
@end example

1146
1147
1148
1149
Nettle's includes two functions for applying a block cipher in Cipher
Block Chaining (@acronym{CBC}) mode, one for encryption and one for
decryption. The functions uses @code{void *} to pass cipher contexts
around.
1150

1151
@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})
1152
1153
@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})

Niels Möller's avatar
Niels Möller committed
1154
Applies the encryption or decryption function @var{f} in @acronym{CBC}
1155
mode. The function @var{f} is of type
1156
1157
1158
1159
1160
1161
1162

@code{void f (void *@var{ctx}, unsigned @var{length}, uint8_t @var{dst},
const uint8_t *@var{src})},

@noindent and the @code{cbc_encrypt} and @code{cbc_decrypt} functions pass their
argument @var{ctx} on to @var{f}.
@end deftypefun
1163

1164
There are also some macros to help use these functions correctly.
1165

1166
@deffn Macro CBC_CTX (@var{context_type}, @var{block_size})
1167
1168
1169
1170
1171
1172
1173
Expands into
@example
@{
   context_type ctx;
   uint8_t iv[block_size];
@}
@end example
1174
1175
@end deffn

Niels Möller's avatar
Niels Möller committed
1176
It can be used to define a @acronym{CBC} context struct, either directly,
1177

1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
@example
struct CBC_CTX(struct aes_ctx, AES_BLOCK_SIZE) ctx;
@end example

or to give it a struct tag,

@example
struct aes_cbc_ctx CBC_CTX (struct aes_ctx, AES_BLOCK_SIZE);
@end example

1188
@deffn Macro CBC_SET_IV (@var{ctx}, @var{iv})
1189
First argument is a pointer to a context struct as defined by @code{CBC_CTX},
1190
1191
1192
and the second is a pointer to an Initialization Vector (IV) that is
copied into that context.
@end deffn
1193
1194
1195

@deffn Macro CBC_ENCRYPT (@var{ctx}, @var{f}, @var{length}, @var{dst}, @var{src})
@deffnx Macro CBC_DECRYPT (@var{ctx}, @var{f}, @var{length}, @var{dst}, @var{src})
1196
1197
1198
1199
1200
A simpler way to invoke @code{cbc_encrypt} and @code{cbc_decrypt}. The
first argument is a pointer to a context struct as defined by
@code{CBC_CTX}, and the second argument is an encryption or decryption
function following Nettle's conventions. The last three arguments define
the source and destination area for the operation.
1201
@end deffn
1202

1203
1204
1205
These macros use some tricks to make the compiler display a warning if
the types of @var{f} and @var{ctx} don't match, e.g. if you try to use
an @code{struct aes_ctx} context with the @code{des_encrypt} function.
1206

1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
@subsection Counter mode

Counter mode uses the block cipher as a keyed pseudo-random generator.
The output of the generator is XORed with the data to be encrypted. It
can be understood as a way to transform a block cipher to a stream
cipher.

The message is divided into @code{n} blocks @code{M_1},@dots{}
@code{M_n}, where @code{M_n} is of size @code{m} which may be smaller
than the block size. Except for the last block, all the message blocks
must be of size equal to the cipher's block size.

If @code{E_k} is the encryption function of a block cipher, @code{IV} is
the initialization vector, then the @code{n} plaintext blocks are
transformed into @code{n} ciphertext blocks @code{C_1},@dots{}
@code{C_n} as follows:

@example
C_1 = E_k(IC) XOR M_1
C_2 = E_k(IC + 1) XOR M_2

@dots{}

C_(n-1) = E_k(IC + n - 2) XOR M_(n-1)
C_n = E_k(IC + n - 1) [1..m] XOR M_n
@end example

The @acronym{IC} is the initial value for the counter, it plays a
similar role as the @acronym{IV} for @acronym{CBC}. When adding,
@code{IC + x}, @acronym{IC} is interpreted as an integer, in network
byte order. For the last block, @code{E_k(IC + n - 1) [1..m]} means that
the cipher output is truncated to @code{m} bytes.

@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})

Applies the encryption function @var{f} in @acronym{CTR} mode. Note that
for @acronym{CTR} mode, encryption and decryption is the same operation,
and hence @var{f} should always be the encryption function for the
underlying block cipher.

When a message is encrypted using a sequence of calls to
@code{ctr_crypt}, all but the last call @emph{must} use a length that is
a multiple of the block size.
@end deftypefun

Like for @acronym{CBC}, there are also a couple of helper macros.

@deffn Macro CTR_CTX (@var{context_type}, @var{block_size})
Expands into
@example
@{
   context_type ctx;
   uint8_t ctr[block_size];
@}
@end example
@end deffn

@deffn Macro CTR_SET_COUNTER (@var{ctx}, @var{iv})
First argument is a pointer to a context struct as defined by
@code{CTR_CTX}, and the second is a pointer to an initial counter that
is copied into that context.
@end deffn

@deffn Macro CTR_CRYPT (@var{ctx}, @var{f}, @var{length}, @var{dst}, @var{src})
A simpler way to invoke @code{ctr_crypt}. The first argument is a
pointer to a context struct as defined by @code{CTR_CTX}, and the second
argument is an encryption function following Nettle's conventions. The
last three arguments define the source and destination area for the
operation.
@end deffn

Niels Möller's avatar
Niels Möller committed
1278

1279
@node Keyed hash functions, Public-key algorithms, Cipher modes, Reference
Niels Möller's avatar
Niels Möller committed
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
@comment  node-name,  next,  previous,  up
@section Keyed Hash Functions

A @dfn{keyed hash function}, or @dfn{Message Authentication Code}
(@acronym{MAC}) is a function that takes a key and a message, and
produces fixed size @acronym{MAC}. It should be hard to compute a
message and a matching @acronym{MAC} without knowledge of the key. It
should also be hard to compute the key given only messages and
corresponding @acronym{MAC}s.

Keyed hash functions are useful primarily for message authentication,
1291
when Alice and Bob shares a secret: The sender, Alice, computes the
Niels Möller's avatar
Niels Möller committed
1292
1293
1294
@acronym{MAC} and attaches it to the message. The receiver, Bob, also computes
the @acronym{MAC} of the message, using the same key, and compares that
to Alice's value. If they match, Bob can be assured that
1295
the message has not been modified on its way from Alice.
Niels Möller's avatar
Niels Möller committed
1296
1297
1298
1299
1300
1301
1302
1303
1304

However, unlike digital signatures, this assurance is not transferable.
Bob can't show the message and the @acronym{MAC} to a third party and
prove that Alice sent that message. Not even if he gives away the key to
the third party. The reason is that the @emph{same} key is used on both
sides, and anyone knowing the key can create a correct @acronym{MAC} for
any message. If Bob believes that only he and Alice knows the key, and
he knows that he didn't attach a @acronym{MAC} to a particular message,
he knows it must be Alice who did it. However, the third party can't
1305
distinguish between a @acronym{MAC} created by Alice and one created by
Niels Möller's avatar
Niels Möller committed
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
Bob.

Keyed hash functions are typically a lot faster than digital signatures
as well.

@subsection @acronym{HMAC}

One can build keyed hash functions from ordinary hash functions. Older
constructions simply concatenate secret key and message and hashes that, but
such constructions have weaknesses. A better construction is
@acronym{HMAC}, described in @cite{RFC 2104}.

For an underlying hash function @code{H}, with digest size @code{l} and
internal block size @code{b}, @acronym{HMAC-H} is constructed as
Niels Möller's avatar
Niels Möller committed
1320
follows: From a given key @code{k}, two distinct subkeys @code{k_i} and
Niels Möller's avatar
Niels Möller committed
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
@code{k_o} are constructed, both of length @code{b}. The
@acronym{HMAC-H} of a message @code{m} is then computed as @code{H(k_o |
H(k_i | m))}, where @code{|} denotes string concatenation.

@acronym{HMAC} keys can be of any length, but it is recommended to use
keys of length @code{l}, the digest size of the underlying hash function
@code{H}. Keys that are longer than @code{b} are shortened to length
@code{l} by hashing with @code{H}, so arbitrarily long keys aren't
very useful. 

Nettle's @acronym{HMAC} functions are defined in @file{<nettle/hmac.h>}.
There are abstract functions that use a pointer to a @code{struct
nettle_hash} to represent the underlying hash function and @code{void
*} pointers that point to three different context structs for that hash
function. There are also concrete functions for @acronym{HMAC-MD5},
@acronym{HMAC-SHA1}, and @acronym{HMAC-SHA256}. First, the abstract
functions:

@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})
Initializes the three context structs from the key. The @var{outer} and
Niels Möller's avatar
Niels Möller committed
1341
@var{inner} contexts corresponds to the subkeys @code{k_o} and
Niels Möller's avatar
Niels Möller committed
1342
1343
1344
1345
@code{k_i}. @var{state} is used for hashing the message, and is
initialized as a copy of the @var{inner} context.
@end deftypefun

1346
@deftypefun void hmac_update (void *@var{state}, const struct nettle_hash *@var{H}, unsigned @var{length}, const uint8_t *@var{data})
Niels Möller's avatar
Niels Möller committed
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
This function is called zero or more times to process the message.
Actually, @code{hmac_update(state, H, length, data)} is equivalent to
@code{H->update(state, length, data)}, so if you wish you can use the
ordinary update function of the underlying hash function instead.
@end deftypefun

@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})
Extracts the @acronym{MAC} of the message, writing it to @var{digest}.
@var{outer} and @var{inner} are not modified. @var{length} is usually
equal to @code{H->digest_size}, but if you provide a smaller value,
only the first @var{length} octets of the @acronym{MAC} are written.

This function also resets the @var{state} context so that you can start
over processing a new message (with the same key).
@end deftypefun

Like for @acronym{CBC}, there are some macros to help use these
functions correctly.

@deffn Macro HMAC_CTX (@var{type})
Expands into
@example
@{
   type outer;
   type inner;
   type state;
@}
@end example
@end deffn

Niels Möller's avatar
Niels Möller committed
1377
It can be used to define a @acronym{HMAC} context struct, either
Niels Möller's avatar
Niels Möller committed
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
directly,

@example
struct HMAC_CTX(struct md5_ctx) ctx;
@end example

or to give it a struct tag,

@example
struct hmac_md5_ctx HMAC_CTX (struct md5_ctx);
@end example

@deffn Macro HMAC_SET_KEY (@var{ctx}, @var{H}, @var{length}, @var{key})
@var{ctx} is a pointer to a context struct as defined by
@code{HMAC_CTX}, @var{H} is a pointer to a @code{const struct
nettle_hash} describing the underlying hash function (so it must match
the type of the components of @var{ctx}). The last two arguments specify
the secret key.
@end deffn

@deffn Macro HMAC_DIGEST (@var{ctx}, @var{H}, @var{length}, @var{digest})
@var{ctx} is a pointer to a context struct as defined by
@code{HMAC_CTX}, @var{H} is a pointer to a @code{const struct
nettle_hash} describing the underlying hash function. The last two
arguments specify where the digest is written.
@end deffn

Niels Möller's avatar
Niels Möller committed
1405
1406
1407
Note that there is no @code{HMAC_UPDATE} macro; simply call
@code{hmac_update} function directly, or the update function of the
underlying hash function.
Niels Möller's avatar
Niels Möller committed
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479

@subsection Concrete @acronym{HMAC} functions
Now we come to the specialized @acronym{HMAC} functions, which are
easier to use than the general @acronym{HMAC} functions.

@subsubsection @acronym{HMAC-MD5}

@deftp {Context struct} {struct hmac_md5_ctx}
@end deftp

@deftypefun void hmac_md5_set_key (struct hmac_md5_ctx *@var{ctx}, unsigned @var{key_length}, const uint8_t *@var{key})
Initializes the context with the key.
@end deftypefun

@deftypefun void hmac_md5_update (struct hmac_md5_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
Process some more data.
@end deftypefun

@deftypefun void hmac_md5_digest (struct hmac_md5_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
Extracts the @acronym{MAC}, writing it to @var{digest}. @var{length} may be smaller than
@code{MD5_DIGEST_SIZE}, in which case only the first @var{length}
octets of the @acronym{MAC} are written.

This function also resets the context for processing new messages, with
the same key.
@end deftypefun

@subsubsection @acronym{HMAC-SHA1}

@deftp {Context struct} {struct hmac_sha1_ctx}
@end deftp

@deftypefun void hmac_sha1_set_key (struct hmac_sha1_ctx *@var{ctx}, unsigned @var{key_length}, const uint8_t *@var{key})
Initializes the context with the key.
@end deftypefun

@deftypefun void hmac_sha1_update (struct hmac_sha1_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
Process some more data.
@end deftypefun

@deftypefun void hmac_sha1_digest (struct hmac_sha1_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
Extracts the @acronym{MAC}, writing it to @var{digest}. @var{length} may be smaller than
@code{SHA1_DIGEST_SIZE}, in which case only the first @var{length}
octets of the @acronym{MAC} are written.

This function also resets the context for processing new messages, with
the same key.
@end deftypefun


@subsubsection @acronym{HMAC-SHA256}

@deftp {Context struct} {struct hmac_sha256_ctx}
@end deftp

@deftypefun void hmac_sha256_set_key (struct hmac_sha256_ctx *@var{ctx}, unsigned @var{key_length}, const uint8_t *@var{key})
Initializes the context with the key.
@end deftypefun

@deftypefun void hmac_sha256_update (struct hmac_sha256_ctx *@var{ctx}, unsigned @var{length}, const uint8_t *@var{data})
Process some more data.
@end deftypefun

@deftypefun void hmac_sha256_digest (struct hmac_sha256_ctx *@var{ctx}, unsigned @var{length}, uint8_t *@var{digest})
Extracts the @acronym{MAC}, writing it to @var{digest}. @var{length} may be smaller than
@code{SHA256_DIGEST_SIZE}, in which case only the first @var{length}
octets of the @acronym{MAC} are written.

This function also resets the context for processing new messages, with
the same key.
@end deftypefun

1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
@node Public-key algorithms, Randomness, Keyed hash functions, Reference
@comment  node-name,  next,  previous,  up
@section Public-key algorithms

Nettle uses @acronym{GMP}, the GNU bignum library, for all calculations
with large numbers. In order to use the public-key features of Nettle,
you must install @acronym{GMP}, at least version 3.0, before compiling
Nettle, and you need to link your programs with @code{-lgmp}.

The concept of @dfn{Public-key} encryption and digital signatures was
discovered by Whitfield Diffie and Martin E. Hellman and described in a
1491
paper 1976. In traditional, ``symmetric'', cryptography, sender and
1492
1493
1494
1495
1496
1497
1498
1499
1500
receiver share the same keys, and these keys must be distributed in a
secure way. And if there are many users or entities that need to
communicate, each @emph{pair} needs a shared secret key known by nobody
else.

Public-key cryptography uses trapdoor one-way functions. A
@dfn{one-way function} is a function @code{F} such that it is easy to
compute the value @code{F(x)} for any @code{x}, but given a value
@code{y}, it is hard to compute a corresponding @code{x} such that
1501
@code{y = F(x)}. Two examples are cryptographic hash functions, and
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
exponentiation in certain groups.

A @dfn{trapdoor one-way function} is a function @code{F} that is
one-way, unless one knows some secret information about @code{F}. If one
knows the secret, it is easy to compute both @code{F} and it's inverse.
If this sounds strange, look at the @acronym{RSA} example below.

Two important uses for one-way functions with trapdoors are public-key
encryption, and digital signatures. Of these, I won't say more about
public-key encryption, as that isn't yet supported by Nettle. So the
rest of this chapter is about digital signatures.

To use a digital signature algorithm, one must first create a
Niels Möller's avatar
Niels Möller committed
1515
@dfn{key-pair}: A public key and a corresponding private key. The private
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
key is used to sign messages, while the public key is used for verifying
that that signatures and messages match. Some care must be taken when
distributing the public key; it need not be kept secret, but if a bad
guy is able to replace it (in transit, or in some user's list of known
public keys), bad things may happen.

There are two operations one can do with the keys. The signature
operation takes a message and a private key, and creates a signature for
the message. A signature is some string of bits, usually at most a few
thousand bits or a few hundred octets. Unlike paper-and-ink signatures,
the digital signature depends on the message, so one can't cut it out of
context and glue it to a different message.

The verification operation takes a public key, a message, and a string
that is claimed to be a signature on the message, and returns true or
false. If it returns true, that means that the three input values
matched, and the verifier can be sure that someone went through with the
1533
signature operation on that very message, and that the ``someone'' also
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
knows the private key corresponding to the public key.

The desired properties of a digital signature algorithm are as follows:
Given the public key and pairs of messages and valid signatures on them,
it should be hard to compute the private key, and it should also be hard
to create a new message and signature that is accepted by the
verification operation.

Besides signing meaningful messages, digital signatures can be used for
authorization. A server can be configured with a public key, such that
any client that connects to the service is given a random nonce message.
If the server gets a reply with a correct signature matching the nonce
message and the configured public key, the client is granted access. So
1547
the configuration of the server can be understood as ``grant access to
1548
whoever knows the private key corresponding to this particular public
1549
key, and to no others''.
1550

Niels Möller's avatar
Niels Möller committed
1551
1552
1553
1554
1555
1556
1557
1558

@menu
* RSA::                         The RSA public key algorithm.
* DSA::                         The DSA digital signature algorithm.
@end menu

@node RSA, DSA, Public-key algorithms, Public-key algorithms
@comment  node-name,  next,  previous,  up
1559
1560
@subsection @acronym{RSA}

Niels Möller's avatar
Niels Möller committed
1561
1562
1563
The @acronym{RSA} algorithm was the first practical digital signature
algorithm that was constructed. It was described 1978 in a paper by
Ronald Rivest, Adi Shamir and L.M. Adleman, and the technique was also
1564
1565
patented in the @acronym{USA} in 1983. The patent expired on September 20, 2000, and since
that day, @acronym{RSA} can be used freely, even in the @acronym{USA}.
1566

1567
It's remarkably simple to describe the trapdoor function behind
1568
@acronym{RSA}. The ``one-way''-function used is
1569
1570
1571
1572
1573
1574
1575

@example
F(x) = x^e mod n
@end example

I.e. raise x to the @code{e}:th power, while discarding all multiples of
@code{n}. The pair of numbers @code{n} and @code{e} is the public key.
1576
@code{e} can be quite small, even @code{e = 3} has been used, although
1577
1578
1579
1580
1581
1582
1583
slightly larger numbers are recommended. @code{n} should be about 1000
bits or larger.

If @code{n} is large enough, and properly chosen, the inverse of F,
the computation of @code{e}:th roots modulo @code{n}, is very difficult.
But, where's the trapdoor?

Niels Möller's avatar
Niels Möller committed
1584
Let's first look at how @acronym{RSA} key-pairs are generated. First
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
@code{n} is chosen as the product of two large prime numbers @code{p}
and @code{q} of roughly the same size (so if @code{n} is 1000 bits,
@code{p} and @code{q} are about 500 bits each). One also computes the
number @code{phi = (p-1)(q-1)}, in mathematical speak, phi is the order
of the multiplicative group of integers modulo n.

Next, @code{e} is chosen. It must have no factors in common with phi (in
particular, it must be odd), but can otherwise be chosen more or less
randomly. @code{e = 65537} is a popular choice, because it makes raising
to the @code{e}:th power particularly efficient, and being prime, it
usually has no factors common with @code{phi}.

Finally, a number @code{d}, @code{d < n} is computed such that @code{e d
mod phi = 1}. It can be shown that such a number exists (this is why
@code{e} and @code{phi} must have no common factors), and that for all x,

@example
(x^e)^d mod n = x^(ed) mod n = (x^d)^e mod n = x
@end example

Using Euclid's algorithm, @code{d} can be computed quite easily from
@code{phi} and @code{e}. But it is still hard to get @code{d} without
knowing @code{phi}, which depends on the factorization of @code{n}.

So @code{d} is the trapdoor, if we know @code{d} and @code{y = F(x)}, we can
recover x as @code{y^d mod n}. @code{d} is also the private half of
Niels Möller's avatar
Niels Möller committed
1611
the @acronym{RSA} key-pair.
1612
1613
1614
1615
1616

The most common signature operation for @acronym{RSA} is defined in
@cite{PKCS#1}, a specification by RSA Laboratories. The message to be
signed is first hashed using a cryptographic hash function, e.g.
@acronym{MD5} or @acronym{SHA1}. Next, some padding, the @acronym{ASN.1}
1617
``Algorithm Identifier'' for the hash function, and the message digest
1618
1619
itself, are concatenated and converted to a number @code{x}. The
signature is computed from @code{x} and the private key as @code{s = x^d
1620
mod n}@footnote{Actually, the computation is not done like this, it is
Niels Möller's avatar
Niels Möller committed
1621
done more efficiently using @code{p}, @code{q} and the Chinese remainder
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
theorem (@acronym{CRT}). But the result is the same.}. The signature, @code{s} is a
number of about the same size of @code{n}, and it usually encoded as a
sequence of octets, most significant octet first.

The verification operation is straight-forward, @code{x} is computed
from the message in the same way as above. Then @code{s^e mod n} is
computed, the operation returns true if and only if the result equals
@code{x}.

@subsection Nettle's @acronym{RSA} support

Nettle represents @acronym{RSA} keys using two structures that contain
large numbers (of type @code{mpz_t}).

@deftp {Context struct} {rsa_public_key} size n e
@code{size} is the size, in octets, of the modulo, and is used internally.
@code{n} and @code{e} is the public key.
@end deftp

@deftp {Context struct} {rsa_private_key} size d p q a b c
@code{size} is the size, in octets, of the modulo, and is used internally.
@code{d} is the secret exponent, but it is not actually used when
signing. Instead, the factors @code{p} and @code{q}, and the parameters
@code{a}, @code{b} and @code{c} are used. They are computed from @code{p},
@code{q} and @code{d} such that @code{a e mod (p - 1) = 1, b e mod (q -
1) = 1, c q mod p= 1}.
@end deftp

Before use, these structs must be initialized by calling one of

Niels Möller's avatar
Niels Möller committed
1652
1653
@deftypefun void rsa_public_key_init (struct rsa_public_key *@var{pub})
@deftypefunx void rsa_private_key_init (struct rsa_private_key *@var{key})
1654
1655
1656
1657
1658
1659
Calls @code{mpz_init} on all numbers in the key struct.
@end deftypefun

and when finished with them, the space for the numbers must be
deallocated by calling one of

Niels Möller's avatar
Niels Möller committed
1660
1661
@deftypefun void rsa_public_key_clear (struct rsa_public_key *@var{pub})
@deftypefunx void rsa_private_key_clear (struct rsa_private_key *@var{key})
1662
1663
1664
Calls @code{mpz_clear} on all numbers in the key struct.
@end deftypefun

1665
1666
In general, Nettle's @acronym{RSA} functions deviates from Nettle's ``no
memory allocation''-policy. Space for all the numbers, both in the key structs
1667
above, and temporaries, are allocated dynamically. For information on how
1668
1669
to customize allocation, see
@xref{Custom Allocation,,GMP Allocation,gmp, GMP Manual}.
Niels Möller's avatar
Niels Möller committed
1670

1671
When you have assigned values to the attributes of a key, you must call
Niels Möller's avatar
Niels Möller committed
1672

Niels Möller's avatar
Niels Möller committed
1673
1674
@deftypefun int rsa_public_key_prepare (struct rsa_public_key *@var{pub})
@deftypefunx int rsa_private_key_prepare (struct rsa_private_key *@var{key})
1675
Computes the octet size of the key (stored in the @code{size} attribute,
1676
and may also do other basic sanity checks. Returns one if successful, or
1677
1678
1679
1680
1681
1682
zero if the key can't be used, for instance if the modulo is smaller
than the minimum size specified by PKCS#1.
@end deftypefun

Before signing or verifying a message, you first hash it with the
appropriate hash function. You pass the hash function's context struct
Niels Möller's avatar
Niels Möller committed
1683
1684
1685
to the @acronym{RSA} signature function, and it will extract the message
digest and do the rest of the work. There are also alternative functions
that take the @acronym{MD5} or @acronym{SHA1} hash digest as argument.
1686
1687
1688

Creation and verification of signatures is done with the following functions:

Niels Möller's avatar
Niels Möller committed
1689
1690
@deftypefun void rsa_md5_sign (const struct rsa_private_key *@var{key}, struct md5_ctx *@var{hash}, mpz_t @var{signature})
@deftypefunx void rsa_sha1_sign (const struct rsa_private_key *@var{key}, struct sha1_ctx *@var{hash}, mpz_t @var{signature})
1691
1692
1693
1694
1695
The signature is stored in @var{signature} (which must have been
@code{mpz_init}:ed earlier). The hash context is reset so that it can be
used for new messages.
@end deftypefun

Niels Möller's avatar
Niels Möller committed
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
@deftypefun void rsa_md5_sign_digest (const struct rsa_private_key *@var{key}, const uint8_t *@var{digest}, mpz_t @var{signature})
@deftypefunx void rsa_sha1_sign_digest (const struct rsa_private_key *@var{key}, const uint8_t *@var{digest}, mpz_t @var{signature});
Creates a signature from the given hash digest. @var{digest} should
point to a digest of size @code{MD5_DIGEST_SIZE} or
@code{SHA1_DIGEST_SIZE}, respectively. The signature is stored in
@var{signature} (which must have been @code{mpz_init}:ed earlier)
@end deftypefun

@deftypefun int rsa_md5_verify (const struct rsa_public_key *@var{key}, struct md5_ctx *@var{hash}, const mpz_t @var{signature})
@deftypefunx int rsa_sha1_verify (const struct rsa_public_key *@var{key}, struct sha1_ctx *@var{hash}, const mpz_t @var{signature})
1706
1707
1708
1709
Returns 1 if the signature is valid, or 0 if it isn't. In either case,
the hash context is reset so that it can be used for new messages.
@end deftypefun

Niels Möller's avatar
Niels Möller committed
1710
@deftypefun int rsa_md5_verify_digest (const struct rsa_public_key *@var{key}, const uint8_t *@var{digest}, const mpz_t @var{signature})
Niels Möller's avatar
Niels Möller committed
1711
@deftypefunx int rsa_sha1_verify_digest (const struct rsa_public_key *@var{key}, const uint8_t *@var{digest}, const mpz_t @var{signature})
Niels Möller's avatar
Niels Möller committed
1712
1713
1714
1715
1716
Returns 1 if the signature is valid, or 0 if it isn't. @var{digest} should
point to a digest of size @code{MD5_DIGEST_SIZE} or
@code{SHA1_DIGEST_SIZE}, respectively.
@end deftypefun

1717
If you need to use the @acronym{RSA} trapdoor, the private key, in a way
1718
that isn't supported by the above functions Nettle also includes a
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
function that computes @code{x^d mod n} and nothing more, using the
@acronym{CRT} optimization.

@deftypefun void rsa_compute_root (struct rsa_private_key *@var{key}, mpz_t @var{x}, const mpz_t @var{m})
Computes @code{x = m^d}, efficiently.
@end deftypefun

At last, how do you create new keys?

@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});
There are lots of parameters. @var{pub} and @var{key} is where the
resulting key pair is stored. The structs should be initialized, but you
Niels Möller's avatar
Niels Möller committed
1731
1732
don't need to call @code{rsa_public_key_prepare} or
@code{rsa_private_key_prepare} after key generation.
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753

@var{random_ctx} and @var{random} is a randomness generator.
@code{random(random_ctx, length, dst)} should generate @code{length}
random octets and store them at @code{dst}. For advice, see
@xref{Randomness}.

@var{progress} and @var{progress_ctx} can be used to get callbacks
during the key generation process, in order to uphold an illusion of
progress. @var{progress} can be NULL, in that case there are no
callbacks.

@var{size_n} is the desired size of the modulo, in bits. If @var{size_e}
is non-zero, it is the desired size of the public exponent and a random
exponent of that size is selected. But if @var{e_size} is zero, it is
assumed that the caller has already chosen a value for @code{e}, and
stored it in @var{pub}.
Returns 1 on success, and 0 on failure. The function can fail for
example if if @var{n_size} is too small, or if @var{e_size} is zero and
@code{pub->e} is an even number.
@end deftypefun

Niels Möller's avatar
Niels Möller committed
1754
1755
1756
1757
1758
1759
@node DSA,  , RSA, Public-key algorithms
@comment  node-name,  next,  previous,  up
@subsection Nettle's @acronym{DSA} support

The @acronym{DSA} digital signature algorithm is more complex than
@acronym{RSA}. It was specified during the early 1990s, and in 1994 NIST
Niels Möller's avatar
Niels Möller committed
1760
1761
1762
published @acronym{FIPS} 186 which is the authoritative specification.
Sometimes @acronym{DSA} is referred to using the acronym @acronym{DSS},
for Digital Signature Standard.
Niels Möller's avatar
Niels Möller committed
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946

For @acronym{DSA}, the underlying mathematical problem is the
computation of discreet logarithms. The public key consists of a large
prime @code{p}, a small prime @code{q} which is a factor of @code{p-1},
a number @code{g} which generates a subgroup of order @code{q} modulo
@code{p}, and an element @code{y} in that subgroup.

The size of @code{q} is fixed to 160 bits, to match with the
@acronym{SHA1} hash algorithm which is used in @acronym{DSA}. The size
of @code{q} is in principle unlimited, but the standard specifies only
nine specific sizes: @code{512 + l*64}, where @code{l} is between 0 and
8. Thus, the maximum size of @code{p} is 1024 bits, at that is also the
recommended size.

The subgroup requirement means that if you compute 

@example
g^t mod p
@end example

for all possible integers @code{t}, you will get precisely @code{q}
distinct values.

The private key is a secret exponent @code{x}, such that

@example
g^x = y mod p
@end example

In mathematical speak, @code{x} is the @dfn{discrete logarithm} of
@code{y} mod @code{p}, with respect to the generator @code{d}. The size
of @code{x} will also be about 160 bits.

The signature generation algorithm is randomized; in order to create a
@acronym{DSA} signature, you need a good source for random numbers
(@pxref{Randomness}).

To create a signature, one starts with the hash digest of the message,
@code{h}, which is a 160 bit number, and a random number @code{k,
0<k<q}, also 160 bits. Next, one computes 

@example
r = (g^k mod p) mod q
s = k^-1 (h + x r) mod q
@end example

The signature is the pair @code{(r, s)}, two 160 bit numbers. Note the
two different mod operations when computing @code{r}, and the use of the
secret exponent @code{x}.

To verify a signature, one first checks that @code{0 < r,s < q}, and
then one computes backwards,

@example
w = s^-1 mod q
v = (g^(w h) y^(w r) mod p) mod q
@end example

The signature is valid if @code{v = r}. This works out because @code{w =
s^-1 mod q = k (h + x r)^-1 mod q}, so that

@example
g^(w h) y^(w r) = g^(w h) (g^x)^(w r) = g^(w (h + x r)) = g^k 
@end example

When reducing mod @code{q} this yields @code{r}. Note that when
verifying a signature, we don't know either @code{k} or @code{x}: those
numbers are secret.

If you can choose between @acronym{RSA} and @acronym{DSA}, which one is
best? Both are believed to be secure. @acronym{DSA} gained popularity
in the late 1990s, as a patent free alternative to @acronym{RSA}. Now
that the @acronym{RSA} patents have expired, there's no compelling
reason to want to use @acronym{DSA}.

@acronym{DSA} signatures are smaller than @acronym{RSA} signatures,
which is important for some specialized applications.

From a practical point of view, @acronym{DSA}'s need for a good
randomness source is a serious disadvantage. If you ever use the same
@code{k} (and @code{r}) for two different message, you leak your private
key.

@subsection Nettle's @acronym{DSA} support

Like for @acronym{RSA}, Nettle represents @acronym{DSA} keys using two
structures, containing values of type @code{mpz_t}. For information on
how to customize allocation, see @xref{Custom Allocation,,GMP
Allocation,gmp, GMP Manual}.

Most of the @acronym{DSA} functions are very similar to the
corresponding @acronym{RSA} functions, but there are a few differences
pointed out below. For a start, there are no functions corresponding to
@code{rsa_public_key_prepare} and @code{rsa_private_key_prepare}.

@deftp {Context struct} {dsa_public_key} p q g y
The public parameters described above.
@end deftp

@deftp {Context struct} {dsa_private_key} x
The private key @code{x}.
@end deftp

Before use, these structs must be initialized by calling one of

@deftypefun void dsa_public_key_init (struct dsa_public_key *@var{pub})
@deftypefunx void dsa_private_key_init (struct dsa_private_key *@var{key})
Calls @code{mpz_init} on all numbers in the key struct.
@end deftypefun

When finished with them, the space for the numbers must be
deallocated by calling one of

@deftypefun void dsa_public_key_clear (struct dsa_public_key *@var{pub})
@deftypefunx void dsa_private_key_clear (struct dsa_private_key *@var{key})
Calls @code{mpz_clear} on all numbers in the key struct.
@end deftypefun

Signatures are represented using the structure below, and need to be
initialized and cleared in the same way as the key structs.

@deftp {Context struct} {dsa_signature} r s
@end deftp

@deftypefun void dsa_signature_init (struct dsa_signature *@var{signature})
@deftypefunx void dsa_signature_clear (struct dsa_signature *@var{signature})
You must call @code{dsa_signature_init} before creating or using a
signature, and call @code{dsa_signature_clear} when you are finished
with it.
@end deftypefun

For signing, you need to provide both the public and the private key
(unlike @acronym{RSA}, where the private key struct includes all
information needed for signing), and a source for random numbers.
Signatures always use the @acronym{SHA1} hash function.

@deftypefun void dsa_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})
@deftypefunx void dsa_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})
Creates a signature from the given hash context or digest.
@var{random_ctx} and @var{random} is a randomness generator.
@code{random(random_ctx, length, dst)} should generate @code{length}
random octets and store them at @code{dst}. For advice, see
@xref{Randomness}.
@end deftypefun

Verifying signatures is a little easier, since no randomness generator is
needed. The functions are

@deftypefun int dsa_verify (const struct dsa_public_key *@var{key}, struct sha1_ctx *@var{hash}, const struct dsa_signature *@var{signature})
@deftypefunx int dsa_verify_digest (const struct dsa_public_key *@var{key}, const uint8_t *@var{digest}, const struct dsa_signature *@var{signature})
Verifies a signa