github.com/0chain/gosdk@v1.17.11/core/encryption/hash.go (about) 1 // Provides the data structures and methods used in encryption. 2 package encryption 3 4 import ( 5 "crypto/sha1" 6 "encoding/hex" 7 8 "github.com/minio/sha256-simd" 9 "golang.org/x/crypto/sha3" 10 ) 11 12 const HASH_LENGTH = 32 13 14 // HashBytes hash bytes 15 type HashBytes [HASH_LENGTH]byte 16 17 // Hash hash the given data and return the hash as hex string 18 // - data is the data to hash 19 func Hash(data interface{}) string { 20 return hex.EncodeToString(RawHash(data)) 21 } 22 23 // RawHash Logic to hash the text and return the hash bytes 24 // - data is the data to hash 25 func RawHash(data interface{}) []byte { 26 var databuf []byte 27 switch dataImpl := data.(type) { 28 case []byte: 29 databuf = dataImpl 30 case HashBytes: 31 databuf = dataImpl[:] 32 case string: 33 databuf = []byte(dataImpl) 34 default: 35 panic("unknown type") 36 } 37 hash := sha3.New256() 38 hash.Write(databuf) 39 var buf []byte 40 return hash.Sum(buf) 41 } 42 43 // ShaHash hash the given data and return the hash as hex string 44 // - data is the data to hash 45 func ShaHash(data interface{}) []byte { 46 var databuf []byte 47 switch dataImpl := data.(type) { 48 case []byte: 49 databuf = dataImpl 50 case HashBytes: 51 databuf = dataImpl[:] 52 case string: 53 databuf = []byte(dataImpl) 54 default: 55 panic("unknown type") 56 } 57 hash := sha256.New() 58 _, _ = hash.Write(databuf) 59 return hash.Sum(nil) 60 } 61 62 // FastHash - sha1 hash the given data and return the hash as hex string 63 // - data is the data to hash 64 func FastHash(data interface{}) string { 65 return hex.EncodeToString(RawFastHash(data)) 66 } 67 68 // RawFastHash - Logic to sha1 hash the text and return the hash bytes 69 // - data is the data to hash 70 func RawFastHash(data interface{}) []byte { 71 var databuf []byte 72 switch dataImpl := data.(type) { 73 case []byte: 74 databuf = dataImpl 75 case HashBytes: 76 databuf = dataImpl[:] 77 case string: 78 databuf = []byte(dataImpl) 79 default: 80 panic("unknown type") 81 } 82 hash := sha1.New() 83 hash.Write(databuf) 84 var buf []byte 85 return hash.Sum(buf) 86 }