51 broke -E logic completely, rewise it
[tfcrypt.git] / tfctr.c
1 #include <string.h>
2 #include "tfdef.h"
3
4 void tf_ctr_crypt(const void *key, void *ctr, void *out, const void *in, size_t sz)
5 {
6         const TF_BYTE_TYPE *uin = in;
7         TF_BYTE_TYPE *uout = out;
8         TF_UNIT_TYPE x[TF_NR_BLOCK_UNITS], y[TF_NR_BLOCK_UNITS];
9         TF_UNIT_TYPE *uctr = ctr;
10         const TF_UNIT_TYPE *ukey = key;
11         size_t sl = sz, i;
12
13         if (sl >= TF_BLOCK_SIZE) {
14                 do {
15                         memcpy(x, uin, TF_BLOCK_SIZE);
16                         uin += TF_BLOCK_SIZE;
17                         data_to_words(x, TF_BLOCK_SIZE);
18
19                         ctr_inc(uctr, TF_NR_BLOCK_UNITS);
20                         tf_encrypt_rawblk(y, uctr, ukey);
21                         for (i = 0; i < TF_NR_BLOCK_UNITS; i++) y[i] ^= x[i];
22
23                         data_to_words(y, TF_BLOCK_SIZE);
24                         memcpy(uout, y, TF_BLOCK_SIZE);
25                         uout += TF_BLOCK_SIZE;
26                 } while ((sl -= TF_BLOCK_SIZE) >= TF_BLOCK_SIZE);
27         }
28
29         if (sl) {
30                 memset(x, 0, TF_BLOCK_SIZE);
31                 memcpy(x, uin, sl);
32                 data_to_words(x, TF_BLOCK_SIZE);
33
34                 ctr_inc(uctr, TF_NR_BLOCK_UNITS);
35                 tf_encrypt_rawblk(y, uctr, ukey);
36                 for (i = 0; i < TF_NR_BLOCK_UNITS; i++) y[i] ^= x[i];
37
38                 data_to_words(y, TF_BLOCK_SIZE);
39                 memcpy(uout, y, sl);
40         }
41
42         memset(x, 0, TF_BLOCK_SIZE);
43         memset(y, 0, TF_BLOCK_SIZE);
44 }