You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

siphash.py 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2016 The Bitcoin Core developers
  3. # Distributed under the MIT software license, see the accompanying
  4. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. """Specialized SipHash-2-4 implementations.
  6. This implements SipHash-2-4 for 256-bit integers.
  7. """
  8. def rotl64(n, b):
  9. return n >> (64 - b) | (n & ((1 << (64 - b)) - 1)) << b
  10. def siphash_round(v0, v1, v2, v3):
  11. v0 = (v0 + v1) & ((1 << 64) - 1)
  12. v1 = rotl64(v1, 13)
  13. v1 ^= v0
  14. v0 = rotl64(v0, 32)
  15. v2 = (v2 + v3) & ((1 << 64) - 1)
  16. v3 = rotl64(v3, 16)
  17. v3 ^= v2
  18. v0 = (v0 + v3) & ((1 << 64) - 1)
  19. v3 = rotl64(v3, 21)
  20. v3 ^= v0
  21. v2 = (v2 + v1) & ((1 << 64) - 1)
  22. v1 = rotl64(v1, 17)
  23. v1 ^= v2
  24. v2 = rotl64(v2, 32)
  25. return (v0, v1, v2, v3)
  26. def siphash256(k0, k1, h):
  27. n0 = h & ((1 << 64) - 1)
  28. n1 = (h >> 64) & ((1 << 64) - 1)
  29. n2 = (h >> 128) & ((1 << 64) - 1)
  30. n3 = (h >> 192) & ((1 << 64) - 1)
  31. v0 = 0x736f6d6570736575 ^ k0
  32. v1 = 0x646f72616e646f6d ^ k1
  33. v2 = 0x6c7967656e657261 ^ k0
  34. v3 = 0x7465646279746573 ^ k1 ^ n0
  35. v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)
  36. v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)
  37. v0 ^= n0
  38. v3 ^= n1
  39. v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)
  40. v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)
  41. v0 ^= n1
  42. v3 ^= n2
  43. v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)
  44. v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)
  45. v0 ^= n2
  46. v3 ^= n3
  47. v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)
  48. v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)
  49. v0 ^= n3
  50. v3 ^= 0x2000000000000000
  51. v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)
  52. v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)
  53. v0 ^= 0x2000000000000000
  54. v2 ^= 0xFF
  55. v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)
  56. v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)
  57. v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)
  58. v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3)
  59. return v0 ^ v1 ^ v2 ^ v3