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