Excel でハッシュ関数を使うメモです。
連日、VBA 関連の記事なのは、本業のせいです!
手順書
SHA-256でハッシュ値を求め、16進数で返す
Option Explicit
Public Function SHA256_HEX(str As String) As String
Dim sha256m As Object
Dim utf8 As Object
Dim bytes() As Byte
Dim hash() As Byte
Dim i As Integer
Dim res As String
Set utf8 = CreateObject("System.Text.UTF8Encoding")
bytes = utf8.GetBytes_4(str)
Set sha256m = CreateObject("System.Security.Cryptography.SHA256Managed")
hash = sha256m.ComputeHash_2((bytes))
For i = LBound(hash) To UBound(hash)
res = res & LCase(Right("0" & Hex(hash(i)), 2))
Next i
SHA256_HEX = LCase(res)
End Function
MD5でハッシュ値を求め、16進数で返す
Option Explicit
Public Function MD5_HEX(str As String) As String
Dim md5 As Object
Dim utf8 As Object
Dim bytes() As Byte
Dim hash() As Byte
Dim i As Integer
Dim res As String
Set utf8 = CreateObject("System.Text.UTF8Encoding")
bytes = utf8.GetBytes_4(str)
Set md5 = CreateObject("System.Security.Cryptography.MD5CryptoServiceProvider")
hash = md5.ComputeHash_2(bytes)
For i = LBound(hash) To UBound(hash)
res = res & LCase(Right("0" & Hex(hash(i)), 2))
Next i
MD5_HEX = LCase(res)
End Function
関数名をそれぞれ SHA256、MD5 にしたかったんだけど、それだと座標扱いになって、シート上で使えなかった悲しみ。
参考書
下は、すんごい昔に読んでいた参考書の最新版です。
載せておいて難ですが、今は本より Google 先生に聞いた方が良いです。
本の内容的には、できることがずらーっと載っているので、どんなことができるかカタログ的に見たい場合には、お薦めです。