package org.fcl.tcs_v1.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* 加密工具类
* @version v1.0 2014-06-01
*
*/
public class MD5Util {
/**
* 该方法将指定的字符串用MD5算法加密后返回。
* @param s 要被加密的字符串
* @return 被加密的字符串
*/
public static String getMD5Encoding(String s) {
byte[] input=s.getBytes();
String output = null;
// 声明16进制字母
char[] hexChar={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
try{
// 获得一个MD5摘要算法的对象
MessageDigest md=MessageDigest.getInstance("MD5");
md.update(input);
/*
MD5算法的结果是128位一个整数,在这里javaAPI已经把结果转换成字节数组了
*/
byte[] tmp = md.digest();//获得MD5的摘要结果
char[] str = new char[32];
byte b=0;
for(int i=0;i<16;i++){
b=tmp[i];
str[2*i] = hexChar[b>>>4 & 0xf];//取每一个字节的低四位换成16进制字母
str[2*i+1] = hexChar[b & 0xf];//取每一个字节的高四位换成16进制字母
}
output = new String(str);
}catch(NoSuchAlgorithmException e){
e.printStackTrace();
}
return output;
}
/**
* 获取文件的MD5值
* @param file 文件
* @return 文件的MD5值
*/
public static String getFileMD5(File file) {
if (!file.exists() || !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) {
e.printStackTrace();
return null;
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
}
/***
* 获取文件的MD5值
* @param filepath 文件路径
* @return 文件的MD5值
* @throws FileNotFoundException
*/
public static String getFileMD5(String filepath) {
File file = new File(filepath);
return getFileMD5(file);
}
public static void main(String[] args) {
System.out.println(getMD5Encoding("111111"));
}
}
转载于:https://blog.51cto.com/fengcl/1704512