From c00520281b68f744e856ae8b9d39b1947a9cedf9 Mon Sep 17 00:00:00 2001 From: greatroar <61184462+greatroar@users.noreply.github.com> Date: Sun, 7 Mar 2021 18:44:21 +0100 Subject: [PATCH] lib/protocol: Optimize FileKey (#7440) --- lib/protocol/encryption.go | 6 ++++-- lib/protocol/encryption_test.go | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/lib/protocol/encryption.go b/lib/protocol/encryption.go index 6125f1850..c1485cc31 100644 --- a/lib/protocol/encryption.go +++ b/lib/protocol/encryption.go @@ -8,7 +8,6 @@ package protocol import ( "context" - "crypto/sha256" "encoding/base32" "encoding/binary" "errors" @@ -20,6 +19,7 @@ import ( "github.com/gogo/protobuf/proto" "github.com/miscreant/miscreant.go" "github.com/syncthing/syncthing/lib/rand" + "github.com/syncthing/syncthing/lib/sha256" "golang.org/x/crypto/chacha20poly1305" "golang.org/x/crypto/hkdf" "golang.org/x/crypto/scrypt" @@ -487,8 +487,10 @@ func KeyFromPassword(folderID, password string) *[keySize]byte { return &key } +var hkdfSalt = []byte("syncthing") + func FileKey(filename string, folderKey *[keySize]byte) *[keySize]byte { - kdf := hkdf.New(sha256.New, append(folderKey[:], filename...), []byte("syncthing"), nil) + kdf := hkdf.New(sha256.New, append(folderKey[:], filename...), hkdfSalt, nil) var fileKey [keySize]byte n, err := io.ReadFull(kdf, fileKey[:]) if err != nil || n != keySize { diff --git a/lib/protocol/encryption_test.go b/lib/protocol/encryption_test.go index 2909f30e0..56806c6c1 100644 --- a/lib/protocol/encryption_test.go +++ b/lib/protocol/encryption_test.go @@ -12,9 +12,11 @@ import ( "reflect" "regexp" "strings" + "sync" "testing" "github.com/syncthing/syncthing/lib/rand" + "github.com/syncthing/syncthing/lib/sha256" ) func TestEnDecryptName(t *testing.T) { @@ -180,3 +182,22 @@ func TestIsEncryptedParent(t *testing.T) { } } } + +var benchmarkFileKey struct { + key [keySize]byte + sync.Once +} + +func BenchmarkFileKey(b *testing.B) { + benchmarkFileKey.Do(func() { + sha256.SelectAlgo() + rand.Read(benchmarkFileKey.key[:]) + }) + + b.ResetTimer() + b.ReportAllocs() + + for i := 0; i < b.N; i++ { + FileKey("a_kind_of_long_filename.ext", &benchmarkFileKey.key) + } +}