字节数组的校验和

huangapple go评论133阅读模式
英文:

checksum of a byte array

问题

我有一个由字符串生成的[]byte

  1. array := []byte("some string")

它看起来像这样:

  1. [115 111 109 101 32 115 116 114 105 110 103]

有没有一种简单的方法来获取[]byte的校验和?像这样:

  1. sum(array)
英文:

I have a []byte, made from a string:

  1. array := []byte("some string")

It looks like expected:

  1. [115 111 109 101 32 115 116 114 105 110 103]

Is there a way to simply get the checksum of []byte? Like:

  1. sum(array)

答案1

得分: 1

也许你需要使用md5.sum来检查可靠性。

https://pkg.go.dev/crypto/md5#Sum

  1. package main
  2. import (
  3. "crypto/md5"
  4. "fmt"
  5. )
  6. func main() {
  7. data := []byte("some string")
  8. fmt.Printf("%x", md5.Sum(data))
  9. }

另一个例子。

https://play.golang.org/p/7_ctunsqHS3

英文:

Maybe you need md5.sum to check reliability.

https://pkg.go.dev/crypto/md5#Sum

  1. package main
  2. import (
  3. "crypto/md5"
  4. "fmt"
  5. )
  6. func main() {
  7. data := []byte("some string")
  8. fmt.Printf("%x", md5.Sum(data))
  9. }

Another example.

https://play.golang.org/p/7_ctunsqHS3

答案2

得分: 1

我认为在可能的情况下,避免使用fmt进行转换是很好的:

  1. package main
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. )
  6. func checksum(s string) string {
  7. b := md5.Sum([]byte(s))
  8. return hex.EncodeToString(b[:])
  9. }
  10. func main() {
  11. s := checksum("some string")
  12. println(s == "5ac749fbeec93607fc28d666be85e73a")
  13. }

https://godocs.io/crypto/md5#Sum

英文:

I think it's good to avoid using fmt for conversion when possible:

  1. package main
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. )
  6. func checksum(s string) string {
  7. b := md5.Sum([]byte(s))
  8. return hex.EncodeToString(b[:])
  9. }
  10. func main() {
  11. s := checksum("some string")
  12. println(s == "5ac749fbeec93607fc28d666be85e73a")
  13. }

https://godocs.io/crypto/md5#Sum

答案3

得分: 0

以下是代码的中文翻译:

  1. package main
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "fmt"
  6. )
  7. func GetMD5HashWithSum(text string) string {
  8. hash := md5.Sum([]byte(text))
  9. return hex.EncodeToString(hash[:])
  10. }
  11. func main() {
  12. hello := GetMD5HashWithSum("some string")
  13. fmt.Println(hello)
  14. }

你可以在Golang Playground上运行它。

英文:
  1. package main
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "fmt"
  6. )
  7. func GetMD5HashWithSum(text string) string {
  8. hash := md5.Sum([]byte(text))
  9. return hex.EncodeToString(hash[:])
  10. }
  11. func main() {
  12. hello := GetMD5HashWithSum("some string")
  13. fmt.Println(hello)
  14. }

You can it on Golang Playground

huangapple
  • 本文由 发表于 2021年10月10日 23:16:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/69516444.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定