curve25519.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* SPDX-License-Identifier: GPL-2.0 OR MIT */
  2. /*
  3. * Copyright (C) 2015-2019 Jason A. Donenfeld <[email protected]>. All Rights Reserved.
  4. */
  5. #ifndef CURVE25519_H
  6. #define CURVE25519_H
  7. #include <crypto/algapi.h> // For crypto_memneq.
  8. #include <linux/types.h>
  9. #include <linux/random.h>
  10. enum curve25519_lengths {
  11. CURVE25519_KEY_SIZE = 32
  12. };
  13. extern const u8 curve25519_null_point[];
  14. extern const u8 curve25519_base_point[];
  15. void curve25519_generic(u8 out[CURVE25519_KEY_SIZE],
  16. const u8 scalar[CURVE25519_KEY_SIZE],
  17. const u8 point[CURVE25519_KEY_SIZE]);
  18. void curve25519_arch(u8 out[CURVE25519_KEY_SIZE],
  19. const u8 scalar[CURVE25519_KEY_SIZE],
  20. const u8 point[CURVE25519_KEY_SIZE]);
  21. void curve25519_base_arch(u8 pub[CURVE25519_KEY_SIZE],
  22. const u8 secret[CURVE25519_KEY_SIZE]);
  23. bool curve25519_selftest(void);
  24. static inline
  25. bool __must_check curve25519(u8 mypublic[CURVE25519_KEY_SIZE],
  26. const u8 secret[CURVE25519_KEY_SIZE],
  27. const u8 basepoint[CURVE25519_KEY_SIZE])
  28. {
  29. if (IS_ENABLED(CONFIG_CRYPTO_ARCH_HAVE_LIB_CURVE25519))
  30. curve25519_arch(mypublic, secret, basepoint);
  31. else
  32. curve25519_generic(mypublic, secret, basepoint);
  33. return crypto_memneq(mypublic, curve25519_null_point,
  34. CURVE25519_KEY_SIZE);
  35. }
  36. static inline bool
  37. __must_check curve25519_generate_public(u8 pub[CURVE25519_KEY_SIZE],
  38. const u8 secret[CURVE25519_KEY_SIZE])
  39. {
  40. if (unlikely(!crypto_memneq(secret, curve25519_null_point,
  41. CURVE25519_KEY_SIZE)))
  42. return false;
  43. if (IS_ENABLED(CONFIG_CRYPTO_ARCH_HAVE_LIB_CURVE25519))
  44. curve25519_base_arch(pub, secret);
  45. else
  46. curve25519_generic(pub, secret, curve25519_base_point);
  47. return crypto_memneq(pub, curve25519_null_point, CURVE25519_KEY_SIZE);
  48. }
  49. static inline void curve25519_clamp_secret(u8 secret[CURVE25519_KEY_SIZE])
  50. {
  51. secret[0] &= 248;
  52. secret[31] = (secret[31] & 127) | 64;
  53. }
  54. static inline void curve25519_generate_secret(u8 secret[CURVE25519_KEY_SIZE])
  55. {
  56. get_random_bytes_wait(secret, CURVE25519_KEY_SIZE);
  57. curve25519_clamp_secret(secret);
  58. }
  59. #endif /* CURVE25519_H */