Create SHA256 64bit hash from concatenated fields

Started by stanl, September 20, 2019, 04:35:58 AM

Previous topic - Next topic

stanl

Not sure this is possible in WB, but maybe with the CLR. I need a way to replace primary keys in a db table as a way to update duplicate values on an import. Assume I have 5 fields [f1 - f5] that make a row distinct. I want to create an SHA256 hash based on a binary calculation of the concatenated fields and store that as a unique 64 char hex string in a lookup table.

td

Code (winbatch) Select
; Load the needed assembly.
ObjectClrOption('useany', 'System.Core')

; Get an instance of the SHA256Cng Class.
objCrypt = ObjectClrNew('System.Security.Cryptography.SHA256Cng')

; Extract the fields using whatever DB technology.

; Assuming fields are Unicode text but could be binary or numeric.
; If the fields do contain non-text a binary buffer could
; be used to create a safearray of bytes (see BinaryOleType.)

; Concatinate strings to make a data blob.
strBlob = 'field one':'field two':'field three':'Field four':'Field five'
strBlob = ChrStringToUnicode(strBlob)
aBytes = ObjectType('array|ui1', strBlob)

; Do the deed.
aHash = objCrypt.ComputeHash(aBytes)

; Returned value is an array of bytes but it should convert to a binary
; buffer if desired.
hHash = BinaryAllocArray(aHash)
strHash = BinaryPeekHex(hHash, 0, BinaryEODGet(hHash))
BinaryFree(hHash)

; Check result
Message('Hash Result', 'Hash string: ':strHash:@lf:'Length: ':StrLen(strHash))

; Cleanup.
objCrypt.Clear()
"No one who sees a peregrine falcon fly can ever forget the beauty and thrill of that flight."
  - Dr. Tom Cade

stanl