Jump to content

_Crypt_HashData() VS UNIQUE constraint


Recommended Posts

I have some strange troubles with work _Crypt_HashData() on unicode strings. -

I'm trying to fill sqlite data base with filelist from some directory and use hash of FullFilePath as PRIMARY KEY but get

"--> Error:    UNIQUE constraint failed: DB.Hash"

There a no duplicates in filelist, so why UNIQUE constraint failed?

 

#include <File.au3>
#include <Array.au3>
#include <Crypt.au3>
#include <SQLite.au3>
;------------------------------------------------------------------------------------------
$sPath = "Some directory"
$PathToSQLiteDLL = "path to sqlite3.dll"
;------------------------------------------------------------------------------------------
Global $aFileList = _FileListToArrayRec($sPath, "*", $FLTAR_FILES, $FLTAR_RECUR, $FLTAR_NOSORT, $FLTAR_FULLPATH)
_ArrayDisplay($aFileList, "Original", Default, 8)


$aMult = _ArrayGetMultiples($aFileList)

_ArrayDisplay($aMult, "Only multiples", Default, 8)

;------------------------------------------------------------------------------------------
$sSqlBuildTable = '(Hash PRIMARY KEY, FullFilePath)'
$sSqlFillTable = '(Hash, FullFilePath)'
;------------------------------------------------------------------------------------------
_SQLite_Startup($PathToSQLiteDLL)
FileDelete(@ScriptDir & "\test.sqlite")
$hDB = _SQLite_Open(@ScriptDir & "\test.sqlite")
_SQLite_Exec($hDB, "PRAGMA cache_size = " & 128*1024& ";" )
_SQLite_Exec($hDB, "BEGIN; DROP TABLE IF EXISTS DB;COMMIT;")
_SQLite_Exec($hDB, 'BEGIN; CREATE TABLE DB ' & $sSqlBuildTable & ';COMMIT;')
;------------------------------------------------------------------------------------------


DataBaseFill($sPath)







;==========================================================================================
Func DataBaseFill($sPath)
    If Not FileExists($sPath) Then Return SetError(1)
    _SQLite_Exec(-1, "PRAGMA synchronous = OFF;" )
    Local $sQuery = "", $k = 0, $n = 8192
    For $i = 1 To $aFileList[0] Step $n
        $k = (($i+$n) > $aFileList[0]) ? ($aFileList[0]-$i-2) : ($n-2)
        $sQuery = 'INSERT INTO DB ' & $sSqlFillTable & ' VALUES '
        For $j = 0 To $k
            $sFullFilePath = $aFileList[$i+$j]
            ;------------------------------------------------------------------------------------------------------------------
            ;$sQuery &= "('" & _Crypt_HashData(StringToBinary($sFullFilePath,2), $CALG_MD5) & "','" & StringRegExpReplace($sFullFilePath, "'", "''") & "'),"
            $sQuery &= "('" & _Crypt_HashData($sFullFilePath, $CALG_MD5) & "','" & StringRegExpReplace($sFullFilePath, "'", "''") & "'),"
        Next
        $sFullFilePath = $aFileList[$i+$k+1]
        ;----------------------------------------------------------------------------------------------------------------------
        ;$sQuery &= "('" & _Crypt_HashData(StringToBinary($sFullFilePath,2), $CALG_MD5) & "','" & StringRegExpReplace($sFullFilePath, "'", "''") & "');"
        $sQuery &= "('" & _Crypt_HashData($sFullFilePath, $CALG_MD5) & "','" & StringRegExpReplace($sFullFilePath, "'", "''") & "');"

        If Not (_SQLite_Exec(-1, $sQuery) = $SQLITE_OK) Then
            ConsoleWrite("-------------------------"& @CRLF)
            ;Exit;Return SetError(2)
        EndIf
        ConsoleWrite(Round(($i+$k+1)/$aFileList[0]*100) & "%" & @CRLF)
    Next
    _SQLite_Exec(-1, "PRAGMA synchronous = NORMAL;" )
EndFunc
;==========================================================================================
Func _ArrayGetMultiples($aArray)

    ; Create dictionaries
    Local $oDict_Original = ObjCreate("Scripting.Dictionary")
    Local $oDict_Multiple = ObjCreate("Scripting.Dictionary")

    Local $vElem

    ; Loop through array
    For $i = 0 To UBound($aArray) - 1
        ; Extract element
        $vElem = $aArray[$i]
        ; Check if already in original array
        If $oDict_Original.Exists($vElem) Then
            ; Check if already in multiple dictionary
            If Not $oDict_Multiple.Exists($vElem) Then
                ; Add to multiple dictionary
                $oDict_Multiple.Item($vElem)
            EndIf
        Else
            ; Add to original element dictionary
            $oDict_Original.Item($vElem)
        EndIf
    Next

    ; Create the return array from teh multipel dictionary
    Return $oDict_Multiple.Keys()

EndFunc   ;==>_ArrayUnique_COM
;==========================================================================================

 

note - if i use _Crypt_HashData(StringToBinary($sFullFilePath,2), $CALG_MD5) instead of _Crypt_HashData($sFullFilePath, $CALG_MD5) or

use $sSqlBuildTable =  '(Hash , FullFilePath PRIMARY KEY)'  instead of $sSqlBuildTable = '(Hash PRIMARY KEY, FullFilePath)'

there a no constraint violation...

Edited by Iczer
typo
Link to comment
Share on other sites

You found a hash that's valid for 2 or more filepathstrings so violation. It's possible that one hash is valid for more than one datastring. So you have to change your tabledesign, for example adding a second field that's realy unique or don't using a primary key.

Edited by AutoBert
Link to comment
Share on other sites

  1. StringToBinary returns from each element in a array of uniquestrings a unique binary string.
  2. Using HashData there is no guarantee to get a unique hash from same array used in 1. . It's only gauranteed that using same string will result same hash.
  3. Using _Crypt_EncryptData returns unique crypted strings from same array used in 1.
  4. Using a compression algo also returns unique strings from same array used in 1. But sometimes the compressed string is longer than original.

Maybe using other algo SHA1 will give no violations , but is also not guaranteed but the chance to get no violation is better as the resulting hash is longer.

If it's realy possible that hash data for eacht string is unique this technique would be used for compressing data because result stringlength is very small. Also a DeHash func would be implemented from the Dev's in AutoIt.

Edited by AutoBert
Link to comment
Share on other sites

I don't believe that one can find an MD5 collision that easily!

I can't reproduce the issue but realize that you only check for duplicate full pathnames, not duplicate file contents. I suspect you have the same file content in two or more files in your directory subtree.

Slightly streamlined version (pathes changed):

#include <File.au3>
#include <Array.au3>
#include <Crypt.au3>
#include <SQLite.au3>
;------------------------------------------------------------------------------------------
$sPath = "."
$PathToSQLiteDLL = "c:\bin\sqlite3.dll"
;------------------------------------------------------------------------------------------
Global $aFileList = _FileListToArrayRec($sPath, "*", $FLTAR_FILES, $FLTAR_RECUR, $FLTAR_NOSORT, $FLTAR_FULLPATH)
_ArrayDisplay($aFileList, "Original", Default, 8)


$aMult = _ArrayGetMultiples($aFileList)

_ArrayDisplay($aMult, "Only multiples", Default, 8)

;------------------------------------------------------------------------------------------
$sSqlBuildTable = '(Hash PRIMARY KEY, FullFilePath text)'
$sSqlFillTable = '(Hash, FullFilePath)'
;------------------------------------------------------------------------------------------
_SQLite_Startup($PathToSQLiteDLL)
FileDelete(@ScriptDir & "\test.sqlite")
$hDB = _SQLite_Open(@ScriptDir & "\test.sqlite")
_SQLite_Exec($hDB, "PRAGMA cache_size = " & 128*1024& ";" )
_SQLite_Exec($hDB, "DROP TABLE IF EXISTS DB;")
_SQLite_Exec($hDB, 'CREATE TABLE DB ' & $sSqlBuildTable & ';')
;------------------------------------------------------------------------------------------


DataBaseFill($sPath)


;==========================================================================================
Func DataBaseFill($sPath)
    If Not FileExists($sPath) Then Return SetError(1)
;~     _SQLite_Exec(-1, "PRAGMA synchronous = OFF;" )
    Local $sQuery = "", $k = 0, $n = 8192
    For $i = 1 To $aFileList[0] Step $n
        $k = (($i+$n) > $aFileList[0]) ? ($aFileList[0]-$i-2) : ($n-2)
        $sQuery = 'begin; INSERT INTO DB ' & $sSqlFillTable & ' VALUES '
        For $j = 0 To $k
            $sFullFilePath = $aFileList[$i+$j]
            ;------------------------------------------------------------------------------------------------------------------
            ;$sQuery &= "('" & _Crypt_HashData(StringToBinary($sFullFilePath,2), $CALG_MD5) & "','" & StringRegExpReplace($sFullFilePath, "'", "''") & "'),"
            $sQuery &= "('" & _Crypt_HashData($sFullFilePath, $CALG_MD5) & "','" & StringReplace($sFullFilePath, "'", "''") & "'),"
        Next
        $sFullFilePath = $aFileList[$i+$k+1]
        ;----------------------------------------------------------------------------------------------------------------------
        ;$sQuery &= "('" & _Crypt_HashData(StringToBinary($sFullFilePath,2), $CALG_MD5) & "','" & StringRegExpReplace($sFullFilePath, "'", "''") & "');"
        $sQuery &= "('" & _Crypt_HashData($sFullFilePath, $CALG_MD5) & "','" & StringReplace($sFullFilePath, "'", "''") & "');"

        If Not (_SQLite_Exec(-1, $sQuery & ";end;") = $SQLITE_OK) Then
            ConsoleWrite("-------------------------"& @CRLF)
            ;Exit;Return SetError(2)
        EndIf
        ConsoleWrite(Round(($i+$k+1)/$aFileList[0]*100) & "%" & @CRLF)
    Next
;~     _SQLite_Exec(-1, "PRAGMA synchronous = NORMAL;" )
EndFunc
;==========================================================================================
Func _ArrayGetMultiples($aArray)

    ; Create dictionaries
    Local $oDict_Original = ObjCreate("Scripting.Dictionary")
    Local $oDict_Multiple = ObjCreate("Scripting.Dictionary")

    Local $vElem

    ; Loop through array
    For $i = 0 To UBound($aArray) - 1
        ; Extract element
        $vElem = $aArray[$i]
        ; Check if already in original array
        If $oDict_Original.Exists($vElem) Then
            ; Check if already in multiple dictionary
            If Not $oDict_Multiple.Exists($vElem) Then
                ; Add to multiple dictionary
                $oDict_Multiple.Item($vElem)
            EndIf
        Else
            ; Add to original element dictionary
            $oDict_Original.Item($vElem)
        EndIf
    Next

    ; Create the return array from teh multipel dictionary
    Return $oDict_Multiple.Keys()

EndFunc   ;==>_ArrayUnique_COM
;==========================================================================================

 

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

@jchd: I first can't believe also, but seeing he uses $FLTAEFULLPATH for _FileListToArrayRec tells me: each element in $aFilelist must be unique. And after

5 hours ago, Iczer said:

note - if i use _Crypt_HashData(StringToBinary($sFullFilePath,2), $CALG_MD5) instead of _Crypt_HashData($sFullFilePath, $CALG_MD5)

it was clear there is no bug (using some elements in array twice) in the func DataBaseFill because then the violation must also happen.

 

Link to comment
Share on other sites

@AutoBert

this exactly my point

$sString_1 = "惚"
$sString_2 = "恥"
$sString_3 = "徳"
$sString_4 = "熟"
$sString_5 = "密"
$sString_6 = "濃"
$sString_7 = "羞"
$sString_8 = "背"
$sString_9 = "恍"
$sString_0 = "艶"

ConsoleWrite("Char = " & BinaryToString(StringToBinary($sString_1, 4), 1) & "  Unicode code = " & AscW($sString_1) & "  hash = " & _Crypt_HashData($sString_1, $CALG_SHA1) & "  hash bin = " & _Crypt_HashData(StringToBinary($sString_1,2), $CALG_SHA1) & @CRLF)
ConsoleWrite("Char = " & BinaryToString(StringToBinary($sString_2, 4), 1) & "  Unicode code = " & AscW($sString_2) & "  hash = " & _Crypt_HashData($sString_2, $CALG_SHA1) & "  hash bin = " & _Crypt_HashData(StringToBinary($sString_2,2), $CALG_SHA1) & @CRLF)
ConsoleWrite("Char = " & BinaryToString(StringToBinary($sString_3, 4), 1) & "  Unicode code = " & AscW($sString_3) & "  hash = " & _Crypt_HashData($sString_3, $CALG_SHA1) & "  hash bin = " & _Crypt_HashData(StringToBinary($sString_3,2), $CALG_SHA1) & @CRLF)
ConsoleWrite("Char = " & BinaryToString(StringToBinary($sString_4, 4), 1) & "  Unicode code = " & AscW($sString_4) & "  hash = " & _Crypt_HashData($sString_4, $CALG_SHA1) & "  hash bin = " & _Crypt_HashData(StringToBinary($sString_4,2), $CALG_SHA1) & @CRLF)
ConsoleWrite("Char = " & BinaryToString(StringToBinary($sString_5, 4), 1) & "  Unicode code = " & AscW($sString_5) & "  hash = " & _Crypt_HashData($sString_5, $CALG_SHA1) & "  hash bin = " & _Crypt_HashData(StringToBinary($sString_5,2), $CALG_SHA1) & @CRLF)
ConsoleWrite("Char = " & BinaryToString(StringToBinary($sString_6, 4), 1) & "  Unicode code = " & AscW($sString_6) & "  hash = " & _Crypt_HashData($sString_6, $CALG_SHA1) & "  hash bin = " & _Crypt_HashData(StringToBinary($sString_6,2), $CALG_SHA1) & @CRLF)
ConsoleWrite("Char = " & BinaryToString(StringToBinary($sString_7, 4), 1) & "  Unicode code = " & AscW($sString_7) & "  hash = " & _Crypt_HashData($sString_7, $CALG_SHA1) & "  hash bin = " & _Crypt_HashData(StringToBinary($sString_7,2), $CALG_SHA1) & @CRLF)
ConsoleWrite("Char = " & BinaryToString(StringToBinary($sString_8, 4), 1) & "  Unicode code = " & AscW($sString_8) & "  hash = " & _Crypt_HashData($sString_8, $CALG_SHA1) & "  hash bin = " & _Crypt_HashData(StringToBinary($sString_8,2), $CALG_SHA1) & @CRLF)
ConsoleWrite("Char = " & BinaryToString(StringToBinary($sString_9, 4), 1) & "  Unicode code = " & AscW($sString_9) & "  hash = " & _Crypt_HashData($sString_9, $CALG_SHA1) & "  hash bin = " & _Crypt_HashData(StringToBinary($sString_9,2), $CALG_SHA1) & @CRLF)
ConsoleWrite("Char = " & BinaryToString(StringToBinary($sString_0, 4), 1) & "  Unicode code = " & AscW($sString_0) & "  hash = " & _Crypt_HashData($sString_0, $CALG_SHA1) & "  hash bin = " & _Crypt_HashData(StringToBinary($sString_0,2), $CALG_SHA1) & @CRLF)

 

i thinking - maybe _Crypt_HashData() need binary as input to work properly?

$vData = "Unicode文字列"

ConsoleWrite(BinaryLen($vData) & @CRLF) ; used in _Crypt_HashData() for buffer lengh in byte structure

ConsoleWrite(StringLen($vData)*2 & @CRLF) ; number of bytes in unicode string (one char = 2 bytes)

ConsoleWrite(BinaryLen(StringToBinary($vData,2)) & @CRLF) ; string to binary result (hash OK with it)

maybe this should be added to _Crypt_HashData() for correct work with strings:

If Not IsBinary($vData) Then
    $vData = StringToBinary($vData,2)
EndIf

just before

$hBuff = DllStructCreate("byte[" & BinaryLen($vData) & "]")
DllStructSetData($hBuff, 1, $vData)

 

Link to comment
Share on other sites

no, _Crypt_HashData() crypted also Strings in each format (ansi, ascii, utf etc.) I know it's rare but seems you found 2 or more strings creating same hash.

Post the file you get after using _FileWriteFromArray, then i test and show the double(s). 

Link to comment
Share on other sites

Iczer is mostly right: you need to convert generic Unicode to UTF8 if you don't want issues. So use _Crypt_HashData(StringToBinary($sString_1,4), $CALG_SHA1)

BTW, the same issue arises with encryption/decryption. It's standard to use UTF8 for that.

Edited by jchd

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

Indeed. Fill free to file a ticket if none is pending about this point.

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

Correct, I was busy over the phone and started typing "File a bug report ..." then changed my mind but got distracted. Sorry for typo, I hate that.

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...