mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-17 03:02:28 +08:00
refactor: Md5File for reading large file
This commit is contained in:
@@ -6,6 +6,7 @@
|
|||||||
package cryptor
|
package cryptor
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bufio"
|
||||||
"crypto/hmac"
|
"crypto/hmac"
|
||||||
"crypto/md5"
|
"crypto/md5"
|
||||||
"crypto/sha1"
|
"crypto/sha1"
|
||||||
@@ -13,7 +14,9 @@ import (
|
|||||||
"crypto/sha512"
|
"crypto/sha512"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"io/ioutil"
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Base64StdEncode encode string with base64 encoding
|
// Base64StdEncode encode string with base64 encoding
|
||||||
@@ -36,14 +39,34 @@ func Md5String(s string) string {
|
|||||||
|
|
||||||
// Md5File return the md5 value of file
|
// Md5File return the md5 value of file
|
||||||
func Md5File(filename string) (string, error) {
|
func Md5File(filename string) (string, error) {
|
||||||
f, err := ioutil.ReadFile(filename)
|
if fileInfo, err := os.Stat(filename); err != nil {
|
||||||
|
return "", err
|
||||||
|
} else if fileInfo.IsDir() {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
file, err := os.Open(filename)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
h := md5.New()
|
hash := md5.New()
|
||||||
h.Write(f)
|
|
||||||
return hex.EncodeToString(h.Sum(nil)), nil
|
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
|
||||||
}
|
}
|
||||||
|
|
||||||
// HmacMd5 return the hmac hash of string use md5
|
// HmacMd5 return the hmac hash of string use md5
|
||||||
|
|||||||
Reference in New Issue
Block a user