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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM