github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/core/access_contoller/crypto/hash/hash.go (about)

     1  /*
     2  Copyright (C) BABEC. All rights reserved.
     3  Copyright (C) THL A29 Limited, a Tencent company. All rights reserved.
     4  
     5  SPDX-License-Identifier: Apache-2.0
     6  */
     7  
     8  package hash
     9  
    10  import (
    11  	"crypto/sha256"
    12  	"fmt"
    13  	"github.com/bigzoro/my_simplechain/core/access_contoller/crypto"
    14  	"hash"
    15  
    16  	"github.com/tjfoc/gmsm/sm3"
    17  	"golang.org/x/crypto/sha3"
    18  )
    19  
    20  type Hash struct {
    21  	hashType crypto.HashType
    22  }
    23  
    24  func (h *Hash) Get(data []byte) ([]byte, error) {
    25  	var hf func() hash.Hash
    26  
    27  	switch h.hashType {
    28  	case crypto.HASH_TYPE_SM3:
    29  		hf = sm3.New
    30  	case crypto.HASH_TYPE_SHA256:
    31  		hf = sha256.New
    32  	case crypto.HASH_TYPE_SHA3_256:
    33  		hf = sha3.New256
    34  	default:
    35  		return nil, fmt.Errorf("unknown hash algorithm")
    36  	}
    37  
    38  	f := hf()
    39  
    40  	f.Write(data)
    41  	return f.Sum(nil), nil
    42  }
    43  
    44  func Get(hashType crypto.HashType, data []byte) ([]byte, error) {
    45  	h := Hash{
    46  		hashType: hashType,
    47  	}
    48  	return h.Get(data)
    49  }
    50  
    51  func GetByStrType(hashType string, data []byte) ([]byte, error) {
    52  	h := Hash{
    53  		hashType: crypto.HashAlgoMap[hashType],
    54  	}
    55  	return h.Get(data)
    56  }
    57  
    58  func GetHashAlgorithm(hashType crypto.HashType) (hash.Hash, error) {
    59  	switch hashType {
    60  	case crypto.HASH_TYPE_SM3:
    61  		return sm3.New(), nil
    62  	case crypto.HASH_TYPE_SHA256:
    63  		return sha256.New(), nil
    64  	case crypto.HASH_TYPE_SHA3_256:
    65  		return sha3.New256(), nil
    66  	default:
    67  		return nil, fmt.Errorf("unknown hash algorithm")
    68  	}
    69  }