1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| #include <iostream>
#include <sstream>
#include <numeric>
#include <vector>
#include <cassert>
#include <iomanip>
using namespace std;
//#define _WIN32_WINNT 0x0500
#include <windows.h>
#include <wincrypt.h>
std::vector<BYTE> Hash( HCRYPTPROV hProv, const std::vector<BYTE> & Data )
{
BOOL bResult;
HCRYPTHASH hHash;
bResult = CryptCreateHash(
hProv,
CALG_MD5,
0,
0,
&hHash);
bResult = CryptHashData(
hHash,
&Data[ 0 ],
static_cast<DWORD>( Data.size() ),
0);
DWORD dwValue;
DWORD dwBufferSize = sizeof(DWORD);
bResult = CryptGetHashParam(
hHash,
HP_HASHSIZE,
reinterpret_cast<BYTE*>( &dwValue ),
&dwBufferSize,
0);
assert( dwBufferSize == sizeof(DWORD) );
std::vector<BYTE> result( dwValue );
bResult = CryptGetHashParam(
hHash,
HP_HASHVAL,
&result[ 0 ],
&dwValue,
0);
if ( !bResult )
{
cerr << "Echec CryptGetHashParam\n";
}
CryptDestroyHash(hHash);
return result;
}
int main()
{
BOOL bResult;
HCRYPTPROV hProv;
bResult = CryptAcquireContext(
&hProv,
NULL,
MS_DEF_PROV,
PROV_RSA_FULL,
0 );
if ( !bResult )
{
if ( GetLastError() == NTE_BAD_KEYSET )
{
bResult = CryptAcquireContext(
&hProv,
NULL,
MS_DEF_PROV,
PROV_RSA_FULL,
CRYPT_NEWKEYSET );
}
if ( !bResult )
{
cerr << "Erreur CryptAcquireContext : " << hex << GetLastError() << "\n";
return 1;
}
}
std::vector<BYTE> data;
data.push_back( 'A' );
data.push_back( 'B' );
data.push_back( 'C' );
data.push_back( 'D' );
data.push_back( 'E' );
data.push_back( 'F' );
std::vector<BYTE> hash = Hash( hProv, data );
cout << std::hex << std::uppercase;
cout << std::setfill('0');
for ( size_t i = 0; i < hash.size(); ++i )
{
if (i != 0)
cout << ' ';
cout << std::setw(2) << static_cast<int>( hash[ i ] );
}
cout << '\n';
CryptReleaseContext( hProv, 0 );
} |