本文提供一個不依賴外部庫、基於 RFC 3174 標準實現的 SHA1Util 類,支持十六進制、Base64、字符串等多種輸出格式,並包含 HMAC-SHA1 功能。可用於密碼加密、數據完整性校驗、簽名生成等場景。
public class SHA1Util {
// 1. 計算字符串 SHA-1,返回十六進制字符串(小寫)
public static String hex_sha1(String s)
// 2. 計算 SHA-1,返回 Base64 編碼字符串
public static String b64_sha1(String s)
// 3. 計算 SHA-1,返回原始字符串(可能含不可見字符)
public static String str_sha1(String s)
// 4. HMAC-SHA1:帶密鑰的雜湊,返回十六進制
public static String hex_hmac_sha1(String key, String data)
// 5. HMAC-SHA1,返回 Base64
public static String b64_hmac_sha1(String key, String data)
// 6. HMAC-SHA1,返回原始字符串
public static String str_hmac_sha1(String key, String data)
// 內部核心實現:core_sha1, core_hmac_sha1, str2binb, binb2hex 等輔助方法
}
public static void main(String[] args) {
String pwd = "admin";
System.out.println("SHA-1(hex): " + SHA1Util.hex_sha1(pwd));
// 輸出: SHA-1(hex): d033e22ae348aeb5660fc2140aec35850c4da997
String key = "secret";
String data = "message";
System.out.println("HMAC-SHA1: " + SHA1Util.hex_hmac_sha1(key, data));
}
rol)、安全加法(safe_add)、邏輯函數(ft)、常量(kt)。chrsz=8)處理,適合 ASCII/UTF-8 兼容字符;中文等多字節字符會按字節處理。sha1_vm_test() 驗證 "abc" 的雜湊值是否符合標準向量。雖然純 Java 實現有助於理解原理,但實際項目中強烈建議使用 JDK 內置的 java.security.MessageDigest 或成熟庫(如 Apache Commons Codec、Bouncy Castle),它們經過優化、原生加速且安全性經過廣泛驗證。
// JDK 標準用法
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] digest = md.digest("admin".getBytes(StandardCharsets.UTF_8));
String hex = Hex.encodeHexString(digest); // 需 Commons Codec 或手動轉十六進制