【问题标题】:Why are my two MD5 hashing methods producing different hashes?为什么我的两种 MD5 散列方法会产生不同的散列?
【发布时间】:2012-03-22 19:24:55
【问题描述】:

我是 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);

}

【问题讨论】:

    标签: java utf-8 md5 message-digest


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      BigInteger bigInt = new BigInteger(1, MD5checksum);
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-09
        • 2015-06-25
        • 2015-10-25
        • 2012-06-17
        • 1970-01-01
        • 2023-03-23
        • 2021-07-12
        • 2011-08-07
        相关资源
        最近更新 更多