golang单向散列函数
生活随笔
收集整理的這篇文章主要介紹了
golang单向散列函数
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
概念
稱謂: 單向散列函數(shù), 哈希函數(shù), 雜湊函數(shù), 消息摘要函數(shù)
接收的輸入: 原像
輸出: 散列值, 哈希值, 指紋, 摘要
單向散列函數(shù)特性
將任意長度的數(shù)據(jù)轉(zhuǎn)換成固定長度的數(shù)據(jù)
很強(qiáng)的抗碰撞性
不可逆
MD4/MD5
- 不安全
- 散列值長度: 128bit == 16byte
sha1
- 不安全
- 散列值長度: 160bit == 20byte
sha2 - 安全
- sha224
- 散列值長度: 224bit == 28byte
- sha256
- 散列值長度: 256== 32byte
- sha384
- 散列值長度: 384bit == 48byte
- sha512
- 散列值長度: 512bit == 64byte
go中使用單向散列函數(shù)
// 第一種方式, 直接調(diào)用sum// 適用于數(shù)據(jù)量比較小的情況func Sum(data []byte) [Size]byte// 第二種方式// 1. 創(chuàng)建哈希接口對(duì)象func New() hash.Hashtype Hash interface {// 通過嵌入的匿名io.Writer接口的Write方法向hash中添加更多數(shù)據(jù),永遠(yuǎn)不返回錯(cuò)誤io.Writer// 返回添加b到當(dāng)前的hash值后的新切片,不會(huì)改變底層的hash狀態(tài)Sum(b []byte) []byte// 重設(shè)hash為無數(shù)據(jù)輸入的狀態(tài)Reset()// 返回Sum會(huì)返回的切片的長度Size() int// 返回hash底層的塊大小;Write方法可以接受任何大小的數(shù)據(jù),// 但提供的數(shù)據(jù)是塊大小的倍數(shù)時(shí)效率更高BlockSize() int}type Writer interface {Write(p []byte) (n int, err error)}// 2. 往創(chuàng)建出的哈希對(duì)象中添加數(shù)據(jù)hash.Hash.Write([]byte("添加的數(shù)據(jù)..."))hash.Hash.Write([]byte("添加的數(shù)據(jù)..."))hash.Hash.Write([]byte("添加的數(shù)據(jù)..."))hash.Hash.Write([]byte("添加的數(shù)據(jù)..."))// 3. 計(jì)算結(jié)果, md5就是散列值md5 := hash.Sum(nil);// 散列值一般是一個(gè)二進(jìn)制的字符串, 有些字符不可見, 需要格式化// 格式化為16進(jìn)制的數(shù)字串 - 0-9, a-ffunc EncodeToString(src []byte) string// 數(shù)據(jù)轉(zhuǎn)換完成之后, 長度是原來的2倍sha256
//驗(yàn)證 myHash()// 使用sha256 func myHash() {// sha256.Sum256([]byte("hello, go"))// 1. 創(chuàng)建哈希接口對(duì)象myHash := sha256.New()// 2. 添加數(shù)據(jù)src := []byte("123 123...")myHash.Write(src)myHash.Write(src)myHash.Write(src)// 3. 計(jì)算結(jié)果res := myHash.Sum(nil)// 4. 格式化為16進(jìn)制形式myStr := hex.EncodeToString(res)fmt.Printf("%s\n", myStr) }總結(jié)
以上是生活随笔為你收集整理的golang单向散列函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: golang非对称加密
- 下一篇: golang中的消息认证