2018-01-24 17:52:25 +00:00
|
|
|
#include <stdlib.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include "sha.h"
|
|
|
|
#include "types.h"
|
|
|
|
#include "utils.h"
|
|
|
|
|
|
|
|
/* Allocate new context. */
|
2018-01-29 18:39:30 +00:00
|
|
|
sha_ctx_t *new_sha_ctx(hash_type_t type, int hmac) {
|
2018-01-24 17:52:25 +00:00
|
|
|
sha_ctx_t *ctx;
|
2018-01-29 18:39:30 +00:00
|
|
|
|
2018-01-24 17:52:25 +00:00
|
|
|
if ((ctx = malloc(sizeof(*ctx))) == NULL) {
|
|
|
|
FATAL_ERROR("Failed to allocate sha_ctx_t!");
|
|
|
|
}
|
2018-01-29 18:39:30 +00:00
|
|
|
|
|
|
|
mbedtls_md_init(&ctx->digest);
|
|
|
|
|
|
|
|
if (mbedtls_md_setup(&ctx->digest, mbedtls_md_info_from_type(type), hmac)) {
|
|
|
|
FATAL_ERROR("Failed to set up hash context!");
|
2018-01-24 17:52:25 +00:00
|
|
|
}
|
2018-01-29 18:39:30 +00:00
|
|
|
|
|
|
|
if (mbedtls_md_starts(&ctx->digest)) {
|
|
|
|
FATAL_ERROR("Failed to start hash context!");
|
|
|
|
}
|
|
|
|
|
2018-01-24 17:52:25 +00:00
|
|
|
return ctx;
|
2018-01-29 18:39:30 +00:00
|
|
|
}
|
2018-01-24 17:52:25 +00:00
|
|
|
|
2018-01-29 18:39:30 +00:00
|
|
|
/* Free an allocated context. */
|
|
|
|
void free_sha_ctx(sha_ctx_t *ctx) {
|
|
|
|
/* Explicitly allow NULL. */
|
|
|
|
if (ctx == NULL) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
mbedtls_md_free(&ctx->digest);
|
|
|
|
free(ctx);
|
2018-01-24 17:52:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/* Update digest with new data. */
|
|
|
|
void sha_update(sha_ctx_t *ctx, const void *data, size_t l) {
|
2018-01-29 18:39:30 +00:00
|
|
|
mbedtls_md_update(&ctx->digest, data, l);
|
2018-01-24 17:52:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/* Read hash from context. */
|
|
|
|
void sha_get_hash(sha_ctx_t *ctx, unsigned char *hash) {
|
2018-01-29 18:39:30 +00:00
|
|
|
mbedtls_md_finish(&ctx->digest, hash);
|
2018-01-24 17:52:25 +00:00
|
|
|
}
|
|
|
|
|
2018-01-29 18:39:30 +00:00
|
|
|
/* SHA256 digest. */
|
|
|
|
void sha256_hash_buffer(unsigned char *digest, const void *data, size_t l) {
|
|
|
|
sha_ctx_t *sha_ctx = new_sha_ctx(HASH_TYPE_SHA256, 0);
|
|
|
|
sha_update(sha_ctx, data, l);
|
|
|
|
sha_get_hash(sha_ctx, digest);
|
|
|
|
free_sha_ctx(sha_ctx);
|
|
|
|
}
|