#include ".\opencsp_hash.h" //HASH函数主要用于完整性校验和提高数字签名的有效
OPENCSP_M$CSP* OPENCSP_Hash::_csp;
//hKey如果哈希算法是密钥哈希,如HMAC或MAC 算法,就用此密钥句柄传递密钥。对非密钥算法,此参数为NULL
OPENCSP_Hash::OPENCSP_Hash(ALG_ID Algid, HCRYPTKEY hKey, DWORD dwFlags)//Algid哈希算法的标示符
:_algId(Algid), _hKey(hKey), _dwFlags(dwFlags)
{
_hHash = OPENCSP_Handle::getHandle();
_csp = OPENCSP_M$CSP::createM$Instance();
_csp->createHash(Algid, hKey, dwFlags, &_hHashInM$);
}
OPENCSP_Hash::~OPENCSP_Hash(void)
{
_csp->destroyHash(_hHashInM$);
}
//Algid选择hash算法,phHash哈希对象的句柄
OPENCSP_Hash* OPENCSP_Hash::createHash(ALG_ID Algid, HCRYPTKEY hKey, DWORD dwFlags, HCRYPTHASH* phHash)
{ // 此函数初始化哈希对象。它创建并返回了一个CSP哈希对象的句柄
OPENCSP_Hash* p = new OPENCSP_Hash(Algid, hKey, dwFlags);
*phHash = p->getHashHandle();
return p;
}
DWORD OPENCSP_Hash::getHashLen(DWORD& len) const //获取哈希值长度
{
DWORD ret = S_OK; //返回正确
switch(_algId)
{
case CALG_SSL3_SHAMD5: //微软提供的算法
len = 16 + 20;
break;
case CALG_MD5: //微软提供的算法
len = 16;
break;
case CALG_SHA1: //微软提供的算法
len = 20;
break;
default:
ret = NTE_BAD_ALGID; //CSP不支持的算法
}
return ret;
}
DWORD OPENCSP_Hash::setHashValue(const BYTE* pbData, DWORD dwLen)//设置哈希值
{
//设置哈希参数,pbData接收参数的缓冲区指针
DWORD ret = _csp->setHashParam(_hHashInM$, HP_HASHVAL, pbData, 0);
if (ret != S_OK) return ret;
return S_OK;
}
DWORD OPENCSP_Hash::getHashValue(HASH_VALUE& hv) //获取哈希值
{
BYTE bData[128] = {0};
DWORD dwLen = 128;
DWORD ret = _csp->getHashParam(_hHashInM$, HP_HASHVAL, bData, &dwLen, 0); // 获得Hash参数
if (ret != S_OK) return ret;
hv.insert(hv.end(), bData, bData + dwLen);
return S_OK;
}
DWORD OPENCSP_Hash::feedHashData(const BYTE* pData, DWORD dataLen) //往哈希句柄填充数据
{
DWORD ret = _csp->hashData(_hHashInM$, pData, dataLen, 0);
return ret;
}