Aquí hay un script de PowerShell que produce un hash SHA256 sólo en los bytes de la imagen utilizando como LockBits extraídos. Esto debería producir un hash único para cada archivo que sea diferente. Tenga en cuenta que no incluí el código iterativo del archivo, sin embargo, debería ser una tarea relativamente simple reemplazar el código duro actual c: \ test.bmp con un iterador de directorio foreach. La variable $ final contiene la cadena hexadecimal - ascii del hash final.
[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("-", "");
Tal vez el código C# equivalentes también le ayudan a comprender:
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("-", "");
}
}
Su primer enfoque no funciona . Devuelve diferentes códigos hash para la misma imagen (metadatos diferentes). El segundo enfoque funciona y es más o menos lo que hacen todos los demás a los distintos niveles de integridad en el script de PowerShell. :-) –