Draft manual for the Nettle library. This manual corresponds to version 1.0.

Copyright 2001 Niels Möller

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.

This document describes the nettle low-level cryptographic library. You can use the library directly from your C-programs, or (recommended) write or use an object-oriented wrapper for your favourite language or application.

This manual coresponds to version 1.0 of the library.

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.

And as the requirements of applications differ in subtle and not so 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 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 interfaces on top of Nettle, and share the code, testcases, benchmarks, 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.

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.

Copyright
*********

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.

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

AES
     The implementation of the AES cipher (also known as rijndael) is written by Rafael Sevilla. Released under the LGPL.

ARCFOUR
     The implementation of the ARCFOUR (also known as RC4) cipher is written by Niels Möller. Released under the LGPL.

BLOWFISH
     The implementation of the BLOWFISH cipher is written by Werner Koch, copyright owned by the Free Software Foundation. Also hacked by Ray Dassen and Niels Möller. Released under the GPL.

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

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

MD5
     The implementation of the MD5 message digest is written by Colin Plumb. It has been hacked some more by Andrew Kuchling and Niels Möller. Released into the public domain.

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 Nettle by Niels Möller. Released under the GPL.

SHA1
     The implementation of the SHA1 message digest is written by Peter Gutmann, and hacked some more by Andrew Kuchling and Niels Möller. Released into the public domain.

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

Conventions
***********

For each supported algorithm, there is an include file that defines a context struct, a few constants, and declares functions for operating on the context. The context struct encapsulates all information needed by the algorithm, and it can be copied or moved in memory with no unexpected effects.

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.

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 foo, the struct tag for the context struct is foo_ctx, constants and functions uses prefixes like FOO_BLOCK_SIZE (a constant) and foo_set_key (a function).

In all functions, strings are represented with an explicit length, of type unsigned, and a pointer of type uint8_t * or 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, but they must not overlap in any other way.

Example
*******

A simple example program that reads a file from standard in and writes its SHA1 checksum on stdout should give the flavour of Nettle.

     /* FIXME: This code is untested. */
     #include <stdio.h>
     #include <stdlib.h>

     #include <nettle/sha.h>

     #define BUF_SIZE 1000

     static void
     display_hex(unsigned length, uint8_t *data)
     {
       static const char digits[16] = "0123456789abcdef";
       unsigned i;

       for (i = 0; i<length; i++)
       {
         uint8_t byte = data[i];
         printf("%c%c ", digits[(byte / 16) & 0xf], digits[byte & 0xf]);
       }
     }

     int
     main(int argc, char **argv)
     {
       struct sha1_ctx ctx;
       uint8_t buffer[BUF_SIZE];
       uint8_t digest[SHA1_DIGEST_SIZE];

       sha1_init(&ctx);
       for (;;)
       {
         int done = fread(buffer, 1, sizeof(buffer), stdin);
         if (done <= 0)
           break;
         sha1_update(&ctx, done, buf);
       }
       if (ferror(stdin))
         return EXIT_FAILURE;

       sha1_digest(&ctx, SHA1_DIGEST_SIZE, digest);

       display_hex(SHA1_DIGEST_SIZE, digest);
       return EXIT_SUCCESS;
     }

Reference
*********

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

Hash functions
==============

A cryptographic 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 H should have the following properties:

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

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

Hash functions are useful as building blocks for digital signatures, message authentication codes, pseudo random generators, association of unique id:s to documents, and many other things.

MD5
---

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

 -- Context struct: struct md5_ctx

 -- Constant: MD5_DIGEST_SIZE
     The size of an MD5 digest, i.e. 16.

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

 -- Function: void md5_init (struct md5_ctx *CTX)
     Initialize the MD5 state.

 -- Function: void md5_update (struct md5_ctx *CTX, unsigned LENGTH, const uint8_t *DATA)
     Hash some more data.

 -- Function: void md5_digest (struct md5_ctx *CTX, unsigned LENGTH, uint8_t *DIGEST)
     Performs final processing and extracts the message digest, writing it to DIGEST. LENGTH may be smaller than MD5_DIGEST_SIZE, in which case only the first LENGTH octets of the digest are written.

     This function also resets the context in the same way as md5_init.

The normal way to use MD5 is to call the functions in order: First md5_init, then md5_update zero or more times, and finally md5_digest. After md5_digest, the context is reset to its initial state, so you can start over calling md5_update to hash new data.

To start over, you can call md5_init at any time.

SHA1
----

SHA1 is a hash function specified by NIST (The U.S. National Institute for Standards and Technology). It outputs hash values of 160 bits, or 20 octets. Nettle defines SHA1 in <nettle/sha.h>.

The functions are analogous to the MD5 ones.

 -- Context struct: struct sha1_ctx

 -- Constant: SHA1_DIGEST_SIZE
     The size of an SHA1 digest, i.e. 20.

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

 -- Function: void sha1_init (struct sha1_ctx *CTX)
     Initialize the SHA1 state.

 -- Function: void sha1_update (struct sha1_ctx *CTX, unsigned LENGTH, const uint8_t *DATA)
     Hash some more data.

 -- Function: void sha1_digest (struct sha1_ctx *CTX, unsigned LENGTH, uint8_t *DIGEST)
     Performs final processing and extracts the message digest, writing it to DIGEST. LENGTH may be smaller than SHA1_DIGEST_SIZE, in which case only the first LENGTH octets of the digest are written.

     This function also resets the context in the same way as sha1_init.

SHA256
------

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

The functions are analogous to the MD5 ones.

 -- Context struct: struct sha256_ctx

 -- Constant: SHA256_DIGEST_SIZE
     The size of an SHA256 digest, i.e. 20.

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

 -- Function: void sha256_init (struct sha256_ctx *CTX)
     Initialize the SHA256 state.

 -- Function: void sha256_update (struct sha256_ctx *CTX, unsigned LENGTH, const uint8_t *DATA)
     Hash some more data.

 -- Function: void sha256_digest (struct sha256_ctx *CTX, unsigned LENGTH, uint8_t *DIGEST)
     Performs final processing and extracts the message digest, writing it to DIGEST. LENGTH may be smaller than SHA256_DIGEST_SIZE, in which case only the first LENGTH octets of the digest are written.

     This function also resets the context in the same way as sha256_init.

struct nettle_hash
------------------

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

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

 -- Constant Struct: struct nettle_cipher nettle_md5
 -- Constant Struct: struct nettle_cipher nettle_sha1
 -- Constant Struct: struct nettle_cipher nettle_sha256

     These are all the hash functions that Nettle implements.

Cipher functions
================

A cipher is a function that takes a message or plaintext and a secret key and transforms it to a ciphertext. Given only the ciphertext, but not the key, it should be hard to find the cleartext. Given matching pairs of plaintext and ciphertext, it should 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 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 ECB, Electronic Code Book mode. However, using ECB is usually a bad idea. For a start, plaintext blocks that are equal are transformed to ciphertext blocks that are equal; that leaks information about the plaintext. Usually you should apply the cipher is some feedback mode, CBC (Cipher Block Chaining) being one of the most popular. See Cipher Block Chaining, for information on how to apply CBC with Nettle.

A stream cipher can be used for messages of arbitrary length; a typical stream cipher is a keyed pseudorandom generator. To encrypt a plaintext message of N octets, you key the generator, generate N octets of pseudorandom data, and XOR it with the plaintext. To decrypt, regenerate the same stream using the key, XOR it to the ciphertext, and the plaintext is recovered.

Caution: The first rule for this kind of cipher is the same as for a One Time Pad: 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 receive an encrypted message. You apply the key, and get a cleartext message that makes sense to you. Can you then be sure that it really was your friend that wrote the message you're reading? The anser is no. For 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 wrote. If you are using a block cipher in 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.

It is recommended to always use an authentication mechanism in addition to encrypting the messages. Popular choices are Message Authetication Codes like HMAC-SHA1 see Keyed hash functions, or digital signatures like rsa.

Some ciphers have so called "weak keys", keys that results in 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 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.

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 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.

AES
---

AES is a quite new block cipher, specified by NIST as a replacement for the older DES standard. The standarad is the result of a competition between cipher designers. The winning design, also known as RIJNDAEL, was constructed by Joan Daemen and Vincent Rijnmen.

Like all the AES candidates, the winning design uses a block size of 128 bits, or 16 octets, and variable keysize, 128, 192 and 256 bits (16, 24 and 32 octets) being the allowed key sizes. It does not have any weak keys. Nettle defines AES in <nettle/aes.h>.

 -- Context struct: struct aes_ctx

 -- Constant: AES_BLOCK_SIZE
     The AES blocksize, 16

 -- Constant: AES_MIN_KEY_SIZE

 -- Constant: AES_MAX_KEY_SIZE

 -- Constant: AES_KEY_SIZE
     Default AES key size, 32

 -- Function: void aes_set_key (struct aes_ctx *CTX, unsigned LENGTH, const uint8_t *KEY)
     Initialize the cipher. The same function is used for both encryption and decryption.

 -- Function: void aes_encrypt (struct aes_ctx *CTX, unsigned LENGTH, const uint8_t *DST, uint8_t *SRC)
     Encryption function. LENGTH must be an integral multiple of the block size. If it is more than one block, the data is processed in ECB mode. src and dst may be equal, but they must not overlap in any other way.

 -- Function: void aes_decrypt (struct aes_ctx *CTX, unsigned LENGTH, const uint8_t *DST, uint8_t *SRC)
     Analogous to aes_encrypt

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 "secret:1", "secret:2", .... If you have keys that don't look like random bit strings, and you want to use ARCFOUR, always hash the key before feeding it to ARCFOUR. For example

     /* A more robust key setup function for ARCFOUR */
     void
     my_arcfour_set_key(struct arcfour_ctx *ctx,
                        unsigned length, const uint8_t *key)
     {
       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);
     }

Nettle defines ARCFOUR in <nettle/arcfour.h>.

 -- Context struct: struct arcfour_ctx

 -- Constant: ARCFOUR_MIN_KEY_SIZE
     Minimum key size, 1

 -- Constant: ARCFOUR_MAX_KEY_SIZE
     Maximum key size, 256

 -- Constant: ARCFOUR_KEY_SIZE
     Default ARCFOUR key size, 16

 -- Function: void arcfour_set_key (struct arcfour_ctx *CTX, unsigned LENGTH, const uint8_t *KEY)
     Initialize the cipher. The same function is used for both encryption and decryption.

 -- Function: void arcfour_crypt (struct arcfour_ctx *CTX, unsigned LENGTH, const uint8_t *KEY)
     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 arcfour_crypt only once with all the data.

CAST128
-------

CAST-128 is a block cipher, specified in 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 <nettle/cast128.h>.

 -- Context struct: struct cast128_ctx

 -- Constant: CAST128_BLOCK_SIZE
     The CAST128 blocksize, 8

 -- Constant: CAST128_MIN_KEY_SIZE
     Minumim CAST128 key size, 5

 -- Constant: CAST128_MAX_KEY_SIZE
     Maximum CAST128 key size, 16

 -- Constant: CAST128_KEY_SIZE
     Default CAST128 key size, 16

 -- Function: void cast128_set_key (struct cast128_ctx *CTX, unsigned LENGTH, const uint8_t *KEY)
     Initialize the cipher. The same function is used for both encryption and decryption.

 -- Function: void cast128_encrypt (struct cast128_ctx *CTX, unsigned LENGTH, const uint8_t *DST, uint8_t *SRC)
     Encryption function. LENGTH must be an integral multiple of the block size. If it is more than one block, the data is processed in ECB mode. src and dst may be equal, but they must not overlap in any other way.

 -- Function: void cast128_decrypt (struct cast128_ctx *CTX, unsigned LENGTH, const uint8_t *DST, uint8_t *SRC)
     Analogous to cast128_encrypt

BLOWFISH
--------

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 <nettle/blowfish.h>.

 -- Context struct: struct blowfish_ctx

 -- Constant: BLOWFISH_BLOCK_SIZE
     The BLOWFISH blocksize, 8

 -- Constant: BLOWFISH_MIN_KEY_SIZE
     Minimum BLOWFISH key size, 8

 -- Constant: BLOWFISH_MAX_KEY_SIZE
     Maximum BLOWFISH key size, 56

 -- Constant: BLOWFISH_KEY_SIZE
     Default BLOWFISH key size, 16

 -- Function: int blowfish_set_key (struct blowfish_ctx *CTX, unsigned LENGTH, const uint8_t *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 blowfish_encrypt or blowfish_decrypt with a weak key will crash with an assert violation.

 -- Function: void blowfish_encrypt (struct blowfish_ctx *CTX, unsigned LENGTH, const uint8_t *DST, uint8_t *SRC)
     Encryption function. LENGTH must be an integral multiple of the block size. If it is more than one block, the data is processed in ECB mode. src and dst may be equal, but they must not overlap in any other way.

 -- Function: void blowfish_decrypt (struct blowfish_ctx *CTX, unsigned LENGTH, const uint8_t *DST, uint8_t *SRC)
     Analogous to blowfish_encrypt

DES
---

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 parallell. One shouldn't be using plain DES at all today, if one uses DES at all one should be using DES3 or "triple DES", see below.

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

 -- Context struct: struct des_ctx

 -- Constant: DES_BLOCK_SIZE
     The DES blocksize, 8

 -- Constant: DES_KEY_SIZE
     DES key size, 8

 -- Function: int des_set_key (struct des_ctx *CTX, const uint8_t *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 des_encrypt or des_decrypt with a bad key will crash with an assert violation.

 -- Function: void des_encrypt (struct des_ctx *CTX, unsigned LENGTH, const uint8_t *DST, uint8_t *SRC)
     Encryption function. LENGTH must be an integral multiple of the block size. If it is more than one block, the data is processed in ECB mode. src and dst may be equal, but they must not overlap in any other way.

 -- Function: void des_decrypt (struct des_ctx *CTX, unsigned LENGTH, const uint8_t *DST, uint8_t *SRC)
     Analogous to des_encrypt

 -- Function: void des_fix_parity (unsigned LENGTH, uint8_t *DST, const uint8_t *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. DST and SRC may be equal.

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 decrypt it using the middle 56 bits of the key, and finally encrypt it again using the last 56 bits of the key. This is known as "ede" triple-DES, for "encrypt-decrypt-encrypt".

The "ede" construction provides some backward compatibility, as you get 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 impractical, some applications uses a "two-key" variant of triple-DES. 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 functions. Nettle includes an inplementation of three-key "ede" triple-DES, it is defined in the same place as plain DES, <nettle/des.h>.

 -- Context struct: struct des3_ctx

 -- Constant: DES3_BLOCK_SIZE
     The DES3 blocksize is the same as DES_BLOCK_SIZE, 8

 -- Constant: DES3_KEY_SIZE
     DES key size, 24

 -- Function: int des3_set_key (struct des3_ctx *CTX, const uint8_t *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 des_encrypt or des_decrypt with a bad key will crash with an assert violation.

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

 -- Function: void des3_encrypt (struct des3_ctx *CTX, unsigned LENGTH, const uint8_t *DST, uint8_t *SRC)
     Encryption function. LENGTH must be an integral multiple of the block size. If it is more than one block, the data is processed in ECB mode. src and dst may be equal, but they must not overlap in any other way.

 -- Function: void des3_decrypt (struct des3_ctx *CTX, unsigned LENGTH, const uint8_t *DST, uint8_t *SRC)
     Analogous to des_encrypt

SERPENT
-------

SERPENT is one of the AES finalists, designed by Ross Anderson, Eli Biham and Lars Knudsen. Thus, the interface and properties are similar to AES'. One pecularity is that it is quite pointless to use it with anything but the maximum key size, smaller keys are just padded to larger ones. Nettle defines SERPENT in <nettle/serpent.h>.

 -- Context struct: struct serpent_ctx

 -- Constant: SERPENT_BLOCK_SIZE
     The SERPENT blocksize, 16

 -- Constant: SERPENT_MIN_KEY_SIZE
     Minumim SERPENT key size, 16

 -- Constant: SERPENT_MAX_KEY_SIZE
     Maximum SERPENT key size, 32

 -- Constant: SERPENT_KEY_SIZE
     Default SERPENT key size, 32

 -- Function: void serpent_set_key (struct serpent_ctx *CTX, unsigned LENGTH, const uint8_t *KEY)
     Initialize the cipher. The same function is used for both encryption and decryption.

 -- Function: void serpent_encrypt (struct serpent_ctx *CTX, unsigned LENGTH, const uint8_t *DST, uint8_t *SRC)
     Encryption function. LENGTH must be an integral multiple of the block size. If it is more than one block, the data is processed in ECB mode. src and dst may be equal, but they must not overlap in any other way.

 -- Function: void serpent_decrypt (struct serpent_ctx *CTX, unsigned LENGTH, const uint8_t *DST, uint8_t *SRC)
     Analogous to serpent_encrypt

TWOFISH
-------

Another AES finalist, this one designed by Bruce Schneier and others. Nettle defines it in <nettle/twofish.h>.

 -- Context struct: struct twofish_ctx

 -- Constant: TWOFISH_BLOCK_SIZE
     The TWOFISH blocksize, 16

 -- Constant: TWOFISH_MIN_KEY_SIZE
     Minumim TWOFISH key size, 16

 -- Constant: TWOFISH_MAX_KEY_SIZE
     Maximum TWOFISH key size, 32

 -- Constant: TWOFISH_KEY_SIZE
     Default TWOFISH key size, 32

 -- Function: void twofish_set_key (struct twofish_ctx *CTX, unsigned LENGTH, const uint8_t *KEY)
     Initialize the cipher. The same function is used for both encryption and decryption.

 -- Function: void twofish_encrypt (struct twofish_ctx *CTX, unsigned LENGTH, const uint8_t *DST, uint8_t *SRC)
     Encryption function. LENGTH must be an integral multiple of the block size. If it is more than one block, the data is processed in ECB mode. src and dst may be equal, but they must not overlap in any other way.

 -- Function: void twofish_decrypt (struct twofish_ctx *CTX, unsigned LENGTH, const uint8_t *DST, uint8_t *SRC)
     Analogous to twofish_encrypt

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 <nettle/nettle-meta.h>.

 -- Meta struct: 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 nettle_set_key_func and nettle_crypt_func. The first argument to these functions is a void * pointer to a context struct, which is of size context_size.

 -- Constant Struct: struct nettle_cipher nettle_aes128
 -- Constant Struct: struct nettle_cipher nettle_aes192
 -- Constant Struct: struct nettle_cipher nettle_aes256

 -- Constant Struct: struct nettle_cipher nettle_arcfour128
 -- Constant Struct: struct nettle_cipher nettle_cast128

 -- Constant Struct: struct nettle_cipher nettle_serpent128
 -- Constant Struct: struct nettle_cipher nettle_serpent192
 -- Constant Struct: struct nettle_cipher nettle_serpent256

 -- Constant Struct: struct nettle_cipher nettle_twofish128
 -- Constant Struct: struct nettle_cipher nettle_twofish192
 -- Constant Struct: struct nettle_cipher nettle_twofish256

     Nettle includes such structs for all the regular ciphers, i.e. ones without weak keys or other oddnesses.

Cipher Block Chaining
=====================

When using CBC mode, cleartext blocks are not encrypted independently of each other, like in Electronic Cook Book mode. Instead, when encrypting a block in CBC mode, the previous ciphertext block is XOR:ed with the cleartext before it is fed to the block cipher. When encrypting the first block, a random block called an 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.

In symbols, if E_k is the encryption function of a blockcipher, and IV is the initialization vector, then n cleartext blocks M_1,... M_n are transformed into n ciphertext blocks C_1,... C_n as follows:

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

     ...

     C_n = E_k(C_(n-1) XOR M_n)

Nettle includes a few utility functions for applying a block cipher in Cipher Block Chaining (CBC) mode. The functions uses void * to pass cipher contexts around.

 -- Function: void cbc_encrypt (void *CTX, void (*F)(), unsigned BLOCK_SIZE, uint8_t *IV, unsigned LENGTH, uint8_t *DST, const uint8_t *SRC)
 -- Function: void cbc_decrypt (void *CTX, void (*F)(), unsigned BLOCK_SIZE, uint8_t *IV, unsigned LENGTH, uint8_t *DST, const uint8_t *SRC)

     Applies the encryption or decryption function F in CBC mode. The function F is really typed as

     void f (void *CTX, unsigned LENGTH, uint8_t DST, const uint8_t *SRC),

     and the cbc_encrypt and cbc_decrypt functions pass their argument CTX on to F.

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

 -- Macro: CBC_CTX (CONTEXT_TYPE, BLOCK_SIZE)
     Expands into

          {
             context_type ctx;
             uint8_t iv[block_size];
          }

It can be used to define a CBC context struct, either directly,

     struct CBC_CTX(struct aes_ctx, AES_BLOCK_SIZE) ctx;

or to give it a struct tag,

     struct aes_cbc_ctx CBC_CTX (struct aes_ctx, AES_BLOCK_SIZE);

 -- Macro: CBC_SET_IV (CTX, IV)
     First argument is a pointer to a context struct as defined by CBC_CTX, and the second is a pointer to an Initialization Vector (IV) that is copied into that context.

 -- Macro: CBC_ENCRYPT (CTX, F, LENGTH, DST, SRC)
 -- Macro: CBC_DECRYPT (CTX, F, LENGTH, DST, SRC)
     A simpler way to invoke cbc_encrypt and cbc_decrypt. The first argument is a pointer to a context struct as defined by 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.

These macros use some tricks to make the compiler display a warning if the types of F and CTX don't match, e.g. if you try to use an struct aes_ctx context with the des_encrypt function.

Keyed Hash Functions
====================

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

Keyed hash functions are useful primarily for message authentication, when the Alice and Bob shares a secret: The sender, Alice, computes the MAC and attaches it to the message. The receiver, Bob, also computes the MAC of the message, using the same key, and compares that to Alice's value. If they match, Bob can be assured that the message has not been modified on it's way from Alice.

However, unlike digital signatures, this assurance is not transferable. Bob can't show the message and the 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 same key is used on both sides, and anyone knowing the key can create a correct MAC for any message. If Bob believes that only he and Alice knows the key, and he knows that he didn't attach a MAC to a particular message, he knows it must be Alice who did it. However, the third party can't distinguish between MAC created by Alice and one created by Bob.

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

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 HMAC, described in RFC 2104.

For an underlying hash function H, with digest size l and internal block size b, HMAC-H is constructed as follows: From a given key k, two distinct subkeys k_i and k_o are constructed, both of length b. The HMAC-H of a message m is then computed as H(k_o | H(k_i | m)), where | denotes string concatenation.

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

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

 -- Function: void hmac_set_key (void *OUTER, void *INNER, void *STATE, const struct nettle_hash *H, unsigned LENGTH, const uint8_t *KEY)
     Initializes the three context structs from the key. The OUTER and INNER contexts corresponds to the subkeys k_o and k_i. STATE is used for hashing the message, and is initialized as a copy of the INNER context.

 -- Function: void hmac_update(void *STATE, const struct nettle_hash *H, unsigned LENGTH, const uint8_t *DATA)
     This function is called zero or more times to process the message. Actually, hmac_update(state, H, length, data) is equivalent to H->update(state, length, data), so if you wish you can use the ordinary update function of the underlying hash function instead.

 -- Function: void hmac_digest (const void *OUTER, const void *INNER, void *STATE, const struct nettle_hash *H, unsigned LENGTH, uint8_t *DIGEST)
     Extracts the MAC of the message, writing it to DIGEST. OUTER and INNER are not modified. LENGTH is usually equal to H->digest_size, but if you provide a smaller value, only the first LENGTH octets of the MAC are written.

     This function also resets the STATE context so that you can start over processing a new message (with the same key).

Like for CBC, there are some macros to help use these functions correctly.

 -- Macro: HMAC_CTX (TYPE)
     Expands into

          {
             type outer;
             type inner;
             type state;
          }

It can be used to define a HMAC constext struct, either directly,

     struct HMAC_CTX(struct md5_ctx) ctx;

or to give it a struct tag,

     struct hmac_md5_ctx HMAC_CTX (struct md5_ctx);

 -- Macro: HMAC_SET_KEY (CTX, H, LENGTH, KEY)
     CTX is a pointer to a context struct as defined by HMAC_CTX, H is a pointer to a const struct nettle_hash describing the underlying hash function (so it must match the type of the components of CTX). The last two arguments specify the secret key.

 -- Macro: HMAC_DIGEST (CTX, H, LENGTH, DIGEST)
     CTX is a pointer to a context struct as defined by HMAC_CTX, H is a pointer to a const struct nettle_hash describing the underlying hash function. The last two arguments specify where the digest is written.

Note that there is no HMAC_UPDATE macro; simply call hmac_update function directly, or the update function of the underlying hash function.

Concrete HMAC functions
-----------------------

Now we come to the specialized HMAC functions, which are easier to use than the general HMAC functions.

HMAC-MD5
........

 -- Context struct: struct hmac_md5_ctx

 -- Function: void hmac_md5_set_key (struct hmac_md5_ctx *CTX, unsigned KEY_LENGTH, const uint8_t *KEY)
     Initializes the context with the key.

 -- Function: void hmac_md5_update (struct hmac_md5_ctx *CTX, unsigned LENGTH, const uint8_t *DATA)
     Process some more data.

 -- Function: void hmac_md5_digest (struct hmac_md5_ctx *CTX, unsigned LENGTH, uint8_t *DIGEST)
     Extracts the MAC, writing it to DIGEST. LENGTH may be smaller than MD5_DIGEST_SIZE, in which case only the first LENGTH octets of the MAC are written.

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

HMAC-SHA1
.........

 -- Context struct: struct hmac_sha1_ctx

 -- Function: void hmac_sha1_set_key (struct hmac_sha1_ctx *CTX, unsigned KEY_LENGTH, const uint8_t *KEY)
     Initializes the context with the key.

 -- Function: void hmac_sha1_update (struct hmac_sha1_ctx *CTX, unsigned LENGTH, const uint8_t *DATA)
     Process some more data.

 -- Function: void hmac_sha1_digest (struct hmac_sha1_ctx *CTX, unsigned LENGTH, uint8_t *DIGEST)
     Extracts the MAC, writing it to DIGEST. LENGTH may be smaller than SHA1_DIGEST_SIZE, in which case only the first LENGTH octets of the MAC are written.

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

HMAC-SHA256
...........

 -- Context struct: struct hmac_sha256_ctx

 -- Function: void hmac_sha256_set_key (struct hmac_sha256_ctx *CTX, unsigned KEY_LENGTH, const uint8_t *KEY)
     Initializes the context with the key.

 -- Function: void hmac_sha256_update (struct hmac_sha256_ctx *CTX, unsigned LENGTH, const uint8_t *DATA)
     Process some more data.

 -- Function: void hmac_sha256_digest (struct hmac_sha256_ctx *CTX, unsigned LENGTH, uint8_t *DIGEST)
     Extracts the MAC, writing it to DIGEST. LENGTH may be smaller than SHA256_DIGEST_SIZE, in which case only the first LENGTH octets of the MAC are written.

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

Miscellaneous functions
=======================

 -- Function: uint8_t * memxor (uint8_t *DST, const uint8_t *SRC, size_t N)
     XOR:s the source area on top of the destination area. The interface doesn't follow the Nettle conventions, because it is intended to be similar to the ANSI-C memcpy function.

memxor is declared in <nettle/memxor.h>.

Compatibility functions
=======================

For convenience, Nettle includes alternative interfaces to some algorithms, for compatibilty with some other popular crypto toolkits. These are not fully documented here; refer to the source or to the documentation for the original implementation.

MD5 is defined in [RFCXXX], which includes a reference implementation. Nettle defines a compatible interface to MD5 in <nettle/md5-compat.h>. This file defines the typedef MD5_CTX, and declares the functions MD5Init, MD5Update and MD5Final.

Eric Young's "libdes" (also part of OpenSSL) is a quite popular DES implementation. Nettle includes a subset if it's interface in <nettle/des-compat.h>. This file defines the typedefs des_key_schedule and des_cblock, two constants DES_ENCRYPT and DES_DECRYPT, and declares one global variable des_check_key, and the functions des_cbc_cksum des_cbc_encrypt, des_ecb2_encrypt, des_ecb3_encrypt, des_ecb_encrypt, des_ede2_cbc_encrypt, des_ede3_cbc_encrypt, des_is_weak_key, des_key_sched, des_ncbc_encrypt des_set_key, and des_set_odd_parity.

Traditional Nettle Soup
***********************

For the serious nettle hacker, here is a recipe for nettlesoup.

4 servings

1 litre fresh nettles (urtica dioica) 2 tablespoons butter 3 tablespoons flour 1 litre buillon (meat or vegetable) 1/2 teaspoon salt a tad white pepper some cream or milk

Gather 1 ltre fresh nettles. Use gloves! Small, tender shoots are preferable but the tops of larger nettles can also be used.

Rinse the nettles very well. Boil them for 10 minutes in lightly salted water. Strain the nettles and save the water. Hack the nettles. Melt the butter and mix in the flour. Dilute with buillon and the nettlewater you save earlier. Add the hacked nettles. If you wish you can add some milk or cream at this stage. Bring to a boil and let boil for a few minutes. Season with salt and pepper.

Serve with boiled egghalves.

Recept på nässelsoppa 4 portioner

1 l färska nässlor 2 msk smör 3 msk vetemjöl 1 l kött- eller grönsaksbuljong 1/2 tsk salt 1-2 krm peppar (lite grädde eller mjölk)

Plocka 1 liter färska nässlor. Använd handskar! Helst små och späda skott, men topparna av större nässlor går också bra.

Skölj nässlorna väl. Förväll dem ca 10 minuter i lätt saltat vatten. Häll av och spara spadet. Hacka nässlorna. Smält smöret, rör i mjöl och späd med buljong och nässelspad. Lägg i de hackade nässlorna. Om så önskas, häll i en skvätt mjölk eller grädde. Koka några minuter, och smaksätt med salt och peppar.

Servera med kokta ägghalvor.

Installation
************

Nettle uses autoconf and automake. To build it, unpack the source and run

     ./configure
     make
     make check
     make install

to install in the default location, /usr/local. The library is installed in /use/local/lib/libnettle.a and the include files are installed in /use/local/include/nettle/.

Only static libraries are installed.