使用JDK自带的MessageDigest计算消息摘要
上代码
/**
* 使用JDK自带MessageDigest
*/
public class MessageDigestUtils {
/**
* 计算消息摘要
* @param algorithm 消息摘要算法
* @param in 数据流
* @return 消息摘要
* @throws IOException
* @throws NoSuchAlgorithmException
*/
public static byte[] digest(String algorithm, InputStream in)
throws IOException, NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(algorithm);
try {
byte[] buf = new byte[4096];
int r;
while ((r = in.read(buf)) != -1) {
md.update(buf, 0, r);
}
} finally {
in.close();
}
return md.digest();
}
public static byte[] digest(String algorithm, File file)
throws NoSuchAlgorithmException, FileNotFoundException, IOException {
return digest(algorithm, new FileInputStream(file));
}
public static byte[] digest(String algorithm, String text, String encoding)
throws NoSuchAlgorithmException, UnsupportedEncodingException, IOException {
return digest(algorithm, new ByteArrayInputStream(text.getBytes(encoding)));
}
}