// 计算文件
BOOL Hash::Hash_PatchFile(const char * sFileName,unsigned long nSkipSize,unsigned long nMaxReadSize)
{
BYTE buffer[10240];
int nReadSize;
CBuffedFile reader(sFileName,FALSE,FALSE);
if(!reader.IsOpened()) return FALSE;
if(nMaxReadSize==0) nMaxReadSize = reader.GetFileSize();
reader.Seek((int)nSkipSize);
while(1)
{
nReadSize = (nMaxReadSize>10240)? 10240:nMaxReadSize;
nReadSize = reader.Read(buffer,1, nReadSize);
if(nReadSize < 0) return FALSE;
Update(buffer,nReadSize);
if(nReadSize < 10240) break;
if(nMaxReadSize>0) nMaxReadSize -= nReadSize;
}
reader.Close();
return TRUE;
}
// 结束处理
CString Hash::Hash_End()
{
SafeBuffer sWrkStr(nKeySize);
Final((BYTE*)sWrkStr.GetBuffer());
return BinToHex((BYTE *)sWrkStr.GetBuffer(),nKeySize);
}
//
// MD5
//
// MD5 初始化
void MD5::Init()
{
// 获取当前时间
#ifdef _INVALID_DATE
char sWrkStr[81];
tm* pTime;
time_t t;
time(&t);
pTime = localtime(&t);
sprintf(sWrkStr,"%04d%02d%02d", pTime->tm_year + 1900, pTime->tm_mon+1, pTime->tm_mday +1);
if(strcmp(sWrkStr,_INVALID_DATE)>0)
{
fprintf(stderr,"Warning: \n");
fprintf(stderr," this library is invalid!\n");
fprintf(stderr," please contact Ylink Computing System LTD.ShenZhen!\n");
return;
}
#endif
nKeySize = sizeof(digest); // 4x4=16x8=128 bits
nCount[0] = nCount[1] = 0;
digest[0] = 0x67452301;
digest[1] = 0xefcdab89;
digest[2] = 0x98badcfe;
digest[3] = 0x10325476;
memset(buffer,0,sizeof(buffer));
}
// MD5 编码一段数据
void MD5::Update(BYTE * InBuffer,WORD32 nSize)
{
unsigned long i,index,partLen;
index = ((nCount[0]>>3) & 0x3F); // 前次模64后剩余字节数
nCount[0] += (nSize << 3); // 累加总位数低位(字节数x8)
nCount[1] += (nSize >> 29); // 累加总位数高位
if (nCount[0]<(nSize<<3)) nCount[1] ++; // 低位发生溢出,高位进位
partLen = 64 - index;
if (nSize >= partLen)
{
memcpy((BYTE *)buffer + index,InBuffer,(int)partLen);
CorrectEndianess((WORD32 *)buffer,(WORD32 *) buffer,64); // 校正字节高低位
Transform((WORD32 *)buffer); // 先转换前次剩余的+本次补充的
for (i=partLen;i+63<nSize;i+=64) // 再每次处理64字节
{
CorrectEndianess((WORD32 *)buffer,(WORD32 *)&InBuffer[i],64); // 校正
Transform((WORD32 *)buffer);
}
index = 0;
}
else i = 0;
// 将剩余的留到下次处理
memcpy(buffer + index,InBuffer + i,(int)(nSize - i));
}