1. 方法一 #include "iostream" #include "windows.h" #include "tchar.h" #include "iomanip" int _tmain(int argc, _TCHAR* argv[]) { HMODULE hCryptdll = LoadLibrary(_T("Cryptdll.dll")); void (WINAPI *MD5Init)(MD5_CTX*) = (void (WINAPI *)(MD5_CTX *))GetProcAddress(hCryptdll, "MD5Init"); void (WINAPI *MD5Update)(MD5_CTX*, unsigned char*, unsigned int) = (void (WINAPI *)(MD5_CTX*, unsigned char*, unsigned int)) GetProcAddress(hCryptdll, "MD5Update"); void (WINAPI *MD5Final)(MD5_CTX*) = (void (WINAPI *)(MD5_CTX*))GetProcAddress(hCryptdll, "MD5Final"); MD5Init(&ctx); unsigned char abc[]="123456"; MD5Update(&ctx, abc, strlen((const char *)abc)); MD5Final(&ctx); cout.fill('0'); cout << hex; for(int i=0; i<16 ;i++) cout<< setw(2) <<(int)ctx.digest[i]; cout << endl; FreeLibrary(hCryptdll); return 0; } 方法二: #include "stdafx.h" #include "iostream" #include "windows.h" #include "tchar.h" #include "iomanip" typedef struct { ULONG i[2]; ULONG buf[4]; unsigned char in[64]; unsigned char digest[16]; } MD5_CTX; MD5_CTX ctx; using namespace std; //计算MD5,成功返回0,失败返回GetLastError() DWORD MD5(__in_bcount(dwDataLen) const LPVOID pData, // 输入数据 __in DWORD dwDataLen, // 输入数据字节长度 __out LPTSTR pszMD5, // 输出字符串,TCHAR长度必须大于等于33 __in BOOL bCap = FALSE) // 是否输出为大写 { DWORD dwReturn = 0; HCRYPTPROV hProv; if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) return (dwReturn = GetLastError()); HCRYPTHASH hHash; if (!CryptCreateHash(hProv, CALG_MD5, 0, 0, &hHash)) { dwReturn = GetLastError(); CryptReleaseContext(hProv, 0); return dwReturn; } if (!CryptHashData(hHash, static_cast<const BYTE*>(pData), dwDataLen, 0)) { dwReturn = GetLastError(); CryptDestroyHash(hHash); CryptReleaseContext(hProv, 0); return dwReturn; } DWORD dwSize; DWORD dwLen = sizeof(dwSize); CryptGetHashParam(hHash, HP_HASHSIZE, reinterpret_cast<BYTE*>(&dwSize), &dwLen, 0); BYTE* pHash = new BYTE[dwSize]; dwLen = dwSize; CryptGetHashParam(hHash, HP_HASHVAL, pHash, &dwLen, 0); lstrcpy(pszMD5, _T("")); TCHAR szTemp[3]; TCHAR *szFmt = bCap ? _T("%X%X") : _T("%x%x"); for (DWORD i = 0; i < dwLen; ++i) { wsprintf(szTemp, szFmt, pHash[i] >> 4, pHash[i] & 0xf); lstrcat(pszMD5, szTemp); } delete [] pHash; CryptDestroyHash(hHash); CryptReleaseContext(hProv, 0); return dwReturn; }