字节数组的校验和

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

checksum of a byte array

问题

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

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

它看起来像这样:

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

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

    sum(array)
英文:

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

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

It looks like expected:

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

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

    sum(array)

答案1

得分: 1

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

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

package main

import (
	"crypto/md5"
	"fmt"
)

func main() {
	data := []byte("some string")
	fmt.Printf("%x", md5.Sum(data))
}

另一个例子。

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

英文:

Maybe you need md5.sum to check reliability.

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

package main

import (
	"crypto/md5"
	"fmt"
)

func main() {
	data := []byte("some string")
	fmt.Printf("%x", md5.Sum(data))
}

Another example.

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

答案2

得分: 1

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

package main

import (
   "crypto/md5"
   "encoding/hex"
)

func checksum(s string) string {
   b := md5.Sum([]byte(s))
   return hex.EncodeToString(b[:])
}

func main() {
   s := checksum("some string")
   println(s == "5ac749fbeec93607fc28d666be85e73a")
}

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

英文:

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

package main

import (
   "crypto/md5"
   "encoding/hex"
)

func checksum(s string) string {
   b := md5.Sum([]byte(s))
   return hex.EncodeToString(b[:])
}

func main() {
   s := checksum("some string")
   println(s == "5ac749fbeec93607fc28d666be85e73a")
}

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

答案3

得分: 0

以下是代码的中文翻译:

package main

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
)

func GetMD5HashWithSum(text string) string {
	hash := md5.Sum([]byte(text))
	return hex.EncodeToString(hash[:])
}

func main() {
	hello := GetMD5HashWithSum("some string")
	fmt.Println(hello)
}

你可以在Golang Playground上运行它。

英文:
package main

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
)

func GetMD5HashWithSum(text string) string {
	hash := md5.Sum([]byte(text))
	return hex.EncodeToString(hash[:])
}

func main() {
	hello := GetMD5HashWithSum("some string")
	fmt.Println(hello)
}

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:

确定