有人可以告诉我哪里出了问题吗?
我无法通过字符串转换来转换由哈希求和函数生成的字节数组,我必须使用 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 将导致 d41d8cd98f00b204e9800998ecf8427e
hashstringjunk 将导致 ��ُ�� ���b~
正确答案
当您将随机二进制数据转换为没有编码方案的字符串时,数据不太可能映射到可打印字符序列。
来自 fmt
包的 %x
动词是对二进制数据进行十六进制编码的便捷方法。来自fmt
包文档中动词定义的“字符串和字节切片”部分: p>
%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
或者,您可以使用嵌套在 encoding
包下的包对数据进行编码:
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: %sn", hash)
fmt.printf("using %%q verb: %qn", hash)
fmt.printf("using %%x verb: %xn", hash)
hexhash := hex.encodetostring(hash[:])
fmt.printf("converted to a hex-encoded string: %sn", hexhash)
base64hash := base64.stdencoding.encodetostring(hash[:])
fmt.printf("converted to a base64-encoded string: %sn", base64hash)
}
输出
Using %s verb: �����Q���6���5�
Using %q verb: "x8dxa8xf1xf8x06xd3Qx9dxa1xe46xdbxfbx9f5xd7"
Using %x verb: 8da8f1f806d3519da1e436dbfb9f35d7
Converted to a hex-encoded string: 8da8f1f806d3519da1e436dbfb9f35d7
Converted to a base64-encoded string: jajx+AbTUZ2h5Dbb+5811w==
去游乐场