版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/The_Reader/article/details/84396340
MD5消息摘要算法
MD5消息摘要算法(英语:MD5 Message-Digest Algorithm),一种被广泛使用的密码散列函数,可以产生出一个128位(16字节)的散列值(hash value),用于确保信息传输完整一致。
Go语言实现方式一:
package main
import (
"fmt"
"crypto/md5"
"encoding/hex"
)
func main() {
var a = []byte("i am the reader")
hash := md5.New()
_, err := hash.Write(a)
if err!=nil{
fmt.Println("hash.Write faild")
}
hashed := hash.Sum(nil)
fmt.Println("a 的md5单向散列为:",hex.EncodeToString(hashed[:]))
hash.Reset()
_, err= hash.Write([]byte("hello world"))
if err!=nil{
fmt.Println("hash.Write faild")
}
hashed = hash.Sum(nil)
fmt.Println("a 的md5单向散列为:",hex.EncodeToString(hashed[:]))
}
Go语言实现方式二:
package main
import (
"fmt"
"crypto/md5"
"encoding/hex"
)
func main() {
hashed := md5.Sum([]byte("i am the reader"))
fmt.Println("a 的md5单向散列为:",hex.EncodeToString(hashed[:]))
}
其两者区别为:用过一次之后可以reset以下,然后可以重复使用,而方式二不可以。
方式一代码比较多,而方式二代码就很少。
SHA256与224
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
)
func main1() {
hash := sha256.New()
hash.Write([]byte("i am the reader"))
sum := hash.Sum(nil)
fmt.Println(sum)
fmt.Println(len(sum) * 8)
s := hex.EncodeToString(sum)
fmt.Println(s)
fmt.Println(len(s) * 8)
}
//结果为:
//[84 251 192 78 28 190 247 247 180 155 4 177 16 2 249 160 236 10 217 96 213 242 65 37 24 13 212 58 232 98 129 229]
//256
//54fbc04e1cbef7f7b49b04b11002f9a0ec0ad960d5f24125180dd43ae86281e5
//512
func main2() {
s1 := sha256.Sum256([]byte("i am the reader"))
fmt.Println(len(s1) * 8)
fmt.Println(s1)
s := hex.EncodeToString(s1[:])
fmt.Println(s)
fmt.Println(len(s) * 8)
}
//结果为:
//256
//[84 251 192 78 28 190 247 247 180 155 4 177 16 2 249 160 236 10 217 96 213 242 65 37 24 13 212 58 232 98 129 229]
//54fbc04e1cbef7f7b49b04b11002f9a0ec0ad960d5f24125180dd43ae86281e5
//512
func main3() {
hash := sha256.New224()
hash.Write([]byte("i am the reader"))
sum := hash.Sum(nil)
fmt.Println(sum)
fmt.Println(len(sum) * 8)
s := hex.EncodeToString(sum)
fmt.Println(s)
fmt.Println(len(s) * 8)
}
//结果为:
//[249 203 73 14 85 217 122 47 50 255 162 90 1 24 181 52 4 26 201 18 73 182 159 29 205 205 201 208]
//224
//f9cb490e55d97a2f32ffa25a0118b534041ac91249b69f1dcdcdc9d0
//448