GO weirdness converting Btye array from MD5 hash to string

WBOY
Release: 2024-02-06 10:24:07
forward
672 people have browsed it

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

Question content

Can someone tell me what's wrong?

I cannot convert the byte array produced by the hash sum function via string conversion, I have to use sprintf.

This is the code snippet:

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

hasstringgood will result in d41d8cd98f00b204e9800998ecf8427e hashstringjunk will result in ��ُ�� ���b~


Correct answer


when you convert random binary data to no encoding scheme string, the data is unlikely to map to a sequence of printable characters.

The %x verb from the fmt package is a convenience method for hexadecimal encoding of binary data. From the "Strings and Byte Slicing" section of the verb definition in the fmt package documentation :

%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
Copy after login

Alternatively, you can encode the data using a package nested under the encoding package:

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)
}
Copy after login

Output

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==
Copy after login

Go to the amusement park

The above is the detailed content of GO weirdness converting Btye array from MD5 hash to string. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!