hmac.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
  3. * SPDX-License-Identifier: Apache-2.0.
  4. */
  5. #include <aws/cal/hmac.h>
  6. #ifndef BYO_CRYPTO
  7. extern struct aws_hmac *aws_sha256_hmac_default_new(
  8. struct aws_allocator *allocator,
  9. const struct aws_byte_cursor *secret);
  10. static aws_hmac_new_fn *s_sha256_hmac_new_fn = aws_sha256_hmac_default_new;
  11. #else
  12. static struct aws_hmac *aws_hmac_new_abort(struct aws_allocator *allocator, const struct aws_byte_cursor *secret) {
  13. (void)allocator;
  14. (void)secret;
  15. abort();
  16. }
  17. static aws_hmac_new_fn *s_sha256_hmac_new_fn = aws_hmac_new_abort;
  18. #endif
  19. struct aws_hmac *aws_sha256_hmac_new(struct aws_allocator *allocator, const struct aws_byte_cursor *secret) {
  20. return s_sha256_hmac_new_fn(allocator, secret);
  21. }
  22. void aws_set_sha256_hmac_new_fn(aws_hmac_new_fn *fn) {
  23. s_sha256_hmac_new_fn = fn;
  24. }
  25. void aws_hmac_destroy(struct aws_hmac *hmac) {
  26. hmac->vtable->destroy(hmac);
  27. }
  28. int aws_hmac_update(struct aws_hmac *hmac, const struct aws_byte_cursor *to_hmac) {
  29. return hmac->vtable->update(hmac, to_hmac);
  30. }
  31. int aws_hmac_finalize(struct aws_hmac *hmac, struct aws_byte_buf *output, size_t truncate_to) {
  32. if (truncate_to && truncate_to < hmac->digest_size) {
  33. size_t available_buffer = output->capacity - output->len;
  34. if (available_buffer < truncate_to) {
  35. return aws_raise_error(AWS_ERROR_SHORT_BUFFER);
  36. }
  37. uint8_t tmp_output[128] = {0};
  38. AWS_ASSERT(sizeof(tmp_output) >= hmac->digest_size);
  39. struct aws_byte_buf tmp_out_buf = aws_byte_buf_from_array(tmp_output, sizeof(tmp_output));
  40. tmp_out_buf.len = 0;
  41. if (hmac->vtable->finalize(hmac, &tmp_out_buf)) {
  42. return AWS_OP_ERR;
  43. }
  44. memcpy(output->buffer + output->len, tmp_output, truncate_to);
  45. output->len += truncate_to;
  46. return AWS_OP_SUCCESS;
  47. }
  48. return hmac->vtable->finalize(hmac, output);
  49. }
  50. int aws_sha256_hmac_compute(
  51. struct aws_allocator *allocator,
  52. const struct aws_byte_cursor *secret,
  53. const struct aws_byte_cursor *to_hmac,
  54. struct aws_byte_buf *output,
  55. size_t truncate_to) {
  56. struct aws_hmac *hmac = aws_sha256_hmac_new(allocator, secret);
  57. if (!hmac) {
  58. return AWS_OP_ERR;
  59. }
  60. if (aws_hmac_update(hmac, to_hmac)) {
  61. aws_hmac_destroy(hmac);
  62. return AWS_OP_ERR;
  63. }
  64. if (aws_hmac_finalize(hmac, output, truncate_to)) {
  65. aws_hmac_destroy(hmac);
  66. return AWS_OP_ERR;
  67. }
  68. aws_hmac_destroy(hmac);
  69. return AWS_OP_SUCCESS;
  70. }