Home >Backend Development >Golang >GO weirdness converting Btye array from MD5 hash to string

GO weirdness converting Btye array from MD5 hash to string

WBOY
WBOYforward
2024-02-06 10:24:07700browse

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)[:])

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 : 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

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)
}

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

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!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete