函数说明:
update函数:这是一个可重入的函数。每次调用传进去的字符串都会和之前的字符串链接。当然,第一次调用update时,之前的字符串长度为0。count[]数组内部保存了字符串长度的位数,所以每次用count[]数组计算时要注意byte与bit的转化。
调用该函数时,首先会计算字符串长度,等于已有字符串长度加上新加字符串长度,然后判断总长度是否大于64,或者说判断新加的字符串有没有补上之前字符串差的那一部分。
有两种情况:
1.如果大于,那么把补上的这部分加之前的用线性函数去转化散列。把除去补的那部分剩余部分放在缓冲区等待下一次调用update函数,因为后面我们会填充10000...0以及长度。
2.如果不大于,那就直接把字符串放进缓冲区,等待补位。
3.如果特别特别大,是一个chunks,那么就把chunks划分成64bytes为一组,足够64bytes的就转化,不足的和上面一样,放进缓冲区,等待补位。
finalize函数:
负责填充1000...0以及长度length,长度是以bit为单位的。一共预留512-448=64位即8个字节来存放长度,所以长度最大值为2^64,超出了只保留最低64位。
参考图:
代码如下:
md5_config.h
#pragma once
//constants for md5transform routine
#define S11 7
#define S12 12
#define S13 17
#define S14 22
#define S21 5
#define S22 9
#define S23 14
#define S24 20
#define S31 4
#define S32 11
#define S33 16
#define S34 23
#define S41 6
#define S42 10
#define S43 15
#define S44 21
md5.h
#ifndef _MD5_H
#define _MD5_H
#include "lb_util.h"
#include "md5_config.h"
namespace lb
{
typedef unsigned int u_int;
typedef unsigned char u_char;
static const int BUFFER_SIZE = 1000; //buffer size
static const int BLOCK_SIZE = 64; //64 //64 * sizeof(u_char) = 512;
static const int DIGEST_SIZE = 16; //16 //16 * 8 = 128
class md5 {
public:
md5(const std::string& sz);
void update(const u_char* input, size_t length);
void update(const char* input, size_t length);
void digest(char* buf) const;
protected:
void init();
void finalize();
void transform(const u_char block[BLOCK_SIZE]);
void en