Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/nacl/bindings/crypto_shorthash.py: 50%
26 statements
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-26 06:36 +0000
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-26 06:36 +0000
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.
16import nacl.exceptions as exc
17from nacl._sodium import ffi, lib
18from nacl.exceptions import ensure
21has_crypto_shorthash_siphashx24 = bool(
22 lib.PYNACL_HAS_CRYPTO_SHORTHASH_SIPHASHX24
23)
25BYTES: int = lib.crypto_shorthash_siphash24_bytes()
26KEYBYTES: int = lib.crypto_shorthash_siphash24_keybytes()
28XBYTES = 0
29XKEYBYTES = 0
31if has_crypto_shorthash_siphashx24:
32 XBYTES = lib.crypto_shorthash_siphashx24_bytes()
33 XKEYBYTES = lib.crypto_shorthash_siphashx24_keybytes()
36def crypto_shorthash_siphash24(data: bytes, key: bytes) -> bytes:
37 """Compute a fast, cryptographic quality, keyed hash of the input data
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)
52 ensure(rc == 0, raising=exc.RuntimeError)
53 return ffi.buffer(digest, BYTES)[:]
56def crypto_shorthash_siphashx24(data: bytes, key: bytes) -> bytes:
57 """Compute a fast, cryptographic quality, keyed hash of the input data
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 )
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)
80 ensure(rc == 0, raising=exc.RuntimeError)
81 return ffi.buffer(digest, XBYTES)[:]