package com.lms.jdk8.md5;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;/** * @Author: 李孟帅 * @Date: 2021-12-14 10:37 * @Description: */public class MD5Util { private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; public static String toHex(byte[] content) throws NoSuchAlgorithmException { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(content); byte[] digest = md5.digest(); return byteToHexString(digest); } public static String toHex(InputStream is) throws NoSuchAlgorithmException, IOException { MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) != -1) { //参数为待加密数据 md5.update(buffer, 0, length); } byte[] digest = md5.digest(); return byteToHexString(digest); } public static String byteToHexString(byte[] bytes) { // 用字节表示就是 16 个字节 // 每个字节用 16 进制表示的话,使用两个字符,所以表示成 16 进制需要 32 个字符 // 比如一个字节为01011011,用十六进制字符来表示就是“5b” char[] str = new char[16 * 2]; int k = 0; // 表示转换结果中对应的字符位置 for (byte b : bytes) { str[k++] = HEX_CHAR[b >>> 4 & 0xf]; // 取字节中高 4 位的数字转换, >>> 为逻辑右移,将符号位一起右移 str[k++] = HEX_CHAR[b & 0xf]; // 取字节中低 4 位的数字转换 } return new String(str); } public static void main(String[] args) throws Exception { FileInputStream inputStream = new FileInputStream("C:\\Users\\tk40q\\Downloads\\startup.cfg"); String s = toHex(inputStream); System.out.println(s); }}