github.com/quantosnetwork/Quantos@v0.0.0-20220306172517-e20b28c5a29a/crypto/hash.go (about) 1 package crypto 2 3 import ( 4 "crypto" 5 "encoding/binary" 6 "hash" 7 "math/big" 8 ) 9 10 type Hash hash.Hash 11 12 type Hex struct { 13 bigN *big.Int 14 bit uint 15 words []big.Word 16 buf []byte 17 } 18 19 func (h Hex) New() *Hex { 20 21 buf := make([]byte,40) 22 for i := range buf { 23 buf[i] = 0 24 } 25 hex := &Hex{} 26 hex.buf = buf[:] 27 28 hex.bigN = new(big.Int) 29 hex.bit = hex.bigN.Bit(0) 30 hex.words = hex.bigN.Bits() 31 return hex 32 33 } 34 35 func (h *Hex) ToString() string { 36 return string(h.ToBytes()) 37 } 38 39 func (h *Hex) ToBytes() []byte { 40 return h.buf 41 } 42 43 func HexFromUint64(i uint64) *Hex { 44 h := new(Hex) 45 hex := h.New() 46 b := make([]byte,40) 47 binary.LittleEndian.PutUint64(b, i) 48 copy(hex.buf, b) 49 hex.bigN.SetBytes(hex.buf) 50 return hex 51 } 52 53 func HexFromBytes(b []byte) *Hex { 54 h := new(Hex) 55 hex := h.New() 56 b2 := make([]byte,40) 57 copy(b2, b) 58 copy(hex.buf, b2) 59 hex.bigN.SetBytes(hex.buf) 60 return hex 61 } 62 63 var hashFn = crypto.SHA3_256 64 65 func (h *Hex) Hash() []byte { 66 67 hasher := hashFn.New() 68 hasher.Write(h.buf) 69 hasher.Write(h.bigN.Bytes()) 70 return hasher.Sum(nil) 71 72 } 73 74 func HashFromHex(h *Hex, content []byte) []byte { 75 return HexFromBytes(content).Hash() 76 } 77 78