blob: 9ecb3c1f0f15d4bc7ebe34f5682fbba7b780ee1f [file] [log] [blame]
Jason A. Donenfeld0ed42a6f2019-11-08 13:22:32 +01001/* SPDX-License-Identifier: GPL-2.0 OR MIT */
2/*
3 * Copyright (C) 2015-2019 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
4 */
5
6#ifndef CURVE25519_H
7#define CURVE25519_H
8
9#include <crypto/algapi.h> // For crypto_memneq.
10#include <linux/types.h>
11#include <linux/random.h>
12
13enum curve25519_lengths {
14 CURVE25519_KEY_SIZE = 32
15};
16
17extern const u8 curve25519_null_point[];
18extern const u8 curve25519_base_point[];
19
20void curve25519_generic(u8 out[CURVE25519_KEY_SIZE],
21 const u8 scalar[CURVE25519_KEY_SIZE],
22 const u8 point[CURVE25519_KEY_SIZE]);
23
24void curve25519_arch(u8 out[CURVE25519_KEY_SIZE],
25 const u8 scalar[CURVE25519_KEY_SIZE],
26 const u8 point[CURVE25519_KEY_SIZE]);
27
28void curve25519_base_arch(u8 pub[CURVE25519_KEY_SIZE],
29 const u8 secret[CURVE25519_KEY_SIZE]);
30
31static inline
32bool __must_check curve25519(u8 mypublic[CURVE25519_KEY_SIZE],
33 const u8 secret[CURVE25519_KEY_SIZE],
34 const u8 basepoint[CURVE25519_KEY_SIZE])
35{
Jason A. Donenfeld1579f1b2020-03-01 22:52:35 +080036 if (IS_ENABLED(CONFIG_CRYPTO_ARCH_HAVE_LIB_CURVE25519) &&
37 (!IS_ENABLED(CONFIG_CRYPTO_CURVE25519_X86) || IS_ENABLED(CONFIG_AS_ADX)))
Jason A. Donenfeld0ed42a6f2019-11-08 13:22:32 +010038 curve25519_arch(mypublic, secret, basepoint);
39 else
40 curve25519_generic(mypublic, secret, basepoint);
41 return crypto_memneq(mypublic, curve25519_null_point,
42 CURVE25519_KEY_SIZE);
43}
44
45static inline bool
46__must_check curve25519_generate_public(u8 pub[CURVE25519_KEY_SIZE],
47 const u8 secret[CURVE25519_KEY_SIZE])
48{
49 if (unlikely(!crypto_memneq(secret, curve25519_null_point,
50 CURVE25519_KEY_SIZE)))
51 return false;
52
Jason A. Donenfeld1579f1b2020-03-01 22:52:35 +080053 if (IS_ENABLED(CONFIG_CRYPTO_ARCH_HAVE_LIB_CURVE25519) &&
54 (!IS_ENABLED(CONFIG_CRYPTO_CURVE25519_X86) || IS_ENABLED(CONFIG_AS_ADX)))
Jason A. Donenfeld0ed42a6f2019-11-08 13:22:32 +010055 curve25519_base_arch(pub, secret);
56 else
57 curve25519_generic(pub, secret, curve25519_base_point);
58 return crypto_memneq(pub, curve25519_null_point, CURVE25519_KEY_SIZE);
59}
60
61static inline void curve25519_clamp_secret(u8 secret[CURVE25519_KEY_SIZE])
62{
63 secret[0] &= 248;
64 secret[31] = (secret[31] & 127) | 64;
65}
66
67static inline void curve25519_generate_secret(u8 secret[CURVE25519_KEY_SIZE])
68{
69 get_random_bytes_wait(secret, CURVE25519_KEY_SIZE);
70 curve25519_clamp_secret(secret);
71}
72
73#endif /* CURVE25519_H */