CBC CFB OFB encode & decode process in C++

前回の続き:(http://d.hatena.ne.jp/studiokingyo/20060407
より
デコードバージョンも用意してサンプルも書いてみました。
dkutil依存なコードもあるけどそこらへんは各自直してください。ではでは。

template<typename T,class FUNCTION_T>
struct block_encode{
block_encode(){}
~block_encode(){}
inline T *ofb(T *target,const T &src,size_t count,
FUNCTION_T encode_func)
{
size_t i;
T ref_t = encode_func(src);
for(i=0;i<count;i++)
{
target[i] ^= ref_t;
ref_t = encode_func(ref_t);
}
return target;
}
inline T *cfb(T *target,const T &src,size_t count,
FUNCTION_T encode_func)
{
size_t i;
T ref_t = encode_func(src);;
for(i=0;i<count;i++)
{
target[i] ^= ref_t;
ref_t = encode_func(target[i]);
}
return target;
}
inline T *cbc(T *target,const T &src,size_t count,
FUNCTION_T encode_func)
{
size_t i;
T ref_t = src;
for(i=0;i<count;i++)
{
ref_t ^= target[i];
ref_t = encode_func(ref_t);
target[i] = ref_t;
}
return target;
}
};

template<typename T,class FUNCTION_T>
struct block_decode{
block_decode(){}
~block_decode(){}
typedef block_encode<T,FUNCTION_T> encoder_type;
encoder_type mEncoder;
inline T *ofb(T *target,const T &src,size_t count,
FUNCTION_T encode_func)
{
return mEncoder.ofb(target,src,count,encode_func);
}
inline T *cfb(T *target,const T &src,size_t count,
FUNCTION_T encode_func)
{
return mEncoder.cfb(target,src,count,eocnde_func);
}
inline T *cbc(T *target,const T &src,size_t count,
FUNCTION_T encode_func)
{
size_t i;
T ref_t = src,t;
for(i=0;i<count;i++)
{
target[i] = encode_func(target[i]);
ref_t ^= target[i];
t = target[i];
target[i] = ref_t;
ref_t = t;

}
return target;
}
};

template<class T>
struct test_cipher{
unsigned m;
test_cipher(){
reset();
}
T operator()(const T &src){
T t = src ^ m;
m += src;
return t;
}
void reset(){
m = 0x12345678;
}

};

void dkutil_block_convert_test()
{

{

block_encode<uint32,test_cipher<uint32> > encoder;
block_decode<uint32,test_cipher<uint32> > decoder;
uint32 ivec = 0xff11ff11;
uint32 target[32],temp[32];
size_t i;
for(i=0;i<32;i++){
temp[i] = target[i] = i;
}
test_cipher<uint32> cipher;
encoder.cbc(target,ivec,DKUTIL_ARRAY_NUM_OF(target),cipher);
cipher.reset();
decoder.cbc(target,ivec,DKUTIL_ARRAY_NUM_OF(target),cipher);
dkcmASSERT(0==memcmp(temp,target,sizeof(temp)));

cipher.reset();
encoder.ofb(target,ivec,DKUTIL_ARRAY_NUM_OF(target),cipher);
cipher.reset();
decoder.ofb(target,ivec,DKUTIL_ARRAY_NUM_OF(target),cipher);
dkcmASSERT(0==memcmp(temp,target,sizeof(temp)));

cipher.reset();
encoder.ofb(target,ivec,DKUTIL_ARRAY_NUM_OF(target),cipher);
cipher.reset();
decoder.ofb(target,ivec,DKUTIL_ARRAY_NUM_OF(target),cipher);
dkcmASSERT(0==memcmp(temp,target,sizeof(temp)));


}


}

追記:cbcエンコードデコードにバグがあったためFIX