cn.jiangzeyin.Md5Util Maven / Gradle / Ivy
package cn.jiangzeyin;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Created by jiangzeyin on 2017/12/12.
*/
public final class Md5Util {
private static MessageDigest messageDigest;
/**
* @param str 字符串
* @return md5 结果
* @throws NoSuchAlgorithmException 异常
* @author jiangzeyin
* date 2016-9-21
*/
public static String getString(String str) throws NoSuchAlgorithmException {
if (StringUtil.isEmpty(str))
throw new IllegalArgumentException("src is null");
if (messageDigest == null)
messageDigest = MessageDigest.getInstance("MD5");
byte[] b = str.getBytes();
messageDigest.reset();
messageDigest.update(b);
byte[] hash = messageDigest.digest();
StringBuilder hs = new StringBuilder();
String s = "";
for (byte aHash : hash) {
s = Integer.toHexString(aHash & 0xFF);
if (s.length() == 1)
hs.append("0").append(s);
else {
hs.append(s);
}
}
return hs.toString().toUpperCase();
}
/**
* 获取文件md5 值
*
* @param file file 对象
* @return md5
* @throws IOException io
* @throws NoSuchAlgorithmException 异常
*/
public static String getFile(File file) throws IOException, NoSuchAlgorithmException {
if (!file.exists() || !file.isFile()) {
return null;
}
byte buffer[] = new byte[1024];
int len;
MessageDigest digest = MessageDigest.getInstance("MD5");
FileInputStream in = new FileInputStream(file);
while ((len = in.read(buffer, 0, 1024)) != -1) {
digest.update(buffer, 0, len);
}
in.close();
StringBuilder sb = new StringBuilder();
for (byte t : digest.digest()) {
String s = Integer.toHexString(t & 0xFF);
if (s.length() == 1) // 补零
s = "0" + s;
sb.append(s);
}
String md5 = sb.toString().toUpperCase();
if (md5.length() != 32)
throw new RuntimeException(file.getPath() + " 获取md5(" + md5 + ") 长度不是32");
return md5;
}
/**
* 获取字符串的字节数组
*
* @param strSrc 字符串
* @param charsetName 编码
* @return byte
* @throws NoSuchAlgorithmException n
* @throws UnsupportedEncodingException u
*/
public static byte[] getBytes(String strSrc, String charsetName) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
return md5.digest(strSrc.getBytes(charsetName));
}
}