imgsrv/hash/hash.go

44 lines
867 B
Go
Raw Permalink Normal View History

2013-05-09 13:47:24 +00:00
package hash
2013-02-09 04:52:40 +00:00
import (
2013-03-27 20:30:24 +00:00
"crypto/md5"
"crypto/sha256"
2013-03-27 20:30:24 +00:00
"fmt"
"io"
"math/rand"
"strings"
2013-03-27 20:30:24 +00:00
"time"
2013-02-09 04:52:40 +00:00
)
func init() {
rand.Seed(time.Now().UnixNano())
}
// Rand64 is an int64 random number
func Rand64() int64 {
2013-03-27 20:30:24 +00:00
return rand.Int63()
}
// GetMd5FromString is a convinience method for getting md5 sum of a string
2013-02-09 04:52:40 +00:00
func GetMd5FromString(blob string) (sum []byte) {
2013-03-27 20:30:24 +00:00
h := md5.New()
defer h.Reset()
io.WriteString(h, blob)
return h.Sum(nil)
2013-02-09 04:52:40 +00:00
}
// GetMd5FromBytes is a convinience method for getting md5 sum of some bytes
2013-02-09 04:52:40 +00:00
func GetMd5FromBytes(blob []byte) (sum []byte) {
2013-03-27 20:30:24 +00:00
h := md5.New()
defer h.Reset()
h.Write(blob)
return h.Sum(nil)
2013-02-09 04:52:40 +00:00
}
// GetSmallHash get a small, decently unique hash
func GetSmallHash(num uint) string {
h := sha256.New()
io.WriteString(h, fmt.Sprintf("%d%d", Rand64(), Rand64()))
return strings.ToLower(fmt.Sprintf("%X", h.Sum(nil)[0:num]))
2013-02-09 04:52:40 +00:00
}