Tiny Encryption Algorithm 加密演算法
阿新 • • 發佈:2021-01-19
技術標籤:汽車電子軟體BootLoader生產力工具加密演算法嵌入式程序升級
圖片來源於網路
目錄
1. 摘要
之前做專案,由於應用程式涉及的演算法屬於公司核心機密,為保證程式碼在程序升級的過程中不被“擷取”,於是,要在程序升級的過程中,對傳輸的檔案進行加密,要用到TEA加密演算法,本文對該演算法做了總結,希望能幫助有加密*需求的小夥伴:)
2. 原始碼
/*
* XXTEA.c
*
* Created on: Feb 27, 2018
* Author: Allen
*/
#include <stdio.h>
#include <string.h>
#define MX ( ((z>>5)^(y<<2)) + ((y>>3)^(z<<4)) ) ^ ( (sum^y) + (k[(p & 3)^e]^z) )
typedef unsigned int UInt32;
typedef int Int32;
typedef unsigned short int Word16;
typedef unsigned char U8;
U8 XXTEA (UInt32 *v, Int32 n, UInt32 *k);
Word16 bteaTest();
/**
* XXTEA, a Tiny Encryption Algorithm
* by David J. Wheeler, Roger M. Needham
*
* code reorganized by PTK.
*
* \param v Pointer to data array.
* \param n Number of entries in data array.
* - when coding positive number
* - when decoding negative number.
* - when 0 just exit with return 1
* \param k Key k[0] - k[3]. 128 bit
*
*/
UInt32 KEY[4] = {0};
/*****************************************************************************/
/*
/*****************************************************************************/
U8 XXTEA (UInt32 *v, Int32 n, UInt32 *k)
{
unsigned long z = v[n-1];
unsigned long y = v[0];
unsigned long sum = 0;
unsigned long DELTA = 0x9e3779b9;
unsigned long e;
long p;
long q;
if(n > 1) /* Coding Part */
{
q = 6 + (52 / n);
while(q-- > 0)
{
sum += DELTA;
e = (sum >> 2) & 3;
for(p = 0; p < (n - 1); p++)
{
y = v[p+1];
v[p]+= MX;
z = v[p];
}
y = v[0];
v[n-1] += MX;
z = v[n-1];
}
return (0);
}
else if(n < -1) /* Decoding Part */
{
n = -n;
q = 6 + (52 / n);
sum = q * DELTA;
while(sum != 0)
{
e = (sum >> 2) & 3;
for(p = (n - 1); p > 0; p--)
{
z = v[p-1];
v[p] -= MX;
y = v[p];
}
z = v[n-1];
v[0] -= MX;
y = v[0];
sum -= DELTA;
}
return (0);
}
return (1); /* Signal n=0 */
}
/*****************************************************************************/
/*
/*****************************************************************************/
#if 1
Word16 bteaTest()
{
UInt32 key[4] = { 0x01234567, 0x89ABCDEF, 0x01234567, 0x89ABCDEF };
UInt32 testVectorPlain[4] = { 0x00000000, 0x11111111, 0x22222222, 0x33333333 };
UInt32 testVectorEncrypted[4]= { 0xa7399503, 0x8b357cd8, 0x56ef7347, 0xa487d28b };
UInt32 buf[4];
Word16 i;
#if 1
memcpy(buf, testVectorPlain, sizeof(buf));
XXTEA(buf, 4, key);
for (i = 0; i < 4; i++)
{
if (buf[i] != testVectorEncrypted[i])
return 0;
}
#endif
#if 0
memcpy(buf, testVectorEncrypted, sizeof(buf));
XXTEA(buf, -4, key);
for (i = 0; i < 4; i++)
{
if (buf[i] != testVectorPlain[i])
return 0;
}
#endif
// ok
return 1;
}
#endif
int main()
{
Word16 tmp = bteaTest();
printf("Encrypted result:%d\r\n", tmp);
return 0;
}
3. 參考資料
【1】Tiny Encryption Algorithm
【2】tea演算法
【3】Tiny-Encryption-Algorithm
【4】TEA加密演算法的C++實現