使用如下python代码计算文件的md5值

import hashlib
# 获取文件的md5值
def getmd5(file):
    m = hashlib.md5()
    with open(file,'rb') as f:
        for line in f:
            m.update(line)
    md5code = m.hexdigest()
    return md5code

在java中使用如下方法获取md5值

/**
 * 获取文件的md5值
 * @param file
 * @return
 */
public static String getFileMD5(File file) {
    if (!file.isFile()) {
        return null;
    }
    MessageDigest digest = null;
    FileInputStream in = null;
    byte buffer[] = new byte[1024];
    int len;
    try {
        digest = MessageDigest.getInstance("MD5");
        in = new FileInputStream(file);
        while ((len = in.read(buffer, 0, 1024)) != -1) {
            digest.update(buffer, 0, len);
        }
        in.close();
    } catch (Exception e) {
        Log.i(InstallPkgUtil.TAG, "get md5 error: " + Log.getStackTraceString(e));
        return null;
    }
    // 这里的处理可能会丢失开头的0
    BigInteger bigInt = new BigInteger(1, digest.digest());
    return bigInt.toString(16);
}

在某些情况下,使用java计算出来的md5值如果开头是0的情况下,会被丢失。导致与python计算出来的不一致。 具体原因是BigInteger处理0开头的数据时会丢失。
BigInteger的相关知识参见这篇博客。

所以修改java端的代码如下:

/**
 * 获取文件的md5值
 * @param file
 * @return
 */
public static String getFileMD5(File file) {
    if (!file.isFile()) {
        return null;
    }

    char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f' };
    MessageDigest digest = null;
    FileInputStream in = null;
    byte buffer[] = new byte[1024];
    int len;
    try {
        digest = MessageDigest.getInstance("MD5");
        in = new FileInputStream(file);
        while ((len = in.read(buffer, 0, 1024)) != -1) {
            digest.update(buffer, 0, len);
        }
        in.close();
    } catch (Exception e) {
        Log.i(InstallPkgUtil.TAG, "get md5 error: " + Log.getStackTraceString(e));
        return null;
    }

    byte[] md = digest.digest();
    // 把密文转换成十六进制的字符串形式
    int j = md.length;
    char str[] = new char[j * 2];
    int k = 0;
    for (int i = 0; i < j; i++) {
        byte byte0 = md[i];
        str[k++] = hexDigits[byte0 >>> 4 & 0xf];
        str[k++] = hexDigits[byte0 & 0xf];
    }
    return new String(str);
}
Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐