sha256-tlsprf.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * TLS PRF P_SHA256
  3. * Copyright (c) 2011, Jouni Malinen <j@w1.fi>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License version 2 as
  7. * published by the Free Software Foundation.
  8. *
  9. * Alternatively, this software may be distributed under the terms of BSD
  10. * license.
  11. *
  12. * See README and COPYING for more details.
  13. */
  14. #include "includes.h"
  15. #include "common.h"
  16. #include "sha256.h"
  17. /**
  18. * tls_prf_sha256 - Pseudo-Random Function for TLS v1.2 (P_SHA256, RFC 5246)
  19. * @secret: Key for PRF
  20. * @secret_len: Length of the key in bytes
  21. * @label: A unique label for each purpose of the PRF
  22. * @seed: Seed value to bind into the key
  23. * @seed_len: Length of the seed
  24. * @out: Buffer for the generated pseudo-random key
  25. * @outlen: Number of bytes of key to generate
  26. * Returns: 0 on success, -1 on failure.
  27. *
  28. * This function is used to derive new, cryptographically separate keys from a
  29. * given key in TLS. This PRF is defined in RFC 2246, Chapter 5.
  30. */
  31. void tls_prf_sha256(const u8 *secret, size_t secret_len, const char *label,
  32. const u8 *seed, size_t seed_len, u8 *out, size_t outlen)
  33. {
  34. size_t clen;
  35. u8 A[SHA256_MAC_LEN];
  36. u8 P[SHA256_MAC_LEN];
  37. size_t pos;
  38. const unsigned char *addr[3];
  39. size_t len[3];
  40. addr[0] = A;
  41. len[0] = SHA256_MAC_LEN;
  42. addr[1] = (unsigned char *) label;
  43. len[1] = os_strlen(label);
  44. addr[2] = seed;
  45. len[2] = seed_len;
  46. /*
  47. * RFC 5246, Chapter 5
  48. * A(0) = seed, A(i) = HMAC(secret, A(i-1))
  49. * P_hash = HMAC(secret, A(1) + seed) + HMAC(secret, A(2) + seed) + ..
  50. * PRF(secret, label, seed) = P_SHA256(secret, label + seed)
  51. */
  52. hmac_sha256_vector(secret, secret_len, 2, &addr[1], &len[1], A);
  53. pos = 0;
  54. while (pos < outlen) {
  55. hmac_sha256_vector(secret, secret_len, 3, addr, len, P);
  56. hmac_sha256(secret, secret_len, A, SHA256_MAC_LEN, A);
  57. clen = outlen - pos;
  58. if (clen > SHA256_MAC_LEN)
  59. clen = SHA256_MAC_LEN;
  60. os_memcpy(out + pos, P, clen);
  61. pos += clen;
  62. }
  63. }