feat: cache derived keys for faster keying (#10114)
Currently `DeriveKey` is called every time that a secret must be encoded/decoded. Since this function is deterministic, its result can be cached to allow a 250x speedup (the original took less than half a microsecond, so this more of a micro-optimization...). ``` go test -bench=. goos: linux goarch: amd64 pkg: forgejo.org/modules/keying cpu: Intel(R) Core(TM) Ultra 5 125H BenchmarkExpandPRK-18 2071627 564.2 ns/op BenchmarkExpandPRKOnce-18 541438192 2.206 ns/op PASS ok forgejo.org/modules/keying 2.369s ``` ## Other changes - Since the keys can be constructed once, it simplifies a bit the callsites (`keying.TOTP.Encrypt(...)` instead of `keying.DeriveKey(keying.ContextTOTP).Encrypt(...)`) - All `Encrypt`/`Decrypt` calls will panic forever if called before `Init` has been called (current it panics as long as `Init` has not been called) - Calling `Init` twice with different keys will trigger a panic (currently racy) - Calling `Decrypt` with a short ciphertext does not panic anymore (like when calling with long-enough garbage) Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/10114 Reviewed-by: Gusted <gusted@noreply.codeberg.org> Co-authored-by: oliverpool <git@olivier.pfad.fr> Co-committed-by: oliverpool <git@olivier.pfad.fr>
This commit is contained in:
@@ -84,7 +84,7 @@ func CreateMigrateTask(ctx context.Context, doer, u *user_model.User, opts base.
|
||||
return err
|
||||
}
|
||||
|
||||
key := keying.DeriveKey(keying.ContextMigrateTask)
|
||||
key := keying.MigrateTask
|
||||
|
||||
opts.CloneAddrEncrypted = base64.RawStdEncoding.EncodeToString(key.Encrypt([]byte(opts.CloneAddr), keying.ColumnAndJSONSelectorAndID("payload_content", "clone_addr_encrypted", task.ID)))
|
||||
opts.CloneAddr = util.SanitizeCredentialURLs(opts.CloneAddr)
|
||||
|
||||
Reference in New Issue
Block a user