首页 > 后端开发 > Golang > 正文

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

WBOY
发布: 2024-02-06 10:24:07
转载
671 人浏览过

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: %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 怪异将 Btye 数组从 MD5 哈希值转换为字符串的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:stackoverflow.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!