java语言MD5加密字符串,计算文件的MD5值
package org.xqlee.utils.security;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Util {
/**
* 加密一个输入字符串
*
* @param visibleString
* 输入一个可见的明码<br>
* 类型:java.lang.String
* @return 一个加密后的MD5值<br>
* 通常用于密码加密
* @throws NoSuchAlgorithmException
*/
public static String getEnMD5String(String visibleString) throws NoSuchAlgorithmException {
MessageDigest md5;
// 生成一个MD5加密计算摘要
md5 = MessageDigest.getInstance("MD5");
// 计算md5函数
md5.update(visibleString.getBytes());
// digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符
// BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的 值
String pwdStr = new BigInteger(1, md5.digest()).toString(16);
return pwdStr;
}
/**
* 计算文件MD5值
*
* @param file
* 输入一个文件参数<br>
* 类型:java.io.File
* @return 该文件的MD5值<br>
* 类型:java.lang.String
* @throws IOException
* IO异常
* @throws NoSuchAlgorithmException
* MD5获取实例异常
*/
public static String getMd5ForFile(File file) throws IOException, NoSuchAlgorithmException {
FileInputStream in = null;
in = new FileInputStream(file);
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] cache = new byte[2048];
int len;
while ((len = in.read(cache)) != -1) {
md5.update(cache, 0, len);
}
in.close();
BigInteger bigInt = new BigInteger(1, md5.digest());
return bigInt.toString(16);
}
}
http://blog.xqlee.com/article/36.html