Paul Kehrer | 7ca0e46 | 2018-07-17 22:40:02 +0800 | [diff] [blame] | 1 | # 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 | |
| 5 | from __future__ import absolute_import, division, print_function |
| 6 | |
| 7 | import binascii |
| 8 | |
| 9 | import pytest |
| 10 | |
| 11 | from cryptography.exceptions import InvalidTag |
| 12 | from cryptography.hazmat.backends.interfaces import CipherBackend |
| 13 | from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 |
| 14 | |
| 15 | from ..hazmat.primitives.test_aead import _aead_supported |
| 16 | |
| 17 | |
| 18 | @pytest.mark.skipif( |
| 19 | not _aead_supported(ChaCha20Poly1305), |
Lucia Li | c6ba99d | 2021-11-08 22:06:11 +0800 | [diff] [blame] | 20 | reason="Requires OpenSSL with ChaCha20Poly1305 support", |
Paul Kehrer | 7ca0e46 | 2018-07-17 22:40:02 +0800 | [diff] [blame] | 21 | ) |
| 22 | @pytest.mark.requires_backend_interface(interface=CipherBackend) |
| 23 | @pytest.mark.wycheproof_tests("chacha20_poly1305_test.json") |
| 24 | def 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) |