crypto_shorthash.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # Copyright 2016 Donald Stufft and individual contributors
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import nacl.exceptions as exc
  15. from nacl._sodium import ffi, lib
  16. from nacl.exceptions import ensure
  17. has_crypto_shorthash_siphashx24 = bool(
  18. lib.PYNACL_HAS_CRYPTO_SHORTHASH_SIPHASHX24
  19. )
  20. BYTES: int = lib.crypto_shorthash_siphash24_bytes()
  21. KEYBYTES: int = lib.crypto_shorthash_siphash24_keybytes()
  22. XBYTES = 0
  23. XKEYBYTES = 0
  24. if has_crypto_shorthash_siphashx24:
  25. XBYTES = lib.crypto_shorthash_siphashx24_bytes()
  26. XKEYBYTES = lib.crypto_shorthash_siphashx24_keybytes()
  27. def crypto_shorthash_siphash24(data: bytes, key: bytes) -> bytes:
  28. """Compute a fast, cryptographic quality, keyed hash of the input data
  29. :param data:
  30. :type data: bytes
  31. :param key: len(key) must be equal to
  32. :py:data:`.KEYBYTES` (16)
  33. :type key: bytes
  34. """
  35. if len(key) != KEYBYTES:
  36. raise exc.ValueError(
  37. "Key length must be exactly {} bytes".format(KEYBYTES)
  38. )
  39. digest = ffi.new("unsigned char[]", BYTES)
  40. rc = lib.crypto_shorthash_siphash24(digest, data, len(data), key)
  41. ensure(rc == 0, raising=exc.RuntimeError)
  42. return ffi.buffer(digest, BYTES)[:]
  43. def crypto_shorthash_siphashx24(data: bytes, key: bytes) -> bytes:
  44. """Compute a fast, cryptographic quality, keyed hash of the input data
  45. :param data:
  46. :type data: bytes
  47. :param key: len(key) must be equal to
  48. :py:data:`.XKEYBYTES` (16)
  49. :type key: bytes
  50. :raises nacl.exceptions.UnavailableError: If called when using a
  51. minimal build of libsodium.
  52. """
  53. ensure(
  54. has_crypto_shorthash_siphashx24,
  55. "Not available in minimal build",
  56. raising=exc.UnavailableError,
  57. )
  58. if len(key) != XKEYBYTES:
  59. raise exc.ValueError(
  60. "Key length must be exactly {} bytes".format(XKEYBYTES)
  61. )
  62. digest = ffi.new("unsigned char[]", XBYTES)
  63. rc = lib.crypto_shorthash_siphashx24(digest, data, len(data), key)
  64. ensure(rc == 0, raising=exc.RuntimeError)
  65. return ffi.buffer(digest, XBYTES)[:]