Skip to content

Commit

Permalink
fix hash stream functions
Browse files Browse the repository at this point in the history
  • Loading branch information
jstaf committed Oct 18, 2023
1 parent 0907672 commit 22f68aa
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 6 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ tmp/
*.core
*.gdb
vgcore.*
__debug_bin
__debug_bin*

# do not include binaries, but do include sources
onedriver
Expand Down
14 changes: 9 additions & 5 deletions fs/graph/hashes.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
}

Expand All @@ -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)))
}

Expand All @@ -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))
}

Expand All @@ -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)
}

Expand Down
14 changes: 14 additions & 0 deletions fs/graph/hashes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package graph

import (
"bytes"
"io"
"os"
"testing"

Expand Down Expand Up @@ -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))
}

0 comments on commit 22f68aa

Please sign in to comment.