Skip to content

Commit 09cdd23

Browse files
committed
Reduce allocations during ECDSA signing
Reduce the number of byte arrays allocated by using big.Int.FillBytes when calculating ECDSA signature. After this change, Benchmarks of ES256 signing method consistently report 4 fewer allocations. Before: ``` BenchmarkECDSASigning/Basic_ES256-8 190572 6702 ns/op 4249 B/op 65 allocs/op BenchmarkECDSASigning/Basic_ES256/sign-only-8 47383 24650 ns/op 3329 B/op 43 allocs/op ``` After: ``` BenchmarkECDSASigning/Basic_ES256-8 187682 6725 ns/op 4121 B/op 61 allocs/op BenchmarkECDSASigning/Basic_ES256/sign-only-8 48656 24446 ns/op 3201 B/op 39 allocs/op ```
1 parent ff7295f commit 09cdd23

File tree

1 file changed

+6
-12
lines changed

1 file changed

+6
-12
lines changed

ecdsa.go

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -128,18 +128,12 @@ func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string
128128
keyBytes += 1
129129
}
130130

131-
// We serialize the outpus (r and s) into big-endian byte arrays and pad
132-
// them with zeros on the left to make sure the sizes work out. Both arrays
133-
// must be keyBytes long, and the output must be 2*keyBytes long.
134-
rBytes := r.Bytes()
135-
rBytesPadded := make([]byte, keyBytes)
136-
copy(rBytesPadded[keyBytes-len(rBytes):], rBytes)
137-
138-
sBytes := s.Bytes()
139-
sBytesPadded := make([]byte, keyBytes)
140-
copy(sBytesPadded[keyBytes-len(sBytes):], sBytes)
141-
142-
out := append(rBytesPadded, sBytesPadded...)
131+
// We serialize the outputs (r and s) into big-endian byte arrays
132+
// padded with zeros on the left to make sure the sizes work out.
133+
// Output must be 2*keyBytes long.
134+
out := make([]byte, 2*keyBytes)
135+
r.FillBytes(out[0:keyBytes]) // r is assigned to the first half of output.
136+
s.FillBytes(out[keyBytes:]) // s is assigned to the second half of output.
143137

144138
return EncodeSegment(out), nil
145139
} else {

0 commit comments

Comments
 (0)