ハッシュ値を取得(SHA256)

ファイルのハッシュ値を計算して、ファイルが変更されていないか確認できます。
SHA256とMD5のハッシュ値の取得方法を紹介します。

' ------------------------------------------------------------
' 説明:ファイルのSHA256を取得
' 引数:1:ファイル名
' 戻値:SHA256 ハッシュ値
' ------------------------------------------------------------
Function GetFileToSHA256(filename As String) As String
	Dim obj As Object
	Dim buff() As Byte
	Dim hashValue() As Byte
	Dim fnum As Integer
	Dim description As String
	Dim idx1 As Integer

	' ファイル番号取得
	fnum = FreeFile

	' ファイル読み込み(バイナリ)
	Open filename For Binary Lock Read As #1
	ReDim buff(LOF(fnum) - 1)
	Get #fnum, 1, buff
	Close #fnum

	' ハッシュのオブジェクトを設定
	Set obj = CreateObject("System.Security.Cryptography.SHA256Managed")
	hashValue = obj.ComputeHash_2(buff)
	Set obj = Nothing

	' 16進法表示に変換
	For idx1 = 0 To UBound(hashValue)
		description = description & Right("0" & Hex(hashValue(idx1)), 2)
	Next idx1

	GetFileToSHA256 = description
End Function

コメント