commoncrypto_sha256.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
  3. * SPDX-License-Identifier: Apache-2.0.
  4. */
  5. #include <aws/cal/hash.h>
  6. #include <CommonCrypto/CommonDigest.h>
  7. static void s_destroy(struct aws_hash *hash);
  8. static int s_update(struct aws_hash *hash, const struct aws_byte_cursor *to_hash);
  9. static int s_finalize(struct aws_hash *hash, struct aws_byte_buf *output);
  10. static struct aws_hash_vtable s_vtable = {
  11. .destroy = s_destroy,
  12. .update = s_update,
  13. .finalize = s_finalize,
  14. .alg_name = "SHA256",
  15. .provider = "CommonCrypto",
  16. };
  17. struct cc_sha256_hash {
  18. struct aws_hash hash;
  19. CC_SHA256_CTX cc_hash;
  20. };
  21. struct aws_hash *aws_sha256_default_new(struct aws_allocator *allocator) {
  22. struct cc_sha256_hash *sha256_hash = aws_mem_acquire(allocator, sizeof(struct cc_sha256_hash));
  23. if (!sha256_hash) {
  24. return NULL;
  25. }
  26. sha256_hash->hash.allocator = allocator;
  27. sha256_hash->hash.vtable = &s_vtable;
  28. sha256_hash->hash.impl = sha256_hash;
  29. sha256_hash->hash.digest_size = AWS_SHA256_LEN;
  30. sha256_hash->hash.good = true;
  31. CC_SHA256_Init(&sha256_hash->cc_hash);
  32. return &sha256_hash->hash;
  33. }
  34. static void s_destroy(struct aws_hash *hash) {
  35. struct cc_sha256_hash *ctx = hash->impl;
  36. aws_mem_release(hash->allocator, ctx);
  37. }
  38. static int s_update(struct aws_hash *hash, const struct aws_byte_cursor *to_hash) {
  39. if (!hash->good) {
  40. return aws_raise_error(AWS_ERROR_INVALID_STATE);
  41. }
  42. struct cc_sha256_hash *ctx = hash->impl;
  43. CC_SHA256_Update(&ctx->cc_hash, to_hash->ptr, (CC_LONG)to_hash->len);
  44. return AWS_OP_SUCCESS;
  45. }
  46. static int s_finalize(struct aws_hash *hash, struct aws_byte_buf *output) {
  47. if (!hash->good) {
  48. return aws_raise_error(AWS_ERROR_INVALID_STATE);
  49. }
  50. struct cc_sha256_hash *ctx = hash->impl;
  51. size_t buffer_len = output->capacity - output->len;
  52. if (buffer_len < hash->digest_size) {
  53. return aws_raise_error(AWS_ERROR_SHORT_BUFFER);
  54. }
  55. CC_SHA256_Final(output->buffer + output->len, &ctx->cc_hash);
  56. hash->good = false;
  57. output->len += hash->digest_size;
  58. return AWS_OP_SUCCESS;
  59. }