commoncrypto_md5.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. #pragma clang diagnostic push
  8. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  9. static void s_destroy(struct aws_hash *hash);
  10. static int s_update(struct aws_hash *hash, const struct aws_byte_cursor *to_hash);
  11. static int s_finalize(struct aws_hash *hash, struct aws_byte_buf *output);
  12. static struct aws_hash_vtable s_vtable = {
  13. .destroy = s_destroy,
  14. .update = s_update,
  15. .finalize = s_finalize,
  16. .alg_name = "MD5",
  17. .provider = "CommonCrypto",
  18. };
  19. struct cc_md5_hash {
  20. struct aws_hash hash;
  21. CC_MD5_CTX cc_hash;
  22. };
  23. struct aws_hash *aws_md5_default_new(struct aws_allocator *allocator) {
  24. struct cc_md5_hash *cc_md5_hash = aws_mem_acquire(allocator, sizeof(struct cc_md5_hash));
  25. if (!cc_md5_hash) {
  26. return NULL;
  27. }
  28. cc_md5_hash->hash.allocator = allocator;
  29. cc_md5_hash->hash.vtable = &s_vtable;
  30. cc_md5_hash->hash.digest_size = AWS_MD5_LEN;
  31. cc_md5_hash->hash.impl = cc_md5_hash;
  32. cc_md5_hash->hash.good = true;
  33. CC_MD5_Init(&cc_md5_hash->cc_hash);
  34. return &cc_md5_hash->hash;
  35. }
  36. static void s_destroy(struct aws_hash *hash) {
  37. struct cc_md5_hash *ctx = hash->impl;
  38. aws_mem_release(hash->allocator, ctx);
  39. }
  40. static int s_update(struct aws_hash *hash, const struct aws_byte_cursor *to_hash) {
  41. if (!hash->good) {
  42. return aws_raise_error(AWS_ERROR_INVALID_STATE);
  43. }
  44. struct cc_md5_hash *ctx = hash->impl;
  45. CC_MD5_Update(&ctx->cc_hash, to_hash->ptr, (CC_LONG)to_hash->len);
  46. return AWS_OP_SUCCESS;
  47. }
  48. static int s_finalize(struct aws_hash *hash, struct aws_byte_buf *output) {
  49. if (!hash->good) {
  50. return aws_raise_error(AWS_ERROR_INVALID_STATE);
  51. }
  52. struct cc_md5_hash *ctx = hash->impl;
  53. size_t buffer_len = output->capacity - output->len;
  54. if (buffer_len < hash->digest_size) {
  55. return aws_raise_error(AWS_ERROR_SHORT_BUFFER);
  56. }
  57. CC_MD5_Final(output->buffer + output->len, &ctx->cc_hash);
  58. hash->good = false;
  59. output->len += hash->digest_size;
  60. return AWS_OP_SUCCESS;
  61. }
  62. #pragma clang diagnostic pop