2012年7月10日火曜日

OpenSSLを使ったファイルハッシュ計算方法

openssl.exeを使った方法と、C++でライブラリを呼び出して計算してみる2パターンをメモ。

【SHA1の場合】
openssl.exe sha1 [ファイル名]

Visual Studioを使ったC++(コンソールアプリ)のサンプルは下記のような感じになります。
サンプルではWindows8 RP版のisoイメージのファイルハッシュを計算してテストしてみました。
  1. #include "stdafx.h"  
  2. #include "Hash.h" // OpenSSLのinclude  
  3.   
  4. #define TARGET_FILE "E:\\Windows8-ReleasePreview-32bit-Japanese.iso"  
  5. #define BUFSIZE (1024 * 16) // OpenSSLの定義と同じ  
  6.   
  7. int _tmain(int argc, _TCHAR* argv[])  
  8. {  
  9.     unsigned char sha1hash[SHA_DIGEST_LENGTH] = { 0 };  
  10.     unsigned char buf[BUFSIZE];  
  11.     DWORD dwStart = 0;  
  12.     DWORD dwEnd = 0;  
  13.   
  14.     // SHA1 using OpneSSL lib  
  15.     printf("Calculate file hash for sha1\n");  
  16.     dwStart = ::GetTickCount();  
  17.     SHA_CTX ctx;  
  18.     SHA1_Init(&ctx);  
  19.     CFile file(TARGET_FILE, CFile::modeRead);  
  20.     UINT nRead = 0;  
  21.   
  22.     do{  
  23.         nRead = file.Read(buf, BUFSIZE);  
  24.         if(nRead > 0){  
  25.             SHA1_Update(&ctx, buf, nRead);  
  26.         }  
  27.     }while(nRead == BUFSIZE);  
  28.    
  29.     SHA1_Final(sha1hash, &ctx);  
  30.     dwEnd = ::GetTickCount() - dwStart;  
  31.   
  32.     printf("SHA1(%s)= ", TARGET_FILE);  
  33.     for(int i = 0; i < SHA_DIGEST_LENGTH; i++){  
  34.         printf("%.2x",sha1hash[i]);  
  35.     }  
  36.     printf("\n");  
  37.     printf("Elapsed Time(ms) = %d\n", dwEnd);  
  38.   
  39.     return 0;  
  40. }  
※OpenSSLライブラリとは、stdafx.hで下記のように書くか、設定画面でリンクの設定をしてください。
  1. // OpenSSL lib  
  2. #pragma comment(lib, "openssl/lib/libeay32.lib")  
  3. #pragma comment(lib, "openssl/lib/ssleay32.lib")  

【MD5の場合】
openssl.exe md5 [ファイル名]

ソースの方はMD5_~に変わるだけで、あとは全く同じなので省略します。

0 件のコメント:

コメントを投稿