go標准庫的學習-hash


參考:https://studygolang.com/pkgdoc

導入方式:

import "hash"

hash包提供hash函數的接口。

 

type Hash

type Hash interface {
    // 通過嵌入的匿名io.Writer接口的Write方法向hash中添加更多數據,永遠不返回錯誤
    io.Writer
    // 返回添加b到當前的hash值后的新切片,不會改變底層的hash狀態
    Sum(b []byte) []byte
    // 重設hash為無數據輸入的狀態
    Reset()
    // 返回Sum會返回的切片的長度
    Size() int
    // 返回hash底層的塊大小;Write方法可以接受任何大小的數據,
    // 但提供的數據是塊大小的倍數時效率更高
    BlockSize() int
}

Hash是一個被所有hash函數實現的公共接口。

sha256包中有一個方法:

func New

func New() hash.Hash

返回一個新的使用SHA256校驗算法的hash.Hash接口。

舉例:

package main

import (
    "fmt"
    "crypto/sha256"
    "log"
    "encoding"
    "bytes"
)

func main() {
    const (
        input1 = "The tunneling gopher digs downwards, "
        input2 = "unaware of what he will find."
    )

    first := sha256.New()
    first.Write([]byte(input1))

    marshaler, ok := first.(encoding.BinaryMarshaler) //類型斷言
    if !ok {
        log.Fatal("first does not implement encoding.BinaryMarshaler")
    }
    state, err := marshaler.MarshalBinary() //將其編碼成二進制形式
    if err != nil {
        log.Fatal("unable to marshal hash:", err)
    }

    second := sha256.New()

    unmarshaler, ok := second.(encoding.BinaryUnmarshaler)
    if !ok {
        log.Fatal("second does not implement encoding.BinaryUnmarshaler")
    }
    if err := unmarshaler.UnmarshalBinary(state); err != nil {//將上面生成的二進制形式的state解碼成input1的值,並寫到unmarshaler中,這樣second中也有input1了
        log.Fatal("unable to unmarshal hash:", err)
    }

    first.Write([]byte(input2))
    second.Write([]byte(input2))

    fmt.Printf("%x\n", first.Sum(nil))//57d51a066f3a39942649cd9a76c77e97ceab246756ff3888659e6aa5a07f4a52
    fmt.Println(bytes.Equal(first.Sum(nil), second.Sum(nil))) //true
}

 

type Hash32

type Hash32 interface {
    Hash
    Sum32() uint32
}

Hash32是一個被所有32位hash函數實現的公共接口。

type Hash64

type Hash64 interface {
    Hash
    Sum64() uint64
}

Hash64是一個被所有64位hash函數實現的公共接口。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM