ecdh_kdf.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * Copyright 2015-2016 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. /* Key derivation function from X9.62/SECG */
  13. /* Way more than we will ever need */
  14. #define ECDH_KDF_MAX (1 << 30)
  15. int ECDH_KDF_X9_62(unsigned char *out, size_t outlen,
  16. const unsigned char *Z, size_t Zlen,
  17. const unsigned char *sinfo, size_t sinfolen,
  18. const EVP_MD *md)
  19. {
  20. EVP_MD_CTX *mctx = NULL;
  21. int rv = 0;
  22. unsigned int i;
  23. size_t mdlen;
  24. unsigned char ctr[4];
  25. if (sinfolen > ECDH_KDF_MAX || outlen > ECDH_KDF_MAX
  26. || Zlen > ECDH_KDF_MAX)
  27. return 0;
  28. mctx = EVP_MD_CTX_new();
  29. if (mctx == NULL)
  30. return 0;
  31. mdlen = EVP_MD_size(md);
  32. for (i = 1;; i++) {
  33. unsigned char mtmp[EVP_MAX_MD_SIZE];
  34. if (!EVP_DigestInit_ex(mctx, md, NULL))
  35. goto err;
  36. ctr[3] = i & 0xFF;
  37. ctr[2] = (i >> 8) & 0xFF;
  38. ctr[1] = (i >> 16) & 0xFF;
  39. ctr[0] = (i >> 24) & 0xFF;
  40. if (!EVP_DigestUpdate(mctx, Z, Zlen))
  41. goto err;
  42. if (!EVP_DigestUpdate(mctx, ctr, sizeof(ctr)))
  43. goto err;
  44. if (!EVP_DigestUpdate(mctx, sinfo, sinfolen))
  45. goto err;
  46. if (outlen >= mdlen) {
  47. if (!EVP_DigestFinal(mctx, out, NULL))
  48. goto err;
  49. outlen -= mdlen;
  50. if (outlen == 0)
  51. break;
  52. out += mdlen;
  53. } else {
  54. if (!EVP_DigestFinal(mctx, mtmp, NULL))
  55. goto err;
  56. memcpy(out, mtmp, outlen);
  57. OPENSSL_cleanse(mtmp, mdlen);
  58. break;
  59. }
  60. }
  61. rv = 1;
  62. err:
  63. EVP_MD_CTX_free(mctx);
  64. return rv;
  65. }