23 #ifndef TAO_CRYPT_MODES_HPP
24 #define TAO_CRYPT_MODES_HPP
31 enum Mode { ECB, CBC };
36 template<CipherDir DIR,
class T, Mode MODE>
41 void Process(byte* c,
const byte* p, word32 sz)
42 { cipher_.Process(c, p, sz); }
43 void SetKey(
const byte* k, word32 sz)
44 { cipher_.SetKey(k, sz, DIR); }
45 void SetKey(
const byte* k, word32 sz,
const byte* iv)
46 { cipher_.SetKey(k, sz, DIR); cipher_.SetIV(iv); }
58 enum { MaxBlockSz = 16 };
61 : blockSz_(sz), reg_(reinterpret_cast<byte*>(r_)),
62 tmp_(reinterpret_cast<byte*>(t_)), dir_(dir), mode_(mode)
66 virtual void Process(byte*,
const byte*, word32);
68 void SetIV(
const byte* iv) { memcpy(reg_, iv, blockSz_); }
74 word32 r_[MaxBlockSz /
sizeof(word32)];
75 word32 t_[MaxBlockSz /
sizeof(word32)];
80 void ECB_Process(byte*,
const byte*, word32);
81 void CBC_Encrypt(byte*,
const byte*, word32);
82 void CBC_Decrypt(byte*,
const byte*, word32);
88 virtual void ProcessAndXorBlock(
const byte*,
const byte*, byte*)
const = 0;
92 inline void Mode_BASE::Process(byte* out,
const byte* in, word32 sz)
95 ECB_Process(out, in, sz);
96 else if (mode_ == CBC) {
97 if (dir_ == ENCRYPTION)
98 CBC_Encrypt(out, in, sz);
100 CBC_Decrypt(out, in, sz);
106 inline void Mode_BASE::ECB_Process(byte* out,
const byte* in, word32 sz)
108 word32 blocks = sz / blockSz_;
111 ProcessAndXorBlock(in, 0, out);
119 inline void Mode_BASE::CBC_Encrypt(byte* out,
const byte* in, word32 sz)
121 word32 blocks = sz / blockSz_;
124 xorbuf(reg_, in, blockSz_);
125 ProcessAndXorBlock(reg_, 0, reg_);
126 memcpy(out, reg_, blockSz_);
134 inline void Mode_BASE::CBC_Decrypt(byte* out,
const byte* in, word32 sz)
136 word32 blocks = sz / blockSz_;
137 byte hold[MaxBlockSz];
140 memcpy(tmp_, in, blockSz_);
141 ProcessAndXorBlock(tmp_, 0, out);
142 xorbuf(out, reg_, blockSz_);
143 memcpy(hold, reg_, blockSz_);
144 memcpy(reg_, tmp_, blockSz_);
145 memcpy(tmp_, hold, blockSz_);
154 #endif // TAO_CRYPT_MODES_HPP