加密算法_单向散列

和对称加密,非对称加密相比最大区别就在于,单向散列算法的最大特点就在于,

不能从密文回到明文,是一个不可逆的状态

为什么会这样?

是因为单向散列是对明文做了信息的提取处理,

加密的仅仅是整个明文的摘要.

常见的散列算法:SHA,MD5,RIPEMD160

我们不深究具体实现方法

在go中如何调用:

调用SHA256

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func Sha256_test(a string){
sum:=sha256.Sum256([]byte(a))
fmt.Printf("%x",sum)
h:=sha256.New()
h.Write([]byte("hello world"))
fmt.Printf("\nSHA256:%x",h.Sum(nil))
}
//如何加密文件中的信息,如下:
//加密文件test.txt,文件中写了"hello world"
func MyIOSsha256(){
f,_:=os.Open("test.txt")
defer f.Close()
h:=sha256.New() //加密算法 实体化
io.Copy(h,f)
fmt.Printf("\nSHA256_NO2%x",h.Sum(nil))
}

输入结果:

SHA256: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9

SHA256_NO2: b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9

调用MD5

1
2
3
4
5
6
7
8
9
func Mymd5(){
data:=[]byte("hello world")
s:=fmt.Sprintf("\n%x" ,md5.Sum(data))
fmt.Println(s)
h:=md5.New()
h.Write(data)
s=hex.EncodeToString(h.Sum(nil))
fmt.Println(s)
}

输出结果:

MD5: 5eb63bbbe01eeed093cb22bb8f5acdc3

调用RIPEMD-160

1
2
3
4
5
6
func MyRipemd160(){
hasher1:=ripemd160.New()
hasher1.Write([]byte("hello world"))
hashString:=fmt.Sprintf("%x",hasher1.Sum(nil))
fmt.Println("RIPEMD:",hashString)
}

输出结果:

RIPEMD: 98c615784ccb5fe5936fbc0cbe9dfdb408d92f0f