java生成32的md5签名串

import java.security.MessageDigest;

import lombok.extern.slf4j.Slf4j;

/**
 * 签名帮助类
 * 
 * @author yangzl
 * @data 2019年4月4日
 *
 */
@Slf4j
public class SignUtils {
    
    private SignUtils() {}
    
    /**
     * 生成32位的MD5签名串
     * @param source 待签名串
     * @param salt 盐
     * @param toUpperCase 是否转大写
     * @return
     */
    public static String md5(String source, String salt, boolean toUpperCase) {
        source = source + salt;

        StringBuilder sb = new StringBuilder(32);

        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(source.getBytes("utf-8"));

            for (int i = 0; i < array.length; i++) {
                if(toUpperCase) {
                    sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).toUpperCase().substring(1, 3));
                } else {
                    sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
                }
            }
        } catch (Exception e) {
            log.error("Can not encode the string '" + source + "' to MD5!", e);
            throw new RuntimeException(e);
        }

        return sb.toString();
    }
}

猜你喜欢

转载自www.cnblogs.com/yangzhilong/p/10672204.html