GO Weirdness 将 Btye 数组从 MD5 哈希转换为字符串

GO Weirdness Converting Btye array to string from MD5 hash

提问人:Galty 提问时间:12/2/2022 更新时间:12/2/2022 访问量:171

问:

有人可以启发我哪里出错了吗?

我无法通过用字符串转换从哈希和函数生成的字节数组,我必须使用 Sprintf。

下面是代码片段:

f, _ := os.Open(filename)
hash := md5.New()
io.Copy(hash, f)
hashStringGood := fmt.Sprintf("%x", hash.Sum(nil))
hashStringJunk := string(hash.Sum(nil)[:])

hasStringGood 将导致 hashStringJunk 将导致d41d8cd98f00b204e9800998ecf8427e��ُ�� ���B~

数组字符串 go 转换

评论


答:

1赞 Burak Serdar 12/2/2022 #1

MD5 哈希值是 128 位值。如果将其转换为字符串,则将获得 16 个字节的二进制数据,其中许多是不可打印的。您必须使用或其他方法将其转换为字符串。fmt.Sprintf

3赞 chuckx 12/2/2022 #2

当您将随机二进制数据转换为没有编码方案的字符串时,数据不太可能映射到可打印字符序列。

包中的谓词是对二进制数据进行十六进制编码的便捷方法。来自 fmt 包文档中谓词定义的“字符串和字节切片”部分:%xfmt

%s  the uninterpreted bytes of the string or slice
%q  a double-quoted string safely escaped with Go syntax
%x  base 16, lower-case, two characters per byte

或者,您可以使用嵌套在编码包下的包来对数据进行编码:

package main

import (
    "crypto/md5"
    "encoding/base64"
    "encoding/hex"
    "fmt"
)

func main() {
    hash := md5.Sum([]byte("input to be hashed"))
    fmt.Printf("Using %%s verb: %s\n", hash)
    fmt.Printf("Using %%q verb: %q\n", hash)
    fmt.Printf("Using %%x verb: %x\n", hash)

    hexHash := hex.EncodeToString(hash[:])
    fmt.Printf("Converted to a hex-encoded string: %s\n", hexHash)

    base64Hash := base64.StdEncoding.EncodeToString(hash[:])
    fmt.Printf("Converted to a base64-encoded string: %s\n", base64Hash)
}

输出

Using %s verb: �����Q���6���5�
Using %q verb: "\x8d\xa8\xf1\xf8\x06\xd3Q\x9d\xa1\xe46\xdb\xfb\x9f5\xd7"
Using %x verb: 8da8f1f806d3519da1e436dbfb9f35d7
Converted to a hex-encoded string: 8da8f1f806d3519da1e436dbfb9f35d7
Converted to a base64-encoded string: jajx+AbTUZ2h5Dbb+5811w==

Go 游乐场