MD5哈希更快

时间:2015-10-06 15:47:40

标签: java optimization hash md5

我有一个单词列表,其中包含来自20级0xf.at的~68000个单词,并且想要散列两个单词以获得散列。然后将此哈希值与现有哈希值进行比较,直到找到这两个词。

我在java中尝试过它,但我没有注意到它,它会慢下来。

import java.io.*;

public class Main {

public static void main(String[] args) throws FileNotFoundException,
        IOException {

    try (BufferedReader br = new BufferedReader(new FileReader("E:/Trojan/Desktop/wordlist.txt"))) {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();
        Hash h = new Hash();
        String myHash = "cd48323bcf01557f5deadc2ec301affb";
        while (line != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
            line = br.readLine();
        }
        String everything = sb.toString();
        String lines[] = everything.split("\\r?\\n");
        for (int j = 1; j <= 68848; j++) {
            for (int i = 1; i <= 68847; i++) {
                //System.out.println(i+":"+lines[i]+" "+j+":"+lines[j]);
                if (h.getHash(lines[i]+lines[j],  "MD5") == myHash){
                    System.out.println(lines[i]+lines[j]);
                     break;
                }
            }
        }
    }
}
}

我从一个stackoverflow的例子中获取了md5哈希函数:

public class Hash {
/**
 * 
 * @param txt, text in plain format
 * @param hashType MD5 OR SHA1
 * @return hash in hashType 
 */
public static String getHash(String txt, String hashType) {
    try {
                java.security.MessageDigest md = java.security.MessageDigest.getInstance(hashType);
                byte[] array = md.digest(txt.getBytes());
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < array.length; ++i) {
                    sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
             }
                return sb.toString();
        } catch (java.security.NoSuchAlgorithmException e) {
            //error action
        }
        return null;
}

public static String md5(String txt) {
    return Hash.getHash(txt, "MD5");
}

public static String sha1(String txt) {
    return Hash.getHash(txt, "SHA1");
}
}

我怎样才能更快地获得这个?

1 个答案:

答案 0 :(得分:0)

您在方法getHash中创建了太多临时对象。尝试减少。 E.g。

private static final char[] HEX ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f',};
public static String getHash(String txt, MessageDigest md) {
    byte[] array = md.digest(txt.getBytes());
    char[] result = new char[array.length*2];
    for (int i = 0; i < array.length; ++i) {
        byte b = array[i];
        result[2*i] = HEX[(b&0x0f0)>>>4];
        result[2*i+1] = HEX[b&0x0f];
    }
    return new String(result);
}

修改 而且你根本不需要String对象。你应该返回byte []并使用Arrays.equals方法。