From db7fbdef951817ff817fa73f87647253c3716a4c Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Sun, 17 Dec 2017 12:03:36 -0800 Subject: [PATCH] use faster sha256 and blake2b implementations fixes #61 --- package.json | 12 ++++++++++++ sum.go | 41 ++++++++++++++++++++++++++++++++--------- 2 files changed, 44 insertions(+), 9 deletions(-) diff --git a/package.json b/package.json index 71ca162..faee9e8 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,18 @@ "hash": "QmfJHywXQu98UeZtGJBQrPAR6AtmDjjbe3qjTo9piXHPnx", "name": "murmur3", "version": "0.0.0" + }, + { + "author": "minio", + "hash": "QmYmZHLQ4ctyTv84Qfrw39jWzSWvbjo8cb6rkb6oWwzC6T", + "name": "sha256-simd", + "version": "0.1.0" + }, + { + "author": "minio", + "hash": "QmctbhjPfFUCFWemafc7LGXUKJuoRm8baJaiQEELMgbUFV", + "name": "blake2b-simd", + "version": "0.1.0" } ], "gxVersion": "0.9.0", diff --git a/sum.go b/sum.go index af194a0..79d1a15 100644 --- a/sum.go +++ b/sum.go @@ -2,13 +2,13 @@ package multihash import ( "crypto/sha1" - "crypto/sha256" "crypto/sha512" "errors" "fmt" - "github.com/spaolacci/murmur3" - blake2b "golang.org/x/crypto/blake2b" + blake2b "github.com/minio/blake2b-simd" + sha256 "github.com/minio/sha256-simd" + murmur3 "github.com/spaolacci/murmur3" blake2s "golang.org/x/crypto/blake2s" sha3 "golang.org/x/crypto/sha3" keccak "leb.io/hashland/keccakpg" @@ -50,14 +50,11 @@ func Sum(data []byte, code uint64, length int) (Multihash, error) { olen := code - BLAKE2B_MIN + 1 switch olen { case 32: - out := blake2b.Sum256(data) - d = out[:] + d = sumBlake2b256(data) case 48: - out := blake2b.Sum384(data) - d = out[:] + d = sumBlake2b384(data) case 64: - out := blake2b.Sum512(data) - d = out[:] + d = sumBlake2b512(data) default: return nil, fmt.Errorf("unsupported length for blake2b: %d", olen) } @@ -115,6 +112,32 @@ func isBlake2b(code uint64) bool { return code >= BLAKE2B_MIN && code <= BLAKE2B_MAX } +func sumBlake2b256(data []byte) []byte { + out := blake2b.Sum256(data) + return out[:] +} + +const blake2b384Size = 384 / 8 + +var blake2b384Config = &blake2b.Config{Size: blake2b384Size} + +func sumBlake2b384(data []byte) []byte { + hasher, err := blake2b.New(blake2b384Config) + if err != nil { + panic(err) + } + hasher.Write(data) + var out [blake2b384Size]byte + copy(out[:], hasher.Sum(nil)[:blake2b384Size]) + return out[:] + +} + +func sumBlake2b512(data []byte) []byte { + out := blake2b.Sum512(data) + return out[:] +} + func sumID(data []byte) []byte { return data }