fix little endian vs big endian in the macros... again... but this time correct
[RRG-proxmark3.git] / client / src / tea.c
blobb2a425e11d2ae186c558d100d795cfaa5a6f1733
1 //-----------------------------------------------------------------------------
2 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
3 // at your option, any later version. See the LICENSE.txt file for the text of
4 // the license.
5 //-----------------------------------------------------------------------------
6 // Generic TEA crypto code.
7 // ref: http://143.53.36.235:8080/source.htm#ansi
8 //-----------------------------------------------------------------------------
9 #include "tea.h"
11 #include "commonutil.h" // bytes_to_num etc
13 #define ROUNDS 32
14 #define DELTA 0x9E3779B9
15 #define SUM 0xC6EF3720
17 void tea_encrypt(uint8_t *v, uint8_t *key) {
19 uint32_t a = 0, b = 0, c = 0, d = 0, y = 0, z = 0;
20 uint32_t sum = 0;
21 uint8_t n = ROUNDS;
23 //key
24 a = bytes_to_num(key, 4);
25 b = bytes_to_num(key + 4, 4);
26 c = bytes_to_num(key + 8, 4);
27 d = bytes_to_num(key + 12, 4);
29 //input
30 y = bytes_to_num(v, 4);
31 z = bytes_to_num(v + 4, 4);
33 while (n-- > 0) {
34 sum += DELTA;
35 y += ((z << 4) + a) ^ (z + sum) ^ ((z >> 5) + b);
36 z += ((y << 4) + c) ^ (y + sum) ^ ((y >> 5) + d);
39 num_to_bytes(y, 4, v);
40 num_to_bytes(z, 4, v + 4);
43 void tea_decrypt(uint8_t *v, uint8_t *key) {
45 uint32_t a = 0, b = 0, c = 0, d = 0, y = 0, z = 0;
46 uint32_t sum = SUM;
47 uint8_t n = ROUNDS;
49 //key
50 a = bytes_to_num(key, 4);
51 b = bytes_to_num(key + 4, 4);
52 c = bytes_to_num(key + 8, 4);
53 d = bytes_to_num(key + 12, 4);
55 //input
56 y = bytes_to_num(v, 4);
57 z = bytes_to_num(v + 4, 4);
59 /* sum = delta<<5, in general sum = delta * n */
60 while (n-- > 0) {
61 z -= ((y << 4) + c) ^ (y + sum) ^ ((y >> 5) + d);
62 y -= ((z << 4) + a) ^ (z + sum) ^ ((z >> 5) + b);
63 sum -= DELTA;
65 num_to_bytes(y, 4, v);
66 num_to_bytes(z, 4, v + 4);