ecdh_helper.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Copyright (c) 2016, Intel Corporation
  3. * Authors: Salvatore Benedetto <salvatore.benedetto@intel.com>
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License
  7. * as published by the Free Software Foundation; either version
  8. * 2 of the License, or (at your option) any later version.
  9. */
  10. #include <linux/kernel.h>
  11. #include <linux/export.h>
  12. #include <linux/err.h>
  13. #include <linux/string.h>
  14. #include <crypto/ecdh.h>
  15. #include <crypto/kpp.h>
  16. #define ECDH_KPP_SECRET_MIN_SIZE (sizeof(struct kpp_secret) + 2 * sizeof(short))
  17. static inline u8 *ecdh_pack_data(void *dst, const void *src, size_t sz)
  18. {
  19. memcpy(dst, src, sz);
  20. return dst + sz;
  21. }
  22. static inline const u8 *ecdh_unpack_data(void *dst, const void *src, size_t sz)
  23. {
  24. memcpy(dst, src, sz);
  25. return src + sz;
  26. }
  27. unsigned int crypto_ecdh_key_len(const struct ecdh *params)
  28. {
  29. return ECDH_KPP_SECRET_MIN_SIZE + params->key_size;
  30. }
  31. EXPORT_SYMBOL_GPL(crypto_ecdh_key_len);
  32. int crypto_ecdh_encode_key(char *buf, unsigned int len,
  33. const struct ecdh *params)
  34. {
  35. u8 *ptr = buf;
  36. struct kpp_secret secret = {
  37. .type = CRYPTO_KPP_SECRET_TYPE_ECDH,
  38. .len = len
  39. };
  40. if (unlikely(!buf))
  41. return -EINVAL;
  42. if (len != crypto_ecdh_key_len(params))
  43. return -EINVAL;
  44. ptr = ecdh_pack_data(ptr, &secret, sizeof(secret));
  45. ptr = ecdh_pack_data(ptr, &params->curve_id, sizeof(params->curve_id));
  46. ptr = ecdh_pack_data(ptr, &params->key_size, sizeof(params->key_size));
  47. ecdh_pack_data(ptr, params->key, params->key_size);
  48. return 0;
  49. }
  50. EXPORT_SYMBOL_GPL(crypto_ecdh_encode_key);
  51. int crypto_ecdh_decode_key(const char *buf, unsigned int len,
  52. struct ecdh *params)
  53. {
  54. const u8 *ptr = buf;
  55. struct kpp_secret secret;
  56. if (unlikely(!buf || len < ECDH_KPP_SECRET_MIN_SIZE))
  57. return -EINVAL;
  58. ptr = ecdh_unpack_data(&secret, ptr, sizeof(secret));
  59. if (secret.type != CRYPTO_KPP_SECRET_TYPE_ECDH)
  60. return -EINVAL;
  61. ptr = ecdh_unpack_data(&params->curve_id, ptr, sizeof(params->curve_id));
  62. ptr = ecdh_unpack_data(&params->key_size, ptr, sizeof(params->key_size));
  63. if (secret.len != crypto_ecdh_key_len(params))
  64. return -EINVAL;
  65. /* Don't allocate memory. Set pointer to data
  66. * within the given buffer
  67. */
  68. params->key = (void *)ptr;
  69. return 0;
  70. }
  71. EXPORT_SYMBOL_GPL(crypto_ecdh_decode_key);