package ncrypt import ( "bufio" "crypto/md5" "encoding/hex" "fmt" "git.noahlan.cn/noahlan/ntool/nbyte" "io" "os" ) // Md5Bytes return the md5 value of bytes. func Md5Bytes(b any) []byte { return nbyte.Md5(b) } // Md5String return the md5 value of string. func Md5String(s any) string { return hex.EncodeToString(Md5Bytes(s)) } // Md5File return the md5 value of file. func Md5File(filename string) (string, error) { if fileInfo, err := os.Stat(filename); err != nil { return "", err } else if fileInfo.IsDir() { return "", nil } file, err := os.Open(filename) if err != nil { return "", err } defer file.Close() hash := md5.New() chunkSize := 65536 for buf, reader := make([]byte, chunkSize), bufio.NewReader(file); ; { n, err := reader.Read(buf) if err != nil { if err == io.EOF { break } return "", err } hash.Write(buf[:n]) } checksum := fmt.Sprintf("%x", hash.Sum(nil)) return checksum, nil }