import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.log4j.Logger;
/**
* MD5帮助类
* 生成文件的md5码,和字符串的MD5码
* @author
* @version [version 1.0, 2011-4-8]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class MD5Util
{
/**
* 日志
*/
private static Logger logger = Logger.getLogger(MD5Util.class);
/**
* 默认的密码字符串组合,apache校验下载的文件的正确性用的就是默认的这个组合
*/
protected static char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
/**
* 为应用程序提供信息摘要算法的功能,如 MD5 或 SHA 算法
*/
protected static MessageDigest messagedigest = null;
static
{
try
{
messagedigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException nsaex)
{
logger.error(MD5Util.class.getName()
+ "初始化失败,MessageDigest不支持MD5Util。");
nsaex.printStackTrace();
logger.error(Config.EXCEPTION, nsaex);
}
}
/**
* MAIN方法
* @param args 参数
* @throws IOException IO异常
*/
public static void main(String[] args) throws IOException
{
long begin = System.currentTimeMillis();
File big = new File("d:/fd.tar.gz");
String md5 = getFileMD5String(big);
long end = System.currentTimeMillis();
System.out.println("md5:" + md5 + " time:" + ((end - begin) / 1000)
+ "s");
}
/**
* 不适用于上G大的文件
*
* @param file 文件
* @return 该文件的MD5码
* @throws IOException IO异常
*/
public static String getFileMD5String(File file) throws IOException
{
if(file.isDirectory())
{
return null;
}
FileInputStream in = new FileInputStream(file);
try
{
byte[] buffer = new byte[1024];
int numRead = 0;
while ((numRead = in.read(buffer)) > 0) {
messagedigest.update(buffer, 0, numRead);
}
} finally
{
if(in != null)
{
in.close();
in = null;
}
}
return bufferToHex(messagedigest.digest());
}
/**
* 获取字符串的MD5码
* @param s 字符串
* @return 该字符串的MD5码
*/
public static String getMD5String(String s)
{
return getMD5String(s.getBytes());
}
/**
* 获取字节数组的MD5码
* @param bytes 字节数组
* @return 该字节数组的MD5码
*/
public static String getMD5String(byte[] bytes)
{
messagedigest.update(bytes);
return bufferToHex(messagedigest.digest());
}
private static String bufferToHex(byte[] bytes)
{
return bufferToHex(bytes, 0, bytes.length);
}
private static String bufferToHex(byte[] bytes, int m, int n)
{
StringBuffer stringbuffer = new StringBuffer(2 * n);
int k = m + n;
for (int l = m; l < k; l++)
{
appendHexPair(bytes[l], stringbuffer);
}
return stringbuffer.toString();
}
private static void appendHexPair(byte bt, StringBuffer stringbuffer)
{
char c0 = hexDigits[(bt & 0xf0) >> 4];
char c1 = hexDigits[bt & 0xf];
stringbuffer.append(c0);
stringbuffer.append(c1);
}
/**
* 密码校验
* @param password 密码
* @param md5PwdStr MD5字符串
* @return 相同返回TRUE,否则返回FALSE
*/
public static boolean checkPassword(String password, String md5PwdStr)
{
String s = getMD5String(password);
return s.equals(md5PwdStr);
}
}