internal/subtle: document and test XORBytes overlap rules #272

This commit is contained in:
Sun Yimin 2024-11-20 14:21:16 +08:00 committed by GitHub
parent 6e742e69ef
commit cd60dad621
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 16 additions and 0 deletions

View File

@ -4,10 +4,15 @@
package subtle package subtle
import "github.com/emmansun/gmsm/internal/alias"
// XORBytes sets dst[i] = x[i] ^ y[i] for all i < n = min(len(x), len(y)), // XORBytes sets dst[i] = x[i] ^ y[i] for all i < n = min(len(x), len(y)),
// returning n, the number of bytes written to dst. // returning n, the number of bytes written to dst.
// If dst does not have length at least n, // If dst does not have length at least n,
// XORBytes panics without writing anything to dst. // XORBytes panics without writing anything to dst.
//
// dst and x or y may overlap exactly or not at all,
// otherwise XORBytes may panic.
func XORBytes(dst, x, y []byte) int { func XORBytes(dst, x, y []byte) int {
n := len(x) n := len(x)
if len(y) < n { if len(y) < n {
@ -19,6 +24,9 @@ func XORBytes(dst, x, y []byte) int {
if n > len(dst) { if n > len(dst) {
panic("subtle.XORBytes: dst too short") panic("subtle.XORBytes: dst too short")
} }
if alias.InexactOverlap(dst[:n], x[:n]) || alias.InexactOverlap(dst[:n], y[:n]) {
panic("subtle.XORBytes: invalid overlap")
}
xorBytes(&dst[0], &x[0], &y[0], n) // arch-specific xorBytes(&dst[0], &x[0], &y[0], n) // arch-specific
return n return n
} }

View File

@ -58,6 +58,14 @@ func TestXorBytesPanic(t *testing.T) {
mustPanic(t, "subtle.XORBytes: dst too short", func() { mustPanic(t, "subtle.XORBytes: dst too short", func() {
subtle.XORBytes(make([]byte, 1), make([]byte, 2), make([]byte, 3)) subtle.XORBytes(make([]byte, 1), make([]byte, 2), make([]byte, 3))
}) })
mustPanic(t, "subtle.XORBytes: invalid overlap", func() {
x := make([]byte, 3)
subtle.XORBytes(x, x[1:], make([]byte, 2))
})
mustPanic(t, "subtle.XORBytes: invalid overlap", func() {
x := make([]byte, 3)
subtle.XORBytes(x, make([]byte, 2), x[1:])
})
} }
func BenchmarkXORBytes(b *testing.B) { func BenchmarkXORBytes(b *testing.B) {