github.com/sixexorg/magnetic-ring@v0.0.0-20191119090307-31705a21e419/p2pserver/common/checksum.go (about)

     1  package common
     2  
     3  import (
     4  	"crypto/sha256"
     5  	"hash"
     6  )
     7  
     8  // checksum implement hash.Hash interface and io.Writer
     9  type checksum struct {
    10  	hash.Hash
    11  }
    12  
    13  func (self *checksum) Size() int {
    14  	return CHECKSUM_LEN
    15  }
    16  
    17  func (self *checksum) Sum(b []byte) []byte {
    18  	temp := self.Hash.Sum(nil)
    19  	h := sha256.Sum256(temp)
    20  
    21  	return append(b, h[:CHECKSUM_LEN]...)
    22  }
    23  
    24  func NewChecksum() hash.Hash {
    25  	return &checksum{sha256.New()}
    26  }
    27  
    28  func Checksum(data []byte) [CHECKSUM_LEN]byte {
    29  	var checksum [CHECKSUM_LEN]byte
    30  	t := sha256.Sum256(data)
    31  	s := sha256.Sum256(t[:])
    32  
    33  	copy(checksum[:], s[:])
    34  
    35  	return checksum
    36  }