首頁 > 後端開發 > Golang > 主體

GO 怪異將 Btye 陣列從 MD5 雜湊值轉換為字串

WBOY
發布: 2024-02-06 10:24:07
轉載
672 人瀏覽過

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學習者快速成長!