1

我是java新手,真的需要一些帮助。我创建了一个命令行工具来获取文件的 MD5 哈希。这很有效,所以我随后定制了我的代码以将其置于 GUI 形式中。这两个程序给出了同一文件的不同哈希值,这令人困惑。我已经研究过 UTF-8,但据我所知,它只适用于字符串而不是文件实例。谁能告诉我为什么他们提供不同的哈希值并指出正确的方向?

第一种方法(命令行)...

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

    System.out.println("Please enter file path: \n");

    BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
    String dir = stdin.readLine();
    File file = new File(dir);

    FileInputStream iStream = null;

    try {iStream = new FileInputStream(file);}
    catch (FileNotFoundException e) {      
        String MD5Output = "There has been an error: " + e.toString();   
    }

    byte[] dataBytes = new byte[1024];

    MessageDigest md = MessageDigest.getInstance("MD5");

    int numRead = iStream.read(dataBytes);
        md.update(dataBytes, 0, numRead);

        iStream.close();

        dataBytes = md.digest();

    md.update(dataBytes);
    System.out.println("MD5: " + new BigInteger(1, md.digest()).toString(16));

}

第二种方法(为gui构建)...

    public void doMD5() throws IOException, NoSuchAlgorithmException {

    File file = new File(jTxtMD51.getText());

    FileInputStream iStream = null;

    try {iStream = new FileInputStream(file);}
    catch (FileNotFoundException e) {      
        String MD5Output = "There has been an error: " + e.toString();   
    }

    byte[] dataBytes = new byte[1024];

    MessageDigest md = MessageDigest.getInstance("MD5");

    int numRead = iStream.read(dataBytes);
        md.update(dataBytes, 0, numRead);

        iStream.close();

        byte[] MD5checksum = md.digest();

    md.update(dataBytes);

    BigInteger bigInt = new BigInteger(1, md.digest());
    String MD5Hash = bigInt.toString(16);

    jTextOutput.append("MD5 is : " + MD5Hash);

}
4

2 回答 2

1

您只需从流中进行一次读取调用。您需要在读取 InputStream 时进行循环(假设您想要读取整个内容,这通常是您想要的)。此外,您似乎使用相同的字节对 digest.update() 进行了 2 次调用。

此外,通常在打印哈希值时,由于它是二进制值,因此使用 base64 编码打印。

于 2012-03-22T19:26:41.063 回答
0

除了@jtahlborn 的评论,你不需要md.update(databytes);在这两种方法中调用,你的第二个方法最后应该有这个:

BigInteger bigInt = new BigInteger(1, MD5checksum);

您的第一个方法不会对 digest() 进行第二次调用,当您调用 update() 时,它的值会发生变化

于 2012-03-22T19:31:55.373 回答