当前位置: 首页 > 工具软件 > md0 > 使用案例 >

MD5Util

聂溪叠
2023-12-01

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.security.MessageDigest;

@Component
public class MD5Util {
public static final Logger LOGGER= LoggerFactory.getLogger(MD5Util.class);
public static String getMD5(String str) {
try {
//生产一个MD5加密计算
MessageDigest md = MessageDigest.getInstance(“MD5”);
//计算md5函数
md.update(str.getBytes());
// .digest()最后确定返回md5 hash值,返回值为8位字符串,应为md5 hash值为16位的hex值
//实际是8位
//BigInteget函数则将8位字符串转换成16位的hex值,用字符串来表示,得到字符串形式的hash值
return new BigInteger(1, md.digest()).toString(16);

    } catch (Exception e) {
        LOGGER.error("getMD5加密失败,报错原因;{}",e);
        return  null;
    }
}

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

    } catch (Exception e) {
        LOGGER.error("getMD5加密失败,报错原因;{}",e);
       return  null;
    }
}

public static void main(String[] args)  {
    String md52=getMD5("123");
    String md2=getMD5("123");
    String md3=getMD5("123");
    String md4=gainMD5("123");
    String md5=gainMD5("123");
    String md6=getMD5("123");
    LOGGER.info("MD5:"+md52+"  length:"+md5.length());
    LOGGER.info("GetMD5:"+md2+"  length:"+md2.length());
    LOGGER.info("GetMD5:"+md3+"  length:"+md3.length());
    LOGGER.info("GetMD5:"+md4+"  length:"+md4.length());
    LOGGER.info("GetMD5:"+md52+"  length:"+md5.length());
    LOGGER.info("GetMD5:"+md6+"  length:"+md6.length());
    //gainMD5:3C10A15C2F06403A2574094A167A4A42 getMD5:3c10a15c2f06403a2574094a167a4a42
}

}

 类似资料:

相关阅读

相关文章

相关问答