重构代码。

dev
ZhouXY108 2023-04-15 13:37:44 +08:00
parent 6335fa03b1
commit b015f5d1c4
1 changed files with 13 additions and 16 deletions

View File

@ -4,10 +4,10 @@ import java.math.BigInteger;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.Objects;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import lombok.extern.slf4j.Slf4j;
import xyz.zhouxy.plusone.constant.ErrorCodeConsts; import xyz.zhouxy.plusone.constant.ErrorCodeConsts;
import xyz.zhouxy.plusone.exception.BizException; import xyz.zhouxy.plusone.exception.BizException;
import xyz.zhouxy.plusone.util.RandomUtil; import xyz.zhouxy.plusone.util.RandomUtil;
@ -17,7 +17,6 @@ import xyz.zhouxy.plusone.util.RandomUtil;
* *
* @author <a href="https://gitee.com/zhouxy108">ZhouXY</a> * @author <a href="https://gitee.com/zhouxy108">ZhouXY</a>
*/ */
@Slf4j
public final class PasswordUtil { public final class PasswordUtil {
private static final char[] SALT_BASE_CHAR_ARRAY = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`!@#$%^&*()_-+={}[]|\\:;\"',.<>?/" private static final char[] SALT_BASE_CHAR_ARRAY = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`!@#$%^&*()_-+={}[]|\\:;\"',.<>?/"
.toCharArray(); .toCharArray();
@ -36,11 +35,12 @@ public final class PasswordUtil {
var passwordWithSalt = salt.substring(0, i) var passwordWithSalt = salt.substring(0, i)
+ password + password
+ salt.substring(1); + salt.substring(1);
String sha512Hex = sha512Hex(passwordWithSalt);
if (sha512Hex == null) { try {
throw new BizException(ErrorCodeConsts.DEFAULT_ERROR_CODE, "未知错误:哈希加密失败!"); return sha512Hex(passwordWithSalt);
} catch (Exception e) {
throw new BizException(ErrorCodeConsts.DEFAULT_ERROR_CODE, "哈希加密失败!", e);
} }
return sha512Hex;
} }
/** /**
@ -57,15 +57,12 @@ public final class PasswordUtil {
throw new IllegalStateException("Utility class"); throw new IllegalStateException("Utility class");
} }
private static String sha512Hex(String data) { @Nonnull
try { private static String sha512Hex(String data) throws NoSuchAlgorithmException {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-512"); MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
messageDigest.update(data.getBytes(StandardCharsets.UTF_8)); messageDigest.update(data.getBytes(StandardCharsets.UTF_8));
byte[] result = messageDigest.digest(); byte[] result = messageDigest.digest();
return new BigInteger(1, result).toString(16); var sha512Hex = new BigInteger(1, result).toString(16);
} catch (NoSuchAlgorithmException e) { return Objects.requireNonNull(sha512Hex);
log.error("{}", e);
}
return null;
} }
} }