github.com/hoffie/larasync@v0.0.0-20151025221940-0384d2bddcef/helpers/crypto/hasher.go (about) 1 package crypto 2 3 import ( 4 "crypto/hmac" 5 "crypto/sha512" 6 "encoding/hex" 7 ) 8 9 const ( 10 // HashingKeySize is the amount of bytes used to initialize 11 // the Hasher for Hashing purposes. 12 HashingKeySize = 32 13 ) 14 15 // Hasher is a helper which can be used to Hash bytes of data 16 // with a given key as initialization vector. 17 type Hasher struct { 18 hashingKey [HashingKeySize]byte 19 } 20 21 // NewHasher is used to generate a new Hasher with the passed 22 // key as initialization vector. 23 func NewHasher(hashingKey [HashingKeySize]byte) *Hasher { 24 return &Hasher{ 25 hashingKey: hashingKey, 26 } 27 } 28 29 // Hash hashes the given data and returns the result as bytes. 30 func (h *Hasher) Hash(chunk []byte) []byte { 31 key := h.hashingKey 32 hasher := hmac.New(sha512.New, key[:]) 33 hasher.Write(chunk) 34 hash := hasher.Sum(nil) 35 return hash 36 } 37 38 // StringHash hashes the given data and returns the result as a 39 // hex encoded byte string. 40 func (h *Hasher) StringHash(chunk []byte) string { 41 return hex.EncodeToString(h.Hash(chunk)) 42 }