1 /*
2  *
3  *
4  * Copyright (C) 1997-2000 The Cryptix Foundation Limited.
5  * Copyright (C) 2000 Farm9.
6  * Copyright (C) 2001 Frank Knobbe.
7  * All rights reserved.
8  *
9  * For Cryptix code:
10  * Use, modification, copying and distribution of this software is subject
11  * the terms and conditions of the Cryptix General Licence. You should have
12  * received a copy of the Cryptix General Licence along with this library;
13  * if not, you can download a copy from http://www.cryptix.org/ .
14  *
15  * For Farm9:
16  * ---  jojo@farm9.com, August 2000, converted from Java to C++, added CBC mode and
17  *      ciphertext stealing technique, added AsciiTwofish class for easy encryption
18  *      decryption of text strings
19  *
20  * Frank Knobbe <frank@knobbe.us>:
21  * ---  April 2001, converted from C++ to C, prefixed global variables
22  *      with TwoFish, substituted some defines, changed functions to make use of
23  *      variables supplied in a struct, modified and added routines for modular calls.
24  *      Cleaned up the code so that defines are used instead of fixed 16's and 32's.
25  *      Created two general purpose crypt routines for one block and multiple block
26  *      encryption using Joh's CBC code.
27  *		Added crypt routines that use a header (with a magic and data length).
28  *		(Basically a major rewrite).
29  *
30  *      Note: Routines labeled _TwoFish are private and should not be used
31  *      (or with extreme caution).
32  *
33  */
34 
35 #ifndef __TWOFISH_LIBRARY_SOURCE__
36 #define __TWOFISH_LIBRARY_SOURCE__
37 
38 #include <string.h>
39 #include <stdlib.h>
40 #include <time.h>
41 #include <ctype.h>
42 #include <sys/types.h>
43 
44 #ifdef WIN32
45 
46 #ifndef u_long
47 typedef unsigned long u_long;
48 #endif
49 #ifndef uint32_t
50 typedef unsigned long uint32_t;
51 #endif
52 #ifndef u_word
53 typedef unsigned short u_word;
54 #endif
55 #ifndef uint16_t
56 typedef unsigned short uint16_t;
57 #endif
58 #ifndef u_char
59 typedef unsigned char u_char;
60 #endif
61 #ifndef uint8_t
62 typedef unsigned char uint8_t;
63 #endif
64 
65 #endif /* WIN32 */
66 
67 #include "twofish.h"
68 
69 
70 bool TwoFish_srand=TRUE;				/* if TRUE, first call of TwoFishInit will seed rand(); */
71 										/* of TwoFishInit */
72 
73 /* Fixed 8x8 permutation S-boxes */
74 static const uint8_t TwoFish_P[2][256] =
75 {
76     {  /* p0 */
77         0xA9, 0x67, 0xB3, 0xE8,   0x04, 0xFD, 0xA3, 0x76,   0x9A, 0x92, 0x80, 0x78,
78         0xE4, 0xDD, 0xD1, 0x38,   0x0D, 0xC6, 0x35, 0x98,   0x18, 0xF7, 0xEC, 0x6C,
79         0x43, 0x75, 0x37, 0x26,   0xFA, 0x13, 0x94, 0x48,   0xF2, 0xD0, 0x8B, 0x30,
80         0x84, 0x54, 0xDF, 0x23,   0x19, 0x5B, 0x3D, 0x59,   0xF3, 0xAE, 0xA2, 0x82,
81         0x63, 0x01, 0x83, 0x2E,   0xD9, 0x51, 0x9B, 0x7C,   0xA6, 0xEB, 0xA5, 0xBE,
82         0x16, 0x0C, 0xE3, 0x61,   0xC0, 0x8C, 0x3A, 0xF5,   0x73, 0x2C, 0x25, 0x0B,
83         0xBB, 0x4E, 0x89, 0x6B,   0x53, 0x6A, 0xB4, 0xF1,   0xE1, 0xE6, 0xBD, 0x45,
84         0xE2, 0xF4, 0xB6, 0x66,   0xCC, 0x95, 0x03, 0x56,   0xD4, 0x1C, 0x1E, 0xD7,
85         0xFB, 0xC3, 0x8E, 0xB5,   0xE9, 0xCF, 0xBF, 0xBA,   0xEA, 0x77, 0x39, 0xAF,
86         0x33, 0xC9, 0x62, 0x71,   0x81, 0x79, 0x09, 0xAD,   0x24, 0xCD, 0xF9, 0xD8,
87         0xE5, 0xC5, 0xB9, 0x4D,   0x44, 0x08, 0x86, 0xE7,   0xA1, 0x1D, 0xAA, 0xED,
88         0x06, 0x70, 0xB2, 0xD2,   0x41, 0x7B, 0xA0, 0x11,   0x31, 0xC2, 0x27, 0x90,
89         0x20, 0xF6, 0x60, 0xFF,   0x96, 0x5C, 0xB1, 0xAB,   0x9E, 0x9C, 0x52, 0x1B,
90         0x5F, 0x93, 0x0A, 0xEF,   0x91, 0x85, 0x49, 0xEE,   0x2D, 0x4F, 0x8F, 0x3B,
91         0x47, 0x87, 0x6D, 0x46,   0xD6, 0x3E, 0x69, 0x64,   0x2A, 0xCE, 0xCB, 0x2F,
92         0xFC, 0x97, 0x05, 0x7A,   0xAC, 0x7F, 0xD5, 0x1A,   0x4B, 0x0E, 0xA7, 0x5A,
93         0x28, 0x14, 0x3F, 0x29,   0x88, 0x3C, 0x4C, 0x02,   0xB8, 0xDA, 0xB0, 0x17,
94         0x55, 0x1F, 0x8A, 0x7D,   0x57, 0xC7, 0x8D, 0x74,   0xB7, 0xC4, 0x9F, 0x72,
95         0x7E, 0x15, 0x22, 0x12,   0x58, 0x07, 0x99, 0x34,   0x6E, 0x50, 0xDE, 0x68,
96         0x65, 0xBC, 0xDB, 0xF8,   0xC8, 0xA8, 0x2B, 0x40,   0xDC, 0xFE, 0x32, 0xA4,
97         0xCA, 0x10, 0x21, 0xF0,   0xD3, 0x5D, 0x0F, 0x00,   0x6F, 0x9D, 0x36, 0x42,
98         0x4A, 0x5E, 0xC1, 0xE0
99     },
100     {  /* p1 */
101         0x75, 0xF3, 0xC6, 0xF4,   0xDB, 0x7B, 0xFB, 0xC8,   0x4A, 0xD3, 0xE6, 0x6B,
102         0x45, 0x7D, 0xE8, 0x4B,   0xD6, 0x32, 0xD8, 0xFD,   0x37, 0x71, 0xF1, 0xE1,
103         0x30, 0x0F, 0xF8, 0x1B,   0x87, 0xFA, 0x06, 0x3F,   0x5E, 0xBA, 0xAE, 0x5B,
104         0x8A, 0x00, 0xBC, 0x9D,   0x6D, 0xC1, 0xB1, 0x0E,   0x80, 0x5D, 0xD2, 0xD5,
105         0xA0, 0x84, 0x07, 0x14,   0xB5, 0x90, 0x2C, 0xA3,   0xB2, 0x73, 0x4C, 0x54,
106         0x92, 0x74, 0x36, 0x51,   0x38, 0xB0, 0xBD, 0x5A,   0xFC, 0x60, 0x62, 0x96,
107         0x6C, 0x42, 0xF7, 0x10,   0x7C, 0x28, 0x27, 0x8C,   0x13, 0x95, 0x9C, 0xC7,
108         0x24, 0x46, 0x3B, 0x70,   0xCA, 0xE3, 0x85, 0xCB,   0x11, 0xD0, 0x93, 0xB8,
109         0xA6, 0x83, 0x20, 0xFF,   0x9F, 0x77, 0xC3, 0xCC,   0x03, 0x6F, 0x08, 0xBF,
110 		0x40, 0xE7, 0x2B, 0xE2,   0x79, 0x0C, 0xAA, 0x82,   0x41, 0x3A, 0xEA, 0xB9,
111         0xE4, 0x9A, 0xA4, 0x97,   0x7E, 0xDA, 0x7A, 0x17,   0x66, 0x94, 0xA1, 0x1D,
112         0x3D, 0xF0, 0xDE, 0xB3,   0x0B, 0x72, 0xA7, 0x1C,   0xEF, 0xD1, 0x53, 0x3E,
113         0x8F, 0x33, 0x26, 0x5F,   0xEC, 0x76, 0x2A, 0x49,   0x81, 0x88, 0xEE, 0x21,
114         0xC4, 0x1A, 0xEB, 0xD9,   0xC5, 0x39, 0x99, 0xCD,   0xAD, 0x31, 0x8B, 0x01,
115         0x18, 0x23, 0xDD, 0x1F,   0x4E, 0x2D, 0xF9, 0x48,   0x4F, 0xF2, 0x65, 0x8E,
116         0x78, 0x5C, 0x58, 0x19,   0x8D, 0xE5, 0x98, 0x57,   0x67, 0x7F, 0x05, 0x64,
117         0xAF, 0x63, 0xB6, 0xFE,   0xF5, 0xB7, 0x3C, 0xA5,   0xCE, 0xE9, 0x68, 0x44,
118         0xE0, 0x4D, 0x43, 0x69,   0x29, 0x2E, 0xAC, 0x15,   0x59, 0xA8, 0x0A, 0x9E,
119         0x6E, 0x47, 0xDF, 0x34,   0x35, 0x6A, 0xCF, 0xDC,   0x22, 0xC9, 0xC0, 0x9B,
120         0x89, 0xD4, 0xED, 0xAB,   0x12, 0xA2, 0x0D, 0x52,   0xBB, 0x02, 0x2F, 0xA9,
121         0xD7, 0x61, 0x1E, 0xB4,   0x50, 0x04, 0xF6, 0xC2,   0x16, 0x25, 0x86, 0x56,
122         0x55, 0x09, 0xBE, 0x91
123     }
124 };
125 
126 static bool TwoFish_MDSready=FALSE;
127 static uint32_t TwoFish_MDS[4][256]; /* TwoFish_MDS matrix */
128 
129 
130 #define	TwoFish_LFSR1(x) (((x)>>1)^(((x)&0x01)?TwoFish_MDS_GF_FDBK/2:0))
131 #define	TwoFish_LFSR2(x) (((x)>>2)^(((x)&0x02)?TwoFish_MDS_GF_FDBK/2:0)^(((x)&0x01)?TwoFish_MDS_GF_FDBK/4:0))
132 
133 #define	TwoFish_Mx_1(x) ((uint32_t)(x))		/* force result to dword so << will work  */
134 #define	TwoFish_Mx_X(x) ((uint32_t)((x)^TwoFish_LFSR2(x)))	/* 5B */
135 #define	TwoFish_Mx_Y(x) ((uint32_t)((x)^TwoFish_LFSR1(x)^TwoFish_LFSR2(x)))	/* EF  */
136 #define	TwoFish_RS_rem(x) { uint8_t b=(uint8_t)(x>>24); uint32_t g2=((b<<1)^((b&0x80)?TwoFish_RS_GF_FDBK:0))&0xFF; uint32_t g3=((b>>1)&0x7F)^((b&1)?TwoFish_RS_GF_FDBK>>1:0)^g2; x=(x<<8)^(g3<<24)^(g2<<16)^(g3<<8)^b; }
137 
138 /*#define	TwoFish__b(x,N)	(((uint8_t *)&x)[((N)&3)^TwoFish_ADDR_XOR])*/ /* pick bytes out of a dword */
139 
140 #define	TwoFish_b0(x)			TwoFish__b(x,0)		/* extract LSB of uint32_t  */
141 #define	TwoFish_b1(x)			TwoFish__b(x,1)
142 #define	TwoFish_b2(x)			TwoFish__b(x,2)
143 #define	TwoFish_b3(x)			TwoFish__b(x,3)		/* extract MSB of uint32_t  */
144 
TwoFish__b(uint32_t x,int n)145 uint8_t TwoFish__b(uint32_t x,int n)
146 {	n&=3;
147 	while(n-->0)
148 		x>>=8;
149 	return (uint8_t)x;
150 }
151 
152 
153 /*	TwoFish Initialization
154  *
155  *	This routine generates a global data structure for use with TwoFish,
156  *	initializes important values (such as subkeys, sBoxes), generates subkeys
157  *	and precomputes the MDS matrix if not already done.
158  *
159  *	Input:	User supplied password (will be appended by default password of 'SnortHas2FishEncryptionRoutines!')
160  *
161  *  Output:	Pointer to TWOFISH structure. This data structure contains key dependent data.
162  *			This pointer is used with all other crypt functions.
163  */
164 
TwoFishInit(char * userkey)165 TWOFISH *TwoFishInit(char *userkey)
166 {   TWOFISH *tfdata;
167 	int i,x,m;
168 	char tkey[TwoFish_KEY_LENGTH+40];
169 
170 	tfdata=malloc(sizeof(TWOFISH));			/* allocate the TwoFish structure */
171 	if(tfdata!=NULL)
172 	{	if(*userkey)
173 		{	strncpy(tkey,userkey,TwoFish_KEY_LENGTH);			/* use first 32 chars of user supplied password */
174 			tkey[TwoFish_KEY_LENGTH]=0;							/* make sure it wasn't more */
175 		}
176 		else
177 			strcpy(tkey,TwoFish_DEFAULT_PW);	/* if no key defined, use default password */
178 		for(i=0,x=0,m=strlen(tkey);i<TwoFish_KEY_LENGTH;i++)	/* copy into data structure */
179 		{	tfdata->key[i]=tkey[x++];							/* fill the whole keyspace with repeating key. */
180 			if(x==m)
181 				x=0;
182 		}
183 
184 		if(!TwoFish_MDSready)
185 			_TwoFish_PrecomputeMDSmatrix();		/* "Wake Up, Neo" */
186 		_TwoFish_MakeSubKeys(tfdata);			/* generate subkeys */
187 		_TwoFish_ResetCBC(tfdata);				/* reset the CBC */
188 		tfdata->output=NULL;					/* nothing to output yet */
189 		tfdata->dontflush=FALSE;				/* reset decrypt skip block flag */
190 		if(TwoFish_srand)
191 		{	TwoFish_srand=FALSE;
192 			srand(time(NULL));
193 		}
194 	}
195 	return tfdata;							/* return the data pointer */
196 }
197 
198 
TwoFishDestroy(TWOFISH * tfdata)199 void TwoFishDestroy(TWOFISH *tfdata)
200 {	if(tfdata!=NULL)
201 		free(tfdata);
202 }
203 
204 
205 /* en/decryption with CBC mode */
_TwoFish_CryptRawCBC(char * in,char * out,unsigned long len,bool decrypt,TWOFISH * tfdata)206 unsigned long _TwoFish_CryptRawCBC(char *in,char *out,unsigned long len,bool decrypt,TWOFISH *tfdata)
207 {	unsigned long rl;
208 
209 	rl=len;											/* remember how much data to crypt. */
210 	while(len>TwoFish_BLOCK_SIZE)					/* and now we process block by block. */
211 	{	_TwoFish_BlockCrypt((uint8_t *)in,(uint8_t *)out,TwoFish_BLOCK_SIZE,decrypt,tfdata); /* de/encrypt it. */
212 		in+=TwoFish_BLOCK_SIZE;						/* adjust pointers. */
213 		out+=TwoFish_BLOCK_SIZE;
214 		len-=TwoFish_BLOCK_SIZE;
215 	}
216 	if(len>0)										/* if we have less than a block left... */
217 		_TwoFish_BlockCrypt((uint8_t *)in,(uint8_t *)out,len,decrypt,tfdata);	/* ...then we de/encrypt that too. */
218 	if(tfdata->qBlockDefined && !tfdata->dontflush)						/* in case len was exactly one block... */
219 		_TwoFish_FlushOutput(tfdata->qBlockCrypt,TwoFish_BLOCK_SIZE,tfdata); /* ...we need to write the...  */
220 																		/* ...remaining bytes of the buffer */
221 	return rl;
222 }
223 
224 /* en/decryption on one block only */
_TwoFish_CryptRaw16(char * in,char * out,unsigned long len,bool decrypt,TWOFISH * tfdata)225 unsigned long _TwoFish_CryptRaw16(char *in,char *out,unsigned long len,bool decrypt,TWOFISH *tfdata)
226 {	/* qBlockPlain already zero'ed through ResetCBC  */
227 	memcpy(tfdata->qBlockPlain,in,len);					/* toss the data into it. */
228 	_TwoFish_BlockCrypt16(tfdata->qBlockPlain,tfdata->qBlockCrypt,decrypt,tfdata); /* encrypt just that block without CBC. */
229 	memcpy(out,tfdata->qBlockCrypt,TwoFish_BLOCK_SIZE);				/* and return what we got */
230 	return TwoFish_BLOCK_SIZE;
231 }
232 
233 /* en/decryption without reset of CBC and output assignment */
_TwoFish_CryptRaw(char * in,char * out,unsigned long len,bool decrypt,TWOFISH * tfdata)234 unsigned long _TwoFish_CryptRaw(char *in,char *out,unsigned long len,bool decrypt,TWOFISH *tfdata)
235 {
236 	if(in!=NULL && out!=NULL && len>0 && tfdata!=NULL)		/* if we have valid data, then... */
237 	{	if(len>TwoFish_BLOCK_SIZE)							/* ...check if we have more than one block. */
238 			return _TwoFish_CryptRawCBC(in,out,len,decrypt,tfdata); /* if so, use the CBC routines... */
239 		else
240 			return _TwoFish_CryptRaw16(in,out,len,decrypt,tfdata); /* ...otherwise just do one block. */
241 	}
242 	return 0;
243 }
244 
245 
246 /*	TwoFish Raw Encryption
247  *
248  *	Does not use header, but does use CBC (if more than one block has to be encrypted).
249  *
250  *	Input:	Pointer to the buffer of the plaintext to be encrypted.
251  *			Pointer to the buffer receiving the ciphertext.
252  *			The length of the plaintext buffer.
253  *			The TwoFish structure.
254  *
255  *	Output:	The amount of bytes encrypted if successful, otherwise 0.
256  */
257 
TwoFishEncryptRaw(char * in,char * out,unsigned long len,TWOFISH * tfdata)258 unsigned long TwoFishEncryptRaw(char *in,
259 								char *out,
260 								unsigned long len,
261 								TWOFISH *tfdata)
262 {	_TwoFish_ResetCBC(tfdata);							/* reset CBC flag. */
263 	tfdata->output=(uint8_t *)out;							/* output straight into output buffer. */
264 	return _TwoFish_CryptRaw(in,out,len,FALSE,tfdata);	/* and go for it. */
265 }
266 
267 /*	TwoFish Raw Decryption
268  *
269  *	Does not use header, but does use CBC (if more than one block has to be decrypted).
270  *
271  *	Input:	Pointer to the buffer of the ciphertext to be decrypted.
272  *			Pointer to the buffer receiving the plaintext.
273  *			The length of the ciphertext buffer (at least one cipher block).
274  *			The TwoFish structure.
275  *
276  *	Output:	The amount of bytes decrypted if successful, otherwise 0.
277  */
278 
TwoFishDecryptRaw(char * in,char * out,unsigned long len,TWOFISH * tfdata)279 unsigned long TwoFishDecryptRaw(char *in,
280 								char *out,
281 								unsigned long len,
282 								TWOFISH *tfdata)
283 {	_TwoFish_ResetCBC(tfdata);							/* reset CBC flag. */
284 	tfdata->output=(uint8_t *)out;							/* output straight into output buffer. */
285 	return _TwoFish_CryptRaw(in,out,len,TRUE,tfdata);	/* and go for it. */
286 }
287 
288 /*	TwoFish Free
289  *
290  *	Free's the allocated buffer.
291  *
292  *	Input:	Pointer to the TwoFish structure
293  *
294  *	Output:	(none)
295  */
296 
TwoFishFree(TWOFISH * tfdata)297 void TwoFishFree(TWOFISH *tfdata)
298 {	if(tfdata->output!=NULL)	/* if a valid buffer is present... */
299 	{	free(tfdata->output);	/* ...then we free it for you... */
300 		tfdata->output=NULL;	/* ...and mark as such. */
301 	}
302 }
303 
304 /*	TwoFish Set Output
305  *
306  *	If you want to allocate the output buffer yourself,
307  *	then you can set it with this function.
308  *
309  *	Input:	Pointer to your output buffer
310  *			Pointer to the TwoFish structure
311  *
312  *	Output:	(none)
313  */
314 
TwoFishSetOutput(char * outp,TWOFISH * tfdata)315 void TwoFishSetOutput(char *outp,TWOFISH *tfdata)
316 {	tfdata->output=(uint8_t *)outp;				/* (do we really need a function for this?) */
317 }
318 
319 /*	TwoFish Alloc
320  *
321  *	Allocates enough memory for the output buffer that would be required
322  *
323  *	Input:	Length of the plaintext.
324  *			Boolean flag for BinHex Output.
325  *			Pointer to the TwoFish structure.
326  *
327  *	Output:	Returns a pointer to the memory allocated.
328  */
329 
TwoFishAlloc(unsigned long len,bool binhex,bool decrypt,TWOFISH * tfdata)330 void *TwoFishAlloc(unsigned long len,bool binhex,bool decrypt,TWOFISH *tfdata)
331 {
332 /*	TwoFishFree(tfdata);	*/			/* (don't for now) discard whatever was allocated earlier. */
333 	if(decrypt)							/* if decrypting... */
334 	{	if(binhex)						/* ...and input is binhex encoded... */
335 			len/=2;						/* ...use half as much for output. */
336 		len-=TwoFish_BLOCK_SIZE;		/* Also, subtract the size of the header. */
337 	}
338 	else
339 	{	len+=TwoFish_BLOCK_SIZE;		/* the size is just increased by the header... */
340 		if(binhex)
341 			len*=2;						/* ...and doubled if output is to be binhexed. */
342 	}
343 	tfdata->output=malloc(len+TwoFish_BLOCK_SIZE);/* grab some memory...plus some extra (it's running over somewhere, crashes without extra padding) */
344 
345 	return tfdata->output;				/* ...and return to caller. */
346 }
347 
348 /* bin2hex and hex2bin conversion */
_TwoFish_BinHex(uint8_t * buf,unsigned long len,bool bintohex)349 void _TwoFish_BinHex(uint8_t *buf,unsigned long len,bool bintohex)
350 {	uint8_t *pi,*po,c;
351 
352 	if(bintohex)
353 	{	for(pi=buf+len-1,po=buf+(2*len)-1;len>0;pi--,po--,len--) /* let's start from the end of the bin block. */
354 		{	c=*pi;												 /* grab value. */
355 			c&=15;												 /* use lower 4 bits. */
356 			if(c>9)												 /* convert to ascii. */
357 				c+=('a'-10);
358 			else
359 				c+='0';
360 			*po--=c;											 /* set the lower nibble. */
361 			c=*pi;												 /* grab value again. */
362 			c>>=4;												 /* right shift 4 bits. */
363 			c&=15;												 /* make sure we only have 4 bits. */
364 			if(c>9)												 /* convert to ascii. */
365 				c+=('a'-10);
366 			else
367 				c+='0';
368 			*po=c;												 /* set the higher nibble. */
369 		}														 /* and keep going. */
370 	}
371 	else
372 	{	for(pi=buf,po=buf;len>0;pi++,po++,len-=2)				 /* let's start from the beginning of the hex block. */
373 		{	c=tolower(*pi++)-'0';								 /* grab higher nibble. */
374 			if(c>9)												 /* convert to value. */
375 				c-=('0'-9);
376 			*po=c<<4;											 /* left shit 4 bits. */
377 			c=tolower(*pi)-'0';									 /* grab lower nibble. */
378 			if(c>9)												 /* convert to value. */
379 				c-=('0'-9);
380 			*po|=c;												 /* and add to value. */
381 		}
382 	}
383 }
384 
385 
386 /*	TwoFish Encryption
387  *
388  *	Uses header and CBC. If the output area has not been intialized with TwoFishAlloc,
389  *  this routine will alloc the memory. In addition, it will include a small 'header'
390  *  containing the magic and some salt. That way the decrypt routine can check if the
391  *  packet got decrypted successfully, and return 0 instead of garbage.
392  *
393  *	Input:	Pointer to the buffer of the plaintext to be encrypted.
394  *			Pointer to the pointer to the buffer receiving the ciphertext.
395  *				The pointer either points to user allocated output buffer space, or to NULL, in which case
396  *				this routine will set the pointer to the buffer allocated through the struct.
397  *			The length of the plaintext buffer.
398  *				Can be -1 if the input is a null terminated string, in which case we'll count for you.
399  *			Boolean flag for BinHex Output (if used, output will be twice as large as input).
400  *				Note: BinHex conversion overwrites (converts) input buffer!
401  *			The TwoFish structure.
402  *
403  *	Output:	The amount of bytes encrypted if successful, otherwise 0.
404  */
405 
TwoFishEncrypt(char * in,char ** out,signed long len,bool binhex,TWOFISH * tfdata)406 unsigned long TwoFishEncrypt(char *in,
407 							 char **out,
408 							 signed long len,
409 							 bool binhex,
410 							 TWOFISH *tfdata)
411 {	unsigned long ilen,olen;
412 
413 
414 	if(len== -1)			/* if we got -1 for len, we'll assume IN is a...  */
415 		ilen=strlen(in);	/* ...\0 terminated string and figure len out ourselves... */
416 	else
417 		ilen=len;			/* ...otherwise we trust you supply a correct length. */
418 
419 	if(in!=NULL && out!=NULL && ilen>0 && tfdata!=NULL) /* if we got usable stuff, we'll do it. */
420 	{	if(*out==NULL)									/* if OUT points to a NULL pointer... */
421 			*out=TwoFishAlloc(ilen,binhex,FALSE,tfdata);  /* ...we'll (re-)allocate buffer space. */
422 		if(*out!=NULL)
423 		{	tfdata->output=(uint8_t *)*out;							/* set output buffer. */
424 			tfdata->header.salt=rand()*65536+rand();		/* toss in some salt. */
425 			tfdata->header.length[0]= (uint8_t)(ilen);
426 			tfdata->header.length[1]= (uint8_t)(ilen>>8);
427 			tfdata->header.length[2]= (uint8_t)(ilen>>16);
428 			tfdata->header.length[3]= (uint8_t)(ilen>>24);
429 			memcpy(tfdata->header.magic,TwoFish_MAGIC,TwoFish_MAGIC_LEN); /* set the magic. */
430 			olen=TwoFish_BLOCK_SIZE;						/* set output counter. */
431 			_TwoFish_ResetCBC(tfdata);						/* reset the CBC flag */
432 			_TwoFish_BlockCrypt((uint8_t *)&(tfdata->header),(uint8_t *)*out,olen,FALSE,tfdata); /* encrypt first block (without flush on 16 byte boundary). */
433 			olen+=_TwoFish_CryptRawCBC(in,*out+TwoFish_BLOCK_SIZE,ilen,FALSE,tfdata);	/* and encrypt the rest (we do not reset the CBC flag). */
434 			if(binhex)									/* if binhex... */
435 			{	_TwoFish_BinHex((uint8_t *)*out,olen,TRUE);		/* ...convert output to binhex... */
436 				olen*=2;								/* ...and size twice as large. */
437 			}
438 			tfdata->output=(uint8_t *)*out;
439 			return olen;
440 		}
441 	}
442 	return 0;
443 }
444 
445 /*	TwoFish Decryption
446  *
447  *	Uses header and CBC. If the output area has not been intialized with TwoFishAlloc,
448  *  this routine will alloc the memory. In addition, it will check the small 'header'
449  *  containing the magic. If magic does not match we return 0. Otherwise we return the
450  *  amount of bytes decrypted (should be the same as the length in the header).
451  *
452  *	Input:	Pointer to the buffer of the ciphertext to be decrypted.
453  *			Pointer to the pointer to the buffer receiving the plaintext.
454  *				The pointer either points to user allocated output buffer space, or to NULL, in which case
455  *				this routine will set the pointer to the buffer allocated through the struct.
456  *			The length of the ciphertext buffer.
457  *				Can be -1 if the input is a null terminated binhex string, in which case we'll count for you.
458  *			Boolean flag for BinHex Input (if used, plaintext will be half as large as input).
459  *				Note: BinHex conversion overwrites (converts) input buffer!
460  *			The TwoFish structure.
461  *
462  *	Output:	The amount of bytes decrypted if successful, otherwise 0.
463  */
464 
TwoFishDecrypt(char * in,char ** out,signed long len,bool binhex,TWOFISH * tfdata)465 unsigned long TwoFishDecrypt(char *in,
466 							 char **out,
467 							 signed long len,
468 							 bool binhex,
469 							 TWOFISH *tfdata)
470 {	unsigned long ilen,elen,olen;
471 	const uint8_t cmagic[TwoFish_MAGIC_LEN]=TwoFish_MAGIC;
472 	uint8_t *tbuf;
473 
474 
475 
476 	if(len== -1)			/* if we got -1 for len, we'll assume IN is...  */
477 		ilen=strlen(in);	/* ...\0 terminated binhex and figure len out ourselves... */
478 	else
479 		ilen=len;			/* ...otherwise we trust you supply a correct length. */
480 
481 	if(in!=NULL && out!=NULL && ilen>0 && tfdata!=NULL) /* if we got usable stuff, we'll do it. */
482 	{	if(*out==NULL)									/* if OUT points to a NULL pointer... */
483 			*out=TwoFishAlloc(ilen,binhex,TRUE,tfdata); /* ...we'll (re-)allocate buffer space. */
484 		if(*out!=NULL)
485 		{	if(binhex)									/* if binhex... */
486 			{	_TwoFish_BinHex((uint8_t *)in,ilen,FALSE);		/* ...convert input to values... */
487 				ilen/=2;								/* ...and size half as much. */
488 			}
489 			_TwoFish_ResetCBC(tfdata);						/* reset the CBC flag. */
490 
491 			tbuf=(uint8_t *)malloc(ilen+TwoFish_BLOCK_SIZE); /* get memory for data and header. */
492 			if(tbuf==NULL)
493 				return 0;
494 			tfdata->output=tbuf;					/* set output to temp buffer. */
495 
496 			olen=_TwoFish_CryptRawCBC(in,(char *)tbuf,ilen,TRUE,tfdata)-TwoFish_BLOCK_SIZE; /* decrypt the whole thing. */
497 			memcpy(&(tfdata->header),tbuf,TwoFish_BLOCK_SIZE); /* copy first block into header. */
498 			tfdata->output=(uint8_t *)*out;
499 			for(elen=0;elen<TwoFish_MAGIC_LEN;elen++)	/* compare magic. */
500 				if(tfdata->header.magic[elen]!=cmagic[elen])
501 					break;
502 			if(elen==TwoFish_MAGIC_LEN)					/* if magic matches then... */
503 			{	elen=(tfdata->header.length[0]) |
504 					 (tfdata->header.length[1])<<8 |
505 					 (tfdata->header.length[2])<<16 |
506 					 (tfdata->header.length[3])<<24;	/* .. we know how much to expect. */
507 				if(elen>olen)							/* adjust if necessary. */
508 					elen=olen;
509 				memcpy(*out,tbuf+TwoFish_BLOCK_SIZE,elen);	/* copy data into intended output. */
510 				free(tbuf);
511 				return elen;
512 			}
513 			free(tbuf);
514 		}
515 	}
516 	return 0;
517 }
518 
_TwoFish_PrecomputeMDSmatrix(void)519 void _TwoFish_PrecomputeMDSmatrix(void)	/* precompute the TwoFish_MDS matrix */
520 {   uint32_t m1[2];
521     uint32_t mX[2];
522     uint32_t mY[2];
523     uint32_t i, j;
524 
525     for (i = 0; i < 256; i++)
526     {   j = TwoFish_P[0][i]       & 0xFF; /* compute all the matrix elements */
527         m1[0] = j;
528         mX[0] = TwoFish_Mx_X( j ) & 0xFF;
529         mY[0] = TwoFish_Mx_Y( j ) & 0xFF;
530 
531         j = TwoFish_P[1][i]       & 0xFF;
532         m1[1] = j;
533         mX[1] = TwoFish_Mx_X( j ) & 0xFF;
534         mY[1] = TwoFish_Mx_Y( j ) & 0xFF;
535 
536         TwoFish_MDS[0][i] = m1[TwoFish_P_00] | /* fill matrix w/ above elements */
537                     mX[TwoFish_P_00] <<  8 |
538                     mY[TwoFish_P_00] << 16 |
539                     mY[TwoFish_P_00] << 24;
540         TwoFish_MDS[1][i] = mY[TwoFish_P_10] |
541                     mY[TwoFish_P_10] <<  8 |
542                     mX[TwoFish_P_10] << 16 |
543                     m1[TwoFish_P_10] << 24;
544         TwoFish_MDS[2][i] = mX[TwoFish_P_20] |
545                     mY[TwoFish_P_20] <<  8 |
546                     m1[TwoFish_P_20] << 16 |
547                     mY[TwoFish_P_20] << 24;
548         TwoFish_MDS[3][i] = mX[TwoFish_P_30] |
549                     m1[TwoFish_P_30] <<  8 |
550                     mY[TwoFish_P_30] << 16 |
551                     mX[TwoFish_P_30] << 24;
552     }
553 	TwoFish_MDSready=TRUE;
554 }
555 
556 
_TwoFish_MakeSubKeys(TWOFISH * tfdata)557 void _TwoFish_MakeSubKeys(TWOFISH *tfdata)	/* Expand a user-supplied key material into a session key. */
558 {	uint32_t k64Cnt    = TwoFish_KEY_LENGTH / 8;
559 	uint32_t k32e[4]; /* even 32-bit entities */
560 	uint32_t k32o[4]; /* odd 32-bit entities */
561 	uint32_t sBoxKey[4];
562 	uint32_t offset,i,j;
563 	uint32_t A, B, q=0;
564 	uint32_t k0,k1,k2,k3;
565     uint32_t b0,b1,b2,b3;
566 
567     /* split user key material into even and odd 32-bit entities and */
568     /* compute S-box keys using (12, 8) Reed-Solomon code over GF(256) */
569 
570 
571     for (offset=0,i=0,j=k64Cnt-1;i<4 && offset<TwoFish_KEY_LENGTH;i++,j--)
572     {	k32e[i] = tfdata->key[offset++];
573 		k32e[i]|= tfdata->key[offset++]<<8;
574 		k32e[i]|= tfdata->key[offset++]<<16;
575 		k32e[i]|= tfdata->key[offset++]<<24;
576     	k32o[i] = tfdata->key[offset++];
577 		k32o[i]|= tfdata->key[offset++]<<8;
578 		k32o[i]|= tfdata->key[offset++]<<16;
579 		k32o[i]|= tfdata->key[offset++]<<24;
580         sBoxKey[j] = _TwoFish_RS_MDS_Encode( k32e[i], k32o[i] ); /* reverse order */
581     }
582 
583     /* compute the round decryption subkeys for PHT. these same subkeys */
584     /* will be used in encryption but will be applied in reverse order. */
585     i=0;
586     while(i < TwoFish_TOTAL_SUBKEYS)
587     {	A = _TwoFish_F32( k64Cnt, q, k32e ); /* A uses even key entities */
588         q += TwoFish_SK_BUMP;
589 
590         B = _TwoFish_F32( k64Cnt, q, k32o ); /* B uses odd  key entities */
591         q += TwoFish_SK_BUMP;
592 
593         B = B << 8 | B >> 24;
594 
595         A += B;
596         tfdata->subKeys[i++] = A;           /* combine with a PHT */
597 
598         A += B;
599         tfdata->subKeys[i++] = A << TwoFish_SK_ROTL | A >> (32-TwoFish_SK_ROTL);
600     }
601 
602     /* fully expand the table for speed */
603     k0 = sBoxKey[0];
604     k1 = sBoxKey[1];
605     k2 = sBoxKey[2];
606     k3 = sBoxKey[3];
607 
608     for (i = 0; i < 256; i++)
609     {   b0 = b1 = b2 = b3 = i;
610         switch (k64Cnt & 3)
611         {	case 1: /* 64-bit keys */
612 				tfdata->sBox[      2*i  ] = TwoFish_MDS[0][(TwoFish_P[TwoFish_P_01][b0]) ^ TwoFish_b0(k0)];
613 				tfdata->sBox[      2*i+1] = TwoFish_MDS[1][(TwoFish_P[TwoFish_P_11][b1]) ^ TwoFish_b1(k0)];
614 				tfdata->sBox[0x200+2*i  ] = TwoFish_MDS[2][(TwoFish_P[TwoFish_P_21][b2]) ^ TwoFish_b2(k0)];
615 				tfdata->sBox[0x200+2*i+1] = TwoFish_MDS[3][(TwoFish_P[TwoFish_P_31][b3]) ^ TwoFish_b3(k0)];
616 				break;
617 			case 0: /* 256-bit keys (same as 4) */
618 				b0 = (TwoFish_P[TwoFish_P_04][b0]) ^ TwoFish_b0(k3);
619 				b1 = (TwoFish_P[TwoFish_P_14][b1]) ^ TwoFish_b1(k3);
620 				b2 = (TwoFish_P[TwoFish_P_24][b2]) ^ TwoFish_b2(k3);
621 				b3 = (TwoFish_P[TwoFish_P_34][b3]) ^ TwoFish_b3(k3);
622 			case 3:  /* 192-bit keys */
623 				b0 = (TwoFish_P[TwoFish_P_03][b0]) ^ TwoFish_b0(k2);
624 				b1 = (TwoFish_P[TwoFish_P_13][b1]) ^ TwoFish_b1(k2);
625 				b2 = (TwoFish_P[TwoFish_P_23][b2]) ^ TwoFish_b2(k2);
626 				b3 = (TwoFish_P[TwoFish_P_33][b3]) ^ TwoFish_b3(k2);
627 			case 2: /* 128-bit keys */
628 				tfdata->sBox[      2*i  ]=
629 					TwoFish_MDS[0][(TwoFish_P[TwoFish_P_01][(TwoFish_P[TwoFish_P_02][b0]) ^
630 					TwoFish_b0(k1)]) ^ TwoFish_b0(k0)];
631 
632 				tfdata->sBox[      2*i+1]=
633 					TwoFish_MDS[1][(TwoFish_P[TwoFish_P_11][(TwoFish_P[TwoFish_P_12][b1]) ^
634 					TwoFish_b1(k1)]) ^ TwoFish_b1(k0)];
635 
636 				tfdata->sBox[0x200+2*i  ]=
637 					TwoFish_MDS[2][(TwoFish_P[TwoFish_P_21][(TwoFish_P[TwoFish_P_22][b2]) ^
638 					TwoFish_b2(k1)]) ^ TwoFish_b2(k0)];
639 
640 				tfdata->sBox[0x200+2*i+1]=
641 					TwoFish_MDS[3][(TwoFish_P[TwoFish_P_31][(TwoFish_P[TwoFish_P_32][b3]) ^
642 					TwoFish_b3(k1)]) ^ TwoFish_b3(k0)];
643 		}
644     }
645 }
646 
647 
648 /**
649  * Encrypt or decrypt exactly one block of plaintext in CBC mode.
650  * Use "ciphertext stealing" technique described on pg. 196
651  * of "Applied Cryptography" to encrypt the final partial
652  * (i.e. <16 byte) block if necessary.
653  *
654  * jojo: the "ciphertext stealing" requires we read ahead and have
655  * special handling for the last two blocks.  Because of this, the
656  * output from the TwoFish algorithm is handled internally here.
657  * It would be better to have a higher level handle this as well as
658  * CBC mode.  Unfortunately, I've mixed the two together, which is
659  * pretty crappy... The Java version separates these out correctly.
660  *
661  * fknobbe:	I have reduced the CBC mode to work on memory buffer only.
662  *			Higher routines should use an intermediate buffer and handle
663  *			their output seperately (mainly so the data can be flushed
664  *			in one chunk, not seperate 16 byte blocks...)
665  *
666  * @param in   The plaintext.
667  * @param out  The ciphertext
668  * @param size how much to encrypt
669  * @param tfdata: Pointer to the global data structure containing session keys.
670  * @return none
671  */
_TwoFish_BlockCrypt(uint8_t * in,uint8_t * out,unsigned long size,int decrypt,TWOFISH * tfdata)672 void _TwoFish_BlockCrypt(uint8_t *in,uint8_t *out,unsigned long size,int decrypt,TWOFISH *tfdata)
673 {	uint8_t PnMinusOne[TwoFish_BLOCK_SIZE];
674 	uint8_t CnMinusOne[TwoFish_BLOCK_SIZE];
675 	uint8_t CBCplusCprime[TwoFish_BLOCK_SIZE];
676 	uint8_t Pn[TwoFish_BLOCK_SIZE];
677 	uint8_t *p,*pout;
678 	unsigned long i;
679 
680     /* here is where we implement CBC mode and cipher block stealing */
681     if(size==TwoFish_BLOCK_SIZE)
682 	{   /* if we are encrypting, CBC means we XOR the plain text block with the */
683         /* previous cipher text block before encrypting */
684 		if(!decrypt && tfdata->qBlockDefined)
685 		{   for(p=in,i=0;i<TwoFish_BLOCK_SIZE;i++,p++)
686 				Pn[i]=*p ^ tfdata->qBlockCrypt[i];	/* FK: I'm copying the xor'ed input into Pn... */
687 		}
688 		else
689 			memcpy(Pn,in,TwoFish_BLOCK_SIZE); /* FK: same here. we work of Pn all the time. */
690 
691         /* TwoFish block level encryption or decryption */
692 		_TwoFish_BlockCrypt16(Pn,out,decrypt,tfdata);
693 
694         /* if we are decrypting, CBC means we XOR the result of the decryption */
695         /* with the previous cipher text block to get the resulting plain text */
696         if(decrypt && tfdata->qBlockDefined)
697         {	for (p=out,i=0;i<TwoFish_BLOCK_SIZE;i++,p++)
698 				*p^=tfdata->qBlockPlain[i];
699         }
700 
701         /* save the input and output blocks, since CBC needs these for XOR */
702         /* operations */
703         _TwoFish_qBlockPush(Pn,out,tfdata);
704 	}
705 	else
706 	{   /* cipher block stealing, we are at Pn, */
707         /* but since Cn-1 must now be replaced with CnC' */
708         /* we pop it off, and recalculate Cn-1 */
709 
710         if(decrypt)
711         {   /* We are on an odd block, and had to do cipher block stealing, */
712             /* so the PnMinusOne has to be derived differently. */
713 
714             /* First we decrypt it into CBC and C' */
715 	        _TwoFish_qBlockPop(CnMinusOne,PnMinusOne,tfdata);
716             _TwoFish_BlockCrypt16(CnMinusOne,CBCplusCprime,decrypt,tfdata);
717 
718             /* we then xor the first few bytes with the "in" bytes (Cn) */
719             /* to recover Pn, which we put in out */
720             for(p=in,pout=out,i=0;i<size;i++,p++,pout++)
721                 *pout=*p ^ CBCplusCprime[i];
722 
723             /* We now recover the original CnMinusOne, which consists of */
724             /* the first "size" bytes of "in" data, followed by the */
725             /* "Cprime" portion of CBCplusCprime */
726             for(p=in,i=0;i<size;i++,p++)
727                 CnMinusOne[i]=*p;
728             for(;i<TwoFish_BLOCK_SIZE;i++)
729                 CnMinusOne[i]=CBCplusCprime[i];
730 
731             /* we now decrypt CnMinusOne to get PnMinusOne xored with Cn-2 */
732             _TwoFish_BlockCrypt16(CnMinusOne,PnMinusOne,decrypt,tfdata);
733 
734             for(i=0;i<TwoFish_BLOCK_SIZE;i++)
735                 PnMinusOne[i]=PnMinusOne[i] ^ tfdata->prevCipher[i];
736 
737             /* So at this point, out has PnMinusOne */
738             _TwoFish_qBlockPush(CnMinusOne,PnMinusOne,tfdata);
739 		    _TwoFish_FlushOutput(tfdata->qBlockCrypt,TwoFish_BLOCK_SIZE,tfdata);
740             _TwoFish_FlushOutput(out,size,tfdata);
741         }
742 		else
743 		{	_TwoFish_qBlockPop(PnMinusOne,CnMinusOne,tfdata);
744 			memset(Pn,0,TwoFish_BLOCK_SIZE);
745 			memcpy(Pn,in,size);
746 			for(i=0;i<TwoFish_BLOCK_SIZE;i++)
747 				Pn[i]^=CnMinusOne[i];
748 			_TwoFish_BlockCrypt16(Pn,out,decrypt,tfdata);
749 			_TwoFish_qBlockPush(Pn,out,tfdata);  /* now we officially have Cn-1 */
750 			_TwoFish_FlushOutput(tfdata->qBlockCrypt,TwoFish_BLOCK_SIZE,tfdata);
751 			_TwoFish_FlushOutput(CnMinusOne,size,tfdata);  /* old Cn-1 becomes new partial Cn */
752 		}
753 		tfdata->qBlockDefined=FALSE;
754 	}
755 }
756 
_TwoFish_qBlockPush(uint8_t * p,uint8_t * c,TWOFISH * tfdata)757 void _TwoFish_qBlockPush(uint8_t *p,uint8_t *c,TWOFISH *tfdata)
758 {	if(tfdata->qBlockDefined)
759 		_TwoFish_FlushOutput(tfdata->qBlockCrypt,TwoFish_BLOCK_SIZE,tfdata);
760 	memcpy(tfdata->prevCipher,tfdata->qBlockPlain,TwoFish_BLOCK_SIZE);
761 	memcpy(tfdata->qBlockPlain,p,TwoFish_BLOCK_SIZE);
762 	memcpy(tfdata->qBlockCrypt,c,TwoFish_BLOCK_SIZE);
763 	tfdata->qBlockDefined=TRUE;
764 }
765 
_TwoFish_qBlockPop(uint8_t * p,uint8_t * c,TWOFISH * tfdata)766 void _TwoFish_qBlockPop(uint8_t *p,uint8_t *c,TWOFISH *tfdata)
767 {	memcpy(p,tfdata->qBlockPlain,TwoFish_BLOCK_SIZE );
768 	memcpy(c,tfdata->qBlockCrypt,TwoFish_BLOCK_SIZE );
769 	tfdata->qBlockDefined=FALSE;
770 }
771 
772 /* Reset's the CBC flag and zero's PrevCipher (through qBlockPlain) (important) */
_TwoFish_ResetCBC(TWOFISH * tfdata)773 void _TwoFish_ResetCBC(TWOFISH *tfdata)
774 {	tfdata->qBlockDefined=FALSE;
775 	memset(tfdata->qBlockPlain,0,TwoFish_BLOCK_SIZE);
776 }
777 
_TwoFish_FlushOutput(uint8_t * b,unsigned long len,TWOFISH * tfdata)778 void _TwoFish_FlushOutput(uint8_t *b,unsigned long len,TWOFISH *tfdata)
779 {	unsigned long i;
780 
781 	for(i=0;i<len && !tfdata->dontflush;i++)
782 		*tfdata->output++ = *b++;
783 	tfdata->dontflush=FALSE;
784 }
785 
_TwoFish_BlockCrypt16(uint8_t * in,uint8_t * out,bool decrypt,TWOFISH * tfdata)786 void _TwoFish_BlockCrypt16(uint8_t *in,uint8_t *out,bool decrypt,TWOFISH *tfdata)
787 {	uint32_t x0,x1,x2,x3;
788     uint32_t k,t0,t1,R;
789 
790 
791 	x0=*in++;
792 	x0|=(*in++ << 8 );
793 	x0|=(*in++ << 16);
794 	x0|=(*in++ << 24);
795     x1=*in++;
796 	x1|=(*in++ << 8 );
797 	x1|=(*in++ << 16);
798 	x1|=(*in++ << 24);
799 	x2=*in++;
800 	x2|=(*in++ << 8 );
801 	x2|=(*in++ << 16);
802 	x2|=(*in++ << 24);
803 	x3=*in++;
804 	x3|=(*in++ << 8 );
805 	x3|=(*in++ << 16);
806 	x3|=(*in++ << 24);
807 
808 	if(decrypt)
809     {	x0 ^= tfdata->subKeys[4];	/* swap input and output whitening keys when decrypting */
810  	    x1 ^= tfdata->subKeys[5];
811 		x2 ^= tfdata->subKeys[6];
812 		x3 ^= tfdata->subKeys[7];
813 
814         k = 7+(TwoFish_ROUNDS*2);
815         for (R = 0; R < TwoFish_ROUNDS; R += 2)
816 		{   t0 = _TwoFish_Fe320( tfdata->sBox, x0);
817             t1 = _TwoFish_Fe323( tfdata->sBox, x1);
818             x3 ^= t0 + (t1<<1) + tfdata->subKeys[k--];
819             x3  = x3 >> 1 | x3 << 31;
820             x2  = x2 << 1 | x2 >> 31;
821             x2 ^= t0 + t1 + tfdata->subKeys[k--];
822 
823             t0 = _TwoFish_Fe320( tfdata->sBox, x2);
824             t1 = _TwoFish_Fe323( tfdata->sBox, x3);
825             x1 ^= t0 + (t1<<1) + tfdata->subKeys[k--];
826             x1  = x1 >> 1 | x1 << 31;
827             x0  = x0 << 1 | x0 >> 31;
828             x0 ^= t0 + t1 + tfdata->subKeys[k--];
829         }
830 
831 		x2 ^= tfdata->subKeys[0];
832 		x3 ^= tfdata->subKeys[1];
833 		x0 ^= tfdata->subKeys[2];
834 		x1 ^= tfdata->subKeys[3];
835 	}
836 	else
837     {	x0 ^= tfdata->subKeys[0];
838 	    x1 ^= tfdata->subKeys[1];
839 		x2 ^= tfdata->subKeys[2];
840 		x3 ^= tfdata->subKeys[3];
841 
842 		k = 8;
843         for (R = 0; R < TwoFish_ROUNDS; R += 2)
844         {   t0 = _TwoFish_Fe320( tfdata->sBox, x0);
845             t1 = _TwoFish_Fe323( tfdata->sBox, x1);
846             x2 ^= t0 + t1 + tfdata->subKeys[k++];
847             x2  = x2 >> 1 | x2 << 31;
848             x3  = x3 << 1 | x3 >> 31;
849             x3 ^= t0 + (t1<<1) + tfdata->subKeys[k++];
850 
851             t0 = _TwoFish_Fe320( tfdata->sBox, x2);
852             t1 = _TwoFish_Fe323( tfdata->sBox, x3);
853             x0 ^= t0 + t1 + tfdata->subKeys[k++];
854             x0  = x0 >> 1 | x0 << 31;
855             x1  = x1 << 1 | x1 >> 31;
856             x1 ^= t0 + (t1<<1) + tfdata->subKeys[k++];
857         }
858 
859 		x2 ^= tfdata->subKeys[4];
860 		x3 ^= tfdata->subKeys[5];
861 		x0 ^= tfdata->subKeys[6];
862 		x1 ^= tfdata->subKeys[7];
863 	}
864 
865 	*out++ = (uint8_t)(x2      );
866     *out++ = (uint8_t)(x2 >>  8);
867     *out++ = (uint8_t)(x2 >> 16);
868     *out++ = (uint8_t)(x2 >> 24);
869 
870     *out++ = (uint8_t)(x3      );
871     *out++ = (uint8_t)(x3 >>  8);
872     *out++ = (uint8_t)(x3 >> 16);
873     *out++ = (uint8_t)(x3 >> 24);
874 
875     *out++ = (uint8_t)(x0      );
876     *out++ = (uint8_t)(x0 >>  8);
877     *out++ = (uint8_t)(x0 >> 16);
878     *out++ = (uint8_t)(x0 >> 24);
879 
880     *out++ = (uint8_t)(x1      );
881     *out++ = (uint8_t)(x1 >>  8);
882     *out++ = (uint8_t)(x1 >> 16);
883     *out++ = (uint8_t)(x1 >> 24);
884 }
885 
886 /**
887  * Use (12, 8) Reed-Solomon code over GF(256) to produce a key S-box
888  * 32-bit entity from two key material 32-bit entities.
889  *
890  * @param  k0  1st 32-bit entity.
891  * @param  k1  2nd 32-bit entity.
892  * @return  Remainder polynomial generated using RS code
893  */
_TwoFish_RS_MDS_Encode(uint32_t k0,uint32_t k1)894 uint32_t _TwoFish_RS_MDS_Encode(uint32_t k0,uint32_t k1)
895 {	uint32_t i,r;
896 
897     for(r=k1,i=0;i<4;i++) /* shift 1 byte at a time */
898         TwoFish_RS_rem(r);
899     r ^= k0;
900     for(i=0;i<4;i++)
901         TwoFish_RS_rem(r);
902 
903     return r;
904 }
905 
_TwoFish_F32(uint32_t k64Cnt,uint32_t x,uint32_t * k32)906 uint32_t _TwoFish_F32(uint32_t k64Cnt,uint32_t x,uint32_t *k32)
907 {   uint8_t b0,b1,b2,b3;
908 	uint32_t k0,k1,k2,k3,result = 0;
909 
910 	b0=TwoFish_b0(x);
911     b1=TwoFish_b1(x);
912     b2=TwoFish_b2(x);
913     b3=TwoFish_b3(x);
914     k0=k32[0];
915     k1=k32[1];
916     k2=k32[2];
917     k3=k32[3];
918 
919     switch (k64Cnt & 3)
920     {	case 1:	/* 64-bit keys */
921 			result =
922 				TwoFish_MDS[0][(TwoFish_P[TwoFish_P_01][b0] & 0xFF) ^ TwoFish_b0(k0)] ^
923 				TwoFish_MDS[1][(TwoFish_P[TwoFish_P_11][b1] & 0xFF) ^ TwoFish_b1(k0)] ^
924 				TwoFish_MDS[2][(TwoFish_P[TwoFish_P_21][b2] & 0xFF) ^ TwoFish_b2(k0)] ^
925 				TwoFish_MDS[3][(TwoFish_P[TwoFish_P_31][b3] & 0xFF) ^ TwoFish_b3(k0)];
926         break;
927 		case 0:	/* 256-bit keys (same as 4) */
928 			b0 = (TwoFish_P[TwoFish_P_04][b0] & 0xFF) ^ TwoFish_b0(k3);
929 			b1 = (TwoFish_P[TwoFish_P_14][b1] & 0xFF) ^ TwoFish_b1(k3);
930 			b2 = (TwoFish_P[TwoFish_P_24][b2] & 0xFF) ^ TwoFish_b2(k3);
931 			b3 = (TwoFish_P[TwoFish_P_34][b3] & 0xFF) ^ TwoFish_b3(k3);
932 
933 		case 3:	/* 192-bit keys */
934 			b0 = (TwoFish_P[TwoFish_P_03][b0] & 0xFF) ^ TwoFish_b0(k2);
935 			b1 = (TwoFish_P[TwoFish_P_13][b1] & 0xFF) ^ TwoFish_b1(k2);
936 			b2 = (TwoFish_P[TwoFish_P_23][b2] & 0xFF) ^ TwoFish_b2(k2);
937 			b3 = (TwoFish_P[TwoFish_P_33][b3] & 0xFF) ^ TwoFish_b3(k2);
938 		case 2:	/* 128-bit keys (optimize for this case) */
939 			result =
940 				  TwoFish_MDS[0][(TwoFish_P[TwoFish_P_01][(TwoFish_P[TwoFish_P_02][b0] & 0xFF) ^ TwoFish_b0(k1)] & 0xFF) ^ TwoFish_b0(k0)] ^
941 				  TwoFish_MDS[1][(TwoFish_P[TwoFish_P_11][(TwoFish_P[TwoFish_P_12][b1] & 0xFF) ^ TwoFish_b1(k1)] & 0xFF) ^ TwoFish_b1(k0)] ^
942 				  TwoFish_MDS[2][(TwoFish_P[TwoFish_P_21][(TwoFish_P[TwoFish_P_22][b2] & 0xFF) ^ TwoFish_b2(k1)] & 0xFF) ^ TwoFish_b2(k0)] ^
943 				  TwoFish_MDS[3][(TwoFish_P[TwoFish_P_31][(TwoFish_P[TwoFish_P_32][b3] & 0xFF) ^ TwoFish_b3(k1)] & 0xFF) ^ TwoFish_b3(k0)];
944         break;
945     }
946     return result;
947 }
948 
_TwoFish_Fe320(uint32_t * lsBox,uint32_t x)949 uint32_t _TwoFish_Fe320(uint32_t *lsBox,uint32_t x)
950 {   return lsBox[        TwoFish_b0(x)<<1    ]^
951            lsBox[      ((TwoFish_b1(x)<<1)|1)]^
952            lsBox[0x200+ (TwoFish_b2(x)<<1)   ]^
953            lsBox[0x200+((TwoFish_b3(x)<<1)|1)];
954 }
955 
_TwoFish_Fe323(uint32_t * lsBox,uint32_t x)956 uint32_t _TwoFish_Fe323(uint32_t *lsBox,uint32_t x)
957 {   return lsBox[       (TwoFish_b3(x)<<1)   ]^
958            lsBox[      ((TwoFish_b0(x)<<1)|1)]^
959            lsBox[0x200+ (TwoFish_b1(x)<<1)   ]^
960            lsBox[0x200+((TwoFish_b2(x)<<1)|1)];
961 }
962 
_TwoFish_Fe32(uint32_t * lsBox,uint32_t x,uint32_t R)963 uint32_t _TwoFish_Fe32(uint32_t *lsBox,uint32_t x,uint32_t R)
964 {   return lsBox[      2*TwoFish__b(x,R  )  ]^
965            lsBox[      2*TwoFish__b(x,R+1)+1]^
966            lsBox[0x200+2*TwoFish__b(x,R+2)  ]^
967            lsBox[0x200+2*TwoFish__b(x,R+3)+1];
968 }
969 
970 
971 #endif
972