commoncrypto_sha1.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 = "SHA1",
  15. .provider = "CommonCrypto",
  16. };
  17. struct cc_sha1_hash {
  18. struct aws_hash hash;
  19. CC_SHA1_CTX cc_hash;
  20. };
  21. struct aws_hash *aws_sha1_default_new(struct aws_allocator *allocator) {
  22. struct cc_sha1_hash *sha1_hash = aws_mem_acquire(allocator, sizeof(struct cc_sha1_hash));
  23. if (!sha1_hash) {
  24. return NULL;
  25. }
  26. sha1_hash->hash.allocator = allocator;
  27. sha1_hash->hash.vtable = &s_vtable;
  28. sha1_hash->hash.impl = sha1_hash;
  29. sha1_hash->hash.digest_size = AWS_SHA1_LEN;
  30. sha1_hash->hash.good = true;
  31. CC_SHA1_Init(&sha1_hash->cc_hash);
  32. return &sha1_hash->hash;
  33. }
  34. static void s_destroy(struct aws_hash *hash) {
  35. struct cc_sha1_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_sha1_hash *ctx = hash->impl;
  43. CC_SHA1_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_sha1_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_SHA1_Final(output->buffer + output->len, &ctx->cc_hash);
  56. hash->good = false;
  57. output->len += hash->digest_size;
  58. return AWS_OP_SUCCESS;
  59. }