使用原生哈希算法。使用自己实现的随机盐生成方法。

This commit is contained in:
zhouxy108 2023-03-17 18:46:06 +08:00
parent 7a44c43402
commit 39cd57e675

View File

@ -1,19 +1,26 @@
package xyz.zhouxy.plusone.system.util;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.annotation.Nonnull;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import lombok.extern.slf4j.Slf4j;
import xyz.zhouxy.plusone.constant.ErrorCodeConsts;
import xyz.zhouxy.plusone.exception.BizException;
import xyz.zhouxy.plusone.util.RandomUtil;
/**
* 密码工具类
*
* @author <a href="https://gitee.com/zhouxy108">ZhouXY</a>
*/
@Slf4j
public final class PasswordUtil {
private static final String SALT_BASE_STRING = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`!@#$%^&*()_-+={}[]|\\:;\"',.<>?/";
private static final char[] SALT_BASE_CHAR_ARRAY = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`!@#$%^&*()_-+={}[]|\\:;\"',.<>?/"
.toCharArray();
/**
* 将密码和随机盐混合并进行哈希加密
@ -29,7 +36,7 @@ public final class PasswordUtil {
var passwordWithSalt = salt.substring(0, i)
+ password
+ salt.substring(1);
String sha512Hex = DigestUtil.sha512Hex(passwordWithSalt);
String sha512Hex = sha512Hex(passwordWithSalt);
if (sha512Hex == null) {
throw new BizException(ErrorCodeConsts.DEFAULT_ERROR_CODE, "未知错误:哈希加密失败!");
}
@ -42,11 +49,23 @@ public final class PasswordUtil {
* @return 生成的随机盐
*/
public static String generateRandomSalt() {
return RandomUtil.randomString(SALT_BASE_STRING, 24);
return RandomUtil.randomStr(SALT_BASE_CHAR_ARRAY, 24);
}
private PasswordUtil() {
// 不允许实例化
throw new IllegalStateException("Utility class");
}
private static String sha512Hex(String data) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
messageDigest.update(data.getBytes(StandardCharsets.UTF_8));
byte[] result = messageDigest.digest();
return new BigInteger(1, result).toString(16);
} catch (NoSuchAlgorithmException e) {
log.error("{}", e);
}
return null;
}
}