lib/model: Verify request content against weak (and possibly strong) hash (#4767)
This commit is contained in:
committed by
Jakob Borg
parent
678c80ffe4
commit
ef0dcea6a4
@@ -7,6 +7,7 @@
|
||||
package scanner
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"hash"
|
||||
"io"
|
||||
@@ -107,6 +108,29 @@ func Blocks(ctx context.Context, r io.Reader, blocksize int, sizehint int64, cou
|
||||
return blocks, nil
|
||||
}
|
||||
|
||||
func Validate(buf, hash []byte, weakHash uint32) bool {
|
||||
rd := bytes.NewReader(buf)
|
||||
if weakHash != 0 {
|
||||
whf := adler32.New()
|
||||
if _, err := io.Copy(whf, rd); err == nil && whf.Sum32() == weakHash {
|
||||
return true
|
||||
}
|
||||
// Copy error or mismatch, go to next algo.
|
||||
rd.Seek(0, io.SeekStart)
|
||||
}
|
||||
|
||||
if len(hash) > 0 {
|
||||
hf := sha256.New()
|
||||
if _, err := io.Copy(hf, rd); err == nil {
|
||||
// Sum allocates, so let's hope we don't hit this often.
|
||||
return bytes.Equal(hf.Sum(nil), hash)
|
||||
}
|
||||
}
|
||||
|
||||
// Both algos failed or no hashes were specified. Assume it's all good.
|
||||
return true
|
||||
}
|
||||
|
||||
type noopHash struct{}
|
||||
|
||||
func (noopHash) Sum32() uint32 { return 0 }
|
||||
|
||||
Reference in New Issue
Block a user