adler32 is not nearly unique. switching to sh256 and adding tests

This commit is contained in:
Vincent Batts 2013-11-05 11:34:16 -05:00
parent 2a87e1f8ca
commit 629bafaa7f
2 changed files with 21 additions and 4 deletions

View File

@ -2,13 +2,18 @@ package hash
import ( import (
"crypto/md5" "crypto/md5"
"crypto/sha256"
"fmt" "fmt"
"hash/adler32"
"io" "io"
"math/rand" "math/rand"
"strings"
"time" "time"
) )
func init() {
rand.Seed(time.Now().UnixNano())
}
func Rand64() int64 { func Rand64() int64 {
return rand.Int63() return rand.Int63()
} }
@ -31,7 +36,7 @@ func GetMd5FromBytes(blob []byte) (sum []byte) {
/* get a small, decently unique hash */ /* get a small, decently unique hash */
func GetSmallHash() (small_hash string) { func GetSmallHash() (small_hash string) {
h := adler32.New() h := sha256.New()
io.WriteString(h, fmt.Sprintf("%d", time.Now().Unix())) io.WriteString(h, fmt.Sprintf("%d%d", time.Now().UnixNano(), Rand64()))
return fmt.Sprintf("%X", h.Sum(nil)) return strings.ToLower(fmt.Sprintf("%X", h.Sum(nil)[0:9]))
} }

View File

@ -3,6 +3,7 @@ package hash
import ( import (
"fmt" "fmt"
"testing" "testing"
"sort"
) )
func TestRand64(t *testing.T) { func TestRand64(t *testing.T) {
@ -36,4 +37,15 @@ func TestMd5String(t *testing.T) {
} }
func TestHash(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)
}
}
} }