我正在使用 SHA-256 算法检测数据库中的相同图像。因为我们使用很多不同的图像格式,所以我不想直接在文件上计算哈希值。相反,我想提取像素数据并计算其哈希值。
不幸的是,我遇到了很多随机冲突:68 张图像使用相同的像素提取(下图)从 6000 张图像中哈希到相同的值,但字节数不同。我觉得这是一个疯狂的碰撞次数。此外,我将我从像素数据计算出的字节转储到一个文件中,然后尝试:
echo -n [字节转储文件] | sha256sum
这导致转储图像的哈希值不同,这让我相信我在使用 MessageDigest 时做错了什么。
这是我获取像素数据的方式:
imageBytes = new byte[4 * width * height];
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
// grab color information
int argb = image.getRGB(x, y);
// a,r,g,b ordered bytes per this pixel. the values are always 0-255 so the byte cast is safe
int offset = y * width;
int pushX = x * 4;
imageBytes[pushX + offset] = (byte) ((argb >> 24) & 0xff);
imageBytes[pushX + 1 + offset] = (byte) ((argb >> 16) & 0xff);
imageBytes[pushX + 2 + offset] = (byte) ((argb >> 8) & 0xff);
imageBytes[pushX + 3 + offset] = (byte) (argb & 0xff);
}
}
然后我使用 MessageDigest 类计算散列:
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.reset();
for (int i = 0; i < imageBytes.length; i++)
{
digest.update(imageBytes[i]);
}
String hashString = new String(encodeHex(digest.digest()));
encodeHex 只是:
private static String encodeHex(byte data[])
{
StringBuilder hex = new StringBuilder(2 * data.length);
for (byte b : data)
{
hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt((b & 0x0F)));
}
return hex.toString();
}
最佳答案
我认为 offset
计算错误。应该是:
int offset = y * width * 4;
创建 imageBytes
的更好方法可能是 ByteBuffer
;它允许您简单地按顺序放置
每个字节,而无需计算索引。此外,它可以直接与MessageDigest一起使用。 .
关于java - 使用 SHA-256 散列图像字节会产生许多随机冲突,我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11040106/