github.com/enetx/g@v1.0.80/string_hash.go (about)

     1  package g
     2  
     3  import (
     4  	"crypto/md5"
     5  	"crypto/sha1"
     6  	"crypto/sha256"
     7  	"crypto/sha512"
     8  	"encoding/hex"
     9  	"hash"
    10  )
    11  
    12  // A struct that wraps an String for hashing.
    13  type shash struct{ str String }
    14  
    15  // Hash returns a shash struct wrapping the given String.
    16  func (s String) Hash() shash { return shash{s} }
    17  
    18  // MD5 computes the MD5 hash of the wrapped String and returns the hash as an String.
    19  func (sh shash) MD5() String { return stringHasher(md5.New(), sh.str) }
    20  
    21  // SHA1 computes the SHA1 hash of the wrapped String and returns the hash as an String.
    22  func (sh shash) SHA1() String { return stringHasher(sha1.New(), sh.str) }
    23  
    24  // SHA256 computes the SHA256 hash of the wrapped String and returns the hash as an String.
    25  func (sh shash) SHA256() String { return stringHasher(sha256.New(), sh.str) }
    26  
    27  // SHA512 computes the SHA512 hash of the wrapped String and returns the hash as an String.
    28  func (sh shash) SHA512() String { return stringHasher(sha512.New(), sh.str) }
    29  
    30  // stringHasher a helper function that computes the hash of the given String using the specified
    31  // hash.Hash algorithm and returns the hash as an String.
    32  func stringHasher(algorithm hash.Hash, hstr String) String {
    33  	_, _ = algorithm.Write(hstr.ToBytes())
    34  	return String(hex.EncodeToString(algorithm.Sum(nil)))
    35  }