首页 > 文章列表 > 使用 golang 生成字符串的 SHA 哈希?

使用 golang 生成字符串的 SHA 哈希?

golang
392 2023-06-28

问题内容

使用 golang 生成字符串的 SHA 哈希?

正确答案

在Go语言中,你可以使用标准库中的crypto/sha1crypto/sha256crypto/sha512等包来生成字符串的SHA哈希。下面是一个使用SHA256生成哈希的示例:

package main

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

func main() {
	str := "Hello, world!"

	// 创建一个SHA256哈希对象
	hash := sha256.New()

	// 将字符串转换为字节数组并计算哈希值
	hash.Write([]byte(str))
	hashValue := hash.Sum(nil)

	// 将哈希值转换为十六进制字符串
	hashString := hex.EncodeToString(hashValue)

	fmt.Println("SHA256 哈希值:", hashString)
}

输出结果:

SHA256 哈希值: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9

上述示例中,我们使用crypto/sha256包创建了一个SHA256哈希对象hash。然后,我们将要哈希的字符串str转换为字节数组并使用hash.Write方法计算哈希值。最后,我们将哈希值转换为十六进制字符串表示,以便进行输出或存储。

类似地,你可以使用crypto/sha1crypto/sha512包来生成SHA1或SHA512哈希。只需将示例中的sha256替换为相应的包名即可。