首页 > 其他分享 >根据字符串计算md5

根据字符串计算md5

时间:2022-12-09 15:35:58浏览次数:35  
标签:return String static 计算 字符串 import public md5

MD5用途

1、对比两个字符串的变化, 例如记录表单数据的改变来决定是否进行更新数据

2、对比字节流是否相同(对比文件、图片、文档等等等)

             import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    private static final char[] hexChar = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f'
    };

    /**
     * 根据字符串获取md5
     * @param str 字符串
     * @return MD5
     */
    public static String getStrMD5(String str) {
        if (StringUtils.isEmpty(str)) return "";
        try {
            return MD5Util.getHash(str.getBytes(), "MD5");
        } catch (Exception ex) {
            return "";
        }

    }

    /**
     * 根据字节计算md5
     *
     * @param bytes 文件字节
     * @param hashType md5
     * @return MD5
     * @throws IOException IOException
     * @throws NoSuchAlgorithmException NoSuchAlgorithmException
     */
    public static String getHash(byte[] bytes, String hashType) throws IOException, NoSuchAlgorithmException {

        InputStream ins = new ByteArrayInputStream(bytes);

        byte[] buffer = new byte[8192];
        MessageDigest md5 = MessageDigest.getInstance(hashType);

        int len;
        while ((len = ins.read(buffer)) != -1) {
            md5.update(buffer, 0, len);
        }

        ins.close();
        return toHexString(md5.digest());
    }



    public static String toHexString(byte[] b) {
        StringBuilder sb = new StringBuilder(b.length * 2);
        for (byte value : b) {
            sb.append(hexChar[(value & 0xf0) >>> 4]);
            sb.append(hexChar[value & 0x0f]);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(getStrMD5("111111111111"));
        System.out.println(getStrMD5("111111111111"));
    }
}

 

标签:return,String,static,计算,字符串,import,public,md5
From: https://www.cnblogs.com/cxyfyf/p/16969041.html

相关文章