Visual C++ (Win32) で、SHA1 のハッシュ値を取得する方法

以下がサンプルコード。Win32 Crypto API を使うコンソールアプリです。
// HashTest.cpp : Defines the entry point for the console application.
// Copyright (c) 2005, 2006 twinkle.cc All Rights Reserved.
//
//" title="https://perltips.twinkle.cc/
//">https://perltips.twinkle.cc/
//
perltips@gmail.com

#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#include <wincrypt.h>

int _tmain(int argc, _TCHAR* argv[])
{
    #define BUFFER_LEN 253
    #define SHA1LEN  20

    PCHAR    pcMessage;
    DWORD    ccMessage;

    DWORD dwStatus = 0;
    HCRYPTPROV hProv = 0;
    HCRYPTHASH hHash = 0;
    BYTE pbHash[SHA1LEN];
    BYTE pbRandom[BUFFER_LEN];
    DWORD cbHash = 0;
    CHAR pcDigits[] = "0123456789ABCDEF";
    CHAR pcHash[SHA1LEN * 2 + 1];

    //Get handle to the crypto provider
    if (!CryptAcquireContext(&hProv,
        NULL,
        NULL,
        PROV_RSA_FULL,
        CRYPT_VERIFYCONTEXT))
    {
        dwStatus = GetLastError();
        goto done;
    }

    // Get a random value
    if( CryptGenRandom(
        hProv,
        BUFFER_LEN,
        pbRandom))
    {
        printf("%d bytes of random data have been generated.\n", BUFFER_LEN);
    }
    else
    {
        dwStatus = GetLastError();
        printf("Random bytes were not correctly generated.\n");
        goto done;
    }
   
    if (!CryptCreateHash(hProv, CALG_SHA1, 0, 0, &hHash))
    {
        dwStatus = GetLastError();
        goto done;
    }
   
    if (!CryptHashData(hHash, pbRandom, BUFFER_LEN, 0))
    {
        dwStatus = GetLastError();
        printf("CryptHashData failed: %d\n", dwStatus);
        goto done;
    }

    cbHash = SHA1LEN;
    if (CryptGetHashParam(hHash, HP_HASHVAL, pbHash, &cbHash, 0))
    {
        printf("SHA1 hash is: ");
        for (DWORD i = 0; i < cbHash; i++)
        {
            pcHash[i * 2]      = pcDigits[pbHash[i] >> 4];
            pcHash[i * 2 + 1 ] = pcDigits[pbHash[i] & 0xf];
            pcHash[i * 2 + 2 ] = '\0';
        }
        printf("%s\n", pcHash);
    }
    else
    {
        dwStatus = GetLastError();
        printf("CryptGetHashParam failed: %d\n", dwStatus);
    }

    done:

    CryptDestroyHash(hHash);
    CryptReleaseContext(hProv, 0);

    WCHAR pwcMessage[BUFFER_LEN];
    MultiByteToWideChar(CP_ACP, 0, pcHash, sizeof(pcHash), pwcMessage, sizeof(pwcMessage));
  
    ccMessage = ( DWORD ) wcslen( pwcMessage );

    if( ( pcMessage = ( PCHAR ) malloc( ccMessage + 1 ) ) )
    {
        WideCharToMultiByte( CP_ACP, 0, pwcMessage, -1, pcMessage, ccMessage + 1, NULL, NULL );
        printf("malloc ok: %s\n", pcMessage);
    }
    else
    {
        printf("Not enough memory");
        dwStatus = ERROR_NOT_ENOUGH_MEMORY;
    }

    return dwStatus;
}
トラックバック URL: https://perltips.twinkle.cc/trackback/128