📄 md5ex.cpp
字号:
#include "stdafx.h"
#include "MD5Ex.h"
MD5Ex::MD5Ex()
{
}
MD5Ex::~MD5Ex()
{
}
string MD5Ex::ResultToHex(unsigned char digest[16], bool bUppercase)
{
string strRetVal = "";
for(int i = 0 ; i < 16; i++)
{
char buf[3] = {0};
if(bUppercase)
sprintf(buf, "%02X", digest[i]);
else
sprintf(buf, "%02x", digest[i]);
strRetVal += buf;
}
return strRetVal;
}
void MD5Ex::OnFileProcessing(int nProgress, MemberFxn addr)
{
void* pThis = addr.GetThis();
unsigned long Addr = addr.GetAddr();
/** the Calling Convention must be __stdcall or
thiscall (thiscall not a keyword),
thiscall is the default calling convention used by C++ member functions
*/
__asm
{
push nProgress ;
mov ecx, pThis ;
call Addr ;
}
}
string MD5Ex::MD5String(unsigned char *pData, unsigned long DataLen, bool bUppercase)
{
MD5_CTX context;
unsigned char digest[16];
MD5Init (&context);
MD5Update (&context, pData, DataLen);
MD5Final (digest, &context);
return ResultToHex(digest, bUppercase);
}
string MD5Ex::MD5File(const char *FileName, bool bUppercase, MemberFxn addr)
{
MD5_CTX context;
FILE *file = 0;
int nFileBufSize = 10240; // 文件缓冲区大小
unsigned char *buffer = new unsigned char[nFileBufSize + 1];
unsigned char digest[16] = {0};
m_bTerminate = false;
try
{
if ((file = fopen (FileName, "rb")) == NULL)
{
m_strErr = "The file can't be opened!";
goto ERR;
}
else
{
int len = 0;
int ReadCount = 0;
unsigned long nFileSize = 0;
// 获取文件大小, 以下方式只能获取小于2^32字节的文件大小
{
HANDLE hFile = CreateFile(FileName, NULL, FILE_SHARE_READ, NULL, OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL, 0);
if(hFile== NULL)
{
m_strErr = "Get file size failed!";
goto ERR;
}
nFileSize=::GetFileSize(hFile, NULL);
CloseHandle(hFile);
}
if(!addr.IsNull())
OnFileProcessing(0, addr);
MD5Init(&context);
while (len = fread (buffer, 1, nFileBufSize, file))
{
ReadCount++;
if(m_bTerminate)
{
m_strErr = "User terminate calculate!";
goto ERR;
}
MD5Update(&context, buffer, len);
if(!addr.IsNull())
{
int n = (int)(nFileSize / 100);
if(n <= 0)
n = 1;
OnFileProcessing((int)(nFileBufSize * ReadCount / n), addr);
}
memset(buffer, nFileBufSize + 1, 0);
}
MD5Final(digest, &context);
if(!addr.IsNull())
OnFileProcessing(100, addr);
fclose (file);
delete[] buffer;
return ResultToHex(digest, bUppercase);
}
}
catch(...)
{
m_strErr = "UnKnow error!";
goto ERR;
}
ERR:
if(file != 0)
fclose (file);
delete[] buffer;
return "";
}
void MD5Ex::StopCalculate()
{
m_bTerminate = true;
}
string MD5Ex::GetError()
{
return m_strErr;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -