6
Golang实现sha256或sha512加密
source link: https://studygolang.com/articles/35818?fr=sidebar
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
代码实现sha-256加密算法
sha-256.go
package tools
import (
"crypto/sha256"
"encoding/hex"
)
//SHA256生成哈希值
func GetSHA256HashCode(stringMessage string) string {
message := []byte(stringMessage) //字符串转化字节数组
//创建一个基于SHA256算法的hash.Hash接口的对象
hash := sha256.New() //sha-256加密
//hash := sha512.New() //SHA-512加密
//输入数据
hash.Write(message)
//计算哈希值
bytes := hash.Sum(nil)
//将字符串编码为16进制格式,返回字符串
hashCode := hex.EncodeToString(bytes)
//返回哈希值
return hashCode
}
用main方法调用sha-256
main.go
package main
import (
"GraduationProject/tools"
"fmt"
)
func main() {
txt := "Hello World!"
code := tools.GetSHA256HashCode(txt)
fmt.Println("\n加密前的明文\n", txt, "\nSHA-256加密后的密文:\n", code)
}
加密前的明文
Hello World!
SHA-256加密后的密文:
7f83b1657ff1fc53b92dc18148a1d65dfc2d4b1fa3d677284addd200126d9069
代码实现sha-512
将sha-256.go文件的第15行加上注释,16行去掉注释
package tools
import (
"crypto/sha256"
"encoding/hex"
)
//SHA256生成哈希值
func GetSHA256HashCode(stringMessage string) string {
message := []byte(stringMessage) //字符串转化字节数组
//创建一个基于SHA256算法的hash.Hash接口的对象
//hash := sha256.New() //sha-256加密
hash := sha512.New() //SHA-512加密
//输入数据
hash.Write(message)
//计算哈希值
bytes := hash.Sum(nil)
//将字符串编码为16进制格式,返回字符串
hashCode := hex.EncodeToString(bytes)
//返回哈希值
return hashCode
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK