Content-MD5计算方法

更新时间:2021-11-14 19:44:55

正确的计算方式:

标准中定义的算法简单点说就是:

1. 先计算MD5加密的二进制数组(128位)。

2. 再对这个二进制进行base64编码(而不是对32位字符串编码)。


JAVA代码示例


public static void main(String[] args) {

		System.out.println("结果:" + getStringContentMD5("D:/无微信“轻流产品介绍”.pdf"));
	}

	/***
	* 计算字符串的Content-MD5
	* @param str 文件路径
	* @return
	*/
	public static String getStringContentMD5(String str) {
		// 获取文件MD5的二进制数组(128位)
		byte[] bytes = getFileMD5Bytes1282(str);
		// 对文件MD5的二进制数组进行base64编码
		return new String(Base64.encodeBase64(bytes));
	}

	/***
	 * 获取文件MD5-二进制数组(128位)
	 * 
	 * @param filePath
	 * @return
	 * @throws IOException
	 */
	public static byte[] getFileMD5Bytes1282(String filePath) {
		FileInputStream fis = null;
		byte[] md5Bytes = null;
		try {
			File file = new File(filePath);
			fis = new FileInputStream(file);
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			byte[] buffer = new byte[1024];
			int length = -1;
			while ((length = fis.read(buffer, 0, 1024)) != -1) {
				md5.update(buffer, 0, length);
			}
			md5Bytes = md5.digest();
			fis.close();
		} catch (FileNotFoundException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return md5Bytes;
	}


PHP代码示例


$contentBase64Md5 = getContentBase64Md5($filePath);

function getContentBase64Md5($filePath){
    //获取文件MD5的128位二进制数组
    $md5file = md5_file($filePath,true);
    //计算文件的Content-MD5
    $contentBase64Md5 = base64_encode($md5file);
    echo ("contentBase64Md5=".$contentBase64Md5);
    return $contentBase64Md5;
}


.NET请求示例


public static string GetContentMD5FromFile(string filePath)
        {
            string ContentMD5 = null;
            try
            {
                FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                // 先计算出上传内容的MD5,其值是一个128位(128 bit)的二进制数组
                byte[] retVal = md5.ComputeHash(file);
                file.Close();
                // 再对这个二进制数组进行base64编码
                ContentMD5 = Convert.ToBase64String(retVal).ToString();
                MessageBox.Show("MD5:" + ContentMD5);
                return ContentMD5;
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误信息", "计算文件的Content-MD5值时发生异常:" + ex.Message);
                return ContentMD5;
            }
        }


我要纠错