From 22f68aa26b9bd2d6062b7dae793d31b59f8a06c2 Mon Sep 17 00:00:00 2001 From: Jeff Stafford Date: Tue, 17 Oct 2023 20:37:55 -0400 Subject: [PATCH] fix hash stream functions --- .gitignore | 2 +- fs/graph/hashes.go | 14 +++++++++----- fs/graph/hashes_test.go | 14 ++++++++++++++ 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index 1973c9c..8395354 100644 --- a/.gitignore +++ b/.gitignore @@ -22,7 +22,7 @@ tmp/ *.core *.gdb vgcore.* -__debug_bin +__debug_bin* # do not include binaries, but do include sources onedriver diff --git a/fs/graph/hashes.go b/fs/graph/hashes.go index fd4259e..a05eac0 100644 --- a/fs/graph/hashes.go +++ b/fs/graph/hashes.go @@ -15,9 +15,11 @@ func SHA256Hash(data *[]byte) string { return strings.ToUpper(fmt.Sprintf("%x", sha256.Sum256(*data))) } -func SHA256HashStream(reader io.Reader) string { +func SHA256HashStream(reader io.ReadSeeker) string { + reader.Seek(0, 0) hash := sha256.New() io.Copy(hash, reader) + reader.Seek(0, 0) return strings.ToUpper(fmt.Sprintf("%x", hash.Sum(nil))) } @@ -28,9 +30,11 @@ func SHA1Hash(data *[]byte) string { } // SHA1HashStream hashes the contents of a stream. -func SHA1HashStream(reader io.Reader) string { +func SHA1HashStream(reader io.ReadSeeker) string { + reader.Seek(0, 0) hash := sha1.New() io.Copy(hash, reader) + reader.Seek(0, 0) return strings.ToUpper(fmt.Sprintf("%x", hash.Sum(nil))) } @@ -43,9 +47,11 @@ func QuickXORHash(data *[]byte) string { } // QuickXORHashStream hashes a stream. -func QuickXORHashStream(reader io.Reader) string { +func QuickXORHashStream(reader io.ReadSeeker) string { + reader.Seek(0, 0) hash := quickxorhash.New() io.Copy(hash, reader) + reader.Seek(0, 0) return base64.StdEncoding.EncodeToString(hash.Sum(nil)) } @@ -56,8 +62,6 @@ func (d *DriveItem) VerifyChecksum(checksum string) bool { if len(checksum) == 0 || d.File == nil { return false } - // all checksums are converted to upper to avoid casing issues from whatever - // the API decides to return at this point in time. return strings.EqualFold(d.File.Hashes.QuickXorHash, checksum) } diff --git a/fs/graph/hashes_test.go b/fs/graph/hashes_test.go index f721800..5e701d8 100644 --- a/fs/graph/hashes_test.go +++ b/fs/graph/hashes_test.go @@ -2,6 +2,7 @@ package graph import ( "bytes" + "io" "os" "testing" @@ -67,3 +68,16 @@ func TestQuickXORHashReader(t *testing.T) { actual := QuickXORHashStream(reader) assert.Equal(t, expected, actual) } + +func TestHashSeekPosition(t *testing.T) { + tmp, err := os.CreateTemp("", "onedriverHashTest") + if err != nil { + t.Error(err) + } + content := []byte("some test content") + io.Copy(tmp, bytes.NewBuffer(content)) + + assert.Equal(t, QuickXORHash(&content), QuickXORHashStream(tmp)) + assert.Equal(t, SHA1Hash(&content), SHA1HashStream(tmp)) + assert.Equal(t, SHA256Hash(&content), SHA256HashStream(tmp)) +}