Skip to content

Commit cb356ef

Browse files
author
Arthur White
committed
Add MD5 checksum functions
1 parent d1b6032 commit cb356ef

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

hash.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package crypto
2+
3+
import (
4+
"crypto/md5"
5+
"fmt"
6+
"io"
7+
"os"
8+
)
9+
10+
// HashMD5 returns the MD5 checksum of source.
11+
func HashMD5(src io.Reader) (string, error) {
12+
h := md5.New()
13+
if _, err := io.Copy(h, src); err != nil {
14+
return "", nil
15+
}
16+
return fmt.Sprintf("%x", h.Sum(nil)), nil
17+
}
18+
19+
// HashFileMD5 returns the MD5 checksum of a file.
20+
func HashFileMD5(path string) (string, error) {
21+
f, err := os.Open(path)
22+
if err != nil {
23+
return "", err
24+
}
25+
defer f.Close()
26+
return HashMD5(f)
27+
}

hash_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package crypto
2+
3+
import (
4+
"os"
5+
"testing"
6+
)
7+
8+
var testsHashFile = []struct {
9+
path string
10+
want string
11+
}{
12+
{"LICENSE", "edbc4f9728a8e311b55e081b27e3caff"},
13+
{"unknown", ""},
14+
}
15+
16+
func TestHashFileMD5(t *testing.T) {
17+
for _, tt := range testsHashFile {
18+
got, err := HashFileMD5(tt.path)
19+
if err != nil && !os.IsNotExist(err) {
20+
panic(err)
21+
}
22+
if got != tt.want {
23+
t.Errorf("%q: want %q, got %q", tt.path, tt.want, got)
24+
}
25+
}
26+
}

0 commit comments

Comments
 (0)