file di Informatica HASH restituisce valori diversi
Domanda
Qualcuno sa, perché il seguente codice restituisce risultati diversi su alcune macchine?
Private Shared Function ComputeHashValue(ByVal Data As String) As String
Dim HashAlgorithm As SHA512 = SHA512.Create
Dim HashValue() As Byte = HashAlgorithm.ComputeHash(Encoding.ASCII.GetBytes(Data))
' Looping over the array and ANDing each byte with 0111111
For i As Integer = 0 To HashValue.Length - 1
HashValue(i) = HashValue(i) And Convert.ToByte(127)
Next
Return Encoding.ASCII.GetString(HashValue)
End Function
Private Shared Function AreByteArraysEqual(ByVal array1 As Byte(), ByVal array2 As Byte()) As Boolean
If array1.Length <> array2.Length Then Return False
For i As Integer = 0 To array1.Length - 1
If array1(i) <> array2(i) Then Return False
Next
Return True
End Function
Private Shared Sub SomeMethod()
Dim t_prvBytes() As Byte = New Byte() {SOME VALUES} 'Previously computed HASH
Dim t_dllStream As New IO.FileStream("C:\myfile.txt", IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
Dim t_reader As New IO.StreamReader(t_dllStream)
Dim t_dllHash() As Byte = System.Text.Encoding.Unicode.GetBytes(ComputeHashValue(t_reader.ReadToEnd))
MsgBox(AreByteArraysEqual(t_dllHash, t_prvBytes))
t_dllStream.Close()
End Function
Soluzione
Non si dovrebbe essere convertendo l'hash in testo tramite Encoding.ASCII
. E ' non di testo ASCII. (Non è testo a tutti.) Sei anche hashing il risultato di ASCII-codifica del testo originale, che si legge nel usando Encoding.Unicode
. Perché?
Si sta facendo tutti i tipi di conversioni tra testo e binario - e probabilmente non dovrebbe essere facendo qualsiasi . Basta hash dei dati binari (usando HashAlgorithm.ComputeHash(Stream)
), e tenere il risultato in binario troppo. Se davvero bisogno di convertire i dati binari in testo, utilizzare Convert.ToBase64String
.
Inoltre, si sta confrontando i dati con un valore precedentemente calcolato -., Ma non si è spiegato in cui tale valore precedentemente calcolato è venuto da iniziare con