资源描述:
《TEA加密算法的C、C++实现.doc》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
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 constant */ 4 unsigned
2、 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);/*
3、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 unsi
4、gned 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 -= del
5、ta; /* 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 #include 5 #include 6 #include 7 8 typedef unsigned char byte; 9 typedef unsi
6、gned 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' -> 1524
7、 */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(const byte *in, size_t size);33 34 /*35 *convert a hex string to a byte array.36 *hex string for
8、mat example:"AF B0 80 7D"37 */38 size_t hexStringToBytes(const string &str, byte *out);39 40 #en