Maison  >  Article  >  développement back-end  >  GO bizarrerie convertissant le tableau Btye du hachage MD5 en chaîne

GO bizarrerie convertissant le tableau Btye du hachage MD5 en chaîne

WBOY
WBOYavant
2024-02-06 10:24:07644parcourir

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

Contenu de la question

Quelqu'un peut-il me dire ce qui ne va pas ?

Je ne peux pas convertir le tableau d'octets généré par la fonction de somme de hachage via la conversion de chaîne, je dois utiliser sprintf.

Voici l'extrait de code :

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

hasstringgood entraînera d41d8cd98f00b204e9800998ecf8427e hashstringjunk entraînera ��ُ�� ���b~


Réponse correcte


Lorsque vous convertissez des données binaires aléatoires en chaîne sans schéma de codage, il est peu probable que les données soient mappées à une séquence de caractères imprimables.

De la section "Strings and Byte Slicing" de la définition du verbe dans la fmt 包的 %x 动词是对二进制数据进行十六进制编码的便捷方法。来自fmt documentation du package  : 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

Alternativement, vous pouvez encoder les données à l'aide d'un package imbriqué sous le package 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)
}

Sortie

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

Aller au parc d'attractions

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer