github.com/clubpay/ronykit/kit@v0.14.4-0.20240515065620-d0dace45cbc7/utils/hash.go (about)

     1  package utils
     2  
     3  import (
     4  	"crypto/sha256"
     5  	"crypto/sha512"
     6  	"hash"
     7  	"sync"
     8  )
     9  
    10  /*
    11     Creation Time: 2019 - Oct - 03
    12     Created by:  (ehsan)
    13     Maintainers:
    14        1.  Ehsan N. Moosa (E2)
    15     Auditor: Ehsan N. Moosa (E2)
    16  */
    17  
    18  var poolSha512 = sync.Pool{
    19  	New: func() any {
    20  		return sha512.New()
    21  	},
    22  }
    23  
    24  // Sha512 appends a 64bytes array which is sha512(in) to out and returns out
    25  func Sha512(in, out []byte) ([]byte, error) {
    26  	h := poolSha512.Get().(hash.Hash) //nolint:forcetypeassert
    27  	if _, err := h.Write(in); err != nil {
    28  		h.Reset()
    29  		poolSha512.Put(h)
    30  
    31  		return out, err
    32  	}
    33  	out = h.Sum(out)
    34  	h.Reset()
    35  	poolSha512.Put(h)
    36  
    37  	return out, nil
    38  }
    39  
    40  // MustSha512 is Sha512 but it panics if any error happens
    41  func MustSha512(in, out []byte) []byte {
    42  	var err error
    43  	out, err = Sha512(in, out)
    44  	if err != nil {
    45  		panic(err)
    46  	}
    47  
    48  	return out
    49  }
    50  
    51  var poolSha256 = sync.Pool{
    52  	New: func() any {
    53  		return sha256.New()
    54  	},
    55  }
    56  
    57  // Sha256 appends a 32bytes array which is sha256(in) to out
    58  func Sha256(in, out []byte) ([]byte, error) {
    59  	h := poolSha256.Get().(hash.Hash) //nolint:forcetypeassert
    60  	if _, err := h.Write(in); err != nil {
    61  		h.Reset()
    62  		poolSha256.Put(h)
    63  
    64  		return out, err
    65  	}
    66  	out = h.Sum(out)
    67  	h.Reset()
    68  	poolSha256.Put(h)
    69  
    70  	return out, nil
    71  }
    72  
    73  func MustSha256(in, out []byte) []byte {
    74  	var err error
    75  	out, err = Sha256(in, out)
    76  	if err != nil {
    77  		panic(err)
    78  	}
    79  
    80  	return out
    81  }