Nettle: a low-level cryptographic library

Next:   [Contents][Index]

Nettle

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

This manual is for the Nettle library (version 3.9), a low-level cryptographic library.

Originally written 2001 by Niels Möller, updated 2023.

This manual is placed in the public domain. You may freely copy it, in whole or in part, with or without modification. Attribution is appreciated, but not required.

Table of Contents


Next: , Previous: , Up: Nettle   [Contents][Index]

1 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, test cases, benchmarks, documentation, etc. Examples are the Nettle module for the Pike language, and LSH, which both use 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.


Next: , Previous: , Up: Nettle   [Contents][Index]

3 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 decryption, 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 of the same type, 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 size_t, 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 usually of the same length. When they differ, e.g., for ccm_encrypt_message, the length argument specifies the size of the destination area. Source and destination pointers may be equal, so that you can process strings in place, but source and destination areas must not overlap in any other way.

Many of the functions lack return value and can never fail. Those functions which can fail, return one on success and zero on failure.


Next: , Previous: , Up: Nettle   [Contents][Index]

4 Example

A simple example program that reads a file from standard input and writes its SHA1 check-sum on standard output should give the flavor of Nettle.

#include <stdio.h>
#include <stdlib.h>

#include <nettle/sha1.h>

#define BUF_SIZE 1000

static void
display_hex(unsigned length, uint8_t *data)
{
  unsigned i;

  for (i = 0; i<length; i++)
    printf("%02x ", data[i]);

  printf("\n");
}

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);
    sha1_update(&ctx, done, buffer);
    if (done < sizeof(buffer))
      break;
  }
  if (ferror(stdin))
    return EXIT_FAILURE;

  sha1_digest(&ctx, SHA1_DIGEST_SIZE, digest);

  display_hex(SHA1_DIGEST_SIZE, digest);
  return EXIT_SUCCESS;  
}

On a typical Unix system, this program can be compiled and linked with the command line

gcc sha-example.c -o sha-example -lnettle

Next: , Previous: , Up: Nettle   [Contents][Index]

5 Linking

Nettle actually consists of two libraries, libnettle and libhogweed. The libhogweed library contains those functions of Nettle that uses bignum operations, and depends on the GMP library. With this division, linking works the same for both static and dynamic libraries.

If an application uses only the symmetric crypto algorithms of Nettle (i.e., block ciphers, hash functions, and the like), it’s sufficient to link with -lnettle. If an application also uses public-key algorithms, the recommended linker flags are -lhogweed -lnettle -lgmp. If the involved libraries are installed as dynamic libraries, it may be sufficient to link with just -lhogweed, and the loader will resolve the dependencies automatically.


Next: , Previous: , Up: Nettle   [Contents][Index]

6 Compatibility

When you write a program using the Nettle library, it’s desirable to have it work together not only with exactly the same version of Nettle you had at hand, but with other current and future versions. If a different version of Nettle is used at compile time, i.e., you recompile it using the header and library files belonging to a different version, we talk about API compatibility (for Application Programming Interface). If a different version of Nettle isn’t used until link time, we talk about ABI compatibility (Application Binary Interface) or binary compatibility. ABI compatibility matters mainly when using dynamic linking with a shared library. E.g., a user has an executable linking at run-time with libnettle.so, and then updates to a later version of the shared library, without updating or recompiling the executable.

Nettle aims to provide backwards compatibility, i.e., a program written for a particular version of the Nettle library should usually work fine with later version of the library. Note that the opposite is not supported: The program should not be expected to work with older versions of the Nettle library; and ABI breakage can be unobvious. E.g, the later version may define a new library symbol, and let header files redefine an old API name as an alias for the new symbol. If the later version ensures that the old symbol is still defined in the library, this change is backwards compatible: A program compiled using headers from the older version can be successfully linked with either version of the library. But if you compile the same program using headers from the later version of the library, and attempt to link with the older version, you’ll get an undefined reference to the new symbol.

API compatibility is rarely broken; exceptions are noted in the NEWS file. For example, the key size argument to the function cast128_set_key was dropped in the Nettle-3.0 release, and all programs using that function had to be updated to work with the new version.

ABI compatibility is broken occasionally. This is also noted in the NEWS file, and the name of the shared library is updated to prevent accidental run-time linking with the wrong version. All programs have to be recompiled before they can link with the new version. Since names are different, multiple versions can be installed on the same system, with a mix of programs linking to one version or the other.

Under some circumstances, it is possible to have a single program linking dynamically with two binary incompatible versions of the Nettle library, thanks to the use of symbol versioning. Consider a program calling functions in both Nettle and GnuTLS. For the direct dependency on Nettle, the program is linked with a particular version of the Nettle shared library. GnuTLS uses Nettle internally, but does not expose any Nettle data structures or the like in its own ABI. In this situation, the GnuTLS shared library may link with a different version of the Nettle library. Then both versions of the Nettle library will be loaded into the program’s address space, and each reference to a symbol will be resolved to the correct version.

Finally, some of Nettle’s symbols are internal. They carry a leading underscore, and are not declared in installed header files. They can be used for local or experimental purposes, but programs referring directly to those symbols get neither API nor ABI compatibility, not even between minor versions.


7 Reference

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


7.1 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 ids to documents, and many other things.

The most commonly used hash functions are MD5 and SHA1. Unfortunately, both these fail the collision-resistance requirement; cryptologists have found ways to construct colliding inputs. The recommended hash functions for new applications are SHA2 (with main variants SHA256 and SHA512). At the time of this writing (Autumn 2015), SHA3 has recently been standardized, and the new SHA3 and other top SHA3 candidates may also be reasonable alternatives.


7.1.2 Miscellaneous hash functions

7.1.2.1 STREEBOG512

STREEBOG512 is a member of the Streebog (GOST R 34.11-2012) family. It outputs hash values of 512 bits, or 64 octets. Nettle defines STREEBOG512 in <nettle/streebog.h>.

Context struct: struct streebog512_ctx
Constant: STREEBOG512_DIGEST_SIZE

The size of a STREEBOG512 digest, i.e. 64.

Constant: STREEBOG512_BLOCK_SIZE

The internal block size of STREEBOG512. Useful for some special constructions, in particular HMAC-STREEBOG512.

Function: void streebog512_init (struct streebog512_ctx *ctx)

Initialize the STREEBOG512 state.

Function: void streebog512_update (struct streebog512_ctx *ctx, size_t length, const uint8_t *data)

Hash some more data.

Function: void streebog512_digest (struct streebog512_ctx *ctx, size_t length, uint8_t *digest)

Performs final processing and extracts the message digest, writing it to digest. length may be smaller than STREEBOG512_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 streebog512_init.

7.1.2.2 STREEBOG256

STREEBOG256 is a variant of STREEBOG512, with a different initial state, and with the output truncated to 256 bits, or 32 octets. Nettle defines STREEBOG256 in <nettle/streebog.h>.

Context struct: struct streebog256_ctx
Constant: STREEBOG256_DIGEST_SIZE

The size of a STREEBOG256 digest, i.e. 32.

Constant: STREEBOG256_BLOCK_SIZE

The internal block size of STREEBOG256. Useful for some special constructions, in particular HMAC-STREEBOG256.

Function: void streebog256_init (struct streebog256_ctx *ctx)

Initialize the STREEBOG256 state.

Function: void streebog256_update (struct streebog256_ctx *ctx, size_t length, const uint8_t *data)

Hash some more data.

Function: void streebog256_digest (struct streebog256_ctx *ctx, size_t length, uint8_t *digest)

Performs final processing and extracts the message digest, writing it to digest. length may be smaller than STREEBOG256_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 streebog256_init.

7.1.2.3 SM3

SM3 is a cryptographic hash function standard adopted by the government of the People’s Republic of China, which was issued by the Cryptography Standardization Technical Committee of China on December 17, 2010. The corresponding standard is GM/T 0004-2012 "SM3 Cryptographic Hash Algorithm".

SM3 algorithm is a hash algorithm in ShangMi cryptosystems. SM3 is mainly used for digital signature and verification, message authentication code generation and verification, random number generation, and the RFC 8998 specification defines the usage of ShangMi algorithm suite in TLS 1.3, etc. According to the State Cryptography Administration of China, its security and efficiency are equivalent to SHA-256.

Nettle defines SM3 in <nettle/sm3.h>.

Context struct: struct sm3_ctx
Constant: SM3_DIGEST_SIZE

The size of a SM3 digest, i.e. 32.

Constant: SM3_BLOCK_SIZE

The internal block size of SM3. Useful for some special constructions, in particular HMAC-SM3.

Function: void sm3_init (struct sm3_ctx *ctx)

Initialize the SM3 state.

Function: void sm3_update (struct sm3_ctx *ctx, size_t length, const uint8_t *data)

Hash some more data.

Function: void sm3_digest (struct sm3_ctx *ctx, size_t length, uint8_t *digest)

Performs final processing and extracts the message digest, writing it to digest. length may be smaller than SM3_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 sm3_init.


7.1.3 Legacy hash functions

The hash functions in this section all have some known weaknesses, and should be avoided for new applications. These hash functions are mainly useful for compatibility with old applications and protocols. Some are still considered safe as building blocks for particular constructions, e.g., there seems to be no known attacks against HMAC-SHA1 or even HMAC-MD5. In some important cases, use of a “legacy” hash function does not in itself make the application insecure; if a known weakness is relevant depends on how the hash function is used, and on the threat model.

7.1.3.1 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_BLOCK_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, size_t length, const uint8_t *data)

Hash some more data.

Function: void md5_digest (struct md5_ctx *ctx, size_t 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.

Function: void md5_compress (const uint32_t *state, uint8_t *input)

Perform a raw MD5 compress on MD5_BLOCK_SIZE bytes from input using state as IV (an array of 4 uint32_t). The output is stored in state. This function provides access to the underlying compression function, for the rare applications that need that (e.g., using different IV from standard MD5).

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.

7.1.3.2 MD2

MD2 is another hash function of Ronald Rivest’s, described in RFC 1319. It outputs message digests of 128 bits, or 16 octets. Nettle defines MD2 in <nettle/md2.h>.

Context struct: struct md2_ctx
Constant: MD2_DIGEST_SIZE

The size of an MD2 digest, i.e. 16.

Constant: MD2_BLOCK_SIZE

The internal block size of MD2.

Function: void md2_init (struct md2_ctx *ctx)

Initialize the MD2 state.

Function: void md2_update (struct md2_ctx *ctx, size_t length, const uint8_t *data)

Hash some more data.

Function: void md2_digest (struct md2_ctx *ctx, size_t length, uint8_t *digest)

Performs final processing and extracts the message digest, writing it to digest. length may be smaller than MD2_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 md2_init.

7.1.3.3 MD4

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

Context struct: struct md4_ctx
Constant: MD4_DIGEST_SIZE

The size of an MD4 digest, i.e. 16.

Constant: MD4_BLOCK_SIZE

The internal block size of MD4.

Function: void md4_init (struct md4_ctx *ctx)

Initialize the MD4 state.

Function: void md4_update (struct md4_ctx *ctx, size_t length, const uint8_t *data)

Hash some more data.

Function: void md4_digest (struct md4_ctx *ctx, size_t length, uint8_t *digest)

Performs final processing and extracts the message digest, writing it to digest. length may be smaller than MD4_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 md4_init.

7.1.3.4 RIPEMD160

RIPEMD160 is a hash function designed by Hans Dobbertin, Antoon Bosselaers, and Bart Preneel, as a strengthened version of RIPEMD (which, like MD4 and MD5, fails the collision-resistance requirement). It produces message digests of 160 bits, or 20 octets. Nettle defined RIPEMD160 in nettle/ripemd160.h.

Context struct: struct ripemd160_ctx
Constant: RIPEMD160_DIGEST_SIZE

The size of a RIPEMD160 digest, i.e. 20.

Constant: RIPEMD160_BLOCK_SIZE

The internal block size of RIPEMD160.

Function: void ripemd160_init (struct ripemd160_ctx *ctx)

Initialize the RIPEMD160 state.

Function: void ripemd160_update (struct ripemd160_ctx *ctx, size_t length, const uint8_t *data)

Hash some more data.

Function: void ripemd160_digest (struct ripemd160_ctx *ctx, size_t length, uint8_t *digest)

Performs final processing and extracts the message digest, writing it to digest. length may be smaller than RIPEMD160_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 ripemd160_init.

7.1.3.5 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/sha1.h> (and in <nettle/sha.h>, for backwards compatibility).

Context struct: struct sha1_ctx
Constant: SHA1_DIGEST_SIZE

The size of a SHA1 digest, i.e. 20.

Constant: SHA1_BLOCK_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, size_t length, const uint8_t *data)

Hash some more data.

Function: void sha1_digest (struct sha1_ctx *ctx, size_t 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.

Function: void sha1_compress (const uint32_t *state, uint8_t *input)

Perform a raw SHA1 compress on SHA1_BLOCK_SIZE bytes from input using state as IV (an array of 5 uint32_t). The output is stored in state. This function provides access to the underlying compression function, for the rare applications that need that (e.g., using different IV from standard SHA1).

7.1.3.6 GOSTHASH94 and GOSTHASH94CP

The GOST94 or GOST R 34.11-94 hash algorithm is a Soviet-era algorithm used in Russian government standards (see RFC 4357). It outputs message digests of 256 bits, or 32 octets. The standard itself does not fix the S-box used by the hash algorith, so there are two popular variants (the testing S-box from the standard itself and the S-box defined by CryptoPro company, see RFC 4357). Nettle provides support for the former S-box in the form of GOSTHASH94 hash algorithm and for the latter in the form of GOSTHASH94CP hash algorithm. Nettle defines GOSTHASH94 and GOSTHASH94CP in <nettle/gosthash94.h>.

Context struct: struct gosthash94_ctx
Constant: GOSTHASH94_DIGEST_SIZE

The size of a GOSTHASH94 digest, i.e. 32.

Constant: GOSTHASH94_BLOCK_SIZE

The internal block size of GOSTHASH94, i.e., 32.

Function: void gosthash94_init (struct gosthash94_ctx *ctx)

Initialize the GOSTHASH94 state.

Function: void gosthash94_update (struct gosthash94_ctx *ctx, size_t length, const uint8_t *data)

Hash some more data.

Function: void gosthash94_digest (struct gosthash94_ctx *ctx, size_t length, uint8_t *digest)

Performs final processing and extracts the message digest, writing it to digest. length may be smaller than GOSTHASH94_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 gosthash94_init.

Context struct: struct gosthash94cp_ctx
Constant: GOSTHASH94CP_DIGEST_SIZE

The size of a GOSTHASH94CP digest, i.e. 32.

Constant: GOSTHASH94CP_BLOCK_SIZE

The internal block size of GOSTHASH94CP, i.e., 32.

Function: void gosthash94cp_init (struct gosthash94cp_ctx *ctx)

Initialize the GOSTHASH94CP state.

Function: void gosthash94cp_update (struct gosthash94cp_ctx *ctx, size_t length, const uint8_t *data)

Hash some more data.

Function: void gosthash94cp_digest (struct gosthash94cp_ctx *ctx, size_t length, uint8_t *digest)

Performs final processing and extracts the message digest, writing it to digest. length may be smaller than GOSTHASH94CP_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 gosthash94cp_init.


7.1.4 The struct nettle_hash abstraction

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 to a context struct, which is of size context_size.

Constant Struct: struct nettle_hash nettle_md2
Constant Struct: struct nettle_hash nettle_md4
Constant Struct: struct nettle_hash nettle_md5
Constant Struct: struct nettle_hash nettle_ripemd160
Constant Struct: struct nettle_hash nettle_sha1
Constant Struct: struct nettle_hash nettle_sha224
Constant Struct: struct nettle_hash nettle_sha256
Constant Struct: struct nettle_hash nettle_sha384
Constant Struct: struct nettle_hash nettle_sha512
Constant Struct: struct nettle_hash nettle_sha3_256
Constant Struct: struct nettle_hash nettle_gosthash94
Constant Struct: struct nettle_hash nettle_gosthash94cp
Constant Struct: struct nettle_hash nettle_sm3

These are all the hash functions that Nettle implements.

Nettle also exports a list of all these hashes.

Function: const struct nettle_hash ** nettle_get_hashes (void)

Returns a NULL-terminated list of pointers to supported hash functions. This list can be used to dynamically enumerate or search the supported algorithms.

Macro: nettle_hashes

A macro expanding to a call to nettle_get_hashes, so that one could write, e.g., nettle_hashes[0]->name for the name of the first hash function on the list. In earlier versions, this was not a macro but the actual array of pointers. However, referring directly to the array makes the array size leak into the ABI in some cases.


Next: , Previous: , Up: Reference   [Contents][Index]

7.2 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 plaintext. 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) and CTR (Counter mode) being two of of the most popular. See See Cipher modes, for information on how to apply CBC and CTR with Nettle.

A stream cipher can be used for messages of arbitrary length. A typical stream cipher is a keyed pseudo-random generator. To encrypt a plaintext message of n octets, you key the generator, generate n octets of pseudo-random 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 plaintext 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 answer 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 Authentication 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, most key setup functions have no return value, but for ciphers with weak keys, the return value indicates whether or not the given key is weak. For good keys, key setup returns 1, and for weak keys, it returns 0. When possible, avoid algorithms 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 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.


7.2.1 AES

AES is a block cipher, specified by NIST as a replacement for the older DES standard. The standard 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 three possible key-size, 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>, and there is one context struct for each key size. (Earlier versions of Nettle used a single context struct, struct aes_ctx, for all key sizes. This interface kept for backwards compatibility).

Context struct: struct aes128_ctx
Context struct: struct aes192_ctx
Context struct: struct aes256_ctx
Context struct: struct aes_ctx

Alternative struct, for the old AES interface.

Constant: AES_BLOCK_SIZE

The AES block-size, 16.

Constant: AES128_KEY_SIZE
Constant: AES192_KEY_SIZE
Constant: AES256_KEY_SIZE
Constant: AES_MIN_KEY_SIZE
Constant: AES_MAX_KEY_SIZE
Constant: AES_KEY_SIZE

Default AES key size, 32.

Function: void aes128_set_encrypt_key (struct aes128_ctx *ctx, const uint8_t *key)
Function: void aes128_set_decrypt_key (struct aes128_ctx *ctx, const uint8_t *key)
Function: void aes192_set_encrypt_key (struct aes192_ctx *ctx, const uint8_t *key)
Function: void aes192_set_decrypt_key (struct aes192_ctx *ctx, const uint8_t *key)
Function: void aes256_set_encrypt_key (struct aes256_ctx *ctx, const uint8_t *key)
Function: void aes256_set_decrypt_key (struct aes256_ctx *ctx, const uint8_t *key)
Function: void aes_set_encrypt_key (struct aes_ctx *ctx, size_t length, const uint8_t *key)
Function: void aes_set_decrypt_key (struct aes_ctx *ctx, size_t length, const uint8_t *key)

Initialize the cipher, for encryption or decryption, respectively.

Function: void aes128_invert_key (struct aes128_ctx *dst, const struct aes128_ctx *src)
Function: void aes192_invert_key (struct aes192_ctx *dst, const struct aes192_ctx *src)
Function: void aes256_invert_key (struct aes256_ctx *dst, const struct aes256_ctx *src)
Function: void aes_invert_key (struct aes_ctx *dst, const struct aes_ctx *src)

Given a context src initialized for encryption, initializes the context struct dst for decryption, using the same key. If the same context struct is passed for both src and dst, it is converted in place. These functions are mainly useful for applications which needs to both encrypt and decrypt using the same key, because calling, e.g., aes128_set_encrypt_key and aes128_invert_key, is more efficient than calling aes128_set_encrypt_key and aes128_set_decrypt_key.

Function: void aes128_encrypt (struct aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void aes192_encrypt (struct aes192_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void aes256_encrypt (struct aes256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void aes_encrypt (struct aes_ctx *ctx, size_t length, uint8_t *dst, const 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 aes128_decrypt (struct aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void aes192_decrypt (struct aes192_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void aes256_decrypt (struct aes256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void aes_decrypt (struct aes_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)

Analogous to the encryption functions above.


Next: , Previous: , Up: Cipher functions   [Contents][Index]

7.2.2 Arcfour

ARCFOUR is a historic stream cipher, also known under the trade marked name RC4, and was a widely used fast stream cipher.

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

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

Another problem is that the output is distinguishable from random data, and that the initial bytes of the generated key stream leak information about the key; for this reason, it was sometimes recommended to discard the first 512, 768 or 1024 bytes of the key stream.

/* A more robust key setup function for ARCFOUR */
void
arcfour_set_key_hashed(struct arcfour_ctx *ctx,
                       size_t length, const uint8_t *key)
{
  struct sha256_ctx hash;
  uint8_t digest[SHA256_DIGEST_SIZE];
  uint8_t buffer[0x200];

  sha256_init(&hash);
  sha256_update(&hash, length, key);
  sha256_digest(&hash, SHA256_DIGEST_SIZE, digest);

  arcfour_set_key(ctx, SHA256_DIGEST_SIZE, digest);
  arcfour_crypt(ctx, sizeof(buffer), buffer, buffer);
}

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, size_t 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, size_t length, uint8_t *dst, const uint8_t *src)

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.


Next: , Previous: , Up: Cipher functions   [Contents][Index]

7.2.3 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 reverse engineered RC2 cipher description, as described in a Usenet post to 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, ekb. This parameter can be used to artificially reduce the key size. In practice, ekb is usually set equal to the input key size. Nettle defines ARCTWO in <nettle/arctwo.h>.

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

Context struct: struct arctwo_ctx
Constant: ARCTWO_BLOCK_SIZE

The ARCTWO block-size, 8.

Constant: ARCTWO_MIN_KEY_SIZE
Constant: ARCTWO_MAX_KEY_SIZE
Constant: ARCTWO_KEY_SIZE

Default ARCTWO key size, 8.

Function: void arctwo_set_key_ekb (struct arctwo_ctx *ctx, size_t length, const uint8_t *key, unsigned ekb)
Function: void arctwo_set_key (struct arctwo_ctx *ctx, size_t length, const uint8_t *key)
Function: void arctwo_set_key_gutmann (struct arctwo_ctx *ctx, size_t length, const uint8_t *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 ekb is 1024, and for convenience, ekb = 0 has the same effect as ekb = 1024.

arctwo_set_key(ctx, length, key) is equivalent to arctwo_set_key_ekb(ctx, length, key, 8*length), and arctwo_set_key_gutmann(ctx, length, key) is equivalent to arctwo_set_key_ekb(ctx, length, key, 1024)

Function: void arctwo_encrypt (struct arctwo_ctx *ctx, size_t length, uint8_t *dst, const 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 arctwo_decrypt (struct arctwo_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)

Analogous to arctwo_encrypt


Next: , Previous: , Up: Cipher functions   [Contents][Index]

7.2.4 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 block-size, 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, size_t length, const uint8_t *key)

Initialize the cipher. The same function is used for both encryption and decryption. Checks for weak keys, returning 1 for good keys and 0 for weak keys. Applications that don’t care about weak keys can ignore the return value.

blowfish_encrypt or blowfish_decrypt with a weak key will crash with an assert violation.

Function: void blowfish_encrypt (struct blowfish_ctx *ctx, size_t length, uint8_t *dst, const 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, size_t length, uint8_t *dst, const uint8_t *src)

Analogous to blowfish_encrypt

Function: int blowfish_bcrypt_hash (char *dst, size_t lenkey, const char *key, size_t lenscheme, const char *scheme, int log2rounds, const uint8_t *salt)

Compute the bcrypt password hash. The function will return 0 if the hash cannot be computed due to invalid input. The function will return 1 and store the computed hash in the array pointed to by dst. The hash is computed based on the chosen scheme, number of rounds log2rounds and specified salt.

dst must point to a character array of at least BLOWFISH_BCRYPT_HASH_SIZE bytes.

key contains the plaintext password string of size lenkey.

scheme is of size lenscheme and contains either just the chosen scheme (valid schemes are: 2a, 2b, 2x or 2y), or (the prefix of) an existing hashed password (typically $2b$10$...).

log2rounds contains the log2 of the number of encryption rounds that must be used to compute the hash. If it is -1 the value will be extracted from scheme.

salt should point to an array of BLOWFISH_BCRYPT_BINSALT_SIZE random bytes to be used to perturb the hash computation. If it is NULL the salt will be extracted from scheme.

Sample code to generate a bcrypt hash:

char password[] = "ExamplePassword";
char scheme[] = "2b";
uint8_t salt[BLOWFISH_BCRYPT_BINSALT_SIZE];
…
/* Make sure that salt is filled with random bytes */
…
char hash[BLOWFISH_BCRYPT_HASH_SIZE];
int result = blowfish_bcrypt(hash,
                             sizeof(password) - 1, password,
                             sizeof(scheme) - 1, scheme, 10, salt);
if (result)
  printf("%s\n", hash);
Function: int blowfish_bcrypt_verify (size_t lenkey, const char *key, size_t lenhashed, const char *hashed)

Verifies the bcrypt password hash against the supplied plaintext password. The function will return 0 if the password does not match. The function will return 1 if the password matches.

key contains the plaintext password string of size lenkey.

hashed contains the hashed string of size lenhashed to compare with.

Sample code to verify a bcrypt hash:

char password[] = "ExamplePassword";
char hash[] =
  "$2y$"  /* Hash algorithm version */
  "10"   /* 2^10 hash rounds (strength) */
  "$"   /* separator */
  "1b2lPgo4XumibnJGN3r3sO" /* base64 encoded 16-byte salt */
  "u7wE7xNfYDKlAxZffJDCJdVfFTAyevu"; /* Hashedpart */
if (blowfish_bcrypt_verify(sizeof(password) - 1, password,
                           sizeof(hash) - 1, hash))
  printf("Password is correct.");
else
  printf("Password is incorrect.");

Next: , Previous: , Up: Cipher functions   [Contents][Index]

7.2.5 Camellia

Camellia is a block cipher developed by Mitsubishi and Nippon Telegraph and Telephone Corporation, described in RFC3713. It is recommended by some Japanese and European authorities as an alternative to AES, and it is one of the selected algorithms in the New European Schemes for Signatures, Integrity and Encryption (NESSIE) project. The algorithm is patented. The implementation in Nettle is derived from the implementation released by NTT under the GNU LGPL (v2.1 or later), and relies on the implicit patent license of the LGPL. There is also a statement of royalty-free licensing for Camellia at https://www.ntt.co.jp/news/news01e/0104/010417.html, but this statement has some limitations which seem problematic for free software.

Camellia uses a the same block size and key sizes as AES: The block size is 128 bits (16 octets), and the supported key sizes are 128, 192, and 256 bits. The variants with 192 and 256 bit keys are identical, except for the key setup. Nettle defines Camellia in <nettle/camellia.h>, and there is one context struct for each key size. (Earlier versions of Nettle used a single context struct, struct camellia_ctx, for all key sizes. This interface kept for backwards compatibility).

Context struct: struct camellia128_ctx
Context struct: struct camellia192_ctx
Context struct: struct camellia256_ctx

Contexts structs. Actually, camellia192_ctx is an alias for camellia256_ctx.

Context struct: struct camellia_ctx

Alternative struct, for the old Camellia interface.

Constant: CAMELLIA_BLOCK_SIZE

The CAMELLIA block-size, 16.

Constant: CAMELLIA128_KEY_SIZE
Constant: CAMELLIA192_KEY_SIZE
Constant: CAMELLIA256_KEY_SIZE
Constant: CAMELLIA_MIN_KEY_SIZE
Constant: CAMELLIA_MAX_KEY_SIZE
Constant: CAMELLIA_KEY_SIZE

Default CAMELLIA key size, 32.

Function: void camellia128_set_encrypt_key (struct camellia128_ctx *ctx, const uint8_t *key)
Function: void camellia128_set_decrypt_key (struct camellia128_ctx *ctx, const uint8_t *key)
Function: void camellia192_set_encrypt_key (struct camellia192_ctx *ctx, const uint8_t *key)
Function: void camellia192_set_decrypt_key (struct camellia192_ctx *ctx, const uint8_t *key)
Function: void camellia256_set_encrypt_key (struct camellia256_ctx *ctx, const uint8_t *key)
Function: void camellia256_set_decrypt_key (struct camellia256_ctx *ctx, const uint8_t *key)
Function: void camellia_set_encrypt_key (struct camellia_ctx *ctx, size_t length, const uint8_t *key)
Function: void camellia_set_decrypt_key (struct camellia_ctx *ctx, size_t length, const uint8_t *key)

Initialize the cipher, for encryption or decryption, respectively.

Function: void camellia128_invert_key (struct camellia128_ctx *dst, const struct camellia128_ctx *src)
Function: void camellia192_invert_key (struct camellia192_ctx *dst, const struct camellia192_ctx *src)
Function: void camellia256_invert_key (struct camellia256_ctx *dst, const struct camellia256_ctx *src)
Function: void camellia_invert_key (struct camellia_ctx *dst, const struct camellia_ctx *src)

Given a context src initialized for encryption, initializes the context struct dst for decryption, using the same key. If the same context struct is passed for both src and dst, it is converted in place. These functions are mainly useful for applications which needs to both encrypt and decrypt using the same key.

Function: void camellia128_crypt (struct camellia128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void camellia192_crypt (struct camellia192_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void camellia256_crypt (struct camellia256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void camellia_crypt (struct camellia_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)

The same function is used for both encryption and decryption. 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.


Next: , Previous: , Up: Cipher functions   [Contents][Index]

7.2.6 CAST128

CAST-128 is a block cipher, specified in RFC 2144. It uses a 64 bit (8 octets) block size, and a key size of 128 bits. It is possible, but discouraged, to use the same algorithm with shorter keys. Nettle refers to the variant with variable key size as CAST-5. Keys for CAST-5 are zero padded to 128 bits, and with very short keys, less than 80 bits, encryption also uses fewer rounds than CAST128. Nettle defines cast128 in <nettle/cast128.h>.

Context struct: struct cast128_ctx
Constant: CAST128_BLOCK_SIZE

The CAST128 block-size, 8.

Constant: CAST128_KEY_SIZE

The CAST128 key size, 16.

Constant: CAST5_MIN_KEY_SIZE

Minimum CAST5 key size, 5.

Constant: CAST5_MAX_KEY_SIZE

Maximum CAST5 key size, 16. With 16 octets key (128 bits), CAST-5 is the same as CAST-128.

Function: void cast128_set_key (struct cast128_ctx *ctx, 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, size_t length, uint8_t *dst, const 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, size_t length, uint8_t *dst, const uint8_t *src)

Analogous to cast128_encrypt

Function: void cast5_set_key (struct cast128_ctx *ctx, size_t length, const uint8_t *key)

Initialize the cipher. This variant of the key setup takes the key size as argument. The same function is used for both encryption and decryption.


Next: , Previous: , Up: Cipher functions   [Contents][Index]

7.2.7 ChaCha

ChaCha is a variant of the stream cipher Salsa20 (see Salsa20), below, also designed by D. J. Bernstein. Nettle defines ChaCha in <nettle/chacha.h>.

Context struct: struct chacha_ctx
Constant: CHACHA_KEY_SIZE

ChaCha key size, 32.

Constant: CHACHA_BLOCK_SIZE

ChaCha block size, 64.

Constant: CHACHA_NONCE_SIZE

Size of the nonce, 8.

Constant: CHACHA_COUNTER_SIZE

Size of the counter, 8.

Function: void chacha_set_key (struct chacha_ctx *ctx, const uint8_t *key)

Initialize the cipher. The same function is used for both encryption and decryption. Before using the cipher, you must also call chacha_set_nonce, see below.

Function: void chacha_set_nonce (struct chacha_ctx *ctx, const uint8_t *nonce)

Sets the nonce. It is always of size CHACHA_NONCE_SIZE, 8 octets. This function also initializes the block counter, setting it to zero.

Function: void chacha_set_counter (struct chacha_ctx *ctx, const uint8_t *counter)

Sets the block counter. It is always of size CHACHA_COUNTER_SIZE, 8 octets. This is rarely needed since chacha_set_nonce initializes the block counter to zero. When it is still necessary, this function must be called after chacha_set_nonce.

Function: void chacha_crypt (struct chacha_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)

Encrypts or decrypts the data of a message, using ChaCha. When a message is encrypted using a sequence of calls to chacha_crypt, all but the last call must use a length that is a multiple of CHACHA_BLOCK_SIZE.

7.2.7.1 32-bit counter variant

While the original paper uses 64-bit counter value, the variant defined in RFC 8439 uses 32-bit counter value. This variant is particularly useful for see ChaCha-Poly1305 AEAD construction, which supports 12-octet nonces.

Constant: CHACHA_NONCE96_SIZE

Size of the nonce, 12.

Constant: CHACHA_COUNTER32_SIZE

Size of the counter, 4.

Function: void chacha_set_nonce96 (struct chacha_ctx *ctx, const uint8_t *nonce)

Sets the nonce. This is similar to the above chacha_set_nonce, but the input is always of size CHACHA_NONCE96_SIZE, 12 octets.

Function: void chacha_set_counter32 (struct chacha_ctx *ctx, const uint8_t *counter)

Sets the block counter. This is similar to the above chacha_set_counter, but the input is always of size CHACHA_COUNTER32_SIZE, 4 octets.

Function: void chacha_crypt32 (struct chacha_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)

Encrypts or decrypts the data of a message, using ChaCha. This is similar to the above chacha_crypt, but it assumes the internal counter value is 32-bit long and the nonce is 96-bit long.


Next: , Previous: , Up: Cipher functions   [Contents][Index]

7.2.8 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 may be 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 parallel. One shouldn’t be using plain DES at all today, if one uses DES at all one should be using “triple DES”, see DES3 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 block-size, 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. Parity bits are ignored. Checks for weak keys, returning 1 for good keys and 0 for weak keys. Applications that don’t care about weak keys can ignore the return value.

Function: void des_encrypt (struct des_ctx *ctx, size_t length, uint8_t *dst, const 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, size_t length, uint8_t *dst, const uint8_t *src)

Analogous to des_encrypt

Function: int des_check_parity (size_t length, const uint8_t *key)

Checks that the given key has correct, odd, parity. Returns 1 for correct parity, and 0 for bad parity.

Function: void des_fix_parity (size_t 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.


Next: , Previous: , Up: Cipher functions   [Contents][Index]

7.2.9 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 implementation 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 block-size 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. Parity bits are ignored. Checks for weak keys, returning 1 if all three keys are good keys, and 0 if one or more key is weak. Applications that don’t care about weak keys can ignore the return value.

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, size_t length, uint8_t *dst, const 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, size_t length, uint8_t *dst, const uint8_t *src)

Analogous to des_encrypt


Next: , Previous: , Up: Cipher functions   [Contents][Index]

7.2.10 Salsa20

Salsa20 is a fairly recent stream cipher designed by D. J. Bernstein. It is built on the observation that a cryptographic hash function can be used for encryption: Form the hash input from the secret key and a counter, xor the hash output and the first block of the plaintext, then increment the counter to process the next block (similar to CTR mode, see Counter mode). Bernstein defined an encryption algorithm, Snuffle, in this way to ridicule United States export restrictions which treated hash functions as nice and harmless, but ciphers as dangerous munitions.

Salsa20 uses the same idea, but with a new specialized hash function to mix key, block counter, and a couple of constants. It’s also designed for speed; on x86_64, it is currently the fastest cipher offered by nettle. It uses a block size of 512 bits (64 octets) and there are two specified key sizes, 128 and 256 bits (16 and 32 octets).

Caution: The hash function used in Salsa20 is not directly applicable for use as a general hash function. It’s not collision resistant if arbitrary inputs are allowed, and furthermore, the input and output is of fixed size.

When using Salsa20 to process a message, one specifies both a key and a nonce, the latter playing a similar rôle to the initialization vector (IV) used with CBC or CTR mode. One can use the same key for several messages, provided one uses a unique random iv for each message. The iv is 64 bits (8 octets). The block counter is initialized to zero for each message, and is also 64 bits (8 octets). Nettle defines Salsa20 in <nettle/salsa20.h>.

Context struct: struct salsa20_ctx
Constant: SALSA20_128_KEY_SIZE
Constant: SALSA20_256_KEY_SIZE

The two supported key sizes, 16 and 32 octets.

Constant: SALSA20_KEY_SIZE

Recommended key size, 32.

Constant: SALSA20_BLOCK_SIZE

Salsa20 block size, 64.

Constant: SALSA20_NONCE_SIZE

Size of the nonce, 8.

Function: void salsa20_128_set_key (struct salsa20_ctx *ctx, const uint8_t *key)
Function: void salsa20_256_set_key (struct salsa20_ctx *ctx, const uint8_t *key)
Function: void salsa20_set_key (struct salsa20_ctx *ctx, size_t length, const uint8_t *key)

Initialize the cipher. The same function is used for both encryption and decryption. salsa20_128_set_key and salsa20_128_set_key use a fix key size each, 16 and 32 octets, respectively. The function salsa20_set_key is provided for backwards compatibility, and the length argument must be either 16 or 32. Before using the cipher, you must also call salsa20_set_nonce, see below.

Function: void salsa20_set_nonce (struct salsa20_ctx *ctx, const uint8_t *nonce)

Sets the nonce. It is always of size SALSA20_NONCE_SIZE, 8 octets. This function also initializes the block counter, setting it to zero.

Function: void salsa20_crypt (struct salsa20_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)

Encrypts or decrypts the data of a message, using salsa20. When a message is encrypted using a sequence of calls to salsa20_crypt, all but the last call must use a length that is a multiple of SALSA20_BLOCK_SIZE.

The full salsa20 cipher uses 20 rounds of mixing. Variants of Salsa20 with fewer rounds are possible, and the 12-round variant is specified by eSTREAM, see https://www.ecrypt.eu.org/stream/finallist.html. Nettle calls this variant salsa20r12. It uses the same context struct and key setup as the full salsa20 cipher, but a separate function for encryption and decryption.

Function: void salsa20r12_crypt (struct salsa20_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)

Encrypts or decrypts the data of a message, using salsa20 reduced to 12 rounds.


Next: , Previous: , Up: Cipher functions   [Contents][Index]

7.2.11 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 peculiarity 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 block-size, 16.

Constant: SERPENT_MIN_KEY_SIZE

Minimum 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, size_t 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, size_t length, uint8_t *dst, const 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, size_t length, uint8_t *dst, const uint8_t *src)

Analogous to serpent_encrypt


Next: , Previous: , Up: Cipher functions   [Contents][Index]

7.2.12 SM4

SM4 is a block cipher standard adopted by the government of the People’s Republic of China, and it was issued by the State Cryptography Administration on March 21, 2012. The standard is GM/T 0002-2012 "SM4 block cipher algorithm". Nettle defines it in <nettle/sm4.h>.

Context struct: struct sm4_ctx
Constant: SM4_BLOCK_SIZE

The SM4 block-size, 16.

Constant: SM4_KEY_SIZE

Default SM4 key size, 16.

Function: void sm4_set_encrypt_key (struct sm4_ctx *ctx, const uint8_t *key)

Initialize the cipher. The function is used for encryption.

Function: void sm4_set_decrypt_key (struct sm4_ctx *ctx, const uint8_t *key)

Initialize the cipher. The function is used for decryption.

Function: void sm4_crypt (const struct sm4_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)

Cryption 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. The same function is used for both encryption and decryption.


7.2.13 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 block-size, 16.

Constant: TWOFISH_MIN_KEY_SIZE

Minimum 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, size_t 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, size_t length, uint8_t *dst, const 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, size_t length, uint8_t *dst, const uint8_t *src)

Analogous to twofish_encrypt


Previous: , Up: Cipher functions   [Contents][Index]

7.2.14 The struct nettle_cipher abstraction

Nettle includes a struct including information about some of the more regular cipher functions. It 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_cipher_func *. The first argument to these functions is a const 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_arctwo40
Constant Struct: struct nettle_cipher nettle_arctwo64
Constant Struct: struct nettle_cipher nettle_arctwo128
Constant Struct: struct nettle_cipher nettle_arctwo_gutmann128
Constant Struct: struct nettle_cipher nettle_arcfour128
Constant Struct: struct nettle_cipher nettle_camellia128
Constant Struct: struct nettle_cipher nettle_camellia192
Constant Struct: struct nettle_cipher nettle_camellia256
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 oddities.

Nettle also exports a list of all these ciphers without weak keys or other oddities.

Function: const struct nettle_cipher ** nettle_get_ciphers (void)

Returns a NULL-terminated list of pointers to supported block ciphers. This list can be used to dynamically enumerate or search the supported algorithms.

Macro: nettle_ciphers

A macro expanding to a call to nettle_get_ciphers. In earlier versions, this was not a macro but the actual array of pointers.


7.3 Cipher modes

Cipher modes of operation specifies the procedure to use when encrypting a message that is larger than the cipher’s block size. As explained in See Cipher functions, splitting the message into blocks and processing them independently with the block cipher (Electronic Code Book mode, ECB), leaks information.

Besides ECB, Nettle provides several other modes of operation: Cipher Block Chaining (CBC), Counter mode (CTR), Cipher Feedback (CFB and CFB8), XEX-based tweaked-codebook mode with ciphertext stealing (XTS) and a couple of AEAD modes (see Authenticated encryption with associated data). CBC is widely used, but there are a few subtle issues of information leakage, see, e.g., SSH CBC vulnerability. Today, CTR is usually preferred over CBC.

Modes like CBC, CTR, CFB and CFB8 provide no message authentication, and should always be used together with a MAC (see Keyed Hash Functions) or signature to authenticate the message.


7.3.1 Cipher Block Chaining

When using CBC mode, plaintext 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 XORed with the plaintext 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 block cipher, and IV is the initialization vector, then n plaintext 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 provides two main functions for applying a block cipher in Cipher Block Chaining (CBC) mode, one for encryption and one for decryption. These functions uses const void * to pass cipher contexts around. The CBC interface is defined in <nettle/cbc.h>.

Function: void cbc_encrypt (const void *ctx, nettle_cipher_func *f, size_t block_size, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src)
Function: void cbc_decrypt (const void *ctx, nettle_cipher_func *f, size_t block_size, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src)

Applies the encryption or decryption function f in CBC mode. The final ciphertext block processed is copied into iv before returning, so that a large message can be processed by a sequence of calls to cbc_encrypt. The function f is of type

void f (const void *ctx, size_t length, uint8_t dst, const uint8_t *src),

and the cbc_encrypt and cbc_decrypt functions pass their argument ctx on to f.

7.3.1.1 Utility macros

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

Macro: CBC_CTX (context_type, block_size)

Expands to

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

7.3.1.2 Cipher-specific functions

Encryption in CBC mode (but not decryption!) is inherently serial. It can pass only one block at a time to the block cipher’s encrypt function. Optimizations to process several blocks in parallel can’t be applied, and on platforms where the underlying cipher is fast, per-function-call overhead, e.g., loading subkeys from memory into registers, can be significant. Depending on platform and cipher used, cbc_encrypt can be considerably slower than both cbc_decrypt and CTR mode. The second reason for poor performance can be addressed by having a combined CBC and encrypt function, for ciphers where the overhead is significant.

Nettle currently includes such special functions only for AES.

Function: void cbc_aes128_encrypt (const struct aes128_ctx *ctx, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src)
Function: void cbc_aes192_encrypt (const struct aes192_ctx *ctx, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src)
Function: void cbc_aes256_encrypt (const struct aes256_ctx *ctx, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src)

Calling cbc_aes128_encrypt(ctx, iv, length, dst, src) does the same thing as calling cbc_encrypt(ctx, aes128_encrypt, AES_BLOCK_SIZE, iv, length, dst, src), but is more efficient on certain platforms.


7.3.2 Counter mode

Counter mode (CTR) 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 n blocks M_1,… M_n, where M_n is of size 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 E_k is the encryption function of a block cipher, IC is the initial counter, then the n plaintext blocks are transformed into n ciphertext blocks C_1,… C_n as follows:

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

…

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

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

Function: void ctr_crypt (const void *ctx, nettle_cipher_func *f, size_t block_size, uint8_t *ctr, size_t length, uint8_t *dst, const uint8_t *src)

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

When a message is encrypted using a sequence of calls to ctr_crypt, all but the last call must use a length that is a multiple of the block size.

Like for CBC, there are also a couple of helper macros.

Macro: CTR_CTX (context_type, block_size)

Expands to

{
   context_type ctx;
   uint8_t ctr[block_size];
}
Macro: CTR_SET_COUNTER (ctx, iv)

First argument is a pointer to a context struct as defined by CTR_CTX, and the second is a pointer to an initial counter that is copied into that context.

Macro: CTR_CRYPT (ctx, f, length, dst, src)

A simpler way to invoke ctr_crypt. The first argument is a pointer to a context struct as defined by 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.


7.3.3 Cipher Feedback mode

Cipher Feedback mode (CFB) and Cipher Feedback 8-bit mode (CFB8) being close relatives to both CBC mode and CTR mode borrow some characteristics from stream ciphers.

For CFB the message is divided into n blocks M_1,… M_n, where M_n is of size 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 E_k is the encryption function of a block cipher, IV is the initialization vector, then the n plaintext blocks 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-1) = E_k(C_(n - 2)) XOR M_(n-1)
C_n = E_k(C_(n - 1)) [1..m] XOR M_n

Cipher Feedback 8-bit mode (CFB8) transforms block cipher into a stream cipher. The message is encrypted byte after byte, not requiring any padding.

If E_k is the encryption function of a block cipher, b is E_k block size, IV is the initialization vector, then the n plaintext bytes are transformed into n ciphertext bytes C_1,… C_n as follows:

I_1 = IV
C_1 = E_k(I_1) [1..8] XOR M_1
I_2 = I_1 [9..b] << 8 | C_1
C_2 = E_k(I_2) [1..8] XOR M_2

…

I_(n-1) = I_(n-2) [9..b] << 8 | C_(n-2)
C_(n-1) = E_k(I_(n-1)) [1..8] XOR M_(n-1)
I_n = I_(n-1) [9..b] << 8 | C_(n-1)
C_n = E_k(I_n) [1..8] XOR M_n

Nettle’s includes functions for applying a block cipher in Cipher Feedback (CFB) and Cipher Feedback 8-bit (CFB8) modes. These functions uses void * to pass cipher contexts around.

Function: void cfb_encrypt (const void *ctx, nettle_cipher_func *f, size_t block_size, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src)
Function: void cfb_decrypt (const void *ctx, nettle_cipher_func *f, size_t block_size, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src)

Applies the encryption or decryption function f in CFB mode. The final ciphertext block processed is copied into iv before returning, so that a large message can be processed by a sequence of calls to cfb_encrypt. Note that for CFB mode internally uses encryption only function and hence f should always be the encryption function for the underlying block cipher.

When a message is encrypted using a sequence of calls to cfb_encrypt, all but the last call must use a length that is a multiple of the block size.

Function: void cfb8_encrypt (const void *ctx, nettle_cipher_func *f, size_t block_size, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src)
Function: void cfb8_decrypt (const void *ctx, nettle_cipher_func *f, size_t block_size, uint8_t *iv, size_t length, uint8_t *dst, const uint8_t *src)

Applies the encryption or decryption function f in CFB8 mode. The final IV block processed is copied into iv before returning, so that a large message can be processed by a sequence of calls to cfb8_encrypt. Note that for CFB8 mode internally uses encryption only function and hence f should always be the encryption function for the underlying block cipher.

Like for CBC, there are also a couple of helper macros.

Macro: CFB_CTX (context_type, block_size)

Expands to

{
   context_type ctx;
   uint8_t iv[block_size];
}
Macro: CFB_SET_IV(ctx, iv)

First argument is a pointer to a context struct as defined by CFB_CTX, and the second is a pointer to an initialization vector that is copied into that context.

Macro: CFB_ENCRYPT (ctx, f, length, dst, src)

A simpler way to invoke cfb_encrypt. The first argument is a pointer to a context struct as defined by CFB_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.

Macro: CFB_DECRYPT (ctx, f, length, dst, src)

A simpler way to invoke cfb_decrypt. The first argument is a pointer to a context struct as defined by CFB_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.

Macro: CFB8_CTX (context_type, block_size)

Expands to

{
   context_type ctx;
   uint8_t iv[block_size];
}
Macro: CFB8_SET_IV (ctx, iv)

First argument is a pointer to a context struct as defined by CFB8_CTX, and the second is a pointer to an initialization vector that is copied into that context.

Macro: CFB8_ENCRYPT (ctx, f, length, dst, src)

A simpler way to invoke cfb8_encrypt. The first argument is a pointer to a context struct as defined by CFB8_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.

Macro: CFB8_DECRYPT (ctx, f, length, dst, src)

A simpler way to invoke cfb8_decrypt. The first argument is a pointer to a context struct as defined by CFB8_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.


7.3.4 XEX-based tweaked-codebook mode with ciphertext stealing

XEX-based tweaked-codebook mode with ciphertext stealing (XTS) is a block mode like (CBC) but tweaked to be able to encrypt partial blocks via a technique called ciphertext stealing, where the last complete block of ciphertext is split and part returned as the last block and part used as plaintext for the second to last block. This mode is principally used to encrypt data at rest where it is not possible to store additional metadata or blocks larger than the plain text. The most common usage is for disk encryption. Due to the fact that ciphertext expansion is not possible, data is not authenticated. This mode should not be used where authentication is critical.

The message is divided into n blocks M_1,… M_n, where M_n is of size m which may be smaller than the block size. XTS always uses a fixed blocksize of 128 bit (16 bytes) length.

Unlike other modes, the key is double the size of that for the used cipher mode (for example 256bit for AES-128 and 512bit for AES-256).

XTS encryption mode operates given:

  • A multiplication by a primitive element alpha. MUL a^j here represents the multiplication, where j is the power of alpha, and the input value is converted into a 16 bytes array a_0[k], k = 0,1,..,15. The multiplication is calculated as a_(j+1)[0] = (2(a_j[0] mod 128)) XOR (135 * floor(a_j[15]/128) a_(j+1)[k] = (2(a_j[k] mod 128)) XOR (floor(a_j[k-1]/128), k = 1,2,..15 Note that this operation is practically a 1 bit left shift operation with carry propagating from one byte to the next, and if the last bit shift results in a carry the decimal value 135 is XORed into the first byte.
  • The encryption key is provided as the Key = K1 | K2, where | denotes string concatenation. E_k1 is the encryption function of the block cipher using K1 as the key, and E_k2 is the same encryption function using K2
  • A 128 bit tweak value is provided as input and is denoted as IV

The n plaintext blocks are transformed into n ciphertext blocks C_1,… C_n as follows.

For a plaintext length that is a perfect multiple of the XTS block size:

T_1 = E_k2(IV)
C_1 = E_k1(P_1 XOR T_1) XOR T_1

…

T_n = T_(n-1) MUL a
C_n = E_k1(P_n XOR T_n) XOR T_n

For any other plaintext lengths:

T_1 = E_k2(IV)
C_1 = E_k1(P_1 XOR T_1) XOR T_1

…

T_(n-2) = T_(n-3) MUL a
C_(n-2) = E_k1(P_(n-2) XOR T_(n-2)) XOR T_(n-2)

T_(n-1) = T_(n-2) MUL a
CC_(n-1) = E_k1(P_(n-1) XOR T_(n-1)) XOR T_(n-1)

T_n = T_(n-1) MUL a
PP = [1..m]Pn | [m+1..128]CC_(n-1)
C_(n-1) = E_k1(PP XOR T_n) XOR T_n

C_n = [1..m]CC_(n-1)

7.3.4.1 General (XTS) interface.

The two general functions to encrypt and decrypt using the XTS block cipher mode are the following:

Function: void xts_encrypt_message (const void *enc_ctx, const void *twk_ctx, nettle_cipher_func *encf, const uint8_t *tweak, size_t length, uint8_t *dst, const uint8_t *src)
Function: void xts_decrypt_message (const void *dec_ctx, const void *twk_ctx, nettle_cipher_func *decf, nettle_cipher_func *encf, const uint8_t *tweak, size_t length, uint8_t *dst, const uint8_t *src)

Applies the encryption function encf or the decryption function decf in XTS mode. At least one block (16 bytes) worth of data must be available therefore specifying a length less than 16 bytes is illegal.

The functions encf decf are of type

void f (const void *ctx, size_t length, uint8_t *dst, const uint8_t *src),

and the xts_encrypt_message and xts_decrypt_message functions pass their arguments enc_ctx, twk_ctx and dec_ctx to the functions encf, decf as ctx.

7.3.4.2 XTS-AES interface

The AES XTS functions provide an API for using the XTS mode with the AES block ciphers. The parameters all have the same meaning as the general interface, except that the enc_ctx, dec_ctx, twk_ctx, encf and decf are replaced with an AES context structure called ctx, and a appropriate set-key function must be called before using any of the encryption or decryption functions in this interface.

Context struct: struct xts_aes128_key

Holds state corresponding to the AES-128 block cipher.

Context struct: struct xts_aes256_key

Holds state corresponding to the AES-256 block cipher.

Function: void xts_aes128_set_encrypt_key (struct xts_aes128_key *ctx, const uint8_t *key)
Function: void xts_aes256_set_encrypt_key (struct xts_aes256_key *ctx, const uint8_t *key)
Function: void xts_aes128_set_decrypt_key (struct xts_aes128_key *ctx, const uint8_t *key)
Function: void xts_aes256_set_decrypt_key (struct xts_aes256_key *ctx, const uint8_t *key)

Initializes the encryption or decryption key for the AES block cipher. The length of the key must be double the size of the key for the corresponding cipher (256 bits for AES-128 and 512 bits for AES-256). One of these functions must be called before any of the other functions.

Function: void xts_aes128_encrypt_message (struct xts_aes128_key *ctx, uint8_t *tweak, size_t length, uint8_t *dst, const uint8_t *src)
Function: void xts_aes256_encrypt_message (struct xts_aes256_key *ctx, uint8_t *tweak, size_t length, uint8_t *dst, const uint8_t *src)
Function: void xts_aes128_decrypt_message (struct xts_aes128_key *ctx, uint8_t *tweak, size_t length, uint8_t *dst, const uint8_t *src)
Function: void xts_aes256_decrypt_message (struct xts_aes256_key *ctx, uint8_t *tweak, size_t length, uint8_t *dst, const uint8_t *src)

These are identical to xts_encrypt_message and xts_decrypt_message, except that enc_ctx, dec_ctx, twk_ctx, encf and decf are replaced by the ctx context structure.


7.4 Authenticated encryption with associated data

Since there are some subtle design choices to be made when combining a block cipher mode with out authentication with a MAC. In recent years, several constructions that combine encryption and authentication have been defined. These constructions typically also have an additional input, the “associated data”, which is authenticated but not included with the message. A simple example is an implicit message number which is available at both sender and receiver, and which needs authentication in order to detect deletions or replay of messages. This family of building blocks are therefore called AEAD, Authenticated encryption with associated data.

The aim is to provide building blocks that it is easier for designers of protocols and applications to use correctly. There is also some potential for improved performance, if encryption and authentication can be done in a single step, although that potential is not realized for the constructions currently supported by Nettle.

For encryption, the inputs are:

  • The key, which can be used for many messages.
  • A nonce, which must be unique for each message using the same key.
  • Additional associated data to be authenticated, but not included in the message.
  • The cleartext message to be encrypted.

The outputs are:

  • The ciphertext, of the same size as the cleartext.
  • A digest or “authentication tag”.

Decryption works the same, but with cleartext and ciphertext interchanged. All currently supported AEAD algorithms always use the encryption function of the underlying block cipher, for both encryption and decryption.

Usually, the authentication tag should be appended at the end of the ciphertext, producing an encrypted message which is slightly longer than the cleartext. However, Nettle’s low level AEAD functions produce the authentication tag as a separate output for both encryption and decryption.

Both associated data and the message data (cleartext or ciphertext) can be processed incrementally. In general, all associated data must be processed before the message data, and all calls but the last one must use a length that is a multiple of the block size, although some AEAD may implement more liberal conventions. The CCM mode is a bit special in that it requires the message lengths up front, other AEAD constructions don’t have this restriction.

The supported AEAD constructions are Galois/Counter mode (GCM), EAX, ChaCha-Poly1305, and Counter with CBC-MAC (CCM). There are some weaknesses in GCM authentication, see https://csrc.nist.gov/groups/ST/toolkit/BCM/documents/comments/CWC-GCM/Ferguson2.pdf. CCM and EAX use the same building blocks, but the EAX design is cleaner and avoids a couple of inconveniences of CCM. Therefore, EAX seems like a good conservative choice. The more recent ChaCha-Poly1305 may also be an attractive but more adventurous alternative, in particular if performance is important.


7.4.1 EAX

The EAX mode is an AEAD mode which combines CTR mode encryption, See Counter mode, with a message authentication based on CBC, See Cipher Block Chaining. The implementation in Nettle is restricted to ciphers with a block size of 128 bits (16 octets). EAX was defined as a reaction to the CCM mode, See Counter with CBC-MAC mode, which uses the same primitives but has some undesirable and inelegant properties.

EAX supports arbitrary nonce size; it’s even possible to use an empty nonce in case only a single message is encrypted for each key.

Nettle’s support for EAX consists of a low-level general interface, some convenience macros, and specific functions for EAX using AES-128 as the underlying cipher. These interfaces are defined in <nettle/eax.h>

7.4.1.1 General EAX interface

Context struct: struct eax_key

EAX state which depends only on the key, but not on the nonce or the message.

Context struct: struct eax_ctx

Holds state corresponding to a particular message.

Constant: EAX_BLOCK_SIZE

EAX’s block size, 16.

Constant: EAX_DIGEST_SIZE

Size of the EAX digest, also 16.

Function: void eax_set_key (struct eax_key *key, const void *cipher, nettle_cipher_func *f)

Initializes key. cipher gives a context struct for the underlying cipher, which must have been previously initialized for encryption, and f is the encryption function.

Function: void eax_set_nonce (struct eax_ctx *eax, const struct eax_key *key, const void *cipher, nettle_cipher_func *f, size_t nonce_length, const uint8_t *nonce)

Initializes ctx for processing a new message, using the given nonce.

Function: void eax_update (struct eax_ctx *eax, const struct eax_key *key, const void *cipher, nettle_cipher_func *f, size_t data_length, const uint8_t *data)

Process associated data for authentication. All but the last call for each message must use a length that is a multiple of the block size. Unlike many other AEAD constructions, for EAX it’s not necessary to complete the processing of all associated data before encrypting or decrypting the message data.

Function: void eax_encrypt (struct eax_ctx *eax, const struct eax_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *dst, const uint8_t *src)
Function: void eax_decrypt (struct eax_ctx *eax, const struct eax_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *dst, const uint8_t *src)

Encrypts or decrypts the data of a message. cipher is the context struct for the underlying cipher and f is the encryption function. All but the last call for each message must use a length that is a multiple of the block size.

Function: void eax_digest (struct eax_ctx *eax, const struct eax_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *digest)

Extracts the message digest (also known “authentication tag”). This is the final operation when processing a message. If length is smaller than EAX_DIGEST_SIZE, only the first length octets of the digest are written.

7.4.1.2 EAX helper macros

The following macros are defined.

Macro: EAX_CTX (context_type)

This defines an all-in-one context struct, including the context of the underlying cipher and all EAX state. It expands to

{
   struct eax_key key;
   struct eax_ctx eax;
   context_type cipher;
}

For all these macros, ctx, is a context struct as defined by EAX_CTX, and encrypt is the encryption function of the underlying cipher.

Macro: EAX_SET_KEY (ctx, set_key, encrypt, key)

set_key is the function for setting the encryption key for the underlying cipher, and key is the key.

Macro: EAX_SET_NONCE (ctx, encrypt, length, nonce)

Sets the nonce to be used for the message.

Macro: EAX_UPDATE (ctx, encrypt, length, data)

Process associated data for authentication.

Macro: EAX_ENCRYPT (ctx, encrypt, length, dst, src)
Macro: EAX_DECRYPT (ctx, encrypt, length, dst, src)

Process message data for encryption or decryption.

Macro: EAX_DIGEST (ctx, encrypt, length, digest)

Extract the authentication tag for the message.

7.4.1.3 EAX-AES128 interface

The following functions implement EAX using AES-128 as the underlying cipher.

Context struct: struct eax_aes128_ctx

The context struct, defined using EAX_CTX.

Function: void eax_aes128_set_key (struct eax_aes128_ctx *ctx, const uint8_t *key)

Initializes ctx using the given key.

Function: void eax_aes128_set_nonce (struct eax_aes128_ctx *ctx, size_t length, const uint8_t *iv)

Initializes the per-message state, using the given nonce.

Function: void eax_aes128_update (struct eax_aes128_ctx *ctx, size_t length, const uint8_t *data)

Process associated data for authentication. All but the last call for each message must use a length that is a multiple of the block size.

Function: void eax_aes128_encrypt (struct eax_aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void eax_aes128_decrypt (struct eax_aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)

Encrypts or decrypts the data of a message. All but the last call for each message must use a length that is a multiple of the block size.

Function: void eax_aes128_digest (struct eax_aes128_ctx *ctx, size_t length, uint8_t *digest)

Extracts the message digest (also known “authentication tag”). This is the final operation when processing a message. If length is smaller than EAX_DIGEST_SIZE, only the first length octets of the digest are written.


7.4.2 Galois counter mode

Galois counter mode is an AEAD constructions combining counter mode with message authentication based on universal hashing. The main objective of the design is to provide high performance for hardware implementations, where other popular MAC algorithms (see Keyed Hash Functions) become a bottleneck for high-speed hardware implementations. It was proposed by David A. McGrew and John Viega in 2005, and recommended by NIST in 2007, NIST Special Publication 800-38D. It is constructed on top of a block cipher which must have a block size of 128 bits.

The authentication in GCM has some known weaknesses, see https://csrc.nist.gov/groups/ST/toolkit/BCM/documents/comments/CWC-GCM/Ferguson2.pdf. In particular, don’t use GCM with short authentication tags.

Nettle’s support for GCM consists of a low-level general interface, some convenience macros, and specific functions for GCM using AES or Camellia as the underlying cipher. These interfaces are defined in <nettle/gcm.h>

7.4.2.1 General GCM interface

Context struct: struct gcm_key

Message independent hash sub-key, and related tables.

Context struct: struct gcm_ctx

Holds state corresponding to a particular message.

Constant: GCM_BLOCK_SIZE

GCM’s block size, 16.

Constant: GCM_DIGEST_SIZE

Size of the GCM digest, also 16.

Constant: GCM_IV_SIZE

Recommended size of the IV, 12. Arbitrary sizes are allowed.

Function: void gcm_set_key (struct gcm_key *key, const void *cipher, nettle_cipher_func *f)

Initializes key. cipher gives a context struct for the underlying cipher, which must have been previously initialized for encryption, and f is the encryption function.

Function: void gcm_set_iv (struct gcm_ctx *ctx, const struct gcm_key *key, size_t length, const uint8_t *iv)

Initializes ctx using the given IV. The key argument is actually needed only if length differs from GCM_IV_SIZE.

Function: void gcm_update (struct gcm_ctx *ctx, const struct gcm_key *key, size_t length, const uint8_t *data)

Provides associated data to be authenticated. If used, must be called before gcm_encrypt or gcm_decrypt. All but the last call for each message must use a length that is a multiple of the block size.

Function: void gcm_encrypt (struct gcm_ctx *ctx, const struct gcm_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *dst, const uint8_t *src)
Function: void gcm_decrypt (struct gcm_ctx *ctx, const struct gcm_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *dst, const uint8_t *src)

Encrypts or decrypts the data of a message. cipher is the context struct for the underlying cipher and f is the encryption function. All but the last call for each message must use a length that is a multiple of the block size.

Function: void gcm_digest (struct gcm_ctx *ctx, const struct gcm_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *digest)

Extracts the message digest (also known “authentication tag”). This is the final operation when processing a message. It’s strongly recommended that length is GCM_DIGEST_SIZE, but if you provide a smaller value, only the first length octets of the digest are written.

To encrypt a message using GCM, first initialize a context for the underlying block cipher with a key to use for encryption. Then call the above functions in the following order: gcm_set_key, gcm_set_iv, gcm_update, gcm_encrypt, gcm_digest. The decryption procedure is analogous, just calling gcm_decrypt instead of gcm_encrypt (note that GCM decryption still uses the encryption function of the underlying block cipher). To process a new message, using the same key, call gcm_set_iv with a new iv.

7.4.2.2 GCM helper macros

The following macros are defined.

Macro: GCM_CTX (context_type)

This defines an all-in-one context struct, including the context of the underlying cipher, the hash sub-key, and the per-message state. It expands to

{
   struct gcm_key key; 
   struct gcm_ctx gcm;
   context_type cipher;
}

Example use:

struct gcm_aes128_ctx GCM_CTX(struct aes128_ctx);

The following macros operate on context structs of this form.

Macro: GCM_SET_KEY (ctx, set_key, encrypt, key)

First argument, ctx, is a context struct as defined by GCM_CTX. set_key and encrypt are functions for setting the encryption key and for encrypting data using the underlying cipher.

Macro: GCM_SET_IV (ctx, length, data)

First argument is a context struct as defined by GCM_CTX. length and data give the initialization vector (IV).

Macro: GCM_UPDATE (ctx, length, data)

Simpler way to call gcm_update. First argument is a context struct as defined by GCM_CTX

Macro: GCM_ENCRYPT (ctx, encrypt, length, dst, src)
Macro: GCM_DECRYPT (ctx, encrypt, length, dst, src)
Macro: GCM_DIGEST (ctx, encrypt, length, digest)

Simpler way to call gcm_encrypt, gcm_decrypt or gcm_digest. First argument is a context struct as defined by GCM_CTX. Second argument, encrypt, is the encryption function of the underlying cipher.

7.4.2.3 GCM-AES interface

The following functions implement the common case of GCM using AES as the underlying cipher. The variants with a specific AES flavor are recommended, while the fucntinos using struct gcm_aes_ctx are kept for compatibility with older versiosn of Nettle.

Context struct: struct gcm_aes128_ctx
Context struct: struct gcm_aes192_ctx
Context struct: struct gcm_aes256_ctx

Context structs, defined using GCM_CTX.

Context struct: struct gcm_aes_ctx

Alternative context struct, using the old AES interface.

Function: void gcm_aes128_set_key (struct gcm_aes128_ctx *ctx, const uint8_t *key)
Function: void gcm_aes192_set_key (struct gcm_aes192_ctx *ctx, const uint8_t *key)
Function: void gcm_aes256_set_key (struct gcm_aes256_ctx *ctx, const uint8_t *key)

Initializes ctx using the given key.

Function: void gcm_aes_set_key (struct gcm_aes_ctx *ctx, size_t length, const uint8_t *key)

Corresponding function, using the old AES interface. All valid AES key sizes can be used.

Function: void gcm_aes128_set_iv (struct gcm_aes128_ctx *ctx, size_t length, const uint8_t *iv)
Function: void gcm_aes192_set_iv (struct gcm_aes192_ctx *ctx, size_t length, const uint8_t *iv)
Function: void gcm_aes256_set_iv (struct gcm_aes256_ctx *ctx, size_t length, const uint8_t *iv)
Function: void gcm_aes_set_iv (struct gcm_aes_ctx *ctx, size_t length, const uint8_t *iv)

Initializes the per-message state, using the given IV.

Function: void gcm_aes128_update (struct gcm_aes128_ctx *ctx, size_t length, const uint8_t *data)
Function: void gcm_aes192_update (struct gcm_aes192_ctx *ctx, size_t length, const uint8_t *data)
Function: void gcm_aes256_update (struct gcm_aes256_ctx *ctx, size_t length, const uint8_t *data)
Function: void gcm_aes_update (struct gcm_aes_ctx *ctx, size_t length, const uint8_t *data)

Provides associated data to be authenticated. If used, must be called before gcm_aes_encrypt or gcm_aes_decrypt. All but the last call for each message must use a length that is a multiple of the block size.

Function: void gcm_aes128_encrypt (struct gcm_aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void gcm_aes192_encrypt (struct gcm_aes192_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void gcm_aes256_encrypt (struct gcm_aes256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void gcm_aes_encrypt (struct gcm_aes_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void gcm_aes128_decrypt (struct gcm_aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void gcm_aes192_decrypt (struct gcm_aes192_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void gcm_aes256_decrypt (struct gcm_aes256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void gcm_aes_decrypt (struct gcm_aes_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)

Encrypts or decrypts the data of a message. All but the last call for each message must use a length that is a multiple of the block size.

Function: void gcm_aes128_digest (struct gcm_aes128_ctx *ctx, size_t length, uint8_t *digest)
Function: void gcm_aes192_digest (struct gcm_aes192_ctx *ctx, size_t length, uint8_t *digest)
Function: void gcm_aes256_digest (struct gcm_aes256_ctx *ctx, size_t length, uint8_t *digest)
Function: void gcm_aes_digest (struct gcm_aes_ctx *ctx, size_t length, uint8_t *digest)

Extracts the message digest (also known “authentication tag”). This is the final operation when processing a message. It’s strongly recommended that length is GCM_DIGEST_SIZE, but if you provide a smaller value, only the first length octets of the digest are written.

7.4.2.4 GCM-Camellia interface

The following functions implement the case of GCM using Camellia as the underlying cipher.

Context struct: struct gcm_camellia128_ctx
Context struct: struct gcm_camellia256_ctx

Context structs, defined using GCM_CTX.

Function: void gcm_camellia128_set_key (struct gcm_camellia128_ctx *ctx, const uint8_t *key)
Function: void gcm_camellia256_set_key (struct gcm_camellia256_ctx *ctx, const uint8_t *key)

Initializes ctx using the given key.

Function: void gcm_camellia128_set_iv (struct gcm_camellia128_ctx *ctx, size_t length, const uint8_t *iv)
Function: void gcm_camellia256_set_iv (struct gcm_camellia256_ctx *ctx, size_t length, const uint8_t *iv)

Initializes the per-message state, using the given IV.

Function: void gcm_camellia128_update (struct gcm_camellia128_ctx *ctx, size_t length, const uint8_t *data)
Function: void gcm_camellia256_update (struct gcm_camellia256_ctx *ctx, size_t length, const uint8_t *data)

Provides associated data to be authenticated. If used, must be called before gcm_camellia_encrypt or gcm_camellia_decrypt. All but the last call for each message must use a length that is a multiple of the block size.

Function: void gcm_camellia128_encrypt (struct gcm_camellia128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void gcm_camellia256_encrypt (struct gcm_camellia256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void gcm_camellia128_decrypt (struct gcm_camellia128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void gcm_camellia256_decrypt (struct gcm_camellia256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)

Encrypts or decrypts the data of a message. All but the last call for each message must use a length that is a multiple of the block size.

Function: void gcm_camellia128_digest (struct gcm_camellia128_ctx *ctx, size_t length, uint8_t *digest)
Function: void gcm_camellia192_digest (struct gcm_camellia192_ctx *ctx, size_t length, uint8_t *digest)
Function: void gcm_camellia256_digest (struct gcm_camellia256_ctx *ctx, size_t length, uint8_t *digest)
Function: void gcm_camellia_digest (struct gcm_camellia_ctx *ctx, size_t length, uint8_t *digest)

Extracts the message digest (also known “authentication tag”). This is the final operation when processing a message. It’s strongly recommended that length is GCM_DIGEST_SIZE, but if you provide a smaller value, only the first length octets of the digest are written.

7.4.2.5 GCM-SM4 interface

The following functions implement the case of GCM using SM4 as the underlying cipher.

Context struct: struct gcm_sm4_ctx

Context structs, defined using GCM_CTX.

Function: void gcm_sm4_set_key (struct gcm_sm4_ctx *ctx, const uint8_t *key)

Initializes ctx using the given key.

Function: void gcm_sm4_set_iv (struct gcm_sm4_ctx *ctx, size_t length, const uint8_t *iv)

Initializes the per-message state, using the given IV.

Function: void gcm_sm4_update (struct gcm_sm4_ctx *ctx, size_t length, const uint8_t *data)

Provides associated data to be authenticated. If used, must be called before gcm_sm4_encrypt or gcm_sm4_decrypt. All but the last call for each message must use a length that is a multiple of the block size.

Function: void gcm_sm4_encrypt (struct gcm_sm4_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void gcm_sm4_decrypt (struct gcm_sm4_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)

Encrypts or decrypts the data of a message. All but the last call for each message must use a length that is a multiple of the block size.

Function: void gcm_sm4_digest (struct gcm_sm4_ctx *ctx, size_t length, uint8_t *digest)

Extracts the message digest (also known “authentication tag”). This is the final operation when processing a message. It’s strongly recommended that length is GCM_DIGEST_SIZE, but if you provide a smaller value, only the first length octets of the digest are written.


7.4.3 Counter with CBC-MAC mode

CCM mode is a combination of counter mode with message authentication based on cipher block chaining, the same building blocks as EAX, see EAX. It is constructed on top of a block cipher which must have a block size of 128 bits. CCM mode is recommended by NIST in NIST Special Publication 800-38C. Nettle’s support for CCM consists of a low-level general interface, a message encryption and authentication interface, and specific functions for CCM using AES as the underlying block cipher. These interfaces are defined in <nettle/ccm.h>.

In CCM, the length of the message must be known before processing. The maximum message size depends on the size of the nonce, since the message size is encoded in a field which must fit in a single block, together with the nonce and a flag byte. E.g., with a nonce size of 12 octets, there are three octets left for encoding the message length, the maximum message length is 2^24 - 1 octets.

CCM mode encryption operates as follows:

  • The nonce and message length are concatenated to create B_0 = flags | nonce | mlength
  • The authenticated data and plaintext is formatted into the string B = L(adata) | adata | padding | plaintext | padding with padding being the shortest string of zero bytes such that the length of the string is a multiple of the block size, and L(adata) is an encoding of the length of adata.
  • The string B is separated into blocks B_1 ... B_n
  • The authentication tag T is calculated as T=0, for i=0 to n, do T = E_k(B_i XOR T)
  • An initial counter is then initialized from the nonce to create IC = flags | nonce | padding, where padding is the shortest string of zero bytes such that IC is exactly one block in length.
  • The authentication tag is encrypted using using CTR mode: MAC = E_k(IC) XOR T
  • The plaintext is then encrypted using CTR mode with an initial counter of IC+1.

CCM mode decryption operates similarly, except that the ciphertext and MAC are first decrypted using CTR mode to retrieve the plaintext and authentication tag. The authentication tag can then be recalculated from the authenticated data and plaintext, and compared to the value in the message to check for authenticity.

7.4.3.1 General CCM interface

For all of the functions in the CCM interface, cipher is the context struct for the underlying cipher and f is the encryption function. The cipher’s encryption key must be set before calling any of the CCM functions. The cipher’s decryption function and key are never used.

Context struct: struct ccm_ctx

Holds state corresponding to a particular message.

Constant: CCM_BLOCK_SIZE

CCM’s block size, 16.

Constant: CCM_DIGEST_SIZE

Size of the CCM digest, 16.

Constant: CCM_MIN_NONCE_SIZE
Constant: CCM_MAX_NONCE_SIZE

The the minimum and maximum sizes for an CCM nonce, 7 and 14, respectively.

Macro: CCM_MAX_MSG_SIZE (nonce_size)

The largest allowed plaintext length, when using CCM with a nonce of the given size.

Function: void ccm_set_nonce (struct ccm_ctx *ctx, const void *cipher, nettle_cipher_func *f, size_t noncelen, const uint8_t *nonce, size_t authlen, size_t msglen, size_t taglen)

Initializes ctx using the given nonce and the sizes of the authenticated data, message, and MAC to be processed.

Function: void ccm_update (struct ccm_ctx *ctx, const void *cipher, nettle_cipher_func *f, size_t length, const uint8_t *data)

Provides associated data to be authenticated. Must be called after ccm_set_nonce, and before ccm_encrypt, ccm_decrypt, or ccm_digest.

Function: void ccm_encrypt (struct ccm_ctx *ctx, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *dst, const uint8_t *src)
Function: void ccm_decrypt (struct ccm_ctx *ctx, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *dst, const uint8_t *src)

Encrypts or decrypts the message data. Must be called after ccm_set_nonce and before ccm_digest. All but the last call for each message must use a length that is a multiple of the block size.

Function: void ccm_digest (struct ccm_ctx *ctx, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *digest)

Extracts the message digest (also known “authentication tag”). This is the final operation when processing a message. length is usually equal to the taglen parameter supplied to ccm_set_nonce, but if you provide a smaller value, only the first length octets of the digest are written.

To encrypt a message using the general CCM interface, set the message nonce and length using ccm_set_nonce and then call ccm_update to generate the digest of any authenticated data. After all of the authenticated data has been digested use ccm_encrypt to encrypt the plaintext. Finally, use ccm_digest to return the encrypted MAC.

To decrypt a message, use ccm_set_nonce and ccm_update the same as you would for encryption, and then call ccm_decrypt to decrypt the ciphertext. After decrypting the ciphertext ccm_digest will return the encrypted MAC which should be identical to the MAC in the received message.

7.4.3.2 CCM message interface

The CCM message fuctions provides a simple interface that will perform authentication and message encryption in a single function call. The length of the cleartext is given by mlength and the length of the ciphertext is given by clength, always exactly tlength bytes longer than the corresponding plaintext. The length argument passed to a function is always the size for the result, clength for the encryption functions, and mlength for the decryption functions.

Function: void ccm_encrypt_message (void *cipher, nettle_cipher_func *f, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t clength, uint8_t *dst, const uint8_t *src)

Computes the message digest from the adata and src parameters, encrypts the plaintext from src, appends the encrypted MAC to ciphertext and outputs it to dst.

Function: int ccm_decrypt_message (void *cipher, nettle_cipher_func *f, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t mlength, uint8_t *dst, const uint8_t *src)

Decrypts the ciphertext from src, outputs the plaintext to dst, recalculates the MAC from adata and the plaintext, and compares it to the final tlength bytes of src. If the values of the received and calculated MACs are equal, this will return 1 indicating a valid and authenticated message. Otherwise, this function will return zero.

7.4.3.3 CCM-AES interface

The AES CCM functions provide an API for using CCM mode with the AES block ciphers. The parameters all have the same meaning as the general and message interfaces, except that the cipher, f, and ctx parameters are replaced with an AES context structure, and a set-key function must be called before using any of the other functions in this interface.

Context struct: struct ccm_aes128_ctx

Holds state corresponding to a particular message encrypted using the AES-128 block cipher.

Context struct: struct ccm_aes192_ctx

Holds state corresponding to a particular message encrypted using the AES-192 block cipher.

Context struct: struct ccm_aes256_ctx

Holds state corresponding to a particular message encrypted using the AES-256 block cipher.

Function: void ccm_aes128_set_key (struct ccm_aes128_ctx *ctx, const uint8_t *key)
Function: void ccm_aes192_set_key (struct ccm_aes192_ctx *ctx, const uint8_t *key)
Function: void ccm_aes256_set_key (struct ccm_aes256_ctx *ctx, const uint8_t *key)

Initializes the encryption key for the AES block cipher. One of these functions must be called before any of the other functions in the AES CCM interface.

Function: void ccm_aes128_set_nonce (struct ccm_aes128_ctx *ctx, size_t noncelen, const uint8_t *nonce, size_t authlen, size_t msglen, size_t taglen)
Function: void ccm_aes192_set_nonce (struct ccm_aes192_ctx *ctx, size_t noncelen, const uint8_t *nonce, size_t authlen, size_t msglen, size_t taglen)
Function: void ccm_aes256_set_nonce (struct ccm_aes256_ctx *ctx, size_t noncelen, const uint8_t *nonce, size_t authlen, size_t msglen, size_t taglen)

These are identical to ccm_set_nonce, except that cipher, f, and ctx are replaced with a context structure.

Function: void ccm_aes128_update (struct ccm_aes128_ctx *ctx, size_t length, const uint8_t *data)
Function: void ccm_aes192_update (struct ccm_aes192_ctx *ctx, size_t length, const uint8_t *data)
Function: void ccm_aes256_update (struct ccm_aes256_ctx *ctx, size_t length, const uint8_t *data)

These are identical to ccm_set_update, except that cipher, f, and ctx are replaced with a context structure.

Function: void ccm_aes128_encrypt (struct ccm_aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void ccm_aes192_encrypt (struct ccm_aes192_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void ccm_aes256_encrypt (struct ccm_aes256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void ccm_aes128_decrypt (struct ccm_aes128_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void ccm_aes192_decrypt (struct ccm_aes192_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void ccm_aes256_decrypt (struct ccm_aes256_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)

These are identical to ccm_set_encrypt and ccm_set_decrypt, except that cipher, f, and ctx are replaced with a context structure.

Function: void ccm_aes128_digest (struct ccm_aes128_ctx *ctx, size_t length, uint8_t *digest)
Function: void ccm_aes192_digest (struct ccm_aes192_ctx *ctx, size_t length, uint8_t *digest)
Function: void ccm_aes256_digest (struct ccm_aes256_ctx *ctx, size_t length, uint8_t *digest)

These are identical to ccm_set_digest, except that cipher, f, and ctx are replaced with a context structure.

Function: void ccm_aes128_encrypt_message (struct ccm_aes128_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t clength, uint8_t *dst, const uint8_t *src)
Function: void ccm_aes192_encrypt_message (struct ccm_aes192_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t clength, uint8_t *dst, const uint8_t *src)
Function: void ccm_aes256_encrypt_message (struct ccm_aes256_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t clength, uint8_t *dst, const uint8_t *src)
Function: int ccm_aes128_decrypt_message (struct ccm_aes128_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t mlength, uint8_t *dst, const uint8_t *src)
Function: int ccm_aes192_decrypt_message (struct ccm_aes192_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t mlength, uint8_t *dst, const uint8_t *src)
Function: int ccm_aes256_decrypt_message (struct ccm_aes256_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t mlength, uint8_t *dst, const uint8_t *src)

These are identical to ccm_encrypt_message and ccm_decrypt_message except that cipher and f are replaced with a context structure.


7.4.4 ChaCha-Poly1305

ChaCha-Poly1305 is a combination of the ChaCha stream cipher and the poly1305 message authentication code (see Poly1305). It originates from the NaCl cryptographic library by D. J. Bernstein et al, which defines a similar construction but with Salsa20 instead of ChaCha.

Nettle’s implementation of ChaCha-Poly1305 follows RFC 8439, where the ChaCha cipher is initialized with a 12-byte nonce and a 4-byte block counter. This allows up to 256 gigabytes of data to be encrypted using the same key and nonce.

For ChaCha-Poly1305, the ChaCha cipher is initialized with a key, of 256 bits, and a per-message nonce. The first block of the key stream (counter all zero) is set aside for the authentication subkeys. Of this 64-octet block, the first 16 octets specify the poly1305 evaluation point, and the next 16 bytes specify the value to add in for the final digest. The final 32 bytes of this block are unused. Note that unlike poly1305-aes, the evaluation point depends on the nonce. This is preferable, because it leaks less information in case the attacker for some reason is lucky enough to forge a valid authentication tag, and observe (from the receiver’s behaviour) that the forgery succeeded.

The ChaCha key stream, starting with counter value 1, is then used to encrypt the message. For authentication, poly1305 is applied to the concatenation of the associated data, the cryptotext, and the lengths of the associated data and the message, each a 64-bit number (eight octets, little-endian). Nettle defines ChaCha-Poly1305 in <nettle/chacha-poly1305.h>.

Constant: CHACHA_POLY1305_BLOCK_SIZE

Same as the ChaCha block size, 64.

Constant: CHACHA_POLY1305_KEY_SIZE

ChaCha-Poly1305 key size, 32.

Constant: CHACHA_POLY1305_NONCE_SIZE

ChaCha-Poly1305 nonce size, 12.

Constant: CHACHA_POLY1305_DIGEST_SIZE

Digest size, 16.

Context struct: struct chacha_poly1305_ctx
Function: void chacha_poly1305_set_key (struct chacha_poly1305_ctx *ctx, const uint8_t *key)

Initializes ctx using the given key. Before using the context, you must also call chacha_poly1305_set_nonce, see below.

Function: void chacha_poly1305_set_nonce (struct chacha_poly1305_ctx *ctx, const uint8_t *nonce)

Initializes the per-message state, using the given nonce.

Function: void chacha_poly1305_update (struct chacha_poly1305_ctx *ctx, size_t length, const uint8_t *data)

Process associated data for authentication.

Function: void chacha_poly1305_encrypt (struct chacha_poly1305_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)
Function: void chacha_poly1305_decrypt (struct chacha_poly1305_ctx *ctx, size_t length, uint8_t *dst, const uint8_t *src)

Encrypts or decrypts the data of a message. All but the last call for each message must use a length that is a multiple of the block size.

Function: void chacha_poly1305_digest (struct chacha_poly1305_ctx *ctx, size_t length, uint8_t *digest)

Extracts the message digest (also known “authentication tag”). This is the final operation when processing a message. If length is smaller than CHACHA_POLY1305_DIGEST_SIZE, only the first length octets of the digest are written.


7.4.5 OCB (Offset Code Book) Mode

The OCB mode is an AEAD construction, featuring particularly fast and simple authentication; it needs one block cipher operation per data block, and almost free authentication. It is constructed on top of a block cipher which must have a block size of 128 bits.

There have been several versions of the OCB scheme, the implementation in Nettle follows RFC 7253, which is almost the same as the scheme OCB3.

7.4.5.1 General interface

Context struct: struct ocb_key

OCB state which depends only on the key, but not on the nonce or the message.

Context struct: struct ocb_ctx

Holds state corresponding to a particular message.

Constant: OCB_BLOCK_SIZE

The block size for OCB’s block size, 16.

Constant: OCB_MAX_NONCE_SIZE

The maximum nonce size for OCB, 15.

Constant: OCB_DIGEST_SIZE

Size of the OCB authentication tag.

Function: void ocb_set_key (struct ocb_key *key, const void *cipher, nettle_cipher_func *f)

Initializes the key struct. The cipher context must be initialized for encryption, and f should be the corresponding encryption function.

Function: void ocb_set_nonce (struct ocb_ctx *ctx, const void *cipher, nettle_cipher_func *f, size_t tag_length, size_t nonce_length, const uint8_t *nonce)

Initializes ctx for processing a new message, using the given nonce. The cipher must be initialized for encryption, and f should be the corresponding encryption function. The tag_length (non-zero, and at most 16) is included when initializing the state, and should be the same value later passed to ocb_digest. Nonce is optional, and length at most 15 bytes.

Function: void ocb_update (struct ocb_ctx *ctx, const struct ocb_key *key, const void *cipher, nettle_cipher_func *f, size_t length, const uint8_t *data)

Process associated data for authentication. All but the last call for each message must use a length that is a multiple of the block size.

Function: void ocb_encrypt (struct ocb_ctx *ctx, const struct ocb_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *dst, const uint8_t *src)

Encrypts the data of a message. cipher is the context struct for the underlying cipher and f is the encryption function. All but the last call for each message must use a length that is a multiple of the block size.

Function: void ocb_decrypt (struct ocb_ctx *ctx, const struct ocb_key *key, const void *encrypt_ctx, nettle_cipher_func *encrypt, const void *decrypt_ctx, nettle_cipher_func *decrypt, size_t length, uint8_t *dst, const uint8_t *src)

Decrypts the data of a message. encrypt_ctx and encrypt define the encryption operation of the underlying cipher, while decrypt_ctx and decrypt represent the decryption operation (for some ciphers, one of context pointer and function pointer may be the same). All but the last call for each message must use a length that is a multiple of the block size.

Function: void ocb_digest (const struct ocb_ctx *ctx, const struct ocb_key *key, const void *cipher, nettle_cipher_func *f, size_t length, uint8_t *digest)

Extracts the message digest (also known “authentication tag”). This is the final operation when processing a message. The length value should be the same as the tag length passed to the preceding ocb_set_nonce call (using a different length is possible, but incompatible with RFC 7253).

Function: void ocb_encrypt_message (const struct ocb_key *ocb_key, const void *cipher, nettle_cipher_func *f, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t clength, uint8_t *dst, const uint8_t *src)

Computes the message digest from the adata and src parameters, encrypts the plaintext from src, appends the tag to the ciphertext and writes it to dst. The clength variable must be equal to the length of src plus tlength.

Function: int ocb_decrypt_message (const struct ocb_key *ocb_key, const void *encrypt_ctx, nettle_cipher_func *encrypt, const void *decrypt_ctx, nettle_cipher_func *decrypt, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t mlength, uint8_t *dst, const uint8_t *src)

Decrypts the ciphertext from src, outputs the plaintext to dst. Like ocb_decrypt, it needs both the encrypt and the decrypt function of the underlying cipher. It also recalculates the authentication tag from adata and the plaintext, and compares it to the final tlength bytes of src. If the values of the received and calculated tags are equal, this will return 1 indicating a valid and authenticated message. Otherwise, this function will return zero.

7.4.5.2 OCB-AES interface

Context struct: struct ocb_aes128_encrypt_key

Key-dependent state for encryption using OCB-AES128. For decryption, a separate struct aes128_ctx, initialized for decryption, is needed as well.

Function: void ocb_aes128_set_encrypt_key (struct ocb_aes128_encrypt_key *ocb, const uint8_t *key)

Initializes ocb and the underlying AES cipher with the given key.

Function: void ocb_aes128_set_decrypt_key (struct ocb_aes128_encrypt_key *ocb, struct aes128_ctx *decrypt, const uint8_t *key)

Initializes ocb and the underlying AES cipher with the given key. In addition, initialize decrypt for decryption using the same key; this is needed for ocb_aes128_decrypt and ocb_aes128_decrypt_message.

Function: void ocb_aes128_set_nonce (struct ocb_ctx *ctx, const struct ocb_aes128_encrypt_key *key, size_t tag_length, size_t nonce_length, const uint8_t *nonce)

Initializes ctx for processing a new message, using the given nonce and key. The tag_length (non-zero, and at most 16) is included when initializing the state, and should be the same value later passed to ocb_digest. Nonce is optional, and length at most 15 bytes.

Function: void ocb_aes128_update (struct ocb_ctx *ctx, const struct ocb_aes128_encrypt_key *key, size_t length, const uint8_t *data)

Process associated data for authentication. All but the last call for each message must use a length that is a multiple of the block size.

Function: void ocb_aes128_encrypt (struct ocb_ctx *ctx, const struct ocb_aes128_encrypt_key *key, size_t length, uint8_t *dst, const uint8_t *src)

Encrypts the data of a message. All but the last call for each message must use a length that is a multiple of the block size.

Function: void ocb_aes128_decrypt (struct ocb_ctx *ctx, const struct ocb_aes128_encrypt_key *key, const struct aes128_ctx *decrypt, size_t length, uint8_t *dst, const uint8_t *src)

Decrypts the data of a message. decrypt is an AES context initialized for decryption using the same key. All but the last call for each message must use a length that is a multiple of the block size.

Function: void ocb_aes128_digest (struct ocb_ctx *ctx, const struct ocb_aes128_encrypt_key *key, size_t length, uint8_t *digest)

Extracts the message digest (also known “authentication tag”). This is the final operation when processing a message. The length value should be the same as the tag length passed to the preceding ocb_aes128_set_nonce call (using a different length is possible, but incompatible with RFC 7253).

Function: void ocb_aes128_encrypt_message (const struct ocb_aes128_encrypt_key *key, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t clength, uint8_t *dst, const uint8_t *src)

Computes the message digest from the adata and src parameters, encrypts the plaintext from src, appends the tag to the ciphertext and writes it to dst. The clength variable must be equal to the length of src plus tlength.

Function: int ocb_aes128_decrypt_message (const struct ocb_aes128_encrypt_key *key, const struct aes128_ctx *decrypt, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t tlength, size_t mlength, uint8_t *dst, const uint8_t *src)

Decrypts the ciphertext from src, outputs the plaintext to dst. Like ocb_aes128_decrypt, it needs an AES context initialized for decryption using the same key. It also recalculates the authentication tag from adata and the plaintext, and compares it to the final tlength bytes of src. If the values of the received and calculated tags are equal, this will return 1 indicating a valid and authenticated message. Otherwise, this function will return zero.


7.4.6 Synthetic Initialization Vector AEAD

SIV-CMAC mode is a combination of counter mode with message authentication based on CMAC. Unlike other counter AEAD modes, it provides protection against accidental nonce misuse, making it a good choice for stateless-servers that cannot ensure nonce uniqueness. It is constructed on top of a block cipher which must have a block size of 128 bits. Nettle’s support for SIV-CMAC consists of a message encryption and authentication interface, for SIV-CMAC using AES as the underlying block cipher. When a nonce is re-used with this mode, message authenticity is retained however an attacker can determine whether the same plaintext was protected with the two messages sharing the nonce. These interfaces are defined in <nettle/siv-cmac.h>.

Unlike other AEAD mode in SIV-CMAC the initialization vector serves as the tag. That means that in the generated ciphertext the tag precedes the ciphertext.

Note also, that the SIV-CMAC algorithm, as specified in RFC 5297, introduces the notion of authenticated data which consist of multiple components. For example with SIV-CMAC the authentication tag of data X followed by Y, is different than the concatenated data X || Y. The interfaces described below follow the AEAD paradigm and do not allow access to this feature and also require the use of a non-empty nonce. In the terminology of the RFC, the input to the S2V function is always a vector of three elements, where S1 is the authenticated data, S2 is the nonce, and S3 is the plaintext.

7.4.6.1 General interface

Constant: SIV_BLOCK_SIZE

SIV-CMAC’s block size, 16.

Constant: SIV_DIGEST_SIZE

Size of the SIV-CMAC digest or initialization vector, 16.

Constant: SIV_MIN_NONCE_SIZE

The the minimum size for an SIV-CMAC nonce, 1.

7.4.6.2 SIV-CMAC-AES interface

The AES SIV-CMAC functions provide an API for using SIV-CMAC mode with the AES block ciphers. The parameters all have the same meaning as the general and message interfaces, except that the cipher, f, and ctx parameters are replaced with an AES context structure, and a set-key function must be called before using any of the other functions in this interface.

Context struct: struct siv_cmac_aes128_ctx

Holds state corresponding to a particular message encrypted using the AES-128 block cipher.

Context struct: struct siv_cmac_aes256_ctx

Holds state corresponding to a particular message encrypted using the AES-256 block cipher.

Function: void siv_cmac_aes128_set_key (struct siv_cmac_aes128_ctx *ctx, const uint8_t *key)
Function: void siv_cmac_aes256_set_key (struct siv_cmac_aes256_ctx *ctx, const uint8_t *key)

Initializes the encryption key for the AES block cipher. One of these functions must be called before any of the other functions in the AES SIV-CMAC interface.

Function: void siv_cmac_aes128_encrypt_message (struct siv_cmac_aes128_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t clength, uint8_t *dst, const uint8_t *src)
Function: void siv_cmac_aes256_encrypt_message (struct siv_cmac_aes256_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t clength, uint8_t *dst, const uint8_t *src)

Computes the message digest from the adata and src parameters, encrypts the plaintext from src, prepends the initialization vector to the ciphertext and outputs it to dst. The clength variable must be equal to the length of src plus SIV_DIGEST_SIZE.

Function: int siv_cmac_aes128_decrypt_message (struct siv_cmac_aes128_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t mlength, uint8_t *dst, const uint8_t *src)
Function: int siv_cmac_aes256_decrypt_message (struct siv_cmac_aes128_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t mlength, uint8_t *dst, const uint8_t *src)

Decrypts the ciphertext from src, outputs the plaintext to dst, recalculates the initialization vector from adata and the plaintext. If the values of the received and calculated initialization vector are equal, this will return 1 indicating a valid and authenticated message. Otherwise, this function will return zero.


7.4.7 SIV-GCM

SIV-GCM, described in RFC 8452, is an AEAD construction similar to AES-GCM, but provides protection against accidental nonce misuse like SIV-CMAC mode.

It is constructed on top of a block cipher which must have a block size of 128 bits and a nonce size of 12 bytes. Nettle’s support for SIV-GCM consists of a message encryption and authentication interface, for SIV-GCM using AES as the underlying block cipher. These interfaces are defined in <nettle/siv-gcm.h>.

Unlike other AEAD mode in SIV-GCM the tag is calculated over the encoded additional authentication data and plaintext instead of the ciphertext.

7.4.7.1 General interface

Constant: SIV_GCM_BLOCK_SIZE

SIV-GCM’s block size, 16.

Constant: SIV_GCM_DIGEST_SIZE

Size of the SIV-GCM digest for tags, 16.

Constant: SIV_GCM_NONCE_SIZE

Size of the SIV-GCM nonce, 12.

Function: void siv_gcm_encrypt_message (const struct nettle_cipher *nc, const void *ctx, void *ctr_ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t clength, uint8_t *dst, const uint8_t *src)

Computes the message digest from the adata and src parameters, encrypts the plaintext from src, appends the authentication tag to the ciphertext and outputs it to dst. The clength variable must be equal to the length of src plus SIV_GCM_DIGEST_SIZE.

Function: int siv_gcm_decrypt_message (const struct nettle_cipher *nc, const void *ctx, void *ctr_ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t mlength, uint8_t *dst, const uint8_t *src)

Decrypts the ciphertext from src, outputs the plaintext to dst, recalculates the initialization vector from adata and the plaintext. If the values of the received and calculated initialization vector are equal, this will return 1 indicating a valid and authenticated message. Otherwise, this function will return zero.

In the above interface, nc must point to a cipher that works with 16-byte block size and the key sizes that are multiple of 8-bytes. The ctx context structure must be initialized for encryption mode using a set-key function, before using any of the functions in this interface. While the ctr_ctx context structure must have the same size as ctx, it does not need to be initialized before calling those functions as it is used as working storage. These structures can point to the same area; in that case the contents of *ctx is destroyed by the call.

For convenience, Nettle provides wrapper functions that works with AES described in the following section.

7.4.7.2 SIV-GCM-AES interface

The SIV-GCM functions provide an API for using SIV-GCM mode with the AES block ciphers. The parameters all have the same meaning as the general and message interfaces, except that the cipher, f, and ctx parameters are replaced with an AES context structure. The AES context structure must be initialized for encryption mode using a set-key function, before using any of the functions in this interface.

Function: void siv_gcm_aes128_encrypt_message (const struct aes128_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t clength, uint8_t *dst, const uint8_t *src)
Function: void siv_gcm_aes256_encrypt_message (const struct aes256_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t clength, uint8_t *dst, const uint8_t *src)

Computes the message digest from the adata and src parameters, encrypts the plaintext from src, appends the authentication tag to the ciphertext and outputs it to dst. The clength variable must be equal to the length of src plus SIV_GCM_DIGEST_SIZE.

Function: int siv_gcm_aes128_decrypt_message (const struct aes128_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t mlength, uint8_t *dst, const uint8_t *src)
Function: int siv_gcm_aes256_decrypt_message (const struct aes256_ctx *ctx, size_t nlength, const uint8_t *nonce, size_t alength, const uint8_t *adata, size_t mlength, uint8_t *dst, const uint8_t *src)

Decrypts the ciphertext from src, outputs the plaintext to dst, recalculates the initialization vector from adata and the plaintext. If the values of the received and calculated initialization vector are equal, this will return 1 indicating a valid and authenticated message. Otherwise, this function will return zero.


7.4.8 The struct nettle_aead abstraction

Nettle includes a struct including information about the supported hash functions. It is defined in <nettle/nettle-meta.h>.

Meta struct: struct nettle_aead name context_size block_size key_size nonce_size digest_size set_encrypt_key set_decrypt_key set_nonce update encrypt decrypt digest

The last seven attributes are function pointers.

Constant Struct: struct nettle_aead nettle_gcm_aes128
Constant Struct: struct nettle_aead nettle_gcm_aes192
Constant Struct: struct nettle_aead nettle_gcm_aes256
Constant Struct: struct nettle_aead nettle_gcm_camellia128
Constant Struct: struct nettle_aead nettle_gcm_camellia256
Constant Struct: struct nettle_aead nettle_eax_aes128
Constant Struct: struct nettle_aead nettle_chacha_poly1305

These are most of the AEAD constructions that Nettle implements. Note that CCM is missing; it requirement that the message size is specified in advance makes it incompatible with the nettle_aead abstraction.

Nettle also exports a list of all these constructions.

Function: const struct nettle_aead ** nettle_get_aeads (void)

Returns a NULL-terminated list of pointers to supported algorithms.This list can be used to dynamically enumerate or search the supported algorithms.

Macro: nettle_aeads

A macro expanding to a call to nettle_get_aeads. In earlier versions, this was not a macro but the actual array of pointers.


7.5 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 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 its 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 a MAC created by Alice and one created by Bob.

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


7.5.1 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-RIPEMD160 HMAC-SHA1, HMAC-SHA256, HMAC-SHA512, and HMAC-SM3. First, the abstract functions:

Function: void hmac_set_key (void *outer, void *inner, void *state, const struct nettle_hash *H, size_t 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, size_t 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, size_t 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 to

{
   type outer;
   type inner;
   type state;
}

It can be used to define a HMAC context 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.

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

7.5.1.1 HMAC-MD5

Context struct: struct hmac_md5_ctx
Function: void hmac_md5_set_key (struct hmac_md5_ctx *ctx, size_t key_length, const uint8_t *key)

Initializes the context with the key.

Function: void hmac_md5_update (struct hmac_md5_ctx *ctx, size_t length, const uint8_t *data)

Process some more data.

Function: void hmac_md5_digest (struct hmac_md5_ctx *ctx, size_t 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.

7.5.1.2 HMAC-RIPEMD160

Context struct: struct hmac_ripemd160_ctx
Function: void hmac_ripemd160_set_key (struct hmac_ripemd160_ctx *ctx, size_t key_length, const uint8_t *key)

Initializes the context with the key.

Function: void hmac_ripemd160_update (struct hmac_ripemd160_ctx *ctx, size_t length, const uint8_t *data)

Process some more data.

Function: void hmac_ripemd160_digest (struct hmac_ripemd160_ctx *ctx, size_t length, uint8_t *digest)

Extracts the MAC, writing it to digest. length may be smaller than RIPEMD160_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.

7.5.1.3 HMAC-SHA1

Context struct: struct hmac_sha1_ctx
Function: void hmac_sha1_set_key (struct hmac_sha1_ctx *ctx, size_t key_length, const uint8_t *key)

Initializes the context with the key.

Function: void hmac_sha1_update (struct hmac_sha1_ctx *ctx, size_t length, const uint8_t *data)

Process some more data.

Function: void hmac_sha1_digest (struct hmac_sha1_ctx *ctx, size_t 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.

7.5.1.4 HMAC-SHA256

Context struct: struct hmac_sha256_ctx
Function: void hmac_sha256_set_key (struct hmac_sha256_ctx *ctx, size_t key_length, const uint8_t *key)

Initializes the context with the key.