go语言 实现哈希算法
验证结果网址 http://www.fileformat.info/tool/hash.htm "golang.org/x/crypto/md4"不存在时,解决方法: cd $GOPATH/src mkdir -p golang.org/x/ cd golang.org/x/ git clone https://github.com/golang/crypto.git 实现md4加密算法 package main import ( "encoding/hex" "fmt" "hash" "golang.org/x/crypto/md4" ) func main() { res := MD4("123456") fmt.Println(res) } // MD4 MD4 func MD4(text string) string { var hashInstance hash.Hash hashInstance = md4.New() arr, _ := hex.DecodeString(text) hashInstance.Write(arr) bytes := hashInstance.Sum(nil) return fmt.Sprintf("%x", bytes) } 实现封装哈希加密算法 package main import ( "crypto/md5" "crypto/sha1" "crypto/sha256" "crypto/sha512" "encoding/hex" "fmt" "hash" "golang.org/x/crypto/md4" "golang.org/x/crypto/ripemd160" ) func main() { res := HASH("123456", "sha256", true) fmt.Println(res) } // HASH HASH func HASH(text string, hashType string, isHex bool) string { var hashInstance hash.Hash switch hashType { case "md4": hashInstance = md4.New() case "md5": hashInstance = md5.New() case "sha1": hashInstance = sha1.New() case "sha256": hashInstance = sha256.New() case "sha512": hashInstance = sha512.New() case "ripemd160": hashInstance = ripemd160.New() } if isHex { arr, _ := hex.DecodeString(text) hashInstance.Write(arr) } else { hashInstance.Write([]byte(text)) } bytes := hashInstance.Sum(nil) return fmt.Sprintf("%x", bytes) } // MD4 MD4 func MD4(text string, isHex bool) string { var hashInstance hash.Hash hashInstance = md4.New() if isHex { arr, _ := hex.DecodeString(text) fmt.Println(arr) hashInstance.Write(arr) } else { hashInstance.Write([]byte(text)) } bytes := hashInstance.Sum(nil) return fmt.Sprintf("%x", bytes) } // MD5 MD5 func MD5(text string, isHex bool) string { var hashInstance hash.Hash hashInstance = md5.New() if isHex { arr, _ := hex.DecodeString(text) fmt.Println(arr) hashInstance.Write(arr) } else { hashInstance.Write([]byte(text)) } bytes := hashInstance.Sum(nil) return fmt.Sprintf("%x", bytes) } 实现双哈希算法 func sha256Double(text string, isHex bool) []byte { hashInstance := sha256.New() if isHex { arr, _ := hex.DecodeString(text) hashInstance.Write(arr) } else { hashInstance.Write([]byte(text)) } bytes := hashInstance.Sum(nil) hashInstance.Reset() hashInstance.Write(bytes) bytes = hashInstance.Sum(nil) return bytes } func sha256DoubleString(text string, isHex bool) string { bytes := sha256Double(text, isHex) return fmt.Sprintf("%x", bytes) }