golang[33]-blockchain-hash

哈希函数有三个特点:

  • 输入无限的字符会输出给我们固定长度的字符(即便是图书馆里面所有的数据)

  • 输入的函数的微小变化最后都会带来哈希函数返回值的巨大变化。

  • 哈希函数的特点是不能根据哈希函数的返回值倒推出我们输入的数据是什么。同样的,我们在计算哈希函数之前,也不能够判断出数据回输出什么样的哈希值。

用途

数字指纹
数字签名
数字防篡改

go实现hash

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
func main(){

//第一种方式
sum:= sha256.Sum256([]byte("jonson love olaya"))
fmt.Printf("%X",sum)

 //第2种方式
 h:=sha256.New()
 h.Write([]byte("jonson love olaya"))
 fmt.Printf("%X",h.Sum(nil))
}

//第3种方式:处理文件
h:=sha256.New()
 f,err := os.Open("hash.test")

 if err !=nil{

 fmt.Printf("error")
 }
 defer f.Close()

if _,err := io.Copy(h,f);err !=nil{
fmt.Printf("error")
}

fmt.Printf("%X",h.Sum(nil))

参考资料

https://golang.org/pkg/crypto/sha256/#example_Sum256

image.png

猜你喜欢

转载自blog.51cto.com/13784902/2329700
33