sha256-kdf.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*
  2. * HMAC-SHA256 KDF (RFC 5295)
  3. * Copyright (c) 2014, Jouni Malinen <j@w1.fi>
  4. *
  5. * This software may be distributed under the terms of the BSD license.
  6. * See README for more details.
  7. */
  8. #include "includes.h"
  9. #include "common.h"
  10. #include "sha256.h"
  11. /**
  12. * hmac_sha256_kdf - HMAC-SHA256 based KDF (RFC 5295)
  13. * @secret: Key for KDF
  14. * @secret_len: Length of the key in bytes
  15. * @label: A unique label for each purpose of the KDF
  16. * @seed: Seed value to bind into the key
  17. * @seed_len: Length of the seed
  18. * @out: Buffer for the generated pseudo-random key
  19. * @outlen: Number of bytes of key to generate
  20. * Returns: 0 on success, -1 on failure.
  21. *
  22. * This function is used to derive new, cryptographically separate keys from a
  23. * given key in ERP. This KDF is defined in RFC 5295, Chapter 3.1.2.
  24. */
  25. int hmac_sha256_kdf(const u8 *secret, size_t secret_len,
  26. const char *label, const u8 *seed, size_t seed_len,
  27. u8 *out, size_t outlen)
  28. {
  29. u8 T[SHA256_MAC_LEN];
  30. u8 iter = 1;
  31. const unsigned char *addr[4];
  32. size_t len[4];
  33. size_t pos, clen;
  34. addr[0] = T;
  35. len[0] = SHA256_MAC_LEN;
  36. addr[1] = (const unsigned char *) label;
  37. len[1] = os_strlen(label) + 1;
  38. addr[2] = seed;
  39. len[2] = seed_len;
  40. addr[3] = &iter;
  41. len[3] = 1;
  42. if (hmac_sha256_vector(secret, secret_len, 3, &addr[1], &len[1], T) < 0)
  43. return -1;
  44. pos = 0;
  45. for (;;) {
  46. clen = outlen - pos;
  47. if (clen > SHA256_MAC_LEN)
  48. clen = SHA256_MAC_LEN;
  49. os_memcpy(out + pos, T, clen);
  50. pos += clen;
  51. if (pos == outlen)
  52. break;
  53. if (iter == 255) {
  54. os_memset(out, 0, outlen);
  55. os_memset(T, 0, SHA256_MAC_LEN);
  56. return -1;
  57. }
  58. iter++;
  59. if (hmac_sha256_vector(secret, secret_len, 4, addr, len, T) < 0)
  60. {
  61. os_memset(out, 0, outlen);
  62. os_memset(T, 0, SHA256_MAC_LEN);
  63. return -1;
  64. }
  65. }
  66. os_memset(T, 0, SHA256_MAC_LEN);
  67. return 0;
  68. }