TEA 加密算法的C/C++实现 啥都不说,直接贴代码,这是转发的哦,来源:Lin u x 联盟收集整理 首先是C 版: 1 void encrypt(unsigned long *v, unsigned long *k) { 2 unsigned long y=v[0], z=v[1], sum=0, i; /* set up */ 3 unsigned long delta=0x9e3779b9; /* a key schedule constant */ 4 unsigned long a=k[0], b=k[1], c=k[2], d=k[3]; /* cache key */ 5 for (i=0; i < 32; i++) { /* basic cycle start */ 6 sum += delta; 7 y += ((z<<4) + a) ^ (z + sum) ^ ((z>>5) + b); 8 z += ((y<<4) + c) ^ (y + sum) ^ ((y>>5) + d);/* end cycle */ 9 } 10 v[0]=y; 11 v[1]=z; 12 } 13 14 void decrypt(unsigned long *v, unsigned long *k) { 15 unsigned long y=v[0], z=v[1], sum=0xC6EF3720, i; /* set up */ 16 unsigned long delta=0x9e3779b9; /* a key schedule constant */ 17 unsigned long a=k[0], b=k[1], c=k[2], d=k[3]; /* cache key */ 18 for(i=0; i<32; i++) { /* basic cycle start */ 19 z -= ((y<<4) + c) ^ (y + sum) ^ ((y>>5) + d); 20 y -= ((z<<4) + a) ^ (z + sum) ^ ((z>>5) + b); 21 sum -= delta; /* end cycle */ 22 } 23 v[0]=y; 24 v[1]=z; 25 } C 语言写的用起来当然不方便,没关系,用C++封装以下就 OK 了: u til.h 1 #ifndef UTIL_H 2 #define UTIL_H 3 4 #include 5 #include 6 #include 7 8 typedef unsigned char byte; 9 typedef unsigned long ulong; 10 11 inline double logbase(double base, double x) { 12 return log(x)/log(base); 13 } 14 15 /* 16 *convert int to hex char. 17 *example:10 -> 'A',15 -> 'F' 18 */ 19 char intToHexChar(int x); 20 21 /* 22 *convert hex char to int. 23 *example:'A' -> 10,'F' -> 15 24 */ 25 int hexCharToInt(char hex); 26 27 using std::string; 28 /* 29 *convert a byte array to hex string. 30 *hex string format example:"AF B0 80 7D" 31 */ 32 string bytesToHexString...