4 * Copyright 2006 Develer S.r.l. (http://www.develer.com/)
5 * This file is part of DevLib - See README.devlib for information.
8 * \brief TEA Tiny Encription Algorith functions (implementation).
11 * \author Francesco Sacchi <batt@develer.com>
13 * The Tiny Encryption Algorithm (TEA) by David Wheeler and Roger Needham
14 * of the Cambridge Computer Laboratory
16 * Placed in the Public Domain by David Wheeler and Roger Needham.
18 * **** ANSI C VERSION ****
22 * TEA is a Feistel cipher with XOR and and addition as the non-linear
25 * Takes 64 bits of data in v[0] and v[1]. Returns 64 bits of data in w[0]
26 * and w[1]. Takes 128 bits of key in k[0] - k[3].
28 * TEA can be operated in any of the modes of DES. Cipher Block Chaining is,
29 * for example, simple to implement.
31 * n is the number of iterations. 32 is ample, 16 is sufficient, as few
32 * as eight may be OK. The algorithm achieves good dispersion after six
33 * iterations. The iteration count can be made variable if required.
35 * Note this is optimised for 32-bit CPUs with fast shift capabilities. It
36 * can very easily be ported to assembly language on most CPUs.
38 * delta is chosen to be the real part of (the golden ratio Sqrt(5/4) -
39 * 1/2 ~ 0.618034 multiplied by 2^32).
44 *#* Revision 1.2 2007/09/19 16:23:27 batt
45 *#* Fix doxygen warnings.
47 *#* Revision 1.1 2007/06/07 09:13:40 batt
48 *#* Add TEA enc/decryption algorithm.
50 *#* Revision 1.1 2007/01/10 17:30:10 batt
51 *#* Add cryptographic routines.
56 #include <mware/byteorder.h>
58 static uint32_t tea_func(uint32_t *in, uint32_t *sum, uint32_t *k)
60 return ((*in << 4) + cpu_to_le32(k[0])) ^ (*in + *sum) ^ ((*in >> 5) + cpu_to_le32(k[1]));
64 * \brief TEA encryption function.
65 * This function encrypts <EM>v</EM> with <EM>k</EM> and returns the
66 * encrypted data in <EM>v</EM>.
67 * \param _v Array of two long values containing the data block.
68 * \param _k Array of four long values containing the key.
70 void tea_enc(void *_v, void *_k)
75 uint32_t *v = (uint32_t *)_v;
76 uint32_t *k = (uint32_t *)_k;
84 y += tea_func(&z, &sum, &(k[0]));
85 z += tea_func(&y, &sum, &(k[2]));
88 v[0] = le32_to_cpu(y);
89 v[1] = le32_to_cpu(z);
93 * \brief TEA decryption function.
94 * This function decrypts <EM>v</EM> with <EM>k</EM> and returns the
95 * decrypted data in <EM>v</EM>.
96 * \param _v Array of two long values containing the data block.
97 * \param _k Array of four long values containing the key.
99 void tea_dec(void *_v, void *_k)
102 uint32_t sum = DELTA * ROUNDS;
104 uint32_t *v = (uint32_t *)_v;
105 uint32_t *k = (uint32_t *)_k;
107 y = cpu_to_le32(v[0]);
108 z = cpu_to_le32(v[1]);
112 z -= tea_func(&y, &sum, &(k[2]));
113 y -= tea_func(&z, &sum, &(k[0]));
117 v[0] = le32_to_cpu(y);
118 v[1] = le32_to_cpu(z);