詳見代碼...
/**
md5 hash
**/
package main
import (
"crypto/md5"
"fmt"
"encoding/hex"
"io"
"reflect"
)
// 方法一
func md5V1(str string) {
bytes := []byte(str)
// 創(chuàng)建 md5 對象
hash := md5.New()
// 也可以增加一個 key,和 key 一起使用 md5 計算摘要榨惠。加鹽
// func NewMD5(key []byte) hash.Hash
// 將要計算的字符串以 byte 數(shù)組的形式寫入對象中
hash.Write(bytes)
// 獲取摘要結果忘衍,返回一個 []byte 類型
hashValue := hash.Sum(nil)
// []uint8(unit8即byte)
fmt.Println(reflect.TypeOf(hashValue).String())
// [177 148 106 201 36 146 210 52 124 98 53 180 210 97 17 132]
fmt.Println(hashValue);
// 通常以 ASCII 形式輸 出四個由 4 字節(jié)組成的十六進制數(shù)
hashSzie := hash.Size()
for i := 0; i < hashSzie; i += 4 {
var val uint32
// 比低位高 3 字節(jié)紧阔,*pow(2,3*8)
val = uint32(hashValue[i]) << 24 +
// 比低位高 2 字節(jié),*pow(2,2*8)
uint32(hashValue[i + 1]) << 16 +
// // 比低位高 1 字節(jié)吭净,*pow(2,1*8)
uint32(hashValue[i + 2]) << 8 +
uint32(hashValue[i + 3])
fmt.Printf("%x", val)
}
fmt.Println()
// 上述轉換過程可以使用 hex.EncodeToString
fmt.Println(hex.EncodeToString(hashValue))
// 其實直接使用 %x 格式化輸出也是一樣的
fmt.Printf("%x\n", hashValue)
// 也可以通過 fmt 寫入 string 字符串
md5Str := fmt.Sprintf("%x", hashValue)
fmt.Println(md5Str)
fmt.Println("==================")
}
// 方法二
func md5V2(str string) {
bytes := []byte(str)
// 該方法寫起來較方法一,三方便
// 返回的 [16]byte 類型,區(qū)別于方法一和方法三中的 []byte
hashValue := md5.Sum(bytes)
// [16]uint8(unit8即byte)
fmt.Println(reflect.TypeOf(hashValue).String())
fmt.Printf("%x\n", hashValue)
fmt.Println("==================")
}
// 方法三
func md5V3(str string) {
hash := md5.New()
// 和方法一的區(qū)別就是此處使用的 io.WriteString 將字符串寫入 hash
// 而方法一使用的 md5.Write 將字符串寫入 hash 中
io.WriteString(hash, str)
hashValue := hash.Sum(nil)
// []uint8(unit8即byte)
fmt.Println(reflect.TypeOf(hashValue).String())
fmt.Printf("%x\n", hashValue)
fmt.Println("==================")
}
func main() {
str := "hello\n";
md5V1(str)
md5V2(str)
md5V3(str)
}