记录一下两个比较常用的md5加密算法

第一个,计算字符串的md5值

public static String getMD5(String s){
        String newString  = null;
        byte[] inputByteArray = s.getBytes();
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F' };
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(inputByteArray);
            byte[] mdByte = md.digest();
            int j = mdByte.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = mdByte[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            newString = new String(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newString;
    }

第二个,计算文件(给出路径)的md5值

public static String getFileMd5(String path) {
        try {
            
            File file = new File(path);
            // md5
            MessageDigest digest = MessageDigest.getInstance("md5");
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int len = -1;
            while ((len = fis.read(buffer)) != -1) {
                digest.update(buffer, 0, len);
            }
            byte[] result = digest.digest();
            StringBuffer sb = new StringBuffer();
            for (byte b : result) {
                
                int number = b & 0xff;//避免byte转int时出现负数
                String str = Integer.toHexString(number);
                // System.out.println(str);
                if (str.length() == 1) {
                    sb.append("0");
                }
                sb.append(str);
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
原文地址:https://www.cnblogs.com/BlogCommunicator/p/4971502.html