2hmac.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /* Copyright 2016 The Chromium OS Authors. All rights reserved.
  2. * Use of this source code is governed by a BSD-style license that can be
  3. * found in the LICENSE file.
  4. */
  5. #include "2sysincludes.h"
  6. #include "2sha.h"
  7. #include "2hmac.h"
  8. int hmac(enum vb2_hash_algorithm alg,
  9. const void *key, uint32_t key_size,
  10. const void *msg, uint32_t msg_size,
  11. uint8_t *mac, uint32_t mac_size)
  12. {
  13. uint32_t block_size;
  14. uint32_t digest_size;
  15. uint8_t k[VB2_MAX_BLOCK_SIZE];
  16. uint8_t o_pad[VB2_MAX_BLOCK_SIZE];
  17. uint8_t i_pad[VB2_MAX_BLOCK_SIZE];
  18. uint8_t b[VB2_MAX_DIGEST_SIZE];
  19. struct vb2_digest_context dc;
  20. int i;
  21. if (!key | !msg | !mac)
  22. return -1;
  23. digest_size = vb2_digest_size(alg);
  24. block_size = vb2_hash_block_size(alg);
  25. if (!digest_size || !block_size)
  26. return -1;
  27. if (mac_size < digest_size)
  28. return -1;
  29. if (key_size > block_size) {
  30. vb2_digest_buffer((uint8_t *)key, key_size, alg, k, block_size);
  31. key_size = digest_size;
  32. } else {
  33. memcpy(k, key, key_size);
  34. }
  35. if (key_size < block_size)
  36. memset(k + key_size, 0, block_size - key_size);
  37. for (i = 0; i < block_size; i++) {
  38. o_pad[i] = 0x5c ^ k[i];
  39. i_pad[i] = 0x36 ^ k[i];
  40. }
  41. vb2_digest_init(&dc, alg);
  42. vb2_digest_extend(&dc, i_pad, block_size);
  43. vb2_digest_extend(&dc, msg, msg_size);
  44. vb2_digest_finalize(&dc, b, digest_size);
  45. vb2_digest_init(&dc, alg);
  46. vb2_digest_extend(&dc, o_pad, block_size);
  47. vb2_digest_extend(&dc, b, digest_size);
  48. vb2_digest_finalize(&dc, mac, mac_size);
  49. return 0;
  50. }