1 /* Copyright (c) 2014, Google Inc. 2 * 3 * Permission to use, copy, modify, and/or distribute this software for any 4 * purpose with or without fee is hereby granted, provided that the above 5 * copyright notice and this permission notice appear in all copies. 6 * 7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY 10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION 12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN 13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ 14 15 #include <openssl/hkdf.h> 16 17 #include <assert.h> 18 #include <string.h> 19 20 #include <openssl/err.h> 21 #include <openssl/hmac.h> 22 23 24 int HKDF(uint8_t *out_key, size_t out_len, 25 const EVP_MD *digest, 26 const uint8_t *secret, size_t secret_len, 27 const uint8_t *salt, size_t salt_len, 28 const uint8_t *info, size_t info_len) { 29 /* https://tools.ietf.org/html/rfc5869#section-2.2 */ 30 const size_t digest_len = EVP_MD_size(digest); 31 uint8_t prk[EVP_MAX_MD_SIZE], previous[EVP_MAX_MD_SIZE]; 32 size_t n, done = 0; 33 unsigned i, prk_len; 34 int ret = 0; 35 HMAC_CTX hmac; 36 37 /* If salt is not given, HashLength zeros are used. However, HMAC does that 38 * internally already so we can ignore it.*/ 39 40 /* Expand key material to desired length. */ 41 n = (out_len + digest_len - 1) / digest_len; 42 if (out_len + digest_len < out_len || n > 255) { 43 OPENSSL_PUT_ERROR(HKDF, HKDF_R_OUTPUT_TOO_LARGE); 44 return 0; 45 } 46 47 HMAC_CTX_init(&hmac); 48 49 /* Extract input keying material into pseudorandom key |prk|. */ 50 if (HMAC(digest, salt, salt_len, secret, secret_len, prk, &prk_len) == NULL) { 51 goto out; 52 } 53 assert(prk_len == digest_len); 54 55 if (!HMAC_Init_ex(&hmac, prk, prk_len, digest, NULL)) { 56 goto out; 57 } 58 59 for (i = 0; i < n; i++) { 60 uint8_t ctr = i + 1; 61 size_t todo; 62 63 if (i != 0 && (!HMAC_Init_ex(&hmac, NULL, 0, NULL, NULL) || 64 !HMAC_Update(&hmac, previous, digest_len))) { 65 goto out; 66 } 67 if (!HMAC_Update(&hmac, info, info_len) || 68 !HMAC_Update(&hmac, &ctr, 1) || 69 !HMAC_Final(&hmac, previous, NULL)) { 70 goto out; 71 } 72 73 todo = digest_len; 74 if (done + todo > out_len) { 75 todo = out_len - done; 76 } 77 memcpy(out_key + done, previous, todo); 78 done += todo; 79 } 80 81 ret = 1; 82 83 out: 84 HMAC_CTX_cleanup(&hmac); 85 if (ret != 1) { 86 OPENSSL_PUT_ERROR(HKDF, ERR_R_HMAC_LIB); 87 } 88 return ret; 89 } 90