卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34141本站已运行391

GO 怪异将 Btye 数组从 MD5 哈希值转换为字符串

go 怪异将 btye 数组从 md5 哈希值转换为字符串

问题内容

有人可以告诉我哪里出了问题吗?

我无法通过字符串转换来转换由哈希求和函数生成的字节数组,我必须使用 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 包文档中动词定义的“字符串和字节切片”部分:

%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==

去游乐场

卓越飞翔博客
上一篇: 从 Go 结构动态添加元素到 JSON
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏