加密函数:
btea_encrypt(T_buffer, TEA_key );
TX_buffer是需要发送的数据,经过该函数后,TX_buffer便是加密后的数据。
解密函数:
btea_decrpyt(RX_buffer, TEA_key);
RX_buffer是接收到的加密数据,经过该函数,RX_buffer便是解密后的数据(即实际传输数据)
BLOCK_SIZE 要和数据长度相等
单片机源程序如下:
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- /*******************
- TEA加密解密算法
- *******************/
- #define DATA_LEN 32
- #define MX (z>>5^y<<2)+(y>>3^z<<4)^(sum^y)+(k[p&3^e]^z)
- #define DELTA 0x9e3779b9
- #define S_LOOPTIME 1 //5
- #define BLOCK_SIZE DATA_LEN //PAGE_SIZE,根据你所要加密的数据包长度修改此参数(单位:字节)
- unsigned char TEA_key[16]=
- {
- 0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,
- 0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F,0x10
- };
- //数据缓冲区
- unsigned char TX_buffer[DATA_LEN];
- unsigned char RX_buffer[DATA_LEN];
- /*加密时使用函数, buf里面的内容就是加密后的数据,key是加密密钥*/
- void btea_encrypt( unsigned char* buf, unsigned char* key )
- {
- unsigned char n=BLOCK_SIZE/4;
- unsigned long *v=(unsigned long *)buf;
- unsigned long *k=(unsigned long *)key;
- unsigned long z = v[n - 1],y = v[0],sum = 0,e ;
- unsigned char p,q ;
- // Coding Part
- q = S_LOOPTIME + 52 / n ;
- while ( q-- > 0 )
- {
- sum += DELTA ;
- e = sum >> 2 & 3 ;
- for ( p = 0 ; p < n - 1 ; p++ )
- y = v[p + 1],
- z = v[p] += MX;
- y = v[0] ;
- z = v[n - 1] += MX;
- }
- }
- /*解密时使用函数, buf里面的内容就是解密后的数据,key是解密密钥*/
- void btea_decrpyt( unsigned char* buf, unsigned char* key )
- {
- unsigned char n=BLOCK_SIZE/4;
- unsigned long *v=(unsigned long *)buf;
- unsigned long *k=(unsigned long *)key;
- unsigned long z = v[n - 1],y = v[0],sum = 0,e ;
- unsigned char p,q ;
- //Decoding Part...
- q = S_LOOPTIME + 52 / n ;
- sum = q * DELTA ;
- while ( sum != 0 )
- {
- e = sum >> 2 & 3 ;
- for ( p = n - 1 ; p > 0 ; p-- )
- z = v[p - 1],
- y = v[p] -= MX;
- z = v[n - 1] ;
- y = v[0] -= MX;
- sum -= DELTA ;
- }
- }
- /************************************************************************************************************/
- void CreateBUF(unsigned char *buf)
- {
- int i = 0;
- for (i = 0;i < DATA_LEN; i++)
- {
- buf[i] = rand()%255;
- }
- }
- void Trans(unsigned char *buf1, unsigned char *buf2)
- {
- int i = 0;
- for (i = 0;i < DATA_LEN; i++)
- {
- buf2[i] = buf1[i];
- }
- }
- void DIS(unsigned char sts, unsigned char*buf)
- {
- int i = 0;
-
- printf("\n");
- switch (sts)
- {
- case 0: printf("实际发送数组:"); break;
- case 1: printf("加密数据数组:"); break;
- case 2: printf("实际接收数组:"); break;
- default: break;
- }
- for (i = 0;i < DATA_LEN; i++)
- {
- printf("%d ", buf[i]);
- }
- printf("\n");
- }
- int main(void)
- {
- srand((time(NULL)));
- CreateBUF(TX_buffer); //生成一组随机数
- DIS(0,TX_buffer); //显示实际数据
- btea_encrypt(TX_buffer, TEA_key); //发送数组加密
- DIS(1,TX_buffer); //显示加密后的数据
- Trans(TX_buffer, RX_buffer); //模拟信道
- btea_decrpyt(RX_buffer, TEA_key); //接收数组解密
- DIS(2, RX_buffer); //显示接收数据
- return 0;
- }
复制代码
所有资料51hei提供下载:
TEA加密解密.zip
(209.98 KB, 下载次数: 73)
|