-
Notifications
You must be signed in to change notification settings - Fork 0
/
tfcbc.c
88 lines (72 loc) · 2.32 KB
/
tfcbc.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <string.h>
#include "tfdef.h"
void tf_cbc_encrypt(const void *key, void *iv, void *out, const void *in, size_t sz)
{
const TF_BYTE_TYPE *uin = (const TF_BYTE_TYPE *)in;
TF_BYTE_TYPE *uout = (TF_BYTE_TYPE *)out;
TF_UNIT_TYPE x[TF_NR_BLOCK_UNITS], y[TF_NR_BLOCK_UNITS];
TF_UNIT_TYPE *uiv = (TF_UNIT_TYPE *)iv;
const TF_UNIT_TYPE *ukey = (const TF_UNIT_TYPE *)key;
size_t sl = sz, i;
if (sl >= TF_BLOCK_SIZE) {
do {
memcpy(x, uin, TF_BLOCK_SIZE);
uin += TF_BLOCK_SIZE;
data_to_words(x, TF_BLOCK_SIZE);
for (i = 0; i < TF_NR_BLOCK_UNITS; i++) y[i] = x[i] ^ uiv[i];
tf_encrypt_rawblk(x, y, ukey);
memcpy(iv, x, TF_BLOCK_SIZE);
data_to_words(x, TF_BLOCK_SIZE);
memcpy(uout, x, TF_BLOCK_SIZE);
uout += TF_BLOCK_SIZE;
} while ((sl -= TF_BLOCK_SIZE) >= TF_BLOCK_SIZE);
}
if (sl) {
memset(x, 0, TF_BLOCK_SIZE);
memcpy(x, uin, sl);
data_to_words(x, TF_BLOCK_SIZE);
ctr_inc(uiv, TF_NR_BLOCK_UNITS);
tf_encrypt_rawblk(y, uiv, ukey);
for (i = 0; i < TF_NR_BLOCK_UNITS; i++) y[i] ^= x[i];
data_to_words(y, TF_BLOCK_SIZE);
memcpy(uout, y, sl);
}
memset(x, 0, TF_BLOCK_SIZE);
memset(y, 0, TF_BLOCK_SIZE);
}
void tf_cbc_decrypt(const void *key, void *iv, void *out, const void *in, size_t sz)
{
const TF_BYTE_TYPE *uin = (const TF_BYTE_TYPE *)in;
TF_BYTE_TYPE *uout = (TF_BYTE_TYPE *)out;
TF_UNIT_TYPE x[TF_NR_BLOCK_UNITS], y[TF_NR_BLOCK_UNITS], t[TF_NR_BLOCK_UNITS];
TF_UNIT_TYPE *uiv = (TF_UNIT_TYPE *)iv;
const TF_UNIT_TYPE *ukey = (const TF_UNIT_TYPE *)key;
size_t sl = sz, i;
if (sl >= TF_BLOCK_SIZE) {
do {
memcpy(x, uin, TF_BLOCK_SIZE);
uin += TF_BLOCK_SIZE;
data_to_words(x, TF_BLOCK_SIZE);
memcpy(t, x, TF_BLOCK_SIZE);
tf_decrypt_rawblk(y, x, ukey);
for (i = 0; i < TF_NR_BLOCK_UNITS; i++) y[i] ^= uiv[i];
memcpy(iv, t, TF_BLOCK_SIZE);
data_to_words(y, TF_BLOCK_SIZE);
memcpy(uout, y, TF_BLOCK_SIZE);
uout += TF_BLOCK_SIZE;
} while ((sl -= TF_BLOCK_SIZE) >= TF_BLOCK_SIZE);
}
if (sl) {
memset(x, 0, TF_BLOCK_SIZE);
memcpy(x, uin, sl);
data_to_words(x, TF_BLOCK_SIZE);
ctr_inc(uiv, TF_NR_BLOCK_UNITS);
tf_encrypt_rawblk(y, uiv, ukey);
for (i = 0; i < TF_NR_BLOCK_UNITS; i++) y[i] ^= x[i];
data_to_words(y, TF_BLOCK_SIZE);
memcpy(uout, y, sl);
}
memset(t, 0, TF_BLOCK_SIZE);
memset(x, 0, TF_BLOCK_SIZE);
memset(y, 0, TF_BLOCK_SIZE);
}