java - Java中的CRC32与pycrc不同

标签 java hash cryptography crc32

我试图在 Java 中查找 CRC32 冲突,然后使用 pycrc 检查哈希值。我尝试了 this 线程中描述的内容,但仍然无法让我的实现与 pycrc 匹配。我做错了什么?

 public static void print() {
        Checksum h = new CRC32();
        Map<Long, String> seen = new HashMap<Long, String>();

        while (true) {
            String s = randomString();
            byte[] b = s.getBytes(StandardCharsets.UTF_8);
            h.update(b, 0, b.length);
            Long l = h.getValue();
            if (!seen.containsKey(l)) {
                seen.put(l, s);
            } else {
                System.out.println(s + "; " + seen.get(l));
                return;
            }
        }
    }

编辑
经过更多调查后,我发现 pycrc 的哈希值与 Java 的实现不同,而是 Java 只是给了我两个具有不同哈希值的字符串。例如,“93C7946B05”哈希值是“0xf2792761”,“323C239466”哈希值是“0x59fc1818”,但是当 Java 比较哈希值时(使用下面的实现),它们看起来“相等”。

更新的代码:

static char[] chars = "0123456789ABCDEF".toCharArray();

public static void print() {
        Checksum h = new CRC32();
        String key;
        Map<String, String> seen = new HashMap<String, String>();

        while (true) {
            String s = randomString();
            byte[] b = s.getBytes(StandardCharsets.UTF_8);
            h.update(b, 0, b.length);
            Long l = h.getValue();
            key = Long.toHexString(l);
            if (!seen.containsKey(key)) {
                seen.put(key, s);
            } else {
                System.out.println(s + "; " + seen.get(key));
                return;
            }
        }
    }

public static String randomString() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        //int len = random.nextInt(32) + 1;
        //for (int i = 0; i < len; i++) {
        for (int i = 0; i < 10; i++) {
            char c = chars[random.nextInt(chars.length)];
            sb.append(c);
        }
        String output = sb.toString();
        return output;
    }

最佳答案

您的问题是您重新使用 CRC32 实例而不调用 h.reset();

因此,您得到的 CRC32 不是针对当前要测试的字符串,而是针对迄今为止测试过的所有字符串的连接。

关于java - Java中的CRC32与pycrc不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39653236/

相关文章:

Java 8 : When the use of Interface static methods becomes a bad practice?

java - 为 LDAP 用户设置已经散列的密码(使用 Java)

c# - 如何散列文件的前 N ​​个字节?

encryption - HTTPs 网址加密

java - Java 中所有 UTF-8 字符的维吉尼亚密码

mysql - Mysql 中的 Md5 和 Salt

java - Spark : Cogroup RDDs fails in case of huge group

java - 朝向触摸点旋转对象

java.io.IOException :Bogus chunk size 异常

algorithm - 作业 : Implementing Karp-Rabin; For the hash values modulo q, 解释为什么用 q 作为 2 的幂是个坏主意?