crypto_hash.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # Copyright 2013 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. from nacl import exceptions as exc
  15. from nacl._sodium import ffi, lib
  16. from nacl.exceptions import ensure
  17. # crypto_hash_BYTES = lib.crypto_hash_bytes()
  18. crypto_hash_BYTES: int = lib.crypto_hash_sha512_bytes()
  19. crypto_hash_sha256_BYTES: int = lib.crypto_hash_sha256_bytes()
  20. crypto_hash_sha512_BYTES: int = lib.crypto_hash_sha512_bytes()
  21. def crypto_hash(message: bytes) -> bytes:
  22. """
  23. Hashes and returns the message ``message``.
  24. :param message: bytes
  25. :rtype: bytes
  26. """
  27. digest = ffi.new("unsigned char[]", crypto_hash_BYTES)
  28. rc = lib.crypto_hash(digest, message, len(message))
  29. ensure(rc == 0, "Unexpected library error", raising=exc.RuntimeError)
  30. return ffi.buffer(digest, crypto_hash_BYTES)[:]
  31. def crypto_hash_sha256(message: bytes) -> bytes:
  32. """
  33. Hashes and returns the message ``message``.
  34. :param message: bytes
  35. :rtype: bytes
  36. """
  37. digest = ffi.new("unsigned char[]", crypto_hash_sha256_BYTES)
  38. rc = lib.crypto_hash_sha256(digest, message, len(message))
  39. ensure(rc == 0, "Unexpected library error", raising=exc.RuntimeError)
  40. return ffi.buffer(digest, crypto_hash_sha256_BYTES)[:]
  41. def crypto_hash_sha512(message: bytes) -> bytes:
  42. """
  43. Hashes and returns the message ``message``.
  44. :param message: bytes
  45. :rtype: bytes
  46. """
  47. digest = ffi.new("unsigned char[]", crypto_hash_sha512_BYTES)
  48. rc = lib.crypto_hash_sha512(digest, message, len(message))
  49. ensure(rc == 0, "Unexpected library error", raising=exc.RuntimeError)
  50. return ffi.buffer(digest, crypto_hash_sha512_BYTES)[:]