2016-09-23 70 views
1

我想在Java中找到CRC32衝突,然後用pycrc檢查散列。我嘗試了this線程中描述的內容,但仍然無法使我的實現與pycrc匹配。我究竟做錯了什麼?Java中的CRC32不同於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 = "ABCDEF".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; 
    } 
+0

請舉例說明。 –

+0

檢查隨機數據上的衝突如何證明任何事情?更不用說不同意其他一些實現? – EJP

+0

@EJP我只是想找到一個碰撞。你認爲使用隨機數據不是一個好辦法嗎?我應該更系統地做這件事嗎? – fluffychaos

回答

0

你的問題是,你再使用CRC32實例,而不調用h.reset();

因此,您得到的CRC32不是用於當前測試的字符串,而是用於目前測試的所有字符串的concat。