I am writing a data structure that needs to hash an arbitrary object. The following function seems to fail if I give an int
is the parameter.
func Hash( obj interface{} ) []byte {
digest := md5.New()
if err := binary.Write(digest, binary.LittleEndian, obj); err != nil {
panic(err)
}
return digest.Sum()
}
Calling this on an int
results in:
panic: binary.Write: invalid type int
What is the right way to do this?
Some common hashing algorithms include MD5, SHA-1, SHA-2, NTLM, and LANMAN. MD5: This is the fifth version of the Message Digest algorithm. MD5 creates 128-bit outputs. MD5 was a very commonly used hashing algorithm.
MD5 was most popular and widely used hash function for quite some years. The MD family comprises of hash functions MD2, MD4, MD5 and MD6. It was adopted as Internet Standard RFC 1321. It is a 128-bit hash function.
Python hash() function is a built-in function and returns the hash value of an object if it has one. The hash value is an integer which is used to quickly compare dictionary keys while looking at a dictionary.
Hashing uses functions or algorithms to map object data to a representative integer value. A hash can then be used to narrow down searches when locating these items on that object data map. For example, in hash tables, developers store data -- perhaps a customer record -- in the form of key and value pairs.
I found that a good way to do this is to serialize the object using the "gob" package, along the following lines:
var (
digest = md5.New()
encoder = gob.NewEncoder(digest)
)
func Hash(obj interface{}) []byte {
digest.Reset()
if err := encoder.Encode(obj); err != nil {
panic(err)
}
return digest.Sum()
}
Edit: This does not work as intended (see below).
binary.Write writes "a fixed-size value or a pointer to a fixed-size value." Type int is not a fixed size value; int is "either 32 or 64 bits." Use a fixed-size value like int32.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With