-
-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathxtea.c
More file actions
87 lines (73 loc) · 2.38 KB
/
xtea.c
File metadata and controls
87 lines (73 loc) · 2.38 KB
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
// SPDX-License-Identifier: MIT
//! \file xtea.c
//! \brief xtea implementation.
#include "xtea.h"
#include "trice.h"
#if ((TRICE_DIRECT_XTEA_ENCRYPT == 1) || (TRICE_DEFERRED_XTEA_ENCRYPT == 1)) && TRICE_OFF == 0
//! golang XTEA works with 64 rounds
static const unsigned int numRounds = 64;
//! 128 bit static key
static const uint32_t k[4] = XTEA_ENCRYPT_KEY;
//! internal constant
static const uint32_t delta = 0x9E3779B9;
//! precomputed values for faster execution
static uint32_t table[64];
// Public API is documented in xtea.h.
// The table can be precomputed at compile time if desired.
void XTEAInitTable(void) {
uint32_t sum = 0;
unsigned i;
// Two rounds of XTEA applied per loop
for (i = 0; i < numRounds;) {
table[i] = sum + k[sum & 3];
i++;
sum += delta;
table[i] = sum + k[(sum >> 11) & 3]; // lint !e661 Warning 661: Possible access of out-of-bounds pointer (1 beyond end of data) by operator '['
i++;
}
}
// encipher converts 64 bits.
//! Code taken and adapted from xtea\block.go
//! \param v 64 bits of data in v[0] and v[1] are encoded in place
static void encipher(uint32_t v[2]) {
uint32_t v0 = v[0], v1 = v[1];
unsigned i;
for (i = 0; i < numRounds;) {
v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ table[i];
i++;
v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ table[i]; // lint !e661 Warning 661: Possible access of out-of-bounds pointer (1 beyond end of data) by operator '['
i++;
}
v[0] = v0;
v[1] = v1;
}
#if XTEA_DECRYPT == 1
//! decipher reverses encipher action.
//! Code taken and adapted from xtea\block.go
//! \param v 64 bits of data in v[0] and v[1] are decoded in place
static void decipher(uint32_t v[2]) {
uint32_t v0 = v[0], v1 = v[1];
for (int i = numRounds; i > 0;) {
i--;
v1 -= (((v0 << 4) ^ (v0 >> 5)) + v0) ^ table[i];
i--;
v0 -= (((v1 << 4) ^ (v1 >> 5)) + v1) ^ table[i];
}
v[0] = v0;
v[1] = v1;
}
// Public API is documented in xtea.h.
void XTEADecrypt(uint32_t* p, unsigned count) {
for (int i = 0; i < count; i += 2) {
decipher(&p[i]); // byte swapping is done inside receiver according to endianness.
}
}
#endif // #if XTEA_DECRYPT == 1
// Public API is documented in xtea.h.
void XTEAEncrypt(uint32_t* p, unsigned count) {
unsigned i;
for (i = 0; i < count; i += 2) {
encipher(&p[i]); // byte swap is done inside receiver
}
}
#endif // #if ((TRICE_DIRECT_XTEA_ENCRYPT == 1) || (TRICE_DEFERRED_XTEA_ENCRYPT == 1)) && TRICE_OFF == 0