sha256-kdf.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * HMAC-SHA256 KDF (RFC 5295) and HKDF-Expand(SHA256) (RFC 5869)
  3. * Copyright (c) 2014-2017, 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 or %NULL to select
  16. * RFC 5869 HKDF-Expand() with arbitrary seed (= info)
  17. * @seed: Seed value to bind into the key
  18. * @seed_len: Length of the seed
  19. * @out: Buffer for the generated pseudo-random key
  20. * @outlen: Number of bytes of key to generate
  21. * Returns: 0 on success, -1 on failure.
  22. *
  23. * This function is used to derive new, cryptographically separate keys from a
  24. * given key in ERP. This KDF is defined in RFC 5295, Chapter 3.1.2. When used
  25. * with label = NULL and seed = info, this matches HKDF-Expand() defined in
  26. * RFC 5869, Chapter 2.3.
  27. */
  28. int hmac_sha256_kdf(const u8 *secret, size_t secret_len,
  29. const char *label, const u8 *seed, size_t seed_len,
  30. u8 *out, size_t outlen)
  31. {
  32. u8 T[SHA256_MAC_LEN];
  33. u8 iter = 1;
  34. const unsigned char *addr[4];
  35. size_t len[4];
  36. size_t pos, clen;
  37. addr[0] = T;
  38. len[0] = SHA256_MAC_LEN;
  39. if (label) {
  40. addr[1] = (const unsigned char *) label;
  41. len[1] = os_strlen(label) + 1;
  42. } else {
  43. addr[1] = (const u8 *) "";
  44. len[1] = 0;
  45. }
  46. addr[2] = seed;
  47. len[2] = seed_len;
  48. addr[3] = &iter;
  49. len[3] = 1;
  50. if (hmac_sha256_vector(secret, secret_len, 3, &addr[1], &len[1], T) < 0)
  51. return -1;
  52. pos = 0;
  53. for (;;) {
  54. clen = outlen - pos;
  55. if (clen > SHA256_MAC_LEN)
  56. clen = SHA256_MAC_LEN;
  57. os_memcpy(out + pos, T, clen);
  58. pos += clen;
  59. if (pos == outlen)
  60. break;
  61. if (iter == 255) {
  62. os_memset(out, 0, outlen);
  63. os_memset(T, 0, SHA256_MAC_LEN);
  64. return -1;
  65. }
  66. iter++;
  67. if (hmac_sha256_vector(secret, secret_len, 4, addr, len, T) < 0)
  68. {
  69. os_memset(out, 0, outlen);
  70. os_memset(T, 0, SHA256_MAC_LEN);
  71. return -1;
  72. }
  73. }
  74. os_memset(T, 0, SHA256_MAC_LEN);
  75. return 0;
  76. }