51 broke -E logic completely, rewise it
[tfcrypt.git] / tfecb.c
1 #include <string.h>
2 #include "tfdef.h"
3
4 void tf_ecb_encrypt(const void *key, 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         const TF_UNIT_TYPE *ukey = key;
10         size_t sl = sz, i;
11
12         if (sl >= TF_BLOCK_SIZE) {
13                 do {
14                         memcpy(x, uin, TF_BLOCK_SIZE);
15                         uin += TF_BLOCK_SIZE;
16                         data_to_words(x, TF_BLOCK_SIZE);
17
18                         tf_encrypt_rawblk(y, x, ukey);
19
20                         data_to_words(y, TF_BLOCK_SIZE);
21                         memcpy(uout, y, TF_BLOCK_SIZE);
22                         uout += TF_BLOCK_SIZE;
23                 } while ((sl -= TF_BLOCK_SIZE) >= TF_BLOCK_SIZE);
24         }
25
26         if (sl) {
27                 memset(x, 0, TF_BLOCK_SIZE);
28                 memcpy(x, uin, sl);
29                 data_to_words(x, TF_BLOCK_SIZE);
30
31                 memset(y, 0, TF_BLOCK_SIZE);
32                 tf_encrypt_rawblk(y, y, ukey);
33                 for (i = 0; i < TF_NR_BLOCK_UNITS; i++) y[i] ^= x[i];
34
35                 data_to_words(y, TF_BLOCK_SIZE);
36                 memcpy(uout, y, sl);
37         }
38
39         memset(x, 0, TF_BLOCK_SIZE);
40         memset(y, 0, TF_BLOCK_SIZE);
41 }
42
43 void tf_ecb_decrypt(const void *key, void *out, const void *in, size_t sz)
44 {
45         const TF_BYTE_TYPE *uin = in;
46         TF_BYTE_TYPE *uout = out;
47         TF_UNIT_TYPE x[TF_NR_BLOCK_UNITS], y[TF_NR_BLOCK_UNITS];
48         const TF_UNIT_TYPE *ukey = key;
49         size_t sl = sz, i;
50
51         if (sl >= TF_BLOCK_SIZE) {
52                 do {
53                         memcpy(x, uin, TF_BLOCK_SIZE);
54                         uin += TF_BLOCK_SIZE;
55                         data_to_words(x, TF_BLOCK_SIZE);
56
57                         tf_decrypt_rawblk(y, x, ukey);
58
59                         data_to_words(y, TF_BLOCK_SIZE);
60                         memcpy(uout, y, TF_BLOCK_SIZE);
61                         uout += TF_BLOCK_SIZE;
62                 } while ((sl -= TF_BLOCK_SIZE) >= TF_BLOCK_SIZE);
63         }
64
65         if (sl) {
66                 memset(x, 0, TF_BLOCK_SIZE);
67                 memcpy(x, uin, sl);
68                 data_to_words(x, TF_BLOCK_SIZE);
69
70                 memset(y, 0, TF_BLOCK_SIZE);
71                 tf_decrypt_rawblk(y, y, ukey);
72                 for (i = 0; i < TF_NR_BLOCK_UNITS; i++) y[i] ^= x[i];
73
74                 data_to_words(y, TF_BLOCK_SIZE);
75                 memcpy(uout, y, sl);
76         }
77
78         memset(x, 0, TF_BLOCK_SIZE);
79         memset(y, 0, TF_BLOCK_SIZE);
80 }