gpt4 book ai didi

java - Java中的CRC32与pycrc不同

转载 作者:太空宇宙 更新时间:2023-11-04 12:13:30 25 4
gpt4 key购买 nike

我试图在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com