lib/protocol: Optimize FileKey (#7440)

This commit is contained in:
greatroar 2021-03-07 18:44:21 +01:00 committed by GitHub
parent 587c89d979
commit c00520281b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 2 deletions

View File

@ -8,7 +8,6 @@ package protocol
import ( import (
"context" "context"
"crypto/sha256"
"encoding/base32" "encoding/base32"
"encoding/binary" "encoding/binary"
"errors" "errors"
@ -20,6 +19,7 @@ import (
"github.com/gogo/protobuf/proto" "github.com/gogo/protobuf/proto"
"github.com/miscreant/miscreant.go" "github.com/miscreant/miscreant.go"
"github.com/syncthing/syncthing/lib/rand" "github.com/syncthing/syncthing/lib/rand"
"github.com/syncthing/syncthing/lib/sha256"
"golang.org/x/crypto/chacha20poly1305" "golang.org/x/crypto/chacha20poly1305"
"golang.org/x/crypto/hkdf" "golang.org/x/crypto/hkdf"
"golang.org/x/crypto/scrypt" "golang.org/x/crypto/scrypt"
@ -487,8 +487,10 @@ func KeyFromPassword(folderID, password string) *[keySize]byte {
return &key return &key
} }
var hkdfSalt = []byte("syncthing")
func FileKey(filename string, folderKey *[keySize]byte) *[keySize]byte { 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 var fileKey [keySize]byte
n, err := io.ReadFull(kdf, fileKey[:]) n, err := io.ReadFull(kdf, fileKey[:])
if err != nil || n != keySize { if err != nil || n != keySize {

View File

@ -12,9 +12,11 @@ import (
"reflect" "reflect"
"regexp" "regexp"
"strings" "strings"
"sync"
"testing" "testing"
"github.com/syncthing/syncthing/lib/rand" "github.com/syncthing/syncthing/lib/rand"
"github.com/syncthing/syncthing/lib/sha256"
) )
func TestEnDecryptName(t *testing.T) { 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)
}
}