关键词:golang 计算 md5 文件 字符串
//MD5
func Md5SmallFile(path string) (string, error) {
file, err := os.Open(path)
if err != nil {
return "", err
}
defer file.Close()
h := md5.New()
_, err = io.Copy(h, file)
if err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
func Md5BigFile(path string) (string, error) {
var fileChunk uint64 = 10485760
file, err := os.Open(path)
if err != nil {
return "", err
}
defer file.Close()
// calculate the file size
info, _ := file.Stat()
fileSize := info.Size()
blocks := uint64(math.Ceil(float64(fileSize) / float64(fileChunk)))
h := md5.New()
for i := uint64(0); i < blocks; i++ {
blockSize := int(math.Min(float64(fileChunk), float64(fileSize-int64(i*fileChunk))))
buf := make([]byte, blockSize)
_, err := file.Read(buf)
if err != nil {
return "", err
}
_, err = io.WriteString(h, string(buf)) // append into the hash
if err != nil {
return "", err
}
}
return hex.EncodeToString(h.Sum(nil)), nil
}
func MD5String(v string) string {
d := []byte(v)
m := md5.New()
m.Write(d)
return hex.EncodeToString(m.Sum(nil))
}
md5.New()返回一个 hash.Hash 对象
hash.Hash对象定义了一个Sum接口,其原型为:
func Sum(data []byte) [Size]byte
Sum()对hash.Hash对象内部存储的内容进行校验计算,然后将其追加到data的后面形成一个新的byte切片,所以一般需要将data设为nil。