sha256-tlsprf.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * TLS PRF P_SHA256
  3. * Copyright (c) 2011, 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. * tls_prf_sha256 - Pseudo-Random Function for TLS v1.2 (P_SHA256, RFC 5246)
  13. * @secret: Key for PRF
  14. * @secret_len: Length of the key in bytes
  15. * @label: A unique label for each purpose of the PRF
  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 TLS. This PRF is defined in RFC 2246, Chapter 5.
  24. */
  25. void tls_prf_sha256(const u8 *secret, size_t secret_len, const char *label,
  26. const u8 *seed, size_t seed_len, u8 *out, size_t outlen)
  27. {
  28. size_t clen;
  29. u8 A[SHA256_MAC_LEN];
  30. u8 P[SHA256_MAC_LEN];
  31. size_t pos;
  32. const unsigned char *addr[3];
  33. size_t len[3];
  34. addr[0] = A;
  35. len[0] = SHA256_MAC_LEN;
  36. addr[1] = (unsigned char *) label;
  37. len[1] = os_strlen(label);
  38. addr[2] = seed;
  39. len[2] = seed_len;
  40. /*
  41. * RFC 5246, Chapter 5
  42. * A(0) = seed, A(i) = HMAC(secret, A(i-1))
  43. * P_hash = HMAC(secret, A(1) + seed) + HMAC(secret, A(2) + seed) + ..
  44. * PRF(secret, label, seed) = P_SHA256(secret, label + seed)
  45. */
  46. hmac_sha256_vector(secret, secret_len, 2, &addr[1], &len[1], A);
  47. pos = 0;
  48. while (pos < outlen) {
  49. hmac_sha256_vector(secret, secret_len, 3, addr, len, P);
  50. hmac_sha256(secret, secret_len, A, SHA256_MAC_LEN, A);
  51. clen = outlen - pos;
  52. if (clen > SHA256_MAC_LEN)
  53. clen = SHA256_MAC_LEN;
  54. os_memcpy(out + pos, P, clen);
  55. pos += clen;
  56. }
  57. }