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

     1  package common
     2  
     3  import (
     4  	"crypto"
     5  
     6  	"github.com/sixexorg/magnetic-ring/errors"
     7  
     8  	_ "golang.org/x/crypto/ripemd160"
     9  	_ "golang.org/x/crypto/sha3"
    10  )
    11  
    12  func Sha256(msg ...[]byte) []byte {
    13  	sha3256 := crypto.SHA3_256.New()
    14  	for _, bytes := range msg {
    15  		sha3256.Write(bytes)
    16  	}
    17  	return sha3256.Sum(nil)
    18  }
    19  
    20  func CalcHash(buf []byte) Hash {
    21  	result := Hash{}
    22  
    23  	sum := Sha256(buf)
    24  
    25  	copy(result[:],sum)
    26  	return result
    27  }
    28  
    29  func Ripemd160(msg []byte) []byte {
    30  	ripemd160 := crypto.RIPEMD160.New()
    31  	ripemd160.Write(msg)
    32  	return ripemd160.Sum(nil)
    33  }
    34  
    35  func Sha256Ripemd160(msg []byte) []byte {
    36  	return Ripemd160(Sha256(msg))
    37  }
    38  
    39  func ZeroBytes(bytes []byte) {
    40  	for i := range bytes {
    41  		bytes[i] = 0
    42  	}
    43  }
    44  func ParseHashFromBytes(bytes []byte) (Hash, error) {
    45  	if len(bytes) != HashLength {
    46  		return Hash{}, errors.ERR_HASH_PARSE
    47  	}
    48  	var hash Hash
    49  	copy(hash[:], bytes)
    50  	return hash, nil
    51  }