代码之家  ›  专栏  ›  技术社区  ›  Abhi

生成的sha512字符串不同于java中生成的字符串

  •  0
  • Abhi  · 技术社区  · 4 年前

    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();
        }
    

    这就是我在围棋中的写作方式:

    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

    我做错了什么?

    1 回复  |  直到 4 年前
        1
  •  2
  •   Cerise Limón    4 年前

    Go代码将消息+盐散列。Java代码散列salt+消息。交换Go代码中的顺序以匹配Java代码。

    在转换为十六进制时使用整数值而不是字节。使用字节时,0x100将转换为零:

    s += fmt.Sprintf("%x", ((int(hashedBytes[i]) & 0xff) + 0x100))[1:]
    

    更好的方法是使用库函数进行转换。使用编码/十六进制:

    return hex.EncodeToString(hashedBytes)
    

    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
    }