com.hp.message.utils.Md5Util Maven / Gradle / Ivy
package com.hp.message.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.Formatter;
/**
* @author 尚肖磊
* @create 2021-03-26 19:29
* @Description: md5签名类
*/
public class Md5Util {
/**
* 获取字符串MD5签名值
*
* @param strData 参与签名的内容
* @return
*/
public static String getStrMd5Code(String strData) {
try {
// 生成一个MD5加密计算摘要
MessageDigest md = MessageDigest.getInstance("MD5");
// 计算md5函数
md.update(strData.getBytes("utf-8"));
//避免出现签名第一位为0 导致异常问题
return toHexString(md.digest());
} catch (Exception e) {
return null;
}
}
/**
* 获取bytes数组MD5签名值
*
* @param byteArray
* @return
* @throws Exception
*/
public static String getBytesMd5Code(byte[] byteArray) throws Exception {
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(byteArray);
return toHexString(md5.digest());
} catch (Exception e) {
return null;
}
}
/**
* 签名文件进行MD5获取其Hash值
*
* @param filePath 文件路径
* @return
*/
public static String getFileMd5Code(String filePath) throws Exception {
File file = new File(filePath);
if (!file.exists()) {
throw new Exception("签名文件不存在");
}
InputStream fis = new FileInputStream(file);
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
md5.update(buffer, 0, length);
}
return toHexString(md5.digest());
} catch (Exception e) {
return null;
} finally {
fis.close();
}
}
private static String toHexString(byte[] bytes) {
Formatter formatter = new Formatter();
for (byte b : bytes) {
formatter.format("%02x", b);
}
String res = formatter.toString();
formatter.close();
return res;
}
}