报文摘要工具类

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import sun.misc.BASE64Encoder;


/**
 * 报文摘要工具类
 * @author fw
 *
 */
public class MDUtil {

	private static final String MD5 = "MD5";
	private static final String SHA1 = "SHA1";
	private static final String SHA256 = "SHA-256";
	private static final String SHA512 = "SHA-512";
	
	/**
	* 计算String的报文摘要
	* @param data待计算摘要的数据字符串
	* @param hashType报文摘要算法类型
	* @return 报文摘要字符串
	* @throws NoSuchAlgorithmException
	*/
	public static String mdStr(String data, String hashType) throws NoSuchAlgorithmException {
		MessageDigest md = MessageDigest.getInstance(hashType);
		byte[] dataBytes = data.getBytes();
		md.update(dataBytes);
		BASE64Encoder be = new BASE64Encoder();
		String result = be.encode(md.digest());
		return result;
	}
	
	/**
	* 计算文件的报文摘要
	* @param fileName待计算摘要的文件名(含路径)
	* @param hashType报文摘要算法类型
	* @return报文摘要字符串
	* @throws NoSuchAlgorithmException
	* @throws IOException
	*/
	public static String mdFile(String fileName, String hashType) throws 
	NoSuchAlgorithmException, IOException {
		MessageDigest md = MessageDigest.getInstance(hashType);
		BufferedInputStream bis = new BufferedInputStream(
			new FileInputStream(fileName));
		byte[] buf = new byte[1024];
		int len = 0;
		while((len = bis.read(buf)) > 0) {
			md.update(buf, 0, len);
		}
		bis.close();
		BASE64Encoder be = new BASE64Encoder();
		String result = be.encode(md.digest());
		return result;
	}
}

你可能感兴趣的:(message,digest)