aboutsummaryrefslogtreecommitdiffstats
path: root/plumbing/hash/hash.go
diff options
context:
space:
mode:
authorPaulo Gomes <pjbgf@linux.com>2022-11-25 14:07:01 +0000
committerPaulo Gomes <pjbgf@linux.com>2022-11-25 14:07:01 +0000
commit7c37589e95f6a88e470bf91d3a0ef8536702f3f4 (patch)
treea8d7351b3d6094cea5974750a312346f1c066e0a /plumbing/hash/hash.go
parentc798d4a42004b1c8976a6a4f42f131f16d08b6fa (diff)
downloadgo-git-7c37589e95f6a88e470bf91d3a0ef8536702f3f4.tar.gz
sha1: Add collision resistent implementation
Implement the same SHA1 collision resistent algorithm used by both the Git CLI and libgit2. Only commits with input that match the unavoidable bit conditions will be further processed, which will result in different hashes. Which is the same behaviour experienced in the Git CLI and Libgit2. Users can override the hash algorithm used with: hash.RegisterHash(crypto.SHA1, sha1.New) xref links: https://github.com/libgit2/libgit2/pull/4136/commits/2dfd1294f7a694bfa9e864a9489ae3cb318a5ed0 https://github.com/git/git/commit/28dc98e343ca4eb370a29ceec4c19beac9b5c01e Signed-off-by: Paulo Gomes <pjbgf@linux.com>
Diffstat (limited to 'plumbing/hash/hash.go')
-rw-r--r--plumbing/hash/hash.go59
1 files changed, 59 insertions, 0 deletions
diff --git a/plumbing/hash/hash.go b/plumbing/hash/hash.go
new file mode 100644
index 0000000..fe3bf76
--- /dev/null
+++ b/plumbing/hash/hash.go
@@ -0,0 +1,59 @@
+// package hash provides a way for managing the
+// underlying hash implementations used across go-git.
+package hash
+
+import (
+ "crypto"
+ "fmt"
+ "hash"
+
+ "github.com/pjbgf/sha1cd/cgo"
+)
+
+// algos is a map of hash algorithms.
+var algos = map[crypto.Hash]func() hash.Hash{}
+
+func init() {
+ reset()
+}
+
+// reset resets the default algos value. Can be used after running tests
+// that registers new algorithms to avoid side effects.
+func reset() {
+ // For performance reasons the cgo version of the collision
+ // detection algorithm is being used.
+ algos[crypto.SHA1] = cgo.New
+}
+
+// RegisterHash allows for the hash algorithm used to be overriden.
+// This ensures the hash selection for go-git must be explicit, when
+// overriding the default value.
+func RegisterHash(h crypto.Hash, f func() hash.Hash) error {
+ if f == nil {
+ return fmt.Errorf("cannot register hash: f is nil")
+ }
+
+ switch h {
+ case crypto.SHA1:
+ algos[h] = f
+ default:
+ return fmt.Errorf("unsupported hash function: %v", h)
+ }
+ return nil
+}
+
+// Hash is the same as hash.Hash. This allows consumers
+// to not having to import this package alongside "hash".
+type Hash interface {
+ hash.Hash
+}
+
+// New returns a new Hash for the given hash function.
+// It panics if the hash function is not registered.
+func New(h crypto.Hash) Hash {
+ hh, ok := algos[h]
+ if !ok {
+ panic(fmt.Sprintf("hash algorithm not registered: %v", h))
+ }
+ return hh()
+}