gitee.com/lh-her-team/common@v1.5.1/crypto/hash/hash.go (about)

     1  package hash
     2  
     3  import (
     4  	"crypto/sha256"
     5  	"fmt"
     6  	"hash"
     7  
     8  	"gitee.com/lh-her-team/common/crypto"
     9  	"github.com/tjfoc/gmsm/sm3"
    10  	"golang.org/x/crypto/sha3"
    11  )
    12  
    13  type Hash struct {
    14  	hashType crypto.HashType
    15  }
    16  
    17  func (h *Hash) Get(data []byte) ([]byte, error) {
    18  	var hf func() hash.Hash
    19  	switch h.hashType {
    20  	case crypto.HASH_TYPE_SM3:
    21  		hf = sm3.New
    22  	case crypto.HASH_TYPE_SHA256:
    23  		hf = sha256.New
    24  	case crypto.HASH_TYPE_SHA3_256:
    25  		hf = sha3.New256
    26  	default:
    27  		return nil, fmt.Errorf("unknown hash algorithm")
    28  	}
    29  	f := hf()
    30  	f.Write(data)
    31  	return f.Sum(nil), nil
    32  }
    33  
    34  func Get(hashType crypto.HashType, data []byte) ([]byte, error) {
    35  	h := Hash{
    36  		hashType: hashType,
    37  	}
    38  	return h.Get(data)
    39  }
    40  
    41  func GetByStrType(hashType string, data []byte) ([]byte, error) {
    42  	h := Hash{
    43  		hashType: crypto.HashAlgoMap[hashType],
    44  	}
    45  	return h.Get(data)
    46  }
    47  
    48  func GetHashAlgorithm(hashType crypto.HashType) (hash.Hash, error) {
    49  	switch hashType {
    50  	case crypto.HASH_TYPE_SM3:
    51  		return sm3.New(), nil
    52  	case crypto.HASH_TYPE_SHA256:
    53  		return sha256.New(), nil
    54  	case crypto.HASH_TYPE_SHA3_256:
    55  		return sha3.New256(), nil
    56  	default:
    57  		return nil, fmt.Errorf("unknown hash algorithm")
    58  	}
    59  }