代码之家  ›  专栏  ›  技术社区  ›  cringe

如何从golang中的字符串获取md5散列?

  •  39
  • cringe  · 技术社区  · 14 年前

    我就是这样开始 md5 散列 string :

    import "crypto/md5"
    
    var original = "my string comes here"
    var hash = md5.New(original)
    

    但显然这不是它的工作方式。有人能给我一个工作样品吗?

    6 回复  |  直到 6 年前
        1
  •  33
  •   Alan    10 年前

    参考文献 Sum 对我来说好好工作

    package main
    
    import (
        "crypto/md5"
        "fmt"
    )
    
    func main() {
        data := []byte("hello")
        fmt.Printf("%x", md5.Sum(data))
    }
    
        2
  •  34
  •   Sridhar Ratnakumar    12 年前

    crypto/md5 doc :

    package main
    
    import (
        "crypto/md5"
        "fmt"
        "io"
    )
    
    func main() {
        h := md5.New()
        io.WriteString(h, "The fog is getting thicker!")
        fmt.Printf("%x", h.Sum(nil))
    }
    
        3
  •  33
  •   user387049    11 年前

    我发现这个办法很有效

    package main
    
    import (
        "crypto/md5"
        "encoding/hex"
        "fmt"
    )
    
    func main() {
        var str string = "hello world"
    
        hasher := md5.New()
        hasher.Write([]byte(str))
        fmt.Println(str)
        fmt.Println(hex.EncodeToString(hasher.Sum(nil)))
    }
    
        4
  •  21
  •   aviv    10 年前
    import (
        "crypto/md5"
        "encoding/hex"
    )
    
    func GetMD5Hash(text string) string {
       hash := md5.Sum([]byte(text))
       return hex.EncodeToString(hash[:])
    }
    
        5
  •  12
  •   sergserg    11 年前

    我用这个来md5散列我的字符串:

    import (
        "crypto/md5"
        "encoding/hex"
    )
    
    func GetMD5Hash(text string) string {
        hasher := md5.New()
        hasher.Write([]byte(text))
        return hex.EncodeToString(hasher.Sum(nil))
    }
    
        6
  •  2
  •   Raed Shomali    7 年前

    下面是一个可用于生成MD5哈希的函数:

    // MD5 hashes using md5 algorithm
    func MD5(text string) string {
        algorithm := md5.New()
        algorithm.Write([]byte(text))
        return hex.EncodeToString(algorithm.Sum(nil))
    }
    

    我将这些实用哈希函数组合在一起: https://github.com/shomali11/util

    你会发现 FNV32 , FNV32a , FNV64 , FNV65a , MD5 , SHA1 , SHA256 SHA512