crypto_hash.py 2.2 KB

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