package net.sc.common.md5;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* @Author Aaron
* @CreateTime 2014-6-16下午05:28:11
* @Version 1.0
* @Desc 用MD5对数据进行加密
*/
public class MD5 {
static final Logger log = LogManager.getLogger(MD5.class);
MessageDigest md5;
static final char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
public MD5() {
try {
// 获得MD5摘要算法的 MessageDigest 对象
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
log.error("创建MD5对象出错, ", e);
throw new IllegalArgumentException("创建md5对象时出错");
}
}
public synchronized String getMD5(String s) {
return this.getMD5(s.getBytes());
}
public synchronized String getMD5(byte[] btInput) {
try {
// 使用指定的字节更新摘要
md5.update(btInput);
// 获得密文
byte[] md = md5.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);
} catch (Exception e) {
log.error("生成MD5码时出错,", e);
throw new IllegalArgumentException("生成MD5出错");
}
}
public String getFileMD5(String filePath) {
File md5File = new File(filePath);
return this.getFileMD5(md5File);
}
public String getFileMD5(File md5File) {
String value = "";
if (!md5File.exists()) {
log.error("计算MD5码时,对应路径文件:{} 不存在.", md5File);
return value;
}
try (FileInputStream in = new FileInputStream(md5File)) {
MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, md5File.length());
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(byteBuffer);
BigInteger bi = new BigInteger(1, md5.digest());
value = bi.toString(16);
} catch (Exception e) {
log.error(String.format("计算文件:%s 的MD5码出错!", md5File.getPath()), e);
} finally {
}
return value;
}
}