ecdh_kdf.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the OpenSSL license (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #include <string.h>
  10. #include <openssl/ec.h>
  11. #include <openssl/evp.h>
  12. #include "ec_local.h"
  13. /* Key derivation function from X9.63/SECG */
  14. /* Way more than we will ever need */
  15. #define ECDH_KDF_MAX (1 << 30)
  16. int ecdh_KDF_X9_63(unsigned char *out, size_t outlen,
  17. const unsigned char *Z, size_t Zlen,
  18. const unsigned char *sinfo, size_t sinfolen,
  19. const EVP_MD *md)
  20. {
  21. EVP_MD_CTX *mctx = NULL;
  22. int rv = 0;
  23. unsigned int i;
  24. size_t mdlen;
  25. unsigned char ctr[4];
  26. if (sinfolen > ECDH_KDF_MAX || outlen > ECDH_KDF_MAX
  27. || Zlen > ECDH_KDF_MAX)
  28. return 0;
  29. mctx = EVP_MD_CTX_new();
  30. if (mctx == NULL)
  31. return 0;
  32. mdlen = EVP_MD_size(md);
  33. for (i = 1;; i++) {
  34. unsigned char mtmp[EVP_MAX_MD_SIZE];
  35. if (!EVP_DigestInit_ex(mctx, md, NULL))
  36. goto err;
  37. ctr[3] = i & 0xFF;
  38. ctr[2] = (i >> 8) & 0xFF;
  39. ctr[1] = (i >> 16) & 0xFF;
  40. ctr[0] = (i >> 24) & 0xFF;
  41. if (!EVP_DigestUpdate(mctx, Z, Zlen))
  42. goto err;
  43. if (!EVP_DigestUpdate(mctx, ctr, sizeof(ctr)))
  44. goto err;
  45. if (!EVP_DigestUpdate(mctx, sinfo, sinfolen))
  46. goto err;
  47. if (outlen >= mdlen) {
  48. if (!EVP_DigestFinal(mctx, out, NULL))
  49. goto err;
  50. outlen -= mdlen;
  51. if (outlen == 0)
  52. break;
  53. out += mdlen;
  54. } else {
  55. if (!EVP_DigestFinal(mctx, mtmp, NULL))
  56. goto err;
  57. memcpy(out, mtmp, outlen);
  58. OPENSSL_cleanse(mtmp, mdlen);
  59. break;
  60. }
  61. }
  62. rv = 1;
  63. err:
  64. EVP_MD_CTX_free(mctx);
  65. return rv;
  66. }
  67. /*-
  68. * The old name for ecdh_KDF_X9_63
  69. * Retained for ABI compatibility
  70. */
  71. int ECDH_KDF_X9_62(unsigned char *out, size_t outlen,
  72. const unsigned char *Z, size_t Zlen,
  73. const unsigned char *sinfo, size_t sinfolen,
  74. const EVP_MD *md)
  75. {
  76. return ecdh_KDF_X9_63(out, outlen, Z, Zlen, sinfo, sinfolen, md);
  77. }