资源描述:
《TEA加密算法的C、C++实现》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、TEA加密算法的C/C++实现啥都不说,直接贴代码,这是转发的哦,来源:Linux联盟收集整理 首先是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 consta
2、nt */ 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
3、<<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=0x9e3779b
4、9; /* 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) +
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了:util.h 1 #ifndef UTIL_H 2 #define UTIL_H 3 4 #incl
6、ude 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:1
7、0 -> 'A',15 -> 'F'18 */19 char intToHexChar(int x);20 21 /*22 *convert hex char to int.23 *example:'A' -> 10,'F' -> 1524 */25 int hexCharToInt(char hex);26 27 using std::string;28 /*29 *convert a byte array to hex string.30 *hex string format example:"
8、AF B0 80 7D"31 */32 string bytesToHexString(const byte *in, size_t size);33 34 /*35 *convert a hex string to a byte array.36 *hex string format example:"AF B0 80 7D"37 */38 size_t hexStringToBytes(const string &str, byte *out);39 40 #en