How to get a hash of a string of text or binary data from the CryptoAPI
This code demonstrates how to get a hash, or a type of fingerprint for any string of data. Hashes are useful in determining if a piece of data has been altered. Usefull for files, data transmissions, etc. Have fun with it!!!
AI
AI Summary: This codebase represents a historical implementation of the logic described in the metadata. Our preservation engine analyzes the structure to provide context for modern developers.
Source Code
Public Function getHash(data As String, hashType As Integer) As String Dim ht As Long Dim sTemp As String Dim sProv As String Dim hLen As Long Dim h As String Dim hl As Long 'get hash type If hashType = 0 Then 'MD5 ht = CALG_MD5 hLen = 16 ElseIf hashType = 1 Then 'SHA hLen = 20 ht = CALG_SHA Else getHash = "" Exit Function End If '--- Prepare string buffers sTemp = vbNullChar sProv = MS_DEF_PROV & vbNullChar '---Gain Access To CryptoAPI If Not CBool(CryptAcquireContext(cryptContext, sTemp, sProv, PROV_RSA_FULL, 0)) Then If Not CBool(CryptAcquireContext(cryptContext, sTemp, sProv, PROV_RSA_FULL, CRYPT_NEWKEYSET)) Then getHash = "" Exit Function End If End If 'Create Empty hash object If Not CBool(CryptCreateHash(cryptContext, ht, 0, 0, hl)) Then getHash = "" Exit Function End If 'Hash the input string. If Not CBool(CryptHashData(hl, data, Len(data), 0)) Then getHash = "" Exit Function End If h = String(20, vbNull) 'Get hash val If Not CBool(CryptGetHashParam(hl, HP_HASHVAL, h, hLen, 0)) Then getHash = "" Exit Function End If getHash = h End Function
Original Comments (3)
Recovered from Wayback Machine