有谁知道我该如何使用“输入”来创建MD5哈希,我不知道该怎么称呼它?任何帮助都将得到最大的满足!谢谢 :)

    InputStream input =  new FileInputStream(fileName);

    StringBuffer hexString = new StringBuffer();
    MessageDigest md = MessageDigest.getInstance("MD5");

    byte[] hash = md.digest();

    for (int i = 0; i < hash.length; i++) {
        if ((0xff & hash[i]) < 0x10) {
            hexString.append("0"
                    + Integer.toHexString((0xFF & hash[i])));
        } else {
            hexString.append(Integer.toHexString(0xFF & hash[i]));
        }
    }
    String string = hexString.toString();
    System.out.println(string);

最佳答案

这将从磁盘读取filename并将MD5哈希结果放入hex

InputStream in = new FileInputStream(filename);
MessageDigest md = MessageDigest.getInstance("MD5");

byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) != -1) {
    md.update(buf, 0, len);
}
in.close();

byte[] bytes = md.digest();

StringBuilder sb = new StringBuilder(2 * bytes.length);
for (byte b : bytes) {
    sb.append("0123456789ABCDEF".charAt((b & 0xF0) >> 4));
    sb.append("0123456789ABCDEF".charAt((b & 0x0F)));
}
String hex = sb.toString();

10-06 06:53