Ecco uno script PowerShell che produce un hash SHA256 su solo i byte dell'immagine come estratti utilizzando LockBits. Questo dovrebbe produrre un hash univoco per ogni file diverso. Si noti che non ho incluso il codice di iterazione del file, tuttavia dovrebbe essere un'operazione relativamente semplice sostituire il c: \ test.bmp attualmente con un iteratore di directory foreach. La variabile $ finale contiene la stringa hex - ascii dell'hash finale.
[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing.Imaging")
[System.Reflection.Assembly]::LoadWithPartialName("System.Security")
$bmp = [System.Drawing.Bitmap]::FromFile("c:\\test.bmp")
$rect = [System.Drawing.Rectangle]::FromLTRB(0, 0, $bmp.width, $bmp.height)
$lockmode = [System.Drawing.Imaging.ImageLockMode]::ReadOnly
$bmpData = $bmp.LockBits($rect, $lockmode, $bmp.PixelFormat);
$dataPointer = $bmpData.Scan0;
$totalBytes = $bmpData.Stride * $bmp.Height;
$values = New-Object byte[] $totalBytes
[System.Runtime.InteropServices.Marshal]::Copy($dataPointer, $values, 0, $totalBytes);
$bmp.UnlockBits($bmpData);
$sha = new-object System.Security.Cryptography.SHA256Managed
$hash = $sha.ComputeHash($values);
$final = [System.BitConverter]::ToString($hash).Replace("-", "");
Forse il codice C equivalente # sarà anche aiutare nella comprensione:
private static String ImageDataHash(FileInfo imgFile)
{
using (Bitmap bmp = (Bitmap)Bitmap.FromFile(imgFile.FullName))
{
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);
IntPtr dataPointer = bmpData.Scan0;
int totalBytes = bmpData.Stride * bmp.Height;
byte[] values = new byte[totalBytes];
System.Runtime.InteropServices.Marshal.Copy(dataPointer, values, 0, totalBytes);
bmp.UnlockBits(bmpData);
SHA256 sha = new SHA256Managed();
byte[] hash = sha.ComputeHash(values);
return BitConverter.ToString(hash).Replace("-", "");
}
}
fonte
2010-01-18 19:55:17
Il tuo primo approccio non funziona . Restituisce diversi hashcode per la stessa immagine (diversi metadati). Il secondo approccio funziona ed è praticamente ciò che fanno gli altri a diversi livelli di completezza nello script PowerShell. :-) –