• Java生成文件摘要


    import java.io.File;
    import java.io.FileInputStream;
    import java.security.MessageDigest;
    
    
    
    /**
     * MD5工具类
     * @Author: CcchenCoco
     * @Version: V1.0 MD5Util, 2022/3/29 11:28
     **/
    public class MD5Util {
    
        private final static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    
        /**
         * 获取文件MD5摘要
         * @Author: CcchenCoco
         * @Version: V1.0 MD5Util, 2022/3/29 11:29
         **/
        public final static String MD5File(File file) {
            FileInputStream in = null;
            byte buffer[] = new byte[2048];
            int len;
            try {
                MessageDigest digest = MessageDigest.getInstance("MD5");
                in = new FileInputStream(file);
                while ((len = in.read(buffer)) != -1) {
                    digest.update(buffer, 0, len);
                }
                in.close();
    
                byte[] b = digest.digest();
                return byteToHexString(b);
    
            } catch (Exception e) {
                return null;
            }
        }
    
        /**
         * 把 byte[]数组转换成十六进制字符串表示形式
         * @Author: CcchenCoco
         * @Date: 2022/3/29 11:29
         * @Param:
         **/
        private static String byteToHexString(byte[] tmp) {
            String s;
            // 用字节表示就是 16 个字节,每个字节用 16 进制表示的话,使用两个字符,所以表示成 16 进制需要 32 个字符
            char str[] = new char[16 * 2];
            // 表示转换结果中对应的字符位置
            int k = 0; 
            // 从第一个字节开始,对 MD5 的每一个字节
            for (int i = 0; i < 16; i++) {
                // 转换成 16 进制字符的转换,取第 i 个字节
                byte byte0 = tmp[i];
                // 取字节中高 4 位的数字转换, >>> 为逻辑右移,将符号位一起右移
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                // 取字节中低 4 位的数字转换
                str[k++] = hexDigits[byte0 & 0xf];
            }
            // 换后的结果转换为字符串
            s = new String(str);
            return s;
        }
    }
    

    参考文献:
    【1】Java加密算法—消息摘要及文件消息摘要
    【2】MD5信息摘要算法详解
    【3】文件全文生成MD5摘要
    【4】一文详解 MD5 信息摘要算法
    【5】三分钟读懂摘要算法

  • 相关阅读:
    大batch任务对structured streaming任务影响
    spark 集群优化
    linux神器 strace解析
    打个 hadoop RPC的栗子
    netty 入门
    c#硬件对接数值转换
    RabbitMQ 消息队列入门
    RabbitMQ 开发环境安装部署
    Nginx-4.Nginx如何处理请求
    Nginx-3.控制nginx
  • 原文地址:https://www.cnblogs.com/shujk/p/16314716.html
Copyright © 2020-2023  润新知