【问题标题】:sha512 string generated is different from string generated in java生成的sha512字符串与java中生成的字符串不同
【发布时间】:2021-12-26 09:35:52
【问题描述】:

我正在尝试生成一个类似于在 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

我做错了什么?

【问题讨论】:

    标签: java go hash


    【解决方案1】:

    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
    }
    

    【讨论】:

    • 我刚刚意识到交换部分.. 还是谢谢 :)
    猜你喜欢
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多