|
@@ -0,0 +1,36 @@
|
|
|
+package com.yingyangfly.baselib.utils;
|
|
|
+
|
|
|
+import java.nio.charset.StandardCharsets;
|
|
|
+import java.security.MessageDigest;
|
|
|
+import java.security.NoSuchAlgorithmException;
|
|
|
+
|
|
|
+public class SHA256Utils {
|
|
|
+ /**
|
|
|
+ * 使用SHA-256算法和盐对密码进行哈希处理
|
|
|
+ *
|
|
|
+ * @param input 需要哈希的密码
|
|
|
+ * @return 哈希值(十六进制字符串)
|
|
|
+ */
|
|
|
+ public static String hashWithSalt(String input) {
|
|
|
+ try {
|
|
|
+ // 获取SHA-256 MessageDigest实例
|
|
|
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
|
|
+
|
|
|
+ // 将输入字符串转换为字节数组,并使用指定的字符编码(此处为UTF-8)
|
|
|
+ byte[] encodedhash = digest.digest(input.getBytes(StandardCharsets.UTF_8));
|
|
|
+
|
|
|
+ // 将字节数组转换为十六进制字符串
|
|
|
+ StringBuilder hexString = new StringBuilder(2 * encodedhash.length);
|
|
|
+ for (byte b : encodedhash) {
|
|
|
+ String hex = Integer.toHexString(0xff & b);
|
|
|
+ if (hex.length() == 1) hexString.append('0');
|
|
|
+ hexString.append(hex);
|
|
|
+ }
|
|
|
+
|
|
|
+ return hexString.toString();
|
|
|
+ } catch (NoSuchAlgorithmException e) {
|
|
|
+ // SHA-256应该总是可用的,但如果发生这种情况,则抛出运行时异常
|
|
|
+ throw new RuntimeException(e);
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|