File: test_generichash.py

package info (click to toggle)
python-nacl 1.5.0-7
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 14,776 kB
  • sloc: ansic: 45,889; python: 7,249; sh: 6,752; asm: 2,974; makefile: 1,011; cs: 35; xml: 30; pascal: 11
file content (245 lines) | stat: -rw-r--r-- 7,397 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# Copyright 2016 Donald Stufft and individual contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import binascii
import copy
import json
import os
from typing import AnyStr, Dict, List, Tuple, Union

import pytest

import nacl.encoding
import nacl.exceptions as exc
import nacl.hash
import nacl.hashlib

from .utils import read_crypto_test_vectors


OVERLONG_PARAMS_VECTORS = [
    (b"key", 65 * b"\xaa", 16 * b"\xaa", 16 * b"\x55", 64, b"will raise"),
    (b"salt", b"key", 17 * b"\xaa", 16 * b"\x55", 64, b"will raise"),
    (b"personal", b"key", 16 * b"\xaa", 17 * b"\x55", 64, b"will raise"),
    (b"digest_size", b"key", 16 * b"\xaa", 16 * b"\x55", 65, b"will raise"),
]


def generichash_vectors() -> List[Tuple[bytes, bytes, bytes, bytes]]:
    # Format: <message> <tab> <key> <tab> <output length> <tab> <output>
    DATA = "crypto-test-vectors-blake2-nosalt-nopersonalization.txt"
    # Type safety: read_crypto_test_vectors returns an arbitrary length tuple, but we
    # know this file's test entries contain exactly four fields.
    return read_crypto_test_vectors(DATA, delimiter=b"\t")  # type: ignore[return-value]


def blake2_salt_pers_vectors() -> List[
    Tuple[bytes, bytes, bytes, bytes, bytes, bytes]
]:
    # Format: <message> <tab> <key> <tab> <salt> <tab>
    # <personalization> <tab> <output length> <tab> <output>
    DATA = "crypto-test-vectors-blake2-salt-personalization.txt"
    # Type safety: read_crypto_test_vectors returns an arbitrary length tuple, but we
    # know this file's test entries contain exactly six fields.
    return read_crypto_test_vectors(DATA, delimiter=b"\t")  # type: ignore[return-value]


def blake2_reference_vectors() -> List[Tuple[str, str, int, str]]:
    DATA = "blake2-kat.json"
    path = os.path.join(os.path.dirname(__file__), "data", DATA)
    jvectors: List[Dict[str, str]] = json.load(open(path))
    vectors = [
        (x["in"], x["key"], len(x["out"]) // 2, x["out"])
        for x in jvectors
        if x["hash"] == "blake2b"
    ]
    return vectors


@pytest.mark.parametrize(
    ["message", "key", "outlen", "output"], generichash_vectors()
)
def test_generichash(
    message: AnyStr, key: AnyStr, outlen: Union[AnyStr, int], output: AnyStr
):
    msg = binascii.unhexlify(message)
    output_bytes = binascii.hexlify(binascii.unhexlify(output))
    k = binascii.unhexlify(key)
    outlen_parsed = int(outlen)
    out = nacl.hash.generichash(msg, digest_size=outlen_parsed, key=k)
    assert out == output_bytes


@pytest.mark.parametrize(
    ["message", "key", "salt", "person", "outlen", "output"],
    OVERLONG_PARAMS_VECTORS,
)
def test_overlong_blake2b_oneshot_params(
    message: bytes,
    key: bytes,
    salt: bytes,
    person: bytes,
    outlen: int,
    output: bytes,
):
    with pytest.raises(exc.ValueError):
        nacl.hash.blake2b(
            message, digest_size=outlen, key=key, salt=salt, person=person
        )


@pytest.mark.parametrize(
    ["message", "key", "outlen", "output"], blake2_reference_vectors()
)
def test_generichash_blake2_ref(
    message: str, key: str, outlen: int, output: str
):
    test_generichash(message, key, outlen, output)


@pytest.mark.parametrize(
    ["message", "key", "salt", "person", "outlen", "output"],
    blake2_salt_pers_vectors(),
)
def test_hash_blake2b(
    message: bytes,
    key: bytes,
    salt: bytes,
    person: bytes,
    outlen: bytes,
    output: bytes,
):
    msg = binascii.unhexlify(message)
    output = binascii.hexlify(binascii.unhexlify(output))
    k = binascii.unhexlify(key)
    slt = binascii.unhexlify(salt)
    pers = binascii.unhexlify(person)
    outlen_parsed = int(outlen)
    out = nacl.hash.blake2b(
        msg, digest_size=outlen_parsed, key=k, salt=slt, person=pers
    )
    assert out == output


def test_expected_hashlib_level_pickle_and_copy_failures():
    h = nacl.hashlib.blake2b()
    with pytest.raises(TypeError):
        copy.deepcopy(h)
    with pytest.raises(TypeError):
        copy.copy(h)


def test_expected_bindings_level_pickle_and_copy_failures():
    from nacl.bindings.crypto_generichash import (
        Blake2State,
        crypto_generichash_BYTES,
    )

    st = Blake2State(crypto_generichash_BYTES)
    with pytest.raises(TypeError):
        copy.deepcopy(st)
    with pytest.raises(TypeError):
        copy.copy(st)


@pytest.mark.parametrize(
    ["message", "key", "outlen", "output"], blake2_reference_vectors()
)
def test_hashlib_blake2_ref_vectors(
    message: str, key: str, outlen: int, output: str
):
    msg = binascii.unhexlify(message)
    k = binascii.unhexlify(key)
    outlen = int(outlen)
    out = binascii.unhexlify(output)
    h = nacl.hashlib.blake2b(msg, digest_size=outlen, key=k)
    dgst = h.digest()
    assert out == dgst


@pytest.mark.parametrize(
    ["message", "key", "outlen", "output"], blake2_reference_vectors()
)
def test_hashlib_blake2_iuf_ref_vectors(
    message: str, key: str, outlen: int, output: str
):
    msg = binascii.unhexlify(message)
    k = binascii.unhexlify(key)
    outlen = int(outlen)
    out = binascii.unhexlify(output)
    h = nacl.hashlib.blake2b(digest_size=outlen, key=k)
    for _pos in range(len(msg)):
        _end = _pos + 1
        h.update(bytes(msg[_pos:_end]))
    dgst = h.digest()
    hdgst = h.hexdigest()
    assert hdgst == output
    assert out == dgst


@pytest.mark.parametrize(
    ["message", "key", "outlen", "output"], blake2_reference_vectors()
)
def test_hashlib_blake2_iuf_cp_ref_vectors(
    message: str, key: str, outlen: int, output: str
):
    msg = binascii.unhexlify(message)
    msglen = len(msg)
    if msglen < 2:
        pytest.skip("Message too short for splitting")
    k = binascii.unhexlify(key)
    outlen = int(outlen)
    out = binascii.unhexlify(output)
    h = nacl.hashlib.blake2b(digest_size=outlen, key=k)
    for _pos in range(len(msg)):
        _end = _pos + 1
        h.update(bytes(msg[_pos:_end]))
        if _end == msglen // 2:
            h2 = h.copy()
    dgst = h.digest()
    d2 = h2.digest()
    assert out == dgst
    assert d2 != dgst


@pytest.mark.parametrize(
    ["message", "key", "salt", "person", "outlen", "output"],
    OVERLONG_PARAMS_VECTORS,
)
def test_overlong_blake2b_iuf_params(
    message: bytes,
    key: bytes,
    salt: bytes,
    person: bytes,
    outlen: int,
    output: bytes,
):
    with pytest.raises(exc.ValueError):
        nacl.hashlib.blake2b(
            message, digest_size=outlen, key=key, salt=salt, person=person
        )


def test_blake2_descriptors_presence():
    h = nacl.hashlib.blake2b()
    assert h.name == "blake2b"
    assert h.block_size == 128
    assert h.digest_size == 32  # this is the default digest_size


def test_blake2_digest_size_descriptor_coherence():
    h = nacl.hashlib.blake2b(digest_size=64)
    assert h.name == "blake2b"
    assert h.block_size == 128
    assert h.digest_size == 64