

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
-
89
For the Minio object storage server, SHA256 hash calculations are an important part of the processing pipeline for payloads. As users issue PUT commands and upload objects, the integrity of the…
-
27
Join GitHub today GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.
-
16
How many bytes (= ASCII characters) of Ruby code does it take to generate a SHA 256 hash sum of STDIN?
-
12
Implementation of SHA512-crypt vs MD5-crypt If you have a new installation, you’re probably using SHA512-based passwords instead of the older MD5-based passwords described...
-
6
实例来源网络,语言版本可能略有差异,请验证后使用。 Javascript HMAC SHA256 <script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/hmac-sha256.js"></script>...
-
4
V2EX › 程序员 试问 sha256 后能否公开数据😂 d5 · 7 小时 43 分钟前 · 1040 次点击
-
2
Message block - 512 Bits10000000 00000000 00000000 00000000►00000000 00000000 00000000 00000000►00000000 00000000 00000000 00000000►00000000 00000000 00000000 00000000►00000000...
-
4
The SHA-256 Project This project was originally assigned in NYU Tandon's CS-GY 6903 Applied Cryptography course, Fall 2021. Here's the original course repo...
-
7
SHA256 and other hashing functions in SAS 26 ...
-
6
Saurabh Kumar Jha February 16, 2023 1 minute read...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK