51 broke -E logic completely, rewise it
[tfcrypt.git] / tfe.c
1 #include <string.h>
2 #include "tfdef.h"
3 #include "tfe.h"
4
5 void tfe_init_iv(struct tfe_stream *tfe, const void *key, const void *iv)
6 {
7         memset(tfe, 0, sizeof(struct tfe_stream));
8         memcpy(tfe->key, key, TF_KEY_SIZE);
9         if (iv) memcpy(tfe->iv, iv, TF_BLOCK_SIZE);
10         tfe->tidx = 0;
11 }
12
13 void tfe_init(struct tfe_stream *tfe, const void *key)
14 {
15         tfe_init_iv(tfe, key, NULL);
16 }
17
18 void tfe_emit(void *dst, size_t szdst, struct tfe_stream *tfe)
19 {
20         TF_BYTE_TYPE *udst = dst;
21         size_t sz = szdst, trem;
22
23         if (!dst && szdst == 0) {
24                 memset(tfe, 0, sizeof(struct tfe_stream));
25                 return;
26         }
27
28         if (tfe->tidx > 0) {
29                 trem = TF_BLOCK_SIZE-tfe->tidx;
30
31                 if (szdst <= trem) {
32                         memcpy(udst, &tfe->tmp[tfe->tidx], szdst);
33                         tfe->tidx += szdst;
34                         if (tfe->tidx >= TF_BLOCK_SIZE) tfe->tidx = 0;
35                         return;
36                 }
37
38                 memcpy(udst, &tfe->tmp[tfe->tidx], trem);
39                 udst += trem;
40                 sz -= trem;
41                 tfe->tidx = 0;
42         }
43
44         if (sz >= TF_BLOCK_SIZE) {
45                 do {
46                         tf_encrypt_rawblk(tfe->iv, tfe->iv, tfe->key);
47                         memcpy(udst, tfe->iv, TF_BLOCK_SIZE);
48                         data_to_words(udst, TF_BLOCK_SIZE);
49                         udst += TF_BLOCK_SIZE;
50                 } while ((sz -= TF_BLOCK_SIZE) >= TF_BLOCK_SIZE);
51         }
52
53         if (sz) {
54                 tf_encrypt_rawblk(tfe->iv, tfe->iv, tfe->key);
55                 memcpy(tfe->tmp, tfe->iv, TF_BLOCK_SIZE);
56                 data_to_words(tfe->tmp, TF_BLOCK_SIZE);
57                 memcpy(udst, tfe->tmp, sz);
58                 tfe->tidx = sz;
59         }
60 }