2 * Worldvisions Tunnel Vision Software:
3 * Copyright (C) 1997-2002 Net Integration Technologies, Inc.
5 * A 'counter mode' cryptography engine abstraction.
7 #include "wvcountermode.h"
10 WvCounterModeEncoder::WvCounterModeEncoder(WvEncoder
*_keycrypt
,
11 const void *_counter
, size_t _countersize
) :
12 keycrypt(_keycrypt
), counter(NULL
)
14 setcounter(_counter
, _countersize
);
18 WvCounterModeEncoder::~WvCounterModeEncoder()
25 void WvCounterModeEncoder::setcounter(const void *_counter
, size_t _countersize
)
28 counter
= new unsigned char[_countersize
];
29 countersize
= _countersize
;
30 memcpy(counter
, _counter
, countersize
);
34 void WvCounterModeEncoder::getcounter(void *_counter
) const
36 memcpy(_counter
, counter
, countersize
);
40 void WvCounterModeEncoder::incrcounter()
42 for (size_t i
= 0; i
< countersize
&& ! ++counter
[i
]; ++i
);
46 bool WvCounterModeEncoder::_encode(WvBuf
&inbuf
, WvBuf
&outbuf
,
50 size_t avail
= inbuf
.used();
51 size_t offset
= outbuf
.used();
53 // generate a key stream
55 for (len
= avail
; len
>= countersize
; len
-= countersize
)
57 counterbuf
.reset(counter
, countersize
);
58 success
= keycrypt
->encode(counterbuf
, outbuf
, true);
62 if (flush
&& len
!= 0 && success
)
64 counterbuf
.reset(counter
, countersize
);
65 success
= keycrypt
->encode(counterbuf
, outbuf
, true);
68 outbuf
.unalloc(countersize
- len
);
73 outbuf
.unalloc(outbuf
.used() - offset
- avail
);
80 len
= outbuf
.optpeekable(offset
);
81 unsigned char *dataout
= outbuf
.mutablepeek(offset
, len
);
82 size_t lenopt
= inbuf
.optgettable();
85 const unsigned char *datain
= inbuf
.get(len
);
98 *(dataout
++) ^= *(datain
++);