使用JDK自带的MessageDigest计算消息摘要

使用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)));
    }
}

posted on 2017-06-26 17:02  zyunx  阅读(1038)  评论(0编辑  收藏  举报

导航