Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper method to hash an arbitrary object

Tags:

hash

go

md5

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?

like image 854
Jake Avatar asked Apr 22 '11 23:04

Jake


People also ask

What are the types of hashing methods?

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.

Which is the standard hash function method?

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.

How does Python hash an object?

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.

What is a hash of an object?

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.


2 Answers

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).

like image 51
Jake Avatar answered Sep 22 '22 03:09

Jake


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.

like image 41
peterSO Avatar answered Sep 25 '22 03:09

peterSO