zoukankan      html  css  js  c++  java
  • 记录一下两个比较常用的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 "";
            }
        }
  • 相关阅读:
    Qt添加程序图标
    QTcpSocket+QTcpServer+QWebEngineView打造简易聊天室
    Qt聊天室
    QThread+QMutex多线程编程
    Qt设置窗体背景渐变
    Could not resolve host: github.com
    git clone某一分支上的内容
    git基本操作
    C++中的static关键字的总结
    C/C++中static关键字作用总结
  • 原文地址:https://www.cnblogs.com/BlogCommunicator/p/4971502.html
Copyright © 2011-2022 走看看