blob: 48023ca63d70f1f3d09c7b333fe5198290241d28 [file] [log] [blame]
Paul Kehrer7ca0e462018-07-17 22:40:02 +08001# This file is dual licensed under the terms of the Apache License, Version
2# 2.0, and the BSD License. See the LICENSE file in the root of this repository
3# for complete details.
4
5from __future__ import absolute_import, division, print_function
6
7import binascii
8
9import pytest
10
11from cryptography.exceptions import InvalidTag
12from cryptography.hazmat.backends.interfaces import CipherBackend
13from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
14
15from ..hazmat.primitives.test_aead import _aead_supported
16
17
18@pytest.mark.skipif(
19 not _aead_supported(ChaCha20Poly1305),
Lucia Lic6ba99d2021-11-08 22:06:11 +080020 reason="Requires OpenSSL with ChaCha20Poly1305 support",
Paul Kehrer7ca0e462018-07-17 22:40:02 +080021)
22@pytest.mark.requires_backend_interface(interface=CipherBackend)
23@pytest.mark.wycheproof_tests("chacha20_poly1305_test.json")
24def test_chacha2poly1305(wycheproof):
25 key = binascii.unhexlify(wycheproof.testcase["key"])
26 iv = binascii.unhexlify(wycheproof.testcase["iv"])
27 aad = binascii.unhexlify(wycheproof.testcase["aad"])
28 msg = binascii.unhexlify(wycheproof.testcase["msg"])
29 ct = binascii.unhexlify(wycheproof.testcase["ct"])
30 tag = binascii.unhexlify(wycheproof.testcase["tag"])
31
32 if wycheproof.valid:
33 chacha = ChaCha20Poly1305(key)
34 computed_ct = chacha.encrypt(iv, msg, aad)
35 assert computed_ct == ct + tag
36 computed_msg = chacha.decrypt(iv, ct + tag, aad)
37 assert computed_msg == msg
38 elif len(iv) != 12:
39 chacha = ChaCha20Poly1305(key)
40 with pytest.raises(ValueError):
41 chacha.encrypt(iv, msg, aad)
42 with pytest.raises(ValueError):
43 chacha.decrypt(iv, ct + tag, aad)
44 else:
45 chacha = ChaCha20Poly1305(key)
46 with pytest.raises(InvalidTag):
47 chacha.decrypt(iv, msg + tag, aad)