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
5from __future__ import absolute_import, division, print_function
6
7import binascii
8
9import pytest
10
11from cryptography.hazmat.backends.interfaces import DHBackend
12from cryptography.hazmat.primitives.asymmetric.x25519 import (
13    X25519PrivateKey, X25519PublicKey
14)
15
16
17@pytest.mark.supported(
18    only_if=lambda backend: backend.x25519_supported(),
19    skip_message="Requires OpenSSL with X25519 support"
20)
21@pytest.mark.requires_backend_interface(interface=DHBackend)
22@pytest.mark.wycheproof_tests("x25519_test.json")
23def test_x25519(backend, wycheproof):
24    assert list(wycheproof.testgroup.items()) == [("curve", "curve25519")]
25
26    private_key = X25519PrivateKey.from_private_bytes(
27        binascii.unhexlify(wycheproof.testcase["private"])
28    )
29    public_key = X25519PublicKey.from_public_bytes(
30        binascii.unhexlify(wycheproof.testcase["public"])
31    )
32
33    assert wycheproof.valid or wycheproof.acceptable
34
35    expected = binascii.unhexlify(wycheproof.testcase["shared"])
36    if expected == b"\x00" * 32:
37        assert wycheproof.acceptable
38        # OpenSSL returns an error on all zeros shared key
39        with pytest.raises(ValueError):
40            private_key.exchange(public_key)
41    else:
42        assert private_key.exchange(public_key) == expected
43