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