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函数实现的公共接口。

posted @ 2019-02-28 23:02  慢行厚积  阅读(4859)  评论(0编辑  收藏  举报