HiveBrain v1.2.0
Get Started
← Back to all entries
patterncModerate

Tiny Encryption Algorithm (TEA) for arbitrary sized data

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
encryptionarbitrarysizedteatinyalgorithmfordata

Problem

The TEA is a very simple encryption algorithm requiring little time and space - perfect for embedded systems. There are extensions to it, and every version has its flaws (WEP was based on it), but for casual protection it's perfect.

Also, the encrypt and decrypt routines are exactly as found from Wikipedia, so I don't expect anyone to check that I'm following the TEA correctly - I'm more interested in the block routines I've added, though if you notice something about the TEA routines it would be good to know.

tea.h

#ifndef __TEA.H__
#define __TEA.H__

#include 

void encrypt (uint32_t* v, uint32_t* k);
void decrypt (uint32_t* v, uint32_t* k);
void encryptBlock(uint8_t * data, uint32_t * len, uint32_t * key);
void decryptBlock(uint8_t * data, uint32_t * len, uint32_t * key);

#endif


tea.c

```
#include "tea.h"
/* encryptBlock
* Encrypts byte array data of length len with key key using TEA
* Arguments:
* data - pointer to 8 bit data array to be encrypted - SEE NOTES
* len - length of array
* key - Pointer to four integer array (16 bytes) holding TEA key
* Returns:
* data - encrypted data held here
* len - size of the new data array
* Side effects:
* Modifies data and len
* NOTES:
data size must be equal to or larger than ((len + 7) / 8) 8 + 8
* TEA encrypts in 8 byte blocks, so it must include enough space to
* hold the entire data to pad out to an 8 byte boundary, plus another
* 8 bytes at the end to give the length to the decrypt algorithm.
*
* - Shortcut - make sure that data is at least len + 15 bytes in size.
*/
void encryptBlock(uint8_t data, uint32_t len, uint32_t * key)
{
uint32_t blocks, i;
uint32_t * data32;

// treat the data as 32 bit unsigned integers
data32 = (uint32_t *) data;

// Find the number of 8 byte blocks, add one for the length
blocks = (((*len) + 7) / 8) + 1;

// Set the last block to the original data length
data32[(blocks2) - 1] = len;

// Set the encrypted

Solution

You should add some sanity checking on the incoming arguments, especially if you intend this to be library code used from multiple projects.

I would recommend you change definition of encryptBlock to require that len is a multiple of 8 bytes. Requiring that the incoming array is sized to a multiple of 8 bytes, but not enforcing that for len is a sure fire way to get memory corruption when someone forgets (e.g. when they are encrypting strings).

Personally I prefer to have the long descriptive comment in the header file rather than the .c file. Anyone using tea.h will find it more useful there.

Context

StackExchange Code Review Q#2050, answer score: 10

Revisions (0)

No revisions yet.