通过MD5加密字符串

#ifndef CRYPTOMD5_H
#define CRYPTOMD5_H

#include <afxwin.h>
#include <atlcoll.h>
#include <wincrypt.h>

class CCryptoMD5 : CObject
{
public:
	CCryptoMD5()
	{
		m_hCryptProv = NULL, m_hCryptHash = NULL;
		CryptAcquireContext(&m_hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
		CryptCreateHash(m_hCryptProv, CALG_MD5, NULL, 0, &m_hCryptHash);
	}

	virtual ~CCryptoMD5()
	{
		if (m_hCryptProv) CryptReleaseContext(m_hCryptProv, 0);
		if (m_hCryptHash) CryptDestroyHash(m_hCryptHash);
	}

	/// <summary>计算指定字节数组的哈希值</summary>
	/// <param name="pbInputBuffer">要计算其哈希代码的输入</param>
	/// <param name="cbInputBuffer">数组中用作数据的字节数</param>
	void ComputeHash(const BYTE* pbInputBuffer, int cbInputBuffer)
	{
		CryptHashData(m_hCryptHash, pbInputBuffer, cbInputBuffer, 0);

		DWORD dwDataLen = (DWORD) sizeof(DWORD);
		DWORD dwHashSize = 0; // 哈希数据长度
		CryptGetHashParam(m_hCryptHash, HP_HASHSIZE, (LPBYTE) &dwHashSize, &dwDataLen, 0);
		m_baHashData.SetCount(dwHashSize); // 重置哈希数据大小
		CryptGetHashParam(m_hCryptHash, HP_HASHVAL, m_baHashData.GetData(), &dwHashSize, 0);
	}

	/// <summary>获取计算指定字节数组的哈希值</summary>
	/// <return>计算指定字节数组的哈希值</return>
	ATL::CAtlArray<BYTE>& GetHashData() { return m_baHashData; }
private:
	/// <summary>计算指定字节数组的哈希值</summary>
	ATL::CAtlArray<BYTE> m_baHashData;

	/// <summary>密码系统服务提供者句柄</summary>
	HCRYPTPROV m_hCryptProv;

	/// <summary>密码系统哈希对象集句柄</summary>
	HCRYPTHASH m_hCryptHash;
};

#endif // CRYPTOMD5_H

你可能感兴趣的:(通过MD5加密字符串)