Java常用消息摘要算法-MD5

xiaoxiao2021-02-28  6

本工具类可实现对字符串或者文件提取MD5值(MD5加密)

import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.security.MessageDigest; /** * MD5 消息摘要工具类 * * @author lixk */ public class MD5 { //摘要算法名称 private final static String ALGORITHM = "MD5"; /** * 提取字节数组的MD5 * * @param data 待提取字节数组 * @return * @throws Exception */ public static String encrypt(byte[] data) { try { //获取MD5摘要算法实例 MessageDigest messageDigest = MessageDigest.getInstance(ALGORITHM); //计算消息摘要 byte[] bytes = messageDigest.digest(data); //返回16进制格式字符串 return byte2Hex(bytes); } catch (Exception e) { throw new RuntimeException("md5 encrypt error", e); } } /** * 提取字符的MD5 * * @param data 待提取字符串 * @return * @throws Exception */ public static String encrypt(String data) { return encrypt(data.getBytes()); } /** * 提取数据流的MD5 * * @param inputStream 待提取数据流 * @return * @throws Exception */ public static String encrypt(InputStream inputStream) { try { //获取MD5摘要算法实例 MessageDigest messageDigest = MessageDigest.getInstance(ALGORITHM); //计算消息摘要 byte[] bytes = new byte[1024]; while (inputStream.read(bytes) != -1) { messageDigest.update(bytes); } //返回16进制格式字符串 return byte2Hex(messageDigest.digest()); } catch (Exception e) { throw new RuntimeException("md5 encrypt error", e); } } /** * 提取文件的MD5 * * @param file 待提取文件 * @return * @throws Exception */ public static String encrypt(File file) { try { return encrypt(new FileInputStream(file)); } catch (Exception e) { throw new RuntimeException("md5 encrypt error", e); } } /** * 将byte转为16进制 * * @param bytes * @return */ private static String byte2Hex(byte[] bytes) { StringBuilder data = new StringBuilder(bytes.length); for (byte b : bytes) { data.append(Integer.toHexString((b >> 4) & 0xf)); //高4位 data.append(Integer.toHexString(b & 0xf)); //低4位 } return data.toString(); } /** * 测试 * * @param args * @throws Exception */ public static void main(String[] args) { //提取字符串的MD5 System.out.println(MD5.encrypt("MD5 消息摘要测试!")); //提取文件的MD5 //System.out.println(MD5.encrypt(new File("C://test.txt"))); } }

运行结果

769c3a6da04c1a29be9a3bb6b497977a

 

 

 

转载请注明原文地址: https://www.6miu.com/read-2350294.html

最新回复(0)