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