
io.github.wslxm.springbootplus2.utils.XjMd5Util Maven / Gradle / Ivy
package io.github.wslxm.springbootplus2.utils;
import io.github.wslxm.springbootplus2.core.constant.NumberConst;
import io.github.wslxm.springbootplus2.core.utils.XjPropUtil;
import lombok.extern.slf4j.Slf4j;
import java.security.MessageDigest;
/***
* md5 密码加密工具类 (系统用户)
* @author 王松
* @email [email protected]
* @date 2020/7/5 0005 22:06
*/
@Slf4j
public class XjMd5Util {
/**
* md5盐-加密盐值
*/
private static String SALT = null;
private static final String DEFAULT_SALT = "xijia";
/**
* md5 加密加盐
*
* @param password 密码
* @param userSalt 用户盐
* @return {@link String}
*/
public static String encode(String password, String userSalt) {
return encode(password, userSalt, getSalt());
}
/**
* md5 加密加盐
*
* 加密规则: 固定盐 + 密码 + 3次动态盐 (动态盐 = 用户id(建议) 或 用户姓名 或 多种组合)
*
*
* @param password 密码
* @param sysSalt 盐值(系统层级)
* @param userSalt 盐值(用户层级)
* @return 加密后的密码
*/
public static String encode(String password, String userSalt, String sysSalt) {
// 对密码进行加盐 start ---
StringBuilder sb = new StringBuilder(sysSalt);
sb.append(password);
for (int i = 0; i < NumberConst.THREE; i++) {
sb.append(userSalt);
}
password = sb.toString();
// 对密码进行加盐 end ---
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
throw new RuntimeException(e);
}
char[] charArray = password.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++) {
byteArray[i] = (byte) charArray[i];
}
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
/**
* 获取盐
* @return
*/
private static String getSalt() {
if (SALT == null) {
// Object pwdSalt = null;
Object pwdSalt = XjPropUtil.findByKey("secure.pwdSalt");
SALT = pwdSalt != null ? pwdSalt.toString() : DEFAULT_SALT;
}
return SALT;
}
public static void main(String[] args) {
// 参数1= 密码
// 参数2= 用户id (用户盐)
// 参数3= (系统盐, 对应yml 配置中的 secure.pwdSalt, 没有配置默认使用 DEFAULT_SALT)
log.info("密码: {}", XjMd5Util.encode("123456", "1", DEFAULT_SALT));
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy