Java MD5加密方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangbinlong/article/details/78662971
package com.dataservice.utils;

import java.security.MessageDigest;

import org.springframework.util.Base64Utils;

public class MD5Util {

    private static final String ALGORITHM = "MD5";

    public static String getMD5(String message) throws Exception {
        MessageDigest digest = MessageDigest.getInstance(ALGORITHM);
        byte[] hashedBytes = digest.digest(message.getBytes("UTF-8"));
        return convertByteArrayToHexString(hashedBytes);
    }

    private static String convertByteArrayToHexString(byte[] arrayBytes) {
        StringBuilder sb = new StringBuilder();
        for (byte arrayByte : arrayBytes) {
            sb.append(Integer.toString((arrayByte & 0xff) + 0x100, 16).substring(1));
        }
        return sb.toString();
    }

    public static String encodeMD5ANDBase64(String originstr) throws Exception {
        String result = null;
        if (originstr != null) {
            // 返回实现指定摘要算法的 MessageDigest 对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 使用utf-8编码将originstr字符串编码并保存到source字节数组
            byte[] source = originstr.getBytes("utf-8");
            // 使用指定的 byte 数组更新摘要
            md.update(source);
            // 通过执行诸如填充之类的最终操作完成哈希计算,结果是一个128位的长整数
            byte[] tmp = md.digest();
            result = Base64Utils.encodeToString(tmp);
        }
        return result;
    }

}

猜你喜欢

转载自blog.csdn.net/zhangbinlong/article/details/78662971