xor.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Copyright 2018 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found src the LICENSE file.
  4. package chacha20
  5. import "runtime"
  6. // Platforms that have fast unaligned 32-bit little endian accesses.
  7. const unaligned = runtime.GOARCH == "386" ||
  8. runtime.GOARCH == "amd64" ||
  9. runtime.GOARCH == "arm64" ||
  10. runtime.GOARCH == "ppc64le" ||
  11. runtime.GOARCH == "s390x"
  12. // addXor reads a little endian uint32 from src, XORs it with (a + b) and
  13. // places the result in little endian byte order in dst.
  14. func addXor(dst, src []byte, a, b uint32) {
  15. _, _ = src[3], dst[3] // bounds check elimination hint
  16. if unaligned {
  17. // The compiler should optimize this code into
  18. // 32-bit unaligned little endian loads and stores.
  19. // TODO: delete once the compiler does a reliably
  20. // good job with the generic code below.
  21. // See issue #25111 for more details.
  22. v := uint32(src[0])
  23. v |= uint32(src[1]) << 8
  24. v |= uint32(src[2]) << 16
  25. v |= uint32(src[3]) << 24
  26. v ^= a + b
  27. dst[0] = byte(v)
  28. dst[1] = byte(v >> 8)
  29. dst[2] = byte(v >> 16)
  30. dst[3] = byte(v >> 24)
  31. } else {
  32. a += b
  33. dst[0] = src[0] ^ byte(a)
  34. dst[1] = src[1] ^ byte(a>>8)
  35. dst[2] = src[2] ^ byte(a>>16)
  36. dst[3] = src[3] ^ byte(a>>24)
  37. }
  38. }