自己写的windows下面实现哈希和随机数生成的函数模块。
#include "windows.h"
#include "stdio.h"
#include "stdlib.h"
int getHash(char *dataIn,int dataInLen,char **dataOut,int *dataOutLen)
{
BOOL bRet=FALSE;
HCRYPTPROV hCryptProv = NULL;
if (!CryptAcquireContext( //获取密钥容器句柄
&hCryptProv,
NULL,
NULL,
PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT))
{
goto err;
}
HCRYPTHASH hHash;
if (!CryptCreateHash(hCryptProv,CALG_MD5,NULL,0,&hHash))
{
goto err;
}
if (!CryptHashData(hHash,(BYTE *)dataIn,dataInLen,0))
{
goto err;
}
BYTE size[4] = {0};
DWORD sizeLen = 4;
if (!CryptGetHashParam(hHash,HP_HASHSIZE,size,&sizeLen,0))
{
DWORD error = GetLastError();
goto err;
}
printf("***********%d\n\n",(int)size);
memcpy(dataOutLen,size,4);
*dataOut = (char *)malloc(20);
if (!CryptGetHashParam(hHash,HP_HASHVAL,(BYTE *)*dataOut,(DWORD *)dataOutLen,0))
{
goto err;
}
// *dataOut = (char *)dataIn;
// *dataOutLen = dataInLen;
if (hHash)
{
CryptDestroyHash(hHash);
hHash = NULL;
}
if (hCryptProv)
{
CryptReleaseContext(hCryptProv,0);
hCryptProv=NULL;
}
return TRUE;
err:
return FALSE;
}
int GenRandom(char **dataOut,int len)
{
BOOL bRet=FALSE;
HCRYPTPROV hCryptProv = NULL;
if (!CryptAcquireContext( //获取密钥容器句柄
&hCryptProv,
NULL,
NULL,
PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT))
{
goto err;
}
*dataOut = (char *)malloc(len);
HCRYPTHASH hHash;
if (!CryptGenRandom(hCryptProv,(DWORD)len,(BYTE *)*dataOut))
{
goto err;
}
if (hCryptProv)
{
CryptReleaseContext(hCryptProv,0);
hCryptProv=NULL;
}
return TRUE;
err:
return FALSE;
}
int main()
{
char *dataOut = NULL;
int dataOutLen = 0;
getHash("1",1,&dataOut,&dataOutLen);
for (int i=0;i<dataOutLen;i++)
{
printf("%x",dataOut[i]);
}
GenRandom(&dataOut,8);
for (int i=0;i<8;i++)
{
printf("%x",dataOut[i]);
}
return 0;
}