The Twofish Encryption Algorithm A 128-Bit Block Cipher:Preface

The Twofish Encryption Algorithm: A 128-Bit Block Cipher The Twofish Encryption Algorithm: A 128-Bit Block Cipher
by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Preface

AES

NIST, the National Institute of Standards and Technology, is replacing the DES encryption algorithm. The new algorithm will be called AES (Advanced Encryption Standard), will have a longer key length (128-, 192-, and 256-bit) and a larger block size (128-bit), be faster than triple DES (and probably DES), and hopefully will remain strong for a long, long time.

The process is an interesting one. In 1997, NIST sent out a request for candidate algorithms. They received fifteen submissions by the June 1998 deadline, five from the U.S. and ten from other countries. In the weeks that followed, most of the submitters posted their algorithms on the World Wide Web. In August 1998, all the submitters presented their algorithms to the world at the First AES Candidate Conference.

There will be a Second AES Candidate Conference in Rome in March 1999, where people will present papers analyzing the algorithms. Through June 1999, NIST is soliciting public comment. Then NIST will choose about five algorithms to go into the second round and, after another comment period and a third conference (sometime in mid-2000), they will choose one to turn into the standard. Then, NIST will write a FIPS, a Federal Information Processing Standard for the new algorithm, and hopefully the AES will be adopted by other standards bodies throughout the world.

All fifteen algorithms are new. Existing ones, like triple-DES, IDEA, RC5, and Blowfish, were not eligible because their block sizes were too small was not eligible because its block and key size were both too small.

The NSA did not submit any algorithm. They had one ready, but NIST preferred to use them as an independent evaluator. Of course, their classified analysis will not be made public, but NIST hopes that the public comments will recommend the same algorithms that the NSA’s analysis does.

NIST required that all submitters state that if their algorithm was chosen as AES, they would give up all patent rights. Some submitters have given up patent rights regardless, others are holding on to their patent rights until they are chosen (and will keep them if they axe not chosen). Some people chose not to submit their algorithms under these circumstances, stating that they do not want to give up the ability to charge for their algorithms. But since NIST received some very high-quality designs from groups that were willing to give them away for free, it seems NIST was correct in demanding patent-free submissions.

Cryptographers are busily analyzing the submissions for security. It’s tempting to think of the process as a big demolition derby: everyone submits their algorithms and then attacks all the others . . . the last one standing wins. Really, it won’t be like that.

At the time of writing (November 1998), there has been some pretty devastating cryptanalysis against three of the weaker candidates. (One was broken minutes after it was presented.) By the end of the first comment period, we expect there to be weaknesses found in only a few others. We strongly believe that at the end of the process most of the candidates will be unbroken. The winner will be chosen based on other factors: performance, flexibility, suitability.

AES will have to work in a variety of current and future applications, doing all sorts of different encryption tasks. Specifically:

• AES will have to be able to encrypt bulk data quickly on top-end 32-bit CPUs and 64-bit CPUs. The algorithm will be used to encrypt streaming video and audio to the desktop in real time.
• AES will have to be able to fit on small 8-bit CPUs in smart cards. To a first approximation, all DES implementations in the world are on small CPUs with very little RAM. It’s in burglar alarms, electricity meters, pay-TV devices, and smart cards. Sure, some of these applications will get 32-bit CPUs as those get cheaper, but that just means that there will be another set of even smaller 8-bit applications.
• AES will have to be efficient on the smaller, weaker, 32-bit CPUs. Smart cards won’t be getting Pentium-class CPUs for a long time. The first 32-bit smart cards will have simple CPUs with a simple instruction set. 16-bit CPUs will be used in embedded systems that need more power than an 8-bit CPU, but can’t afford a 32-bit CPU.
• AES will have to be efficient in hardware, in not very many gates. There axe lots of encryption applications in dedicated hardware: contactless cards for fare payment, for example.
• AES will have to be key agile. There are many applications where small amounts of text are encrypted with each key, and the key changes frequently. This is a very different optimization problem than encrypting a lot of data with a single key.
• AES will have to be able to be parallelized. Sometimes you have a lot of gates in hardware, and raw speed is all you care about.
• AES will have to work on DSPs. Sooner or later, your cell phone will have proper encryption built in. So will your digital camera and your digital video recorder.
• AES will need to be secure as a hash function. There are many applications where DES is used both for encryption and authentication; there just isn’t enough room for a second cryptographic primitive. AES will have to serve these same two roles.
• AES needs to be secure for a long time. Infrastructure is hard to update. Like DES, AES hardware is likely to be installed and used for decades. A radical new algorithm, with interesting and exciting ideas, just doesn’t make sense. A conservative algorithm is what is needed.

Choosing a single algorithm for all these applications is not easy, but that’s what we have to do. It might make more sense to have a family of algorithms, each tuned to a particular application, but there will be only one AES. And when AES becomes a standard, customers will want their encryption products to be “buzzword compliant.” They’ll demand it in hardware, in desktop computer software, on smart cards, in electronic-commerce terminals, and in other places we never thought it would be used. Anything we pick for AES has to work in all those applications.

We designed Twofish with this in mind. It’s the fastest submission on the Pentium, second fastest on the Pentium Pro/Pentium 11, efficient on RAM-poor smart cards (some other algorithms can’t even fit on some smart cards), implementable in hardware at either high speeds or low gate count, and suitable to be used in a hash function. It’s flexible enough for implementations where one key encrypts megabytes, and for implementations where the key changes with each block.

For more information on the AES process, visit the NIST AES home page at http://www.nist.gov/slash aes. A general performance comparison of all the AES candidates can be found at http: //www.counterpane.com/aes-performance.html [SKW+99a]; see also Brian Gladman’s work at http://www. seven77.demon.co.uk/aes.htm. For a summary of the most recent attacks against the different candidates, see Lars Knudsen’s summary at http://www.ii.uib.no/~larsr/aes.html.

This Book

This book contains all the details about Twofish, from the design criteria to the best cryptanalysis at the time of writing (November 1998). It is based on the original Twofish AES submission [SKW+98a], but also includes the first three Twofish Technical Reports [Fer98b, WW98, WS98] and the various Twofish articles and papers [SKW+98b, Sch98, SKW+99b].

This book does not contain information about the other fourteen AES submissions, or any comparisons of Twofish with them. Since this book is about the design of Twofish, which was completed without seeing the other AES submissions (except for LOKI97 and a preliminary version of Serpent, which were published early), we felt that it would be inappropriate to discuss the other submissions in this book.

As analysis progresses, more will become known about Twofish. The latest information can always be found on the Twofish web site:

http://www.counterpane.com/twofish.html

The web site also contains downloadable Twofish source code:

• Reference C implementation.
• Optimized C for the Intel Pentium, Pentium Pro, and Pentium II.
• Assembly code for the Intel Pentium, Pentium Pro, and Pentium II.
• 6805 assembly code.

Additional implementations will be added when they become available.

The authors would like to thank Carl Ellison, Nina Fefferman, Paul and Randy Milbert, who read and commented on drafts of the original AES submission, and Beth Riedman, who copyedited the manuscript twice (both the original AES submission and this book). Additionally, the authors would like to thank NIST for initiating the AES process, Miles Smid, Jim Foti, and Ed Roback for putting up with a never-ending stream of questions and complaints about its details, and all the other AES candidates for submitting their algorithms, and making the AES selection process so interesting. We know how much effort they all went through.

This work has been funded by Counterpane Systems and Hi/fn Inc.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Introduction

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Chapter 1
Introduction

In 1972 and 1974, the National Bureau of Standards (now the National Institute of Standards and Technology, or NIST) issued the first public request for an encryption standard. The result was DES [NBS77], arguably the most widely used and successful encryption algorithm in the world.

Despite its popularity, DES has been plagued with controversy. Some cryptographers objected to the “closed-door” design process of the algorithm. The debate about whether DES’ key is too short for acceptable commercial security has raged for many years [DH79], but recent advances in distributed key search techniques have left no doubt in anyone’s mind that its key is simply too short for today’s security applications [Wie94, BDR+96, Koc98b]. Triple-DES has emerged as an interim solution in many high-security applications, such as banking, but it is too slow for some uses. More fundamentally, the 64-bit block length shared by DES and most other well-known ciphers opens it up to attacks when large amounts of data are encrypted under the same key.

In response to a growing desire to replace DES, NIST announced the Advanced Encryption Standard (AES) program in 1997 [NIST97a].

NIST solicited comments from the public on the proposed standard, and eventually issued a call for algorithms to satisfy the standard [NIST97b]. The intention is for NIST to make all submissions public and eventually, through a process of public review and comment, choose a new encryption standard to replace DES.

NIST’s call requested a block cipher. Block ciphers can be used to design stream ciphers with a variety of synchronization and error extension properties, one-way hash functions, message authentication codes, and pseudo-random number generators. Because of this flexibility, they are the workhorse of modern cryptography.

NIST specified several other design criteria: a longer key length, larger block size, faster speed, and greater flexibility. While no single algorithm can be optimized for all needs, NIST intends AES to become the standard symmetric algorithm of the next decade.

Twofish is our submission to the AES selection process. It meets all the required NIST criteria—128-bit block; 128-, 192-, and 256-bit keys; efficient on various platforms; etc.—and some strenuous design requirements, performance as well as cryptographic, of our own.

Specifically, Twofish is a 128-bit block cipher that accepts a variable-length key up to 256 bits. The cipher is a 16-round Feistel network with a bijective F function made up of four key-dependent 8-by-8-bit S-boxes, a fixed 4-by-4 maximum distance separable matrix over GF(28), a pseudo-Hadamard transform, bitwise rotations, and a carefully designed key schedule. A fully optimized implementation of Twofish encrypts on a Pentium Pro at 16.1 clock cycles per byte, and an 8-bit smart card implementation encrypts at 1660 clock cycles per byte. Twofish can be implemented in hardware in 8000 gates. The design of both the round function and the key schedule permits a wide variety of tradeoffs between speed, software size, key setup time, gate count, and memory. We have extensively cryptanalyzed Twofish; our best attack breaks six rounds (without the whitening) with 241 chosen plaintexts and 2232 effort.

Twofish can:

• Encrypt data at 258 clock cycles per block on a Pentium Pro, after an 8600 clock-cycle key setup, or after a 6500 clock-cycle key setup if 256 Kbytes of tables are available.
• Encrypt data at 860 clock cycles per block on a Pentium Pro, after a 1250 clock-cycle key setup.
• Encrypt data at 26500 clock cycles per block on a 6805 smart card, after a 1750 clock-cycle key setup, using only 60 bytes of RAM.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Twofish Design Goals

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Chapter 2
Twofish Design Goals

Twofish was designed to meet NIST’s design criteria for AES [NIST97b]. Specifically, they are:

• A 128-bit symmetric block cipher.
• Key lengths of 128 bits, 192 bits, and 256 bits.
• No weak keys.
• Efficiency, both on the Intel Pentium Pro and other software and hardware platforms.
• Flexible design: e.g., accept additional key lengths; be implementable on a wide variety of platforms and applications; and be suitable for a stream cipher, hash function, and MAC.
• Simple design, both to facilitate ease of analysis and ease of implementation.

Additionally, we imposed the following performance criteria on our design:

• Encrypt data in less than 500 clock cycles per block on an Intel Pentium, Pentium Pro, and Pentium II for a fully optimized version of the algorithm.
• Be capable of setting up a 128-bit key (for optimal encryption speed) in less than the time required to encrypt 32 blocks on a Pentium, Pentium and Pentium II.
• Encrypt data in less than 5000 clock cycles per block on a Pentium, Pentium Pro, and Pentium II, with no key setup time.
• Not contain any operations that make it inefficient on other 32-bit microprocessors.
• Not contain any operations that make it inefficient on 8-bit and 16-bit microprocessors.
• Not contain any operations that reduce its efficiency on existing and proposed 64-bit microprocessors; e.g., Merced.
• Not include any elements that make it inefficient in hardware.
• Have a variety of performance tradeoffs with respect to the key schedule.
• Encrypt data in less than 10 milliseconds on a commodity 8-bit microprocessor.
• Be implementable on an 8-bit microprocessor with only 64 bytes of RAM.
• Be implementable in hardware using less than 20000 gates.

Our cryptographic goals were as follows:

• 12-round Twofish (without whitening) should have no chosen-plaintext attack requiring fewer than 280 chosen plaintexts and less than 2N time, where N is the key length.
• 12-round Twofish (without whitening) should have no related-key attack requiring fewer than 264 chosen plaintexts, and less than 2N/2 time, where N is the key length.

Finally, we imposed the following flexibility goals:

• Accept any key length up to 256 bits.
• Have variants with a variable number of rounds.
• Have a key schedule that can be precomputed for maximum speed, or computed on the fly for maximum agility and minimum memory requirements. Additionally, it should be suitable for dedicated hardware applications: e.g., no large tables.
• Be suitable as a stream cipher, one-way hash function, MAC, and pseudo-random number generator, using well-understood construction methods.
• Have a family-key variant to allow for different, non-interoperable versions of the cipher.

We feel we have met all of these goals in the design of Twofish.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Twofish Building Blocks

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Chapter 3
Twofish Building Blocks

3.1 Feistel Networks

A Feistel network is a general method of transforming any function (usually called the F function) into a permutation. It was invented by Horst Feistel [FNS75] in his design of Lucifer [Fei73], and popularized by DES [NBS77].

All commonly used symmetric block ciphers are product ciphers; they are strong ciphers constructed by many iterations of a round function, which is itself a kind of weak cipher. In a Feistel cipher, the round function consists of taking one part of the data being encrypted, feeding it into some key dependent function F, and then XORing (or otherwise combining) the result into another part of the block. If the part of the data used as input to the F function and the part of the data combined with output from the F function are each half of the block, then the cipher is a “balanced” Feistel network [SK96].

This is the basis of most block ciphers published since then, including FEAL [SM88], GOST [GOST89], Khufu and Khafre [Mer91], LOKI [BPS90, BKPS93], CAST-128 [Ada97a], Blowfish [Sch94], and RC5 [Riv95].

Two rounds of a Feistel network are collectively called a “cycle” [SK96]. In one cycle, every bit of the text block has been modified once.1 Twofish is a 16-round Feistel network with a bijective F function, which corresponds to eight cycles.

1 The notion of a cycle allows balanced Feistel networks to be compared with unbalanced Feistel networks [SK96, ZMI90] such as MacGuffin [BS95] (cryptanalyzed in [RP95a]) and Bear/Lion [AB96a], and with SP-networks (also called uniform transformation structures [Fei73]) such as SAFER and Shark [RDP+96] (see also [YTH96]). Thus, 8-cycle (8-round) SAFER is comparable to 8-cycle (16-round) DES and 8-cycle (32-round) Skipjack [NSA98].

3.2 Whitening

Whitening, the technique of XORing key material before the first round and after the last round, was used by Ralph Merkle in Khufu/Khafre, and independently invented by Ron Rivest for DES-X [KR96a].

In [KR96a], it was shown that whitening substantially increases the difficulty of keysearch attacks against the remainder of the cipher. In our attacks on reduced-round Twofish variants, we discovered that whitening substantially increased the difficulty of attacking the cipher by hiding from an attacker the specific inputs to the first and last rounds’ F functions.

Twofish XORs 128 bits of subkey before the first Feistel round, and another 128 bits after the last Feistel round. These subkeys are calculated in the same manner as the round subkeys, but are not used anywhere else in the cipher.

3.3 S-boxes

An S-box is a table-driven non-linear substitution operation used in most block ciphers. S-boxes vary in both input size and output size, and can be created either randomly or algorithmically. S-boxes were first used in Lucifer, then DES, and afterwards in most encryption algorithms.

Twofish uses four different, bijective, key-dependent, 8-by-8-bit S-boxes. Each S-box is constructed using two fixed 8-by-8-bit permutations and several bytes of key material. These S-boxes can either be precomputed for a specific key, or computed on the fly for every required value. This provides a lot of flexibility and tradeoffs both in hardware and software.

3.4 MDS Matrices

A maximum distance separable (MDS) code over a field is a linear mapping from a field elements to b field elements, producing a composite vector of a + b elements, with the property that the minimum number of non-zero elements in any non-zero vector is at least b + 1 [MS77].2 Put another way, the “distance” (i.e., the number of elements that differ) between any two distinct vectors produced by the MDS mapping is at least b + 1. It can easily be shown that no mapping can have a larger minimum distance between two distinct vectors, hence the term maximum distance separable. MDS mappings can be represented by an MDS matrix consisting of a × b elements. Reed-Solomon (RS) error-correcting codes are known to be MDS. A necessary and sufficient condition for an a × b matrix to be MDS is that all possible square submatrices, obtained by discarding rows or columns, are non-singular.

2 We describe only the normal form of a linear MDS code. Any MDS code can be converted to an equivalent code in normal form.

Serge Vaudenay first proposed MDS matrices as a cipher design element [Vau95]. Shark [RDP+96] and Square [DKR97] use MDS matrices (see also [YMT97]), although we first saw the construction used in the unpublished cipher Manta [Fer96].3

3 Manta is a block cipher with a large block size and an emphasis on long-term security rather than speed. It uses an SP-like network with DES as the S-boxes and MDS matrices for the permutations.

MDS matrices are useful building blocks for ciphers because they guarantee a certain degree of diffusion. If one of the input elements is changed, all the output elements must change. If two input elements are changed, all but one of the output elements must change, etc. Twofish uses a single 4-by-4 MDS matrix over GF(28). This is one of the two main diffusion elements of Twofish. (There is also an RS-code with the MDS property used in the key schedule; this doesn’t add diffusion to the cipher, but does add diffusion to the key schedule.)

3.5 Pseudo-Hadamard Transforms

A pseudo-Hadamard transform (PHT) is a simple mixing operation that is very efficient in software. Given two inputs, a and b, the 32-bit PHT is defined as:

a´ = a + b mod 232

b´ = a + 2b mod 232

SAFER [Mas94] uses 8-bit PHTs extensively for diffusion.

Twofish uses a 32-bit PHT to mix the outputs from its two parallel 32-bit g functions. This PHT can be executed in two opcodes on most modern microprocessors, including the Pentium family. This is the second main diffusion element in Twofish.

3.6 Key Schedule

The key schedule is the means by which the key bits are turned into round keys that the cipher can use. The requirements call for a variable-length key. The easiest way of using this is to have a key schedule that expands a variable-length key to a fixed set of expanded key values.

Twofish needs a lot of key material, and has a complicated key schedule. To facilitate analysis, the key schedule uses the same primitives as the round function. Except for two additional rotations, each pair of expanded key words is constructed by applying the Twofish round function (with key-dependent S-boxes) to a fixed input.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Chapter 4
Twofish

Figure 4.1 shows an overview of the Twofish block cipher. Twofish uses a 16-round Feistel-like structure with additional whitening of the input and output. The only non-Feistel elements are the 1-bit rotates. The rotations can be moved into the F function to create a pure Feistel structure, but this requires an additional rotation of the words just before the output whitening step.

The plaintext is split into four 32-bit words. In the input whitening step, these are XORed with four key words. This is followed by 16 rounds. In each round, the two words on the left are used as input to the g functions. (One of them is rotated by 8 bits first.) The g function consists of four byte-wide key-dependent S-boxes, followed by a linear mixing step based on an MDS matrix. The results of the two g functions are combined using a Pseudo-Hadamard Transform (PHT), and two round key words are added. These two results are then XORed into the words on the right (one of which is rotated left by one bit first, the other is rotated right by one bit afterwards). The left and right halves are then swapped for the next round. After all the rounds, the swap of the last round is reversed, and the four words are XORed with four more key words to produce the ciphertext.

More formally, the 16 bytes of plaintext p0, ... , p15 are first split into four words P0, ..., P3 of 32 bits each using the little-endian convention.

In the input whitening step, these words are XORed with four words of the expanded key.

R0,i = Pi ⊕ Ki i = 0,...,3

In each of the 16 rounds, the first two words are used as input to the function F, which also takes the round number as input. The third word is XORed with the first output of F and then rotated right by one bit. The fourth word is rotated left by one bit and then XORed with the second output word of F. Finally, the two halves are exchanged. Thus,

(Fr,0,Fr,1) = F(Rr,0,Rr,1,r)

Fig. 4.1. Twofish
Rr+1,0 = ROR(Rr,2 ⊕ Fr,0,1)
Rr+1,1 = ROL(Rr,3,1) ⊕ Fr,1)
Rr+1,2 = Rr,0
Rr+1,3 = Rr,1

for r = 0, ..., 15 and where ROR and ROL are functions that rotate their first argument (a 32-bit word) left or right by the number of bits indicated by their second argument.

The output whitening step undoes the “swap” of the last round, and XORs the data words with four words of the expanded key.

Ci = R16,(i+2) mod 4⊕Ki+4 i = 0,...,3

The four words of ciphertext are then written as 16 bytes c0, ..., c15 using the same little-endian conversion used for the plaintext.

4.1 The Function F

The function F is a key-dependent permutation on 64-bit values. It takes three arguments: two input words R0 and R1, and the round number r used to select the appropriate subkeys. R0 is passed through the g function, which yields T0. R1 is rotated left by eight bits and then passed through the g function to yield T1. The results T0 and T1 are then combined using a PHT and two words of the expanded key are added.

T0 = g(R0)
T1 = g(ROL(R1,8))
F0 = (T0 + T1 + K2r+8) mod 232
F1 = (T0 + 2T1 + K2r+9) mod 232

where (F0, F1) is the result of F. We also define the function F´ for use in our analysis. F´ is identical to the F function, except that it does not add any key blocks to the output. (The PHT is still performed.)

4.2 The Function g

The function g forms the heart of Twofish. The input word X is split into four bytes. Each byte is run through its own key-dependent S-box. Each S-box is an 8-bit permutation: it takes eight bits of input and produces eight bits of output. The four results are interpreted as components of a vector of length 4 over GF(28), and multiplied by the 4 × 4 MDS matrix (using the field GF(28) for the computations).

The resulting vector is interpreted as a 32-bit word which is the result of g.

where si are the key-dependent S-boxes and Z is the result of g. For this to be well-defined, we need to specify the correspondence between byte values and the field elements of GF(28). We represent GF(28) as GF(2)[x]/v(x), where v(x) = x8 + x6 + x5 + x3 + 1 is a primitive polynomial of degree 8 over GF(2). The field element a = å7i=0 aixi with ai ∈ GF(2) is identified with the byte value å7i=0 ai2i. This is in some sense the “natural” mapping; addition in GF(28) corresponds to a XOR of the bytes.

The MDS matrix is given by:

where the elements have been written as hexadecimal byte values using the above-defined correspondence.

4.3 The Key Schedule

The key schedule has to provide 40 words of expanded key K0, ..., K39, and the 4 key-dependent S-boxes used in the g function. Twofish is defined for keys of length N = 128, N = 192, and N = 256.

We define k = N/64. The key M consists of 8k bytes m0, ..., m8k-1. The bytes are first converted into 2k words of 32 bits each

and then into two word vectors of length k.

Me = (Mo,M2,...,M2k-2)
M0 = (M1,M3,...,M2k-1)

A third word vector of length k is also derived from the key. This is done by taking the key bytes in groups of eight, interpreting them as a vector over GF(28), and multiplying them by a 4 × 8 matrix derived from an RS code. Each result of four bytes is then interpreted as a 32-bit word. These words make up the third vector.

for i = 0,....k – 1, and

S = (Sk-1, Sk-2,...,S0)

Note that S lists the words in “reverse” order. For the RS matrix multiply, GF(28) is represented by GF(2)[x]/w(x), where w(x) = x8 + x6 + x3 + x 2 + 1 is another primitive polynomial of degree 8 over GF(2). The mapping between byte values and elements of GF(28) uses the same definition as used for the MDS matrix multiply. Using this mapping, the RS matrix is given by:

The three vectors Me, Mo, and S from the basis of the key schedule.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

4.3.1 Additional Key Lengths

Twofish can accept keys of any byte length up to 256 bits. For key sizes that are not defined above, the key is padded at the end with zero bytes to the next larger length that is defined. For example, an 80-bit key m0, ... , m9 would be extended by setting mi = 0 for i = 10, ..., 15 and treating it as a 128-bit key. Every key of non-standard length is thus equivalent to exactly one key of a standard length.

Fig. 4.2. The Function h

We have not defined Twofish for keys whose length is not an integral number of bytes. Although this can be done trivially, we see no reason to do so. Keys that span only part of a byte create a lot of extra software complexity that can easily lead to implementation bugs. There is very little to be gained from the use of such odd-sized keys.

4.3.2 The Function h

Figure 4.2 shows an overview of the function h. This is a function that takes two inputs—a 32-bit word X and a list L = (L0, ..., Lk-1) of 32-bit words of length k—and produces one word of output. This function works in k stages. In each stage, the four bytes are each passed through a fixed S-box and then XORed with a byte derived from the list. Finally, the bytes are once again passed through a fixed S-box, and the four bytes are multiplied by the MDS matrix just as in g. More formally: we split the words into bytes.

li,j = [Li/28j] mod 28
xj = [X/28j] mod 28

for i = 0,..., k – 1 and j = 0, ..., 3. Then the sequence of substitutions and XORs is applied.

yk,j = xj j = 0,...,3

If k = 4 we have

y3,0 = q1[y4,0] ⊕ l3,0
y3,1 = q0[y4,1] ⊕ l3,1
y3,2 = q0[y4,2] ⊕ l3,2
y3,3 = q1[y4,3]


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Performance of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Chapter 5
Performance of Twofish

Twofish has been designed from the start with performance in mind. It is efficient on a variety of platforms: 32-bit CPUs, 8-bit smart cards, and dedicated VLSI hardware. More importantly, though, Twofish has been designed to allow several layers of performance tradeoffs, depending on the relative importance of encryption speed, key setup, memory use, hardware gate count, and other implementation parameters. The result is a highly flexible algorithm that can be implemented efficiently in a variety of cryptographic applications.

All these options are interoperable; these are simply implementation tradeoffs and do not affect the mathematics of Twofish. One end of a communication could use the fastest Pentium II implementation, and the other the cheapest hardware implementation.

5.1 Performance on Large Microprocessors

Table 5.1 gives Twofish’s performance, encryption or decryption, for different key scheduling options and on several modern microprocessors using different languages and compilers. This table shows our results for many different implementations. Each implementation is presented on a single line. The first column gives the CPU the implementation was run on (PPro/II = Pentium Pro/Pentium II, U-SPARC = Ultra-SPARC, PPC = Power PC). The second column is the programming language (ASM = assembly language, MS C = Microsoft Visual C++ 4.2, BC = Borland C 5.0, C = standard C compiler). The keying options are explained below. The code size column contains the approximate total code size (in bytes) of the routines for encryption, decryption, and key setup, where available. All remaining numbers in the row are in clock cycles. For each key size we show the number of clock cycles required for the key setup, and the number of clock cycles required to encrypt a single block. The times for encryption and decryption are identical in assembly, and encryption is slightly slower than decryption in C; only the encryption (i.e., the larger) number is given. There is no time required to set up the algorithm except for key setup. The time required to change a key is the same as the time required to set up a key.

For example, on a Pentium Pro a fully optimized assembly-language version of Twofish can encrypt or decrypt data in 258 clock cycles per block, or 16.1 clock cycles per byte, after a 12700-clock key setup (equivalent to encrypting 45 blocks). On a 200 MHz Pentium Pro microprocessor, this translates to a 90 Mbits/sec.

Processor | Lang | Keying Option | Code Size | Clocks to Key |  |  | Clocks to Encrypt
 |  |  |  | 128 | 192 | 256 | 128 | 192 | 256
PPro/II | ASM | Comp. | 9000 | 8600 | 11300 | 14100 | 258 | 258 | 258
PPro/II | ASM | Full | 8500 | 7600 | 10400 | 13200 | 315 | 315 | 315
PPro/II | ASM | Part. | 10700 | 4900 | 7600 | 10500 | 460 | 460 | 460
PPro/II | ASM | Min. | 13600 | 2400 | 5300 | 8200 | 720 | 720 | 720
PPro/II | ASM | Zero | 9100 | 1250 | 1600 | 2000 | 860 | 1130 | 1420
PPro/II | MS C | Full | 11200 | 8000 | 11200 | 15700 | 600 | 600 | 600
PPro/II | MS C | Part. | 13200 | 7100 | 9700 | 14100 | 800 | 800 | 800
PPro/II | MS C | Min. | 16600 | 3000 | 7800 | 12200 | 1130 | 1130 | 1130
PPro/II | MS C | Zero | 10500 | 2450 | 3200 | 4000 | 1310 | 1750 | 2200
PPro/II | BC | Full | 14100 | 10300 | 13600 | 18800 | 640 | 640 | 640
PPro/II | BC | Part. | 14300 | 9500 | 11200 | 16600 | 840 | 840 | 840
PPro/II | BC | Min. | 17300 | 4600 | 10300 | 15300 | 1160 | 1160 | 1160
PPro/II | BC | Zero | 10100 | 3200 | 4200 | 4800 | 1910 | 2670 | 3470
Pentium | ASM | Comp. | 9100 | 12300 | 14600 | 17100 | 290 | 290 | 290
Pentium | ASM | Full | 8200 | 11000 | 13500 | 16200 | 315 | 315 | 315
Pentium | ASM | Part. | 10300 | 5500 | 7800 | 9800 | 430 | 430 | 430
Pentium | ASM | Min. | 12600 | 3700 | 5900 | 7900 | 740 | 740 | 740
Pentium | ASM | Zero | 8700 | 1800 | 2100 | 2600 | 1000 | 1300 | 1600
Pentium | MS C | Full | 11800 | 11900 | 15100 | 21500 | 630 | 630 | 630
Pentium | MS C | Part. | 14100 | 9200 | 13400 | 19800 | 900 | 900 | 900
Pentium | MS C | Min. | 17800 | 3800 | 11100 | 16900 | 1460 | 1460 | 1460
Pentium | MS C | Zero | 11300 | 2800 | 3900 | 4900 | 1740 | 2260 | 2760
Pentium | BC | Full | 12700 | 14200 | 18100 | 26100 | 870 | 870 | 870
Pentium | BC | Part. | 14200 | 11200 | 16500 | 24100 | 1100 | 1100 | 1100
Pentium | BC | Min. | 17500 | 4700 | 12100 | 19200 | 1860 | 1860 | 1860
Pentium | BC | Zero | 11800 | 3700 | 4900 | 6100 | 2150 | 2730 | 3270
U-SPARC | C | Full |  | 16600 | 21600 | 24900 | 750 | 750 | 750
U-SPARC | C | Part. |  | 8300 | 13300 | 19900 | 930 | 930 | 930
U-SPARC | C | Min. |  | 3300 | 11600 | 16600 | 1200 | 1200 | 1200
U-SPARC | C | Zero |  | 1700 | 3300 | 5000 | 1450 | 1680 | 1870
PPC 750 | C | Full |  | 12200 | 17100 | 22200 | 590 | 590 | 590
PPC 750 | C | Part. |  | 7800 | 12200 | 17300 | 780 | 780 | 780
PPC 750 | C | Min. |  | 2900 | 9100 | 14200 | 1280 | 1280 | 1280
PPC 750 | C | Zero |  | 2500 | 3600 | 4900 | 1030 | 1580 | 2040
68040 | C | Full | 16700 | 53000 | 63500 | 96700 | 3500 | 3500 | 3500
68040 | C | Part. | 18100 | 36700 | 47500 | 78500 | 4900 | 4900 | 4900
68040 | C | Min. | 23300 | 11000 | 40000 | 71800 | 8150 | 8150 | 8150
68040 | C | Zero | 16200 | 9800 | 13300 | 17000 | 6800 | 8600 | 10400
Table 5.1. Twofish Performance with Different Key Lengths and Options


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Performance of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

5.1.1 Keying Options

We implemented four different keying options. All of our keying options pre-compute Ki for i = 0,...,39 and use 160 bytes of RAM to store these constants. The differences occur in the way the function g is implemented. There are several other possible keying options, each with slightly different setup/throughput tradeoffs, but the examples listed below are representative of the range of possibilities.

Full Keying.
This option performs the full key precomputations. Using 4 Kbytes of table space, each S-box is expanded to a 8-by-32-bit table that combines both the S-box lookup and the multiply by the column of the MDS matrix. Using this option, a computation of g consists of four table lookups, and three XORs. Encryption and decryption speeds are constant regardless of key size.
Partial Keying.
For applications where few blocks are encrypted with a single key, it may not make sense to build the complete key schedule. The partial keying option precomputes the four S-boxes in 8-by-8-bit tables, and uses four fixed 8-by-32-bit MDS tables to perform the MDS multiply. This reduces the key-schedule table space to 1 Kbyte. For each byte, the last of the q-box lookups is in fact incorporated into the MDS table, so only k of the q-boxes are incorporated into the 8-by-8-bit S-box table that is built by the key schedule. Encryption and decryption speeds are again constant regardless of key size.
Minimal Keying.
For applications where very few blocks are encrypted with a single key, there is a further possible optimization. Compared to partial keying, one less layer of q-boxes is precomputed into the S-box table, and the remaining q-box is done during the encryption. For the 128-bit key this is particularly efficient, as precomputing the S-boxes now consists of copying the table of the appropriate q-box and XORing it with a constant (which can be done word-by-word instead of byte-by-byte). This option uses a 1 Kbyte table to store the partially precomputed S-boxes. The necessary key bytes from S are of course precomputed, as they are needed in every round.
Zero Keying.
The zero keying option does not precompute any of the S-boxes, and thus needs no extra tables. Instead, every entry is computed on the fly. The key setup time consists purely of computing the Ki values and S. For an application that cannot have any key setup time, the time it takes to encrypt one block is the sum of the key setup time and encryption time for the zero keying option.
Compiled.
In this option, available only in assembly language, the subkey constants are directly embedded into a key-specific copy of the code, saving memory fetches and allowing the use of the Pentium LEA opcode to perform both the PHT and the subkey addition all in a single clock cycle. Some additional setup time is required, as well as about an extra 5000 bytes of memory to hold the “compiled” code, but this option allows the fastest execution time of 258 clocks per block on the Pentium Pro. The setup time for a Pentium more than doubles over the full keying case because of its smaller cache size, but the Pentium MMX setup time is still comparable to the Pentium Pro setup time. However, almost all the extra time required is consumed merely in copying the code; the table does not reflect the fact that, once a single key has been initialized, future keys can be compiled at a cost of only a few hundred more clocks than full key schedule time.

5.1.2 Code and Data Size

As shown in Table 5.1, the code size for a fully optimized Twofish implementation on a Pentium Pro ranges from about 8450 bytes in assembler to 14100 bytes in Borland C. In assembler, the encryption and decryption routines are each about 2250 bytes in size; the remaining 4000 bytes of code are in the key scheduling routines, but about 2200 bytes of that total can be discarded if only 128-bit keys are needed. In Borland C, the encryption and decryption routines are each about 4500 bytes in length, and the key schedule routine is slightly less than 5000 bytes. Note that each routine fits easily within the code cache of a Pentium or a Pentium Pro. These sizes are larger than Blowfish but very similar to a fully optimized assembly language version of DES. Note that, with the exception of the zero keying option, the code sizes in the table are for fully unrolled implementations; in either C or assembler, it is possible to achieve significantly smaller code sizes using loops with round counters, at a cost in performance.

In addition to the code, there are about 4600 bytes of fixed tables for the MDS matrix, q0 and q1 required for key setup, and each key requires about 4300 bytes of key-dependent data tables for the full keying option. During encryption or decryption, these tables fit easily in the Pentium data cache. The other keying options use less data and table space, as discussed above.

5.1.3 Large Memory Implementations

For machines with sufficient RAM and a good memory cache subsystem, large precomputed tables can be used to reduce the key setup time for Twofish even further. For example, in compiled, full, or partial keying modes, the first two levels of q0 and q1 lookups with one key byte can be precomputed for all four S-boxes, requiring 256 Kbytes of table (four tables of 64 Kbytes each). This approach saves roughly 2000 clocks per key setup on the Pentium Pro in assembly language; details are shown in Table 5.2. For instance, the compiled mode key setup for 128-bit keys on a Pentium Pro can be reduced from 8700 clocks to 6500 clocks. Unfortunately, the savings on Pentium and Pentium MMX CPUs seems to depend on the performance of the L2 cache subsystem (which is included in the Pentium Pro and thus is more predictable); the gain seems to range from 500 clocks down to nothing. Implementing this “big table” version in C also leads to savings of about 1000 clocks per key setup on the Pentium Pro, depending on the quality of the compiler; again, Pentium performance gains are minimal.

Processor | Lang | Keying Option | Code Size | Clocks to Key |  |  | Clocks to Encrypt
 |  |  |  | 128 | 192 | 256 | 128 | 192 | 256
PPro/II | ASM | Comp. | 271,200 | 6500 | 9200 | 11900 | 258 | 258 | 258
PPro/II | ASM | Full | 270,600 | 5300 | 8000 | 11000 | 315 | 315 | 315
PPro/II | ASM | Part. | 272,900 | 2600 | 5300 | 8200 | 460 | 460 | 460
PPro/II | MS C | Full | 273,300 | 7300 | 11200 | 15700 | 600 | 600 | 600
Table 5.2. Twofish Performance with Large Fixed Tables


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Performance of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

For the ultimate in key agility, a full 256 Mbytes of precomputed tables could comprise all four S-boxes for the final two stages of q0, q1, covering all 216 key byte possibilities for the 128-bit key case, and including the MDS matrix multiply. With a good memory subsystem, such a version should cut another 1000 clocks or so out of the above key setup times. Clearly, this is a fairly expensive solution (at least with today’s technology), but it illustrates the flexibility of Twofish very nicely.

5.1.4 Total Encryption Times

Any performance measures that do not take key setup into account are only valid for asymptotically large amounts of text. For shorter messages, performance is the sum of key setup and encryption. For very short messages, the key setup time can overwhelm the encryption speed.

Table 5.3 gives Twofish’s performance on the Pentium Pro (assembly-language version), both 128-bit key setup and encryption, for a variety of message lengths. This table assumes the best of our implementations (not including the large-memory implementations) for the particular length of text.

5.1.5 Hash Function Performance

Hash functions built from block ciphers generally require the algorithm to be uniquely keyed for each text block [Pre93, Sch96]. Assuming the chaining variables are the plaintext and ciphertext, and the block to be hashed is the key, Twofish can hash text at a rate of 175 clock cycles per byte on a Pentium, assuming a 128-bit key, and 132 clock cycles per byte on a Pentium Pro/II.

Plaintext (bytes) | Keying Option | Clocks to Key | Clocks to Encrypt | Total Clocks per Byte
16 | Zero | 1250 | 860 | 131.9
32 | Zero | 1250 | 1720 | 92.8
64 | Zero | 1250 | 4690 | 73.3
128 | Minimal | 2400 | 6880 | 63.5
256 | Partial | 4900 | 7360 | 47.9
512 | Compiled | 8600 | 8256 | 32.9
1K | Compiled | 8600 | 16512 | 24.5
2K | Compiled | 8600 | 33024 | 20.3
4K | Compiled | 8600 | 66048 | 18.2
8K | Compiled | 8600 | 132096 | 17.2
16K | Compiled | 8600 | 264192 | 16.7
32K | Compiled | 8600 | 528384 | 16.4
64K | Compiled | 8600 | 1056768 | 16.3
1M | Compiled | 8600 | 270532608 | 16.1
Table 5.3. Best Speed to Encrypt a Message with a New 128-bit Key on a Pentium Pro

5.1.6 Language, Compiler, and Processor Choice

As with most algorithms, the choices of language and compiler can have a huge impact on performance. It is clear that the Borland C 5.0 compiler chosen as the standard AES reference is not the best optimizing compiler. For example, the Microsoft Visual C++ 4.2 compiler generates Twofish code that is at least 20 percent faster than Borland on a Pentium computer, with both set to optimize for speed (630 clocks per block for Microsoft Visual C++ 4.2 versus 870 clocks per block for Borland C 5.0), on a Pentium Pro/II, the difference between the compilers is not quite as large (e.g., 600 clocks/block vs. 640 clocks/block), but it is still significant. Part of the difference stems from the inability of the Borland C compiler to generate intrinsic rotate instructions, despite documentation claiming that it is possible. This problem alone accounts for nearly half of the speed difference between Borland and Microsoft. The remaining speed difference comes simply from poorer code generation. The Borland C compiler is uniformly slower than Microsoft’s compiler. The encryption speed in Microsoft C of 40 Pentium clocks per byte (i.e., 630 clocks/block at 16 bytes/block) is over ten percent faster than the best known DES assembly language implementation on the same platform. However, coding the Twofish algorithm in assembly language achieves speeds of 258 clocks, achieving a very significant speedup over any of the C implementations.

To make matters even more complicated, the assembly language that optimizes performance on a Pentium (or Pentium MMX) is drastically different from the assembly language required to maximize speed on a Pentium Pro or Pentium II, even though the final code size and speed achieved on each platform are almost identical. For example, the Pentium Pro/II CPUs can perform only one memory read per clock cycle, while the Pentium and Pentium MMX can perform two. However, the Pentium Pro/II can perform two ALU operations per clock in addition to memory accesses, while the Pentium can process only a total of two ALU operations or memory accesses per clock. These (and other) significant architectural differences result in the fact that running the optimal Pentium Twofish encryption code on a Pentium Pro results in a slowdown of nearly 2:1—and vice versa! Fortunately, it is relatively simple to detect the CPU type at run-time and select which version of the assembly code to use. Another anomaly is that the key schedule setup time is considerably faster (43 percent) on the Pentium MMX than on the Pentium, not because the key schedule uses any MMX instructions, but simply because of the larger cache size of the MMX chip.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Performance of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Empirically, there also seems to be some anomalous behavior of the C compilers. In almost all cases, the encryption and decryption routines in C achieved speeds within a few percent of each other. However, there were cases in the table where the two speeds differed by considerably more than ten percent (we used the larger number in the table), which is very odd because the “inner loop” C code used is virtually identical. We also noted several cases where compiler switches that seemed unrelated to performance optimization sometimes caused very large changes in timings.

It should be noted that performance numbers for Pentium II processors are almost identical in all cases to those for a Pentium Pro, which is not surprising since Intel claims they have the same core. The Pentium and Pentium MMX achieve almost identical speeds for encryption and decryption, although, as noted above, the MMX key setup times are faster, due mainly to the larger cache size.

The bottom line is that, when comparing the relative performance of different algorithms, using the same language and compiler for all implementations helps to make the comparison meaningful, but it does not guarantee a valid measure of the relative speeds. We have listed many different software performance metrics across platforms and languages to facilitate speed comparisons between Twofish and other algorithms. Our belief is that, on any given platform (e.g., Pentium Pro), the assembly-language performance numbers are the best numbers to use to gauge absolute performance, since they are unaffected by the vagaries and limitations of the compiler (e.g., inability to produce rotate opcodes). High-level languages (e.g., C, Java) are also important because of the ease of porting to different platforms, but once an algorithm becomes standardized, it will ultimately be coded in assembly for the most popular platforms.

RAM, ROM, or EEPROM for Key Working RAM Code and Table Size Clocks per Block Time per Block @ 4MHz
24 | 36 | 2200 | 26500 | 6.6 msec
24 | 36 | 2150 | 32900 | 8.2 msec
24 | 36 | 2000 | 35000 | 8.7 msec
24 | 36 | 1750 | 37100 | 9.3 msec
184 | 36 | 1900 | 15300 | 3.8 msec
184 | 36 | 1700 | 18100 | 4.5 msec
184 | 36 | 1450 | 19200 | 4.8 msec
1208 | 36 | 1300 | 12700 | 3.2 msec
1208 | 36 | 1100 | 15500 | 3.9 msec
1208 | 36 | 850 | 16600 | 4.2 msec
3256 | 36 | 1000 | 11900 | 3.0 msec
Table 5.4. Twofish Performance on a 6805 Smart Card

5.2 Performance on Smart Cards

Twofish is ideally suited for smart cards. It can fit on the smallest smart cards while exhibiting reasonable performance, and can take advantage of more RAM or more powerful processors with increased performance. It can operate efficiently in environments that require rapid key changes, and can be implemented in dedicated hardware in only a few gates.

We implemented Twofish on a 6805 CPU, which is a typical smart card processor, with several different space—time tradeoff options [SKW+99b]. Our results are shown in Table 5.4. The code size includes both encryption and decryption.1 The block encryption and decryption times are almost identical. If only encryption is required, minor improvements in code size and speed can be obtained. The only key schedule precomputation time required in this implementation is the Reed-Solomon mapping used to generate the S-box key material S from the key M, which requires slightly over 1750 clocks per key. This setup time can be made considerably shorter at the cost of two additional 256-byte ROM tables. It should also be observed that the lack of a second index register on the 6805 has a significant impact on the code size and performance, so a different CPU with multiple index registers (e.g., 6502) might be a better fit for Twofish.

1For comparison purposes: DES on a 6805 takes about 1K code, 23 bytes of RAM, and 20000 clock cycles per block.

5.2.1 RAM Usage

For any encryption algorithm, memory usage can be divided into two parts: that required to hold the expanded key, and that required as working space to encrypt or decrypt text (including the text block). In applications where a smart card holds a single key for a long period of time, the key can be put into EEPROM or even ROM, greatly reducing RAM requirements. Most applications, however, require the smart card to encrypt using session keys, which change with each transaction. In these situations, the expanded key must be stored in RAM, along with working space to perform the encryption.

Twofish—the 128-bit key version—can be implemented in a smart card in 60 bytes of RAM. This includes the text block, key, and working space. If a slightly expanded key (16 bytes of the key plus another eight bytes of the Reed-Solomon results (S)) can be stored in ROM or EEPROM, then Twofish can be implemented in only 36 bytes of RAM. In either case, there is zero key setup time for the next encryption operation with the same key.2

2All of our implementations leave the key intact so that it can be used again.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Performance of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Larger key sizes require more RAM to store the larger keys: 36 bytes for 192-bit keys and 48 bytes for 256-bit keys. If these applications can store key material in ROM or EEPROM, then these key lengths can be implemented on smart cards with only 36 bytes of RAM. All of this RAM can be reused for other purposes between block encryption operations.

For smart cards with larger memory to hold key-dependent data, encryption speed can increase considerably. This is because the round keys can be precomputed as part of the expanded key, requiring a total of 184 bytes of key memory. As shown in Table 5.4, this option nearly halves the encryption time. If the smart card has enough additional memory available to hold 1 Kbyte of precomputed S-box in either RAM, ROM, or EEPROM (for a total of 1208 bytes), performance improves further. Finally, as shown in the final row of Table 5.4, if the entire precomputed S-box plus MDS table can be held in memory (3256 bytes), the speed can again be increased slightly more. It should be noted that some of these “large RAM” implementations save 512 bytes of code space by assuming that certain tables are not required in ROM, with the entire precomputation being performed instead on the host that sets the key in the smart card. If the smart card has to perform its own key expansion the code size will increase. This increase has its own space/time tradeoff options.

This flexibility makes Twofish well-suited for both small and large smart-card processors: Twofish works in the most RAM-poor environments, while at the same time it is able to take advantage of both moderate-RAM cards and large-RAM cards.

5.2.2 Encryption Speed and Key Agility

On a 6805 with only 60 bytes of RAM, Twofish encrypts at speeds of 26500 to 37100 clocks per block, depending on the amount of ROM available for the code. On a 4 MHz chip, this translates to 6.6 msec to 9.3 msec per encryption. In these implementations, the key-schedule precomputation time is minimal: slightly over 1750 clocks per key. This setup time could be cut considerably at the cost of two additional 512-byte ROM tables, which would be used during the key schedule.

If ROM is expensive, Twofish can be implemented in less space at slower speeds. The space-speed tradeoffs are of two types: unrolling loops and implementing various lookup tables. By far, the latter has the larger impact on size and speed. For example, Twofish’s MDS matrix can be computed in three different ways:

• Full table lookups for the multiplications by EF and 5B. This is the fastest, and requires 512 bytes of ROM for tables.
• Single table lookup for the multiplications by α-1. This is slower, but only requires 256 bytes of ROM for the table.
• No tables, all multiplies done with shifts and XORs. This is the slowest, and the smallest.

Longer keys are slower, but only slightly so. For the small memory versions, Twofish’s encryption time per block increases by less than 2600 clocks per block for 192-bit keys, and by about 5200 clocks per block for 256-bit keys. Similarly, the key schedule precomputation increases to 2550 clocks for 192-bit keys, and to 3400 clocks for 256-bit keys.

As shown in Table 5.4, in smart card CPUs with sufficient additional RAM storage to hold the entire set of subkeys, the throughput improves significantly, although the key setup time also increases. The time savings per block is over 11000 clocks, cutting the block encryption time down to about 15000 clocks; i.e., nearly doubling the encryption speed. The key setup time increases by roughly the same number of clocks, thus making the key setup time comparable to a single block encryption. This approach also cuts down the code size by a few hundred bytes. It should be noted further that, in fixed-key environments, the subkeys can be stored along with the key bytes in EEPROM, cutting the total RAM usage down to 36 bytes while maintaining the higher speed.

As another tradeoff, if another 1 Kbyte of RAM or EEPROM is available, all four 8-bit S-boxes can be precomputed. Clearly, this approach has relatively low key agility, but the time required to encrypt a block decreases by roughly 6000 clocks. When combined with precomputed subkeys as discussed in the previous paragraph, the block encryption time drops to about 12000 clocks, nearly three times the best speed for “low RAM” implementations. In most cases, this approach would be used only where the key is fixed, but it does allow for very high throughput. Similarly, if 3 Kbytes of RAM or EEPROM is available for tables, throughput can be further improved slightly.

The wide variety of possible speeds again illustrates Twofish’s flexibility in these constrained environments. The algorithm does not have one speed; it has many speeds, depending on available resources.

5.2.3 Code Size

Twofish code is very compact: 1760 to 2200 bytes for minimal RAM footprint, depending on the implementation. The same code base can be used for both encryption and decryption. If only encryption is required, minor improvements in code size can be obtained (on the order of 150 bytes). The extra code required for larger keys is fairly negligible: less than 100 extra bytes for a 192-bit key, and less than 200 bytes for a 256-bit key.

Observe that it is possible to save further ROM space by computing q0 and q1 lookups using the underlying 4-bit construction, as specified in Section 4.3.5. Such a scheme would replace 512 bytes of ROM table with 64 bytes of ROM and a small subroutine to compute the full 8-bit q0 and q1, saving perhaps 350 bytes of ROM; unfortunately, encryption speed would decrease by a factor of ten or more. Thus, this technique is only of interest in smart card applications for which ROM size is extremely critical but performance is not. Nonetheless, such an approach illustrates the implementation flexibility afforded by Twofish.

5.3 Performance on the Alpha

The 64-bit Alpha 21164 CPU can run up to 600 MHz using only a 0.35 micron CMOS process, compared to the 0.25 micron technology used in a Pentium II. The Alpha is widely regarded as the fastest general purpose processor available today. Its architecture and performance are expected to remain at the leading edge of technology for the foreseeable future. It has a 4-way superscalar architecture, which is fairly close in many respects to a Pentium II. Twofish should run on an Alpha in roughly the same number of clocks as on a Pentium Pro (i.e., 300).


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Performance of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

5.4 Performance on Future Microprocessors

Given the ever-advancing capabilities of CPUs, it is worthwhile to make some observations about how the Twofish algorithm will run on future processors, including Intel’s Merced. Not many details are known about Merced, other than that it includes an Explicitly Parallel Instruction Computing (EPIC) architecture, as well the ability to run existing Pentium code. EPIC is related to VLIW architectures that allow many parallel opcodes to be executed at once, while the Pentium allows only two opcodes in parallel, and the Pentium Pro/Pentium II may process up to three opcodes per clock. However, access to memory tables is limited in most VLIW implementations to only a few parallel operations, and we expect similar restrictions to hold for Merced. For example, an existing Philips VLIW CPU can process up to five opcodes in parallel, but only two of the opcodes can read from memory.

Since Twofish relies on 8-bit non-linear S-boxes, it is clear that table access is an integral part of the algorithm. Thus, Twofish might not be able to take advantage of all the parallel execution units available on a VLIW processor. However, there is still plenty of parallelism in Twofish that can be well-utilized in an optimized VLIW software implementation. Equally important, the alternative of not using large S-boxes, while it may allow greater parallelism, also naturally involves less non-linearity and thus generally requires more rounds. For example, Serpent [BAK98], based on “inline” computation of 4-bit S-boxes, may experience a relatively larger speedup than Twofish on a VLIW CPU, but Serpent also requires 32 rounds, and is considerably slower to start with.

It should also be noted that, as with most encryption algorithms, the primitive operations used in Twofish could very easily be added to a CPU instruction set to improve software performance significantly. Future mainstream CPUs may include such support for the new AES standard. However, it is also worthwhile to remember that DES has been a standard for more than twenty years, and no popular CPU has added instruction set support for it, even though DES software performance would benefit greatly from such features.

5.5 Hardware Performance

No actual logic design has been implemented for Twofish, but estimates in terms of gates for each building block have been made. As in software, there are many possible space-time tradeoffs in hardware implementations of Two-fish. Thus, it is not meaningful to give just one figure for the speed and size attributes of Twofish in hardware. Instead, we will try to outline several of the options and give estimates for speed and gate count of several different architectures.

For example, the round subkeys could be precomputed and stored in a RAM, or they could be computed on the fly. If computed on the fly, the h function logic could be time-multiplexed between subkeys and the round function to save size at a cost in speed, or the logic could be duplicated, adding gates but perhaps running twice as fast. If the subkeys were precomputed, the h function logic would be used during a key setup phase to compute the subkeys, saving gates but adding a startup time roughly equal to one block encryption time. Similarly, a single h function logic block could be time-multiplexed between computing T0 and T1, halving throughput but saving even more gates.

As another example of the possible tradeoffs, the S-boxes could be pre-computed and stored in on-chip RAMs, allowing faster operation because there is no need to ripple through several layers of key material XORs and q permutations. The addition of such RAMs (e.g., eight 256-byte RAMs) would perhaps double or triple the size of the logic, and it would also impose a significant startup time on key change to initialize the RAMs. Despite these disadvantages, such an architecture might raise the throughput by a factor of two or more (particularly for the larger key sizes), so for high-performance systems with infrequent re-keying, this option may be attractive.

The construction method specified in Section 4.3.5 for building the 8-bit permutations q0 and q1 from four 4-bit permutations was selected mainly to minimize gate count in many hardware implementations of Twofish. These permutations can be built either directly in logic gates or as full 256-byte ROMs in hardware, but such a ROM is usually several times larger than the direct logic implementation. Since each full h block in hardware (see Figure 4.2) involves six q0 blocks and six q1 blocks (for N = 128), the gate savings mount fairly quickly. The circuit delays in building q0 or q1 using logic gates are typically at least as low as those using ROMs, although this metric is certainly somewhat dependent on the particular silicon technology and circuit library available.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Performance of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

It should also be noted that the Twofish round structure can be very nicely pipelined to break up the overall function into smaller and much faster blocks (e.g., q’s, key XORs, MDS, PHT, subkey addition, Feistel XOR). None of these operations individually is slow, but trying to run all of them in a single clock cycle does affect the cycle time. In ECB mode, counter mode, or an interleaved chaining mode, the throughput can be dramatically increased by pipelining the Twofish round structure. As a very simple example of two-level pipelining, we could compute the qi’s, key XORs and MDS multiply for one block during “even” clocks, while the PHT, subkey addition, and Feistel XOR would be computed on the “odd” clocks; a second block is processed in parallel on the alternate clock cycles. Using careful balancing of circuit delays between the two clock phases, this approach allows us to cut the logic delay in half, thus running the clock at twice the speed of an unpipelined approach. Such an approach does not require duplicating the entire Twofish round function logic, but merely the insertion of one extra layer of clocked storage elements (128 bits). Thus, for a very modest increase in gate count, throughput can be doubled, assuming that the application can use one of these cipher modes. It is clear that this general approach can be applied with more levels of pipelining to get higher throughput, although diminishing returns are achieved past a certain point. For even higher levels of performance, multiple independent engines can be used to achieve linear speedups at a linear ear cost in gates. We see no problem meeting NSA’s requirement to “be able to encrypt data at a minimum of 1 Gb/s, pipelined if necessary, in existing technology” [McD97].

Gate Count h Blocks Clocks
/Block 		Interleave Levels Clock Speed Throughput (Mbits/sec) Startup Clocks
8000 | 0.25 | 324 | 1 | 80 MHz | 32 | 20
14000 | 1 | 72 | 1 | 40 MHz | 71 | 4
19000 | 1 | 32 | 1 | 40 MHz | 160 | 40
23000 | 2 | 16 | 1 | 40 MHz | 320 | 20
26000 | 2 | 32 | 2 | 80 MHz | 640 | 20
28000 | 2 | 48 | 3 | 120 | MHz 960 | 20
30000 | 2 | 64 | 4 | 150 MHz | 1200 | 20
80000 | 2 | 16 | 1 | 80 MHz | 640 | 300
Table 5.5. Hardware Tradeoffs (128-bit Key)

Table 5.5 gives hardware size and speed estimates for the case of 128-bit keys. The first line of the table is a “byte serial” implementation. It uses one clock per S-box lookup, and four clocks per h function (including the MDS). We allow two clocks for the PHT and key addition. With four h functions per round, each round requires 18 clock cycles.

The next line uses a fully wired h function, but still computes the round keys on the fly. The other versions all precompute the round subkeys. The last line is a version that precomputes the S-boxes in to dedicated RAM instead of computing the S-boxes on the fly. Depending on the architecture, the logic will grow somewhat in size for larger keys, and the clock speed (or startup time) may increase, but it is believed that a 128-bit AES scheme will be acceptable in the market long enough that most vendors will choose to implement that recommended key length.

These estimates are all based on existing 0.35 micron CMOS technology. All the examples in the table are actually quite small in today’s technology, except the final (highest performance non-pipeline) instance, but even that is very doable today and will become fairly inexpensive as the next generation silicon technology (0.25 micron) becomes the industry norm.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Twofish Design Philosophy

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Chapter 6
Twofish Design Philosophy

In the design of Twofish, we tried to stress the following principles:

Performance. When comparing different options, compare them on the basis of relative performance.
Conservativeness. Do not design close to the edge. In other words, leave a margin for error and provide more security than is provably required. Also, try to design against attacks that are not yet known.
Simplicity. Do not include ad hoc design elements without a clear reason or function. Try to design a cipher whose details can be easily kept in one’s head.

These principles were applied not only to the overall design of Twofish, but to the design of the S-boxes and the key schedule.

6.1 Performance-Driven Design

The goal of performance-driven design is to build and evaluate ciphers on the basis of performance [SW97]. The early post-DES cipher designs would often compete on the number of rounds in the cipher. The original FEAL paper [SM88], for example, discussed the benefits of a stronger round function and fewer rounds. Other cipher designs of the period—REDOC-II [CW91], LOKI89 [BPS90] and LOKI91 [BKPS93], IDEA [LM91, LMM91]—only considered performance as an afterthought. Khufu/Khafre [Mer91] was the first published algorithm that explicitly used operations that were efficient on 32-bit microprocessors; SEAL [RC94, RC98] is a more recent example. RC2 [Riv97, KRRR98] and Jeroboam [CM98] were designed for 16-bit microprocessors, SOBER [Ros98] for 8-bit ones. Other, more recent designs, do not seem to take performance into account at all. Two 1997 designs, SPEED [Zhe97]1 and Zhu-Guo [ZG97], are significantly slower than alternatives that existed years previous.

1SPEED has been cryptanalyzed in [HKSW98, UTK98, HKR+98].

Arbitrary metrics, such as the number of rounds, are not good measures of performance. What is important is the cipher’s speed: the number of clock cycles per byte encrypted. When ciphers are analyzed according to this property, the results can be surprising [SW97]. RC5 might have twice the number of rounds of DES,2 but since its round function is more than twice as fast as DES’, RC5 is faster than DES on most microprocessors.

2Here we use the term “round” in the traditional sense: as it was defined by DES [NBS77] and has been used to describe Feistel-network ciphers ever since. The RC5 documentation [Riv95] uses the term “round” differently: one RC5-defined round equals two Feistel rounds.

Even when cryptographers made efforts to use efficient 32-bit operations, they often lacked a full appreciation of low-level software optimization principles associated with high-performance CPUs. Thus, many algorithms are not as efficient as they could be. Minor modifications in the design of Blowfish [Sch94], SEAL [RC94, RC98], and RC4 [Sch96] could improve performance without affecting security [SW97] (or, alternatively, increase the algorithms’ complexity without affecting performance). In designing Twofish, we tried to evaluate all design decisions in terms of performance.

Since NIST’s platform of choice was the Intel Pentium Pro [NIST97b], we concentrated on that platform. However, we did not ignore performance on other 32-bit CPUs, as well as 8-bit and 16-bit CPUs. If there is any lesson from the past twenty years of microprocessors, it is that the high end gets better and the low end never goes away. Yesterday’s top-of-the-line CPUs are currently in smart cards. Today’s CPUs will eventually be in smart cards, while the 8-bit microprocessors will move to devices even smaller. The only thing we did not consider in our performance metrics is bitslice implementations [Bih97, SAM97, NM97], since these can only be used in very specialized applications and often require unrealistic implementations; e.g., 32 simultaneous ECB encryptions, or 32 interleaved IVs.3

3One AES submission, Serpent [BAK98], uses ideas from bitslice implementations to create a cipher that is optimized for 32-bit processors while sacrificing performance on 8-bit processors.

6.1.1 Performance-driven Tradeoffs

During our design, we constantly evaluated the relative performance of different modifications to our round function. Twofish’s round function encrypts at about 20 clock cycles; 16 rounds translates to about 320 clock cycles per block encrypted. When we contemplated a change to the round function, we evaluated it in terms of increasing or decreasing the number of rounds to keep performance constant. For example:

• We could have added a data-dependent rotation to the output of the two MDS matrices in each round. This would add 10 clock cycles to the round function on the Pentium (two on the Pentium Pro). To keep the performance constant, we would have to reduce the number of rounds to 11. The question to ask is: Are 11 rounds of the modified cipher more or less secure than 16 rounds of the unmodified cipher?
• We could have removed the one-bit rotation. This would have saved clocks equivalent to one Twofish round. Are 17 rounds of this new round function more or less secure than 16 rounds of the old one?
• We could have defined the key-dependent S-boxes using the whole key, instead of half of it. This would have doubled key setup time on high-end machines, and halved encryption speed on memory-poor implementations (where the S-boxes could not be precomputed). On memory-poor machines, we would have to cut the number of rounds in half to be able to afford this. Are 8 rounds of this improved cipher better than 16 rounds of the current design?

This analysis is necessarily dependent on the microprocessor architecture the algorithm is being compared on. While we focused on the Intel Pentium architecture, we also tried to keep 8-bit smart card and hardware implementations in mind. For example, we considered using an 8-by-8 MDS matrix over GF(24) to ensure a finer-grained diffusion, instead of a 4-by-4 MDS matrix over GF(28); the former would have been no slower on a Pentium but at least twice as slow on a low-memory smart card.

6.2 Conservative Design

In the last decade there has been considerable research in designing ciphers to be resistant to known attacks [Nyb91 Nyb93, OCo94a, OCo94b, OCo94c, Knu94a, Knu94b, Nyb94, DGV94b, Nyb95, NK95, Mat96, Nyb96], such as differential [BS93], linear [Mat94], and related-key cryptanalysis [WH87, Bih94, KSW96, KSW97]. This research has culminated in strong cipher designs—CAST-128 [Ada97a] and MISTY [Mat97] are probably the most noteworthy—as well as some excellent cryptanalytic theory.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Twofish Design Philosophy

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

However, it is dangerous to rely solely on theory when designing ciphers. Ciphers provably secure against differential cryptanalysis have been attacked with higher-order differentials [Lai94, Knu95b] or the interpolation attack [JK97]: KN-cipher [NK95] was attacked in [JK97, SMK98], Kiefer [Kie96] in [JK97], and a version of CAST in [MSK98a]. The CAST cipher cryptanalyzed in [MSK98a] is not CAST-128, but it does illustrate that while the CAST design procedure [AT93, HT94a] can create ciphers resistant to differential and linear cryptanalysis, it does not create ciphers resistant to whatever form of cryptanalysis comes next. SNAKE [LC97], another cipher provably secure against differential and linear cryptanalysis, was successfully broken using the interpolation attack [MSK98b). When designing a cipher, it is prudent to assume that new attacks will be developed in order to break it.

We took a slightly different approach in our design. Instead of trying to optimize Twofish against known attacks, we tried to make Twofish strong against both known and unknown attacks. While it is impossible to optimize a cipher design for resisting attacks that axe unknown, conservative design and overengineering can instill some confidence.

Many elements of Twofish reflect this philosophy. We used well-studied design elements throughout the algorithm. We started with a Feistel network, probably the most studied block-cipher structure, instead of something newer like an unbalanced Feistel network [SK96, ZMI90] or a generalized Feistel network [Nyb96].

We did not implement multiplication mod 216 + 1 (as in IDEA or MMB [DGV93]) or data-dependent rotations (as in Madryga [Mad84] and RC54 or Akelarre [AGMP96]5) for non-linearity. The most novel design elements we used-MDS matrices and PHTs-are only intended for diffusion (and are used in Square [DKR97] and SAFER, respectively).

4RC5’s security is almost wholly based on data-dependent rotations. Although initial cryptanalysis was promising [KY95] (see also [Se198]), subsequent research [KM97, BK98] suggests that there is considerably more to learn about the security properties of data-dependent rotations.
5Akelaxre was severely broken in [FS97, KR97].

We used key-dependent S-boxes because they offer adequate protection against known statistical attacks and are likely to offer protection to any unknown similar attacks. We defined Twofish at 16 rounds, even though our analysis cannot break anywhere near that number. We added one-bit rotations to prevent potential attacks that relied solely on the byte structure. We designed a very thorough key schedule to prevent related-key and weak-key attacks.

6.3 Simple Design

A guiding design principle behind Twofish is that the round function should be simple enough for us to keep in our heads. Anecdotal evidence from algorithms like FEAL [SM88], CAST, and Blowfish indicates that complicated round functions are not always better than simple ones. Also, complicated round functions are harder to analyze and rely on more ad hoc arguments for security (e.g., REDOC-II [CW91]).

However, with enough rounds, even bad round functions can be made to be secure.6 Even a simple round function like TEA’s [WN95] or RC5’s seems secure after 32 rounds [BK98]. In Twofish, we tried to create a simple round function and then iterate it more than enough times for security.

6Student cryptography projects bear this observation out. At 16 rounds, the typical student cipher fares rather badly against a standard suite of statistical tests. At 32 rounds, it looks better. At 128 rounds, even the worst designs look very good.

6.3.1 Reusing Primitives

One of the ways to simplify a design is to reuse the same primitives in multiple parts of a cipher. Cryptographic design does not lend itself to the adage of not putting all your eggs in one basket. Since any particular “basket” has the potential of breaking the entire cipher, it makes more sense to use as few baskets as possible—and to scrutinize those baskets intensely.

To that end, we used essentially the same construction (8-by-8-bit key-dependent S-boxes consisting of alternating fixed permutations and subkey XORs followed by an MDS matrix followed by a PHT) in both the key schedule and the round function. The differences were in the key material used (the round function’s g function uses a list of key-derived words processed by an RS code; the key schedule’s h function uses individual key bytes directly) and the rotations. The rotations represent a performance-driven design trade-off: putting the additional rotations into F would have unacceptably slowed down the cipher performance on high-end machines. The use of the RS code to derive the key material for g adds substantial resistance to related-key attacks.

While many algorithms reuse the encryption operation in their key schedule (e.g., Blowfish, Panama [DC98a, DC98b], RC4, CRISP [Lee96], YTH [YTH96]), and several alternative DES key schedules reuse the DES operation [Knu94b, BB96], we are unaware of any that reuse the same primitives in exactly this manner.7 We feel that doing so greatly simplifies the analysis of Twofish, since the same kinds of analysis can apply to the cipher in two different ways.

7The closest idea is an alternate DES key schedule that uses the DES round function, both the 32-bit block input and 48-bit key input, to create round subkeys [Ada97b].

6.3.2 Reversibility

While it is essential that any block cipher be reversible, so that ciphertext can be decrypted back into plaintext, it is not necessary that the identical function be used for encryption and decryption. Some block ciphers are reversible with changes only in the key schedule (e.g., DES, IDEA, Blowfish), while others require different algorithms for encryption and decryption (e.g., SAFER, Serpent, Square).

The Twofish encryption and decryption round functions are slightly different, but are built from the same blocks. That is, it is simple to build a hardware or software module that does both encryption and decryption without duplicating much functionality, but the exact same module cannot both encrypt and decrypt.

Note that having the cipher work essentially the same way in both directions is a nice feature in terms of analysis, since it lets analysts consider chosen-plaintext and chosen-ciphertext attacks at once, rather than considering them as separate attacks with potentially radically different levels of difficulty [Cop98].


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Twofish Design Philosophy

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

6.4 S-boxes

The security of a cipher can be very sensitive to the particulars of its S-boxes: size, number, values, usage. Ciphers invented before the public discovery of differential cryptanalysis sometimes used arbitrary sources for their S-box entries.

Randomly constructed known S-boxes are unlikely to be secure. Khafre uses S-boxes taken from the RAND tables [RAND55], and it is vulnerable to differential cryptanalysis [BS92]. NewDES8 [Sco85], with S-boxes derived from the Declaration of Independence [Jeff+76], could be made much stronger with good S-boxes. DES variants with random fixed S-boxes are very likely to be weak [BS93, Mat95], and CMEA was weakened extensively because of a poor S-box choice [WSK97].

8Despite the algorithm name, NewDES is neither a DES variant nor a new algorithm based on DES.

Some cipher designers responded to this threat by carefully crafting S-boxes to resist known attacks—DES [Cop94], sn DES [KPL93, Knu93c, KLPL95], CAST [MA96, Ada97a]—while others relied on random key-dependent S-boxes for security—Khufu, Blowfish, WAKE [Whe94].9 The best existing attack on Khufu breaks 16 rounds [CC94], while the best attack on Blowfish breaks only four [Rij7]. Serpent [BAK98] reused the DES S-boxes.

9The WAKE design has several variants (Cla97, CIa98]; neither the basic algorithm nor its variants have been extensively cryptanalyzed.

GOST [GOST89] navigated a middle course: each application has different fixed S-boxes, turning them into an application-specific family key.

6.4.1 Large S-boxes

S-boxes vary in size, from GOST’s 4-by-4-bit S-boxes to Tiger’s 8-by-64-bit S-boxes [AB96b]. Large S-boxes are generally assumed to be more secure than smaller ones—a view we share—but at the price of increased storage requirements; DES’ eight 6-by-4-bit S-boxes require 256 bytes of storage, while Blowfish’s four 8-by-32-bit S-boxes require 4 Kbytes. Certainly input size matters more than output size; an 8-by-64-bit S-box can be stored in 2 Kbytes, while a 16-by-16-bit S-box requires 128 Kbytes. (Note that there is a limit to the advantages of making S-boxes bigger. S-boxes with small input size and very large output size tend to have very good linear approximations; S-boxes with sufficiently large outputs relative to input size axe guaranteed to have at least one perfect linear approximation [Bih95].)

Twofish used the same solution as Square: mid-sized S-boxes (8-by-8-bit) used to construct a large S-box (8-by-32-bit).

6.4.2 Algorithmic S-boxes

S-boxes can either be specified as large tables, like DES, Khufu/Khafre, and YLCY [YLCY98], or derived algebraically, like FEAL, LOKI89/LOKI91 (and LOKI97 [Bro98]), IDEA, and SAFER. The advantage of the former is that there is no mathematical structure that can potentially be used for cryptanalysis. The advantage of the latter is that the S-boxes are more compact, and can be more easily implemented in applications where the ROM or RAM for large tables is not available.

Algebraic S-boxes can result in S-boxes that are vulnerable to differential cryptanalysis: [Mur90] against FEAL, and [Knu93a, Knu93b] against LOKI. Higher-order differential cryptanalysis is especially powerful against algorithms with simple algebraic S-boxes [Knu95b, JK97, SMK98].

Both tabular and algebraic techniques, however, can be used to generate S-boxes with given cryptographic properties simply by testing the results of the generation algorithm. There has been much written about testing S-boxes for their resistance to different statistical attacks, starting from the work done on DES [AT90, AT93, Cop94, Ada97a, Mor98].

In Twofish we tried to do both: we chose to build our 8-by-8-bit S-boxes algorithmically out of 4-by-4-bit S-boxes. However, we chose the 4-by-4-bit S-boxes randomly and then extensively tested the resulting 8-by-8-bit S-boxes against the cryptographic properties we required. This idea is similar to the one used in CS-Cipher [SV98].

6.4.3 Key-dependent S-boxes

S-boxes are either fixed for all keys or key dependent. It is our belief that ciphers with key-dependent S-boxes are, in general, more secure than fixed S-boxes.

There axe two different philosophies regarding key-dependent S-boxes. In some ciphers, the S-box is constructed specifically to ensure that no two entries are identical—Khufu and WAKE—while others simply create the S-box randomly and hope for the best: REDOG-II [CW91] and Blowfish [Sch94]. The latter results in a simpler key schedule, but may result in weaknesses (e.g., a weakness in reduced-round variants of Blowfish [Vau96a]). Another strategy is to generate key-dependent S-boxes from a known secure S-box and a series of strict mathematical rules: e.g., Biham-DES [BB94].

Most key-dependent S-boxes are created by some process completely orthogonal to the underlying cipher. SEAL, for example, uses SHA [NIST93] to create its key-dependent S-boxes. Blowfish uses repeated iterations of it-self The results are S-boxes that axe effectively random, but the cost is an enormous performance penalty in key setup time.10

10For example, setting up a single Blowfish key takes as much time as encrypting 520 blocks, or 4160 bytes, of data.

An alternative is to build the S-boxes using fairly simple key-dependent operations from fixed S-boxes. This results in a much faster key setup, but unless the creation algorithm is extensively cryptanalyzed together with the encryption algorithm, unwanted synergies could lead to attacks on the resulting cipher.

To avoid differential (as well as high-order differential, linear, and related-key) attacks, we made the small S-boxes key dependent. It is our belief that while random key-dependent S-boxes can offer acceptable security if used correctly, the benefits of a surjective S-box are worth the additional complexities that constructing them entails. So, to avoid attacks based on non-surjective round functions [BB95, RP95b, RPD97, CWSK98], we made the 8-by-8-bit S-boxes bijective.

This construction is similar to Skipjack’s use of a single fixed 8-by-8-bit S-box, four key bytes, and a 4-round Feistel structure to create five different 16-by-16-bit key-dependent S-boxes [NSA98].

However, there is really no such thing as a key-dependent S-box. Twofish uses a complex multi-stage series of S-boxes and round subkeys that are often precomputed as key-dependent S-boxes for efficiency purposes. (For example, see Figure 4.3 on page 18.) We often used this conceptualization. when carrying out our own cryptanalysis against Twofish.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Twofish Design Philosophy

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

6.5 The Key Schedule

An algorithm’s key schedule is the mechanism that distributes key material to the different parts of the cipher that need it, expanding the key material in the process. This is necessary for three reasons:

• There are fewer key bits provided as input to the cipher than are needed by the cipher.
• The key bits used in each round must be unique to the round in order to avoid “slide” attacks [Wag95b].
• The cipher must be secure against an attacker with partial knowledge or control over some key bits.

When key schedules are poorly designed, they often lead to strange cipher properties: large classes of equivalent keys, self-inverse keys, and so forth. These properties can often aid an attacker in a real-world attack. For example, the DES weak (self-inverse) keys have been exploited in many attacks on larger cryptographic mechanisms built from DES [Knu95a], and the S-1 [Anon95] cipher was broken due to a bad key-schedule design [Wag95a]. Even worse, they can make attacks on the cipher easier, and some attacks on the cipher will be focused directly at the key schedule, such as related-key differential attacks [KSW96, KSW97]. These attacks can be especially devastating when the cipher is used in a hash function construction.

Key schedules can be divided into several broad categories [CDN98]. In some key schedules, knowledge of a round subkey uniquely specifies bits of other round subkeys. In some ciphers the bits are just reused, as in DES, IDEA, and LOKI; and in others some manipulation of the round subkeys is required to determine the other round subkeys: e.g., CAST and SAFER. Other key schedules are designed so that knowledge of one round subkey does not directly specify bits of other round subkeys. Either the round subkey itself is used to generate the other round subkeys in some cryptographically secure manner, as in RC5 and CS-Cipher [SV98], or a one-way function is used to generate the round subkeys (sometimes the block cipher itself): e.g., Blowfish, Serpent [BAK98], ICE11 [Kwa97], and Shark.

11ICE was cryptanalyzed in [RKR98].

Some simple design principles guided our development of the key schedule for Twofish:

Design the Key Schedule for the Cipher. This is not simply a cryptographic PRNG or hash function grafted onto the cipher; the Twofish key schedule is instead an integral part of the whole cipher design.
Reuse the Same Primitives. The Twofish key schedule’s subkey generation mechanism, h, is built from the same primitives as the Twofish round function. This allowed us to apply much of the same analysis to both the round function and the subkey generation. This also makes for a relatively simple picture of the cipher and key schedule together. It is reasonable to consider one round’s operations and the derivation of its subkeys at the same time.
Use All Key Bytes the Same Way. All key material goes through h (or g, which is the same function). That is, the only way a key bit can affect the cipher is after it defines a key-dependent S-box. This allows us to analyze the properties of the key schedule in terms of the properties of the byte permutations.
Make It Hard to Attack Both S-box and Subkey Generation. The key material used to derive the key-dependent S-boxes in g is derived from the key using an RS code having properties similar to those of the MDS matrix. Deriving the key material in this way maximizes the difficulties of an attacker’s trying to mount any kind of related-key attack on the cipher, by giving him conflicting requirements between controlling the S-box keys and controlling the subkeys.

The key schedule design of some other ciphers has led to various undesirable properties. These properties, such as the existence of equivalent keys; DES-style weak, semi-weak, and quasi-weak keys; and DES-style complementation properties do not necessarily make the cipher weak. However, they tend to make it harder to use the cipher securely. With our key schedule, we can make convincing arguments that none of these properties exists.

6.5.1 Performance Issues

Key schedules vary widely in performance. The DES key schedule can be computed in less than the time required to do one encryption. The Blowfish key schedule requires the time equivalent to 521 encryptions to complete. Most other algorithms fall somewhere in the middle.

For large messages, performance of the key schedule is minor compared to performance of the encryption and decryption functions. For smaller messages, key setup can overwhelm encryption speed. In the design of Twofish, we tried to balance these two items. Our performance criteria included:

• The key schedule must be precomputable for maximal efficiency. This involves trying to minimize the amount of storage required to keep the precomputed key material.
• The key schedule must work “on the fly,” deriving each block of subkey material as it is needed, with as little required memory as possible.
• The key schedule must be reasonably efficient for hardware implementations.
• The key schedule must have minimal latency for changing keys.12
12In its comments on the AES criteria, the NSA suggested that “a goal should be that two blocks could be enciphered with different keys in virtually the same time as two blocks could be enciphered with the same key” [McD97]. The cynical reader would immediately conclude that the NSA is concerned with the efficiency of their brute-force keysearch machines. However, there axe implementations where key agility is a valid concern. Key-stretching techniques can always be used to frustrate brute-force attacks [QDD86, KSHW98]. A better defense, of course, is to always use keys too laxge to make a brute-force search practicable, and to generate them randomly.

If security were not an issue, we would design a simple key schedule where the key bits were used in some natural order, like Skipjack, or with some minimal shuffling, like DES and IDEA. However, these key schedules cause weaknesses when the block cipher is used as a one-way hash function.

If performance were not an issue, it would make sense to simply use a one-way hash function to expand the key into the subkeys and S-box entries, as is done in Khufu, Blowfish, and SEAL. However, the AES efficiency requirements make such an approach unacceptable.

Balancing these two requirements led us to design a relatively simple key schedule with a very complicated analysis.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:The Design of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Chapter 7
The Design of Twofish

7.1 The Round Structure

An n-bit block cipher with a k-bit key uses its key to select among 2k possible different permutations on the 2n. possible inputs/outputs to the cipher. This can be imagined as an enormous (virtual) codebook; each possible n-bit plaintext block leads to only one possible n-bit ciphertext block under a given key. Data is encrypted in n-bit chunks, with each n-bit chunk's encryption independent of other encryptions. This can be contrasted with a stream cipher, where different parts of the message are treated differently. The goal for a block cipher is to be impossible in practice to distinguish from a random permutation family on n-bit blocks.

DES is a 64-bit cipher, and most block ciphers in the literature are also 64-bit ciphers; AES, on the other hand, requires a 128-bit block cipher.

A product cipher (sometimes called an iterative block cipher) is a block cipher made by iterating a fairly simple round function many times, each time with its own key. Thus, a 4-round product cipher would look like

EK(X) = RK3(RK2(RK1(RK0(X))))

where K0...3 are functions of K.

Each round function, RK(), is actually a weak block cipher. It implements the basic Shannon principles of encryption, confusion and diffusion [Sha49], and can be viewed as a key-dependent transformation of plaintext into ciphertext. It is weak in the sense that if an attacker knows much about the plaintext (such as simple plaintext statistics), he can quickly break the round function and recover its round key.

Even a very weak round function is resistant to attack when the sequence of inputs to the function is random and unknown to the attacker. Iterating the round function many times makes the input to the last round very hard for an attacker to guess; this prevents the attacker from being able to attack the last round, and thus prevents him from attacking the cipher as a whole. An increased number of rounds means a decrease in the throughput of a cipher, but an attack effective against an n-round version of a particular algorithm might be ineffective against an n + 1-round version. Some of the best cipher analysis shows how to break reduced-round variants of the design and why each attack cannot be extended to a greater number of rounds.

Fig. 7.1. A Simple SP-network Construction

7.1.1 Common Block Cipher Structures

All well-known block ciphers use this iterated round structure, and given the number of different algorithms that have been proposed over the years, there are surprisingly few round-function structures.

SP Networks. These were named by Horst Feistel [Fei73, FNS75], although the ideas are much older. “SP” stands for “substitution-permutation,” and one round of an SP-network consists of a substitution layer followed by a permutation layer. These two layers are meant to capture C. Shannon’s fundamental notions in cipher design of confusion and diffusion [Sha49]. The substitution layer confuses the statistics of the input by breaking it up into smaller pieces and performing substitutions on those pieces. The permutation layer diffuses the statistics of the input by rearranging the bits output from the substitution layer, each of which should be a function of more than one input bit. Figure 7.1 gives a simple SP-network construction (which is not secure).

SP-networks have been well-studied in the cryptographic literature; examples of SP-network designs are SAFER [Mas94], Shark [RDP+96], and Square [DKR97].1 Rotor machines can be viewed as SP networks: the rotor is a substitution layer, and the key-dependent stepping of the rotor is the permutation.

1 See also [HT94b].

Feistel Networks. These were invented by Horst Feistel [FNS75] in his design of Lucifer[Fei73]. The fundamental building block of a Feistel network is the F function, a key-dependent mapping of an input string onto an output string. An F function is always non-linear and possibly non-surjective2

2 A non-surjective F function is one in which not all outputs in the output space can occur.

F : {0,1}n/2 × {0, 1}k → {0, 1}n/2

where n is the block size of the Feistel network, and F is a function taking n/2 bits of the block and k bits of a key as input, and producing an output of length n/2 bits. In each round, the “source block” is the input to F, and the output of F is XORed with the “target block,” after which these two blocks swap places for the next round. Feistel networks are the most studied block cipher structure, and are the basis for most of the algorithms proposed in the literature.

Fig. 7.2. A 3-round Feistel Network

Figure 7.2 shows a 3-round Feistel network. Here (PL, PR) is the plaintext, (CL, CR) is the ciphertext, (L1, R1) and (L2, R2) are intermediate values, and K1, K2, and K3 are round-dependent subkeys.

In order to decrypt the ciphertext (CL, CR) one starts at the tail end of the network and works backwards. It is important to understand that data flows the same direction through F even during decryption and that the reversibility of the network comes from the property that α ⊕ α = 0 for any α. This is easy to see if we compute the ciphertext as a function of the plaintext:

(L1, R1) = (PL, PR ⊕ F(PL))
(L2, R2) = (R1, L1 ⊕ F(R1))
(CL, CR) = (R2, L2 ⊕ F(R2))

Then reversing the network we find:

(L2, R2) = (CR ⊕ F(CL), CL)
(L1, R1) = (R2 ⊕ F(L2), L2)
(PL, PR) = (R1 ⊕ F(L1), L1)

Fig. 7.3. An Incomplete 2-round Feistel Network

Incomplete Feistel Networks. This is a variant of the Feistel network where the F-function has an input and output size that is some fraction of n other than n/2. Skipjack, for example, has an F-function whose input and output is one-quarter the block size [NSA98]:

F : {0,1}n/4 × {0, 1}k → {0, 1}n/4

Figure 7.3 shows a 2-round variant of an incomplete Feistel network whose F-function also has an input and output of one-quarter the block size. In each round, the source block is the input into F, and is XORed with the target block; the other bits are unused in the round (hence the name “incomplete Feistel network”).3 Then, the subblocks are rotated among each other, so that each subblock becomes the source and target in subsequent rounds. The first incomplete Feistel networks in the literature were Khufu and Khafre [Mer91], although their similarities to shift-register-based stream ciphers (common in military cryptographic hardware) make it likely that there is a significant amount of classified literature on their design and analysis.

3A taxonomy of these Feistel-network variants can be found in [SK96].

Source-heavy Feistel Networks. In this variant of the Feistel network, the source and target blocks are of different size, with the source block larger than the target block. Both RC2 [Riv97] and MacGuffin [BS95] have a 48-by-16-bit source-heavy structure; the F-function takes a 48-bit input and produces a 16-bit output. The underlying block cipher in MD4 [Riv91] and MD5 [Riv92] are 96-by-32-bit structures. SHA-1 [NIST93] is a 128-by-32-bit structure. Figure 7.4 shows a source-heavy 2-round Feistel network.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:The Design of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Target-heavy Feistel Networks. These are the opposite: Feistel-type networks where the F-function has a larger output than input. Tiger [AB96b] uses a 64-by-192-bit target-heavy structure. Figure 7.5 shows a target-heavy 2-round Feistel network.

Other Variants. There are other round function structures, which are variants of the above. IDEA [LMM91] is a variant of an SP-network, for example. In “fenced” constructions, multiple parallel implementations of the same structure are separated by specially constructed mixing operations [Rit96].

Fig. 7.4. A Source-heavy 2-round Feistel Network

Fig. 7.5. A Target-heavy 2-round Feistel Network

Although there has been some analysis of incomplete, source-heavy, and target-heavy Feistel networks [SK96], they are not nearly as well-understood as Feistel and SP networks. Given the current state of analysis, we discarded any of the newer structures.

Our Choice. Twofish was designed as a Feistel network, primarily because it is one of the most studied block-cipher building blocks, but also because the Feistel structure takes care of its own inverse. The structure of a Feistel network means that the F function need only be calculated in one direction.4 This means that we were able to use operations in our F function that are inefficient in the other direction, and make do with tables and constants for one direction only. Contrast this with an SP-network, which must execute its encryption function in both the forward and backward directions.

4In fact, the F function can be non-surjective, as it is in DES or Blowfish.

7.2 The Key-dependent S-boxes

A fundamental component of Twofish is the set of four key-dependent S-boxes. These must have several properties:

• The four different S-boxes actually need to be different.
• Few or no keys may cause the S-boxes used to be “weak,” in the sense of having high-probability differential or linear characteristics, or in the sense of having a very simple algebraic representation.
• There should be few or no pairs of keys that define the same S-boxes. That is, changing even one bit of the key used to define an S-box should always lead to a different S-box. In fact, these pairs of keys should lead to extremely different S-boxes.

7.2.1 The Fixed Permutations q0 and q1

The construction method for building q0 and q1 from 4-bit permutations (specified in Section 4.3.5) was chosen because it decreases hardware and memory costs for some implementations, as discussed previously, without adding any apparent weaknesses to the cipher. It is helpful to recall that these individual fixed-byte permutations are used only to construct the key-dependent S-boxes, which, in turn, are used only within the h and g functions. In particular, the individual characteristics of q0 and q1 are not terribly relevant (except perhaps in some related-key attacks), because Twofish always uses at least three of these permutations in series together with at least two XORs with key material bytes.

Consideration was initially given to using random full 8-bit permutations for q0 and q1, as well as algebraically derived permutations (e.g., multiplicative inverses over GF(28)) that have slightly better individual permutation characteristics, but no substantial improvement was found when composite keyed S-boxes were constructed and compared to the q0 and q1 used in Two-fish.

The construction of q0 and q1 is a basically a 2-round SP network. We investigated several possible constructions. The main alternative was a 3- or 4-round Feistel network. We chose the SP network, as it has a lower circuit-depth. This reduces the propagation delay in a hardware implementation of the q-box. As several q-boxes are used in series, an increase in propagation delay has significant effects on the hardware speed of the cipher.

The q0 and q1 permutations were constructed by performing a random search for the 4-bit permutations t0, t1, t2, and t3. Using the notation of Matsui [Mat96], we define

and

where q is the mapping DPmax and LPmax are being computed for, the probabilities are taken over a uniformly distributed X, and the operator computes the overall parity of the bitwise-AND of its two operands. Only fixed permutations with DPmax ≤ 10/256, LPmax ≤ 1/16, and fewer than three fixed points5 were accepted as potential candidates. These criteria alone rejected over 99.8 percent of all randomly chosen permutations of the given construction. Pairs of permutations meeting these criteria were then evaluated as potential (q0, q1) pairs, computing various metrics when combined with key material into Twofish’s S-box structure, as described below.

5A fixed point for a function f is a value x such that f(x) = x.

The actual q0 and q1 chosen were one of several pairs with virtually identical statistics that were found with only a few tens of hours of searching on Pentium class computers. Each permutation has DPmax = 10/256 and LPmax = 1/16; q0 has one fixed point, while q1 has two fixed points.

7.2.2 The S-boxes.

Each S-box is defined with two, three, or four bytes of key material, depending on the Twofish key size. This is done as follows for 128-bit Twofish keys:

s0(x) = q1[q0[q0[x] ⊕ s0,0] ⊕ s1,0]
s1(x) = q0[q0[q1[x] ⊕ s0,1] ⊕ s1,1]
s2(x) = q1[q1[q0[x] ⊕ s0,2] ⊕ s1,2]
s3(x) = q0[q1[q1[x] ⊕ s0,3] ⊕ s1,3]

where the si,j are the bytes derived from the key bytes using the RS matrix. Note that if s0,i = s0,j and s1,i = s1,j for i ≠ j, then si(x) ≠ sj(x) for most values of x. In fact, as each S-box uses a unique order of q-boxes, it is extremely unlikely that two different S-boxes could produce the identical mapping.

Note that when all si,j = 0, then s0(x) = q1[s1(q1–1[x])]. Similar relationships hold between other S-boxes. We have not been able to find any weaknesses resulting from this, as long as q0 and q1 have no high-probability differential characteristics.

In some sense this construction is similar to a rotor machine [PB92, DK85, Bau93, Bau97], with two different types of rotor (q0 and q1). The first rotor is fixed, and the fixed offset between two rotors is specified by a key byte. We did not find any useful cryptanalysis from this parallel, but someone else might.

For the 128-bit key, we have experimentally verified that each N/8-bit key used to define a byte permutation results in a distinct permutation. For example, in the case of a 128-bit key, the S-box s0 uses 16 bits of key material. Each of the 216 s0 permutations defined is distinct, as is also the case for s1, s2, and s3. We have not yet exhaustively tested longer key lengths, but we conjecture that all S-boxes generated by our construction are distinct. We also conjecture that this would be the case for almost all choices of q0 and q1 meeting the basic criteria discussed above.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:The Design of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

 |  | – log2(Pr(DPmax = x/256))
Key Size | Max Value | x = | 8 | 10 | 12 | 14 | 16 | 18 | 20 | 22 | 24
128 bits | 18/256 | 15.4 | 1.3 | 0.9 | 4.1 | 8.0 | 12.0 |  |  |
192 bits | 24/256 | 15.2 | 1.3 | 0.9 | 4.1 | 8.0 | 12.2 | 16.5 | 20.8 | 25.0
256 bits* | 22/256 | 15.1 | 1.3 | 0.9 | 4.1 | 8.0. | 12.2 | 16.7 | 22.0 |
Table 7.1. DPmax Over All Keys

7.2.3 Exhaustive and Statistical Analysis

Given the fixed permutations q0 and q1, and the definitions for how to construct s0, s1, s2, and s3 from them, we have performed extensive testing of the characteristics of these key-dependent S-boxes. In the 128-bit key case, all testing has been performed exhaustively, which is feasible because each S-box uses only 16 bits of key material. In many cases, however, only statistical (i.e., Monte Carlo) testing has been possible for the larger key sizes. In this section, we present and discuss these results. It is our hope to complete exhaustive testing over time for the larger key sizes where feasible, but the probability distributions obtained for the statistical tests give us a fairly high degree of confidence that no surprises are in store.

Computing DPmax Over All Keys. Table 7.1 shows the DPmax distribution for the various key sizes. A detailed explanation of the format of this table will also help in understanding the other tables in this section. An asterisk (*) next to a key size in the tables discussed in this section indicates that the entries in that row are a statistical distribution using Monte Carlo sampling of key bits, not an exhaustive test. For example, in Table 7.1, only the 256-bit key row uses statistical sampling; the 128-bit and 192-bit cases involve an exhaustive test. Clearly, the maximum value from a statistical sample is not a guaranteed maximum.

Note that, for 128-bit keys, each S-box has a DPmax value no larger than 18/256. The remaining columns give the distribution of observed DPmax values. Each entry is expressed as the negative base-2 logarithm of the fraction of S-boxes with the given value (or value range), with blank entries indicating that no value in the range was found. For example, in the N = 128 case only one of every 212.0 key-dependent S-boxes has DPmax = 18/256, while over half (1 in 20.9) have DPmax = 12/256. These statistics are taken over all four S-boxes (s0, s1, s2, s3), so a total of 4 × 216 (i.e., 256K) S-boxes were evaluated for the 128-bit key case. Each Monte Carlo sampling involves at least 216 S-boxes, but in many cases the number is considerably larger.

Computing LPmax Over All Keys. Table 7.2 shows the distribution of LPmax for the various key sizes. Observe that the vast majority of Twofish S-boxes have LPmax < (88/256)2, although there is a small fraction of S-boxes with larger values. For 128-bit keys, no Twofish S-box has an LPmax value greater than (100/256)2, while the maximum value is somewhat higher for larger key sizes. Monte Carlo statistics are given for the larger two key sizes, since the computational load for computing LPmax is roughly a factor of 15 higher than for DPmax.

 |  | – log2(Pr(LPmax = (x/256)2))
Key size | Max Value | x = | 56..63 | 64..71 | 72..79 | 80..87 | 88..95 | 96..103 | 104..111
128 bits | (100/256)2 | 9.3 | 1.0 | 1.2 | 4.2 | 8.0 | 12.4 |
192 bits* | (104/256)2 | 9.3 | 1.0 | 1.2 | 4.2 | 8.2 | 12.2 | 17.0
256 bits* | (108/256)2 | 9.4 | 1.0 | 1.2 | 4.2 | 8.1 | 12.5 | 17.4
Table 7.2. LPmax Over All Keys.

 |  | – log2(Pr(# fixed points = x))
Key Size | Max Value | x = | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10
128 bits | 8 | 1.4 | 1.4 | 2.4 | 4.1 | 6.0 | 8.2 | 11.1 | 14.1 | 17.0 |  |
192 bits | 10 | 1.4 | 1.4 | 2.4 | 4.0 | 6.0 | 8.4 | 10.9 | 13.8 | 16.8 | 19.8 | 23.4
256 bits* | 10 | 1.4 | 1.4 | 2.4 | 4.0 | 6.0 | 8.4 | 10.9 | 13.7 | 16.8 | 21.0 | 21.0
random |  | 1.4 | 1.4 | 2.4 | 4.0 | 6.0 | 8.3 | 10.9 | 13.7 | 16.7 | 19.9 | 23.2
Table 7.3. Number of Fixed Points Over All Keys


The Twofish Encryption Algorithm A 128-Bit Block Cipher:The Design of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Counting Fixed Points Over All Keys. The distribution of the number of permutation fixed points for various key sizes is given in Table 7.3. A fixed point of an S-box si is a value x for which x = si(x). This metric does not necessarily have any direct cryptographic significance. However, it is a useful way to verify that the S-boxes are behaving similarly to random S-boxes, since it is possible to compute the theoretical distribution of fixed points for random S-boxes. The probabilities for random bijective S-boxes is given in the last row. (The probability of n fixed points is approximately e–1/n!.) The Twofish S-box distributions of fixed points over all keys match theory fairly well.

Differences between S-boxes. The metrics discussed so far give us a fair level of confidence that the Twofish method of constructing key-dependent S-boxes does a reasonable job of approximating a random set of S-boxes, when viewed individually. Another possible concern is how different the various Twofish S-boxes are from each other, for a given key length. This issue is of particular interest in dealing with related-key attacks, but it also has an important bearing on the ability of an attacker to model the S-boxes. Despite the fact that the Twofish S-boxes are key dependent, if the entire set (or large subsets) of S-boxes, taken as a black box, are very closely related, the benefit of key dependency is severely weakened. As a pathological example, consider a fixed 8-bit permutation q[x] which has very good DPmax and LPmax values, but which is used as a key-dependent family of S-boxes simply by defining sk(x) = q[x]⊕k. It is true that each sk permutation also has good individual metrics, but the class of s permutations is so closely related that conventional differential and linear cryptanalysis techniques can probably be effectively applied without knowing the key k. The Twofish S-box structure has been carefully designed with this issue in mind.

For example, if an attacker wants to perform a differential attack that is not key dependent, then he can view each S-box as a series of q-boxes and XORs with key bytes. The direct consequence is that he needs to use 3 to 5 differential characteristics of q-boxes per S-box, which makes the probability of any differential characteristic much smaller.

In one class of related-key attacks, an attacker attempts to modify the key bytes in such a way as to minimize the differences in the round subkey values Ai, Bi. Since the Twofish S-box structure is used in computing Ai and Bi, with Me and Mo. as key material, respectively, a measure of the differential characteristics of Ai (or Bi) across keys M will help us understand both how different the S-boxes are from each other and how likely such an attack is to succeed.

To this end, let us first look at how many consecutive values of Ai with a fixed XOR difference can be generated for two different keys. That is, if Ai is the sequence for the key M and A´i is the sequence for the key M´, then we want to examine how many consecutive Ai, A´i satisfy Ai ⊕ A´i = δ for some fixed XOR difference δ. A nearly identical argument holds for the Bi, so we can restrict our attention to the Ai, and furthermore, we can consider only those changes which affect Me, the key material used by the S-boxes when computing Ai.

If we let yi be the output sequence for one S-box used in generating the Ai, and y´i the output sequence for the same S-box when generating the A´i, then we can consider the difference sequence y* = yi ⊕ y´i. For example, in the 128-bit key case, with 16 bits of key material per S-box, there are about 231 distinct pairs of keys for each S-box, so there would be 231 such difference sequences, each of length 20. We can then consider the probability of having a “run” of n consecutive equal values in the sequence. If n can be made to approach 20, then a related-key attack might be able to control the entire sequence of Ai values, and, even worse, our belief in the independence of the key-dependent S-boxes must be called seriously into question. Note that an attacker has exactly 16 bits of freedom for a single S-box in the 128-bit key case, so intuitively it seems unlikely that he should be able to force a given difference sequence that is very long.

Table 7.4 shows the distribution of run lengths of the same XOR difference y*i for consecutive i. For random byte sequences, we would theoretically expect that Pr(XOR run length = n) should be roughly 2–8(n–1), which matches quite nicely with the behavior observed in the table. It can be seen that the probability of injecting a constant difference into more than five consecutive subkey entries is extremely low, which is reassuring.

 |  | – log2(Pr(XOR run length = n))
Key Size | Max Value | n = | 1 | 2 | 3 | 4 | 5
128 bits | 5 | 0.01 | 7.98 | 15.95 | 23.89 | 30.00
192 bits* | 4 | 0.01 | 7.98 | 15.93 | 23.69 |
256 bits* | 5 | 0.01 | 7.98 | 15.93 | 24.02 | 30.29
Table 7.4. Subkey XOR Difference Run Lengths

 |  | – log2(Pr(max # equal XOR differences = n))
Key Size | Max Value | x = | 1 | 2 | 3 | 4 | 4 | 6


The Twofish Encryption Algorithm A 128-Bit Block Cipher:The Design of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Table 7.5 shows the results of measuring this same property in a different way. Instead of requiring a run of n consecutive identical differences, this metric is similar to a “mini”-DPmax, computed over only the 20 input values used in the subkey generation (e.g., 0, 2, 4, . . ., 38). The quantity measured is the maximum number of equal differences out of the 20 values generated, across key pairs. In other words, while it may be difficult to generate a large run, it may be possible to generate equal values in a large (non-consecutive) fraction of the set of differences. However, the results are again very encouraging, showing that it is extremely difficult to force more than five or six differences to be identical. This also shows that it is not possible to influence only a few Ai, as that would require many zero differences.

Comparison to Random S-boxes. For every metric discussed here, a similar distribution using randomly generated 8-bit permutations has been generated for purposes of comparison. For example, DPmax was computed for a set of 216 randomly generated permutations, and the resulting distribution of DPmax values was compared to that of the Twofish key-dependent S-boxes. For each metric, the probability distributions looked virtually identical to those obtained for the Twofish set of key-dependent S-boxes, except for small fluctuations on the tail ends of the distribution, as should be expected. This similarity is comforting, as is the fact that the probability distributions for each metric look quite similar across key sizes. These results help confirm our belief that, from a statistical standpoint, the Twofish S-box sets behave largely like a randomly chosen set of permutations.

7.3 MDS Matrix

The four bytes output from the four S-boxes are multiplied by a 4-by-4 MDS matrix over GF(28). This matrix multiply is the principal diffusion mechanism in Twofish. The MDS property guarantees that the number of changed input bytes plus the number of changed output bytes is at least five. In other words, any change in a single input byte is guaranteed to change all four output bytes; any change in any two input bytes is guaranteed to change at least three output bytes; and so forth. More than 2127 such MDS matrices exist, but the Twofish MDS matrix is also carefully chosen with the property of preserving the number of bytes changed even after the rotation in the round function.

7.3.1 Non-key-dependent Coefficients

The MDS matrix used in Twofish has fixed coefficients. Initially, some thought was given to making the matrix itself key dependent, but such a scheme would require the verification that the key-dependent values in fact formed an MDS matrix, adding a non-trivial computational load to the key selection and key scheduling process. However, it should be noted that there are many acceptable MDS matrices, even with the extended properties discussed below.

7.3.2 Implementation Issues

For software implementation on a modern microprocessor, the MDS matrix multiply is normally implemented using four lookup tables, each consisting of 256 32-bit words, so the particular coefficients used in the matrix do not affect performance. This works because the actual transformation defined by the MDS matrix is purely linear over GF(2). That is, each of the output bits is the XOR of a subset of the input bits and hence we can XOR four table lookups together to compute the entire 32-bit word. However, for smart cards and in hardware, “simple” coefficients, as in Square [DKR97], can make implementations cheaper and faster.

7.3.3 Preserving Diffusion Properties after Rotation

Unlike the MDS matrix used in Square, Twofish does not use the inverse matrix for decryption because of its Feistel structure, nor is there a requirement that the matrix be a circulant matrix. However, because of the rotation applied after the XOR within the round function, it is desirable to select the MDS matrix carefully to preserve the diffusion properties even after the rotation. For both encryption and decryption, a right rotation by one bit occurs after the XOR. This direction of rotation is chosen to preserve the MDS property with respect to the PHT addition a + 2b, since the rotation undoes the shift applied to b as part of the PHT. It is true that the most significant bit of b is still “lost” in this half of the PHT, but the MDS properties for three of the bytes are still fully guaranteed with respect to b, and they are met with probability 254/255 for the fourth byte.

The effect of the rotation on the unshifted PHT additions also needs to be addressed. A single byte input change to the MDS matrix will change all four output bytes, which affect the round function output, but after rotation there is no such guarantee. If a byte value difference of 1 is one output from the matrix multiply, performing a 32-bit rotate on the result will shift in one bit from the next byte in the 32-bit word and shift out the only non-zero bit. The MDS matrix coefficients in Twofish are carefully selected so that, if a byte difference 1 is output from the matrix multiply with a single byte input change, the next highest byte is guaranteed to have its least significant bit changed as well. Thus, if the rotation shifts out the only original flipped bit, it will also shift in a flipped bit from the next byte.

The construction used to preserve this property after rotation is actually very simple. The idea is to choose a small set of non-zero elements of GF(28) with the property that, for each pair x, y in the set, if x*a = 1, then y*a (i.e., y/x) has the least significant bit set. We then use such a set as the coefficients to construct an MDS matrix. Observe that this property is reflexive; i.e., if x = y, then y/x = 1, so the property holds. It is intuitively obvious (and empirically verified) that the probability that two random field elements satisfy this property is roughly one half, so it should not be difficult to find such sets of elements. Also, since over 75 percent of all 4-by-4 matrices over GF(28) are MDS, the hope of finding such a matrix sounds reasonable.

A computer search was executed over all primitive polynomials of degree eight, looking for sets of three “simple” elements x,y,z with the above property. Simple in this context means that x * a for arbitrary a can be easily computed using at most a few shifts and XORs. Several dozen sets of suitable values were found, each of which allowed several MDS matrices with the three values. The primitive polynomial v(x) = x8 + x6 + x5 + x3 + x0 was selected, together with the field elements 01, EF, and 5B (using hexadecimal notation and the field element to byte value correspondence of Chapter 4). The element EF is actually ß–2 + ß–1 + 1, where ß is a root of v(x), and 5B is ß–2 + 1, so multiplication by these elements consists of two LFSR right shifts mod v(x), plus a few byte XORs.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:The Design of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Alternate Constructions. It should also be noted that a very different type of construction could be used to preserve MDS properties on rotation. Use of an 8-by-8 MDS matrix over CF(24) will guarantee eight output nibble changes for every input nibble change. Because the changes now are nibble-based, a 1-bit rotation may shift the only non-zero bit of a nibble out of a byte, but the other nibble remains entirely contained in the byte. In fact, it can easily be seen that this construction preserves the MDS property nicely even for multi-bit rotations. Unfortunately, 8-by-8 MDS matrices over GF(24) are nowhere near as plentiful as 4-by-4 matrices over GF(28), so very little freedom is available to pick simple coefficients. The best construction for such a matrix seems to be an extended RS-(15,7) code over GF(24), which requires considerably more gates in hardware and more tables in smart card firmware than the Twofish matrix. Because of this additional cost, we decided not to use an 8-by-8 MDS matrix over GF(24).

Hamming
Weight 		Number of
Occurrences 		Number with
MSB Set
8 | 7/1020 | 1
9 | 23/1020 | 4
10 | 42/1020 | 15
Table 7.6. Hamming Weight Distribution of MDS Output after 1-byte Input Change

7.3.4 Rotational Uniqueness of Output Vectors

Another constraint imposed on the Twofish MDS matrix is that no row (or column) of the matrix be a rotation of another row (or column) of the matrix. This property guarantees that all single-byte input differences result in unique output differences, even when rotations over eight bits are applied to the output, as is done in generating the round subkeys. This constraint did not seem to limit the pool of candidate matrices significantly. In fact, the Twofish MDS matrix actually exhibits a much stronger property: all 1020 MDS output differences for single-byte input changes are distinct from all others, even under bitwise rotations by each of the rotation values in the range 6..26. The subkey generation routine takes advantage of this property to help thwart related-key differential attacks. For all single-byte input changes, the rotation of the output 32-bit word B by eight bits has an output difference that is guaranteed to be unique from output differences in the unrotated A quantity.

7.3.5 Maximizing the Minimal Hamming Distance

There are many MDS matrices containing only the three elements 01, EF, and 5B. The particular Twofish matrix was also chosen to maximize the minimum binary Hamming weight of the output differences over all single-byte input differences. The Twofish MDS matrix guarantees that any single-byte input change will produce an output Hamming difference of at least eight bits, in addition to the property that all four output bytes will be affected. In fact, as shown in Table 7.6, only seven of the 1020 possible single-byte input differences result in output differences with Hamming weight difference 8; the remaining 1013 differences result in higher Hamming weights. Also, only one of the seven outputs with Hamming weight 8 has its most significant bit set, meaning that at least eight bits will be affected even in the PHT term T0 + 2T1 for 1019 of the 1020 possible single-byte input differences. Input differences in two bytes are guaranteed to affect three output bytes, and they can result in an output Hamming difference of only three bits, with probability 0.000018; the probability that the output difference Hamming weight is less than eight bits for 2-byte input differences is only 0.00125, which is less than the corresponding probability (0.0035) for a totally random binomial distribution.

There are many other MDS matrices, using either the same or another set of simple field elements, that can guarantee the same minimum output Hamming difference, and the particular matrix chosen is representative of the class. No higher minimum Hamming weight was found for any matrices with such simple elements.

7.4 PHT

The PHT operation, including the addition of the round subkeys, was chosen to facilitate very fast operation on the Pentium CPU family using the LEA (load effective address) opcodes. The LEA opcodes allow the addition of one register to a shifted (by 1,2,4,8) version of another register, along with a 32-bit constant, all in a single clock cycle, with the result placed in an arbitrary Pentium register. For best performance, a version of the encryption and decryption code can be “compiled” for a given key, with the round subkeys inserted as constant values in LEA opcodes in the instruction stream. This is what was done for the “compiled” keying option explained in section 5.1.1. This approach requires a full instantiation in memory of the code for each key in use, but it provides a speedup for bulk encryption.

7.4.1 Eliminating the PHT

Instead of using four key-dependent S-boxes, a 4-by-4 MDS matrix, and the PHT, we could have used eight key-dependent S-boxes and an 8-by-8 MDS matrix over GF(28), hence eliminating the PHT. Such a construction would be easier to analyze and would have nicer properties, but it is much slower in virtually all implementations and would not be worth it.

7.4.2 Diffusion and the Least Significant Bit

One disadvantage of the PHT is that it does not provide complete diffusion for the special case of the least significant bit of T0 + 2T1. In particular, the least significant bit of T0 + 2T1 depends only on the least significant bit of T0, and thus depends only on half of the input bits to the Feistel function. This means that F does not exhibit complete diffusion: there is one output bit which is not affected by all input bits. In fact, we use this property in our differential attack in Section 9.2.

We could have replaced the PHT with a variant that exhibits better diffusion; however, this would have incurred a significant performance penalty. Is it better to eliminate this weakness, if the price is that we must reduce the number of rounds to retain the same performance?

We believe that the PHT yields an excellent bang-for-the-buck ratio. In practice, the PHT’s incomplete diffusion to the least significant bit of T0 + 2T1 should not be a problem, because full diffusion will be easily achieved in the next two rounds; also, the 1-bit rotation prevents the least significant bits from lining up across multiple rounds, which seems to prevent attacks based on analyzing least significant bits.

7.5 Key Addition

As noted in the previous section, the round subkeys axe combined with the PHT output via addition to enable optimal performance on the Pentium CPU family. From a cryptographic standpoint, an XOR operation could have been used, but it would reduce the best Pentium software performance for bulk encryption. It should be noted that using addition instead of XOR does impose a minor gate count and speed penalty in hardware, but this additional overhead was considered to be well worth the extra performance in software. On a smart card, using addition instead of XOR has virtually no impact on code size or speed.

7.6 Feistel Combining Operation

Twofish uses XOR to combine the output of F with the target block. This is done primarily for simplicity; XOR is the most efficient operation in both hardware and software. We chose not to use addition (used in MD4 [Riv91], MD5 [Riv92], RIPE-MD [RIPE92], HAVAL [ZPS93], RIPEMD-160 [DBP96], and SHA [NIST93]), or a more complicated combining function like Latin squares (used in DESV [CDN95]). We also did not implement dynamic swapping [KKT94] or other additional complexities.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:The Design of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

7.7 Use of Different Groups

By design, the general ordering of operations in Twofish alternates as follows: 8-by-8 S-box, MDS matrix, PHT with subkey addition, and XOR. The underlying algebraic operations thus alternate between non-linear table lookup, a GF(2)-linear combination of the bits by the MDS matrix, integer addition mod 232, and GF(2) addition (XOR). Within the S-boxes, several levels of alternating XOR and 8-by-8 permutations are applied. The goal of this ordering is to help destroy any hope of using a single algebraic structure as the basis of an attack. No two consecutive operations use the same structure, except for the PHT and the key addition that are designed to be merged for faster implementations.

7.8 Diffusion in the Round Function

There are two major mechanisms for providing diffusion in the round function. The first is the MDS matrix multiply, which ensures that each output byte depends on all input bytes. The two outputs of the g functions (T0 and T1) are then combined using a PHT so that both of them will affect both 32-bit Feistel XOR quantities. The half of the PHT involving the quantity T0 + 2T1 will lose the most significant bit of T1 due to the multiply by 2. This bit could be regained using some extra operations, but the software performance would be significantly decreased, with very little apparent cryptographic benefit. In general, the most significant byte of this PHT output will still have a non-zero output difference with probability 254/255 over all 1-byte input differences.

7.8.1 Changes Induced by F

We cannot guarantee that a single byte input change to the F function will change seven or eight of the output bytes of F. The reason is that the carries in the addition of the PHT can remove certain byte differences. For example, an addition with a constant might turn a difference of 0000018016 into 0000008016. The chances of this happening depend on the distance between the two bits that influence each other. A large reduction in the number of changed bytes is very unlikely.

7.9 One-bit Rotation

Within each round, both of the 32-bit words that are XORed with the round function results are also rotated by a single bit. One word is rotated before the XOR, and one after the XOR. This structure provides symmetry for decryption in the sense that the same software pipeline structure can be applied in either direction. By rotating a single bit per round, each 32-bit quantity is used as an input to the round function twice in each of the eight possible bit alignments within the byte.

7.9.1 Reason for Rotations

These rotations in the Twofish round functions were included specifically to help break up the byte-aligned nature of the S-box and MDS matrix operations, which we feared might otherwise permit attacks using statistics based on strict byte alignment. For example, Square uses an 8-by-8-bit permutation and an MDS matrix in a fashion fairly similar to Twofish, but without any rotations. An early draft of the Square paper proposed a very simple and powerful attack, based solely on such byte statistics, that forced the authors to increase the number of rounds from six to eight. Also, an attack against SAFER is based on the cipher’s reliance on a byte structure [Knu95c].

Choosing a rotation by an odd number of bits ensures that each of the four 32-bit words are used as input to the g function in each of the eight possible bit positions within a byte. Rotating by only one bit position helps optimize performance on the Pentium CPU (which, unlike the Pentium Pro, has a one-clock penalty for multi-bit rotations) and on smart card CPUs (which generally do not have multi-bit rotate opcodes for 32-bit words). Limiting rotations to single-bit also helps minimize hardware costs, since the wiring overhead of fixed multi-bit rotations is not negligible.

7.9.2 Downsides to Rotations

There are three downsides to the rotations in Twofish. First, there is a minor performance impact (less than 7 percent on the Pentium) in software due to the extra rotate opcodes. Second, the rotations make the cipher non-symmetric in that the encryption and decryption algorithms are slightly different, thus requiring distinct code for encryption and decryption. It is only the rotations that separate Twofish from having a “reversible” Feistel structure. Third, the rotates make it harder to analyze the cipher for security against differential and linear attacks. In particular, they make the simple technique of merely counting active S-boxes quite a bit more complicated. On the other hand, it is much harder for the attacker to analyze the cipher. For instance, it is much harder to find iterative characteristics, since the bits do not line up. The rotates also make it harder to use the same high-probability characteristic several times, because the bits get rotated out of place. On the whole, the advantages were considered to outweigh the disadvantages.

7.9.3 Converting to a Pure Feistel Structure

It is possible to convert Twofish to a pure Feistel structure by incorporating round-dependent rotation amounts in F, and adding some fixed rotations just before the output whitening. This might be a useful view of the cipher for analysis purposes, but we do not expect any implementation to use such a structure.

The rotations were also very carefully selected to work together with the PHT and the MDS matrix to preserve the MDS difference properties for single byte input differences to g. In particular, for both encryption and decryption, the one-bit right rotation occurs after the Feistel XOR with the PHT output. The MDS matrix was chosen to guarantee that a 32-bit word rotate right by one bit will preserve the fact that all four bytes of the 32-bit word are changed for all single input byte differences. Thus, placing the right rotation after the XOR preserves this property. However, during decryption, the rotate right is done after the XOR with the Feistel quantity involving T0 + 2T1. Note that, in this case, the rotate right puts the 2T1 quantity back on its byte boundary, except that the most significant bit has been lost. Therefore, given a single input byte difference that affects only T1, the least significant three bytes of the Feistel XOR output are guaranteed to change after the rotation, and the most significant byte will change with probability 254/255.

The fact that the rotate left by one bit occurs before the Feistel XORs during encryption guarantees that the same relative ordering (i.e., rotate right after XOR) occurs during decryption, preserving the difference-property for both directions. Also, performing one rotation before and one after the Feistel XOR imposes a symmetry between encryption and decryption that helps guarantee very similar software performance for both operations on the Pentium CPU family, which has only one ALU pipeline capable of performing rotations.

7.10 The Number of Rounds

Sixteen rounds corresponds to eight cycles, which seems to be the norm for block ciphers. DES, IDEA, and Skipjack all have eight cycles. Twofish was defined to have eight cycles (16 rounds) primarily out of pessimism. Although our best non-related-key attack only breaks five rounds of the cipher, we cannot be sure that undiscovered cryptanalysis techniques do not exist that can do better. Hence, we consider 16 rounds to be a good balance between our natural skepticism and our desire to optimize performance. Even so, we took pains to ensure that the Twofish key schedule works with a variable number of rounds. It is easy to define Twofish variants with more or fewer rounds.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Design of the Twofish Key Schedule

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Chapter 8
Design of the Twofish Key Schedule

The key schedule for Twofish is a really a huge piece by itself. While it reuses many of the components of the cipher, it also required a significant amount of independent engineering. This chapter addresses the issues we came across in designing the key schedule.

To understand the design of the key schedule, it is necessary to consider how key material is used in Twofish:

The Whitening Subkeys. A whitening subkey of 128 bits is XORed into the plaintext block before encryption, and another 128 bits subkey after encryption. Since the rest of the encryption is a permutation, this can be seen as selecting among as many as 2256 different (but closely related) 128-bit to 128-bit permutations for the whole cipher. This key material has the effect of making many cryptanalytic attacks a little more difficult at a very low cost. Note that nearly all the added strength against cryptanalytic attack is added by the XOR of subkeys into the input to the first and last rounds’ F functions.
The Round Subkeys. Each round, 64 bits of key material are combined into the output of the F function using addition modulo 232. The F function without the round subkey addition is a permutation on 64-bit values; the round subkey selects among one of 264 closely related permutations in each round. These subkeys must be slightly different per round to prevent a slide attack, as will be discussed below.
The Key-dependent S-boxes. To create the S-boxes, the key is mapped down to a block of data half its size, S, and that block of data is used to specify the S-boxes for the whole cipher. As discussed earlier, the key-dependent S-boxes are derived by alternating fixed S-box lookups with XORs of key material. The key-dependent S-boxes define one of 2L/2 possible permutations for the g function, where L is the number of bits in the cipher key. Unlike the other keys used, different S values typically lead to radically different g functions.

8.1 Round Subkeys

8.1.1 Equivalence of Round Subkeys

In this section, we discuss whether different sequences of subkeys can give equivalent encryption functions. Recall that F´ is the F function without the addition of the round subkeys, which takes two 32-bit words as input and produces two 32-bit words as output. For this analysis we keep the function F´ constant. That is, we only vary the subkeys Ki and not S.

The properties of a Feistel cipher ensure that no pair of 2-round subkey sequences can be equivalent for all inputs. It is natural to ask next whether any pairs of three sequential rounds’ subkeys can exist that cause exactly the same encryption.

For a pair of subkey sequences, (k0, k1, k2) and (k*0, k*1, k*2), to be equivalent in their effects, every input block (L0, R0) must encrypt to the same output block (L1, R2) for both sequences of subkeys. Note that k0 ≠ k*0 and k2 ≠ k*2, as we would otherwise have two sequences of 2-round keys that would define the same 2-round encryption function. We have the following equalities:

R1 = R0 ⊕ (k0 + F´(L0))

R*1 = R0 ⊕ (k*0 + F´(L0))

L1 = L0 ⊕ (k1 + F´(R1))

L1 = L0 ⊕ (k*1 + F´(R*1))

R2 = R1 ⊕ (k2 + F´(L1))

R2 = R*1 ⊕ (k*2 + F´(L1))

where ⊕ represents bitwise XORing, and + represents 32-bit componentwise addition. Using the two equations for L1 we get

k1 + F´(R1) = k*1 + F´(R*1)

δ1 = F´(R1) - F´(R*1)

where δ1 = k*1 - k1 is fixed. Let T = F´ (L0) + k0 and observe that when L0 goes over all possible values, so does T. We get

δ1 = F´(R0 ⊕ T) - F´(R0 ⊕ (T + δ0)) (8.1)

where δ0 = k*0 - k0. Note that δ1 and δ0 depend only on the round keys, and that the equation must hold for all values of R0 and T. Set T = 0 and look at the cases R0 = 0 and R0 = δ0. We get

F´(0) - F´(δ0) = δ1 = F´(δ0) - F´(0) = - δ1

The subtraction here is modulo 232 for each of the two 32-bit words. That leaves us with the following possible values for δ1:

δ1 ∈ {(0,0), (0,231), (231,0), (231,231)}

These are the possible difference values at the output of F´ in equation 8.1. We can easily convert them to difference values at the input of the PHT of F´. Each of the possible values for δ1 corresponds to exactly one possible value for (δT0, δT1):

(δT0, δT1) ∈ {(0,0), (0,231), (231,0), (231,231)}

We can write down the analogue to equation 8.1 for g:

δT0 = g(R´ ⊕ T´) - g(R´ ⊕ (T´ + δ´0))

for all R´ and T´ and where δ´0 is the appropriate half of δ0. Observe that for the specific values of δT0 that are possible, subtraction and XOR are the same. For T´ = 0 this translates in a simple differential equation

δT0 = g(R´) ⊕ g(R´ ⊕ δ´0)

for all R´. We know that g has only one perfect differential: 0 → 0, so we conclude that δ´0 = 0. Similarly, we can conclude that the other half of δ0 must also be zero, and thus δ0 = 0. This is a contradiction, as k0 ≠ k*0.

We conclude that there are no two sets of 3-round subkey sequences that result in the same encryption function.

A Conjecture about Equivalent Subkeys in Twofish. We believe that, for up to 16 rounds of Twofish, there are no pairs of round subkeys that (with the same F´ function) result in the same encryption function. There simply do not appear to be enough degrees of freedom in choosing the different subkeys to make pairs of equivalent subkey sequences in as few as 16 rounds. However, we have been unable to prove this.

Note that this conjecture does not hold for an arbitrary number of rounds. Any fixed round function is an element of the permutation group on 128-bit values S2128. The order of this group is (2128)! ≈ 22134, and the order of any group element must be a divisor of the order of the group. Thus, any round function when iterated (2128)! times, results in the identity mapping.1 For this number of rounds there are thus many equivalent round subkeys.

1In fact, this property holds for any bijective function, including the complete Twofish encryption and the AES block cipher (irrespective of which candidate is chosen).

8.1.2 Equivalent keys

Can two keys generate the same sequence of round subkeys? We have performed exhaustive tests to show this is not the case. To generate the same round subkeys, the two keys will have to generate the same set of Ai and Bi.

We observe that Ai = h(2ρi, Me), where the h function consists of applying the MDS matrix multiplication to the four values (y0, y1, y2, y3) obtained by running the value 2i through 1 + N/64 levels of q0 and q0, XORing with bytes from Me. Since the MDS matrix is non-singular, it is easily seen that to generate the same sequence of Ai values, the keys must generate the same sequence of values for y0, y1, y2 and y3.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Design of the Twofish Key Schedule

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

The sequence of y0 values for 256-bit keys is

q1[q0[q0[q1[q1[i] ⊕ k3] ⊕ k2] ⊕ k1] ⊕ k0]

where the kj are different bytes from Me. Smaller keys result in similar equations with fewer key bytes, so the analysis is almost identical. The question at hand is whether two distinct sets of four key bytes can result in an identical sequence of 20 y0 values. In fact, we exclude the input and output whitening values to concentrate solely on the round subkeys, so only 16 values are included in our test (one per round). Clearly, there are 232 such sequences. However, this number can be reduced for the purposes of our search by noting that, since the “outer” mapping q1 is bijective, it can be removed from the equation, leaving us with

q0[q0[q1[q1[i] ⊕ k3] ⊕ k2] ⊕ k1] ⊕ k0

Now the outer XOR term k0 can be effectively removed by creating a related sequence with only 15 values, where the y0 values for i = 5, ..., 19 are XORed with the i = 4 value. The k0 terms thus cancel out, so there are only 224 equivalence classes of sequences, speeding up the search dramatically. If all these sequences (each with 15*8 = 120 bits) are unique, then the y0 sequence is also guaranteed to be unique.

For 192-bit keys, the y0 sequence is

q1[q0[q0[q1[i] ⊕ k2] ⊕ k1] ⊕ k0] ⊕k0]

and for 128-bit keys, it is

q1[q0[q0[i] ⊕ k1] ⊕ k0]

In a manner identical to that discussed for 256-bit keys, the outer q1 permutation can be removed for these smaller keys, and the outer k0 term can similarly be removed by creating the related XOR sequence. The number of the remaining sequences is 216 and 28, respectively. All these sequences can then be compared across key sizes (with a total of NS = 224 + 216 + 28 sequences) to verify uniqueness.

A computer search has been performed over y0, y1, y2 and y3, for all sequences across all key lengths. It turns out that only 64 bits of each sequence were sufficient to distinguish the sequences. This fact is actually quite encouraging, since there are 120 bits in each sequence, giving some heuristic comfort that the sequences are in fact quite different. Each search requires slightly more than 128 MB of memory (i.e., 8Ns bytes) to hold all the sequences, which are then sorted and compared to adjacent values to guarantee uniqueness. The test was run on a Pentium computer with only 32 MB of memory, so the search was actually performed in multiple passes, running through all the Ns values several times, on each pass selecting only those values falling into certain bins. For example, using approximately 8 MB of memory, there are 16 passes, with the mth pass discarding all sequence values for which a fixed 4-bit field of the sequence does not equal to m.

Similar arguments apply to the Bi sequence, and the same empirical verification has been performed for both sequences. Note that, since the operations used to compute K2i and K2i+1 from Ai and Bi are reversible, proving that the Ai and Bi sequences are distinct is more than sufficient to prove that the Kj sequences are distinct.

The definitive result from these tests is that there are no two distinct keys of any size for which the same sequence of Ai and Bi values is obtained. Thus, the round subkey sequence Kj is unique across keys.

8.2 Controlling Changes in Round Subkeys

In a related-key attack, one is concerned about introducing controlled differences into key material that will produce predictable effects that depend on the pair of keys. The basic intuition is that if one can observe the difference in behavior produced by two keys known to have a particular mathematical difference, then one might be able to discern information about the true value of the two keys. Normally one does not limit the attack to pairs of keys and instead may consider subsets of keys instead. Either way, this is a natural attack in many environments where multiple encryption keys are used which are not truly independent of each other.

One very natural notion of mathematical difference is the XOR difference of two values. In this section we consider the problem of trying to produce two sequences of round subkeys {Ki} and {K´i} that have a desired difference (either additive or XOR). Recall that the Ki (and K´i) are computed as a function of the sequences A and B (respectively A´ and B´). Therefore we consider the problem of trying to produce two sequences A = {Ai} and A´ = {A´i} such that individual elements have a desired difference δi = Ai ⊕ A´i (a similar discussion holds for B = {Bi}). A and B are generated using four 8-bit, key-dependent S-boxes in parallel followed by multiplication by a 4-by-4 MDS matrix over GF(28), where each S-box output is treated as one component of a four-dimensional vector over GF(28). Due to the linearity of the MDS matrix multiply, it is very natural to consider attacks that introduce XOR differences between A and A´, since it is very easy to pass XOR differences through the MDS matrix.

8.2.1 XOR Difference Sequences in A and B

Let A and A´ be sequences for two keys M and M´ respectively. If we have a specific difference sequence, δ = {δi}, we want to see in A (i.e., δi Ai ⊕ A´i), we are faced with an interesting problem: since the MDS matrix multiply is XOR-linear, each desired output XOR from the matrix multiply uniquely determines the input XOR. This means that:

1. Any input difference δIi to the MDS matrix corresponds to an output difference for each of the four S-boxes. Hence a difference sequence δ induces four XOR-difference sequences δj for the four S-boxes. For any difference sequence δj = {δji}, each value is an 8-bit value instead of a 32-bit value. As a result, we will sometimes refer to these sequences as difference byte sequences.
2. The zero sequence δ can occur only when each difference byte sequence δj is the zero sequence.
3. Only 1020 possible output differences (out of the 232) in δi can occur with a single “active” (altered) S-box (i.e., only one δj is a non-zero sequence). Most differences require all four S-boxes to be active and hence all δj to be non-zero sequences.

The above analysis is of course also valid for the B sequence.

Given that any desired difference sequence δ corresponds to four difference byte sequences δj, we need to examine the properties of the S-boxes to determine the difficulty of generating specific δj.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Design of the Twofish Key Schedule

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

8.2.2 Byte Sequences with Given Difference

In generating A and A´ with a specific difference δ, one must generate four pairs of byte sequences (σj, σ´j), each with a specific difference δj, where σj = {σji} and σ´j = {σ´ji}. The inputs to the four S-boxes used to produce these values are {0, 2, 4, ..., 38} (whereas they axe 1, 3, 5, ..., 39} for B). Therefore our byte sequences are given by σji = sj [2i] and σ´ji = s´j[2i]. Hence any questions about difference byte sequences reduce to questions about the sequences

{sj[0], sj[2],...,sj[38]}, {s´j[0], s´j[2],...,s´j[38]}

For a given δj we will estimate the chance that there exists a pair (σj, σ´j) with that difference sequence.

We can model each byte sequence generated by a key-dependent S-box as a randomly selected non-repeating byte sequence of length 20. This allows us to make many useful predictions about the likelihood of finding keys or pairs of keys with various interesting properties. Because we will be analyzing the key schedule using this assumption in the remainder of this section, we should discuss how reasonable it is to treat this byte sequence as randomly generated. As discussed in Section 7.2.3, we have not found any statistical deviations between our key-dependent S-boxes and the random model in any of our extensive statistical tests.

Not all byte sequences are possible; due to the bijectivity of the S-boxes we know that all the bytes in the sequence are distinct. There are 256!/236! of those sequences, which is close to 2159.

Each key-dependent S-box uses N/8 bits of key material; hence, if the S-boxes were truly random we would expect two 20-byte sequences to create the desired difference with probability roughly 2N/4-1. 2-160 (There are 2N/4-1 pairs of byte sequences, and each has a 2-160 chance of being a match.) For example, for N = 256 we expect with probability 2-97 that there exists a pair of our S-boxes that produces the desired difference sequence. Note that this probability is for any specific difference sequence. There are many such possible difference sequences, and of course some of those actually occur. Attacks requiring a specific difference sequence seem more likely than attacks requiring any of a class of 297 usable difference sequences.

Most difference sequences in A will require that all four δj are non-zero. For a randomly chosen difference δ in the A sequence we thus expect that there are two keys that generate exactly this difference with probability about 2-388.

8.2.3 Identical Byte Sequences

As discussed in section 8.1.2, we have empirically verified that there are no equivalent S-box keys that generate the same sequence of 20 bytes. That holds for our specific choice of q0 and q1. This section analyzes the probability of two identical sequences occurring for arbitrary q-boxes.

The estimate of section 8.2.2 holds for the special case of δj being the all-zero sequence. If we are a little more careful, then we can actually improve the estimate for this case. While this result shows that the S-boxes are not uniformly distributed throughout the space of all possible 8-bit S-boxes, it shows that the S-boxes display better than average differences in this particular case.

To improve the estimate, we peel off one layer of our q construction and assume the rest of the construction is random. Without loss of generality we look at2

2:For ease of discussion, we number the key bytes as k0,..., k3 going into one S-box. The actual byte ordering for s0 and a 256-bit key’s subkey-generating S-box is k0, k8, k16, k24. The numbering of the key bytes has no effect on the security arguments in this section.

s1(x) = q0[q0[q1[q1[q0[x] ⊕ k0] ⊕ k1] ⊕ k2] ⊕ k3]

Identical sequences are possible only if the inputs to the last q0 fixed permutation are identical for both sequences. That means that the task of finding a pair of identical sequences comes down to a simpler task: finding a pair of (k0, k1, k2) byte values that leads to a pair of sequences before the XOR with k3 that have a fixed XOR difference. Then, k3 can be changed to include the XOR difference, and identical sequences of inputs will go into the last q0 S-box.

Let

t[i]:= q0[q1[q1[q0[i] ⊕ k0] ⊕ k1] ⊕ k2]

The goal is to find a pair of t[i] sequences such that

t[i] ⊕ t*[i] = constant

Let us assume that t generates a random sequence (with the restriction that all byte values must be distinct). The chances of any pair of t, t* generating such a constant difference is about 2-151. (The domain in which we are searching for collisions is the set of all 19-byte sequences with non-repeated values. There are 256!/237! of these sequences, which is close to 2151.) This brings the chance of finding a pair with such a constant difference down to 247. 2-151 = 2-104.

8.2.4 The A and B Sequences

From the properties of the byte sequences, we can discuss the properties of the A and B sequences generated by each key M.

Ai = MDS(s0(2i, Me), s1(2i, Me), s2(2i, Me), s3(2i, Me))

Since the MDS matrix multiply is invertible, and since i is different for each round’s subkey words generated, we can see that no A or B value can repeat itself.

Similarly, we can see from the construction of h that each key byte affects exactly one S-box used to generate A or B. Changing a single key byte always alters every one of the 20 bytes of output from that S-box; the MDS matrix ensures that every byte of every word in the 20-word A or B sequence to which this key byte contributes is altered.

Consider a single byte of output from one of the S-boxes. If we cycle any one of the key bytes that contributes to that S-box through all 256 possible values, the output of the S-box will also cycle through all 256 possible values. If we take four key bytes that contribute to four different S-boxes, and we cycle those four bytes through all possible values, then the result of h will also cycle through all possible values. This proves that A and B are uniformly distributed for all key lengths, assuming the key M is uniformly distributed.

8.2.5 The Sequence (K2i, K2i+1)

As Ai and Bi are uniformly distributed (over all keys), so are all the Ki. As all pairs (Ai, Bi are distinct, all the pairs (K2i, K2i+1) are distinct, although it might happen that Ki = Kj for any pair of i and j.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Design of the Twofish Key Schedule

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

8.2.6 Difference Sequences in the Subkeys

Difference sequences in A and B translate into difference sequences in (K2i, K2i+1). However, while it is natural to consider A and B difference sequences in terms of XOR differences, subkeys can reasonably be considered either as XOR differences or as differences modulo 232. Thus, we may discuss difference sequences:

D[i,M, M*] = Ki,M - Ki,M*

X[i,M, M*] = Ki,M ⊕ Ki,M*

where the difference is computed between the key value M and M*.

XOR Differences in the Subkeys. Each round, the subkeys are added to the results of the PHT of two g functions, and the results of those additions are XORed into half of the cipher block. An XOR difference in the subkeys has a fairly high probability of passing through the addition operation and ending up in the cipher block. (The probability of this is determined by the Hamming weight of the XOR difference, not counting the highest-order bit.) However, to get into the subkeys, an XOR difference must first pass through the first addition.

Consider

x + y = z

(x ⊕ δ0)+ y = z ⊕ δ1

Let k be the number of bits set in δ0 , not counting the highest-order bit. Then, the highest probability value for δ1 is δ0, and the probability that this will hold is 2-k. This is true because addition and XOR are very closely related operations. The only difference between the two is the carry between bit positions. If flipping a given bit changes the carry into the next bit position, this alters the output XOR difference. This happens with probability 1/2 per bit. The situation is more complex for multiple adjacent bits, but the general rule still holds: for every bit in the XOR difference not in the high-order bit position, the probability that the difference will pass through correctly is cut in half.

For the subkey generation, consider an XOR difference, δ0, in A. This affects two subkey words:

K2i = Ai + Bi

K2i+1 = ROL(Ai + 2Bi, 9)

where the additions are modulo 232. If we assume these XOR differences propagate independently in the two subkeys (which appears to be the case), we see that this leads to an XOR difference of δ0 in the even subkey word with probability 2-k, and the XOR difference ROL(δ0, 9) in the odd subkey with the same probability. The most probable XOR difference in the round’s subkey block thus occurs with probability 2-2k. A desired XOR difference sequence for all 20 pairs of subkey words is thus quite difficult to get to work when k ≥ 3, assuming the desired XOR difference sequence can be created in the A sequence at all.

When the XOR difference is in B, the result is slightly more complicated; the most probable XOR difference in a round’s pair of subkey words may be either 2-(2k-1) or 2-2k, depending on whether or not the XOR difference in B covers the next-to-highest-order bit.

Additive Differences in the Subkeys. An XOR difference in A or B is easy to analyze in terms of additive differences modulo 232: a XOR difference with k active bits has 2k equally likely additive differences. Note that if we have an additive difference in A, we get it in both subkey words, just rotated left nine bits in the odd subkey word. Thus, k-bit XOR differences lead to a given additive difference in a pair of subkey words with probability 2-2k. (The rotation does not really complicate things much for the attacker, who knows where the changed bits are.)

8.3 The Round Function

The round function F takes a 64-bit input and produces a 64-bit output; and F is characterized by the four S-boxes si and the round keys K2r+8, K2r+9. The S-boxes depend on N /2 bits of key material S. We show that all the F functions generated in this way are distinct. Our test for distinctness of the round functions concentrates on only a single bit of the output, which will be sufficient to prove uniqueness.

In particular, consider the value

F1 = (T0 + 2T1 + K2r+9) mod 232

where T0 =g(R0 and T1 =g(ROL(R1, 8)). Because the g function involves an MDS matrix multiply, which uses the XOR operation, it is difficult to analyze the full F1 value due to the interaction between operations of different algebraic groups (i.e., XOR and addition). However, if we examine only the least significant bit (1sb) of F1, we can ignore carries, so the operation can be analyzed entirely Using XOR. Note that this bit does not depend on R1, due to the multiplication by 2 in the PHT. Further, the MDS matrix element that maps the S-box output is a simple linear transformation (i.e., multiplication by a GF(28) field element). Thus, for each S-box, the effect of the final fixed permutation (q0 or q1) of the S-box and the MDS multiply on the lsb of F1 is a simple fixed mapping from eight bits to one bit.

Now, consider two keys with distinct values for S. Since the S values are different, at least one of the four S-boxes must have different key material under the two different keys. To prove uniqueness, we simply fix the inputs to the remaining three S-boxes, so that their XOR “contribution” to the lsb of F1 is fixed. Up to a fixed XOR constant (based on K2r+9 and the other three S-boxes), we are then left with a simple function involving a single S-box that maps eight bits to one bit, with N/8 bits of key material used in the S-box. We can remove dependence on the fixed constant by constructing sequences consisting of the XOR of two bits in the S-box/MDS lsb output sequence, similar to the method discussed in section 8.1.2. If this sequence of bits is unique across the all 2N/8 possible key material values for the S-box, then the F function is unique with respect to that S-box. If all four S-boxes are unique in this way, then the F function is unique for each distinct value of S.

To remove the dependence on the constant bit, we performed our search on a modified sequence in which each bit was the XOR of two lsbs of the S-box/MDS output values. Since the si mapping has 256 inputs, this limits the sequence down to only 255 values, which is still easily sufficient to distinguish between F functions. Let us first consider the 256-bit key case, which obviously involves the longest search. Note, for example,

s0(x) = q1[q0[q0[q1[q1[x] ⊕ k3] ⊕ k2] ⊕ k1] ⊕ k0]

where the kj bytes are a subset of the bytes in S. There are 232 such functions, but, unfortunately, since we are dealing only with the lsb, there is no obvious method to cut down the search time by a factor of 256, as we were able to do in section 8.1.2. Similar sequences were produced for the smaller key sizes, with all sequences for each S-box combined across key sizes in the test, for a total of NF = 232 + 224 + 216 sequences per S-box.

To avoid a “birthday surprise” collision with NF sequences, we require more than 64 bits of each sequence. Even with only 64 bits, however, a total of over 32 GB of memory would be required, a size far beyond the budget of this experiment. Thus, this test was also performed in multiple passes, with each pass generating all NF sequences but discarding those values not falling into the selected bin for the particular pass, as before. It was found empirically that the performance time was roughly proportional to the number of passes; in other words, the sort/compare time for a given pass was considerably shorter than the O(232) time required to generate the “filtered” list. For example, on a 200 MHz Pentium computer with slightly over 256MB of available RAM, 128 passes are required, which empirically were completed for a single S-box in slightly less than three days. Each sequence value in the list consisted of 64 bits, with additional sequence bits used to filter out values not to be used in a given pass. For a 128-pass test, this means that seven extra bits were used to help avoid a birthday surprise collision. The filtering code (in C) was carefully optimized so that most of the values to be filtered on each pass were quickly rejected. Since 127 of every 128 values were filtered out on each pass, this simple optimization sped up performance considerably, without requiring particularly fast generation of the 64-bit sequence values to be included.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Design of the Twofish Key Schedule

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

The test was run on several Pentium computers with various amounts of RAM over a period of about ten days. The results showed that, for each of the four S-boxes, all NF mappings have a unique lsb sequence. Thus, each F function is unique for each distinct value of S.

8.4 Properties of the Key Schedule and Cipher

One NIST requirement is that the AES candidates have no weak keys. Here we argue that Twofish has none.

8.4.1 Equivalent Keys

A pair of equivalent keys, M, M*, is a pair of keys that encrypts all plaintexts into the same ciphertexts. We are almost certain that there are no equivalent keys in Twofish. As shown in section 8.1.2, there is no pair of keys, M, M*, that gives the same subkey sequence {Ki}. Section 8.3 showed that for two keys to generate the same round function in any one round, they must generate the same S.

It is conceivable that different sequences of subkeys and different S-boxes in g could end up producing the same encryption function, thus giving equivalent keys. This appears to be extremely unlikely, but we cannot prove that such equivalent keys do not exist.

A Conjecture about Equivalent Keys in Twofish. We conjecture that there are no pairs of Twofish keys that lead to identical encryptions for all inputs.

8.4.2 Self-Inverse Keys

Self-inverse keys are keys for which encrypting a block of data twice with the same key gives back the original data. We do not believe that self-inverse keys exist for Twofish. Keys cannot generate a self-inverse sequence of subkeys, because the same round subkey value can never appear more than once in the cipher. Again, it is conceivable that some keys axe self-inverse despite using different subkeys at different points, but again this is extremely unlikely. Self-inverse DES keys are sometimes referred to as “weak keys.”3

3The term “weak key” is used in conflicting ways in the literature. DES’ weak keys are fundamentally different from the weak keys of IDEA or Blowfish.

8.4.3 Pairs of Inverse Keys

A pair of inverse keys is a pair of keys M0, M1 such that EM0(EM 1(X)) = X, for all X. We cannot see any way for this to occur. Encryption and decryption are slightly different processes, because of the one-bit rotations, so even if M0, M0, generate a pair of subkey sequences that are reversed, we still do not get pairs of inverse keys.

Consider a Twofish variant without those one-bit rotations. Can we find M0, M1, that lead to reversed subkey sequences? That is, can we find a pair of keys whose subkeys appear in the opposite position—the pre-XOR subkeys for M0 are the post-XOR subkeys for M1, the first round subkeys for M0 are the last round subkeys for M1, etc. To get reversed subkeys, we need to get reversed byte sequences from each of the eight byte-wide key-scheduling S-boxes. Finding a pair of byte sequences that are one another’s reverse sequences is the same difficulty as finding a collision in the whole byte sequence, and thus the same difficulty as finding a difference sequence in all 20 output byte positions. By the same arguments as we used above regarding difference sequences, then, this kind of reversed subkey sequence almost certainly doesn’t exist for any pair of keys M0, M1. For these reasons, we do not believe that there are pairs of inverse keys for Twofish. Note that pairs of inverse keys in DES are sometimes referred to as “semi-weak keys.”

8.4.4 Simple Relations

A key complementation property exists when

EM (P) = C ⇒ EM´ (P´) = C´

where P´, C´, and K´ are the bitwise complement of P, C, and K, respectively. No such property has been observed for Twofish.

More generally, a simple relation [Knu94b] is defined as

EM (P) = C ⇒ Ef(M)´ (g(P,M))= h(C, M)

where f, g, and h are simple functions. We have found no simple relations for Twofish, and strongly doubt that they exist.

8.5 Key-dependent Characteristics and Weak Keys

The concept of a key-dependent characteristic seems to have been introduced in [BB93] in their cryptanalysis of Lucifer, and also appears in [DGV94a] in an analysis of IDEA.4 The idea is that certain iterative properties of the block cipher useful to an attacker become more effective against the cipher for a specific subset of keys.

4See [Haw98] for further cryptanalysis of IDEA weak keys.

A differential attack on Twofish may consider XOR-based differences, additive differences, or both. If an attacker sends XOR differences through the PHT and subkey addition steps, his differential characteristic probabilities will be dependent on the subkey values involved. In general, low-weight sub-keys will give an attacker some advantage, but this advantage is relatively small. (Zero bits in the subkeys improve the probabilities of cleanly getting XOR-based differential characteristics through the subkey addition.) Since there appears to be no special way to choose the key to make the subkey sequence especially low weight, we do not believe this kind of key-dependent differential characteristic will have any relevance in attacking Twofish.

A much more interesting issue in terms of key-dependent characteristics is whether the key-dependent S-boxes are ever generated with especially high-probability differential or high-bias linear characteristics. The statistical analysis presented earlier shows that the best linear and differential characteristics over all possible keys are still quite unlikely.

Note that the structure of both differential and linear attacks in Twofish is such that such attacks appear to generally require good characteristics through at least three of the four key-dependent S-boxes (if not all four), so a single high-probability differential or linear characteristic for one S-box will not create a weakness in the cipher as a whole.

8.6 Reed-Solomon Code

The RS structure helps defend against many possible related-key attacks by diffusing the key material in a direction “orthogonal” to the flow used in computing the 8-by-8-bit S-boxes of Twofish. For example, a single byte change in the key is guaranteed to affect all four key-dependent S-boxes in g. Since RS codes are MDS [MS77], the minimum number of different bytes between distinct 12-byte vectors generated by the RS code is guaranteed to be at least five. Notice that any attempt in a related-key attack to affect only a single byte in the computation of A or B is guaranteed to affect all four bytes in the computation of T0 and Ti. The S-box keys are used in reverse order from the associated key bytes so that related-key material is used in a different order in the round function than in the subkey generation.

The reversible RS code used in Twofish was chosen via computer search to minimize implementation cost. The code generator polynomial is

where α is a root of the primitive polynomial w(x) used to define the field.

Because all of these coefficients are “simple,” this RS computation is easily performed with no tables, using only a few shifts and XOR operations; this is particularly attractive for smart cards and hardware implementations. This computation is only performed once per key schedule setup per 64 bits of key, so the concern in choosing an RS code with such simple coefficients was not the performance overhead, but saving ROM space or gates. Precomputing the RS remainders requires only eight bytes of RAM on a smart card for 128-bit keys.

To take advantage of the simple coefficients of the polynomial, the RS matrix multiply should not be implemented as a direct matrix multiply but as a loop over the input bytes, where each iteration uses the coefficients of the polynomial once.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Cryptanalysis of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Chapter 9
Cryptanalysis of Twofish

We have spent over one thousand man-hours cryptanalyzing Twofish. A summary of our successful attacks is as follows:

• On Twofish with fixed S-boxes, no 1-bit rotations, and no whitening, we have a meet-in-the-middle attack on eleven rounds requiring 2225 memory, 256 known plaintexts, and 2232 work, and a differential attack breaking nine rounds, requiring 241 memory, 241 chosen plaintexts, and 2254 work.
• On standard Twofish, we have a 4-round meet-in-the-middle attack requiring 256 known plaintexts, but 2225 memory and 2232 work. We also have a differential attack which breaks five rounds of full Twofish with 2232 work and 241 chosen-plaintext queries.
• We have a chosen-key attack. This attack involves choosing 160 bits of a pair of keys, K, K*, with the remaining bits to be found. The attack requires 234 work, 232 chosen-plaintext queries, and 212 adaptive chosen-plaintext queries, in order to break 10 rounds without the whitening.
• We have a related-key attack against 10-round Twofish without whitening. This attack requires 2155 related-key queries, 2187 work, and for each of the 2155 keys it requires 232 chosen plaintexts and 212 adaptive chosen plaintexts.

The fact that Twofish seems to resist related-key attacks well is arguably the most interesting result, because related-key attacks give the attacker the most control over the cipher's inputs. Conventional cryptanalysis allows an attacker to control both the plaintext and ciphertext inputs into the cipher. Related-key cryptanalysis gives the attacker an additional way into a cipher: the key schedule. A cipher that is resistant to attacks with related keys is necessarily resistant to simpler techniques that only involve the plaintext and ciphertext.1

1We have discussed the relevance of related-key attacks to practical implementations of a block cipher in [KSW96, KSW97]. Most importantly, related-key attacks affect a cipher's ability to be used as a one-way hash function.

Based on our analysis, we conjecture that there exists no more efficient attack on Twofish than brute force. That is, we conjecture that the most efficient attack against Twofish with a 128-bit key has a complexity of 2128; the most efficient attack against Twofish with a 192-bit key has a complexity of 2192; and the most efficient attack against Twofish with a 256-bit key has a complexity of 2256.

Cipher variant Rounds Work Memory
256-bit key, Fixed S, no whitening, no rotations | 11 | 2232 | 2225
256-bit key, Fixed S, no whitening | 10 | 2232 | 2225
256-bit key, Fixed S | 6 | 2232 | 2225
256-bit key, Full Twofish | 4 | 2232 | 2225

Table 9.1. Attack Results for Our Meet-in-the-Middle Attack

9.1 A Meet-in-the-Middle Attack on Twofish

9.1.1 Results of the Attack

Table 9.1 summarizes our attack results. One notable feature of this attack is that it demonstrates the impact of adding the pre- and post-whitening and the key-dependent S-boxes. Without these two features, we would have an extremely simple attack on 10 out of the 16 rounds of our cipher—enough to raise questions about its ultimate security. With these two features, however, the attack extends to only four rounds. Resistance to meet-in-the-middle attacks comes from quickly getting every bit of the key involved in every bit of the block being encrypted.

9.1.2 Overview of the Attack

In a meet-in-the-middle attack, we try to derive some intermediate state inside the cipher, using only part of the key material from both the plaintext and the ciphertext. For each possible value that the part of the key that we guessed can take, we derive that intermediate value from the plaintext and also from the ciphertext. We get two huge lists of possible intermediate values. We then sort the two lists, and check them for matching values. A matching value of more bits than we would expect to occur randomly indicates that our guesses were correct. This kind of attack is important to consider because the AES candidates are using large keys, which imply a very high security level. A user expecting 256 bits worth of security should be concerned by attacks that involve guessing 200 bits of key in each direction. Also, it is easy for cipher designers used to thinking in terms of 64-bit blocks and 128-bit keys to design ciphers that do not get all 256 bits of key involved in the encryption process quickly enough.

9.1.3 Attacking Twofish with Fixed S and no Whitening

In this Twofish variant, all key material is in the round subkeys. We acquire about 256 plaintext/ciphertext pairs from this Twofish variant with ten rounds.

We label the four words of the data during the encryption as A, B, C, and D. From the plaintext side, we guess the round subkeys for the first three rounds, for a total of 192 bits. We also guess one subkey (used to determine the value XORed into A) in the fourth round. We thus know the value of the low-order bit of D after the fifth round, because (1) we knew the value of D after the third round, (2) we know the value of A going into the fifth round, and (3) we know that the low-order bit of the value XORed into D is dependent only on A and one bit of the fifth round's subkey. For each of the 2225 possibilities for these key values, we compute this bit for all 256 plaintexts we have. We store these in a list, and sort them.

From the ciphertext side, we guess the round keys for the tenth, ninth, and eighth rounds, and we guess the subkey from the seventh round that affects the value XORed into D. We use this to derive the high-order bit from D going into the seventh round, which was rotated from its position as the low-order bit of D after the fifth round. Again, for all 2224 possible key values guessed, we compute this bit for each of the 256 ciphertexts we have. Again, we sort this list.

We now merge the two sorted lists, and thus search for matches. This ought to take on the order of 2232 work total. Thus, we use 2225 blocks of memory, and about 2232 work to break ten rounds of Twofish with fixed S-boxes and no whitening.

Note that without the one-bit rotations in the cipher, we would have needed to know only the low-order bit of the F-function output in the seventh round. This would actually allow us to attack one more round. This is evidence that the one-bit rotations do, in fact, provide some resistance against real attacks.

9.1.4 Attacking Twofish with Fixed S

With the whitening added, the attack becomes much harder. From the plain-text side, we must guess all four pre-whitening subkeys, allowing us to get our known low-order bit only into the output of the third round. Similarly, from the ciphertext side, we must guess all four post-whitening subkeys and the last round’s subkeys, and one subkey word from the next-to-last round. We can thus attack only six rounds in this case.

9.1.5 Attacking Normal Twofish

Attacking the full Twofish is still harder. From the plaintext side, we must guess the 128 bits of S, the round subkey that determines the value that is XORed into C in the first round, and the pre-whitening subkey for C. This allows us to predict the low-order bit of B after the second round XORed with an unknown constant (i.e., we predict that this bit will take on a sequence of values or the negation of that sequence). A similar approach is used from the ciphertext side, allowing only four rounds to be attacked.

Key
Length 		Variant Rounds Chosen
Texts 		Work
128 | No whitening, fixed S | 7 | 241 | 2126
192 | No whitening, fixed S | 8 | 241 | 2190
256 | No whitening, fixed S | 9 | 241 | 2254
128 | No whitening, no one-bit rotates | 6 | 241 | 2126
192 | No whitening, no one-bit rotates | 6 | 241 | 2158
256 | No whitening, no one-bit rotates | 7 | 241 | 2254
256 | Normal Twofish | 5 | 241 | 2232

Table 9.2. Attack Results for Our Differential Attack

9.2 Differential Cryptanalysis

9.2.1 Results of the Attack

Table 9.2 summarizes our attack results against several variants of Twofish.

9.2.2 Overview of the Attack

The attack uses two different differential properties of the F function:

1. If the input difference into the F function is (0, X), where X represents any non-zero difference at all, then the output difference of the F function can be expressed additively as (+Y, +2Y), where Y is some other unknown difference. Unfortunately, these additive differences do not always translate cleanly into XOR differences. However, the low-order bit of the second word of F’s output is always unchanged, since 2Y always has its low-order bit clear. This happens with probability 1.
2. If the same XOR difference comes out of the two g functions during the F function computation, and this difference has k bits not in the high-order position, then with probability 2-k, the F function will generate an output difference of (0, X), where X is some unknown difference.

Our attack works by first trying to force the second event described above to occur in the second round, in a batch of several pairs of plaintexts. If it occurs, then the first event described above occurs in the next round with probability one, resulting in a single bit whose difference is known in the output of the fourth round. This allows an attack on reduced-round Twofish.

The attack requires that we get a specific, predictable difference sequence. We choose

r | ΔRr,0 | ΔRr,1 | ΔRr,2 | ΔRr,3
0 | 0 | 0 | a′ | b′
1 | a | b | 0 | 0
2 | 0 | ? | a | b
3 | ? | (?,1) | 0 | ?
4 | ? | ? | ? | (?,1)
5 | ? | ? | ? | ?

where the table gives the difference patterns for the round values for each of the 5 rounds, and where a′ = ROL(a, 1), b′ = ROR(b, 1), and (?, 1) represents a 32-bit difference of which one bit is known. To recognize right pairs, we shall (roughly speaking) guess enough of the key to decrypt up one round, checking whether the low-order bit of the difference is as expected.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Cryptanalysis of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

The only critical event for this attack occurs at r = 1, where we need the characteristic (a, b) → (0, X) to happen with high probability. Based on the properties of the MDS matrix, we know that there are three single-byte output XORs for s0 that lead to an output XOR of g with Hamming weight of only 8. If the same one of those differences goes into the MDS matrix in both g computations in the second round, then, with probability 2-8, we get an offsetting pair of values in the two g outputs; one g output has some value added to it modulo 232, and the other output has the same value subtracted from it. When the outputs go through the PHT, they lead to only one output word from the whole F being changed, which is what makes this attack possible. Therefore, we choose a = (α, 0, 0, 0) to be a single-byte difference in s0, and b = ROR(a, 8) so that the single-byte difference into the second g computation in round 2 lines up with the single-byte difference in a.

In this attack, we will consider N batches of 256 plaintext pairs, of which at least one is expected to consist of all right pairs. We must choose the inputs to the cipher to allow ourselves to later form such batches. We will then guess some part of the key as needed to check the one known bit of difference going into the fifth round. That key guess will be used to test each batch. Batches that are not made up of right pairs will typically be distinguished after a small number of pairs are checked, because the one-bit difference will be wrong with probability 1/2 in each wrong pair checked with the right key, and in each pair checked with the wrong key. The attack thus consists of the following steps:

1. Request the encryptions of plaintext blocks necessary to form at least one batch of 256 plaintext pairs that has a very high probability of being made up of only right pairs.
2. Guess the smallest amount of key material that will let us see the one bit of difference we know in right pairs.
3. For each such guess, check each batch until one batch turns out to be made of only right pairs.

If there are N batches to be checked, and each takes on average about two trial decryptions’ worth of work, then we end up with 2N work we must do for each guess of key material necessary to see whether the known difference is as we expect it to be.

9.2.3 Building the Batches

Overview. We break the problem into three parts, here. First, we describe how to take a single right pair and generate 255 other right pairs from it. Then, we describe how to take a pair that gets the same 8-bit XOR difference out of both g functions, and use it to generate enough pairs that it is likely that at least one is an actual right pair; i.e., the differences from the two g functions cancel out in the first addition of the PHT. Finally, we describe how to choose pairs so that we are very likely to get at least one pair that gets the same 8-bit XOR difference from both g functions.

Let us suppose we must choose n0 pairs before we get a pair such that both g functions get the same 8-bit XOR difference. (That is, we must choose n0 pairs to get our differential through half of the second round.) We have no way to know which pair has the desired differential, so we must treat all of them as potentially right pairs.

Let us also suppose that given a pair whose differential survives through half of the second round, we must choose n1 related pairs before we find one pair that survives through the whole second round. The rest of the differential occurs with probability one, so one of these pairs is a right pair. We must apply this process to all the potential right pairs to be nearly certain of getting a right pair. Thus, we now have n0n1 pairs to deal with.

Finally, let us suppose that, given a right pair, we must expand it into n2 batches of 256 pairs each before we will be able to detect it. We must do this to all potential right pairs, meaning that we end up with n0n1n2 batches total, each of 256 pairs. Thus, we need to request a total of n0n1n2256 pairs of plaintexts for encryption.

This tells us about the chosen text requirements, but not the workload for the attack. Suppose we have to guess k bits, and that given a guessed partial key, we can check a batch with an average of work equivalent to n3 encryptions. Then the total work factor is 2kn0n1n2n3. As we discuss below, n3 ≈ 1, n2 = 216, n1 = 28, and n0 = 28.

Amplifying Right Pairs. The greatest difficulty in this attack is determining a sequence of inputs that gives us at least one batch of 256 pairs of plaintexts that contains all right pairs. This is necessary because we know only that one bit of difference in the output from the fourth round. Essentially, what we need to do is to "magnify" the effects of a right pair so that a single right pair generates 256 right pairs.

To see how this can be done, let us consider a pair of inputs to the F-function,

X = (C, D) = (c0, c1, c2, c3), (d0, d1, d2, d3)

X* = (C*, D*) = (c0, c1*, c2, c3), (d0, d*1, d2, d3)

such that we know that we have a right pair; i.e., that the two g functions have the same XOR difference after processing X and X*, that these XOR differences have Hamming weights of eight bits only, and that the two XOR differences cancel out during the first addition in the PHT, leading to an output difference of (0, ?). We want to find a way to choose related input pairs that will also be right pairs. To do this, we must consider some details of how right pairs really work. When we compute F(C, D), we find

f0 = g(C) + g(D)

f1 = g(C) + 2g(D)

When we apply an XOR difference to a value, this has the effect of flipping k bits, where k is the Hamming weight of the XOR difference. In terms of mod 232 addition, flipping bit j means adding 2j or subtracting it, depending on whether the bit was on or off. If X, X* is a right pair, it means that g(C), g(D) both got the same 8-bit difference, and that each bit of C covered by a bit of that XOR difference was different than the corresponding bit of D covered by that bit of the difference. In other words, the XOR difference must result in subtracting from g(C) whatever it adds to g(D), so that g(C) + g(D) will be unchanged. This means that simply changing g(C) at random won’t generally produce more right pairs from this one.

There are two ways to make more right pairs from this right pair:

1. Find a way to change one or more inactive bytes (c0, c2, c3, d0, d2, d3) such that the 8 bits that are changed in g(C), g(D) in the original pair aren’t changed. Since we don’t know which bits those are, this looks hard to do.
2. Find a way to change those inactive bytes that leads to the same XOR difference being applied to g(C) and g(D). If the same bits are flipped in g(C) and g(D), then the resulting pair will also be a right pair. This is our approach.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Cryptanalysis of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Our solution is as follows: If we flip the same bits in g(C) as in g(D), then the sum g(C) + g(D) will be unchanged, and as a result, the effect of the input difference in c1, d1 will also be unchanged. Let x3, y3 be the bytes that actually go into the S-box s3 in the two g functions. We control c3, d3, but their values axe XORed with some unknown bytes before being used as x3, y3. Thus,

x3 = c3 ⊕ z3

y3 = d3 ⊕ z4

We need to be able to choose c3, d3 so that x3 = y3. If we ever did that, then we could generate 255 additional cases where y3 = z3, simply by XORing 1,...,255 into both c3 and d3. Now, if we knew z3 ⊕ z4, we could choose any c3 value we liked, and then set d3 = c3 ⊕ z3 ⊕ z4, giving us x3 = y3. We thus try all 256 possible values for z3 ⊕ z4. One of those values is right; we can use it to take a single right pair, and produce 255 more just like it. This is done by keeping A and B constant, and by choosing

C = (c0, c1, c2, c3 ⊕ i)

D = (d0, d1, d2, d3 ⊕ i ⊕ z3 ⊕ z4)

C* = (c0, c*1, c2, c3 ⊕ i)

D* = (d0, d*1, d2, d3 ⊕ i ⊕ z3 ⊕ z4)

where c1, d1, and c*1, d*1 are the bytes changed in the original right pair. For each potential right pair, we thus generate 256 pairs of text according to the above formula for each guess about z3 ⊕ z4. This means that each potential right pair generates 256 batches of 256 pairs of plaintexts (and corresponding pairs of ciphertexts), or a total of 216 plaintext pairs. Thus, n0 = 256.

Deriving a Right Pair from a Partial Right Pair. Suppose we have a pair of texts, (C, D), (C*, D*), such that g(C) ⊕ g(C*) = g(D) ⊕ g(D*), with that XOR difference having Hamming weight of 8. In most (255/256) cases, this won’t be a right pair, because g(C) + g(D) ≠ g(C*) + g(D*). To turn this into a right pair, some of the bits in g(C) which axe covered by the XOR difference need to be flipped. We thus choose the available bytes, c0 and c2, and vary both bytes randomly in different texts. After about 256 different random c0, c2 choices, we expect to derive a real right pair from the partial right pair. Naturally, most of the pairs we generate will not be right pairs, and we won’t be able to distinguish them from wrong pairs until we mount the attack.

We thus determine that n1 = 256.

Finding a Single Partial Right Pair. A partial right pair can be found by getting the same XOR difference out from the S-box determined by c1 and also by d1. We don’t know the S-box these are going through, but simulations show that if we try i, i ⊕ δ as a pair of inputs into a random 8-bit-wide bijective S-box, s, we have a probability of 1/2 of getting any desired output XOR difference. If there axe three XOR differences that lead, after the MDS matrix is applied, to 8-bit XOR differences, then the probability is thus 7/8 that this approach will work to find a partial right pair.

We have the same complications we did above: we control c1, d1, but we need to control x1 = c1 ⊕ z1,y1 = d1 ⊕ z2, the inputs to the S-boxes in the two g functions. Similarly to the way we dealt with this above, we end up guessing z1 ⊕ z2. The result is that we generate 216 plaintext pairs, of which at least one is almost certainly a partial right pair. Thus, n2 = 216.

Testing a Batch of Plaintext Pairs. We generate n0n1n2 = 2828216 = 232 batches of plaintext pairs. During our attack, we must guess as much of the key material as is required, and for each guess, we must test each batch to see if it is made up of only right pairs. The probability of a randomly-selected key giving us a “false positive”—that is, a batch that appears to be right but is not—is 2-256. This probability is low enough that we never expect a single false positive.

We now consider the difficulty of testing one such batch of plaintext pairs. The question is how many trial partial decryptions we must do for each batch, on average, before determining that the batch is not made up of only right pairs. For a guessed partial key, each batch will yield a sequence of 256 bits; in the batch of right pairs, they will all be the expected bit. However, for each batch, we can stop searching as soon as we find a single bit that is different than the others. The expected number of trial partial decryptions required per batch is thus

2 · 1/2 + 3 · 1/4 + 4 · 1/8 + ··· + (n + 1) · 1/2n ≈ 3

Each partial decryption is less work than a full encryption. We take n3 = 1 for our estimates, which corresponds to each partial decryption being one-third as much work as a full encryption.

9.2.4 Mounting the Attack

To mount the attack, we must determine what key material must be guessed to check our batches. Consider a 5-round Twofish variant without whitening and without the 1-bit rotations. In this case, we need only guess S. Recall that in a right pair, we know the difference in only one bit—the low-order bit of D in this case—at the input to the fifth round. After guessing S, we can compute the value of the g function that uses A as its input in the fifth round. The low-order bit of this is XORed with the low-order bit of the corresponding subkey, and then XORed into the bit whose difference we know. Knowledge of the low-order bit of that g output thus gives us the desired bit difference.

To extend this another round, we must also guess the subkey in the sixth round that affects the value XORed into A. Because we only have to get the low bit of D, we need not compute the B value input into the fifth round’s F function at all. This requires 232 additional work.

To extend this one more round, we must guess the whole set of round subkeys in the next round. This requires 264 additional work.

Five-round Twofish consists of ten g computations and a little extra work. To be conservative, we can consider each g computation to be 1/8 of a trial encryption.

Key Length Rounds Work(equiv. trial encs.)
128 | 5 | 230 · 264 = 294
128 | 6 | 230 · 296 = 2126
192 | 5 | 230 · 296 = 2126
192 | 6 | 230 · 2128 = 2158
256 | 5 | 230 · 2128 = 2158
256 | 6 | 230 · 2160 = 2190
256 | 7 | 230 · 2224 = 2254

Table 9.3. Differential Attack Results against a Variant with No Whitening and No Rotations

Key Length Rounds Work(equiv. trial encs.)
128 | 5 | 230 · 274 = 2104 |
128 | 6 | 230 · 2138 = 2166 | (No longer useful.)
192 | 5 | 230 · 2106 = 2136 |
192 | 6 | 230 · 2170 = 2200 | (No longer useful.)
256 | 5 | 230 · 2138 = 2168 |
256 | 6 | 230 · 2202 = 2232 |
256 | 7 | 230 · 2266 = 2296 | (No longer useful.9)

Table 9.4. Differential Attack Results against a Variant with No Whitening

Thus, for five- to seven-round Twofish with no whitening and no 1-bit rotates, we have the results summarized in Table 9.3.2 (Note that all of these results are for 241 chosen plaintexts.)

2We are indebted to Eli Biham for the suggestion of guessing the whole last round’s subkeys for the 256-bit key.

When we add back in the 1-bit rotates, the attacks grow substantially harder. (Interestingly, though we put the 1-bit rotates in because of concerns about the byte structure, so far, the 1-bit rotates have complicated several attacks based on exploiting properties of the low bit of one of the PHT words.) We must now learn both g function outputs in the fifth round, as well as guessing the high-order 10 or so bits of round subkey used to alter the value XORed into D in the fifth round. We list the resulting attack complexities in Table 9.4.

The whitening also adds a little difficulty. When combined with the 1-bit rotates, we get the results summarized in Table 9.5. We note that there are straightforward differential attacks on four rounds that work despite the 1-bit rotations and whitening, but they involve using only the (0, X) → (?, (?, 1)) differential.

Key Length Rounds Work(equiv. trial encs.)
128 | 5 | 230 · 2128 = 2158 | (No longer useful.)
192 | 5 | 230 · 2170 = 2200 | (No longer useful.)
256 | 5 | 230 · 2202 = 2232 |

Table 9.5.3 Differential Attack Results against Reduced Rounds

Key Length Rounds Work(equiv. trial encs.)
all | 6 | 230 · 232 = 262
all | 7 | 230 · 296 = 2126
192 & 256 | 8 | 230 · 2160 = 2190
256 | 9 | 230 · 2224 = 2254

Table 9.6. Differential Attack Results on a Variant with Known S and No Rotations

Finally, we can consider the difficulty of this attack on a Twofish variant with a fixed, known S value and no 1-bit rotates. In this case, we have the difficulties results listed in Table 9.6.

Again, this demonstrates how the additional key material in the key-dependent S-boxes adds to the practical difficulty of an attack. Additionally, with fixed S-boxes, it may be possible for the attacker to get a substantial improvement, perhaps by as much as a factor of 256, on the number of plain-text batches he must request. This would reduce the plaintext requirement and the work factors on all these attacks by the same factor.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Cryptanalysis of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

9.2.5 Lessons from the Analysis

We have learned three important lessons from this analysis:

1. The 1-bit rotates really do add difficulty to some attacks.
2. The key-dependent S-boxes add a great deal of security to the cipher against some attacks.
3. The whitening adds a fair amount of security to the cipher at essentially no cost.

9.3 Extensions to Differential Cryptanalysis

9.3.1 Higher-Order Differential Cryptanalysis

Higher-order differential cryptanalysis looks at higher order relations (e.g., quadratic) between pairs of plaintext and ciphertexts [Lai94, Knu95b]. These attacks seem to work best against algorithms with simple algebraic functions, only a few rounds, and poor short-term diffusion. In particular, we are not aware of any higher-order differential attack reported in the open literature that is successful against more than six rounds of the target cipher. We cannot find any higher-order differentials that can be exploited in the cryptanalysis of Twofish.

9.3.2 Truncated Differentials

Attacks using truncated differentials apply a differential attack to only a partial block [Knu95b]. We have not found any truncated attacks against Twofish. The almost complete diffusion within a round function makes it very difficult to isolate a portion of the block and ignore the rest of the block. Truncated differential attacks are most often successful when most of the cipher’s internal components operate on narrow bit paths; Twofish’s 64-bit-wide F function seems to make truncated differential characteristics hard to find. We believe that Twofish is secure against truncated differential attacks. For example, our differential attack, described above, is properly classified as a truncated differential attack, and it can successfully attack only five rounds of the full Twofish.

9.4 Search for the Best Differential Characteristic

One aspect of our analysis work is a search for an upper bound on the probability of a differential characteristic. This section contains our results to date. We expect to continue this work and achieve significant improvements over our current results.

The first choice we have to make in differential cryptanalysis is what type of differences to use. Twofish contains S-boxes, an MDS matrix multiply, addition modulo 232, XORs, and rotations. There are two types of differences that we think could be useful: a XOR difference, and a difference mod 232. When we use a XOR difference we have to use approximations for the S-boxes and the additions modulo 232; when we use a differences modulo 232 we have to use approximations for the S-boxes, the MDS matrix multiply, the XORs, and the rotations.

The XOR and addition operations are fairly closely related, and either operation can be approximated with reasonable success in the group of the other operation. In the comparison we will ignore the S-boxes; we assume they are equally hard to approximate in each of the groups. An XOR differential has to approximate two addition operations in each round. An additive differential has to approximate the MDS matrix, a single XOR, and a rotation. We estimate that it is about as difficult to approximate an addition for an XOR differential as it is to approximate an XOR for an additive differential. The rotations are relatively simple to approximate in both cases, so we ignore them for this comparison. Thus, if we ignore the MDS matrix, it would seem that additive differentials are more attractive.

For our analysis, the MDS matrix multiply is best written as a linear function: each output bit is the XOR of several input bits. This is very easy from the point of view of an XOR difference; no approximation is necessary and any given input difference leads to precisely one output difference. For an additive difference this is much harder. There do not seem to be any good approximations of the MDS matrix for an additive difference. Therefore, we estimate that XOR-based differentials are much more effective than additive differentials. In the rest of this paper we will look only at XOR-based differentials.

We use the following notations: Let β be the set of all possible byte values. Let G be the F-function without the key-dependent S-boxes. Thus G consists of two MDS matrix multiplies, the PHT, and the subkey addition.

9.4.1 Differentials of the S-boxes

In this section we look at differential characteristics of the S-boxes. Each S-box consists of a sequence of q-mappings and XORs with a key byte. For q0 and q1 the probability of each differential can easily be computed by trying all possible pairs of inputs.

We define pi (a, b) to be the probability that qi has an output difference of b, given an input difference of a. In other words,

We now look at the first two stages of an S-box. This consists of a q-mapping, followed by an XOR with a key byte, followed by another q-mapping. As usual, we assume uniform random distributions of the input values and the key bytes. We define pij (a, b) to be the probability that this construction gives an output difference b given an input difference a, where i is the number of the first q-mapping, and j is the number of the second q-mapping. It is easy to see that

for i, j ∈ {0, 1}, and we can extend this definition to arbitrary long chains of q-mappings and key-byte XORs. In general, it holds that

S-box 128-bit Key 192-bit Key 256-bit Key
0 | 1.0649 · 2-8 | 1.0084 · 2-8 | 1.0043 · 2-8
1 | 1.0566 · 2-8 | 1.0087 · 2-8 | 1.0043 · 2-8
2 | 1.0533 · 2-8 | 1.0097 · 2-8 | 1.0045 · 2-8
3 | 1.0538 · 2-8 | 1.0088 · 2-8 | 1.0044 · 2-8

Table 9.7. Best Differential Probabilities of the S-boxes under Random Key

for i, j,..., m ∈ {0, 1}. This allows us to compute the exact probabilities for each of the S-boxes in Twofish. Table 9.7 gives the probabilities of the best differential of each of the S-boxes for each key length. From this point of view the S-boxes are very good; there are no high-probability differentials. (Note that the average differential probability is 1/255 = 1.0039 .2-8, as we know that the S-boxes are permutations, and thus the output differential 0 does not occur in non-trivial cases. The best differential probability must be at least as large as the average.)

Note that the numbers in this table hold only when the key bytes are chosen at random. In our analysis we assumed that the probabilities in each q-stage were independent. If we try a differential many times, each time with random input and key byte values, then we expect to get the numbers in the table. However, for any particular set of key bytes there are differentials with a much higher probability (as shown in section 7.2.3). Our computations are no longer valid, because for any fixed key byte, the differential probabilities of pi and pj in equation 9.1 are no longer independent of each other.

Twofish uses the same S-boxes in each round. When analyzing a multi-round differential characteristic, the differential probabilities of each of the round functions are not independent either. This makes the analysis of the probability of a differential characteristic more difficult.

9.4.2 Differentials of F

The function F takes a 64-bit input and produces a 64-bit output. Thus there are a total of about 2128 possible differentials. It is clearly not possible to compute or list all of them. To alleviate this problem we will group the differentials in sets, and for every set compute upper bounds on the probability of the differentials in that set.

We split the 2128 different differential patterns into a number of subsets. The input difference is classified by the set of input bytes that are nonzero. There are 256 different classifications of input differences. The output difference too is classified by the set of output bytes that are non-zero. We group differentials with the same input and output classification in the same set. There are therefore 216 different sets of differentials, each containing between 1 and 25516 elements.

We will construct differentials of F in two steps. First we use a differential approximation of the S-boxes, and then we use an approximation of the differentials of G.

Differentials of G. The MDS matrix multiply is purely linear, and thus creates no problem for our differential. The PHT and key addition use addition modulo 232 as basic operation. This makes the differentials non-trivial. A theoretical analysis of differential probabilities is difficult, as the probabilities at the result are not independent of each other. We therefore chose to use numerical simulation to establish bounds on the differential probability.

We are trying to derive an upper bound on differential probabilities. Therefore, we are interested in finding good bounds for the most likely differentials of G. We know that for any 128-bit key, the best differential probability of an S-box is 18/256. If we look only at the S-boxes, then the most likely differentials occur when there are a low number of active S-boxes. The most important task is thus to find good bounds on the differential characteristics of G for differentials with a low number of active S-boxes.

We performed numerical simulations of differentials of G. Given an input difference, we generated n random input pairs with that difference and applied the G function (using random keys). We collected the output differences and counted how often each of them appeared. Due to limited resources we could do this analysis only for moderately large n.

From this data we would like to derive a bound on the differential probability. Let us assume a specific differential occurs k times out of n tries. It is obviously not a good idea to use k/n as a bound on the differential probability. Most possible differences occur zero times, but we should not assume that they have a zero probability. If we knew the distribution of the probability we could give some meaningful bound; for example, saying that the probability is less than x with a confidence level of 1 percent. However, in our case we do not know the distribution of the differential probabilities, and it would be dangerous to assume one. We can, however, reverse the process.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Cryptanalysis of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Let us assume that a specific differential has a probability p. If we try the input difference n times, we expect to find this differential around p · n times. The number of times this differential is actually observed is binomially distributed. Let X be a stochastic variable that represents the number of times the differential is observed. We have

From this distribution we can derive a bound on the lower tail of the binomial distribution [Fer98a]:

for k ≤ p · n. Given a probability p for the differential, we can say that we have an unlikely event if the differential occurs k times and Pr(X ≤ k) < γ where γ would be a small number. This is a normal test for statistical significance.

We use the following rule to derive a bound on a differential that occurs k out of n times. We use a probability p such that Pr(X ≤ k) < γ for some global parameter γ (typical values for γ are 0.05 or 0.01). Of course, we try to choose p as low as possible given this condition. This will overestimate p for most differentials, but underestimate the actual p in a few cases.

We ran these simulations for all input differences with a low enough number of active S-boxes. For every differential that we tried, we estimated the probability using this rule. For each set of differentials with the same input and output characterization, we computed the maximum estimated probability. For each differential, there is a small chance that we underestimated the probability. However, it is far less likely that we underestimated the maximum probability of a set of differentials. For our maximum to be too low we have to underestimate the probability of the most likely differential. This by itself is rather unlikely. Not only that, we cannot significantly overestimate the probability of any differential with a probability close to the most likely differential. We therefore feel confident that these approximations are reasonable, and that they most likely will result in our overestimating the actual differential probability quite significantly.

For differentials with too many active S-boxes (for which we did not run the simulations), we simply use an upper bound of 1 on the probability of a differential of G.

To improve efficiency, we generate our input differences using a straightforward structure. This improves our performance and allows us to increase the number of samples that we make. However, the differentials that we try are no longer independent of each other. We have observed that the use of structures significantly increases the peaks in the bounds. The smaller the structures that we use, the lower the maximum probability bound tends to be. Therefore, we try to reduce the use of structures. We hope our next software version will allow us to eliminate structures altogether.

Apart from these numerical results, we know that certain differential patterns cannot occur. For example, if the input difference is restricted to the first input word of G, then the output difference must have active bits in both output words. Similarly, if the input difference is restricted to the second input word of G, then the output difference must have active bits in both halves, except when the output of the MDS matrix has a difference of 0x80000000. In this special case, we know that all four S-boxes in this half must be active (otherwise more than one byte in the output of the MDS matrix must change). Our software generates all these impossible differential patterns and sets the differential probabilities of the associated sets to zero.

Prob. Differential
2-20 | x000 0x00 → 0000 xxxx
2-26 | x000 0x00 → 0000 0xxx
2-22 | x000 0x00 → xxxx 0000
2-26 | 000x x000 → 0000 xxxx
2-22 | 000x x000 → xxxx 0000
2-20 | 00x0 000x → 0000 xxxx
2-22 | 00x0 000x → xxxx 0000
2-14 | 0x00 0000 → 0x0x 0x0x

Table 9.8. Experimentally Found Differentials of F

Differentials of F. Given the results from the last section, we can now create a table of upper bounds on the differential probabilities of differentials of F. For each set of differentials we know how many active S-boxes there are. Let σ be the maximum probability of a differential of an S-box. We can now bound the probability of each set of differentials by multiplying the bounds that we found in the previous section on the set by the proper power of σ.

The value σ can be set in various ways. We know that most S-boxes have a best differential probability of 12/256. For the time being we will use this value for σ. Other values, especially larger ones, will be discussed later.

Experimental Results. We ran a test for differential characteristics of the F function with one active byte in each 4-byte g input and at most four active bytes at the 8-byte F output. Table 9.8 shows some interesting differentials that we found. The probabilities are very approximate, as they derive from numerical experiments with not too many samples. Note that in all but the last of these, the two active input bytes are going through the same key-dependent S-box due to the 8-bit rotate at the input of the second g function. The leading cause of all of these differentials seems to be that these two bytes generate the same output differential from the S-box, and thus the same differential at the output of the MDS matrix. With some positive probability, the PHT maps this into an output differential where one half is zero. This probability depends on the bit pattern of the differential just before the PHT.

The last characteristic has a different explanation. The input differential results in a differential at the output of the MDS matrix that has a relatively high chance of being converted into a 0x0x pattern after a constant is added to it. For example, the differential 03f2037a16 has a fair chance of being converted to a 0x0x pattern after a 32-bit addition.

All of these characteristics have a relatively low probability. We have not found any attack that directly relates to this property, but it provides a useful starting point for further research. In particular, upper bounds on the differential characteristics of F of this type could be used to improve our bound on the best differential characteristic for the full cipher.

9.4.3 Differentials of the Round Function

Once we have derived bounds on the differentials of F, we can do the same for the round function. The differential pattern at the start of the round is characterized by 16 bits; each bit indicates whether the differential pattern in the corresponding byte is non-zero. Given the characterization of the differential pattern at the input of the round, we know exactly which S-boxes are active. We can generate a list of all suitable differential patterns of F with their associated probability bound. Each of these differentials is combined with the other half of the input differential using the rotate and XOR operations. Each choice of the F differential set leads to several possible output differential patterns as the rotate and XORs can lead to different output characterizations depending on the exact differential.

For example, let us look at a differential pattern of 0110 in a 32-bit word. This pattern indicates that only the middle two bytes of the 4-byte word contain active differential bits. After a left rotation, the possible output differential patterns are: 0100, 0110, 1010, 1100, and 1110. XORing two differential patterns can similarly lead to a list of possible results. If we XOR two words, one with a differential pattern of 0101 and one with a differential pattern of 0011, then the possible result patterns are 0110 and 0111.

For each input differential pattern to the round, we can go through all possible F differential patterns, and generate all possible output patterns that can arise. For each possible output pattern of the round, we keep track of the largest upper bound that we generate this way. This produces an upper bound for each of the 232 possible input/output differential patterns of the round function.

9.4.4 Multi-round Patterns

The simplest way of generating multi-round patterns would be to use the list of 232 possible round patterns and a standard search algorithm. We use an algorithm that is somewhat more efficient than that. There are 216 possible differential patterns after r rounds, as each of the 16 data bytes can have a zero or non-zero difference. For each of the 216 possible patterns, we store an upper bound on the probability of any characteristic that has this difference pattern after r rounds. Furthermore, we store the list of differential patterns of F, and a precomputed table of how the rotates and XORs can propagate patterns. For each difference pattern after r + 1 rounds, we use this data to compute an upper bound on the probability of a differential characteristic that has this pattern after r + 1 rounds.

Given the output pattern of the round in question, we know the first half of the input pattern. This leaves us with 256 possible differential input patterns, and 256 possible differential patterns of F. Each of the 216 possible combinations is tried to see whether it can yield the required output differential pattern. The process can be speeded up by traversing either the F output patterns or the input patterns in decreasing order of probability and using some simple cut-off logic.

9.4.5 Results

The results depend on the parameters used to estimate the differential probabilities of G, and the values of γ and σ.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Cryptanalysis of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Our current results use n = 211 tries for all differentials with one active S-box, and n = 28 tries for all differentials with 2 active S-boxes. The structure size is 8 and 16 respectively. We use γ = 0.05, and σ = 12/256. The full Twofish cipher has 16 rounds. We assume that an adversary can somehow bypass the first round and can mount a 3R-attack. We thus look at the best 12-round differential characteristic.

With these parameters we found an upper bound on the probability of a 12-round differential characteristic of 2-102.8. This puts a differential attack against Twofish well outside the practical realm.

This upper bound is pessimistic in the following areas:

• The best differential pattern used three active S-boxes in four of the 12 rounds. The probability of passing a differential with three active S-boxes through G is currently taken to be 1. This is clearly overly optimistic, especially since the differential pattern used has both a low input and a low output weight. We believe that extending our simulations to all differentials with three active S-boxes will yield a significant further reduction in probability.
• Many of the rounds in the best differential pattern use fancy transformations of the difference pattern by the rotations. This is to be expected of our algorithm, but any non-trivial transformation poses serious restrictions on the actual difference patterns of that word. This makes it much less likely that our upper bound can actually be approached by an actual differential.
• Our estimates are based on the maximum probability of groups of differentials. It is not clear at all that there exists a differential that has a probability that even approaches our upper bound.

9.4.6 Other Problems for the Attacker

To create an attack, the attacker has to choose a specific differential characteristic. That characteristic uses certain specific differences of each of the S-boxes. To get anywhere near the bound, all of these differences need to have a probability close to our σ. We chose σ equal to the probability of the best differential of most S-boxes. However, a specific differential will not have the same probability under all keys. If the S-box keys are not known, the attacker has two options. First, he can guess the S-box key bits, and construct a differential characteristic based on that assumption. To achieve good differential probabilities in enough S-boxes, he will have to guess the keys of at least two S-boxes (between 32 and 64 bits, depending on the key size). Alternatively, he can try to find a differential that works for all keys. As we saw in section 9.4.1, this leads to very low differential probabilities.

9.4.7 Best S-box Differential

We use σ = 12/256 while we know that there are keys for which the best S-box differential has probability 18/256 for a 128-bit key, and even higher for larger key sizes. However, those higher probabilities only occur for a small subset of the keys. We need to address the question of how much we are willing to pay in the size of the keyspace the attack is effective on to get a higher probability. If we have an attack that works for 2-28 the key space, how much more efficient should the attack be before it is a better choice for the attacker?

The most natural way is to look at the expected work for the attacker before recovering a single key. We assume that there are enough keys to attack, and optimize the attacker’s strategy to find any one key with the least amount of work. This is a reasonable way of looking at the attacker’s problem. After all, we know there is an attack that is effective on a subset of 2-64 of the keys with 264 work: a simple exhaustive search of any subset of that size will do. With such a brute-force attack on a subset of the keys, the expected amount of work before a key is found remains the same.

Let us now look at our Twofish differentials. Suppose we want to use a differential of S-box 0 with probability 14/256; this is possible for about one in eight of all possible keys. We have restricted ourselves to 1/8 of the set of keys, so the workload of our attack should be reduced by at least a factor of 8 for this to be worthwhile. We ran our search for the best differential characteristic pattern again where S-box 0 had a best differential probability of 14/256. The resulting differential probability was 4.6 times higher than the result with σ = 12/256. Is this worth it?

Let us assume a differential has a probability that depends on the key. We have a list of (pi, ki) where the probability of the differential is at most pi for a fraction ki of all keys. The expected workload of the attacker to get a single right pair is 1/pi for a fraction ki of the key space, and thus ς ki/pi when taken over all keys. The workload is at least max ki/pi. This corresponds to the workload of an attack with a differential with probability min pi/ki. In our situation, the minimum occurs when we use the S-box approximation with probability 12/256. As we currently ignore the 1/ki term, the actual “effective” probability of a real differential is lower than the bound that we have derived.

We conclude that using a higher probability than 12/256 for an S-box approximation is not worth the loss in key space on which the approximation holds. Thus the bounds we presented earlier hold, and are in fact pessimistic.

9.4.8 Other Variants

As an experiment, we ran the same analysis for Twofish with the 1-bit rotations removed. This makes our approximations match the behavior of the differential much better. Our results give an upper bound on the probability of a 12-round differential characteristic of 2-104.1

This bound is not much better than we have for full Twofish. However, the sequence of differential patterns that achieves this bound uses far more approximations of F that have three active S-boxes. In all cases it uses differential characteristics of G that have three active input bytes and only a few active output bytes. In practice, such differentials of G will have a far lower probability than the upper bound of 1 that we currently use. Therefore, we expect that our bound can be improved to beyond 2-128.

We have no reason to believe that the 1-bit rotations make Twofish stronger against a differential attack. They were conceived to break up the byte-level structure, but they do not require a separate approximation or increase the avalanche effect of the cipher. We think it is unlikely that the full Twofish has a differential characteristic that is significantly more likely than the version without rotations.

9.4.9 Further Work

We will continue our analysis work to improve the bound and our understanding of the intricacies of Twofish. We have several areas that we plan to improve.

Improved G Differential Estimates. An obvious way to improve our overall bound is to improve our bounds on the differentials of G. We hope to be able to do this in the near future. A larger sample size will improve the accuracy of our estimates. Extending our computations to differentials of G with three active S-boxes should give a great improvement.

More Accurate Patterns. Our current pattern-representation is somewhat coarse. We group differentials only by which bytes contain active bits. Apart from the first and final round, all internal differential patterns in our best result have at most four active bytes (out of 16). A more fine-grained grouping of the differentials could lead to a better upper bound.

For example, there are only a few G differences with one active input byte that have a relatively high probability. Instead of grouping these into the sets, we could treat them separately. This would ensure that our algorithm doesn’t magically transform the output of the high-probability difference pattern to one with fewer active bytes by the rotation. The characterization could be extended with special cases for differences that have only a few active nibbles. We expect that this will result in more S-boxes being needed for a full differential characteristic, and thus a lower bound.

Improved Treatment of S-box Differentials. There is still room to improve our approximations of the S-boxes. We can, for example, compute the best differential approximation for each of the output differences separately. This can then be combined with the analysis of G to get a better bound on differentials of F.

The data on the best S-box differentials in section 7.2.3 is merged for all the S-boxes. We plan to test the differentials again and collect information for each S-box separately.

We will also improve our handling of the variation of differential probability over the key-space. This will also result in a better bound.

Additive Differentials. We would like to take a closer look at additive differentials modulo 232. Although we do not expect these to be more useful, it would be nice to derive some bound in that case too.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Cryptanalysis of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

9.4.10 Conclusion

For practical purposes, Twofish is immune to differential cryptanalysis. We have shown that any 12-round differential has a probability of at most 2-102.8. This bound is far from tight, and we expect that any real differential has a much smaller probability.

The Twofish structure is not easy to analyze. The mixing of various operations makes it hard to give a clean analysis and forces us to use approximation techniques. Some aspects, such as the rotates, make the analysis a lot harder and force us to use less accurate approximations, while there is no a priori reason to assume that the rotations would have any significant influence on the differential probabilities.

One can argue whether a cipher with a structure that is easier to analyze would be preferable. On the one hand, a structure that allows easier analysis makes it easier to rule out certain attacks. On the other hand, the very structure that makes it easy to analyze might be used in a future attack. Although differential attacks were obviously considered during the design, Twofish was not specifically strengthened against differential attacks, or designed to allow a simple upper bound on differential probabilities to be derived. This is a result of the design philosophy of Twofish. It was not optimized specifically against known attacks; it is a conservative design that tries to resist both known and unknown attacks.

9.5 Linear Cryptanalysis

We perform a similar analysis to that of Section 9.4 in the context of linear cryptanalysis. The approach is the same, but a simpler model was used.

Our model is much as before: it is centered around the pattern of active bytes. (Here a byte position is considered active if any of its bits are active in the linear approximation for that round; i.e., if the mask T selects at least one bit from that byte position.) We used a fairly rough approximation of the effect of the PHT. This approximation fails to accurately treat some low-probability approximations for the PHT where there are fewer active bytes at the output than at the input. This analysis also ignores the 1-bit rotations.

Because of the second limitation, our model should be considered only a heuristic; it may fail to capture some important features of the round function.

A search for the best linear characteristics within this model found that every 12-round characteristic has at least 36 active S-boxes. Here is an example of one characteristic we found:

1  FE->FF (1 active)
2  FF<-FF (2 active)
3  FF->DD (4 active)
4  CC<-DD (6 active)
5  CC->00 (0 active)
6  C<-00  (6 active)
7  CC->77 (4 active)
8  00<-77 (0 active)
9  00->77 (4 active)
10 66<-77 (6 active)
11 66->00 (0 active)
12 66<-00 (3 active)
13 66 07

The first few approximations for the F function are 0116 → FF16, FF16, 2216 → FF16, 3316 → DD16, and so on.

To translate these results into an estimated attack complexity, we turn to the results of Section 7.2.3. We have LPmax ≤ (108/256)2, so this suggests an attacker would need at least (LPmax)-36 ≈ 289.6 known plaintexts; and such an analysis would only work for a very small class of weak keys (representing about 2-49.1 of the keyspace for 128-bit keys, or about 2-68 of the 192-bit keyspace).

It is much more natural to demand that the attack work for a significant percentage of all keys. In this case, LPmax = (80/256)2 is a much more representative value, and thus in this model any linear attack working for a significant fraction of the keyspace would require at least 2120.8 chosen plaintexts.

These results are only heuristic estimates, and probably overestimate the probability of the best linear characteristic. Nonetheless, they present some useful evidence for the security of Twofish against linear cryptanalysis.

A more thorough analysis along the lines of section 9.4 remains to be performed.

9.5.1 Multiple Linear Approximations

Multiple linear approximations [KR94, KR95] allow one to combine the bias of several high-probability linear approximations. However, it only provides a significant advantage over traditional linear cryptanalysis when there are a number of linear approximations whose bias is close to that of the best linear approximation. In practice, this seems to improve linear attacks by a small constant factor. Hence, we do not feel that Twofish is vulnerable to this kind of cryptanalysis.

9.5.2 Non-linear Cryptanalysis

Another generalization of linear cryptanalysis looks at non-linear relations [KR96b], e.g., quadratic relations. While this attack, combined with the technique of multiple approximations [KR94], managed to improve the best linear attack against DES a minute amount [SK98], we do not believe it can be brought to bear against Twofish for the same reasons that it is immune to linear cryptanalysis.

9.5.3 Generalized Linear Cryptanalysis

This generalization of linear cryptanalysis uses the notion of binary I/O sums [HKM95, Har96, JH96]. An attacker attempts to find a statistical imbalance that can be described as the result of some group operation on some function of the plaintext and some function of the ciphertext. We have not found any such statistical imbalances, and believe Twofish to be immune to this kind of analysis.

9.5.4 Partitioning Cryptanalysis

Partitioning cryptanalysis is another generalization of linear cryptanalysis [Har96, JH96, HM97].3. An attacker trying to carry out a partitioning attack is generally trying to find some way of partitioning the input and output spaces of the round function so that knowledge of which partition the input to a round is in gives some information about which partition the output from a round is in. This can be seen as a general form of a failure of the block cipher to get good confusion; an attacker after N rounds can distinguish the output from the Nth round from a random block of bits, because the output is somewhat more likely to be in one specific partition than in any of the others. This can be used in a straightforward way to attack the last round of the cipher.4

3Similar ideas can be found in [Vau96b]
4Basic results against reduced-round DES can be found in [HYSK98].

We have been unable to find any useful way to partition the input and output spaces of the Twofish F function or a Twofish round that works consistently across many keys, because of the key-dependent S-boxes. For the 128-bit key case, there are 264 different F functions, presumably each with its own most useful partitioning. We are not aware of any general way to partition F’s inputs and outputs to facilitate such attacks.

9.5.5 Differential-linear Cryptanalysis

Differential-linear cryptanalysis uses a combination of techniques from both differential and linear cryptanalysis [LH94]. Due to the need to cover the last part of the cipher with two copies of a linear characteristic, the bias of the linear characteristic is likely to be extremely small unless the linear portion of the attack is confined to just three or four rounds. (The available linear characteristics for Twofish’s round function have a relatively low probability, and are very hard to combine due to the MDS and PHT mappings.) This means that the cryptanalyst would need to cover almost all of the rounds with the differential characteristic, making a differential-linear analysis not much more powerful than a purely differential analysis. Therefore, we feel that differential-linear cryptanalysis is unlikely to be successful against the Twofish structure. In our analysis, we have found no differential-linear attacks that work against Twofish.

9.6 Interpolation Attack

The interpolation attack [JK97, MSK98b] is effective against ciphers that use simple algebraic functions. The principle of the attack is simple: if the ciphertext can be represented as a polynomial or rational expression (with N coefficients) of the plaintext, then the polynomial or rational expression can be reconstructed using N plaintext/ciphertext pairs.

However, interpolation attacks are often only workable against ciphers with a very small number of rounds, or against ciphers whose round functions have very low algebraic degree. Twofish’s S-boxes already have relatively large algebraic degree, and the combination of operations from different algebraic groups (including both addition mod 232 and XOR) should help increase the degree even further. Therefore, we believe that Twofish is secure against interpolation attacks after even only a small number of rounds.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Cryptanalysis of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

9.7 Partial Key Guessing Attacks

A good key schedule should have the property that, when an attacker guesses some subset of the key bits, he does not learn very much about the subkey sequence or other internal operations in the cipher. The Twofish key schedule has this property.

Consider an attacker who guesses the even words of the key Me. He learns nothing of the key S to g. For each round subkey block, he now knows Ai. If he guesses K0, he can compute the corresponding K1. He can carry this attack out against as many round subkeys as he likes, but each guess takes 32 bits. We can see no way for the attacker to actually test the 96-bit guess that it would take to attack even one round’s subkey in this way on the full Twofish.

An alternative is to guess the key input S to g. This is only half the length of the full key M, but provides no information about the round keys Ki. The differential attack described in Section 9.2 is the best way we were able to find to test such a partial key guess. We can see no way to test a guess of S on the full 16-round Twofish.

9.8 Related-key Cryptanalysis

Related-key cryptanalysis [Bih94, KSW96, KSW97] uses a cipher’s key schedule to break plaintexts encrypted with related keys. In its most advanced form, differential related-key cryptanalysis, both plaintexts and keys with chosen differentials are used to recover the keys. This type of analysis has had considerable success against ciphers with simplistic key schedules—e.g., GOST [GOST89] and 3-Way [DGV94b, Dae95]—and is a realistic attack in some circumstances. A conventional attack is usually judged in terms of the number of plaintexts or ciphertexts needed for the attack, and the level of access to the cipher needed to get those texts (i.e., known plaintext, chosen plaintext, adaptive chosen plaintext). A related-key attack adds another parameter—number of related keys under which the plaintexts will be encrypted.

9.8.1 Resistance to Related-key Slide Attacks

A “slide” attack occurs in an iterated cipher when the encryption of one block for rounds 1 through n is the same as the encryption of another block for rounds s + 1 to s + n. An attacker can look at two encryptions, and can slide the rounds forward in one of them relative to another. S-1 [Anon95] can be broken with a slide attack [Wag95a]. Travois [Yuv97] has identical round functions, and can also be broken with a slide attack. Conventional slide attacks allow one to break the cipher with only known- or chosen-plaintext queries; however, as we shall see next, there is a generalization to related-key attacks as well.

Related-key slide attacks were first discovered by Biham in his attack on a DES variant [Bih94]. To mount a related-key slide attack on Twofish, an attacker must find a pair of keys M, M* such that the key-dependent S-boxes in g are unchanged, but the subkey sequences slide down one round. This amounts to finding, for each of the eight byte-permutations used for subkey generation, a change in the keys such that:

si(j, M) = si(j + 2s, M*)

for n values of j. In total, this requires 8n of these relations to hold.

Let us look in more detail for a fixed key M. Let m ≥ {5,...,8} be the number of S-boxes used to compute the round keys that are affected by the difference between M and M*. Observe that m ≥ 5 due to the restriction that S cannot change and the properties of the RS matrix that at least five inputs must change to keep the output constant. There are at most (8 m)232m-128 possible choices of M*. We have a total of nm 8-bit relations that need to be satisfied. The expected number of M* that satisfy these relations is thus (8 m).2-8nm+32m-128. For n ≥ 4 this is dominated by the case m = 5; we will ignore the other cases for now. So for each M we can expect about 238-40n keys M* that support a slide attack for n ≥ 4. This means that any specific key is unlikely to support a slide attack with n ≥ 4. Over all possible key pairs, we expect 2293-40n pairs M, M* for which a slide of n ≥ 4 occurs. Thus, it is unlikely that a pair exists at all with n ≥ 8.

Swapping Key Halves. It is worth considering what happens when we swap key halves. That is, we swap the key bytes so that the values of Me and Mo are exchanged. In that case, the sequence of Ai and Bi values totally changes because of the different index values used. We can see no useful attack that could come from this.

Permuting the Subkeys. Although there is no known attack stemming from it, it is interesting to ask whether there exist pairs of keys that give permutations of one another’s subkeys. There are 20! ways that the rounds’ subkey blocks could be permuted. This is almost as large as 264, and so there may very well be pairs of keys that give permutations of one another’s round subkey blocks.

9.8.2 Resistance to Related-key Differential Attacks

A related-key differential attack seeks to mount a differential attack on a block cipher through the key, as well as or instead of through the plain-text/ciphertext port. Against Twofish, such an attack must control the sub-key difference sequence for at least the rounds in the middle. For the sake of simplifying discussions of the attack, let us consider an attacker who wants to put a chosen subkey difference into the middle 12 rounds’ subkeys. That is, he wants to change M to M* and control D[i, M, M*] for i = 12,...,35. At the same time, he needs to keep the g function, and thus the key S, from changing. All else being equal, the longer the key, the more freedom an attacker has to mount a related-key differential attack. We thus will assume the use of 256-bit keys for the remainder of this section. Note that a successful related-key attack on 128- or 192-bit keys that gets only zero subkey differences in the rounds whose subkey differences it must control translates directly to an equivalent related-key attack on 256-bit keys.

Consider the position of the attacker if he attempts a related-key differential attack with different S keys. This must result in different g outputs for all inputs, since we know that there are no pairs of S values that lead to identical S-boxes. Assuming the pair of S values does not lead to linearly related S-boxes, it will not be possible to compensate for this change in S with changes in the subkeys in single rounds. If we assume 12 active rounds in the attack, the added difficulty is approximately that of adding 24 active S-boxes to the existing related-key attack. For this reason, we believe that any useful related-key attack will require a pair of keys that keeps S unchanged.

9.8.3 The Zero Difference Case

The simplest related-key attack to analyze is the one that keeps both S and also the middle 12 rounds’ subkeys unchanged. It thus seeks to generate identical A and B sequences for 12 rounds, and thus to keep the individual byte sequences used to derive A and B identical.

The RS code used to derive S from M strictly limits the ways an attacker can change M without altering S. The attacker must try to keep the number of active subkey generating S-boxes as low as possible, since each active S-box is another constraint on his attack. The attacker can keep the number of active S-boxes down to five without altering S, so this is what he should do. With only the key bytes affecting these five subkey generation S-boxes active, he can alter between one and four bytes in all five S-boxes; the nature of the RS matrix is that if he needs to alter four bytes in any one of these S-boxes, he must alter bytes in all five. In practice, in order to maximize his control over the byte sequences generated by these S-boxes, he must alter four bytes in all five active S-boxes.

To get zero subkey differences, the attacker must get zero differences in the byte sequences generated by all five active S-boxes. Consider a single such byte sequence: the attacker tries to find a pair of four-byte key inputs such that they lead to identical byte sequences in the middle 12 rounds, which means the middle 12 bytes. There are 263 pairs of key inputs from which to choose, and about 295 possible byte sequences available. If the byte sequences behave more-or-less like random functions of the key inputs, this implies that it is extremely unlikely that an attacker can find a pair of key inputs that will get identical byte sequences in these middle 12 rounds. We discuss this kind of analysis of byte sequences in Section 8.2.3. From this analysis, we would not expect to see a pair of keys for even one S-box with more than eight successive bytes unchanged, and we would expect even eight successive bytes of unchanged byte sequence to require control of all four key bytes into the S-box. We would expect a specific pair of key bytes to be required to generate these similar byte sequences.

To extend this to five active S-boxes, we expect there to be, at best, a single pair of values for the 20 active key bytes that leave the middle eight subkeys unchanged.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Cryptanalysis of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

9.8.4 Other Difference Sequences

An attacker who has control of the XOR difference sequences in Ai, Bi does not necessarily have great control over the XOR or modulo 232 difference sequence that appears in the subkeys.

First, we must consider the context of a related-key differential attack. The attacker does not generally know all of the key bytes generating either Ai or Bi. Instead, he knows the XOR difference sequence in Ai and Bi.

Consider an Ai value with an XOR difference of δ. If the Hamming weight of δ is k, not including the high-order bit, then the best estimate for the XOR difference that ends up in the two subkey words for a given round generally has probability of about 2-2k. (Control of the Ai, Bi XOR difference sequence does not make controlling the subkey XOR differences substantially easier.)

Consider an Ai value with an XOR difference of δ. If the Hamming weight of δ is k, then the best estimate for the modulo 232 difference of the two subkey words for a given round has probability of about 2-k.

This points out one of the difficulties in mounting any kind of successful related-key attack with non-zero Ai, Bi difference sequences. If an attacker can find a difference sequence for Ai, Bi that keeps k = 3, and needs to control the subkey differences for 12 rounds, he has a probability of about 2-72 of getting the most likely XOR subkey difference sequence, and about 2-36 of getting the most likely modulo 232 difference sequence. After getting the most likely mod 232 difference into the subkeys, however, the attacker must deal with the fact that the output values are XORed into half of the block. Those relatively high-probability mod 232 differences end up back at 2-72 probability for any given XOR difference sequence actually being XORed into the successive rounds’ target blocks.

9.8.5 Probability of a Successful Attack with One Related-key Query

We consider the use of the RS matrix in deriving S from M to be a powerful defense against related-key differential attacks, because it forces an attacker to keep at least five key generation S-boxes active. Our analysis suggests that any useful control of the subkey difference sequence requires that each active S-box in the attack have all four key bytes changed.

Further, our analysis suggests that, for nearly any useful difference sequence, each active S-box in the attack has a specific pair of defining key bytes it needs to work. An attacker specifying his key relation in terms of bytewise XOR has five pairs of sequences of four key bytes each, which he wants to get. This leaves him with a probability of a pair of keys with his desired relation actually leading to the desired attack of about 2-115, which moves the attack totally outside the realm of practical attacks.

So long as an attacker is unable to improve this, either by finding a way to get useful difference sequences into the subkeys without having so many active key bytes, or by finding a way to mount related-key attacks with different S values for the different keys, we do not believe that any kind of related-key differential attack is feasible.

Note the implication of this: clever ways to control a couple extra rounds’ subkey differences are not going to make the attacks feasible, unless they also allow the attacker to use far fewer active key bytes. For reference, note that with one altered key byte per active subkey generation S-box, the attacker ends up with a 2-39 probability that a pair of related keys will yield an attack; with two key bytes per active S-box, this increases to 2-78; with three key bytes per active S-box, it increases to 2-117. In practice, this means that any key relation requiring more than one byte of key changed per active S-box appears to be impractical.

9.8.6 Conclusions

Our analysis suggests that related-key differential attacks against the full Twofish are not workable. Note, however, that we have spent less time working on resistance to chosen-key attacks, such as will be available to an attacker if Twofish is used in the straightforward way to define a hash function. For this reason, we recommend that more analysis be done before Twofish is used in the straightforward way as a hash function, and we note that it appears to be much more secure to use Twofish in this way with 128-bit keys than with 256-bit keys, despite the fact that this also slows the speed of a hash function down by a factor of two.

9.9 A Chosen-key Attack

A chosen-key attack is a variant of a related-key attack. Not only are there several keys that are related, the attacker actually gets to choose some parts of these keys. The parts not chosen are unknown to the attacker, and the objective of the attack is to find them.

Attack Type Rounds Work Factor Text Req. Special Req.
Partial Chosen Key | 10 | 234 | 232;212 | 160 bits of key from K, K* chosen by attacker
Related-Key | 10 | 2187 | 232;212 | 2155 related-key queries
Table 9.9. Attack Results for Our Chosen-key Attack

9.9.1 Overview of the Attack

Results. We define a partial chosen key attack on a 10-round Twofish without the pre- or post-whitening. The attack requires us to control 20 selected bytes of the key, and to set them differently for a pair of related keys K, K*. The remaining 12 bytes of the two keys, which are the same for both keys, are unknown to us; recovering them is the objective of the attack. Our attack results are summarized in Table 9.9.

Note that the text requirements are shown as n;m, where n is the number of chosen plaintexts, and m is the number of adaptive chosen plaintexts. Also note that the related-key version of the attack requires this many chosen and adaptive chosen plaintexts for each of the 2155 related-key pairs.

How the Attack Works. The attack works as follows:

1. Choose a pair of keys, K, K*, with the property that the middle eight round subkeys are the same for both keys, and the S key value is the same for both keys. This leaves us with some knowledge about the differences that make it into the subkeys as well.
2. Request one encryption under K, and 232 encryptions under K*, trying to find a way to offset the effect of the change in the first round subkey.
3. When we find a likely right pair (detected because of the zero difference in half the ciphertext block), use it to probe the contents of each S-box in turn. This allows us to recover the S key value. This value, given the RS matrix used for its derivation and our starting partial knowledge of the key, allows us to recover the rest of the key algebraically.

9.9.2 Finding a Key Pair

The first step in the attack is finding a pair of keys, K, K*, with some relationship, such that we get a useful subkey difference sequence, while leaving the S key unchanged. We described above how such keys can exist. Here, we assume the existence of some pair of keys with a subkey XOR difference sequence zero in rounds one through eight but with non-zero XOR subkey differences in rounds zero and nine.

Structure of the Key Pair. Based on the discussion above, we assume that the keys K, K* differ in 20 bytes, with the changed bytes selected in such a way to leave S unchanged between the two keys, and to change all four key bytes used to define five of the S-boxes used for subkey generation. We note that a random pair of keys chosen to have this property has only a 2-155 probability of being the pair of keys that will generate our desired sub-key difference sequence. This makes this attack impractical as a differential related-key attack, though an attacker who is able to control the active 20 bytes of key involved in a pair of keys could mount the attack for a chosen pair of keys. (That is, the attacker could choose the values of the active 20 bytes of both K and K*, while remaining ignorant of the other twelve bytes of K and K*, which must be identical for both keys. The attacker would then attempt to learn those remaining 12 bytes of key.)

Subkey Differences. We actually care only about the subkey difference in the round subkey words. Recall that the subkey words are generated from a pair of 32-bit words, which are generated from the subkey generation S-boxes. Let’s call these values U, V and U*, V*. We don’t know any of U, V, U*, V*, but we do know U′ = U ⊕ U* and V′ = V ′ V*.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Cryptanalysis of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

9.9.3 Choosing the Plaintexts to Request

From U′, V′, it is possible to generate a set of about 232 XOR difference values that we can expect to see result from the changed subkeys when they’re used in the F function in the first round. We thus do the following:

1. Request the encryption of some fixed 128-bit block A, B, C, D under key K.
2. For each of the 232 different 64-bit XOR difference values, Xi, Yi, we might expect from U′, V′, request the encryption of 128-bit block (A, B, C ⊕ Xi, D ⊕ Yi).
3. Consider only those ciphertexts from the second step that lead to the same right half of ciphertext as the encryption under K in the first step. The goal is to determine the output XOR from the first round’s F function when the input is A, B, under the two keys. (The only difference in the output is caused by the difference in round subkeys.) Note that we expect to have about one false positive occur; we simply run the attack on both potential right pairs; the wrong pair will not allow the attacker to find any S-box offsetting differences.

9.9.4 Extracting the Key Material

At this point, we know the single XOR difference from the F function. We can now learn the S-boxes in the g function. To do this, we replace the high-order byte of A in the right pair with 256 different values. Thus, we request the encryption of Aj, B, C, D under K*. This causes one of 256 possible XOR differences in the g function output. We expect to have to try about 512 requests with different XOR difference values Xi, Yi, where these values are derived from the Xi, Yi values that generated the original right pair based on the possible XOR differences in g. We thus request 512 plaintexts of the form Aj, B, C ⊕ Xi, D ⊕ Yi) to be encrypted under K*. One of these we expect to be a right pair, which we can recognize, again, by the fact that the right half of the ciphertext is the same for Aj, B, C, D encrypted under K, and for Aj, B, C ⊕ Xi, D ⊕ Yi encrypted under K*.

After carrying this out for each of the Aj, we have good information about the XOR differences being generated from g by the changes between A and Aj as input. In particular, we will note the 14 cases where we probably got 8-bit Hamming weights in the output XOR difference of g. This information should be enough to brute-force this S-box, s3. That is, we try all 232 possible S-boxes for s3, and expect one to be the best fit for our data.

We repeat the attack for each of the other bytes in A, so that we recover all four S-boxes in g. When we know these S-boxes, this means we know S. Note that at the beginning of the attack, we already know 20 of the 32 key bytes used. More importantly, due to the structure of the RS matrix used to derive S from the raw key bytes, we know all but three bytes used to derive each 4-byte “row” of values in S. This allows us to guess and check the remaining key bytes three bytes at a time, thus recovering the entire key.

9.10 Side-Channel Cryptanalysis and Fault Analysis

Resistance to these attacks was not part of the AES criteria, and hence not a major concern in this design. However, we do have these comments to make on the design.

Side-channel cryptanalysis [KSWH98b] uses information about the cipher in addition to the plaintext or ciphertext. Examples include timing [Koc96], power consumption (including differential power analysis [Koc98a]), NMR scanning, and electronic emanations.5 With many algorithms it is possible to reconstruct the key from these side channels. While total resistance to side-channel cryptanalysis is probably impossible, we note that Twofish executes in constant time on most processors.

5The NSA refers to this particular side channel as "TEMPEST."

Fault analysis [BDL97, BS97] can be used to successfully cryptanalyze this cipher. Again, we believe that total resistance to fault analysis is an impossible design constraint for a cipher. The resistance to fault analysis of any block cipher can be improved using classical tamper-resistance and fault-tolerance techniques (although see [AK96]).

In most cases, Twofish seems to be inherently resistant to timing analysis. However, it is worth noting that in certain special cases, implementers may need to take extra care to avoid the possibility of timing attacks. On platforms with extremely limited memory resources, it is natural to compute the multiplies over GF(28) on the fly without the aid of additional tables by using a shift-register-based approach. If this approach is to be followed, beware: timing attacks may be possible. The obvious way to clock a shift register in software is to shift it and then XOR in the feedback polynomial if the bit that shifted out was a one—but this algorithm does not execute in constant time, because the XOR operation is performed only if a certain data bit is set. Thus, this implementation pattern should be avoided. A better approach would be to XOR in either zero or the feedback polynomial, depending on the value of the bit just shifted out, thereby guaranteeing constant-time execution and resistance to timing analysis. This is probably only of concern to smart cards and other computing platforms without much memory.

9.11 Attacking Simplified Twofish

9.11.1 Twofish with Known S-boxes

As discussed above, our differential attack on Twofish with fixed S-boxes works for 6-round Twofish, and requires only 267 effort. A 7-round differential attack requires 2131 effort.

Additionally, much of Twofish’s related-key attack resistance comes from the derivation of the S-boxes, so a related-key attack is much easier against a known S-box variant.

9.11.2 Twofish without Round Subkeys

We attack a Twofish variant without any subkeys, thus whose whole key material is in the key-dependent S-boxes. The attack requires about 233 chosen plaintexts; it breaks the Twofish variant with about 236 effort, even when the cipher has a 128-bit key. (Note that this is the amount of key material used to define the S-boxes in normal Twofish with a 256-bit key.)

It is obvious that a Twofish variant with fixed S-boxes and no subkeys would be insecure—there would be no key material injected. We develop a slide attack on Twofish with any number of rounds, and a 128-bit key. (The Twofish key would be 256 bits, but since we never use more than 128 bits of key in the key-dependent S-boxes, the effective key size is 128 bits.)

Note that this attack would not work if we used round subkeys that were simply counter values, as would happen if we used the identity permutation for all the key-scheduling S-boxes. We are not currently aware of any attack on such a Twofish variant.

Overview of the Attack. In a slide attack, we attempt to find a pair of plaintexts, (P, P*), such that P* has the same value as the intermediate value after one or more rounds of encrypting P. If we can find and expose this value, we gain direct access to the results of a single round of the cipher; we then attack that single round to recover the key.

Our attack has two parts:

1. We must first find a pair of plaintexts, (P, P*), such that P* is the result of encrypting P with one round.
2. We use this pair to derive four relations on g and thus determine the specific S-boxes used in g. This yields the effective key of the cipher.

Finding Our Related Pair of Texts. Twofish is a Feistel cipher, operating on two 64-bit halves in each block. We use the representation where the left half of the block is the input to the Feistel function, and the halves are swapped after each round. Let (L0, R0) represent a given pair of 64-bit halves input into the cipher, and let (LN, RN) represent the resulting ciphertext. To mount this attack, we need to find some (L0, R0, L1) such that L1 is the value of the left half of the block after the first round. To test whether we have such a pair, we can try encrypting (L0, R0) and (L1, L0). When we have a triple with the desired properties, we get (LN, RN) from the first encryption, and (LN+1 LN) from the second encryption.

We use a trick by Biham [Bih94] to get such a pair of plaintexts with only 233 chosen plaintexts: we choose a fixed L0, and encrypt it with 232 randomly selected R0 values as (L0, R0). We then encrypt the same L0 with 232 random R1, values, as, (R1, L0). By the birthday paradox, we expect to see one pair of values for which R1 = R0 ⊕ F(L0). To find this pair, we sort the ciphertexts from the first batch of encryptions on their left halves, and the ciphertexts from the second batch of encryptions on their right halves. When we find a match, the probability is good that we have a pair with the desired property.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Cryptanalysis of Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Extracting g Values. Once we have this triple (L0, R0, L1), we also have two relations on F: F(L0) = R0 ⊕ L1 and F(LN) = RN ⊕ LN+1. Note, however, that we do not yet have direct g values. Instead, we have two instances of the results of combining two g outputs with a PHT. Since we have the actual PHT output values, we can simply undo the PHT, yielding relations on g. Our pair has given us two relations on F, and thus four relations on g.

Extracting the S-boxes. The g outputs are the result of applying four key-dependent S-boxes to the input bytes, and then combining those bytes with an MDS matrix multiply. Since the MDS multiply is invertible, we invert it to get back the actual S-box outputs for all four different values. If those values are all different, then we have four bytes of output from each S-box. We can try all 232 possible key input values for each S-box, and see which ones are consistent with the results; for most sets byte values, only one or two S-boxes will match them. We thus learn each key-dependent S-box in g, perhaps with a couple of alternative values. We try all possible alternatives against any plaintext/ciphertext values we have available, and very quickly recover the correct S-boxes. Since this is the only key material in this Twofish variant, the attack is done.

9.11.3 Twofish with Non-bijective S-boxes

We decided early in the design process to use purely bijective S-boxes. One rationale was to ensure that the 64-bit round function is bijective. That way, iterative 2-round differential characteristics cannot exist; when they do exist, they often result in the highest-probability multi-round characteristic, so avoiding them should help to reduce the risk of a successful differential attack. Also, attacks based on non-surjective round functions [BB95, RP95b, RPD97, CWSK98] are sure to fail when the 64-bit Feistel round function is bijective.6

6Vaudenay’s attack on Blowfish took advantage of non-bijectivity in the Blowfish round function [Vau96a].

We argue here that this was a good design decision, by showing that a Twofish variant that uses non-bijective S-boxes is likely to be much easier to break.

Observe that when q0 and q1 are non-bijective, their 3-way composition into si is likely to be even more non-surjective than either q0 or q1 on its own. It is easily seen that the expected size of the range of a random function on eight bits (such as q0 or q1) is r1 = 1 - (1 - (1 - 1/256)256 ≈ 1 - e-1 ≈ 0.632. When we compose such a function twice, its expected range becomes r2 = 1 - (1 - 1/256)256r1, ≈ 1-e-r1 ≈ 0.469; and the expected size of the range of a 3-way composition will be rs ≈ 1 - e-r2 ≈ 0.374. In other words, we expect that only about 96 ≈ 0.374 × 256 of all possible 8-bit values can appear as the output of the S-box. Therefore, the output of the h function can attain only about 226.3 ≈ 964 possible values, and the 64-bit Feistel function can attain only about 252.6 of all 264 possible outputs. This is certainly a rather large certificational weakness. (This gets worse when the key size grows, since the number of compositions of the q functions gets larger.)

We point out a serious differential attack when using non-bijective random S-boxes. Consider the probability pΔx that a given input difference Δx yields a collision in the S-box output; i.e., Δx → 0. Let p = ςΔx≠0 pΔx/255 be the average probability over all non-zero input differences, and let m = maxΔx≠0 pΔx be the maximum probability over all non-zero input differences. We have E p = 3/256; also, Pr(p ≥ 2/256) ≈ 0.78, Pr(p ≥ 10/256) ≈ 0.02, and Pr(p ≥ 16/256) ≈ 0.0002. As for the distribution of m, empirically E m ≈ 11.7/256; experiments suggest Pr(m ≥ 10/256) ≈ 0.975, Pr(m ≥ 16/256) ≈ .04, and Pr(m ≥ 22/256) ≈ 0.0002.

Consider a Twofish variant with random non-bijective S-boxes and no rotations. We obtain a 2-round iterative differential characteristic with probability m, and thus a 13-round differential characteristic with probability m6.

We find that, for 97.5 percent of the keys, one can break the variant with about 228 chosen plaintexts; for 4 percent of the keys, it can be broken with 224 chosen plaintexts; and for a class of weak keys consisting of 0.02 percent of the keys, the variant cipher can be broken with roughly 221 chosen plain-texts. (Of course, one can trade off the number of texts needed against the size of the weak key class; the figures given are just examples of points on a smooth curve.)

Next we consider a Twofish variant with random non-bijective S-boxes, but with all rotations left intact. If we look at any 2-round differential characteristic whose first round is the trivial characteristic and whose second round involves just one active S-box, we expect its probability to be about p. One difficulty is that the rotations prevent us from finding an iterative 2-round characteristic. However, we can certainly piece together 6.5 different 2-round differential characteristics (each of the right form so it will have probability about p) to find a 13-round characteristic with expected probability p6. (The latter probability can probably be improved to about 3p6, due to the extra degrees of freedom, but as we are only doing a back-of-the-envelope estimate anyway, we will omit these considerations.) Thus, we can find a differential attack that succeeds with about 239 chosen plaintexts for the majority (about 78 percent) of the keys; also, for 2 percent of the keys, this variant can be broken with 228 chosen plaintexts; and for a class of weak keys consisting of 0.02 percent of the keys, the variant cipher can be broken with roughly 224 chosen plaintexts.

This analysis clearly shows the value of bijective S-boxes in stopping differential cryptanalysis. Also, it helps show the benefit of the rotations: they make short iterative characteristics much harder to find, thereby conferring (we hope) some additional resistance against differential attacks.

9.12 Trap Doors in Twofish

We assert that Twofish has no trap doors. As designers, we have made every effort to make Twofish secure against all known (and unknown) cryptanalysis, and we have made no effort to build in a secret way of breaking Twofish. However, there is no way to prove this, and not much reason for anyone to believe us. We can offer some assurances.

In this book, we have outlined all of the design elements of Twofish and our justifications for including them. We have explained, in great detail, how we chose Twofish’s “magic constants”: the RS code, q0, q1 and the MDS matrix. There are no mysterious design elements; everything has an explicit purpose. Moreover, we feel that the use of key-dependent S-boxes makes it harder to install a trap door into the cipher. As difficult as it is to create a trap door for a particular set of carefully constructed S-boxes, it is much harder to create one that works with all possible S-boxes or even a reasonably useful subset of them (of relative size 2-20 or so).

Additionally, any trap door would have to survive 16 rounds of Twofish. It would have to work even though there is almost perfect diffusion in each round. It would have to survive the pre- and post-whitening. These design elements have long been known to make any patterns difficult to detect; trap doors would be no different.

None of this constitutes a proof. Any reasonable proof of general security for a block cipher would also prove P ≠ NP. Rather than outlining the proof here, we would likely skip the AES competition and go collect our Fields Medal.

However, we have made headway towards a philosophical proof. Assume for a moment that, despite the difficulties listed above, we did manage to put a trap door into Twofish. This would imply one of two things:

One, that we have invented a powerful new cryptanalytic attack and have carefully crafted Twofish to be resistant to all known attacks but vulnerable to this new one. We cannot prove that this is not true. However, we can point out that as cryptographers we would achieve much more fame and glory by publishing our powerful new cryptanalytic attack. In fact, we would probably publish it along with this paper, making sure Twofish is immune so that we can profitably attack the other AES submissions.

The other possibility is that we have embedded a trap door into the Twofish magic constants and then transformed them by some means so that finding them would be a statistical impossibility (see [Har96] for some discussion of this possibility). The resulting construction would seem immune to current cryptanalytic techniques, but we as designers would know a secret transformation rule that we could apply to facilitate cryptanalysis. Again, we cannot prove that this is not true. However, it has been shown that this type of cipher, called a “master-key cryptosystem,” is equivalent to a public-key cryptosystern [BFL96]. Again, as cryptographers we would achieve far greater recognition by publishing a public-key cryptosystem. that is not dependent on factoring [RSA78] or the discrete logarithm problem [DH76, E1G85, NIST94]. And the resulting algorithm’s dual capabilities as both a symmetric and public-key algorithm would make it far more flexible than the AES competition requires (and hence an excellent choice for the standard).

There is a large gap between a weakness that is exploitable in theory and one that is exploitable in practice. Even the best attack against DES (a linear-cryptanalysis-like attack combining quadratic approximations and a multiple-approximation method) requires just under 243 plaintext/ciphertext blocks [SK98], which is equivalent to about 64 terabytes of plaintext/ciphertext encrypted under a single key. A useful trap door would need to work with much less plaintext—a few thousand blocks—or it would have to reduce the effective keyspace to something on the order of 272. We believe that, given the quality of the public cryptanalytic research community, it would be impossible to put a weakness of this magnitude into a block cipher and have it remain undetected through the AES process. And we would be foolish to even try.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Using Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Chapter 10
Using Twofish

10.1 Chaining Modes

All standard block-cipher chaining modes work with Twofish: CBC, CFB, OFB, counter [NBS80]. We axe aware of no problems with using Twofish with any commonly used chaining mode. (See [Sch961 for a detailed comparison of the various modes of operation.) A cryptanalyst considering OFB-, CFB-, or CBC-mode encryption with Twofish may collapse the pre- and post-whitening of key material into a single XOR, but he does not appear to benefit much from this.

10.2 One-Way Hash Rinctions

It is not hard to build a one-way hash function out of Twofish [Win84]. We suggest the following construction, taken from [Pre93]:

Hi = Mi ⊕ EHi-1 (Mi)

This mode seems to be somewhat preferable to Davies-Meyer, because it gives the cryptanalyst less control over the value entering the key port and thus may provide more robust protection in case there are any related-key attacks on Twofish.

We believe that Twofish, with its strong key schedule, can be used securely in any of these formats. Note, however, that the key schedule has been analyzed mainly for related-key attacks, not for the class of chosen-key attack that hash functions must resist. Additionally, the 128-bit block size makes straightforward use of this construction useful only when collision-finding attacks can be expected to be unable to try 264 trial hashes to find a collision.

As keys that are non-standaxd sizes have equivalent keys that are longer, any use of Twofish in a hashing construction must ensure that only a single key length is used. We recommend using 128-bit keys for hashing constructions.

10.3 Message Authentication Codes

Twofish can be easily used to build a very strong message authentication code using the CBC-MAC construction [BKR94]. In fact, [BKR94] gives formal proofs of security for the CBC-MAC approach, assuming that the underlying cipher is secure. We feel that this makes Twofish-CBC-MAC a very strong candidate for use in message authentication applications.

Alternatives include using Twofish as a hash function, and then constructing a MAC out of the hash function [BCK96].

10.4 Pseudorandom Number Generators

Twofish can also be used as a primitive in a pseudorandom number generator suitable for generating session keys, public-key parameters, protocol nonces, and so on [Plu94, KSWH98a, Gut98, KSWH98c].

10.5 Larger Keys

Even though it would be straightforward to extend the Twofish key schedule scheme to larger key sizes, there is currently no definition of Twofish for key lengths greater than 256 bits. We urge caution in trying to extend key lengths; our experience with Twofish has taught us that extending the key length can have important security implications.

10.6 Additional Block Sizes

There is no definition of Twofish for block lengths other than 128 bits. While it may be theoretically possible to extend the construction to larger block sizes, we have not evaluated these constructions at all. We urge caution in trying to extend the block size; many of the constructions we use may not scale well to 256 bits, 512 bits, or larger blocks.

10.7 More or Fewer Rounds

Twofish is defined to have 16 rounds. We designed the key schedule to allow natural extensions to more or fewer rounds if and when required. We strongly advise against reducing the number of rounds. We believe it is safe to increase the number of rounds, although we see no need to do so. Note that the key schedule cannot support more than 124 rounds, as the 8-bit input counter to the key schedule S-boxes overflows.

Algorithm Key Length Width (bits) Rounds Cycles Clocks/ Byte
Twofish | variable | 128 | 16 | 8 | 16.1
Blowfish | variable | 64 | 16 | 8 | 19.8
Square | 128 | 128 | 8 | 8 | 20.3
RC5-32/16 | variable | 64 | 32 | 16 | 24.8
CAST-128 | 128 | 64 | 16 | 8 | 29.5
DES | 56 | 64 | 16 | 8 | 43
Serpent | 128,192, 256 | 128 | 32 | 32 | 45
SAFER (S)K-128 | 128 | 64 | 8 | 8 | 52
FEAL-32 | 64, 128 | 64 | 32 | 16 | 65
IDEA | 128 | 64 | 8 | 8 | 74
Triple-DES | 112 | 64 | 48 | 24 | 116
Table 10.1. Performance of Different Block Ciphers (on a Pentium)

More and more recent ciphers are being defined with a variable number of rounds; e.g., SAFER-K64 [Mas94], RC5 [Riv95], and SPEED [Zhe97]. This means that it is impossible to categorically state that a given cipher construction is insecure: there might always be a number of rounds n for which the cipher is still secure. However, while this might theoretically be true, this is not a useful engineering definition of “secure.” After all, the user of the cipher actually has to choose how many rounds to use. In a performance-driven model, it is useful to compare ciphers of equal speed, and compare their security, or compare ciphers of equal security and compare their speeds. For example, FEAL-32 is secure against both differential and linear attacks. Its speed is 65 clock cycles per byte of encryption, which makes it less desirable than faster, also secure, alternatives. As speed is relatively easy to measure and quantify, the simplest way of comparing ciphers in a performance-driven model is to choose the number of rounds in such a way as to make the two ciphers equally fast. The hard question of “which cipher is more secure” then remains, but at least that is a clearly defined problem.

With that in mind, Table 10.1 gives performance metrics for block and stream ciphers on the Pentium processor.1 Similar comparisons are being done for the AES candidates [SKW+99a], and will presumably be one of the criteria in the selection process.

1These metrics are based on theoretical analyses of the algorithms and actual hand-tooled assembly-language implementations [SW97, PRB98a, PRB98b].


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Using Twofish

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

10.8 Family Key Variant: Twofish-FK

We often see systems that use a proprietary variant of an existing cipher, altered in some hopefully security-neutral way to prevent that system from interoperating with standard implementations of the cipher. A family key is a way of designing this into the algorithm: each different family key is used to define a different variant of the cipher. In some sense, the family key is like an additional key to the cipher, but in general, it is acceptable for the family key to be very computationally expensive to change. We would expect nearly all Twofish implementations that used any family key to use only one family key.

Our goals for the family key algorithm are as follows:

• No family key variant should be substantially weaker than the original cipher.
• Related-key attacks between different unknown but related family keys, or between a known family key and the original cipher, should be hard to mount.
• The family key should not merely reorder the set of 128-by-128-bit permutations provided by the cipher, it should change that set.

A Twofish family key is simply a 256-bit random Twofish key. This key, FK, is used to derive several blocks of bits, as follows:

1. Preprocessing Step:
This step is done once per family key.
a) T0 = FK.
b) T1 = (EFK(0), EFK(1)) ⊕ FK.
c) T2 = EFK(2).
d) T3 = EFK(3).
e) T4 = First 8 bytes of EFK(4).

Note that, using our little-endian convention, the small integers used as plaintext inputs should occur in the first plaintext byte.
2. Key Scheduling Step: This step is done once per key used under this family key.
a) Before subkey generation, T0 is XORed into the key, using as many of the leading bytes of T0 as necessary.
b) After subkey generation, T2 is XORed into the pre-whitening subkeys, T3 is XORed into the post-whitening subkeys, and T4 is XORed into each round’s 64-bit subkey block.
c) Before the cipher’s S-boxes are derived, T1, is XORed into the key. Once again, we use as many of the leading bytes of T1, as we need. Each byte of the key is then passed through the byte permutation q0, and the result is passed through the RS matrix to get S. Note that the definition of T1, means that the effect of the first XOR of FK into the key is undone.

Note the properties of the alterations made by any family key:

• The keyspace is simply permuted for the initial subkey generation.
• The subkeys are altered in a simple way. However, there is strong evidence that this alteration cannot occur by changing keys, based on the same difference sequence analysis used in discussing related-key attacks on Twofish.
• The S-boxes used in the cipher are altered in a powerful way, but one which does not alter the basic required properties of the key schedule. Getting no changes in the S-boxes used in the cipher still requires changing at least five bytes of key, and those five bytes of key must change five of the S-boxes used for subkey generation.

10.8.1 Analysis

Effects of Family Keys on Cryptanalysis. We are not aware of any substantial difference in the difficulty of cryptanalyzing the family key version of the cipher rather than the regular version. The cipher’s operations are unchanged by the family key; only subkey and S-box generation are changed. However, they are changed in simple ways; the S-boxes are generated in exactly the same way as before, but the key material provided to them is processed in a simple way first; the round subkeys are generated in the same way as before (again, with the key material processed in a simple way first), and then have a constant 64-bit value XORed in. Related-key attacks of the kind we have been able to consider are made slightly harder, rather than easier, by this 64-bit value. The new constants XORed into the whitening subkeys simply permute the input and output space of the cipher in a very simple way.

Related Keys across Family Keys. Related-key attacks under the same family key appear, as we said above, to be at least as hard as related-key attacks in normal Twofish. There is still the question, however, of whether there are interesting related keys across different family keys. It is hard to see how such related keys would be used, but the analysis may be worth pursuing anyway.

An interesting question, from the perspective of an attacker, is whether there ar e pairs of keys that give identical subkeys except for the constant values XORed into them, and that also give identical S-boxes. By allowing an attacker to put a constant XOR into all round subkeys, such pairs of keys would provide a useful avenue of attack.

This can be done by finding a pair of related family keys, FK, FK*, that are identical in their first 128 bits, and a pair of 128-bit cipher keys, M, M*, such that M generates the same set of S-boxes with FK that M* does with FK*. For a random pair of M, M* values, this has probability 2-64 of happening, Thus, an attacker given complete control over M, M* and knowledge of FK, FK* can find such a pair of keys and family keys. However, this does not seem to translate into any kind of clean related-key attack; the attacker must actually choose the specific keys used.

We do not consider this to be a valid attack against the system. In general, related-key attacks between family keys seem unrealistic, but one which also requires the attacker to be able to choose specific key values he is trying to recover is also pointless.

A Valid Related-key Attack. An attacker can also try to find quadruples FK, FK*, M, M* such that the subkey generation and the S-box generation both get identical values. This requires that

T0 ⊕ M = T0* ⊕ M*

T1 ⊕ M = T1* ⊕ M*

If FK, FK* have the property that

T0 ⊕ T0* = T1 ⊕ T1* = δ

then related-key pairs M, M ⊕ Ϙ will put a fixed XOR difference into every round subkey, and may allow some kind of related-key attack. Again, we do not think this is an interesting attack; the attacker must force the family keys to be chosen this way, since the probability that any given pair of family keys will work this way is (for 128-bit cipher keys) 2-128. We do not expect such relationships to occur by chance until about 264 family keys are in use.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Historical Remarks

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Chapter 11
Historical Remarks

Twofish originated from an attempt to take the original Blowfish design and modify it for a 128-bit block. We wanted to leverage the speed and good diffusion of Blowfish, while also improving it where we could. We wanted the new cipher to have a bijective F function, a much more efficient key schedule, and to be implementable in custom hardware and smart cards in addition to 32-bit processors (i.e., have smaller tables). And we wanted it to be even faster than Blowfish (per byte encrypted), if possible.

Initial thoughts were to have the Blowfish round structure operate on the four 32-bit subblocks in a circular structure (an incomplete Feistel network), but there were problems getting the diffusion to work in both the encryption and decryption directions. Having two parallel Blowfish round functions and letting them interact via a two-dimensional Feistel structure ran into the same problems. Our solution was to have a single Feistel structure with two Blowfish-like 32-bit round functions and to combine them using a PHT (an idea stolen from SAFER). This idea also provided nearly complete avalanche during the round.

Round subkeys are required to avoid slide attacks against identical round functions. We used addition instead of XOR to take advantage of the Pentium LEA opcode and implement them in effectively zero time.

We used 8-by-8-bit S-boxes and an MDS matrix (an idea stolen from Square, although Square uses a single fixed S-box) instead of random 8-by-32-bit S-boxes, both to simplify the key schedule and ensure that the g function is bijective. This construction ensured that Twofish would be efficient on 32-bit processors (by precomputing the S-boxes and MDS matrix into four 8-by-32-bit S-boxes) while still allowing it to be computed on the fly in smart cards. And since our MDS matrix is only ever computed in one direction, we did not have to worry about the matrix’s efficiency in the reverse direction (which Square had to consider).

The construction also gave us considerable performance flexibility. We worked hard to keep this flexibility, so implementers would have a choice of how much key pre-processing to do depending on the amount of plaintext to be encrypted. And we tried to maintain these tradeoffs for 32-bit microprocessors, 8-bit microprocessors, and custom hardware.

Since one goal was to be able to keep the complete design in our heads, any complication that did not have a clear purpose was deleted. Additional complications we chose not to introduce were key-dependent MDS matrices or round-dependent variations on the byte ordering and the PHT. We also toyed with the idea of swapping 32-bit words within the Feistel halves (something we called the “twist”), but abandoned it because we saw no need for the additional complexity.

We did keep in the one-bit rotations of the target block, primarily to reduce the vulnerability to any attack based on byte boundaries. The particular manifestation of this one-bit rotation was due to a combination of performance and cryptanalytic concerns. Larger rotations would be slower in some implementations, and simpler constructions were less secure.

We considered using all the key bytes, rather than just half, to define the key-dependent S-boxes. Unfortunately, this made the key setup time for high-end machines unreasonably large, and also made encryption too slow on low-end machines. By dropping this to half the key bits, these performance figures were improved substantially. By carefully selecting how the key bytes were folded down to half their size before being used to generate the cipher’s S-boxes, we were able to ensure that pairs of keys with the same S-boxes would have very different subkey sequences.

The key schedule gave us the most trouble. We had to resist the temptation to build a cryptographic key schedule like the ones used by Blowfish, Khufu, and SEAL, because low-end implementations needed to be able to function with minimal additional memory and, if necessary, to compute the subkeys as needed by the cipher. However, a simple key schedule can be an important weak point in a cipher design, leaving the whole cipher vulnerable to partial-key guessing attacks, related-key attacks, or to attacks based on waiting for especially weak keys to be selected by a user. Though our final key schedule is rather complex, it is conceptually much simpler than many of our intermediate designs. Reusing many of the primitives of the cipher (each round’s subkeys are generated by a computation nearly identical to the one that goes on inside the round function, except for the specific inputs involved) made it possible to investigate properties of both the key schedule and of the cipher at the same time.

We spent considerable time choosing q0 and q1. Since these provide the primary non-linearity in the cipher, they had to be strong. We wanted to be able to construct them algebraically for applications where storing 512 bytes of fixed tables was not possible. In the end, we built permutations from random parameters, and tested the permutations against our required criteria.

The name “Twofish” reared its head late in the design process. We tried various names beginning with “Blow” or ending with “fish.” The name Twofish was chosen for several reasons: it is traditional to name ciphers after sea creatures, and animals in general; no one liked “Blowfish II”; the round function originally derived from two Blowfish round functions in parallel; and of course, there is Dr. Seuss [Seu60].1

1For readers who did not grow up in North America: Dr. Seuss was a famous writer of children’s books, one of which is called One Fish, Two Fish, Red Fish, Blue Fish. The marketing tie-ins were too lucrative to ignore.

And finally, we cryptanalyzed Twofish. We cryptanalyzed and cryptanalyzed and cryptanalyzed, right up to the morning of the submission deadline. Since then we have cryptanalyzed more, and are continuing to do so. There’s no stopping.


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Conclusions and Further Work

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Chapter 12
Conclusions and Further Work

We have presented Twofish, the rationale behind its design, and the results of our initial cryptanalysis. Design and cryptanalysis go hand in hand—it is impossible to do one without the other—and it is only in the analysis that the strength of an algorithm can be demonstrated.

During the design process, we learned several lessons about cipher design:

• The encryption algorithm and key schedule must be designed in tandem; subtle changes in one affect the other. It is not enough to design a strong round function and then to graft a strong key schedule onto it (unless you are satisfied with an inefficient and inelegant construction like Blowfish has); both must work together.
• There is no such thing as a key-dependent S-box, only a complicated multistage non-linear function that is implemented as a key-dependent S-box for efficiency.
• Keys should be as short as possible. It is much harder to design an algorithm with a long key than an algorithm with a short key. Throughout our design process, we found it easier to design and analyze Twofish with a 128-bit key than Twofish with a 192-or 256-bit key.
• Build a cipher with strong local encryption and let the round function handle the global diffusion. Designing Twofish in this manner made it very hard to mount any statistical cryptanalytical attacks.
• Consider performance at every stage of the design. Having a code optimization guru on our team from the beginning drastically changed the way we looked at design tradeoffs, to the ultimate benefit of Twofish.
• Analysis can go on forever. Even after the 15 June 1998 AES submission deadline, we are still cryptanalyzing Twofish.

We believe Twofish to be an ideal algorithm choice for AES. It is efficient on large microprocessors, smart cards, and dedicated hardware, The multiple layers of performance tradeoffs in the key schedule make it suitable for a variety of implementations. And the attention to cryptographic detail in the design—both the encryption function and the key schedule—make it suitable as a codebook, output-feedback and cipher-feedback stream cipher, one-way hash function (using standard techniques for converting block ciphers into hash functions), and pseudorandom number generator.

We welcome any new cryptanalysis from the cryptographic community. We plan on continuing to evaluate Twofish all through the AES selection process and beyond. Specifically:

• Whether the number of rounds can safely be reduced. At this point our best non-related-key attack—a differential attack—can only break five rounds. If no better attacks are found after a few years, it may be safe to reduce the number of rounds to 14 or even 12. 12-round Twofish can encrypt and decrypt data at about 220 clock cycles per block on a Pentium, Pentium Pro, and Pentium II.
• Whether there are alternative fixed tables that increase security. We have chosen both the MDS matrix and the fixed permutations, q0 and q1, to meet our mathematical requirements. In the event we find better constants that make Twofish even harder to cryptanalyze, we may want to revise the algorithm.
• Whether we can define a Twofish variant with fixed S-boxes. This variant would have a faster key setup time than the algorithm presented here—about 1200 clock cycles on a Pentium Pro—and the same encryption and decryption speeds. Although we cannot break Twofish with fixed S-boxes, further research is required on what the fixed S-boxes would look like, and how much data could be safely encrypted with this variant.
• Whether we can improve our lower bounds on the complexity of a differential attack and a linear attack.

Developing Twofish was a richly rewarding experience, and one of our most satisfying cryptographic projects to date. There is an enormous gap between simply creating a cryptographic primitive and completing a full design process, and we have learned much by completing the process.


by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

References

[AB96a] | R. Anderson and E. Biham, “Two Practical and Provably Secure Block Ciphers: BEAR and LION,” Fast Software Encryption, Third International Workshop Proceedings, Springer-Verlag, 1996, pp. 113-120. [Page 5]
[AB96b] | R. Anderson and E. Biham, “Tiger: A Fast New Hash Function,” Fast Software Encryption, Third International Workshop Proceedings, Springer-Verlag, 1996, pp. 89-97. [Pages 38, 46]
[Ada97a] | C. Adams, “Constructing Symmetric Ciphers Using the CAST Design Procedure,” Designs, Codes and Cryptography, v.12, n.3, Nov 1997, pp. 71-104. [Pages 5, 35, 38, 39]
[Ada97b] | C. Adams, “DES-80,” Workshop on Selected Areas in Cryptography (SAC ’97) Workshop Record, School of Computer Science, Carleton University, 1997, pp. 160-171. [Page 37]
[AGMP96] | G. Alvarez, D. De la Guia, F. Montoya, and A. Peinado, “Akelarre: A New Block Cipher Algorithm,” Workshop on Selected Areas in Cryptography (SAC ’96) Workshop Record, Queens University, 1996, pp. 1-14. [Page 36]
[AK96] | R. Anderson and M. Kuhn, “Tamper Resistance — A Cautionary Note,” Proceedings of the Second USENIX Workshop on Electronic Commerce, USENIX Press, 1996, pp. 1-11. [Page 111]
[Anon95] | Anonymous, “this looked like it might be interesting,” sci.crypt Usenet posting, 9 Aug 1995. [Pages 41, 104]
[AT90] | C.M. Adams and S.E. Tavares, “The Structured Design on Cryptographically Good S-Boxes,” Journal of Cryptology, v. 3,n. 1, 1990, pp. 27-41. [Page 39]
[AT93] | C.M. Adams and S.E. Tavares, “Designing S-boxes for Ciphers Resistant to Differential Cryptanalysis,” Proceedings of the 3rd Symposium on State and Progress of Research in Cryptography, Rome, Italy, 15-16 Feb 1993, pp. 181-190. [Pages 35, 39]
[BAK98] | E. Biham, R. Anderson, and L. Knudsen, “Serpent: A New Block Cipher Proposal,” Fast Software Encryption, 5th International Workshop Proceedings, Springer-Verlag, 1998, pp. 222-238. [Pages 30, 34, 38, 41]
[Bau93] | F.L. Bauer, Kryptologie, Springer-Verlag, 1993. (In German.) [Page 49]
[Bau97] | F.L. Bauer, Decrypted Secrets, Springer-Verlag, 1997. [Page 49]
[BB93] | I. Ben-Aroya and E. Biham, “Differential Cryptanalysis of Lucifer,” Advances in Cryptology — CRYPTO ’93 Proceedings, Springer-Verlag, 1994, pp. 187-199. [Page 75]
[BB94] | E. Biham and A. Biryukov, “How to Strengthen DES Using Existing Hardware,” Advances in Cryptology — ASIACRYPT ’94 Proceedings, Springer-Verlag, 1994, pp. 398-412. [Page 39]
[BB95] | E. Biham and A. Biryukov, “An Improvement of Davies’ Attack on DES,” Advances in Cryptology — EUROCRYPT ’94 Proceedings, Springer-Verlag, 1995, pp. 461-467. [Pages 40, 114]
[BB96] | U. Blumenthal and S. Bellovin, “A Better Key Schedule for DES-Like Ciphers,” Pragocrypt ’96 Proceedings, 1996, pp. 42-54. [Page 37]
[BCK96] | M. Bellare, R. Canetti, and H. Karwczyk, “Keying Hash Functions for Message Authentication,” Advances in Cryptology — CRYPTO ’96 Proceedings, Springer-Verlag, 1996, pp. 1-15. [Page 120]
[BDL97] | D. Boneh, R.A. DeMillo, and R.J. Lipton “On the Importance of Checking Cryptographic Protocols for Faults,” Advances in Cryptology — EUROCRYPT ’97 Proceedings, Springer-Verlag, 1997, pp. 37-51.[Page 111]
[BDR+96] | M. Blaze, W. Diffie, R. Rivest, B. Schneier, T. Shimomura, E. Thompson, and M. Weiner, “Minimal Key Lengths for Symmetric Ciphers to Provide Adequate Commercial Security,” Jan 1996. [Page 1]
[BFL96] | M. Blaze, J. Feigenbaum, and F. T. Leighton, Master-Key Cryptosystems, DIMACS Technical Report 96-02, Rutgers University, Piscataway, 1996. [Page 116]
[Bih94] | E. Biham, “New Types of Cryptanalytic Attacks Using Related Keys,” Journal of Cryptology, v. 7, n. 4, 1994, pp. 229-246. [Pages 35, 104, 105, 113]
[Bih95] | E. Biham, “On Matsui’s Linear Cryptanalysis,” Advances in Cryptology — EUROCRYPT ’94 Proceedings, Springer-Verlag, 1995, pp. 398-412. [Page 38]
[Bih97] | E. Biham, “A Fast New DES Implementation in Software,” Fast Software Encryption, 4th International Workshop Proceedings, Springer-Verlag, 1997, pp. 260-271. [Page 34]
[BK98] | A. Biryukov and E. Kushilevitz, “Improved Cryptanalysis of RC5,” Advances in Cryptology — EUROCRYPT ’98 Proceedings, Springer-Verlag, 1998, pp. 85-99. [Page 36]
[BKPS93] | L. Brown, M. Kwan, J. Pieprzyk, and J. Seberry, “Improving Resistance to Differential Cryptanalysis and the Redesign of LOKI,” Advances in Cryptology — ASIACRYPT ’91 Proceedings, Springer-Verlag, 1993, pp. 36-50. [Pages 5, 33]
[BKR94] | M. Bellare, J. Kilian, and P. Rogaway, “The security of the cipher block chaining message authentication code,” Advances in Cryptology — CRYPTO ’94, Springer-Verlag, 1994. [Page 120]
[BPS90] | L. Brown, J. Pieprzyk, and J. Seberry, “LOKI: A Cryptographic Primitive for Authentication and Secrecy Applications,” Advances in Cryptology — AUSCRYPT ’90 Proceedings, Springer-Verlag, 1990, pp. 229-236. [Pages 5, 33]
[Bro98] | L. Brown, “Design of LOKI97,” draft AES submission, 1998. [Page 39]
[BS92] | E. Biham and A. Shamir, “Differential Cryptanalysis of Snefru, Khafre, REDOC II, LOKI, and Lucifer,” Advances in Cryptology — CRYPTO ’91 Proceedings, Springer-Verlag, 1992, pp. 156-171. [Page 38]
[BS93] | E. Biham and A. Shamir, Differential Cryptanalysis of the Data Encryption Standard, Springer-Verlag, 1993. [Pages 35, 38]
[BS95] | M. Blaze and B. Schneier, “The MacGuffin Block Cipher Algorithm,” Fast Software Encryption, Second International Workshop Proceedings, Springer-Verlag, 1995, pp. 97-110. [Pages 5, 46]
[BS97] | E. Biham and A. Shamir, “Differential Fault Analysis of Secret Key Cryptosystems,” Advances in Cryptology — CRYPTO ’97 Proceedings, Springer-Verlag, 1997, pp. 513-525. [Page 111]
[CDN95] | G. Carter, E. Dawson, and L. Nielsen, “DESV: A Latin Square Variation of DES,” Proceedings of the Workshop on Selected Areas in Cryptography (SAC ’95), Ottawa, Canada, 1995, pp. 158-172. [Page 58]
[CDN98] | G. Carter, E. Dawson, and L. Nielsen, “Key Schedules of Iterative Block Ciphers,” Third Australian Conference, ACISP ’98, Springer-Verlag, to appear. [Page 41]
[Cla97] | C.S.K. Clapp, “Optimizing a Fast Stream Cipher for VLIW, SIMD, and Superscalar Processors,” Fast Software Encryption, 4th International Workshop Proceedings, Springer-Verlag, 1997, pp. 273-287. [Page 38]
[Cla98] | C.S.K. Clapp, “Joint Hardware/Software Design of a Fast Stream Cipher,” Fast Software Encryption, 5th International Workshop Proceedings, Springer-Verlag, 1998, pp. 75-92. [Page 38]
[CM98] | H. Chabanne and E. Michon, “JEROBOAM,” Fast Software Encryption, 5th International Workshop Proceedings, Springer-Verlag, 1998, pp. 49-59. [Page 33]
[Cop94] | D. Coppersmith, “The Data Encryption Standard (DES) and its Strength Against Attacks,” IBM Journal of Research and Development, v. 38, n. 3, May 1994, pp. 243-250. [Pages 38, 39]
[Cop98] | D. Coppersmith, personal communication, 1998. [Page 38]
[CW91] | T. Cusick and M.C. Wood, “The REDOC-II Cryptosystem,” Advances in Cryptology — CRYPTO ’90 Proceedings, Springer-Verlag, 1991, pp. 545-563. [Pages 33, 36, 39]
[CWSK98] | D. Coppersmith, D. Wagner, B. Schneier, and J. Kelsey, “Cryptanalysis of TWOPRIME,” Fast Software Encryption, 5th International Workshop Proceedings, Springer-Verlag, 1998, pp. 32-48. [Pages 40, 114]
[Dae95] | J. Daemen, “Cipher and Hash Function Design,” Ph.D. thesis, Katholieke Universiteit Leuven, Mar 95. [Page 104]
[DBP96] | H. Dobbertin, A. Bosselaers, and B. Preneel, “RIPEMD-160: A Strengthened Version of RIPEMD,” Fast Software Encryption, Third International Workshop Proceedings, Springer-Verlag, 1996, pp. 71-82. [Page 58]
[DC98a] | J. Daemen and C. Clapp, “Fast Hashing and Stream Encryption with PANAMA,” Fast Software Encryption, 5th International Workshop Proceedings, Springer-Verlag, 1998, pp. 60-74. [Page 37]
[DC98b] | J. Daemen and C. Clapp, “The Panama Cryptographic Function,” Dr. Dobbs Journal, v. 23, n. 12, Dec 1998, pp. 42-49. [Page 37]
[DGV93] | J. Daemen, R. Govaerts, and J. Vandewalle, “Block Ciphers Based on Modular Arithmetic,” Proceedings of the 3rd Symposium on: State and Progress of Research in Cryptography, Fondazione Ugo Bordoni, 1993, pp. 80-89. [Page 36]
[DGV94a] | J. Daemen, R. Govaerts, and J. Vandewalle, “Weak Keys for IDEA,” Advances in Cryptology — EUROCRYPT ’93 Proceedings, Springer-Verlag, 1994, pp. 159-167. [Page 75]
[DGV94b] | J. Daemen, R. Govaerts, and J. Vandewalle, “A New Approach to Block Cipher Design,” Fast Software Encryption, Cambridge Security Workshop Proceedings, Springer-Verlag, 1994, pp. 18-32. [Pages 35, 104]
[DH76] | W. Diffie and M. Hellman, “New Directions in Cryptography,” IEEE Transactions on Information Theory, v. IT-22, n. 6, Nov 1976, pp. 644-654. [Page 116]
[DH79] | W. Diffie and M. Hellman, “Exhaustive Cryptanalysis of the NBS Data Encryption Standard,” Computer, v. 10, n. 3, Mar 1979, pp. 74-84. [Page 1]
[DK85] | C. Deavours and L.A. Kruh, Machine Cryptography and Modern Cryptanalysis, Artech House, Dedham MA, 1985. [Page 49]
[DKR97] | J. Daemen, L. Knudsen, and V. Rijmen, “The Block Cipher Square,” Fast Software Encryption, 4th International Workshop Proceedings, Springer-Verlag, 1997, pp. 149-165. [Pages 6, 36, 44, 54]
[ElG85] | T. ElGamal, “A Public-Key Cryptosystem and a Signature Scheme Based on Discrete Logarithms,” IEEE Transactions on Information Theory, v. IT-31, n. 4, 1985, pp. 469-472. [Page 116]
[Fei73] | H. Feistel, “Cryptography and Computer Privacy,” Scientific American, v. 228, n. 5, May 1973, pp. 15-23. [Pages 5, 44]
[Fer96] | N. Ferguson, personal communication, 1996. [Page 7]
[Fer98a] | N. Ferguson, “Bounds on the tail of binomial distributions,” research notes, 1998. [Page 93]
[Fer98b] | N. Ferguson, “Upper Bounds on Differential Characteristics in Two-fish,” Twofish Technical Report #1, Counterpane Systems, Aug 1998. [Page v]
[FNS75] | H. Feistel, W.A. Notz, and J.L. Smith, “Some Cryptographic Techniques for Machine-to-Machine Data Communications, Proceedings on the IEEE, v. 63, n. 11, 1975, pp. 1545-1554. [Pages 5, 44]
[FS97] | N. Ferguson and B. Schneier, “Cryptanalysis of Akelarre,” Workshop on Selected Areas in Cryptography (SAC ’97) Workshop Record, School of Computer Science, Carleton University, 1997, pp. 201-212. [Page 36]
[GC94] | H. Gilbert and P. Chauvaud, “A Chosen-Plaintext Attack on the 16-Round Khufu Cryptosystem,” Advances in Cryptology — CRYPTO ’94 Proceedings, Springer-Verlag, 1994, pp. 359-368. [Page 38]
[GOST89] | GOST, Gosudarstvennyi Standard 28147-89, “Cryptographic Protection for Data Processing Systems,” Government Committee of the USSR for Standards, 1989. [Pages 5, 38, 104]
[Gut98] | P. Gutmann, “Software Generation of Random Numbers for Crypto-graphic Purposes,” Proceedings of the 1998 USENIX Security Symposium, USENIX Press, 1998, pp. 243-257. [Page 120]
[Har96] | C. Harpes, Cryptanalysis of Iterated Block Ciphers, ETH Series on Information Processing, v. 7, Hartung-Gorre Verlang Konstanz, 1996. [Pages 102, 116]
[Haw98] | P. Hawkes, “Differential-Linear Weak Key Classes of IDEA,” Advances in Cryptology — EUROCRYPT ’98 Proceedings, Springer-Verlag, 1998, pp. 112-126. [Page 75]
[HKM95] | C. Harpes, G. Kramer, and J. Massey, “A Generalization of Linear Cryptanalysis and the Applicability of Matsui’s Piling-up Lemma,” Advances in Cryptology — EUROCRYPT ’95 Proceedings, Springer-Verlag, 1995, pp. 24-38. [Page 102]
[HKR+98] | C. Hall, J. Kelsey, V. Rijmen, B. Schneier, and D. Wagner, “Cryptanalysis of SPEED,” Selected Areas in Cryptography, Springer-Verlag, 1998, to appear. [Page 33]
[HKSW98] | C. Hall, J. Kelsey, B. Schneier, and D. Wagner, “Cryptanalysis of SPEED,” Financial Cryptography ’98 Proceedings, Springer-Verlag, 1998, pp. 309-310. [Page 33]
[HM97] | C. Harpes and J. Massey, “Partitioning Cryptanalysis,” Fast Software Encryption, 4th International Workshop Proceedings, Springer-Verlag, 1997, pp. 13-27. [Page 102]
[HT94a] | H.M. Heys and S.E. Tavares, “On the Security of the CAST Encryption Algorithm,” Canadian Conference on Electrical and Computer Engineering, 1994, pp. 332-335. [Page 35]
[HT94b] | H.M. Heys and S.E. Tavares, “The Design of Substitution-Permutation Networks Resistant to Differential and Linear Cryptanalysis,” 2nd ACM Conference on Computer and Communications Security, ACM Press, 1994, pp. 148-155. [Page 44]
[HYSK98] | T. Hamade, T. Yokoyama, T. Shimada, and T. Kanedo, “On Partitioning Cryptanalysis of DES,” 1998 Symposium on Cryptography and Information Security, 2.2.A. (In Japanese.) [Page 103]
[Jeff+76] | T. Jefferson et al., “Declaration of Independence,” Philadelphia PA, 4 Jul 1776. [Page 38]
[JH96] | T. Jakobsen and C. Harpes, “Bounds on Non-Uniformity Measures for Generalized Linear Cryptanalysis and Partitioning Cryptanalysis,” Pragocrypt ’96 Proceedings, 1996, pp. 467-479. [Page 102]
[JK97] | T. Jakobsen and L. Knudsen, “The Interpolation Attack on Block Ciphers,” Fast Software Encryption, 4th International Workshop Proceedings, Springer-Verlag, 1997, pp. 28-40. [Pages 35, 39, 103]
[Kie96] | K. Kiefer, “A New Design Concept for Building Secure Block Ciphers,” Proceedings of the 1st International Conference on the Theory and Applications of Cryptography, Pragocrypt ’96, CTU Publishing House, 1996, pp. 30-41. [Page 35]
[KKT94] | T. Kaneko, K. Koyama, and R. Terada, “Dynamic Swapping Schemes and Differential Cryptanalysis,” IEICE Transactions, v. E77-A, 1994, pp. 1328-1336. [Page 58]
[KLPL95] | K. Kim, S. Lee, S. Park, and D. Lee, “Securing DES S-boxes Against Three Robust Cryptanalysis,” Proceedings of the Workshop on Selected Areas in Cryptography (SAC ’95), Ottawa, Canada, 1995, pp. 145-157. [Page 38]
[KM97] | L.R. Knudsen and W. Meier, “Differential Cryptanalysis of RC5,” European Transactions on Communication, v. 8, n. 5, 1997, pp. 445-454. [Page 36]
[Knu93a] | L.R. Knudsen, “Cryptanalysis of LOKI,” Advances in Cryptology — ASIACRYPT ’91, Springer-Verlag, 1993, pp. 22-35. [Page 39]
[Knu93b] | L.R. Knudsen, “Cryptanalysis of LOKI91,” Advances in Cryptology — AUSCRYPT ’92, Springer-Verlag, 1993, pp. 196-208. [Page 39]
[Knu93c] | L.R. Knudsen, “Iterative Characteristics of DES and s2DES,” Advances in Cryptology — CRYPTO ’92, Springer-Verlag, 1993, pp. 497-511. [Page 38]
[Knu94a] | L.R. Knudsen, “Block Ciphers — Analysis, Design, Applications,” Ph.D. dissertation, Aarhus University, Nov 1994. [Page 35]
[Knu94b] | L.R. Knudsen, “Practically Secure Feistel Ciphers,” Fast Software Encryption, Cambridge Security Workshop Proceedings, Springer-Verlag, 1994, pp. 211-221. [Pages 35, 37, 75]
[Knu95a] | L.R. Knudsen, “New Potentially ’Weak’ Keys for DES and LOKI,” Advances in Cryptology — EUROCRYPT ’94 Proceedings, Springer-Verlag, 1995, pp. 419-424. [Page 40]
[Knu95b] | L.R. Knudsen, “Truncated and Higher Order Differentials,” Fast Software Encryption, 2nd International Workshop Proceedings, Springer-Verlag, 1995, pp. 196-211. [Pages 35, 39, 90]
[Knu95c] | L.R. Knudsen, “A Key-Schedule Weakness in SAFER K-64,” Advances in Cryptology — CRYPTO ’95 Proceedings, Springer-Verlag, 1995, pp. 274-286. [Page 60]
[Koc96] | P. Kocher, “Timing Attacks on Implementations of Diffie-Hellman, RSA, DSS, and Other Systems,” Advances in Cryptology — CRYPTO ’96 Proceedings, Springer-Verlag, 1996, pp. 104-113. [Page 111]
[Koc98a] | P. Kocher, “Differential Power Analysis, “ available online from http://www.cryptography.com/dpa/. [Page 111]
[Koc98b] | P. Kocher, “DES Key Search Project,” available online from http://www.cryptography.com/des/index.html. [Page 1]
[KPL93] | K. Kim, S. Park, and S. Lee, “Reconstruction of s2DES S-Boxes and their Immunity to Differential Cryptanalysis,” Proceedings of the 1993 Japan-Korea Workshop on Information Security and Cryptography, Seoul, Korea, 24-26 October 1993, pp. 282-291. [Page 38]
[KR94] | B. Kaliski Jr. and M. Robshaw, “Linear Cryptanalysis Using Multiple Approximations,” Advances in Cryptology — CRYPTO ’94 Proceedings, Springer-Verlag, 1994, pp. 26-39. [Page 102]
[KR95] | B. Kaliski Jr. and M. Robshaw, “Linear Cryptanalysis Using Multiple Approximations and FEAL,” Fast Software Encryption, Second International Workshop Proceedings, Springer-Verlag, 1995, pp. 249-264. [Page 102]
[KR96a] | J. Kilian and P. Rogaway, “How to Protect DES Against Exhaustive Key Search,” Advances in Cryptology — CRYPTO ’96 Proceedings, Springer-Verlag, 1996, pp. 252-267. [Pages 5, 6]
[KR96b] | L. Knudsen and M. Robshaw, “Non-Linear Approximations in Linear Cryptanalysis,” Advances in Cryptology — EUCROCRYPT ’96, Springer-Verlag, 1996, pp. 224-236. [Page 102]
[KR97] | L.R. Knudsen and V. Rijmen, “Two Rights Sometimes Make a Wrong,” Workshop on Selected Areas in Cryptography (SAC ’97) Workshop Record, School of Computer Science, Carleton University, 1997, pp. 213-223. [Page 36]
[KRRR98] | L.R. Knudsen, V. Rijmen, R. Rivest, and M. Robshaw, “On the Design and Security of RC2,” Fast Software Encryption, 5th International Workshop Proceedings, Springer-Verlag, 1998, pp. 206-221. [Page 33]
[KSHW98] | J. Kelsey, B. Schneier, C. Hall, and D. Wagner, “Secure Applications of Low-Entropy Keys,” Information Security. First International Workshop ISW ’97 Proceedings, Springer-Verlag, 1998, 121-134. [Page 42]
[KSW96] | J. Kelsey, B. Schneier, and D. Wagner, “Key-Schedule Cryptanalysis of IDEA, G-DES, GOST, SAFER, and Triple-DES,” Advances in Cryptology — CRYPTO ’96 Proceedings, Springer-Verlag, 1996, pp. 237-251. [Pages 35, 41, 79, 104]
[KSW97] | J. Kelsey, B. Schneier, and D. Wagner, “Related-Key Cryptanalysis of 3-WAY, Biham-DES, CAST, DES-X, NewDES, RC2, and TEA,” Information and Communications Security, First International Conference Proceedings, Springer-Verlag, 1997, pp. 203-207. [Pages 35, 41, 79, 104]
[KSWH98a] | J. Kelsey, B. Schneier, D. Wagner, and C. Hall, “Cryptanalytic Attacks on Pseudorandom Number Generators,” Fast Software Encryption, 5th International Workshop Proceedings, Springer-Verlag, 1998, pp. 168-188. [Page 120]
[KSWH98b] | J. Kelsey, B. Schneier, D. Wagner, and C. Hall, “Side Channel Cryptanalysis of Product Ciphers,” ESORICS ’98 Proceedings, Springer-Verlag, 1998, pp 97-110. [Page 111]
[KSWH98c] | J. Kelsey, B. Schneier, D. Wagner, and C. Hall, “Yarrow: A Pseudo-random Number Generator,” in preparation. [Page 120]
[Kwa97] | M. Kwan, “The Design of ICE Encryption Algorithm,” Fast Software Encryption, 4th International Workshop Proceedings, Springer-Verlag, 1997, pp. 69-82. [Page 41]
[KY95] | B.S. Kaliski and Y.L. Yin, “On Differential and Linear Cryptanalysis of the RC5 Encryption Algorithm,” Advances in Cryptology — CRYPTO ’95 Proceedings, Springer-Verlag, 1995, pp. 445-454. [Page 36]
[Lai94] | X. Lai, “Higher Order Derivations and Differential Cryptanalysis,” Communications and Cryptography: Two Sides of One Tapestry, Kluwer Academic Publishers, 1994, pp. 227-233. [Page 35, 90]
[LC97] | C.-H. Lee and Y.-T. Cha, “The Block Cipher: SNAKE with Provable Resistance Against DC and LC Attacks, “ Proceedings of JW-ISC ’97, KIISC and ISEC Group of IEICE, 1997, pp. 3-17. [Page 35]
[Lee96] | M. Leech, “CRISP: A Feistel Network with Hardened Key Scheduling,” Workshop on Selected Areas in Cryptography (SAC ’96) Workshop Record, Queens University, 1996, pp. 15-29. [Page 37]
[LH94] | S. Langford and M. Hellman, “Differential-Linear Cryptanalysis,” Advances in Cryptology — CRYPTO ’94 Proceedings, Springer-Verlag, 1994, pp. 17-26. [Page 103]
[LM91] | X. Lai and J. Massey, “A Proposal for a New Block Encryption Standard,” Advances in Cryptology — EUROCRYPT ’90 Proceedings, Springer-Verlag, 1991, pp. 389-404. [Page 33]
[LMM91] | X. Lai, J. Massey, and S. Murphy, “Markov Ciphers and Differential Cryptanalysis,” Advances in Cryptology — CRYPTO ’91 Proceedings, Springer-Verlag, 1991, pp. 17-38. [Pages 33, 46]
[MA96] | S. Mister and C. Adams, “Practical S-Box Design,” Workshop on Selected Areas in Cryptography (SAC ’96) Workshop Record, Queens University, 1996, pp. 61-76. [Page 38]
[Mad84] | W.E. Madryga, “A High Performance Encryption Algorithm,” Computer Security: A Global Challenge, Elsevier Science Publishers, 1984, pp. 557-570. [Page 36]
[Mas94] | J.L. Massey, “SAFER K-64: A Byte-Oriented Block-Ciphering Algorithm,” Fast Software Encryption, Cambridge Security Workshop Proceedings, Springer-Verlag, 1994, pp. 1-17. [Pages 7, 44, 121]
[Mat94] | M. Matsui, “Linear Cryptanalysis Method for DES Cipher,” Advances in Cryptology — EUROCRYPT ’93 Proceedings, Springer-Verlag, 1994, pp. 386-397. [Page 35]
[Mat95] | M. Matsui, “On Correlation Between the Order of S-Boxes and the Strength of DES,” Advances in Cryptology — EUROCRYPT ’94 Proceedings, Springer-Verlag, 1995, pp. 366-375. [Page 38]
[Mat96] | M. Matsui, “New Structure of Block Ciphers with Provable Security Against Differential and Linear Cryptanalysis,” Fast Software Encryption, 3rd International Workshop Proceedings, Springer-Verlag, 1996, pp. 205-218. [Pages 35, 48]
[Mat97] | M. Matsui, “New Block Encryption Algorithm MISTY,” Fast Software Encryption, 4th International Workshop Proceedings, Springer-Verlag, 1997, pp. 54-68. [Page 35]
[McD97] | T.J. McDermott, “NSA comments on criteria for AES,” letter to NIST, National Security Agency, 2 Apr 97. [Pages 32, 42]
[Mer91] | R.C. Merkle, “Fast Software Encryption Functions,” Advances in Cryptology — CRYPTO ’90 Proceedings, Springer-Verlag, 1991, pp. 476-501. [Pages 5, 33, 46]
[Mor98] | S. Moriai, “How to Design Secure S-boxes Against Different Differential, Liear, Higher Order Differential,and Interpolation Attacks,” 1998 Symposium on Cryptography and Information Security, 2.2.C. (In Japanese.) [Page 39]
[MS77] | F.J. MacWilliams and N.J.A. Sloane, “The Theory of Error-Correcting Codes,” North-Holland, Amsterdam, 1977. [Pages 6, 76]
[MSK98a] | S. Moriai, T. Shimoyama, and T. Kaneko, “Higher Order Differential Attack of a CAST Cipher,” Fast Software Encryption, 5th International Workshop Proceedings, Springer-Verlag, 1998, pp. 17-31. [Page 35]
[MSK98b] | S. Moriai, T. Shimoyama, and T. Kaneko, “Interpolation Attacks of the Block Cipher: SNAKE,” 1998 Symposium on Cryptography and Information Security, 7.2.C. (In Japanese.) [Pages 35, 103]
[Mur90] | S. Murphy, “The Cryptanalysis of FEAL-4 with 20 Chosen Plaintexts,” Journal of Cryptology, v. 2, n. 3, 1990, pp. 145-154. [Page 39]
[NBS77] | National Bureau of Standards, NBS FIPS PUB 46, “Data Encryption Standard,” National Bureau of Standards, U.S. Department of Commerce, Jan 1977. [Pages 1, 5, 34]
[NBS80] | National Bureau of Standards, NBS FIPS PUB 46, “DES Modes of Operation,” National Bureau of Standards, U.S. Department of Commerce, Dec 1980.[Page 119]
[NIST93] | National Institute of Standards and Technology, “Secure Hash Standard,” U.S. Department of Commerce, May 1993. [Pages 39, 46, 58]
[NIST94] | National Institute of Standards and Technologies, NIST FIPS PUB 186, “Digital Signature Standard,” U.S. Department of Commerce, May 1994. [Page 116]
[NIST97a] | National Institute of Standards and Technology, “Announcing Development of a Federal Information Standard for Advanced Encryption Standard,” Federal Register, v. 62, n. 1, 2 Jan 1997, pp. 93-94. [Page 1]
[NIST97b] | National Institute of Standards and Technology,”Announcing Request for Candidate Algorithm Nominations for the Advanced Encryption Standard (AES),” Federa Register, v. 62, n. 117, 12 Sep 1997, pp. 48051-48058. [Pages 1, 3, 34]
[NK95] | K. Nyberg and L.R. Knudsen, “Provable Security Against Differential Cryptanalysis,” Journal of Cryptology, v. 8, n. 1, 1995, pp. 27-37. [Page 35]
[NM97] | J. Nakajima and M. Matsui, “Fast Software Implementation of MISTY on Alpha Processors,” Proceedings of JW-ISC ’97, KIISC and ISEC Group of IEICE, 1997, pp. 55-63. [Page 34]
[NSA98] | NSA, “Skipjack and KEA Algorithm Specifications,” Version 2.0, National Security Agency, 29 May 1998. [Pages 5, 40, 46]
[Nyb91] | K. Nyberg, “Perfect Nonlinear S-boxes,” Advances in Cryptology — EUROCRYPT ’91 Proceedings, Springer-Verlag, 1991, pp. 378-386. [Page 35]
[Nyb93] | K. Nyberg, “On the Construction of Highly Nonlinear Permutations,” Advances in Cryptology — EUROCRYPT ’92 Proceedings, Springer-Verlag, 1993, pp. 92-98. [Page 35]
[Nyb94] | K. Nyberg, “Differentially Uniform Mappings for Cryptography,” Advances in Cryptology — EUROCRYPT ’93 Proceedings, Springer-Verlag, 1994, pp. 55-64. [Page 35]
[Nyb95] | K. Nyberg, “Linear Approximation of Block Ciphers,” Advances in Cryptology — EUROCRYPT ’94 Proceedings, Springer-Verlag, 1995, pp. 439-444. [Page 35]
[Nyb96] | K. Nyberg, “Generalized Feistel Networks,” Advances in Cryptology — ASIACRYPT ’96 Proceedings, Springer-Verlag, 1996, pp. 91-104. [Pages 35, 36]
[OCo94a] | L. O’Connor, “Enumerating Nondegenerate Permutations,” Advances in Cryptology — EUROCRYPT ’93 Proceedings, Springer-Verlag, 1994, pp. 368-377. [Page 35]
[OCo94b] | L. O’Connor, “On the Distribution of Characteristics in Bijective Mappings,” Advances in Cryptology — EUROCRYPT ’93 Proceedings, Springer-Verlag, 1994, pp. 360-370. [Page 35]
[OCo94c] | L. O’Connor, “On the Distribution of Characteristics in Composite Permutations,” Advances in Cryptology — CRYPTO ’93 Proceedings, Springer-Verlag, 1994, pp. 403-412. [Page 35]
[PB92] | H. Beker and F. Piper, Cipher Systems, Northwind Books, 1992. [Page 49]
[Plu94] | C. Plumb, “Truly Random Numbers,” Dr. Dobbs Journal, v. 19, n. 13, Nov 1994, pp. 113-115. [Page 120]
[PRB98a] | B. Preneel, V. Rijmen, and A. Bosselaers, “Principles and Performance of Cryptographic Algorithms,” Dr. Dobbs Journal, v. 23, n. 12, Dec 1998, pp. [Page 121]
[PRB98b] | B. Preneel, V. Rijmen, and A. Bosselaers, “Recent Developments in the Design of Conventional Cryptographic Algorithms,” State of the Art and Evolution of Computer Security and Industrial Cryptography, Lecture Notes in Computer Science, B. Preneel, R. Govaerts, J. Vandewalle, Eds., Springer-Verlag, 1998, to appear. [Page 121]
[Pre93] | B. Preneel, Analysis and Design of Cryptographic Hash Functions, Ph.D. dissertation, Katholieke Universiteit Leuven, Jan 1993. [Pages 23, 119]
[QDD86] | J.-J. Quisquater, Y. Desmedt, and M. Davio, “The Importance of ’Good’ Key Scheduling Schemes,” Advances in Cryptology — CRYPTO ’85 Proceedings, Springer-Verlag, 1986, pp. 537-542. [Page 42]
[RAND55] | RAND Corporation, A Million Random Digits with 100,000 Normal Deviates, Glencoe, IL, Free Press Publishers, 1955. [Page 38]
[RC94] | P. Rogaway and D. Coppersmith, “A Software-Optimized Encryption Algorithm,” Fast Software Encryption, Cambridge Security Workshop Proceedings, Springer-Verlag, 1994, pp. 56-63. [Page 33, 34]
[RC98] | P. Rogaway and D. Coppersmith, “A Software-Optimized Encryption Algorithm,” Journal of Cryptology, v. 11, n. 4, 1998, pp. 273-287. [Pages 33, 34]
[RDP+96] | V. Rijmen, B. Preneel, A. Bosselaers, and E. DeWin, “The Cipher SHARK,” Fast Software Encryption, 3rd International Workshop Proceedings, Springer-Verlag, 1996, pp. 99-111. [Pages 5, 6, 44]
[Rij97] | V. Rijmen, Cryptanalysis and Design of Iterated Block Ciphers, Ph. D. thesis, Katholieke Universiteit Leuven, Oct 1997. [Page 38]
[RIPE92] | Research and Development in Advanced Communication Technologies in Europe, RIPE Integrity Primitives: Final Report of RACE Integrity Primitives Evaluation (R1040), RACE, June 1992. [Page 58]
[Rit96] | T. Ritter, “The Fenced DES Cipher: Stronger than DES but Made from DES,” Ritter Software Engineering, 1996. [Page 46]
[Riv91] | R.L. Rivest, “The MD4 Message Digest Algorithm,” Advances in Cryptology — CRYPTO ’90 Proceedings, Springer-Verlag, 1991, pp. 303-311. [Pages 46, 58]
[Riv92] | R.L. Rivest, “The MD5 Message Digest Algorithm,” RFC 1321, Apr 1992. [Pages 46, 58]
[Riv95] | R.L. Rivest, “The RC5 Encryption Algorithm,” Fast Software Encryption, 2nd International Workshop Proceedings, Springer-Verlag, 1995, pp. 86-96. [Pages 5, 34, 121]
[Riv97] | R. Rivest, “A Description of the RC2(r) Encryption Algorithm,” Internet-Draft, work in progress, June 1997. [Pages 33, 46]
[RKR98] | B. Van Rompay, L.R. Knudsen, and V. Rijmen, “Differential Cryptanalysis of the ICE Encryption Algorithm,” Fast Software Encryption, 5th International Workshop Proceedings, Springer-Verlag, 1998, pp. 270-283. [Page 41]
[Ros98] | G. Rose, “A Stream Cipher Based on Linear Feedback over GF(28),” Third Australian Conference, ACISP ’98, Springer-Verlag, to appear. [Page 33]
[RP95a] | V. Rijmen and B. Preneel, “Cryptanalysis of MacGuffin,” Fast Software Encryption, Second International Workshop Proceedings, Springer-Verlag, 1995, pp. 353-358. [Page 5]
[RP95b] | V. Rijmen and B. Preneel, “On Weaknesses of Non-surjective Round Functions,” Proceedings of the Workshop on Selected Areas in Cryptography (SAC ’95), Ottawa, Canada, 1995, pp. 100-106. [Pages 40, 114]
[RPD97] | V. Rijman, B. Preneel, and E. DeWin, “On Weaknesses of Non-surjective Round Functions,” Designs, Codes, and Cryptography, v. 12, n. 3, 1997, pp. 253-266. [Pages 40, 114]
[RSA78] | R. Rivest, A. Shamir, and L. Adleman, “A Method for Obtaining Digital Signatures and Public-Key Cryptosystems,” Communications of the ACM, v. 21, n. 2, Feb 1978, pp. 120-126. [Page 116]
[SAM97] | T. Shimoyama, S. Amada, and S. Moriai, “Improved Fast Software Implementation of Block Ciphers,” Information and Communications Security, First International Conference, ICICS ’97 Proceedings, Springer-Verlag, 1997, pp. 203-207. [Page 34]
[Sch94] | B. Schneier, “Description of a New Variable-Length Key, 64-Bit Block Cipher (Blowfish),” Fast Software Encryption, Cambridge Security Workshop Proceedings, Springer-Verlag, 1994, pp. 191-204. [Pages 5, 34, 39]
[Sch96] | B. Schneier, Applied Cryptography, Second Edition, John Wiley & Sons, 1996. [Pages 23, 34, 119]
[Sch98] | B. Schneier, “The Twofish Encryption Algorithm,” Dr. Dobbs Journal, v . 23, n. 12, Dec 1998, pp. 30-38. [Page v]
[Sco85] | R. Scott, “Wide Open Encryption Design Offers Flexible Implementation,” Cryptologia, v. 9, n. 1, Jan 1985, pp. 75-90. [Page 38]
[Sel98] | A.A. Selcuk, “New Results in Linear Cryptanalysis of RC5,” Fast Software Encryption, 5th International Workshop Proceedings, Springer-Verlag, 1998, pp. 1-16.[Page 36]
[Seu60] | Dr. Seuss, One Fish, Two Fish, Red Fish, Blue Fish, Beginner Books, 1960. [Page 127]
[Sha49] | C. Shannon, “Communication Theory of Secrecy Systems,” Bell Systems Technical Journal, v. 28, n. 4, 1949,pp. 656-715. [Pages 43, 44]
[SK96] | B. Schneier and J. Kelsey, “Unbalanced Feistel Networks and Block Cipher Design,” Fast Software Encryption, 3rd International Workshop Proceedings, Springer-Verlag, 1996, pp. 121-144. [Pages 5, 36, 46, 47]
[SK98] | T. Shimoyama and T. Kaneko, “Quadratic Relation of S-box and Its Application to the Linear Attack of Full Round DES,” Advances in Cryptology — CRYPTO ’98 Proceedings, Springer-Verlag, 1998, pp. 200-211. [Pages 102, 116]
[SKW+98a] | B. Schneier, J. Kelsey, D. Whiting, D. Wagner, C. Hall, and N. Ferguson, “Twofish: A 128-Bit Block Cipher,” NIST AES Proposal, 15 June 1998. [Page v]
[SKW+98b] | B. Schneier, J. Kelsey, D. Whiting, D. Wagner, C. Hall, and N. Ferguson, “On the Twofish Key Schedule,” Proceedings of the 1998 SAC Conference, Springer-Verlag, 1998, to appear. [Page v]
[SKW+99a] | B. Schneier, J. Kelsey, D. Whiting, D. Wagner, C. Hall, and N. Ferguson, “Performance Comparison of the AES Submissions,” submitted to the 2nd AES Candidate Conference, 1999, to appear. [Pages v, 121]
[SKW+99b] | B. Schneier, J. Kelsey, D. Whiting, D. Wagner, C. Hall, and N. Ferguson, “Twofish on Smart Cards,” Proceedings of CARDIS 98, Springer-Verlag, to appear. [Pages v, 26]
[SM88] | A. Shimizu and S. Miyaguchi, “Fast Data Encipherment Algorithm FEAL,” Advances in Cryptology — EUROCRYPT ’87 Proceedings, Springer-Verlag, 1988, pp. 267-278, [Pages 5, 33, 36]
[SMK98] | T. Shimoyama, S. Moriai, and T. Kaneko, “Improving the Higher Order Differential Attack and Cryptanalysis of the KN Cipher,” Information Security. First International Workshop ISW ’97 Proceedings, Springer-Verlag, 1998, pp. 32-42. [Pages 35, 39]
[SV98] | J. Stern and S. Vaudenay, “CS-Cipher,” Fast Software Encryption, 5th International Workshop Proceedings, Springer-Verlag, 1998, pp. 189-205. [Pages 39, 41]
[SW97] | B. Schneier and D. Whiting, “Fast Software Encryption: Designing Encryption Algorithms for Optimal Speed on the Intel Pentium Processor,” Fast Software Encryption, 4th International Workshop Proceedings, Springer-Verlag, 1997, pp. 242-259. [Pages 33, 34, 121]
[UTK98] | M. Uemra, H. Tanaka, and T. Kanedo, “On the Weak Keys in SPEED Cipher by Higher Order Differential Attack,” 1998 Symposium on Cryptography and Information Security, 1.2.D. (In Japanese.) [Page 33]
[Vau95] | S. Vaudenay, “On the Need for Multipermutations: Cryptanalysis of MD4 and SAFER,” Fast Software Encryption, Second International Workshop Proceedings, Springer-Verlag, 1995, pp. 286-297. [Page 6]
[Vau96a] | S. Vaudenay, “On the Weak Keys in Blowfish,” Fast Software Encryption, 3rd International Workshop Proceedings, Springer-Verlag, 1996, pp. 27-32. [Pages 39, 114]
[Vau96b] | S. Vaudenay, “An Experiment on DES Statistical Cryptanalysis,” 3rd ACM Conference on Computer and Communications Security, ACM Press, 1996, pp. 139-147. [Page 102]
[Wag95a] | D. Wagner, “Cryptanalysis of S-1,” sci.crypt Usenet posting, 27 Aug 1995. [Pages 41, 104]
[Wag95b] | D. Wagner, personal communication, 1995. [Page 40]
[WH87] | R. Winternitz and M. Hellman, “Chosen-key Attacks on a Block Cipher,” Cryptologia, v. 11, n. 1, Jan 1987, pp. 16-20. [Page 35]
[Whe94] | D. Wheeler, “A Bulk Data Encryption Algorithm,” Fast Software Encryption, Cambridge Security Workshop Proceedings, Springer-Verlag, 1994, pp. 127-134. [Page 38]
[Wie94] | M.J. Wiener, “Efficient DES Key Search,” TR-244, School of Computer Science, Carleton University, May 1994. [Page 1]
[Win84] | R.S. Winternitz, “Producing One-Way Hash Functions from DES,” Advances in Cryptology: Proceedings of Crypto 83, Plenum Press, 1984, pp. 203-207. [Page 119]
[WN95] | D. Wheeler and R. Needham, “TEA, a Tiny Encryption Algorithm,” Fast Software Encryption, 2nd International Workshop Proceedings, Springer-Verlag, 1995, pp. 97-110. [Page 36]
[WS98] | D. Whiting and B. Schneier “Improved Twofish Implementations,” Twofish Technical Report #3, Counterpane Systems, to appear. [Page v]
[WSK97] | D. Wagner, B. Schneier, and J. Kelsey, “Cryptanalysis of the Cellular Message Encryption Algorithm,” Advances in Cryptology — CRYPTO ’97 Proceedings, Springer-Verlag, 1997, pp. 526-537. [Page 38]
[WW98] | D. Whiting and D. Wagner, “Empirical Verification of Twofish Key Uniqueness Properties,” Twofish Technical Report #2, Counterpane Systems, 22 Sep 1998. [Page v]
[YLCY98] | X. Yi, K.Y. Lam, S.X. Cheng, and X.H. You, “A New Byte-Oriented Block Cipher,” Information Security. First International Workshop ISW ’97 Proceedings, Springer-Verlag, 1998, 209-220. [Page 39]
[YMT97] | A.M. Youssef, S. Mister, and S.E. Tavares, “On the Design of Linear Transformations for Substitution Permutation Encryption Networks,” Workshop on Selected Areas in Cryptography (SAC ’97) Workshop Record, School of Computer Science, Carleton University, 1997, pp. 40-48. [Page 7]
[YTH96] | A.M. Youssef, S.E. Tavares, and H.M. Heys, “A New Class of Substitution-Permutation Networks,” Workshop on Selected Areas in Cryptography (SAC ’96) Workshop Record, Queens University, 1996, pp. 132-147. [Pages 5, 37]
[Yuv97] | G. Yuval, “Reinventing the Travois: Encryption/MAC in 30 ROM Bytes,” Fast Software Encryption, 4th International Workshop Proceedings, Springer-Verlag, 1997, pp. 205-209. [Page 104]
[ZG97] | F. Zhu and B.-A. Guo, “A Block-Ciphering Algorithm Based on Addition-Multiplication Structure in GF(2n),” Workshop on Selected Areas in Cryptography (SAC ’97) Workshop Record, School of Computer Science,Carleton University, 1997, pp. 145-159. [Page 33]
[Zhe97] | Y. Zheng, “The SPEED Cipher,” Financial Cryptography ’97 Proceedings, Springer-Verlag, 1997, pp. 71-89. [Pages 33, 121]
[ZMI90] | Y. Zheng, T. Matsumoto, and H. Imai, “On the Construction of Block Ciphers Provably Secure and Not Relying on Any Unproved Hypotheses,” Advances in Cryptology — CRYPTO ’89 Proceedings, Springer-Verlag, 1990, pp. 461-480. [Pages 5, 36]
[ZPS93] | Y. Zheng, J. Pieprzyk, and J. Seberry, “HAVAL — A One-Way Hashing Algorithm with Variable Length of Output,” Advances in Cryptology — AUSCRYPT ’92 Proceedings, Springer-Verlag, 1993, pp. 83-104. [Page 58]


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Overview of Symbols

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

A. Overview of Symbols

This appendix gives an overview of the symbols used in the definition of Twofish. For data elements, lowercase symbols usually refer to byte values and uppercase symbols usually refer to 32-bit word values.

A | The list of Ai words used in the key schedule. [Page 67]
A0, . . . , A19 | Intermediate values in the key schedule. [Page 16]
a0, . . . , a4 | Intermediate 4-bit values used in the definition of the q mappings. [Page 16]
B | The list of Bi words used in the key schedule. [Page 67]
B0, . . . , B19 | Intermediate values in the key schedule. [Page 16]
b0, . . . , b4 | Intermediate 4-bit values used in the definition of the q mappings. [Page 16]
C0, . . . , C3 | The four 32-bit words of the ciphertext. [Page 11]
c0, . . . , c15 | The bytes of the ciphertext. [Page 11]
DPmax(f) | The probability of the best differential characteristic of f. [Page 48]
F (X, Y, r) | The Feistel round function. This function takes the round number r and two data words X and Y as input. It produces two words of output. The round number is used to select the correct words from the expanded key. Note that the definition of F depends on the key. [Page 11]
F’(X, Y) | This is the F function without the final addition of two key words. It is thus independent of the round number, but still depends on the key. [Page 11]
Fr,0, Fr,1 | The two output words from the F function in round r. [Page 11]
g(X) | This function maps a 32-bit word to a 32-bit word. It consists of four S-boxes, and the MDS matrix. It is defined as g(X) → h(X, S). Note that S depends on the key, so this function depends also on the key. [Page 11]
h(X, L) | A function that maps the 32-bit word X to a 32-bit result under control of a list of words L that is derived from the key. This function is used both in the key schedule, and in the round function. [Page 14]
K0, . . . , K39 | The expanded key, consisting of 40 words of 32 bits each. The words K0, . . . , K3 are used for the pre-whitening, K4, . . . , K7 for the post-whitening, and K8, . . . , K39 for the 16 rounds. [Page 16]
k | The length of the key divided by 64. [Page 12]
L | The list of key-derived words used in h. [Page 14]
L0, . . . , Lk-1 | The k words of L. [Page 14]
li, 0, . . . , li, 3 | The four bytes of Li. [Page 15]
LPmax(f) | The significance-probability of the best linear characteristic of f. [Page 48]
M0, . . . , M2k-1 | The 2k 32-bit words of the key. [Page 12]
Me, Mo | Two lists of 32-bit words. The first one consists of the even key words and the second one of the odd key words. [Page 13]
m0, . . . , m 8k-1 | The 8k bytes of the key. [Page 12]
N | The length of the key, in bits. [Page 12]
P0, . . . , P3 | The four 32-bit words of the plaintext. [Page 9]
p0, . . . , p15 | The bytes of the plaintext. [Page 9]
q0, q1 | Two distinct fixed bijective functions that map byte values into byte values. [Page 16]
Rr,0, . . . , Rr,3 | The 32-bit words of the data just before round r. The rounds are numbered 0, . . . , 15. For r = 0 these words are the data just before the first round (but after the whitening). For r = 16 they are the data just after the last round (but before the whitening). [Page 9]
r | The round number. The rounds are numbered 0 to 15 when encrypting. [Page 11]
ROL(X, n) | A function that rotates a 32-bit value X left by n bits. [Page 11]
ROR(X, n) | A function that rotates a 32-bit value X right by n bits. [Page 11]
S | A list of k 32-bit words that is derived from the key using the RS matrix. [Page 13]
S0, . . . , Sk-1 | The words that make up S. Note that these are put in reverse order to create S. [Page 13]
s0, . . . , s3 | The key-dependent S-boxes. Each S-box consists of a sequence of table lookups in a q-table, and XORs with key bytes. [Page 16]
si,0, . . ., si,3 | The four bytes of Si. [Page 13]
T0,T1 | Two intermediate values used in the computation of F. These are the results of the two g functions, just before the PHT. [Page 11]
t0, . . . , t3 | Four permutations on 4-bit values. One set of four t permutations is used to define q0, a second set is used to define q1. [Page 17]
v | The polynomial used to define GF(28) for the MDS matrix multiply. [Page 12]
w | The polynomial used to define GF(28) for the RS matrix multiply. [Page 13]
x | The input to one of the q mappings. [Page 16]
x0, . . . , x3 | The four input bytes to g or h. [Page 12]
y | The output of one of the q mappings. [Page 16]
y0, . . . , y3 | Four intermediate bytes in g or h [Page 12].
yi,j | The intermediate values used in the computation of yi from xi. [Page 15]
z0, . . . , z3 | The four output bytes from g or h. [Page 15]
Z | The 32-bit output word from g or h. [Page 12]
ρ | A constant used for notational convenience. [Page 16]


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Twofish Test Vectors

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

B. Twofish Test Vectors

B.1 Intermediate Values

The following file shows the intermediate values of three Twofish computations. This particular implementation does not swap the halves but instead applies the F function alternately between the two halves.

FILENAME: “ecb_ival.txt”

Electronic Codebook (ECB) Mode
Intermediate Value Tests

Algorithm Name:      TWOFISH
Principal Submitter: Bruce Schneier, Counterpane Systems

=========

KEYSIZE=128

KEY=0000000000000000000000000000000

;
;makeKey:   Input key            -->  S-box key   [Encrypt]
;             00000000 00000000  -->  00000000
;             00000000 00000000  -->  00000000
;           Subkeys
;             52C54DDE 11F0626D  Input whiten
;             7CAC9D4A 4D1B4AAA
;             B7B83A10 1E7D0BEB  Output whiten
;             EE9C341F CFE14BE4
;             F98FFEF9 9C5B3C17  Round subkeys
;             15A48310 342A4D81
;             424D89FE C14724A7
;             311B834C FDE87320
;             3302778F 26CD67B4
;             7A6C6362 C2BAF60E
;             3411B994 D972C87F
;             84ADB1EA A7DEE434
;             54D2960F A2F7CAA8
;             A6B8FF8C 8014C425
;             6A748D1C EDBAF720
;             928EF78C 0338EE13
;             9949D6BE C8314176
;             07C07D68 ECAE7EA7
;             1FE71844 85C05C89
;             F298311E 696EA672
PT=00000000000000000000000000000000

Encrypt()

R[-1] :x= 00000000 00000000 00000000 00000000.
R[ 0] :x= 52C54DDE 11F0626D 7CAC9D4A 4D1B4AAA.
R[ 1] :x= 52C54DDE 11F0626D C38DCAA4 7A0A91B6. t0=C06D4949 t1=41B9BFC1
R[ 2] :x= 55A538DE 5C5A4DB6 C38DCAA4 7A0A91B6. t0=7C4536B9 t1=67A58299
R[ 3] :x= 55A538DE 5C5A4DB6 899063BD 893E49A9. t0=60DAC1A4 t1=2D84C23D
R[ 4] :x= 2AE61A96 84BC42D3 899063BD 893E49A9. t0=607AAEAD t1=6ED2DBF9
R[ 5] :x= 2AE61A96 84BC42D3 F14F2618 821B5F36. t0=067D0B49 t1=318EACB4
R[ 6] :x= 0FFE0AD1 D6B87B70 F14F2618 821B5F36. t0=58554EDB t1=62585CF7
R[ 7] :x= 0FFE0AD1 D6B87B70 CD0D38A1 C069BD9B. t0=839B0017 t1=B3A89DB0
R[ 8] :x= A85CE579 DE2661CE CD0D38A1 C069BD9B. t0=E9BC6975 t1=F0DDA4C3
R[ 9] :x= A85CE579 DE2661CE 7A39754C 973ABD2A. t0=54687CDF t1=9044BF4B
R[10] :x= 013077D7 B3528BA1 7A39754C 973ABD2A. t0=77FC927F t1=8B8678CC
R[11] :x= 013077D7 B3528BA1 D57933FD F8EA8B1B. t0=E3C81108 t1=828E7493
R[12] :x= 64F0EAA1 DA27090C D57933FD F8EA8B1B. t0=B33C25D6 t1=83068533
R[13] :x= 64F0EAA1 DA27090C F64F1005 99149A52. t0=A0AA2F81 t1=FFF30DB7
R[14] :x= B0681C46 606D0273 F64F1005 99149A52. t0=114C17C5 t1=EB143CFF
R[15] :x= B0681C46 606D0273 EB27628F 2C51191D. t0=677DA87D t1=989D1459
R[16] :x= C1708BA9 9522A3CE EB27628F 2C51191D. t0=9357B338 t1=AC9926BF
R[17] :x= 5C9F589F 322C12F6 2FECBFB6 5AC3E82A.

CT=9F589F5CF6122C32B6BFEC2F2AE8C35A

Decrypt ()

CT=9F589F5CF6122C32B6BFEC2F2AE8C35A

R[17] :x= 5C9F589F 322C12F6 2FECBFB6 5AC3E82A.
R[16] :x= C1708BA9 9522A3CE EB27628F 2C51191D. t0=9357B338 t1=AC9926BF
R[15] :x= B0681C46 606D0273 EB27628F 2C51191D. t0=677DA87D t1=989D1459
R[14] :x= B0681C46 606D0273 F64F1005 99149A52. t0=114C17C5 t1=EB143CFF
R[13] :x= 64F0EAA1 DA27090C F64F1005 99149A52. t0=A0AA2F81 t1=FFF30DB7
R[12] :x= 64F0EAA1 DA27090C D57933FD F8EA8B1B. t0=B33C25D6 t1=83068533
R[11] :x= 013077D7 B3528BA1 D57933FD F8EA8B1B. t0=E3C81108 t1=828E7493
R[10] :x= 013077D7 B3528BA1 7A39754C 973ABD2A. t0=77FC927F t1=8B8678CC
R[ 9] :x= A85CE579 DE2661CE 7A39754C 973ABD2A. t0=54687CDF t1=9044BF4B
R[ 8] :x= A85CE579 DE2661CE CD0D38A1 C069BD9B. t0=E9BC6975 t1=F0DDA4C3
R[ 7] :x= 0FFE0AD1 D6B87B70 CD0D38A1 C069BD9B. t0=839B0017 t1=B3A89DB0
R[ 6] :x= 0FFE0AD1 D6B87B70 F14F2618 821B5F36. t0=58554EDB t1=62585CF7
R[ 5] :x= 2AE61A96 84BC42D3 F14F2618 821B5F36. t0=067D0B49 t1=318EACB4
R[ 4] :x= 2AE61A96 84BC42D3 899063BD 893E49A9. t0=607AAEAD t1=6ED2DBF9
R[ 3] :x= 55A538DE 5C5A4DB6 899063BD 893E49A9. t0=60DAC1A4 t1=2D84C23D
R[ 2] :x= 55A538DE 5C5A4DB6 C38DCAA4 7A0A91B6. t0=7C4536B9 t1=67A58299
R[ 1] :x= 52C54DDE 11F0626D C38DCAA4 7A0A91B6. t0=C06D4949 t1=41B9BFC1
R[ 0] :x= 52C54DDE 11F0626D 7CAC9D4A 4D1B4AAA.
R[-1] :x= 00000000 00000000 00000000 00000000.

PT=00000000000000000000000000000000

========

KEYSIZE=192

KEY=0123456789ABCDEFFEDCBA98765432100011223344556677

;
;makeKey:   Input key            -->   S-box key [Encrypt]
;           EFCDAB89 67452301    -->   B89FF6F2
;           10325476 98BADCFE    -->   B255BC4B
;           77665544 33221100    -->   45661061
;         Subkeys
;           38394A24 C36D1175 Input whiten
;           E802528F 219BFEB4
;           B9141AB4 BD3E70CD Output whiten
;           AF609383 FD36908A
;           03EFB931 1D2EE7EC Round subkeys
;           A7489D55 6E44B6E8
;           714AD667 653AD51F
;           B6315B66 B27C05AF
;           A06C8140 9853D419
;           4016E346 8D1C0DD4
;           F05480BE B6AF816F
;           2D7DC789 45B7BD3A
;           57F8A163 2BEFDA69
;           26AE7271 C2900D79
;           ED323794 3D3FFD80
;           5DE68E49 9C3D2478
;           DF326FE3 5911F70D
;           C229F13B B1364772
;           4235364D 0CEC363A
;           57C8DD1F 6A1AD61E
;
PT=00000000000000000000000000000000

Encrypt ()

R[-1] :x= 00000000 00000000 00000000 00000000.
R[ 0] :x= 38394A24 C36D1175 E802528F 219BFEB4.
R[ 1] :x= 38394A24 C36D1175 9C263D67 5E68BE8F. t0=988C8223 t1=33D1ECEC
R[ 2] :x= C8F5099F 0C4B8F53 9C263D67 5E68BE8F. t0=E8C880BC t1=19C23B0A
R[ 3] :x= C8F5099F 0C4B8F53 69948F5E E67C030F. t0=C615F1F6 t1=17AE5B7E
R[ 4] :x= 07633866 59421079 69948F5E E67C030F. t0=90AB32AA t1=7F56EB43
R[ 5] :x= 07633866 59421079 C015BE79 149B9CEC. t0=52971E00 t1=F6BC546D
R[ 6] :x= A042B99D 709EF54B C015BE79 149B9CEC. t0=DAA00849 t1=2D2F5FCE
R[ 7] :x= A042B99D 709EF54B 0CD39FA6 B250BEDA. t0=EE03FB5B t1=FB5A051C
R[ 8] :x= F7B097FA 9E5C4FF7 0CD39FA6 B250BEDA. t0=09A1B597 t1=18041948
R[ 9] :x= F7B097FA 9E5C4FF7 77FC8B29 CC2B3F88. t0=99C9694E t1=F1687F43
R[10] :x= A279C718 421A8D38 77FC8B29 CC2B3F88. t0=5D174956 t1=2F7D5E04
R[11] :x= A279C718 421A8D38 5B1A0904 12FEBF99. t0=5BC40012 t1=78D2617B
R[12] :x= E4409C22 702548A2 5B1A0904 12FEBF99. t0=C251B3CE t1=4AC0BD46
R[13] :x= E4409C22 702548A2 5DDAA2A1 EFB2F051. t0=91BC2070 t1=6FC0BBF3
R[14] :x= 8561A604 825D2480 5DDAA2A1 EFB2F051. t0=A7D24F8E t1=84878F62
R[15] :x= 8561A604 825D2480 5CC6CB7B 62A2CE64. t0=93690387 t1=0EB8FA83
R[16] :x= 17738CD3 B5142D18 5CC6CB7B 62A2CE64. t0=5FE8370B t1=F3D5AB78
R[17]: x= E5D2D1CF DF9CBEA9 B8131F50 4822BD92.

CT=CFD1D2E5A9BE9CDF501F13B892BD2248

Decrypt ()

CT=CFD1D2E5A9BE9CDF501F13B892BD2248

R[17] :x= E5D2D1CF DF9CBEA9 B8131F50 4822BD92.
R[16] :x= 17738CD3 B5142D18 5CC6CB7B 62A2CE64. t0=5FE8370B t1=F3D5AB78
R[15] :x= 8561A604 825D2480 5CC6CB7B 62A2CE64. t0=93690387 t1=0EB8FA83
R[14] :x= 8561A604 825D2480 5DDAA2A1 EFB2F051. t0=A7D24F8E t1=84878F62
R[13] :x= E4409C22 702548A2 5DDAA2A1 EFB2F051. t0=91BC2070 t1=6FC0BBF3
R[12] :x= E4409C22 702548A2 5B1A0904 12FEBF99. t0=C251B3CE t1=4AC0BD46
R[11] :x= A279C718 421A8D38 5B1A0904 12FEBF99. t0=5BC40012 t1=78D2617B
R[10] :x= A279C718 421A8D38 77FC8B29 CC2B3F88. t0=5D174956 t1=2F7D5E04
R[ 9] :x= F7B097FA 9E5C4FF7 77FC8B29 CC2B3F88. t0=99C9694E t1=F1687F43
R[ 8] :x= F7B097FA 9E5C4FF7 0CD39FA6 B250BEDA. t0=09A1B597 t1=18041948
R[ 7] :x= A042B99D 709EF54B 0CD39FA6 B250BEDA. t0=EE03FB5B t1=FB5A051C
R[ 6] :x= A042B99D 709EF54B C015BE79 149B9CEC. t0=DAA00849 t1=2D2F5FCE
R[ 5] :x= 07633866 59421079 C015BE79 149B9CEC. t0=52971E00 t1=F6BC546D
R[ 4] :x= 07633866 59421079 69948F5E E67C030F. t0=90AB32AA t1=7F56EB43
R[ 3] :x= C8F5099F 0C4B8F53 69948F5E E67C030F. t0=C615F1F6 t1=17AE5B7E
R[ 2] :x= C8F5099F 0C4B8F53 9C263D67 5E68BE8F. t0=E8C880BC t1=19C23B0A
R[ 1] :x= 38394A24 C36D1175 9C263D67 5E68BE8F. t0=988C8223 t1=33D1ECEC
R[ 0] :x= 38394A24 C36D1175 E802528F 219BFEB4.
R[-1] :x= 00000000 00000000 00000000 00000000.

PT=00000000000000000000000000000000

========

KEYSIZE=256

KEY=0123456789ABCDEFFEDCBA987654321000112233445566778899AABBCCDDEEFF

;
;makeKey:  Input key             -->  S-box key [Encrypt]
;            EFCDAB89 67452301   -->  B89FF6F2
;            10325476 98BADCFE   -->  B255BC4B
;            77665544 33221100   -->  45661061
;            FFEEDDCC BBAA9988   -->  8E4447F7
;          Subkeys
;            5EC769BF 44D13C60 Input whiten
;            76CD39B1 16750474
;            349C294B EC21F6D6 Output whiten
;            4FBD10B4 578DA0ED
;            C3479695 9B6958FB Round subkeys
;            6A7FBC4E 0BF1830B
;            61B5E0FB D78D9730
;            7C6CF0C4 2F9109C8
;            E69EA8D1 ED99BDFF
;            35DC0BBD A03E5018
;            FB18EA0B 38BD43D3
;            76191781 37A9A0D3
;            72427BEA 911CC0B8
;            F1689449 71009CA9
;            B6363E89 494D9855
;            590BBC63 F95A28B5
;            FB72B4E1 2A43505C
;            BFD34176 5C133D12
;            3A9247F7 9A3331DD
;            EE7515E6 F0D54DCD
;
PT=00000000000000000000000000000000

Encrypt ()

R[-1] :x= 00000000 00000000 00000000 00000000.
R[ 0] :x= 5EC769BF 44D13C60 76CD39B1 16750474.
R[ 1] :x= 5EC769BF 44D13C60 D38B6C9F A23B7169. t0=29C0736C t1=E4D3D68D
R[ 2] :x= 99424DFF FBC14BFC D38B6C9F A23B7169. t0=9D16BBB3 t1=64AD7A3F
R[ 3] :x= 99424DFF FBC14BFC 698BE047 6A997290. t0=E66B9D19 t1=B87B2DFD
R[ 4] :x= 2C125DD7 5A526278 698BE047 6A997290. t0=0BB41F61 t1=3945E62C
R[ 5] :x= 2C125DD7 5A526278 E35CD910 7CB57D06. t0=D5397903 t1=F35A3092
R[ 6] :x= D5178F25 00D35CC5 E35CD910 7CB57D06. t0=8C8927A1 t1=C3D8103E
R[ 7] :x= D5178F25 00D35CC5 D8447F91 65C2BD96. t0=4D8B7489 t1=0B2FC79F
R[ 8] :x= FF92E109 DF621C97 D8447F91 65C2BD96. t0=C1176720 t1=F301CE95
R[ 9] :x= FF92E109 DF621C97 28BFEFF5 D45666FB. t0=9F3BEC03 t1=77BD388E
R[10] :x= BB79AD2E AA410F41 28BFEFF5 D45666FB. t0=8C6DB451 t1=0B8B72BA
R[11] :x= BB79AD2E AA410F41 6576A3ED BFF8215E. t0=8A317EF8 t1=A1EAEAAE
R[12] :x= 4A6BBAFF 439F4766 6576A3ED BFF8215E. t0=8F8307AA t1=472014C3
R[13] :x= 4A6BBAFF 439F4766 F7186836 04CA5304. t0=CEB0BBE1 t1=C12302BE
R[14] :x= CBD3C29D BC31FEBE F7186836 04CA5304. t0=5CF5C93C t1=C1033512
R[15] :x= CBD3C29D BC31FEBE D4E77B7C 5415D5D3. t0=853A6BB2 t1=9F09EB26
R[16] :x= 85411C2B 7777DC05 D4E77B7C 5415D5D3. t0=877AF61D t1=4B61EEC7
R[17] :x= E07B5237 B8342305 CAFC0C9F 20FA7CE8.

CT=37527BE0052334B89F0CFCCAE87CFA20

Decrypt()

CT=37527BE0052334B89F0CFCCAE87CFA20

R[17] :x= E07B5237 B8342305 CAFC0C9F 20FA7CE8.
R[16] :x= 85411C2B 7777DC05 D4E77B7C 5415D5D3. t0=877AF61D t1=4B61EEC7
R[15] :x= CBD3C29D BC31FEBE D4E77B7C 5415D5D3. t0=853A6BB2 t1=9F09EB26
R[14] :x= CBD3C29D BC31FEBE F7186836 04CA5304. t0=5CF5C93C t1=C1033512
R[13] :x= 4A6BBAFF 439F4766 F7186836 04CA5304. t0=CEB0BBE1 t1=C12302BE
R[12] :x= 4A6BBAFF 439F4766 6576A3ED BFF8215E. t0=8F8307AA t1=472014C3
R[11] :x= BB79AD2E AA410F41 6576A3ED BFF8215E. t0=8A317EF8 t1=A1EAEAAE
R[10] :x= BB79AD2E AA410F41 28BFEFF5 D45666FB. t0=8C6DB451 t1=0B8B72BA
R[ 9] :x= FF92E109 DF621C97 28BFEFF5 D45666FB. t0=9F3BEC03 t1=77BD388E
R[ 8] :x= FF92E109 DF621C97 D8447F91 65C2BD96. t0=C1176720 t1=F301CE95
R[ 7] :x= D5178F25 00D35CC5 D8447F91 65C2BD96. t0=4D8B7489 t1=0B2FC79F
R[ 6] :x= D5178F25 00D35CC5 E35CD910 7CB57D06. t0=8C8927A1 t1=C3D8103E
R[ 5] :x= 2C125DD7 5A526278 E35CD910 7CB57D06. t0=D5397903 t1=F35A3092
R[ 4] :x= 2C125DD7 5A526278 698BE047 6A997290. t0=0BB41F61 t1=3945E62C
R[ 3] :x= 99424DFF FBC14BFC 698BE047 6A997290. t0=E66B9D19 t1=B87B2DFD
R[ 2] :x= 99424DFF FBC14BFC D38B6C9F A23B7169. t0=9D16BBB3 t1=64AD7A3F
R[ 1] :x= 5EC769BF 44D13C60 D38B6C9F A23B7169. t0=29C0736C t1=E4D3D68D
R[ 0] :x= 5EC769BF 44D13C60 76CD39B1 16750474.
R[-1] :x= 00000000 00000000 00000000 00000000.

PT=00000000000000000000000000000000

B.2 Full Encryptions

The following file shows a number of (plaintext, ciphertext, key) pairs. These pairs are related, and can easily be tested automatically. The plaintext of each entry is the ciphertext of the previous one. The key of each entry is made up of the ciphertext two and three entries back. We believe that these test vectors provide a thorough test of a Twofish implementation.

FILENAME: “ecb_tbl.txt”

Electronic Codebook (ECB) Mode
Tables Known Answer Test
Tests permutation tables and MDS matrix multiply tables.

Algorithm Name: TWOFISH
Principal Submitter: Bruce Schneier, Counterpane Systems

========

KEYSIZE=128

I=1
KEY=00000000000000000000000000000000
PT=00000000000000000000000000000000
CT=9F589F5CF6122C32B6BFEC2F2AE8C35A

I=2
KEY=00000000000000000000000000000000
PT=9F589F5CF6122C32B6BFEC2F2AE8C35A
CT=D491DB16E7B1C39E86CB086B789F5419

I=3
KEY=9F589F5CF6122C32B6BFEC2F2AE8C35A
PT=D491DB16E7B1C39E86CB086B789F5419
CT=019F9809DE1711858FAAC3A3BA20FBC3

I=4
KEY=D491DB16E7B1C39E86CB086B789F5419
PT=019F9809DE1711858FAAC3A3BA20FBC3
CT=6363977DE839486297E661C6C9D668EB

I=5
KEY=019F9809DE1711858FAAC3A3BA20FBC3
PT=6363977DE839486297E661C6C9D668EB
CT=816D5BD0FAE35342BF2A7412C246F752

I=6
KEY=6363977DE839486297E661C6C9D668EB
PT=816D5BD0FAE35342BF2A7412C246F752
CT=5449ECA008FF5921155F598AF4CED4D0

I=7
KEY=816D5BD0FAE35342BF2A7412C246F752
PT=5449ECA008FF5921155F598AF4CED4D0
CT=6600522E97AEB3094ED5F92AFCBCDD10

I=8
KEY=5449ECA008FF5921155F598AF4CED4D0
PT=6600522E97AEB3094ED5F92AFCBCDD10
CT=34C8A5FB2D3D08A170D120AC6D26DBFA

I=9
KEY=6600522E97AEB3094ED5F92AFCBCDD10
PT=34C8A5FB2D3D08A170D120AC6D26DBFA
CT=28530B358C1B42EF277DE6D4407FC591

I=10
KEY=34C8A5FB2D3D08A170D120AC6D26DBFA
PT=28530B358C1B42EF277DE6D4407FC591
CT=8A8AB983310ED78C8C0ECDE030B8DCA4

   :
   :
   :

I=48
KEY=137A24CA47CD12BE818DF4D2F4355960
PT=BCA724A54533C6987E14AA827952F921
CT=6B459286F3FFD28D49F15B1581B08E42

I=49
KEY=BCA724A54533C6987E14AA827952F921
PT=6B459286F3FFD28D49F15B1581B08E42
CT=5D9D4EEFFA9151575524F115815A12E0

========

KEYSIZE=192

I=1
KEY=000000000000000000000000000000000000000000000000
PT=00000000000000000000000000000000
CT=EFA71F788965BD4453F860178FC19101

I=2
KEY=000000000000000000000000000000000000000000000000
PT=EFA71F788965BD4453F860178FC19101
CT=88B2B2706B105E36B446BB6D731A1E88

I=3
KEY=EFA71F788965BD4453F860178FC191010000000000000000
PT=88B2B2706B105E36B446BB6D731A1E88
CT=39DA69D6BA4997D585B6DC073CA341B2

I=4
KEY=88B2B2706B105E36B446BB6D731A1E88EFA71F788965BD44
PT=39DA69D6BA4997D585B6DC073CA341B2
CT=182B02D81497EA45F9DAACDC29193A65

I=5
KEY=39DA69D6BA4997D585B6DC073CA341B288B2B2706B105E36
PT=182B02D81497EA45F9DAACDC29193A65
CT=7AFF7A70CA2FF28AC31DD8AE5DAAAB63

I=6
KEY=182B02D81497EA45F9DAACDC29193A6539DA69D6BA4997D5
PT=7AFF7A70CA2FF28AC31DD8AE5DAAAB63
CT=D1079B789F666649B6BD7D1629F1F77E

I=7
KEY=7AFF7A70CA2FF28AC31DD8AE5DAAAB63182B02D81497EA45
PT=D1079B789F666649B6BD7D1629F1F77E
CT=3AF6F7CE5BD35EF18BEC6FA787AB506B

I=8
KEY=D1079B789F666649B6BD7D1629F1F77E7AFF7A70CA2FF28A
PT=3AF6F7CE5BD35EF18BEC6FA787AB506B
CT=AE8109BFDA85C1F2C5038B34ED691BFF

I=9
KEY=3AF6F7CE5BD35EF18BEC6FA787AB506BD1079B789F666649
PT=AE8109BFDA85C1F2C5038B34ED691BFF
CT=893FD67B98C550073571BD631263FC78

I=10
KEY=AE8109BFDA85C1F2C5038B34ED691BFF3AF6F7CE5BD35EF1
PT=893FD67B98C550073571BD631263FC78
CT=16434FC9C8841A63D58700B5578E8F67

   :
   :
   :

I=48
KEY=DEA4F3DA75EC7A8EAC3861A9912402CD5DBE44032769DF54
PT=FB66522C332FCC4C042ABE32FA9E902F
CT=F0AB73301125FA21EF70BE5385FB76B6

I=49
KEY=FB66522C332FCC4C042ABE32FA9E902FDEA4F3DA75EC7A8E
PT=F0AB73301125FA21EF70BE5385FB76B6
CT=E75449212BEEF9F4A390BD860A640941

========

KEYSIZE=256

I=1
KEY=0000000000000000000000000000000000000000000000000000000000000000
PT=00000000000000000000000000000000
CT=57FF739D4DC92C1BD7FC01700CC8216F

I=2
KEY=0000000000000000000000000000000000000000000000000000000000000000
PT=57FF739D4DC92C1BD7FC01700CC8216F
CT=D43BB7556EA32E46F2A282B7D45B4E0D

I=3
KEY=57FF739D4DC92C1BD7FC01700CC8216F00000000000000000000000000000000
PT=D43BB7556EA32E46F2A282B7D45B4E0D
CT=90AFE91BB288544F2C32DC239B2635E6

I=4
KEY=D43BB7556EA32E46F2A282B7D45B4E0D57FF739D4DC92C1BD7FC01700CC8216F
PT=90AFE91BB288544F2C32DC239B2635E6
CT=6CB4561C40BF0A9705931CB6D408E7FA

I=5
KEY=90AFE91BB288544F2C32DC239B2635E6D43BB7556EA32E46F2A282B7D45B4E0D
PT=6CB4561C40BF0A9705931CB6D408E7FA
CT=3059D6D61753B958D92F4781C8640E58

I=6
KEY=6CB4561C40BF0A9705931CB6D408E7FA90AFE91BB288544F2C32DC239B2635E6
PT=3059D6D61753B958D92F4781C8640E58
CT=E69465770505D7F80EF68CA38AB3A3D6

I=7
KEY=3059D6D61753B958D92F4781C8640E586CB4561C40BF0A9705931CB6D408E7FA
PT=E69465770505D7F80EF68CA38AB3A3D6
CT=5AB67A5F8539A4A5FD9F0373BA463466

I=8
KEY=E69465770505D7F80EF68CA38AB3A3D63059D6D61753B958D92F4781C8640E58
PT=5AB67A5F8539A4A5FD9F0373BA463466
CT=DC096BCD99FC72F79936D4C748E75AF7

I=9
KEY=5AB67A5F8539A4A5FD9F0373BA463466E69465770505D7F80EF68CA38AB3A3D6
PT=DC096BCD99FC72F79936D4C748E75AF7
CT=C5A3E7CEE0F1B7260528A68FB4EA05F2

I=10
KEY=DC096BCD99FC72F79936D4C748E75AF75AB67A5F8539A4A5FD9F0373BA463466
PT=C5A3E7CEE0F1B7260528A68FB4EA05F2
CT=43D5CEC327B24AB90AD34A79D0469151

   :
   :
   :

I=48
KEY=2E2158BC3E5FC714C1EEECA0EA696D48D2DED73E59319A8138E0331F0EA149EA
PT=248A7F3528B168ACFDD1386E3F51E30C
CT=431058F4DBC7F734DA4F02F04CC4F459

I=49
KEY=248A7F3528B168ACFDD1386E3F51E30C2E2158BC3E5FC714C1EEECA0EA696D48
PT=431058F4DBC7F734DA4F02F04CC4F459
CT=37FE26FF1CF66175F5DDF4C33B97A205


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Code

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

C. Code

Twofish source code is available on the Twofish web site:

http://www.counterpane.com/twofish.html

The web site also contains the following downloadable Twofish implementations:

• Reference C implementation.
• Optimized C for the Intel Pentium, Pentium Pro, and Pentium II.
• Assembly code for the Intel Pentium, Pentium Pro, and Pentium II.
• 6805 assembly code.

C.1 C Code

This section contains C source code that implements Twofish. This is the code that the authors used during the development of Twofish.

/********************************************************************
PLATFORM.H — Platform-specific defines for TWOFISH code

Submitters:
  Bruce Schneier, Counterpane Systems
  Doug Whiting, Hi/fn
  John Kelsey, Counterpane Systems
  Chris Hall, Counterpane Systems
  David Wagner, UC Berkeley
  Niels Ferguson, Counterpane Systems

Code Author:        Doug Whiting,    Hi/fn

Version 1.00        April 1998

Copyright 1998, Hi/fn and Counterpane Systems. All rights reserved.

Notes:
  *   Tab size is set to 4 characters in this file

********************************************************************/

/* use intrinsic rotate if possible */
#define ROL (x,n) (((x) << ((n) & 0x1F)) | ((x) >> (32-((n) & 0x1F))))
#define ROR (x,n) (((x) >> ((n) & 0x1F)) | ((x) << (32-((n) & 0x1F))))

#if (0) && defined (__BORLANDC__) && (__BORLANDC__ >= 0x462)
#error “!!! This does not work for some reason!!!”
#include     <stdlib.h>      /* get prototype _lrotl (), _lrotr () */
#pragma inline __lrotl__
#pragma inline __lrotr__
#undef ROL                   /* get rid of inefficient definitions */
#undef ROR
#define ROL (x,n) __lrotl__(x,n)      /* use intrinsic rotations */
#define ROR (x,n) __lrotr__(x,n)
#endif

#ifdef _MSC_VER
#include    <stdlib.h>       /* get prototypes rotation functions */
#undef ROL
#undef ROR
#pragma intrinsic (_lrotl, _lrotr)   /* use intrinsic rotations */
#define ROL (x,n)    _lrotl (x,n)
#define ROR (x,n)    _lrotr (x,n)
#endif

#ifndef _M_IX86
#ifdef __BORLANDC__
#define _M_IX86          300     /* ensure defined for Intel CPUs */
#endif
#endif

#ifdef _M_IX86
#define     LittleEndian     1   /* e.g., 1 for Pentium, 0 for 68K */
#define     ALIGN32          0   /* need dword alignment? */
#else   /* non-Intel platforms  */
#define     LittleEndian     0   /* (assume big endian) */
#define     ALIGN32          1 /* (assume alignment needed) */
#endif

#if LittleEndian
#define     Bswap (x)        (x) /* NOP for little-endian machines */
#define     ADDR_XOR         0   /* NOP for little-endian machines */
#else
#define   Bswap (x) ((ROR (x,8) & 0xFF00FF00) | (ROL (x,8) & 0x00FF00FF))
#define     ADDR_XOR         3   /* convert byte address in dword */
#endif

/* Macros for extracting bytes from dwords (correct for endianness) */
#define _b(x,N) (((BYTE *) &x) [((N) & 3) ^ ADDR_XOR])

#define     b0(x)        _b(x,0)          /* extract LSB of DWORD */
#define     b1(x)        _b(x,1)
#define     b2(x)        _b(x,2)
#define     b3(x)        _b(x,3)          /* extract MSB of DWORD */

/* =============================================================== */

/* aes.h */
/* AES Cipher header file for ANSI C Submissions
    Lawrence E. Bassham III
    Computer Security Division
    National Institute of Standards and Technology

    This sample is to assist implementers developing to the
Cryptographic API Profile for AES Candidate Algorithm Submissions.
Please consult this document as a cross-reference.

  ANY CHANGES, WHERE APPROPRIATE, TO INFORMATION PROVIDED IN THIS FILE
MUST BE DOCUMENTED. CHANGES ARE ONLY APPROPRIATE WHERE SPECIFIED WITH
THE STRING “CHANGE POSSIBLE”. FUNCTION CALLS AND THEIR PARAMETERS
CANNOT BE CHANGED. STRUCTURES CAN BE ALTERED TO ALLOW IMPLEMENTERS TO
INCLUDE IMPLEMENTATION SPECIFIC INFORMATION.
*/

/* Includes:
    Standard include files
*/

#include     <stdio.h>
#include     “platform.h”           /* platform-specific defines */
/*  Defines:
        Add any additional defines you need
*/

#define DIR_ENCRYPT     0      /* Are we encrypting? */
#define DIR_DECRYPT     1      /* Are we decrpyting? */
#define MODE_ECB        1      /* Are we ciphering in ECB mode? */
#define MODE_CBC        2      /* Are we ciphering in CBC mode? */
#define MODE_CFB1       3      /* Are we ciphering in 1-bit CFB mode?*/

#define TRUE            1
#define FALSE           0

#define BAD_KEY_DIR       -1   /* Invalid Key direction */
#define BAD_KEY_MAT       -2   /* Key material not of correct length */
#define BAD_KEY_INSTANCE  -3   /* Key passed is not valid */
#define BAD_CIPHER_MODE   -4   /* Params struct is invalid */
#define BAD_CIPHER_STATE  -5   /* Cipher in wrong state */

/* CHANGE POSSIBLE: inclusion of algorithm specific defines */
/* TWOFISH specific definitions */

#define MAX_KEY_SIZE      64   /* # of chars in key representation */
#define MAX_IV_SIZE       16   /* # of bytes needed to represent an IV */
#define BAD_INPUT_LEN     -6   /* inputLen not a multiple of block size */
#define BAD_PARAMS        -7   /* invalid parameters */
#define BAD_IV_MAT        -8   /* invalid IV text */
#define BAD_ENDIAN        -9   /* incorrect endianness define */
#define BAD_ALIGN32       -10  /* incorrect 32-bit alignment */

#define BLOCK_SIZE        128  /* number of bits per block */
#define MAX_ROUNDS         16  /* max # rounds */
#define ROUNDS_128         16  /* default # of rounds for 128-bit keys*/
#define ROUNDS_192         16  /* default # of rounds for 192-bit keys*/
#define ROUNDS_256         16  /* default # of rounds for 256-bit keys*/
#define MAX_KEY_BITS      256  /* max number of bits of key */
#define MIN_KEY_BITS      128  /* min number of bits of key (zero pad) */
#define VALID_SIG 0x48534946 /* initialization signature ('FISH') */
#define MCT_OUTER         400  /* MCT outer loop */
#define MCT_INNER         10000  /* MCT inner loop */
#define REENTRANT         1 /* forces reentrant code (slightly slower) */

#define INPUT_WHITEN           0   /* subkey array indices */
#define OUTPUT_WHITEN          ( INPUT_WHITEN + BLOCK_SIZE/32)
#define ROUND_SUBKEYS          (OUTPUT_WHITEN + BLOCK_SIZE/32)
#define TOTAL_SUBKEYS          (ROUND_SUBKEYS + 2*MAX_ROUNDS)

/* Typedefs:
    Typedef'ed data storage elements. Add any algorithm specific
    parameters at the bottom of the structs as appropriate.
*/

typedef unsigned char BYTE;
typedef unsigned long DWORD;        /* 32-bit unsigned quantity */
typedef DWORD fullSbox[4] [256];

/* The structure for key information */
typedef struct
    {
    BYTE direction;                 /* Encrypting or decrypting? */
#if ALIGN32
    BYTE dummyAlign[3];             /* keep 32-bit alignment */
#endif
    int keyLen;                     /* Length of the key */
    char keyMaterial [MAX_KEY_SIZE+4];/*Raw key data in ASCII */

    /* Twofish-specific parameters:   */
    DWORD keySig;                     /* set to VALID_SIG by makeKey()*/
    int numRounds;                    /* number of rounds in cipher */
    DWORD key32 [MAX_KEY_BITS/32];    /* actual key bits, in dwords */
    DWORD sboxKeys [MAX_KEY_BITS/64]; /* key bits used for S-boxes */
    DWORD subKeys [TOTAL_SUBKEYS];    /* whitening & round subkeys */
#if REENTRANT
    fullSbox sBox8x32;                /* fully expanded S-box */
  #if defined (COMPILE_KEY) && defined (USE_ASM)
  #undef VALID_SIG
  #define VALID_SIG 0x504D4F43        /* 'COMP' */
      void *encryptFuncPtr;           /* ptr to asm encrypt function */
      void *decryptFuncPtr;           /* ptr to asm decrypt function */
      DWORD codeSize;                 /* size of compiledCode */
      BYTE compiledCode [5000];       /* make room for the code */
  #endif
#endif
    } keyInstance;

/* The structure for cipher information */
typedef struct
    {
    BYTE mode;                   /* MODE_ECB, MODE_CBC, or MODE_CFB1 */
#if ALIGN32
    BYTE dummyAlign[3];          /* keep 32-bit alignment */
#endif
    BYTE IV[MAX_IV_SIZE];        /* CFB1 iv bytes (CBC uses iv32) */

    /* Twofish-specific parameters: */
    DWORD cipherSig;             /* set to VALID_SIG by cipherInit () */
    DWORD iv32[BLOCK_SIZE/32];   /* CBC IV bytes arranged as dwords */
    } cipherInstance;

/* Function protoypes */
int makeKey (keyInstance *key, BYTE direction,
            int keyLen, char *keyMaterial);

int cipherInit (cipherInstance *cipher, BYTE mode, char *IV);

int blockEncrypt (cipherInstance *cipher, keyInstance *key,
                 BYTE *input, int inputLen, BYTE *outBuffer);

int blockDecrypt (cipherInstance *cipher, keyInstance *key,
                 BYTE *input, int inputLen, BYTE *outBuffer);

/* do key schedule using modified key.keyDwords */
int reKey (keyInstance *key);

/* affect number of rounds for given keyLen (64, 128, 192, 256)
*/ int setRounds (int keyLen, int nRounds);

/* API to check table usage, for use in ECB_TBL KAT */
#define     TAB_DISABLE         0
#define     TAB_ENABLE          1
#define     TAB_RESET           2
#define     TAB_QUERY           3
#define     TAB_MIN_QUERY       50
int TableOp (int op);

#define     CONST       /* helpful C++ syntax sugar, NOP for ANSI C */
#if BLOCK_SIZE == 128         /* optimize block copies */
#define     Copy1(d,s,N)   ((DWORD *) (d)) [N] = ((DWORD *)(s)) [N]
#define     BlockCopy(d,s) \
    { Copy1(d,s,0);Copy1(d,s,1);Copy1(d,s,2);Copy1(d,s,3); }
#else
#define     BlockCopy(d,s) { memcpy (d,s,BLOCK_SIZE/8); }
#endif

/* ================================================================= */

/* DEBUG.H — debug assist macros */
#ifdef DEBUG
CONST int debugCompile  =  1;
extern  int debug;
extern  void DebugIO(CONST char *s);    /* display the debug output */

#define DebugDump (x,s,R,XOR,doRot,showT,needBswap) \
    { if (debug) _Dump(x,s,R,XOR,doRot,showT,needBswap,t0,t1); }
#define DebugDumpKey (key) { if (debug) _DumpKey(key); }
#define IV_ROUND -100

void _Dump (CONST void *p, CONST char *s, int R, int XOR, int doRot,
           int showT, int needBswap, DWORD t0, DWORD t1)
     {
     char line [512]; /* build output here */
     int i, n;
     DWORD q[4];

     if (R == IV_ROUND)
         sprintf (line,“%sIV: ”,s);
     else
         sprintf (line, “%sR[%2d]: ” , s, R);
     for (n=0;line[n];n++) ;

     for (i=0; i<4;i++)
         {
         q[i] = ((CONST DWORD *)p)[i^(XOR)];
         if (needBswap) q[i]=Bswap(q[i]);
         }

     sprintf (line+n, “x= %08lX %08lX %08lX %08lX.”,
              ROR(q[0], doRot*(R )/2),
              ROL(q[1], doRot*(R )/2),
              ROR(q[2], doRot*(R+1)/2),
              ROL(q[3], doRot*(R+1)/2));
     for (;line[n];n++);

     if (showT)
         sprintf(line+n,“ t0=%08lX. t1=%08lX.”,t0,t1);
     for (;line[n] ;n++) ;
         sprintf(line+n, “\n”);
     DebugIO(line);
     }

void _DumpKey (CONST keyInstance *key)
    {
    char    line [512];
    int     i;
    int     k64Cnt=(key->keyLen+63)/64; /* round up */
    int     subkeyCnt = ROUND_SUBKEYS + 2*key->numRounds;

    sprintf(line,
“;\n;makeKey:    Input key             —>  S-box key     [%s]\n”,
         (key->direction == DIR_ENCRYPT) ? “Encrypt” : “Decrypt”);
  DebugIO(line);
  for (i=0;i<k64Cnt;i++) /* display in RS format */
      {
      sprintf (line, “;%12s %08lX %08lX —> %08lX\n”,“”,
              key->key32[2*i+1],key->key32[2*i],
              key->sboxKeys[k64Cnt-1-i]);
       DebugIO(line);
       }
   sprintf (line,“;%11sSubkeys\n”,“”);
   DebugIO(line);
   for (i=0;i<subkeyCnt/2;i++)
       {
        sprintf(line,“;%12s %08lX %08lX%s\n”,“”,
               key->subKeys[2*i],key->subKeys[2*i+1],
               (2*i ==  INPUT_WHITEN) ? “ Input whiten” :
               (2*i == OUTPUT_WHITEN) ? “ Output whiten” :
               (2*i == ROUND_SUBKEYS) ? “ Round subkeys” : “”);
        DebugIO(line);
        }
    DebugIO(“;\n”);
    }
#else
CONST int debugCompile = 0;
#define DebugDump(x,s,R,XOR,doRot,showT,needBswap)
#define DebugDumpKey (key)
#endif

/* ================================================================ */

/**********************************************************************
TABLE.H — Tables, macros, etc. for Twofish S-boxes and MDS matrix

Submitters:
  Bruce Schneier, Counterpane Systems
  Doug Whiting,   Hi/fn
  John Kelsey,    Counterpane Systems
  Chris Hall,     Counterpane Systems
  David Wagner,   UC Berkeley
  Niels Ferguson, Counterpane Systems

Code Author:         Doug Whiting,   Hi/fn

Version 1.00         April 1998

Copyright 1998, Hi/fn and Counterpane Systems. All rights reserved.

Notes:
  * Tab size is set to 4 characters in this file
  * These definitions should be used in optimized and unoptimized
    versions to insure consistency.

**********************************************************************/

/* for computing subkeys */
#define SK_STEP         0x02020202u
#define SK_BUMP         0x01010101u
#define SK_ROTL         9

/* Reed-Solomon code parameters: (12,8) reversible code
    g(x) = x**4 + (a + 1/a) x**3 + a x**2 + (a + 1/a) x + 1
   where a = primitive root of field generator 0x14D */
#define RS_GF_FDBK 0x14D /* field generator */
#define RS_rem(x) \
 { BYTE b= (BYTE) (x >> 24); \
   DWORD g2= ((b<<1) ^ ((b&0x80) ? RS_GF_FDBK : 0 )) & 0xFF; \
   DWORD g3= ((b>>1) & 0x7F) ^ ((b&1) ? RS_GF_FDBK >> 1 : 0 ) ^ g2 ; \
   x= (x << 8) ^ (g3 << 24) ^ (g2 << 16) ^ (g3 << 8) ^ b; \
}

/* Macros for the MDS matrix
* The MDS matrix is (using primitive polynomial 169):
*    01  EF  5B  5B
*    5B  EF  EF  01
*    EF  5B  01  EF
*    EF  01  EF  5B
------------------------------------------------------------------
* More statistical properties of this matrix (from MDS.EXE output):
*
* Min Hamming weight (one byte difference) = 8. Max=26. Total = 1020.
* Prob[8] : 7   23   42   20   52   95   88    94  121  128   91
*         102   76   41   24    8    4    1     3    0    0    0
* Runs[8] : 2    4    5    6    7    8    9    11
* MSBs[8] : 1    4   15    8   18   38   40    43
* HW=8: 05040705 0A080E0A 14101C14 28203828 50407050 01499101 A080E0A0
* HW=9: 04050707 080A0E0E 10141C1C 20283838 40507070 80A0E0E0 C6432020
*       07070504 0E0E0A08 1C1C1410 38382820 70705040 E0E0A080 202043C6
*       05070407 0A0E080E 141C101C 28382038 50704070 A0E080E0 4320C620
*       02924B02 089A4508
* Min Hamming weight (two byte difference) = 3. Max=28. Total = 390150.
* Prob [3] : 7 18 55 149 270 914 2185 5761 11363 20719
*       32079 43492 51612 53851 52098 42015 31117 20854 11538 6223
*        2492 1033
* MDS OK, ROR: 6+  7+  8+  9+ 10+ 11+ 12+ 13+ 14+ 15+ 16+
*             17+ 18+ 19+ 20+ 21+ 22+ 23+ 24+ 25+ 26+
*/
#define MDS_GF_FDBK   0x169   /* primitive polynomial for GF(256)*/
#define LFSR1(x) ( ((x) >> 1) ^ (((x) & 0x01) ? MDS_GF_FDBK/2 : 0))
#define LFSR2(x) ( ((x) >> 2) ^ (((x) & 0x02) ? MDS_GF_FDBK/2 : 0) \
                              ^ (((x) & 0x01) ? MDS_GF_FDBK/4 :0))

#define Mx_1(x) ((DWORD) (x)) /* force to dword so << will work */
#define Mx_X(x) ((DWORD) ((x) ^ LFSR2(x))) /* 5B */
#define Mx_Y(x) ((DWORD) ((x) ^ LFSR1(x) ^ LFSR2(x))) /* EF */

#define M00     Mul_1
#define M01     Mul_Y
#define M02     Mul_X
#define M03     Mul_X

#define M10     Mul_X
#define M11     Mul_Y
#define M12     Mul_Y
#define M13     Mul_1

#define M20     Mul_Y
#define M21     Mul_X
#define M22     Mul_1
#define M23     Mul_Y

#define M30     Mul_Y
#define M31     Mul_1
#define M32     Mul_Y
#define M33     Mul_X

#define Mul_1   Mx_1
#define Mul_X   Mx_X
#define Mul_Y   Mx_Y

/* Define the fixed p0/p1 permutations used in keyed S-box lookup.
   By changing the following constant definitions for P_ij, the
   S-boxes will automatically get changed in all the Twofish source
   code. Note that P_i0 is the “outermost” 8x8 permutation applied.
   See the f32() function to see how these constants are to be used.
*/
#define P_00   1                     /* “outermost” permutation */
#define P_01   0
#define P_02   0
#define P_03   (P_01^1)              /* “extend” to larger key sizes */
#define P_04   1
#define P_10   0
#define P_11   0
#define P_12   1
#define P_13   (P_11^1)
#define P_14   0

#define P_20   1
#define P_21   1
#define P_22   0
#define P_23   (P_21^1)
#define P_24   0

#define P_30   0
#define P_31   1
#define P_32   1
#define P_33   (P_31^1)
#define P_34   1

#define p8(N)  P8x8[P_##N]           /* some syntax shorthand */

/* fixed 8x8 permutation S-boxes */

/*********************************************************************
* 07:07:14 05/30/98 [4x4] TestCnt=256. keySize=128. CRC=4BD14D9E.
* maxKeyed: dpMax = 18. lpMax =100. fixPt = 8. skXor = 0. skDup = 6.
*log2(dpMax [6..18])= --- 15.42 1.33 0.89 4.05 7.98 12.05
*log2(lpMax[7..12])= 9.32 1.01 1.16 4.23 8.02 12.45
*log2(fixPt[0.. 8])= 1.44 1.44 2.44 4.06 6.01 8.21 11.07 14.09 17.00
*log2(skDup [0.. 6])= --- 2.37 0.44 3.94 8.36 13.04 17.99
*********************************************************************/
CONST BYTE P8x8[2] [256]=
    {
/*  p0: */
/*  dpMax = 10. lpMax =64. cycleCnt= 1 1 1 0. */
/* 817D6F320B59ECA4.ECB81235F4A6709D.
   BA5E6D90C8F32471.D7F4126E9B3085CA. */
    0xA9, 0x67, 0xB3, 0xE8, 0x04, 0xFD, 0xA3, 0x76,
    0x9A, 0x92, 0x80, 0x78, 0xE4, 0xDD, 0xD1, 0x38,
    0x0D, 0xC6, 0x35, 0x98, 0x18, 0xF7, 0xEC, 0x6C,
    0x43, 0x75, 0x37, 0x26, 0xFA, 0x13, 0x94, 0x48,
    0xF2, 0xD0, 0x8B, 0x30, 0x84, 0x54, 0xDF, 0x23,
    0x19, 0x5B, 0x3D, 0x59, 0xF3, 0xAE, 0xA2, 0x82,
    0x63, 0x01, 0x83, 0x2E, 0xD9, 0x51, 0x9B, 0x7C,
    0xA6, 0xEB, 0xA5, 0xBE, 0x16, 0x0C, 0xE3, 0x61,
    0xC0, 0x8C, 0x3A, 0xF5, 0x73, 0x2C, 0x25, 0x0B,
    0xBB, 0x4E, 0x89, 0x6B, 0x53, 0x6A, 0xB4, 0xF1,
    0xE1, 0xE6, 0xBD, 0x45, 0xE2, 0xF4, 0xB6, 0x66,
    0xCC, 0x95, 0x03, 0x56, 0xD4, 0x1C, 0x1E, 0xD7,
    0xFB, 0xC3, 0x8E, 0xB5, 0xE9, 0xCF, 0xBF, 0xBA,
    0xEA, 0x77, 0x39, 0xAF, 0x33, 0xC9, 0x62, 0x71,
    0x81, 0x79, 0x09, 0xAD, 0x24, 0xCD, 0xF9, 0xD8,
    0xE5, 0xC5, 0xB9, 0x4D, 0x44, 0x08, 0x86, 0xE7,
    0xA1, 0x1D, 0xAA, 0xED, 0x06, 0x70, 0xB2, 0xD2,
    0x41, 0x7B, 0xA0, 0x11, 0x31, 0xC2, 0x27, 0x90,
    0x20, 0xF6, 0x60, 0xFF, 0x96, 0x5C, 0xB1, 0xAB,
    0x9E, 0x9C, 0x52, 0x1B, 0x5F, 0x93, 0x0A, 0xEF,
    0x91, 0x85, 0x49, 0xEE, 0x2D, 0x4F, 0x8F, 0x3B,
    0x47, 0x87, 0x6D, 0x46, 0xD6, 0x3E, 0x69, 0x64,
    0x2A, 0xCE, 0xCB, 0x2F, 0xFC, 0x97, 0x05, 0x7A,
    0xAC, 0x7F, 0xD5, 0x1A, 0x4B, 0x0E, 0xA7, 0x5A,
    0x28, 0x14, 0x3F, 0x29, 0x88, 0x3C, 0x4C, 0x02,
    0xB8, 0xDA, 0xBO, 0x17, 0x55, 0x1F, 0x8A, 0x7D,
    0x57, 0xC7, 0x8D, 0x74, 0xB7, 0xC4, 0x9F, 0x72,
    0x7E, 0x15, 0x22, 0x12, 0x58, 0x07, 0x99, 0x34,
    0x6E, 0x50, 0xDE, 0x68, 0x65, 0xBC, 0xDB, 0xF8,
    0xC8, 0xA8, 0x2B, 0x40, 0xDC, 0xEF, 0x32, 0xA4,
    0xCA, 0x10, 0x21, 0xF0, 0xD3, 0x5D, 0x0F, 0x00,
    0x6F, 0x9D, 0x36, 0x42, 0x4A, 0x5E, 0xC1, 0xE0,
/*  p1: */
/*  dpMax = 10. 1pMax =64. cycleCnt= 2 0 0 1. */
/* 28BDF76E31940AC5.1E2B4C376DA5F908.
   4C75169A0ED82B3F.B951C3DE647F208A. */
    0x75, 0xF3, 0xC6, 0xF4, 0xDB, 0x7B, 0xFB, 0xC8,
    0x4A, 0xD3, 0xE6, 0x6B, 0x45, 0x7D, 0xE8, 0x4B,
    0xD6, 0x32, 0xD8, 0xFD, 0x37, 0x71, 0xF1, 0xE1,
    0x30, 0x0F, 0xF8, 0x1B, 0x87, 0xFA, 0x06, 0x3F,
    0x5E, 0xBA, 0xAE, 0x5B, 0x8A, 0x00, 0xBC, 0x9D,
    0x6D, 0xC1, 0xB1, 0x0E, 0x80, 0x5D, 0xD2, 0xD5,
    0xA0, 0x84, 0x07, 0x14, 0xB5, 0x90, 0x2C, 0xA3,
    0xB2, 0x73, 0x4C, 0x54, 0x92, 0x74, 0x36, 0x51,
    0x38, 0xB0, 0xBD, 0x5A, 0xFC, 0x60, 0x62, 0x96,
    0x6C, 0x42, 0xF7, 0x10, 0x7C, 0x28, 0x27, 0x8C,
    0x13, 0x95, 0x9C, 0xC7, 0x24, 0x46, 0x3B, 0x70,
    0xCA, 0xE3, 0x85, 0xCB, 0x11, 0xD0, 0x93, 0xB8,
    0xA6, 0x83, 0x20, 0xFF, 0x9F, 0x77, 0xC3, 0xCC,
    0x03, 0x6F, 0x08, 0xBF, 0x40, 0xE7, 0x2B, 0xE2,
    0x79, 0x0C, 0xAA, 0x82, 0x41, 0x3A, 0xEA, 0xB9,
    0xE4, 0x9A, 0xA4, 0x97, 0x7E, 0xDA, 0x7A, 0x17,
    0x66, 0x94, 0xA1, 0x1D, 0x3D, 0xF0, 0xDE, 0xB3,
    0x0B, 0x72, 0xA7, 0x1C, 0xEF, 0xD1, 0x53, 0x3E,
    0x8F, 0x33, 0x26, 0x5F, 0xEC, 0x76, 0x2A, 0x49,
    0x81, 0x88, 0xEE, 0x21, 0xC4, 0x1A, 0xEB, 0xD9,
    0xC5, 0x39, 0x99, 0xCD, 0xAD, 0x31, 0x8B, 0x01,
    0x18, 0x23, 0xDD, 0x1F, 0x4E, 0x2D, 0xF9, 0x48,
    0x4F, 0xF2, 0x65, 0x8E, 0x78, 0x5C, 0x58, 0x19,
    0x8D, 0xE5, 0x98, 0x57, 0x67, 0x7F, 0x05, 0x64,
    0xAF, 0x63, 0xB6, 0xFE, 0xF5, 0xB7, 0x3C, 0xA5,
    0xCE, 0xE9, 0x68, 0x44, 0xE0, 0x4D, 0x43, 0x69,
    0x29, 0x2E, 0xAC, 0x15, 0x59, 0xA8, 0x0A, 0x9E,
    0x6E, 0x47, 0xDF, 0x34, 0x35, 0x6A, 0xCF, 0xDC,
    0x22, 0xC9, 0xC0, 0x9B, 0x89, 0xD4, 0xED, 0xAB,
    0x12, 0xA2, 0x0D, 0x52, 0xBB, 0x02, 0x2F, 0xA9,
    0xD7, 0x61, 0x1E, 0xB4, 0x50, 0x04, 0xF6, 0xC2,
    0x16, 0x25, 0x86, 0x56, 0x55, 0x09, 0xBE, 0x91,
    };
/* ============================================================ */
/***************************************************************
  TWOFISH.C — C API calls for TWOFISH AES submission

Submitters:
  Bruce Schneier, Counterpane Systems
  Doug Whiting,   Hi/fn
  John Kelsey,    Counterpane Systems
  Chris Hall,     Counterpane Systems
  David Wagner,   UC Berkeley
  Niels Ferguson, Counterpane Systems

Code Author:        Doug Whiting, Hi/fn

Version  1.00        April 1998

Copyright 1998, Hi/fn and Counterpane Systems. All rights reserved.

Notes:
  * Pedagogical version (non-optimized)
  * Tab size is set to 4 characters in this file

*****************************************************************/

#include   “aes.h”
#include   “table.h”

/*
******************************************************************
*          Constants/Macros/Tables
*****************************************************************/

#define VALIDATE_PARMS 1 /* nonzero —> check all parameters */
#define FEISTEL        0 /* nonzero —> use Feistel version (slow) */
int tabEnable=0;         /* are we gathering stats? */
BYTE tabUsed[256];       /* one bit per table */

#if FEISTEL
CONST       char *moduleDescription=“Pedagogical C code (Feistel)”;
#else
CONST       char *moduleDescription=“Pedagogical C code”;
#endif
CONST       char *modeString = “”;

#define P0_USED     0X01
#define P1_USED     0x02
#define B0_USED     0x04
#define B1_USED     0x08
#define B2_USED     0x10
#define B3_USED     0x20
#define ALL_USED    0x3F

/* number of rounds for various key sizes: 128, 192, 256 */
int         numRounds [4]= {0,ROUNDS_128,ROUNDS_192,ROUNDS_256};

#ifndef DEBUG
#define DEBUG   1                    /* force debug */
#endif
#include    “debug.h”                /* debug display macros */

extern DWORD Here (DWORD x);         /* return caller's address! */
DWORD TwofishCodeStart (void) { return Here (0); };

/*
+******************************************************************
*
* Function Name: setRounds
*
* Function:      Set the number of rounds for Twofish
*
* Arguments:     keyLen    = which keyLength to affect (128, 192, 256)
*                numRounds = how many rounds
*
* Return:        TRUE if the values passed in are valid
*
* Notes: This routine sets global variable(s) which are used in
*        setting up the key schedule.
*
-******************************************************************
int setRounds (int keyLen, int nRounds)
    {
    if ((nRounds < 2) || (nRounds > MAX_ROUNDS) || (nRounds & 1))
       return FALSE;

    switch (keyLen)
        {
        case 128:   numRounds [1]=nRounds;    break;
        case 192:   numRounds [2]=nRounds;    break;
        case 256:   numRounds [3]=nRounds;    break;
        default:    return FALSE;
        }

    return TRUE;
    }
/*
+******************************************************************
*
* Function Name:     TableOp
*
* Function:          Handle table use checking
*
* Arguments:         op  =   what to do (see TAB_* defns in AES.H)
*
* Return:        TRUE —> done (for TAB_QUERY)
*
* Notes: This routine is for use in generating the tables KAT file.
*
-******************************************************************
int TableOp (int op)
    {
    static int queryCnt=0;
    int i;
    switch (op)
        {
        case TAB_DISABLE:
            tabEnable=0;
            break;
        case TAB_ENABLE:
            tabEnable=1;
            break;
        case TAB_RESET:
            queryCnt=0;
            for (i=0; i<256; i++)
                tabUsed [i]=0;
            break;
        case TAB_QUERY:
            queryCnt++;
            for (i=0; i<256;i++)
                if (tabUsed [i] ! = ALL_USED)
                    return FALSE;
                if (queryCnt < TAB_MIN_QUERY) /* do a minimum number */
                    return FALSE;
                break;
        }
    return TRUE;
    }
/*
+******************************************************************
*
* Function Name:     ParseHexDword
*
* Function:          Parse ASCII hex nibbles and fill in key/iv dwords
*
* Arguments:         bit       =   # bits to read
*                    srcTxt    =   ASCII source
*                    d         =   ptr to dwords to fill in
*                    dstTxt    =   where to make a copy of ASCII source
*                                     (NULL ok)
*
* Return:            Zero if no error. Nonzero —> invalid hex or length
*
* Notes: Note that the parameter d is a DWORD array, not a byte array.
*   This routine is coded to work both for little-endian and big-
*   endian architectures. The character stream is interpreted as a
*   LITTLE-ENDIAN byte stream, since that is how the Pentium works,
*   but the conversion happens automatically below.
*
-*****************************************************************/
int ParseHexDword (int bits, CONST char *srcTxt, DWORD *d, char *dstTxt)
    {
    int i;
    DWORD b;
    char c;
#if ALIGN32
    char alignDummy [3]; /* keep dword alignment */
#endif

    union /* make sure LittleEndian is defined correctly */
        {
        BYTE  b[4];
        DWORD d[1];
        } v;
    v.d[0] = 1;
    if (v.b[0 ^ ADDR_XOR] != 1) /* sanity check on switch */
        return BAD_ENDIAN;

#if VALIDATE_PARMS
  #if ALIGN32
    if (((int)d) & 3)
        return BAD_ALIGN32;
  #endif
#endif

    for (i=0; i*32<bits;i++)
        d[i]=0;                   /* first, zero the field */
    for (i=0;i*4<bits; i++)       /* parse one nibble at a time */
        {
        c=srcTxt [i];
        if (dstTxt) dstTxt[i] = c;
        if ((c >= '0') && (c <= '9'))
            b=c-'0';
        else if ((c >= 'a') && (c <= 'f'))
            b=c-'a'+10;
        else if ((c >= 'A') && (c <= 'F'))
            b=c-'A'+10;
        else
            return BAD_KEY_MAT; /* invalid hex character */
        /* works for big and little endian! */
        d[i/8] |= b << (4*((i^1)&7));
        }

    return 0;                     /* no error */
    }
/*
+******************************************************************
*
* Function Name: f32
*
* Function:      Run four bytes through keyed S-boxes
*                and apply MDS matrix
*
* Arguments:     x        =   input to f function
*                k32      =   pointer to key dwords
*                keyLen   =   total key length (k32 —> keyLey/2 bits)
*
* Return:        The output of the keyed permutation applied to x.
*
* Notes:
*   This function is a keyed 32-bit permutation. It is the major
*   building block for the Twofish round function, including the four
*   keyed 8x8 permutations and the 4x4 MDS matrix multiply. This
*   function is used both for generating round subkeys and within the
*   round function on the block being encrypted.
*
*   This version is fairly slow and pedagogical, although a smartcard
*   would probably perform the operation exactly this way in firmware.
*   For ultimate performance, the entire operation can be completed
*   with four lookups into four 256x32-bit tables, with three dword
*   xors.
*
*   The MDS matrix is defined in TABLE.H. To multiply by Mij, just
*   use the macro Mij(x).
*
-*****************************************************************/
DWORD f32 (DWORD x,CONST DWORD *k32,int keyLen)
    {
    BYTE b[4];

    /* Run each byte thru 8x8 S-boxes, xoring with key bytes. */
    /* Note that each byte uses a different combination of S-boxes.*/

     *((DWORD *)b) = Bswap(x);   /* make b[0] = LSB, b[3] = MSB */
     switch (((keyLen + 63)/64) & 3)
         {
         case 0:     /* 256 bits of key */
             b[0] = p8(04)[b[0]] ^ b0(k32[3]);
             b[1] = p8(14)[b[1]] ^ b1(k32[3]);
             b[2] = p8(24)[b[2]] ^ b2(k32[3]);
             b[3] = p8(34)[b[3]] ^ b3(k32[3]);
             /* fall thru, having pre-processed b[0]..b[3] */
         case 3: /* 192 bits of key */
             b[0] = p8(03) [b[0]] ^ b0(k32[2]);
             b[1] = p8(13) [b[1]] ^ b1(k32[2]);
             b[2] = p8(23) [b[2]] ^ b2(k32[2]);
             b[3] = p8(33) [b[3]] ^ b3(k32[2]);
             /* fall thru, having pre-processed b[0]..b[3] */
         case 2:     /* 128 bits of key */
         b[0] = p8(00) [p8(01)[p8(02) [b[0]]^b0(k32[1])]^b0(k32[0])];
         b[1] = p8(10) [p8(11)[p8(12) [b[1]]^b1(k32 [1])]^b1(k32[0])];
         b[2] = p8(20) [p8(21)[p8(22) [b[2]]^b2(k32 [1])]^b2(k32[0])];
         b[3] = p8(30) [p8(31)[p8(32) [b[3]]^b3(k32 [1])]^b3(k32[0])];
      }

  if (tabEnable)
      { /* we could give a “tighter” bound, but this works OK */
      tabUsed [b0(x)] |= (p_00 == 0) ? P0_USED : P1_USED;
      tabUsed [b1(x)] |= (p_10 == 0) ? P0_USED : P1_USED;
      tabUsed [b2(x)] |= (p_20 == 0) ? P0_USED : P1_USED;
      tabUsed [b3(x)] |= (p_30 == 0) ? P0_USED : P1_USED;
      tabUsed[b[0]  ] |= B0_USED;
      tabUsed[b[1]  ] |= B1_USED;
      tabUsed[b[2]  ] |= B2_USED;
      tabUsed[b[3]  ] |= B3_USED;
      }

   /* Now perform the MDS matrix multiply inline. */
   return ((M00(b[0]) ^ M01(b[1]) ^ M02(b[2]) ^ M03(b[3])) )^
          ((M10(b[0]) ^ M11(b[1]) ^ M12(b[2]) ^ M13(b[3])) << 8)^
          ((M20(b[0]) ^ M21(b[1]) ^ M22(b[2]) ^ M23(b[3])) <<16)^
          ((M30(b[0]) ^ M31(b[1]) ^ M32(b[2]) ^ M33(b[3])) <<24);
   }
/*
+******************************************************************
*
* Function Name: RS_MDS_Encode
*
* Function:      Use (12,8) Reed-Solomon code over GF(256) to produce
*                a key S-box dword from two key material dwords.
*
* Arguments:     k0 = 1st dword
*                K1 = 2nd dword
*
* Return:        Remainder polynomial generated using RS code
*
* Notes:
*   Since this computation is done only once per reKey per 64 bits of
*   key, the performance impact of this routine is imperceptible. The
*   RS code chosen has “simple” coefficients to allow smartcard/
*   hardware implementation without lookup tables.
*
-******************************************************************/
DWORD RS_MDS_Encode (DWORD k0, DWORD k1)
    {
    int i, j;
    DWORD r;

    for (i=r=0; i<2;i++)
        {
        r ^=(i) ? k0 : k1;            /* merge in 32 more key bits */
        for (j=0;j<4;j++)             /* shift one byte at a time*/
            RS_rem(r);
        }
    return r;
    }

/*
+*********************************************************************
*
* Function Name:    reKey
*
* Function:         Initialize the Twofish key schedule from key32
*
* Arguments:        key         = ptr to keyInstance to be initialized
*
* Return:           TRUE on success
*
* Notes:
*   Here we precompute all the round subkeys, although that is not
*   actually required. For example, on a smartcard, the round subkeys
*   can be generated on-the-fly using f32()
*
-********************************************************************/
int reKey(keyInstance *key)
    {
    int     i, k64Cnt;
    int     keyLen     = key->keyLen;
    int     subkeyCnt  = ROUND_SUBKEYS + 2*key->numRounds;
    DWORD   A,B;
    /*even/odd key dwords */
    DWORD   k32e[MAX_KEY_BITS/64], k32o [MAX_KEY_BITS/64];

#if VALIDATE_PARMS
  #if ALIGN32
    if ((((int)key) & 3) || (((int)key->key32) & 3))
        return BAD_ALIGN32;
  #endif
    if ((key->keyLen % 64) || (key->keyLen < MIN_KEY_BITS))
        return BAD_KEY_INSTANCE;
    if (subkeyCnt > TOTAL_SUBKEYS)
        return BAD_KEY_INSTANCE;
#endif

    k64Cnt=(keyLen+63)/64;     /* round up to next multiple of 64 bits */
    for (i=0;i<k64Cnt;i++)
        {                         /* split into even/odd key dwords */
         k32e[i]=key->key32[2*i ];
         k32o [i]=key->key32[2*i+1];
         /* compute S-box keys using (12,8) RS-code over GF (256) */
         Key->sboxKeys [k64Cnt-1-i]=RS_MDS_Encode(k32e[i],k32o[i]);
         }
  for (i=0;i<subkeyCnt/2;i++) /* compute round subkeys for PHT */
      {
       A = f32(i*SK_STEP ,k32e, keyLen);
       B = f32 (i*SK_STEP+SK_BUMP, k32o, keyLen);
       B = ROL (B,8);
       key->subKeys [2*i ] = A+ B; /* combine with a PHT */
       key->subKeys [2*i+1] = ROL(A+2*B, SK_ROTL);
       }

   DebugDumpKey(key);

   return TRUE;
   }
/*
+*******************************************************************
*
* Function Name:  makeKey
*
* Function:       Initialize the Twofish key schedule
*
* Arguments:      key         = ptr to keyInstance to be initialized
*                 direction   = DIR_ENCRYPT or DIR_DECRYPT
*                 keyLen      = # bits of key text at *keyMaterial
*                 keyMaterial = ptr to hex ASCII chars representing key
*
* Return:         TRUE on success
*                 else error code (e.g., BAD_KEY_DIR)
*
* Notes:
*   This parses the key bits from keyMaterial. No crypto stuff happens
*   here. The function reKey() is called to actually build the key
*   schedule after the keyMaterial has been parsed.
*
-********************************************************************/
int makeKey(keyInstance *key, BYTE direction,
           int keyLen, CONST char *keyMaterial)
    {
    int i;

#if VALIDATE_PARMS               /* first, check parameters */
    if (key == NULL)
        return BAD_KEY_INSTANCE;  /* must have a keyInstance to init. */
    if ((direction != DIR_ENCRYPT) && (direction !=DIR_DECRYPT))
       return BAD_KEY_DIR;        /* must have valid direction */
    if ((keyLen > MAX_KEY_BITS) || (keyLen < 8))
       return BAD_KEY_MAT;        /* length must be valid */
    if (keyMaterial == NULL)
       return BAD_KEY_MAT;        /* must have some data to work with */
    key->keySig = VALID_SIG;      /* show that we are initialized */
  #if ALIGN32
    if ((((int)key) & 3) || (((int)key->key32) & 3))
        return BAD_ALIGN32;
  #endif
#endif

    key->direction = direction;      /* set our cipher direction */
    key->keyLen    = (keyLen+63) & ~63;            /* round up */
    key->numRounds = numRounds [(keyLen-1)/64];
    for (i=0;i<MAX_KEY_BITS/32;i++) /* zero unused bits */
           key->key32[i]=0;

    if (ParseHexDword(keyLen, keyMaterial, key->key32, key->keyMaterial))
        return BAD_KEY_MAT;

    key->keyMaterial [MAX_KEY_SIZE]=0;    /* terminate ASCII string */

    return reKey(key);    /* generate round subkeys */
    }

/*
+*******************************************************************
*
* Function Name: cipherInit
*
* Function:      Initialize the Twofish cipher in a given mode
*
* Arguments:     cipher = ptr to cipherInstance to be initialized
*                mode   = MODE_ECB, MODE_CBC, or MODE_CFB1
*                IV     = ptr to hex ASCII test representing IV bytes
*
* Return:        TRUE on success
*                else error code (e.g., BAD_CIPHER_MODE)
*
-********************************************************************/
int cipherInit(cipherInstance *cipher, BYTE mode, CONST char *IV)
    {
    int i;
#if VALIDATE_PARMS            /* first, check parameters */
    if (cipher == NULL)
        return BAD_PARAMS;     /* must have a cipherInstance to init */
    if ((mode ! = MODE_ECB) && (mode != MODE_CBC)
       && (mode != MODE_CFB1))
        return BAD_CIPHER_MODE;  /* must have valid cipher mode */
    if ((mode !=MODE_ECB) && (IV == NULL))
        return BAD_PARAMS;   /* must have IV for CBC and CFB modes */
    cipher->cipherSig = VALID_SIG;
  #if ALIGN32
    if ((((int) cipher) & 3) || (((int)cipher->IV) & 3)
       || (((int)cipher->iv32) & 3))
       return BAD_ALIGN32;
  #endif
#endif

    if (mode !=MODE_ECB)          /* parse the IV */
        {
        if (ParseHexDword (BLOCK_SIZE, IV, cipher ->iv32, NULL))
            return BAD_IV_MAT;
        for (i=0;i<BLOCK_SIZE/32;i++) /* byte-oriented copy for CFB1*/
            (DWORD *) cipher->IV) [i] = Bswap (cipher->iv32[i]);
        }
    cipher->mode        =   mode;

    return TRUE;
    }

/*
+*********************************************************************
*
* Function Name: blockEncrypt
*
* Function:      Encrypt block(s) of data using Twofish
*
* Arguments:     cipher    = ptr to already initialized cipherInstance
*                key       = ptr to already initialized keyInstance
*                input     = ptr to data blocks to be encrypted
*                inputLen  = # bits to encrypt (multiple of blockSize)
*                outBuffer = ptr to where to put encrypted blocks
*
* Return:        # bits ciphered (>= 0)
*                else error code (e.g., BAD_CIPHER_STATE, ...)
*
* Notes: The only supported block size for ECB/CBC modes is BLOCK_SIZE
*        bits. If inputLen is not a multiple of BLOCK_SIZE bits in
*        those modes, an error BAD_INPUT_LEN is returned. In CFB1
*        mode, all block sizes can be supported.
*
-*********************************************************************/
int blockEncrypt(cipherInstance *cipher, keyInstance *key,
                 CONST BYTE *input, int inputLen, BYTE *outBuffer)
    {
    int i,n,r;                     /* loop variables */
    DWORD x[BLOCK_SIZE/32];        /* block being encrypted */
    DWORD t0, t1, tmp;             /* temp variables */
    int rounds=key->numRounds;     /* number of rounds */
    BYTE bit, ctBit, carry;        /* temps for CFB */
#if ALIGN32
    BYTE alignDummy;               /* keep 32-bit alignment on stack */
#endif

#if VALIDATE_PARMS
    if ((cipher == NULL) || (cipher->cipherSig != VALID_SIG))
        return BAD_CIPHER_STATE;
    if ((key ==NULL) || (key->keySig != VALID_SIG))
        return BAD_KEY_INSTANCE;
    if ((rounds < 2) || (rounds > MAX_ROUNDS) || (rounds&1))
        return BAD_KEY_INSTANCE;
    if ((cipher->mode != MODE_CFB1) && (inputLen % BLOCK_SIZE))
        return BAD_INPUT_LEN;
  #if ALIGN32
    if ( (((int)cipher) & 3) || (((int)key ) & 3) ||
         (((int)input ) & 3) || (((int)outBuffer) & 3))
        return BAD_ALIGN32;
  #endif
#endif

    if (cipher->mode == MODE_CFB1)
        { /* use recursion here to handle CFB, one block at a time */
         cipher->mode = MODE_ECB;  /* do encryption in ECB */
         for (n=0;n<inputLen;n++)
             {
             blockEncrypt (cipher, key, cipher->IV,BLOCK_SIZE, (BYTE *)x);
             bit = 0x80 >> (n & 7); /* which bit position in byte */
             ctBit = (input[n/8] & bit)
                     ^ (((BYTE *) x) [0] & 0x80) >> (n&7));
             outBuffer[n/8] = (outBuffer[n/8] & ~ bit) || ctBit;
             carry = ctBit >> (7 - (n&7));
             for (i=BLOCK_SIZE/8-1;i>=0;i—)
                 {
                 bit = cipher->IV[i] >> 7; /* save next “carry” */
                 cipher->IV[i] = (cipher->IV[i] << 1) ^ carry;
                 carry = bit;
                 }
             }
         cipher->mode = MODE_CFB1; /* restore mode for next time */
         return inputLen;
         }

     /* here for ECB, CBC modes */
     for (n=0;n<inputLen;n+=BLOCK_SIZE, input+=BLOCK_SIZE/8,
                            outBuffer+=BLOCK_SIZE/8)
        {
#ifdef DEBUG
        DebugDump (input,“\n”,-1,0,0,0,1);
        if (cipher->mode == MODE_CBC)
            DebugDump (cipher->iv32, “”,IV_ROUND,0,0,0,0);
#endif
        for (i=0;i<BLOCK_SIZE/32;i++) /* copy and add whitening */
            {
            x[i]=Bswap(((DWORD *)input)[i])
                 ^ key->subKeys[INPUT_WHITEN+i];
            if (cipher->mode ==MODE_CBC)
                x[i] ^= cipher->iv32[i];
            }

        DebugDump (x,“”,0,0,0,0,0);
        for (r=0;r<rounds;r++)       /* main Twofish encryption loop */
            {
#if FEISTEL
             t0 = f32(ROR(x[0], (r+1)/2), key->sboxKeys, key->keyLen);
             t1 = f32(ROL(x[1],8+(r+1)/2), key->sboxKeys, key->keyLen);
                                       /* PHT, round keys */
             x[2] ^= ROL(t0 + t1 + key->subKeys [ROUND_SUBKEYS+2*r ], r /2);
             x[3] ^= ROR(t0 + 2*t1 + key->subKeys [ROUND_SUBKEYS+2*r+1], (r+2) /2);

             DebugDump(x,“”,r+1,2*(r&1),1,1,0);
#else
             t0 = f32( x[0] ,key->sboxKeys,key->keyLen);
             t1 = f32(ROL(x[1],8),key->sboxKeys, key->keyLen);

             x[3] = ROL(x[3],1);
             x[2]^= t0 + t1 + key->subKeys [ROUND_SUBKEYS+2*r ];
             x[3]^= t0 + 2*t1 + key->subKeys       [ROUND_SUBKEYS+2*r+1];
             x[2] = ROR(x[2],1);

             DebugDump(x,“”,r+1,2*(r&1),0,1,0); /* use same format */
#endif
             if (r < rounds-1)          /* swap for next round */
                 {
                 tmp = x[0]; x[0]= x[2]; x[2] = tmp;
                 tmp = x[1]; x[1]= x[3]; x[3] = tmp;
                 }
             }
#if FEISTEL
        x[0] = ROR(x[0],8);             /* “final permutation” */
        x[1] = ROR(x[1],8);
        x[2] = ROR(x[2],8);
        x[3] = ROL(x[3],8);
#endif
        for (i=0;i<BLOCK_SIZE/32;i++) /* copy out, with whitening */
            {
            ((DWORD *)outBuffer)[i] =
                Bswap (x[i] ^ key->subKeys[OUTPUT_WHITEN+i]);
            if (cipher->mode == MODE_CBC)
                cipher->iv32[i] = Bswap(((DWORD *)outBuffer)[i]);
            }
#ifdef DEBUG
        DebugDump(outBuffer,“”,rounds+1,0,0,0,1);
        if (cipher->mode == MODE_CBC)
            DebugDump(cipher->iv32,“”,IV_ROUND,0,0,0,0);
#endif
        }

    return inputLen;
    }

/*
+********************************************************************
*
* Function Name: blockDecrypt
*
* Function:      Decrypt block(s) of data using Twofish
*
* Arguments:     cipher    = ptr to already initialized cipherInstance
*                key       = ptr to already initialized keyInstance
*                input     = ptr to data blocks to be decrypted
*                inputLen  = # bits to encrypt (multiple of blockSize)
*                outBuffer = ptr to where to put decrypted blocks
*
* Return:        #bits ciphered (>= 0)
*                else error code (e.g., BAD_CIPHER_STATE, ...)
*
* Notes: The only supported block size for ECB/CBC modes is BLOCK_SIZE
*        bits. If inputLen is not a multiple of BLOCK_SIZE bits in
*        those modes, an error BAD_INPUT_LEN is returned. In CFB1
*        mode, all block sizes can be supported.
*
-*********************************************************************/
int blockDecrypt(cipherInstance *cipher, keyInstance *key,
                CONST BYTE *input, int inputLen, BYTE *outBuffer)
    {
    int i,n,r;                    /* loop counters */
    DWORD x[BLOCK_SIZE/32];       /* block being encrypted */
    DWORD t0,t1;                  /* temp variables */
    int rounds=key->numRounds;    /* number of rounds*/
    BYTE bit, ctBit, carry;       /* temps for CFB */
#if ALIGN32
    BYTE alignDummy;              /* keep 32-bit alignment on stack */
#endif

#if VALIDATE_PARMS
    if ((cipher == NULL) || (cipher->cipherSig != VALID_SIG))
        return BAD_CIPHER_STATE;
    if ((key == NULL) || (key->keySig != VALID_SIG))
        return BAD_KEY_INSTANCE;
    if ((rounds < 2) || (rounds > MAX_ROUNDS) || (rounds&1))
        return BAD_KEY_INSTANCE;
    if ((cipher->mode != MODE_CFB1) && (inputLen % BLOCK_SIZE))
        return BAD_INPUT_LEN;
#if ALIGN32
  if ( (((int)cipher) & 3) || (((int)key ) & 3) ||
       (((int)input) & 3) || (((int)outBuffer) & 3))
      return BAD_ALIGN32;
 #endif
#endif

    if (cipher->mode == MODE_CFB1)
        { /* use blockEncrypt to handle CFB, one block at a time */
         cipher->mode = MODE_ECB; /* do encryption in ECB */
         for (n=0;n<inputLen;n++)
             {
             blockEncrypt(cipher,key,cipher->IV,BLOCK_SIZE, (BYTE *)x);
             bit = 0x80 >> (n & 7);
             ctBit = input [n/8] & bit;
             outBuffer[n/8] = (outBuffer [n/8] & ~ bit) ||
                         (ctBit ^ (((BYTE *) x) [0] & 0x80) >> (n&7)));
             carry = ctBit >> (7 - (n&7));
             for (i=BLOCK_SIZE/8-1;i>=0;i—)
                 {
                 bit = cipher->IV[i] >> 7; /* save next “carry” */
                 cipher->IV[i] = (cipher->IV[i] << 1) ^ carry;
                 carry = bit;
                 }
         }
     cipher->mode = MODE_CFB1; /* restore mode for next time */
     return inputLen;
     }

/* here for ECB, CBC modes */
for (n=0;n<inputLen;n+=BLOCK_SIZE,input+=BLOCK_SIZE/8,
                    outBuffer+=BLOCK_SIZE/8)
    {
    DebugDump (input,“\n”,rounds+1,0,0,0,1);

    for (i=0;i<BLOCK_SIZE/32;i++) /* copy and add whitening */
        x [i]=Bswap (((DWORD *)input)[i])
              ^ key->subKeys[OUTPUT_WHITEN+i];

    for (r=rounds-1;r>=0;r—)            /* main decryption loop */
        {
        t0   = f32 ( x[0] ,key->sboxKeys, key->keyLen);
        t1   = f32(ROL(x[1],8), key->sboxKeys, key->keyLen);

        DebugDump(x,“”,r+1,2*(r&1),0,1,0);
        x[2] = ROL(x[2],1);
        x[2]^= t0 + t1 + key->subKeys [ROUND_SUBKEYS+2*r ];
        x[3]^= t0 + 2*t1 + key->subKeys [ROUND_SUBKEYS+2*r+1];
        x[3] = ROR(x[3],1);

        if (r)                /* unswap, except for last round */
            {
            t0 = x[0]; x[0]= x[2]; x[2] = t0;
            t1 = x[1]; x[1]= x[3]; x[3] = t1;
            }
        }
    DebugDump (x,“”,0,0,0,0,0);

    for (i=0;i<BLOCK_SIZE/32;i++) /* copy out, with whitening */
        {
        x[i] ^= key->subKeys [INPUT_WHITEN+i];
        if (cipher->mode == MODE_CBC)
            {
            x[i] ^= cipher->iv32[i];
            cipher->iv32[i] = Bswap(((DWORD *)input)[i]);
            }
        ((DWORD *)outBuffer)[i] = Bswap(x[i]);
        }
    DebugDump (outBuffer, “”, -1,0,0,0,1);
        }
    return inputLen;
    }

DWORD TwofishCodeSize(void) { return Here(0)-TwofishCodeStart(); };


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Index

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Previous Table of Contents Next

Index

F-function 2, 9-11, 17, 18, 37, 47, 58-60, 63, 64, 72,73, 81-83, 85, 87, 91, 92, 95, 103, 143
F´-function 11, 64, 65, 143
g-function 7, 9-12, 15, 16, 18, 21, 37, 41, 48, 59-61, 65, 71, 72, 76, 83, 85, 88, 104, 125, 143
h-function 14-16, 18, 30-32, 37, 41, 48, 66, 70, 114, 144
q-box 14-16, 21, 22, 29, 31, 48-51, 69, 72, 73, 91, 114, 115, 122, 126, 130, 144, 145
16-bit CPU 3, 33, 34
3-Way 104
32-bit CPU 3, 19, 33, 34, 125
64-bit CPU 3
8-bit CPU 2-4, 19, 26, 33-35, 76, 125
6502 26
6805 2, 26, 28, 157
68040 20
Advanced Encryption Standard see AES
AES 1, 24, 34, 42, 43, 116, 129
candidate 74, 80, 121
design criteria 3, 42
process 1, 117, 130
standard 30
Akelarre 36
algebraic degree 103
Alpha CPU 29
assembly 19, 20, 22-25, 121, 157
attack
brute-force 42, 98
chosen ciphertext 38
chosen key 79
partial 109
chosen plaintext 4, 38, 104
adaptive 104
chosen-key 108, 119
collision-finding 119
differential 40, 52, 60, 75, 79, 90, 97, 99, 100, 104, 105, 112, 114, 115, 121, 130
differential-linear 103
higher-order differential 35, 40
interpolation 35, 103
keysearch 6
known plaintext 104
linear 40, 60, 76, 101, 102, 121, 130
meet-in-the-middle 79-82
non-related-key 61
non-surjective round function 40
partial key guessing 104, 126
partitioning 102
related-key 4, 36, 37, 40, 41, 48, 51, 52, 67, 76, 79, 104-108, 112, 119, 122-124, 126
differential 41, 56, 105-108, 110
slide 105
slide 40, 63, 104, 105, 112, 113, 125
statistical 36, 39, 60, 129
truncated differential 90
unknown 33, 35, 36, 100, 115
weak-key 36, 126
Bear/Lion 5
Biham, Eli 88, 105, 113
Biham-DES 39
birthday paradox 73, 113
block size 1, 7, 44, 46, 119, 120
Blowfish 5, 22, 34, 36-42, 47, 114, 121, 125, 126, 129
Borland C 19, 20, 22, 24
cache 22, 23, 25
CAST 35, 36, 38, 41
CAST-128 5, 35, 121
CBC mode 119
CBC-MAC 120
CFB mode 119, 129
characteristic
differential 48, 49, 52, 75, 76, 83, 90-93, 95-100, 103, 114, 143
2-round 115
2-round iterative 114, 115
iterative 115
trivial 115
truncated 90
iterative 60
key-dependent 75, 76
linear 48, 76, 101-103, 144
cipher
iterated 43, 104
product 5, 43
stream 1, 3, 4, 46, 121, 129
clock cycle 19, 20, 22, 24, 25, 30-32,34, 35, 57, 60
key setup 2, 21-23, 26, 28, 130
per block 2, 19, 23, 24, 26, 28, 34,
130
per byte 2, 21, 24, 34, 121
CMEA 38
code size 2, 19, 22-23, 25, 26, 28-29
complementation property 42, 75
confusion 43, 44, 103
counter mode 31, 119
CRISP 37
cryptanalysis
differential 35, 38, 39, 52, 76, 82-90, 100, 103, 115
differential-linear 103
higher-order differential 39, 90
linear 35, 52, 101-103, 116
generalised 102
non-linear 102
partitioning 102
related-key 35, 79, 104-108
differential 104
side-channel 111
power 111
timing 111
CS-Cipher 39, 41
cycle 5, 61
data-dependent rotation 34, 36
Davies-Meyer 119
Declaration of Independence 38
DES 1, 5-7, 22, 24, 26, 30, 33, 34, 37-43, 47, 61, 102, 103, 105, 116, 121
DES-X 5
DESV 58
difference sequence 52, 71
differential power analysis 111
diffusion 7, 35, 36, 43, 44, 54, 59, 125
global 129
discrete logarithm problem 116
dynamic swapping 58
ECB mode 31, 34
EEPROM 26-28
electronic emanation 111
EPIC 29
equivalent keys 40, 42, 74
factoring 116
family key 4, 38, 122-124
fault analysis Ill
FEAL 5, 33, 36, 39
FEAL-32 121
Feistel
cipher 5, 64, 113
function 113, 114, 143
half 126
network 2, 5, 34, 36, 44-48, 125
balanced 5
generalized 36
incomplete 46-47
source-heavy 46-47
target-heavy 46-47
unbalanced 5, 36
round 6, 34
structure 9, 40, 47, 54, 60, 125
two-dimensional 125
xor 31, 59, 61
Feistel, Horst 5, 44
Fields Medal 116
fixed point 49, 51
gate count 2, 4, 19, 30-32, 58, 76
GF(28) 7, 12, 13, 35, 48, 54-57, 67, 72, 145
GOST 5, 38, 104
Hamming weight 56, 71, 83, 85, 107
hardware 2-4, 6, 19, 26, 30, 35, 125,
129
hash function 1, 3, 4, 23, 41, 42, 79, 119, 120, 130
HAVAL 58
ICE 41
IDEA 33, 36, 37, 39, 41, 42, 46, 61, 75,121
interleave 31, 32, 34
Java 25
Jeroboam 33
key agility 4, 23, 28-29, 42
key schedule 2, 4, 7, 12, 21, 33, 36, 37, 40-42, 61, 63-77, 104, 125, 129
keysetup 19, 20, 22, 23, 28, 30, 40, 42
time 2, 3, 21, 22, 25, 27, 28, 35, 126
key stretching 42
keying
compiled 22-24, 57
full 21-24
minimal 21, 24
option 19, 21, 22
partial 21-24
zero 21, 22, 24
Khafre 5, 33, 38, 39, 46
Khufu 5, 33, 38, 39, 42, 46, 126
Kiefer 35
KN-cipher 35
Latin square 58
LEA opcode 22, 57, 125
little-endian convention 9, 11, 122
LOKI 5, 39, 41
LOK189 33, 39
LOK191 33, 39
LOK197 39
Lucifer 5, 6, 44, 75
MAC see message authentication code
MacGuffin 5, 46
Madryga 36
magic constant 115, 116
Manta 7
master-key cryptosystem 116
Matsui, Mitsuru 48
maximum distance separable see MDS
MD4 46, 58
MD5 46, 58
MDS code 6
MDS matrix 2, 6, 7, 9, 10, 12, 13, 15, 18, 21-23, 27, 28, 31, 32, 34-37, 41, 54-61, 66-68, 70, 72, 83, 90, 91, 93-95, 103, 115, 125, 126, 130, 143, 145
Merced 3, 29
Merkle, Ralph 5
message authentication code 1, 3, 4, 120
Microsoft Visual C 19, 20, 23, 24
MISTY 35
MMB 36
multiple linear approximations 102
NewDES 38
NIST 1, 3, 34, 74 NMR scanning 111
non-bijective S-box 114
nonce 120
NSA 32, 42
OFB mode 119, 129
Panama 37
Pentium 3, 20, 22-25, 30, 34, 35, 49, 60, 67, 73, 74, 121, 125, 130, 157
Pentium family 7, 29, 35, 57, 58, 61
Pentium II 3, 19, 20, 23-25, 29, 30, 130, 157
Pentium MMX 22, 23, 25
Pentium Pro 2, 3, 19, 20, 22-25, 29, 30, 34, 60, 130, 157
Philips 30
PHT 7, 9-11, 16, 18, 22, 31, 32, 36, 37, 54, 55, 57-59, 61, 65, 71, 72, 75, 83, 85, 88, 91, 93, 95, 101, 103, 113, 125, 126
pipeline 31, 32, 59, 61
Power PC 19, 20
primitive polynomial 12, 13, 55, 76
PRNG 1, 4, 41, 120, 130
pseudo-Hadamaxd transform see PHT
public-key
algorithm 116
cryptosystem 116
quasi-weak keys 42
RAM 4, 21, 22, 26-31, 39, 73, 74, 77
RAND tables 38
RC2 33, 46
RC4 34, 37
RC5 5, 34, 36, 41, 121
REDOC-II 33, 36, 39
Reed-Solomon see RS
RIPE-MD 58
RIPEMD-160 58
Rivest, Ron 5
ROM 26-29, 31, 39, 76
rotor machine 44, 49
round function 2, 7, 10, 17, 18, 30, 31, 33-37, 41, 43, 46, 54, 55, 59, 60, 65, 72, 74, 76, 92, 96, 101-104, 114, 125, 126,129, 144
non-surjective 114
RS code 6, 13, 37, 41, 56, 106, 115
RS matrix 13, 26, 49, 76-77, 105-107, 111, 122, 145
S-1 40, 104
SAFER 5, 7, 36, 37, 39, 41, 44, 60, 121, 125
SAFER-K64 121
SEAL 33, 34, 39, 42, 126
self-inverse keys 40, 74
semi-weak keys 42, 75
Serpent 30, 34, 37, 38, 41, 121
session key 120
Seuss, Dr. 127
SHA 39, 58
SHA-1 46
Shannon, C. 44
Shark 5, 6, 41, 44
Skipjack 5, 40, 42, 46, 61
smart card 2, 19, 26-29, 34, 35, 58, 60, 125, 129
SNAKE 35
sn DES 38
SOBER 33
SP network 5, 7, 44, 46-48
SPEED 33, 121
Square 6, 36, 37, 39, 44, 54, 60, 121,125
subkey
permuting the 105
subkey difference
chosen 106
swapping key halves 105
symbols, overview 143
symmetric algorithm 1, 116
TEA 36
TEMPEST 111
test vectors 147
throughput 21, 28, 29, 31, 32, 43
Tiger 38, 46
trap door 115
Travois 104
Triple-DES 1, 121
twist 126
Twofish
definition 9
history 125
name 126
overview 10
performance 19
simplified 112
with non-bijective S-boxes 114
without round keys 112
Twofish-FK 122
Ultra-SPARC 19, 20
uniform transformation structure 5
Vaudenay, Serge 6, 114
VLIW 30
WAKE 38, 39
weak keys 3, 40, 42, 48, 74, 75
web site 157
whitening 4-6, 9-11, 60, 63, 66, 79-82, 87-89, 109, 116, 119, 123, 144
post- 81, 122, 144
pre- 81, 82, 122, 144
YLCY 39
YTH 37
Zhu-Guo 33


The Twofish Encryption Algorithm A 128-Bit Block Cipher:Table of Contents

by Bruce Schneier ; John Kelsey ; Doug Whiting ; David Wagner ; Chris Hall ; Niels Ferguson
Wiley Computer Publishing, John Wiley & Sons, Inc.
ISBN: 0471353817 Pub Date: 03/01/99

Preface

Chapter 1—Introduction
Chapter 2—Twofish Design Goals
Chapter 3—Twofish Building Blocks
3.1 Feistel Networks
3.2 Whitening
3.3 S-boxes
3.4 MDS Matrices
3.5 Pseudo-Hadamard Transforms
3.6 Key Schedule
Chapter 4—Twofish
4.1 The Function F
4.2 The Function g
4.3 The Key Schedule
4.3.1 Additional Key Lengths
4.3.2 The Function h
4.3.3 The Key-dependent S-boxes
4.3.4 The Expanded Key Words Kj
4.3.5 The Permutations q0 and q1
4.4 Round Function Overview
Chapter 5—Performance of Twofish
5.1 Performance on Large Microprocessors
5.1.1 Keying Options
5.1.2 Code and Data Size
5.1.3 Large Memory Implementations
5.1.4 Total Encryption Times
5.1.5 Hash Function Performance
5.1.6 Language, Compiler, and Processor Choice
5.2 Performance on Smart Cards
5.2.1 RAM Usage
5.2.2 Encryption Speed and Key Agility
5.2.3 Code Size
5.3 Performance on the Alpha
5.4 Performance on Future Microprocessors
5.5 Hardware Performance
Chapter 6—Twofish Design Philosophy
6.1 Performance-Driven Design
6.1.1 Performance-driven Tradeoffs
6.2 Conservative Design
6.3 Simple Design
6.3.1 Reusing Primitives
6.3.2 Reversibility
6.4 S-boxes
6.4.1 Large S-boxes
6.4.2 Algorithmic S-boxes
6.4.3 Key-dependent S-boxes
6.5 The Key Schedule
6.5.1 Performance Issues
Chapter 7—The Design of Twofish
7.1 The Round Structure
7.1.1 Common Block Cipher Structures
7.2 The Key-dependent S-boxes
7.2.1 The Fixed Permutations q0 and q1
7.2.2 The S-boxes.
7.2.3 Exhaustive and Statistical Analysis
7.3 MDS Matrix
7.3.1 Non-key-dependent Coefficients
7.3.2 Implementation Issues
7.3.3 Preserving Diffusion Properties after Rotation
7.3.4 Rotational Uniqueness of Output Vectors
7.3.5 Maximizing the Minimal Hamming Distance
7.4 PHT
7.4.1 Eliminating the PHT
7.4.2 Diffusion and the Least Significant Bit
7.5 Key Addition
7.6 Feistel Combining Operation
7.7 Use of Different Groups
7.8 Diffusion in the Round Function
7.8.1 Changes Induced by F
7.9 One-bit Rotation
7.9.1 Reason for Rotations
7.9.2 Downsides to Rotations
7.9.3 Converting to a Pure Feistel Structure
7.10 The Number of Rounds
Chapter 8—Design of the Twofish Key Schedule
8.1 Round Subkeys
8.1.1 Equivalence of Round Subkeys
8.1.2 Equivalent keys
8.2 Controlling Changes in Round Subkeys
8.2.1 XOR Difference Sequences in A and B
8.2.2 Byte Sequences with Given Difference
8.2.3 Identical Byte Sequences
8.2.4 The A and B Sequences
8.2.5 The Sequence (K2i, K2i+1)
8.2.6 Difference Sequences in the Subkeys
8.3 The Round Function
8.4 Properties of the Key Schedule and Cipher
8.4.1 Equivalent Keys
8.4.2 Self-Inverse Keys
8.4.3 Pairs of Inverse Keys
8.4.4 Simple Relations
8.5 Key-dependent Characteristics and Weak Keys
8.6 Reed-Solomon Code
Chapter 9—Cryptanalysis of Twofish
9.1 A Meet-in-the-Middle Attack on Twofish
9.1.1 Results of the Attack
9.1.2 Overview of the Attack
9.1.3 Attacking Twofish with Fixed S and no Whitening
9.1.4 Attacking Twofish with Fixed S
9.1.5 Attacking Normal Twofish
9.2 Differential Cryptanalysis
9.2.1 Results of the Attack
9.2.2 Overview of the Attack
9.2.3 Building the Batches
9.2.4 Mounting the Attack
9.2.5 Lessons from the Analysis
9.3 Extensions to Differential Cryptanalysis
9.3.1 Higher-Order Differential Cryptanalysis
9.3.2 Truncated Differentials
9.4 Search for the Best Differential Characteristic
9.4.1 Differentials of the S-boxes
9.4.2 Differentials of F
9.4.3 Differentials of the Round Function
9.4.4 Multi-round Patterns
9.4.5 Results
9.4.6 Other Problems for the Attacker
9.4.7 Best S-box Differential
9.4.8 Other Variants
9.4.9 Further Work
9.4.10 Conclusion
9.5 Linear Cryptanalysis
9.5.1 Multiple Linear Approximations
9.5.2 Non-linear Cryptanalysis
9.5.3 Generalized Linear Cryptanalysis
9.5.4 Partitioning Cryptanalysis
9.5.5 Differential-linear Cryptanalysis
9.6 Interpolation Attack
9.7 Partial Key Guessing Attacks
9.8 Related-key Cryptanalysis
9.8.1 Resistance to Related-key Slide Attacks
9.8.2 Resistance to Related-key Differential Attacks
9.8.3 The Zero Difference Case
9.8.4 Other Difference Sequences
9.8.5 Probability of a Successful Attack with One Related-key Query
9.8.6 Conclusions
9.9 A Chosen-key Attack
9.9.1 Overview of the Attack
9.9.2 Finding a Key Pair
9.9.3 Choosing the Plaintexts to Request
9.9.4 Extracting the Key Material
9.10 Side-Channel Cryptanalysis and Fault Analysis
9.11 Attacking Simplified Twofish
9.11.1 Twofish with Known S-boxes
9.11.2 Twofish without Round Subkeys
9.11.3 Twofish with Non-bijective S-boxes
9.12 Trap Doors in Twofish
Chapter 10—Using Twofish
10.1 Chaining Modes
10.2 One-Way Hash Rinctions
10.3 Message Authentication Codes
10.4 Pseudorandom Number Generators
10.5 Larger Keys
10.6 Additional Block Sizes
10.7 More or Fewer Rounds
10.8 Family Key Variant: Twofish-FK
10.8.1 Analysis
Chapter 11—Historical Remarks
Chapter 12—Conclusions and Further Work
References
Appendix A
Appendix B
Appendix C
Index