c++MD5算法

来源:互联网 发布:微信美化软件 编辑:程序博客网 时间:2024/04/30 21:28

关于MD5的C源码,请参考大牛的另外一篇文章:MD5的C源码


md5.h:

[cpp] view plaincopy
  1. #ifndef MD5_H  
  2. #define MD5_H  
  3.   
  4. #include <string>  
  5. #include <fstream>  
  6.   
  7. /* Type define */  
  8. typedef unsigned char byte;  
  9. typedef unsigned int uint32;  
  10.   
  11. using std::string;  
  12. using std::ifstream;  
  13.   
  14. /* MD5 declaration. */  
  15. class MD5 {  
  16. public:  
  17.     MD5();  
  18.     MD5(const void *input, size_t length);  
  19.     MD5(const string &str);  
  20.     MD5(ifstream &in);  
  21.     void update(const void *input, size_t length);  
  22.     void update(const string &str);  
  23.     void update(ifstream &in);  
  24.     const byte* digest();  
  25.     string toString();  
  26.     void reset();  
  27. private:  
  28.     void update(const byte *input, size_t length);  
  29.     void final();  
  30.     void transform(const byte block[64]);  
  31.     void encode(const uint32 *input, byte *output, size_t length);  
  32.     void decode(const byte *input, uint32 *output, size_t length);  
  33.     string bytesToHexString(const byte *input, size_t length);  
  34.   
  35.     /* class uncopyable */  
  36.     MD5(const MD5&);  
  37.     MD5& operator=(const MD5&);  
  38. private:  
  39.     uint32 _state[4];   /* state (ABCD) */  
  40.     uint32 _count[2];   /* number of bits, modulo 2^64 (low-order word first) */  
  41.     byte _buffer[64];   /* input buffer */  
  42.     byte _digest[16];   /* message digest */  
  43.     bool _finished;     /* calculate finished ? */  
  44.   
  45.     static const byte PADDING[64];  /* padding for calculate */  
  46.     static const char HEX[16];  
  47.     static const size_t BUFFER_SIZE = 1024;  
  48. };  
  49.   
  50. #endif/*MD5_H*/  

md5.cpp:
[cpp] view plaincopy
  1. #include "md5.h"  
  2.   
  3. using namespace std;  
  4.   
  5. /* Constants for MD5Transform routine. */  
  6. #define S11 7  
  7. #define S12 12  
  8. #define S13 17  
  9. #define S14 22  
  10. #define S21 5  
  11. #define S22 9  
  12. #define S23 14  
  13. #define S24 20  
  14. #define S31 4  
  15. #define S32 11  
  16. #define S33 16  
  17. #define S34 23  
  18. #define S41 6  
  19. #define S42 10  
  20. #define S43 15  
  21. #define S44 21  
  22.   
  23.   
  24. /* F, G, H and I are basic MD5 functions. 
  25. */  
  26. #define F(x, y, z) (((x) & (y)) | ((~x) & (z)))  
  27. #define G(x, y, z) (((x) & (z)) | ((y) & (~z)))  
  28. #define H(x, y, z) ((x) ^ (y) ^ (z))  
  29. #define I(x, y, z) ((y) ^ ((x) | (~z)))  
  30.   
  31. /* ROTATE_LEFT rotates x left n bits. 
  32. */  
  33. #define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32-(n))))  
  34.   
  35. /* FF, GG, HH, and II transformations for rounds 1, 2, 3, and 4. 
  36. Rotation is separate from addition to prevent recomputation. 
  37. */  
  38. #define FF(a, b, c, d, x, s, ac) { \  
  39.     (a) += F ((b), (c), (d)) + (x) + ac; \  
  40.     (a) = ROTATE_LEFT ((a), (s)); \  
  41.     (a) += (b); \  
  42. }  
  43. #define GG(a, b, c, d, x, s, ac) { \  
  44.     (a) += G ((b), (c), (d)) + (x) + ac; \  
  45.     (a) = ROTATE_LEFT ((a), (s)); \  
  46.     (a) += (b); \  
  47. }  
  48. #define HH(a, b, c, d, x, s, ac) { \  
  49.     (a) += H ((b), (c), (d)) + (x) + ac; \  
  50.     (a) = ROTATE_LEFT ((a), (s)); \  
  51.     (a) += (b); \  
  52. }  
  53. #define II(a, b, c, d, x, s, ac) { \  
  54.     (a) += I ((b), (c), (d)) + (x) + ac; \  
  55.     (a) = ROTATE_LEFT ((a), (s)); \  
  56.     (a) += (b); \  
  57. }  
  58.   
  59.   
  60. const byte MD5::PADDING[64] = { 0x80 };  
  61. const char MD5::HEX[16] = {  
  62.     '0''1''2''3',  
  63.     '4''5''6''7',  
  64.     '8''9''a''b',  
  65.     'c''d''e''f'  
  66. };  
  67.   
  68. /* Default construct. */  
  69. MD5::MD5() {  
  70.     reset();  
  71. }  
  72.   
  73. /* Construct a MD5 object with a input buffer. */  
  74. MD5::MD5(const void *input, size_t length) {  
  75.     reset();  
  76.     update(input, length);  
  77. }  
  78.   
  79. /* Construct a MD5 object with a string. */  
  80. MD5::MD5(const string &str) {  
  81.     reset();  
  82.     update(str);  
  83. }  
  84.   
  85. /* Construct a MD5 object with a file. */  
  86. MD5::MD5(ifstream &in) {  
  87.     reset();  
  88.     update(in);  
  89. }  
  90.   
  91. /* Return the message-digest */  
  92. const byte* MD5::digest() {  
  93.     if (!_finished) {  
  94.         _finished = true;  
  95.         final();  
  96.     }  
  97.     return _digest;  
  98. }  
  99.   
  100. /* Reset the calculate state */  
  101. void MD5::reset() {  
  102.   
  103.     _finished = false;  
  104.     /* reset number of bits. */  
  105.     _count[0] = _count[1] = 0;  
  106.     /* Load magic initialization constants. */  
  107.     _state[0] = 0x67452301;  
  108.     _state[1] = 0xefcdab89;  
  109.     _state[2] = 0x98badcfe;  
  110.     _state[3] = 0x10325476;  
  111. }  
  112.   
  113. /* Updating the context with a input buffer. */  
  114. void MD5::update(const void *input, size_t length) {  
  115.     update((const byte*)input, length);  
  116. }  
  117.   
  118. /* Updating the context with a string. */  
  119. void MD5::update(const string &str) {  
  120.     update((const byte*)str.c_str(), str.length());  
  121. }  
  122.   
  123. /* Updating the context with a file. */  
  124. void MD5::update(ifstream &in) {  
  125.   
  126.     if (!in)  
  127.         return;  
  128.   
  129.     std::streamsize length;  
  130.     char buffer[BUFFER_SIZE];  
  131.     while (!in.eof()) {  
  132.         in.read(buffer, BUFFER_SIZE);  
  133.         length = in.gcount();  
  134.         if (length > 0)  
  135.             update(buffer, length);  
  136.     }  
  137.     in.close();  
  138. }  
  139.   
  140. /* MD5 block update operation. Continues an MD5 message-digest 
  141. operation, processing another message block, and updating the 
  142. context. 
  143. */  
  144. void MD5::update(const byte *input, size_t length) {  
  145.   
  146.     uint32 i, index, partLen;  
  147.   
  148.     _finished = false;  
  149.   
  150.     /* Compute number of bytes mod 64 */  
  151.     index = (uint32)((_count[0] >> 3) & 0x3f);  
  152.   
  153.     /* update number of bits */  
  154.     if((_count[0] += ((uint32)length << 3)) < ((uint32)length << 3))  
  155.         _count[1]++;  
  156.     _count[1] += ((uint32)length >> 29);  
  157.   
  158.     partLen = 64 - index;  
  159.   
  160.     /* transform as many times as possible. */  
  161.     if(length >= partLen) {  
  162.   
  163.         memcpy(&_buffer[index], input, partLen);  
  164.         transform(_buffer);  
  165.   
  166.         for (i = partLen; i + 63 < length; i += 64)  
  167.             transform(&input[i]);  
  168.         index = 0;  
  169.   
  170.     } else {  
  171.         i = 0;  
  172.     }  
  173.   
  174.     /* Buffer remaining input */  
  175.     memcpy(&_buffer[index], &input[i], length-i);  
  176. }  
  177.   
  178. /* MD5 finalization. Ends an MD5 message-_digest operation, writing the 
  179. the message _digest and zeroizing the context. 
  180. */  
  181. void MD5::final() {  
  182.   
  183.     byte bits[8];  
  184.     uint32 oldState[4];  
  185.     uint32 oldCount[2];  
  186.     uint32 index, padLen;  
  187.   
  188.     /* Save current state and count. */  
  189.     memcpy(oldState, _state, 16);  
  190.     memcpy(oldCount, _count, 8);  
  191.   
  192.     /* Save number of bits */  
  193.     encode(_count, bits, 8);  
  194.   
  195.     /* Pad out to 56 mod 64. */  
  196.     index = (uint32)((_count[0] >> 3) & 0x3f);  
  197.     padLen = (index < 56) ? (56 - index) : (120 - index);  
  198.     update(PADDING, padLen);  
  199.   
  200.     /* Append length (before padding) */  
  201.     update(bits, 8);  
  202.   
  203.     /* Store state in digest */  
  204.     encode(_state, _digest, 16);  
  205.   
  206.     /* Restore current state and count. */  
  207.     memcpy(_state, oldState, 16);  
  208.     memcpy(_count, oldCount, 8);  
  209. }  
  210.   
  211. /* MD5 basic transformation. Transforms _state based on block. */  
  212. void MD5::transform(const byte block[64]) {  
  213.   
  214.     uint32 a = _state[0], b = _state[1], c = _state[2], d = _state[3], x[16];  
  215.   
  216.     decode(block, x, 64);  
  217.   
  218.     /* Round 1 */  
  219.     FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */  
  220.     FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */  
  221.     FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */  
  222.     FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */  
  223.     FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */  
  224.     FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */  
  225.     FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */  
  226.     FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */  
  227.     FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */  
  228.     FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */  
  229.     FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */  
  230.     FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */  
  231.     FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */  
  232.     FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */  
  233.     FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */  
  234.     FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */  
  235.   
  236.     /* Round 2 */  
  237.     GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */  
  238.     GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */  
  239.     GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */  
  240.     GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */  
  241.     GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */  
  242.     GG (d, a, b, c, x[10], S22,  0x2441453); /* 22 */  
  243.     GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */  
  244.     GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */  
  245.     GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */  
  246.     GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */  
  247.     GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */  
  248.     GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */  
  249.     GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */  
  250.     GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */  
  251.     GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */  
  252.     GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */  
  253.   
  254.     /* Round 3 */  
  255.     HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */  
  256.     HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */  
  257.     HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */  
  258.     HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */  
  259.     HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */  
  260.     HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */  
  261.     HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */  
  262.     HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */  
  263.     HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */  
  264.     HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */  
  265.     HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */  
  266.     HH (b, c, d, a, x[ 6], S34,  0x4881d05); /* 44 */  
  267.     HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */  
  268.     HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */  
  269.     HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */  
  270.     HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */  
  271.   
  272.     /* Round 4 */  
  273.     II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */  
  274.     II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */  
  275.     II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */  
  276.     II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */  
  277.     II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */  
  278.     II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */  
  279.     II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */  
  280.     II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */  
  281.     II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */  
  282.     II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */  
  283.     II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */  
  284.     II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */  
  285.     II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */  
  286.     II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */  
  287.     II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */  
  288.     II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */  
  289.   
  290.     _state[0] += a;  
  291.     _state[1] += b;  
  292.     _state[2] += c;  
  293.     _state[3] += d;  
  294. }  
  295.   
  296. /* Encodes input (ulong) into output (byte). Assumes length is 
  297. a multiple of 4. 
  298. */  
  299. void MD5::encode(const uint32 *input, byte *output, size_t length) {  
  300.   
  301.     for(size_t i=0, j=0; j<length; i++, j+=4) {  
  302.         output[j]= (byte)(input[i] & 0xff);  
  303.         output[j+1] = (byte)((input[i] >> 8) & 0xff);  
  304.         output[j+2] = (byte)((input[i] >> 16) & 0xff);  
  305.         output[j+3] = (byte)((input[i] >> 24) & 0xff);  
  306.     }  
  307. }  
  308.   
  309. /* Decodes input (byte) into output (ulong). Assumes length is 
  310. a multiple of 4. 
  311. */  
  312. void MD5::decode(const byte *input, uint32 *output, size_t length) {  
  313.   
  314.     for(size_t i=0, j=0; j<length; i++, j+=4) {    
  315.         output[i] = ((uint32)input[j]) | (((uint32)input[j+1]) << 8) |  
  316.             (((uint32)input[j+2]) << 16) | (((uint32)input[j+3]) << 24);  
  317.     }  
  318. }  
  319.   
  320. /* Convert byte array to hex string. */  
  321. string MD5::bytesToHexString(const byte *input, size_t length) {  
  322.     string str;  
  323.     str.reserve(length << 1);  
  324.     for(size_t i = 0; i < length; i++) {  
  325.         int t = input[i];  
  326.         int a = t / 16;  
  327.         int b = t % 16;  
  328.         str.append(1, HEX[a]);  
  329.         str.append(1, HEX[b]);  
  330.     }  
  331.     return str;  
  332. }  
  333.   
  334. /* Convert digest to string value */  
  335. string MD5::toString() {  
  336.     return bytesToHexString(digest(), 16);  
  337. }  

测试文件test.cpp:
[cpp] view plaincopy
  1. #include "md5.h"  
  2. #include <iostream>  
  3.   
  4. using namespace std;  
  5.   
  6. void PrintMD5(const string &str, MD5 &md5) {  
  7.     cout << "MD5(\"" << str << "\") = " << md5.toString() << endl;  
  8. }  
  9.   
  10. string FileDigest(const string &file) {  
  11.   
  12.     ifstream in(file.c_str(), ios::binary);  
  13.     if (!in)  
  14.         return "";  
  15.   
  16.     MD5 md5;  
  17.     std::streamsize length;  
  18.     char buffer[1024];  
  19.     while (!in.eof()) {  
  20.         in.read(buffer, 1024);  
  21.         length = in.gcount();  
  22.         if (length > 0)  
  23.             md5.update(buffer, length);  
  24.     }  
  25.     in.close();  
  26.     return md5.toString();  
  27. }  
  28.   
  29. int main() {  
  30.   
  31.     cout << MD5("abc").toString() << endl;  
  32.     cout << MD5(ifstream("D:\\test.txt")).toString() << endl;  
  33.     cout << MD5(ifstream("D:\\test.exe", ios::binary)).toString() << endl;  
  34.     cout << FileDigest("D:\\test.exe") << endl;  
  35.   
  36.     MD5 md5;  
  37.     md5.update("");  
  38.     PrintMD5("", md5);  
  39.   
  40.     md5.update("a");  
  41.     PrintMD5("a", md5);  
  42.   
  43.     md5.update("bc");  
  44.     PrintMD5("abc", md5);  
  45.   
  46.     md5.update("defghijklmnopqrstuvwxyz");  
  47.     PrintMD5("abcdefghijklmnopqrstuvwxyz", md5);  
  48.   
  49.     md5.reset();  
  50.     md5.update("message digest");  
  51.     PrintMD5("message digest", md5);  
  52.   
  53.     md5.reset();  
  54.     md5.update(ifstream("D:\\test.txt"));  
  55.     PrintMD5("D:\\test.txt", md5);  
  56.     return 0;  
  57. }  

类MD5封装了与MD5相关的操作,其有

4个构造函数:

MD5();                                                                             //默认构造函数
MD5(const void *input, size_t length);                      //输入内存地址与长度信息的构造函数
MD5(const string &str);                                               //输入字符串的构造函数
MD5(ifstream &in);                                                      //输入流的构造函数

3个Update函数:

void update(const void *input, size_t length);       //往MD5对象内添加内存块
void update(const string &str);                                //添加字符串
void update(ifstream &in);                                        //添加流


const byte* digest();                                                 //计算MD5码,并返回指向它的指针

string toString();                                                       //计算MD5,并返回其对应的字符串

void reset();                                                              //重置,



test.cpp文件内的main函数描述了MD5类的用法.


转自:MD5算法

0 0