1 /* 2 Copyright (C) 2000-2007 MySQL AB 3 Use is subject to license terms 4 5 This program is free software; you can redistribute it and/or modify 6 it under the terms of the GNU General Public License as published by 7 the Free Software Foundation; version 2 of the License. 8 9 This program is distributed in the hope that it will be useful, 10 but WITHOUT ANY WARRANTY; without even the implied warranty of 11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 GNU General Public License for more details. 13 14 You should have received a copy of the GNU General Public License 15 along with this program; see the file COPYING. If not, write to the 16 Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, 17 MA 02110-1335 USA. 18 */ 19 20 /* twofish.hpp defines Twofish 21 */ 22 23 24 #ifndef TAO_CRYPT_TWOFISH_HPP 25 #define TAO_CRYPT_TWOFISH_HPP 26 27 #include "misc.hpp" 28 #include "modes.hpp" 29 #ifdef USE_SYS_STL 30 #include <algorithm> 31 #else 32 #include "algorithm.hpp" 33 #endif 34 35 36 namespace STL = STL_NAMESPACE; 37 38 39 #if defined(TAOCRYPT_X86ASM_AVAILABLE) && defined(TAO_ASM) 40 #define DO_TWOFISH_ASM 41 #endif 42 43 namespace TaoCrypt { 44 45 enum { TWOFISH_BLOCK_SIZE = 16 }; 46 47 48 // Twofish encryption and decryption, see 49 class Twofish : public Mode_BASE { 50 public: 51 enum { BLOCK_SIZE = TWOFISH_BLOCK_SIZE }; 52 Twofish(CipherDir DIR,Mode MODE)53 Twofish(CipherDir DIR, Mode MODE) 54 : Mode_BASE(BLOCK_SIZE, DIR, MODE) {} 55 56 #ifdef DO_TWOFISH_ASM 57 void Process(byte*, const byte*, word32); 58 #endif 59 void SetKey(const byte* key, word32 sz, CipherDir fake = ENCRYPTION); SetIV(const byte * iv)60 void SetIV(const byte* iv) { memcpy(r_, iv, BLOCK_SIZE); } 61 private: 62 static const byte q_[2][256]; 63 static const word32 mds_[4][256]; 64 65 word32 k_[40]; 66 word32 s_[4][256]; 67 68 static word32 h0(word32 x, const word32 *key, unsigned int kLen); 69 static word32 h(word32 x, const word32 *key, unsigned int kLen); 70 71 void ProcessAndXorBlock(const byte*, const byte*, byte*) const; 72 73 void encrypt(const byte*, const byte*, byte*) const; 74 void decrypt(const byte*, const byte*, byte*) const; 75 76 void AsmEncrypt(const byte* inBlock, byte* outBlock) const; 77 void AsmDecrypt(const byte* inBlock, byte* outBlock) const; 78 79 Twofish(const Twofish&); // hide copy 80 Twofish& operator=(const Twofish&); // and assign 81 }; 82 83 84 typedef BlockCipher<ENCRYPTION, Twofish, ECB> Twofish_ECB_Encryption; 85 typedef BlockCipher<DECRYPTION, Twofish, ECB> Twofish_ECB_Decryption; 86 87 typedef BlockCipher<ENCRYPTION, Twofish, CBC> Twofish_CBC_Encryption; 88 typedef BlockCipher<DECRYPTION, Twofish, CBC> Twofish_CBC_Decryption; 89 90 91 92 } // naemspace 93 94 #endif // TAO_CRYPT_TWOFISH_HPP 95 96