我正在嘗試生成一個類似于在 java 代碼中生成的散列,以便可以比較它們以檢查稍后在資料庫中的重復項。
這是java代碼生成它的方式:
public String getHash(String algorithm, String message, String salt) throws NoSuchAlgorithmException {
// Create MessageDigest instance for given algorithm
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(salt.getBytes());
byte[] bytes = md.digest(message.getBytes());
// Convert it to hexadecimal format
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i ) {
sb.append(Integer.toString((bytes[i] & 0xff) 0x100, 16)
.substring(1));
}
return sb.toString();
}
我在 Go 中是這樣寫的:
func HashSha512(original string) (string, error) {
salt := "abcde687869"
originalStrBytes := []byte(original)
sha512Hasher := sha512.New()
saltedValueBytes := append(originalStrBytes, []byte(salt)...)
sha512Hasher.Write(saltedValueBytes)
hashedBytes := sha512Hasher.Sum(nil)
s := ""
var x uint64 = 0x100
y := byte(x)
for i := 0; i < len(hashedBytes); i {
s = fmt.Sprintf("%x", ((hashedBytes[i] & 0xff) y))[1:]
}
return s, nil
}
但是生成的字串不一樣。
去游樂場鏈接:https : //play.golang.com/p/uXaw7y2tklN
生成的字串是
99461a225184c478b8398c7f0dcc1d3afed107660d08a7282a10f5e2ab6
java中為同一個字串生成的字串是
020e93364e5186b7d4ac211cd116425234937d390fcc4e1c554fa1e4bafcb934493047ab841e06f00aa28aabee43b737a6bae2f3fc52e431dde724e691aa952d
我究竟做錯了什么?
uj5u.com熱心網友回復:
Go 代碼散列訊息 鹽。Java 代碼散列鹽 訊息。交換 Go 代碼中的順序以匹配 Java 代碼。
在轉換為十六進制時使用整數值而不是位元組。使用位元組時 0x100 轉換為零:
s = fmt.Sprintf("%x", ((int(hashedBytes[i]) & 0xff) 0x100))[1:]
更好的是,使用庫函式進行轉換。使用編碼/十六進制:
return hex.EncodeToString(hashedBytes)
使用 fmt:
return fmt.Sprintf("%x", hashedBytes)
字串編碼為位元組的方式可能有所不同。Java 代碼使用平臺的默認字符集。假設 Go 應用程式使用典型的 UTF-8 編碼字串,則轉換后的位元組是 UTF-8 編碼的。
這是該函式的一個更簡單的版本:
func HashSha512hex(original string) (string, error) {
salt := "abcde6786"
h := sha512.New()
io.WriteString(h, salt)
io.WriteString(h, original)
s := h.Sum(nil)
return hex.EncodeToString(s), nil
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358288.html
