java - 使用 SHA-256 散列图像字节会产生许多随机冲突,我做错了什么?

标签 java bufferedimage sha hash-collision message-digest

我正在使用 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/

相关文章:

java - 频繁更新控制台时回车 '\r'不可靠

java - 我是否必须物理保存图像才能在 JSP 中显示它?

java - 如何处理不断更新的大图像

c - readFile 和 ConvertCharToIntArray 方法影响 Sha-1 的哈希实现

java - SHA 256 从 Java 到 C#

java - 使用 Java,如何限制对象属性具有特定值?

java - 多线程中不需要的输出

java - 错误 : the method sort (Comparable []) in the type Selection is not applicable for the arguments (int[])

Java 将 BufferedImages 编码为视频文件 (mp4)

c# - 如何让 MSBuild 对 Clickonce 应用程序中的所有文件进行签名