diff --git a/hash/hash.go b/hash/hash.go index d928aae..1c1c4d4 100644 --- a/hash/hash.go +++ b/hash/hash.go @@ -2,13 +2,18 @@ package hash import ( "crypto/md5" + "crypto/sha256" "fmt" - "hash/adler32" "io" "math/rand" + "strings" "time" ) +func init() { + rand.Seed(time.Now().UnixNano()) +} + func Rand64() int64 { return rand.Int63() } @@ -31,7 +36,7 @@ func GetMd5FromBytes(blob []byte) (sum []byte) { /* get a small, decently unique hash */ func GetSmallHash() (small_hash string) { - h := adler32.New() - io.WriteString(h, fmt.Sprintf("%d", time.Now().Unix())) - return fmt.Sprintf("%X", h.Sum(nil)) + h := sha256.New() + io.WriteString(h, fmt.Sprintf("%d%d", time.Now().UnixNano(), Rand64())) + return strings.ToLower(fmt.Sprintf("%X", h.Sum(nil)[0:9])) } diff --git a/hash/hash_test.go b/hash/hash_test.go index e5ba05e..dcf723d 100644 --- a/hash/hash_test.go +++ b/hash/hash_test.go @@ -3,6 +3,7 @@ package hash import ( "fmt" "testing" + "sort" ) func TestRand64(t *testing.T) { @@ -36,4 +37,15 @@ func TestMd5String(t *testing.T) { } func TestHash(t *testing.T) { + seen := []string{} + for i := 0; i < 10000; i++ { + h := GetSmallHash() + j := sort.SearchStrings(seen, h) + if len(seen) != 0 && j < len(seen) && h == seen[j] { + t.Errorf("there is a non-unique hash after %d attempts [%s and %s]", i, h, seen[j]) + } else { + seen = append(seen, h) + sort.Strings(seen) + } + } }