码迷,mamicode.com
首页 > 编程语言 > 详细

c++builder CryptoAPI md5

时间:2015-07-28 00:24:39      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

#include <wincrypt.h>

DWORD GetHash(
    CONST BYTE * pbData,
    DWORD        dwDataLen,
    ALG_ID       algId,
    LPTSTR       pszHash )
{
    DWORD dwReturn = 0;
    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, 0, 0, &hHash ) )
    {
        dwReturn = GetLastError( );
        CryptReleaseContext( hProv, 0 );
        return dwReturn;
    }

    if ( !CryptHashData( hHash, pbData, dwDataLen, 0 ) )
    {
        dwReturn = GetLastError( );
        CryptDestroyHash( hHash );
        CryptReleaseContext( hProv, 0 );
        return dwReturn;
    }

    DWORD dwSize;
    DWORD dwLen = sizeof( dwSize );
    CryptGetHashParam( hHash, HP_HASHSIZE, ( BYTE * )( & dwSize ), & dwLen, 0 );

    BYTE * pHash = new BYTE[ dwSize ];
    dwLen = dwSize;
    CryptGetHashParam( hHash, HP_HASHVAL, pHash, & dwLen, 0 );

    lstrcpy( pszHash, _T( "" ) );
    TCHAR szTemp[ 3 ];
    for ( DWORD i = 0; 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, 0 );
    return dwReturn;
}

void __fastcall TForm2::Button2Click( TObject * Sender )
{
    char szStr[ 20 ] =    {        0 } ;
    TCHAR szHash[ 41 ] = {    0    } ;

    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 );
}

 

c++builder CryptoAPI md5

标签:

原文地址:http://www.cnblogs.com/cb168/p/4681460.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!