57 lines
1.7 KiB
Java
57 lines
1.7 KiB
Java
package xin.merlin.myblog_server.utils;
|
||
|
||
import org.springframework.beans.factory.annotation.Value;
|
||
import org.springframework.stereotype.Component;
|
||
|
||
import java.security.MessageDigest;
|
||
import java.security.NoSuchAlgorithmException;
|
||
|
||
@Component
|
||
public class SHA256Util {
|
||
/**
|
||
* 对输入字符串进行SHA-256加密
|
||
* @param input 输入字符串
|
||
* @return 加密后的十六进制字符串
|
||
*/
|
||
public String encryptSHA256(String input) {
|
||
try {
|
||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||
byte[] encodedhash = digest.digest(input.getBytes());
|
||
return bytesToHex(encodedhash);
|
||
} catch (NoSuchAlgorithmException e) {
|
||
throw new RuntimeException("SHA-256 algorithm not found", e);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 将字节数组转换为十六进制字符串
|
||
* @param hash 字节数组
|
||
* @return 十六进制字符串
|
||
*/
|
||
private String bytesToHex(byte[] hash) {
|
||
StringBuilder hexString = new StringBuilder(2 * hash.length);
|
||
for (int i = 0; i < hash.length; i++) {
|
||
String hex = Integer.toHexString(0xff & hash[i]);
|
||
if (hex.length() == 1) {
|
||
hexString.append('0');
|
||
}
|
||
hexString.append(hex);
|
||
}
|
||
return hexString.toString();
|
||
}
|
||
|
||
/**
|
||
* 使用用户ID生成盐值,并对密码进行加密
|
||
* @param password 用户输入的密码
|
||
* @return 加密后的密码哈希值
|
||
*/
|
||
@Value("${jwt.salt}")
|
||
private String salt;
|
||
|
||
public String encryptPassword(String password) {
|
||
String s = encryptSHA256(salt);
|
||
// 将盐值与密码拼接后进行SHA-256加密
|
||
return encryptSHA256(s +s + password + s);
|
||
}
|
||
}
|