单项散列函数又称安全散列函数或者哈希函数,是根据消息内容算出散列值,散列值又称为消息摘要。
单项散列函数实现有下面2种方式
- MD算法家族
-SHA算法家族
mbedtls所支持的单项散列算法在接口文件如下
- MD2 include/mbedtls/md2.h
- MD4 include/mbedtls/md4.h
- MD5 include/mbedtls/md5.h
- SHA1 include/mbedtls/sha1.h
- SHA224 include/mbedtls/sha256.h
- SHA245 include/mbedtls/sha256.h
- SHA384 include/mbedtls/sha512.h
- SHA512 include/mbedtls/sha512.h
include/mbedtls/md.h 是md通用接口文件,把是md算法和sha算法的抽象
下面使用md通用接口采用SHA256计算摘要
注意要打开如下宏
- MBEDTLS_MD_C 使能md通用接口
- MBEDTLS_SHA256_C 使能SHA256算法
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include "mbedtls/md.h"
#include "mbedtls/platform.h"
static void dump_buf(char *info, uint8_t *buf, uint32_t len)
{
mbedtls_printf("%s", info);
for (int i = 0; i < len; i++) {
mbedtls_printf("%s%02X%s", i % 16 == 0 ? "\n\t":" ",
buf[i], i == len - 1 ? "\n":"");
}
mbedtls_printf("\n");
}
int main(void)
{
uint8_t digest[32];
char *msg1 = "abc";
char *msg2 = "def";
mbedtls_md_context_t ctx;
const mbedtls_md_info_t *info;
mbedtls_md_init(&ctx);
info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
mbedtls_md_setup(&ctx, info, 0);
mbedtls_printf("\n md info setup, name: %s, digest size: %d\n",
mbedtls_md_get_name(info), mbedtls_md_get_size(info));
mbedtls_md_starts(&ctx);
mbedtls_md_update(&ctx, msg1, strlen(msg1));
mbedtls_md_update(&ctx, msg2, strlen(msg2));
mbedtls_md_finish(&ctx, digest);
dump_buf("\n md sha-256 digest:", digest, sizeof(digest));
mbedtls_md_free(&ctx);
return 0;
}
运行结果
sha256sum验证