github.com/ronaksoft/rony@v0.16.26-0.20230807065236-1743dbfe6959/tools/hash.go (about)

     1  package tools
     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     Copyright Ronak Software Group 2020
    17  */
    18  
    19  var poolSha512 = sync.Pool{
    20  	New: func() interface{} {
    21  		return sha512.New()
    22  	},
    23  }
    24  
    25  // Sha512 appends a 64bytes array which is sha512(in) to out
    26  func Sha512(in, out []byte) error {
    27  	h := poolSha512.Get().(hash.Hash)
    28  	if _, err := h.Write(in); err != nil {
    29  		h.Reset()
    30  		poolSha512.Put(h)
    31  
    32  		return err
    33  	}
    34  	h.Sum(out)
    35  	h.Reset()
    36  	poolSha512.Put(h)
    37  
    38  	return nil
    39  }
    40  
    41  func MustSha512(in, out []byte) {
    42  	if err := Sha512(in, out); err != nil {
    43  		panic(err)
    44  	}
    45  }
    46  
    47  var poolSha256 = sync.Pool{
    48  	New: func() interface{} {
    49  		return sha256.New()
    50  	},
    51  }
    52  
    53  // Sha256 appends a 32bytes array which is sha256(in) to out
    54  func Sha256(in, out []byte) error {
    55  	h := poolSha256.Get().(hash.Hash)
    56  	if _, err := h.Write(in); err != nil {
    57  		h.Reset()
    58  		poolSha256.Put(h)
    59  
    60  		return err
    61  	}
    62  	h.Sum(out)
    63  	h.Reset()
    64  	poolSha256.Put(h)
    65  
    66  	return nil
    67  }
    68  
    69  func MustSha256(in, out []byte) {
    70  	if err := Sha256(in, out); err != nil {
    71  		panic(err)
    72  	}
    73  }