Skip to content

Commit

Permalink
internal/subtle: document and test XORBytes overlap rules #272
Browse files Browse the repository at this point in the history
  • Loading branch information
emmansun authored Nov 20, 2024
1 parent 6e742e6 commit cd60dad
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
8 changes: 8 additions & 0 deletions internal/subtle/xor.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,15 @@

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)),
// returning n, the number of bytes written to dst.
// If dst does not have length at least n,
// 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 {
n := len(x)
if len(y) < n {
Expand All @@ -19,6 +24,9 @@ func XORBytes(dst, x, y []byte) int {
if n > len(dst) {
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
return n
}
8 changes: 8 additions & 0 deletions internal/subtle/xor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,14 @@ func TestXorBytesPanic(t *testing.T) {
mustPanic(t, "subtle.XORBytes: dst too short", func() {
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) {
Expand Down

0 comments on commit cd60dad

Please sign in to comment.