Debian Codegraph @

src/nacl/bindings/crypto_shorthash.py

raw
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
15
16 import nacl.exceptions as exc
17 from nacl._sodium import ffi, lib
18 from nacl.exceptions import ensure
19
20
21 has_crypto_shorthash_siphashx24 = bool(
22 lib.PYNACL_HAS_CRYPTO_SHORTHASH_SIPHASHX24
23 )
24
25 BYTES: int = lib.crypto_shorthash_siphash24_bytes()
26 KEYBYTES: int = lib.crypto_shorthash_siphash24_keybytes()
27
28 XBYTES = 0
29 XKEYBYTES = 0
30
31 if has_crypto_shorthash_siphashx24:
32 XBYTES = lib.crypto_shorthash_siphashx24_bytes()
33 XKEYBYTES = lib.crypto_shorthash_siphashx24_keybytes()
34
35
36 def crypto_shorthash_siphash24(data: bytes, key: bytes) -> bytes:
37 """Compute a fast, cryptographic quality, keyed hash of the input data
38
39 :param data:
40 :type data: bytes
41 :param key: len(key) must be equal to
42 :py:data:`.KEYBYTES` (16)
43 :type key: bytes
44 """
45 if len(key) != KEYBYTES:
46 raise exc.ValueError(
47 "Key length must be exactly {} bytes".format(KEYBYTES)
48 )
49 digest = ffi.new("unsigned char[]", BYTES)
50 rc = lib.crypto_shorthash_siphash24(digest, data, len(data), key)
51
52 ensure(rc == 0, raising=exc.RuntimeError)
53 return ffi.buffer(digest, BYTES)[:]
54
55
56 def crypto_shorthash_siphashx24(data: bytes, key: bytes) -> bytes:
57 """Compute a fast, cryptographic quality, keyed hash of the input data
58
59 :param data:
60 :type data: bytes
61 :param key: len(key) must be equal to
62 :py:data:`.XKEYBYTES` (16)
63 :type key: bytes
64 :raises nacl.exceptions.UnavailableError: If called when using a
65 minimal build of libsodium.
66 """
67 ensure(
68 has_crypto_shorthash_siphashx24,
69 "Not available in minimal build",
70 raising=exc.UnavailableError,
71 )
72
73 if len(key) != XKEYBYTES:
74 raise exc.ValueError(
75 "Key length must be exactly {} bytes".format(XKEYBYTES)
76 )
77 digest = ffi.new("unsigned char[]", XBYTES)
78 rc = lib.crypto_shorthash_siphashx24(digest, data, len(data), key)
79
80 ensure(rc == 0, raising=exc.RuntimeError)
81 return ffi.buffer(digest, XBYTES)[:]