#include <wincrypt.h>
DWORD GetHash(
CONST BYTE * pbData,
DWORD dwDataLen,
ALG_ID algId,
LPTSTR pszHash )
{
DWORD dwReturn = ;
HCRYPTPROV hProv;
if ( !CryptAcquireContext( &hProv, NULL, NULL, PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT ) )
{
return ( dwReturn = GetLastError( ) );
} HCRYPTHASH hHash;
// Alg Id:CALG_MD5,CALG_SHA
if ( !CryptCreateHash( hProv, algId, , , &hHash ) )
{
dwReturn = GetLastError( );
CryptReleaseContext( hProv, );
return dwReturn;
} if ( !CryptHashData( hHash, pbData, dwDataLen, ) )
{
dwReturn = GetLastError( );
CryptDestroyHash( hHash );
CryptReleaseContext( hProv, );
return dwReturn;
} DWORD dwSize;
DWORD dwLen = sizeof( dwSize );
CryptGetHashParam( hHash, HP_HASHSIZE, ( BYTE * )( & dwSize ), & dwLen, ); BYTE * pHash = new BYTE[ dwSize ];
dwLen = dwSize;
CryptGetHashParam( hHash, HP_HASHVAL, pHash, & dwLen, ); lstrcpy( pszHash, _T( "" ) );
TCHAR szTemp[ ];
for ( DWORD i = ; i < dwLen; ++i )
{
// wsprintf(szTemp, _T("%X%X"), pHash[i] >> 4, pHash[i] & 0xf);
wsprintf( szTemp, L"%02X", pHash[ i ] );
lstrcat( pszHash, szTemp );
}
delete[ ]pHash; CryptDestroyHash( hHash );
CryptReleaseContext( hProv, );
return dwReturn;
} void __fastcall TForm2::Button2Click( TObject * Sender )
{
char szStr[ ] = { } ;
TCHAR szHash[ ] = { } ; strcpy( szStr, "ww" ); // wcscpy
GetHash( ( BYTE * )szStr, strlen( szStr ), CALG_MD5, szHash );
Caption = szHash; strcpy( szStr, "ww" ); // wcscpy
GetHash( ( BYTE * )szStr, strlen( szStr ), CALG_MD5, szHash );
Caption = szHash;
//
// strwcpy( szStr, "测试SHA" );
// GetHash( ( BYTE * )szStr, strlen( szStr ), CALG_SHA, szHash );
// MessageBox( NULL, szHash, szStr, MB_OK );
}
多数时候这个函数的dwProvType
使用PROV_RSA_FULL
(网上的开源代码基本都是使用这个常数),这对MD5,SHA-1等都有效;但是却不是正确的SHA-256/512的provider type,所以使用这个常数创建的context会在之后创建SHA-256/512算法时发生错误。
正确的做法是使用PROV_RSA_AES
。
from http://blog.kingsamchen.com/archives/tag/sha